Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/realm/configuration_realm.py +169 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/realm/modeling_realm.py +1855 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/realm/retrieval_realm.py +176 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/realm/tokenization_realm.py +534 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/realm/tokenization_realm_fast.py +223 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/retribert/__init__.py +29 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/retribert/configuration_retribert.py +108 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/retribert/modeling_retribert.py +217 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/retribert/tokenization_retribert.py +475 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/retribert/tokenization_retribert_fast.py +150 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/__init__.py +29 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/configuration_speech_to_text_2.py +134 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/modeling_speech_to_text_2.py +905 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/processing_speech_to_text_2.py +105 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/tokenization_speech_to_text_2.py +252 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tapex/__init__.py +26 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tapex/tokenization_tapex.py +1470 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/trajectory_transformer/__init__.py +27 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/trajectory_transformer/configuration_trajectory_transformer.py +155 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py +602 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/__init__.py +29 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/configuration_transfo_xl.py +189 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py +1128 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py +178 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py +1303 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py +251 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/tokenization_transfo_xl.py +825 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/__init__.py +20 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/configuration_tvlt.py +187 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/feature_extraction_tvlt.py +233 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/image_processing_tvlt.py +438 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/modeling_tvlt.py +1274 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/processing_tvlt.py +86 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/van/__init__.py +27 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/van/configuration_van.py +110 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/van/modeling_van.py +520 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/vit_hybrid/__init__.py +28 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/vit_hybrid/configuration_vit_hybrid.py +180 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/vit_hybrid/image_processing_vit_hybrid.py +341 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/vit_hybrid/modeling_vit_hybrid.py +740 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/xlm_prophetnet/__init__.py +28 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/xlm_prophetnet/configuration_xlm_prophetnet.py +181 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/xlm_prophetnet/modeling_xlm_prophetnet.py +0 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/xlm_prophetnet/tokenization_xlm_prophetnet.py +322 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/depth_anything/__init__.py +27 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/depth_anything/configuration_depth_anything.py +176 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/depth_anything/modeling_depth_anything.py +427 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/depth_pro/__init__.py +29 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/depth_pro/configuration_depth_pro.py +204 -0
- miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/depth_pro/image_processing_depth_pro.py +389 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/realm/configuration_realm.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The REALM 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 |
+
"""REALM 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 RealmConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of
|
| 27 |
+
|
| 28 |
+
1. [`RealmEmbedder`]
|
| 29 |
+
2. [`RealmScorer`]
|
| 30 |
+
3. [`RealmKnowledgeAugEncoder`]
|
| 31 |
+
4. [`RealmRetriever`]
|
| 32 |
+
5. [`RealmReader`]
|
| 33 |
+
6. [`RealmForOpenQA`]
|
| 34 |
+
|
| 35 |
+
It is used to instantiate an REALM model according to the specified arguments, defining the model architecture.
|
| 36 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the REALM
|
| 37 |
+
[google/realm-cc-news-pretrained-embedder](https://huggingface.co/google/realm-cc-news-pretrained-embedder)
|
| 38 |
+
architecture.
|
| 39 |
+
|
| 40 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 41 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 46 |
+
Vocabulary size of the REALM model. Defines the number of different tokens that can be represented by the
|
| 47 |
+
`inputs_ids` passed when calling [`RealmEmbedder`], [`RealmScorer`], [`RealmKnowledgeAugEncoder`], or
|
| 48 |
+
[`RealmReader`].
|
| 49 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 50 |
+
Dimension of the encoder layers and the pooler layer.
|
| 51 |
+
retriever_proj_size (`int`, *optional*, defaults to 128):
|
| 52 |
+
Dimension of the retriever(embedder) projection.
|
| 53 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 54 |
+
Number of hidden layers in the Transformer encoder.
|
| 55 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 56 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 57 |
+
num_candidates (`int`, *optional*, defaults to 8):
|
| 58 |
+
Number of candidates inputted to the RealmScorer or RealmKnowledgeAugEncoder.
|
| 59 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 60 |
+
Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 61 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
|
| 62 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 63 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 64 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 65 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 66 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 67 |
+
The dropout ratio for the attention probabilities.
|
| 68 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 69 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 70 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 71 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 72 |
+
The vocabulary size of the `token_type_ids` passed when calling [`RealmEmbedder`], [`RealmScorer`],
|
| 73 |
+
[`RealmKnowledgeAugEncoder`], or [`RealmReader`].
|
| 74 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 75 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 76 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 77 |
+
The epsilon used by the layer normalization layers.
|
| 78 |
+
span_hidden_size (`int`, *optional*, defaults to 256):
|
| 79 |
+
Dimension of the reader's spans.
|
| 80 |
+
max_span_width (`int`, *optional*, defaults to 10):
|
| 81 |
+
Max span width of the reader.
|
| 82 |
+
reader_layer_norm_eps (`float`, *optional*, defaults to 1e-3):
|
| 83 |
+
The epsilon used by the reader's layer normalization layers.
|
| 84 |
+
reader_beam_size (`int`, *optional*, defaults to 5):
|
| 85 |
+
Beam size of the reader.
|
| 86 |
+
reader_seq_len (`int`, *optional*, defaults to 288+32):
|
| 87 |
+
Maximum sequence length of the reader.
|
| 88 |
+
num_block_records (`int`, *optional*, defaults to 13353718):
|
| 89 |
+
Number of block records.
|
| 90 |
+
searcher_beam_size (`int`, *optional*, defaults to 5000):
|
| 91 |
+
Beam size of the searcher. Note that when eval mode is enabled, *searcher_beam_size* will be the same as
|
| 92 |
+
*reader_beam_size*.
|
| 93 |
+
|
| 94 |
+
Example:
|
| 95 |
+
|
| 96 |
+
```python
|
| 97 |
+
>>> from transformers import RealmConfig, RealmEmbedder
|
| 98 |
+
|
| 99 |
+
>>> # Initializing a REALM realm-cc-news-pretrained-* style configuration
|
| 100 |
+
>>> configuration = RealmConfig()
|
| 101 |
+
|
| 102 |
+
>>> # Initializing a model (with random weights) from the google/realm-cc-news-pretrained-embedder style configuration
|
| 103 |
+
>>> model = RealmEmbedder(configuration)
|
| 104 |
+
|
| 105 |
+
>>> # Accessing the model configuration
|
| 106 |
+
>>> configuration = model.config
|
| 107 |
+
```"""
|
| 108 |
+
|
| 109 |
+
model_type = "realm"
|
| 110 |
+
|
| 111 |
+
def __init__(
|
| 112 |
+
self,
|
| 113 |
+
vocab_size=30522,
|
| 114 |
+
hidden_size=768,
|
| 115 |
+
retriever_proj_size=128,
|
| 116 |
+
num_hidden_layers=12,
|
| 117 |
+
num_attention_heads=12,
|
| 118 |
+
num_candidates=8,
|
| 119 |
+
intermediate_size=3072,
|
| 120 |
+
hidden_act="gelu_new",
|
| 121 |
+
hidden_dropout_prob=0.1,
|
| 122 |
+
attention_probs_dropout_prob=0.1,
|
| 123 |
+
max_position_embeddings=512,
|
| 124 |
+
type_vocab_size=2,
|
| 125 |
+
initializer_range=0.02,
|
| 126 |
+
layer_norm_eps=1e-12,
|
| 127 |
+
span_hidden_size=256,
|
| 128 |
+
max_span_width=10,
|
| 129 |
+
reader_layer_norm_eps=1e-3,
|
| 130 |
+
reader_beam_size=5,
|
| 131 |
+
reader_seq_len=320, # 288 + 32
|
| 132 |
+
num_block_records=13353718,
|
| 133 |
+
searcher_beam_size=5000,
|
| 134 |
+
pad_token_id=1,
|
| 135 |
+
bos_token_id=0,
|
| 136 |
+
eos_token_id=2,
|
| 137 |
+
**kwargs,
|
| 138 |
+
):
|
| 139 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 140 |
+
|
| 141 |
+
# Common config
|
| 142 |
+
self.vocab_size = vocab_size
|
| 143 |
+
self.max_position_embeddings = max_position_embeddings
|
| 144 |
+
self.hidden_size = hidden_size
|
| 145 |
+
self.retriever_proj_size = retriever_proj_size
|
| 146 |
+
self.num_hidden_layers = num_hidden_layers
|
| 147 |
+
self.num_attention_heads = num_attention_heads
|
| 148 |
+
self.num_candidates = num_candidates
|
| 149 |
+
self.intermediate_size = intermediate_size
|
| 150 |
+
self.hidden_act = hidden_act
|
| 151 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 152 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 153 |
+
self.initializer_range = initializer_range
|
| 154 |
+
self.type_vocab_size = type_vocab_size
|
| 155 |
+
self.layer_norm_eps = layer_norm_eps
|
| 156 |
+
|
| 157 |
+
# Reader config
|
| 158 |
+
self.span_hidden_size = span_hidden_size
|
| 159 |
+
self.max_span_width = max_span_width
|
| 160 |
+
self.reader_layer_norm_eps = reader_layer_norm_eps
|
| 161 |
+
self.reader_beam_size = reader_beam_size
|
| 162 |
+
self.reader_seq_len = reader_seq_len
|
| 163 |
+
|
| 164 |
+
# Retrieval config
|
| 165 |
+
self.num_block_records = num_block_records
|
| 166 |
+
self.searcher_beam_size = searcher_beam_size
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
__all__ = ["RealmConfig"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/realm/modeling_realm.py
ADDED
|
@@ -0,0 +1,1855 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The REALM authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch REALM model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import Optional, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from torch import nn
|
| 24 |
+
from torch.nn import CrossEntropyLoss
|
| 25 |
+
|
| 26 |
+
from ....activations import ACT2FN
|
| 27 |
+
from ....cache_utils import Cache
|
| 28 |
+
from ....modeling_layers import GradientCheckpointingLayer
|
| 29 |
+
from ....modeling_outputs import (
|
| 30 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 31 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 32 |
+
MaskedLMOutput,
|
| 33 |
+
ModelOutput,
|
| 34 |
+
)
|
| 35 |
+
from ....modeling_utils import PreTrainedModel
|
| 36 |
+
from ....pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 37 |
+
from ....utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
|
| 38 |
+
from ....utils.deprecation import deprecate_kwarg
|
| 39 |
+
from .configuration_realm import RealmConfig
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
_EMBEDDER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-embedder"
|
| 44 |
+
_ENCODER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-encoder"
|
| 45 |
+
_SCORER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-scorer"
|
| 46 |
+
_CONFIG_FOR_DOC = "RealmConfig"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def load_tf_weights_in_realm(model, config, tf_checkpoint_path):
|
| 50 |
+
"""Load tf checkpoints in a pytorch model."""
|
| 51 |
+
try:
|
| 52 |
+
import re
|
| 53 |
+
|
| 54 |
+
import numpy as np
|
| 55 |
+
import tensorflow as tf
|
| 56 |
+
except ImportError:
|
| 57 |
+
logger.error(
|
| 58 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
| 59 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
| 60 |
+
)
|
| 61 |
+
raise
|
| 62 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
| 63 |
+
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
|
| 64 |
+
# Load weights from TF model
|
| 65 |
+
init_vars = tf.train.list_variables(tf_path)
|
| 66 |
+
names = []
|
| 67 |
+
arrays = []
|
| 68 |
+
|
| 69 |
+
for name, shape in init_vars:
|
| 70 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
| 71 |
+
array = tf.train.load_variable(tf_path, name)
|
| 72 |
+
names.append(name)
|
| 73 |
+
arrays.append(array)
|
| 74 |
+
|
| 75 |
+
for name, array in zip(names, arrays):
|
| 76 |
+
if isinstance(model, RealmReader) and "reader" not in name:
|
| 77 |
+
logger.info(f"Skipping {name} as it is not {model.__class__.__name__}'s parameter")
|
| 78 |
+
continue
|
| 79 |
+
|
| 80 |
+
# For pretrained openqa reader
|
| 81 |
+
if (name.startswith("bert") or name.startswith("cls")) and isinstance(model, RealmForOpenQA):
|
| 82 |
+
name = name.replace("bert/", "reader/realm/")
|
| 83 |
+
name = name.replace("cls/", "reader/cls/")
|
| 84 |
+
|
| 85 |
+
# For pretrained encoder
|
| 86 |
+
if (name.startswith("bert") or name.startswith("cls")) and isinstance(model, RealmKnowledgeAugEncoder):
|
| 87 |
+
name = name.replace("bert/", "realm/")
|
| 88 |
+
|
| 89 |
+
# For finetuned reader
|
| 90 |
+
if name.startswith("reader"):
|
| 91 |
+
reader_prefix = "" if isinstance(model, RealmReader) else "reader/"
|
| 92 |
+
name = name.replace("reader/module/bert/", f"{reader_prefix}realm/")
|
| 93 |
+
name = name.replace("reader/module/cls/", f"{reader_prefix}cls/")
|
| 94 |
+
name = name.replace("reader/dense/", f"{reader_prefix}qa_outputs/dense_intermediate/")
|
| 95 |
+
name = name.replace("reader/dense_1/", f"{reader_prefix}qa_outputs/dense_output/")
|
| 96 |
+
name = name.replace("reader/layer_normalization", f"{reader_prefix}qa_outputs/layer_normalization")
|
| 97 |
+
|
| 98 |
+
# For embedder and scorer
|
| 99 |
+
if name.startswith("module/module/module/"): # finetuned
|
| 100 |
+
embedder_prefix = "" if isinstance(model, RealmEmbedder) else "embedder/"
|
| 101 |
+
name = name.replace("module/module/module/module/bert/", f"{embedder_prefix}realm/")
|
| 102 |
+
name = name.replace("module/module/module/LayerNorm/", f"{embedder_prefix}cls/LayerNorm/")
|
| 103 |
+
name = name.replace("module/module/module/dense/", f"{embedder_prefix}cls/dense/")
|
| 104 |
+
name = name.replace("module/module/module/module/cls/predictions/", f"{embedder_prefix}cls/predictions/")
|
| 105 |
+
name = name.replace("module/module/module/bert/", f"{embedder_prefix}realm/")
|
| 106 |
+
name = name.replace("module/module/module/cls/predictions/", f"{embedder_prefix}cls/predictions/")
|
| 107 |
+
elif name.startswith("module/module/"): # pretrained
|
| 108 |
+
embedder_prefix = "" if isinstance(model, RealmEmbedder) else "embedder/"
|
| 109 |
+
name = name.replace("module/module/LayerNorm/", f"{embedder_prefix}cls/LayerNorm/")
|
| 110 |
+
name = name.replace("module/module/dense/", f"{embedder_prefix}cls/dense/")
|
| 111 |
+
|
| 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 |
+
else:
|
| 132 |
+
try:
|
| 133 |
+
pointer = getattr(pointer, scope_names[0])
|
| 134 |
+
except AttributeError:
|
| 135 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
| 136 |
+
continue
|
| 137 |
+
if len(scope_names) >= 2:
|
| 138 |
+
num = int(scope_names[1])
|
| 139 |
+
pointer = pointer[num]
|
| 140 |
+
if m_name[-11:] == "_embeddings":
|
| 141 |
+
pointer = getattr(pointer, "weight")
|
| 142 |
+
elif m_name == "kernel":
|
| 143 |
+
array = np.transpose(array)
|
| 144 |
+
try:
|
| 145 |
+
assert pointer.shape == array.shape, (
|
| 146 |
+
f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
|
| 147 |
+
)
|
| 148 |
+
except AssertionError as e:
|
| 149 |
+
e.args += (pointer.shape, array.shape)
|
| 150 |
+
raise
|
| 151 |
+
logger.info(f"Initialize PyTorch weight {name}")
|
| 152 |
+
pointer.data = torch.from_numpy(array)
|
| 153 |
+
return model
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class RealmEmbeddings(nn.Module):
|
| 157 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 158 |
+
|
| 159 |
+
def __init__(self, config):
|
| 160 |
+
super().__init__()
|
| 161 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 162 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 163 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 164 |
+
|
| 165 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 166 |
+
# any TensorFlow checkpoint file
|
| 167 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 168 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 169 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 170 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 171 |
+
self.register_buffer(
|
| 172 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 173 |
+
)
|
| 174 |
+
self.register_buffer(
|
| 175 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
def forward(
|
| 179 |
+
self,
|
| 180 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 181 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 182 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 183 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 184 |
+
past_key_values_length: int = 0,
|
| 185 |
+
) -> torch.Tensor:
|
| 186 |
+
if input_ids is not None:
|
| 187 |
+
input_shape = input_ids.size()
|
| 188 |
+
else:
|
| 189 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 190 |
+
|
| 191 |
+
seq_length = input_shape[1]
|
| 192 |
+
|
| 193 |
+
if position_ids is None:
|
| 194 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 195 |
+
|
| 196 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 197 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 198 |
+
# issue #5664
|
| 199 |
+
if token_type_ids is None:
|
| 200 |
+
if hasattr(self, "token_type_ids"):
|
| 201 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 202 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 203 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 204 |
+
else:
|
| 205 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 206 |
+
|
| 207 |
+
if inputs_embeds is None:
|
| 208 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 209 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 210 |
+
|
| 211 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 212 |
+
if self.position_embedding_type == "absolute":
|
| 213 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 214 |
+
embeddings += position_embeddings
|
| 215 |
+
embeddings = self.LayerNorm(embeddings)
|
| 216 |
+
embeddings = self.dropout(embeddings)
|
| 217 |
+
return embeddings
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class RealmSelfAttention(nn.Module):
|
| 221 |
+
def __init__(self, config, position_embedding_type=None):
|
| 222 |
+
super().__init__()
|
| 223 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 224 |
+
raise ValueError(
|
| 225 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 226 |
+
f"heads ({config.num_attention_heads})"
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
self.num_attention_heads = config.num_attention_heads
|
| 230 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 231 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 232 |
+
|
| 233 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 234 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 235 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 236 |
+
|
| 237 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 238 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
| 239 |
+
config, "position_embedding_type", "absolute"
|
| 240 |
+
)
|
| 241 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 242 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 243 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 244 |
+
|
| 245 |
+
self.is_decoder = config.is_decoder
|
| 246 |
+
|
| 247 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 248 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 249 |
+
x = x.view(new_x_shape)
|
| 250 |
+
return x.permute(0, 2, 1, 3)
|
| 251 |
+
|
| 252 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 253 |
+
def forward(
|
| 254 |
+
self,
|
| 255 |
+
hidden_states: torch.Tensor,
|
| 256 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 257 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 258 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 259 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 260 |
+
past_key_values: Optional[Cache] = None,
|
| 261 |
+
output_attentions: Optional[bool] = False,
|
| 262 |
+
) -> tuple[torch.Tensor]:
|
| 263 |
+
mixed_query_layer = self.query(hidden_states)
|
| 264 |
+
|
| 265 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 266 |
+
# and values come from an encoder; the attention mask needs to be
|
| 267 |
+
# such that the encoder's padding tokens are not attended to.
|
| 268 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 269 |
+
|
| 270 |
+
if is_cross_attention and past_key_values is not None:
|
| 271 |
+
# reuse k,v, cross_attentions
|
| 272 |
+
key_layer = past_key_values[0]
|
| 273 |
+
value_layer = past_key_values[1]
|
| 274 |
+
attention_mask = encoder_attention_mask
|
| 275 |
+
elif is_cross_attention:
|
| 276 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 277 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 278 |
+
attention_mask = encoder_attention_mask
|
| 279 |
+
elif past_key_values is not None:
|
| 280 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 281 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 282 |
+
key_layer = torch.cat([past_key_values[0], key_layer], dim=2)
|
| 283 |
+
value_layer = torch.cat([past_key_values[1], value_layer], dim=2)
|
| 284 |
+
else:
|
| 285 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 286 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 287 |
+
|
| 288 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 289 |
+
|
| 290 |
+
use_cache = past_key_values is not None
|
| 291 |
+
if self.is_decoder:
|
| 292 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 293 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 294 |
+
# key/value_states (first "if" case)
|
| 295 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 296 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 297 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 298 |
+
# if encoder bi-directional self-attention `past_key_values` is always `None`
|
| 299 |
+
past_key_values = (key_layer, value_layer)
|
| 300 |
+
|
| 301 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 302 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 303 |
+
|
| 304 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 305 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
| 306 |
+
if use_cache:
|
| 307 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
| 308 |
+
-1, 1
|
| 309 |
+
)
|
| 310 |
+
else:
|
| 311 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 312 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 313 |
+
distance = position_ids_l - position_ids_r
|
| 314 |
+
|
| 315 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 316 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 317 |
+
|
| 318 |
+
if self.position_embedding_type == "relative_key":
|
| 319 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 320 |
+
attention_scores = attention_scores + relative_position_scores
|
| 321 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 322 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 323 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 324 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 325 |
+
|
| 326 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 327 |
+
if attention_mask is not None:
|
| 328 |
+
# Apply the attention mask is (precomputed for all layers in RealmModel forward() function)
|
| 329 |
+
attention_scores = attention_scores + attention_mask
|
| 330 |
+
|
| 331 |
+
# Normalize the attention scores to probabilities.
|
| 332 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 333 |
+
|
| 334 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 335 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 336 |
+
attention_probs = self.dropout(attention_probs)
|
| 337 |
+
|
| 338 |
+
# Mask heads if we want to
|
| 339 |
+
if head_mask is not None:
|
| 340 |
+
attention_probs = attention_probs * head_mask
|
| 341 |
+
|
| 342 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 343 |
+
|
| 344 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 345 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 346 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 347 |
+
|
| 348 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 349 |
+
|
| 350 |
+
if self.is_decoder:
|
| 351 |
+
outputs = outputs + (past_key_values,)
|
| 352 |
+
return outputs
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
class RealmSelfOutput(nn.Module):
|
| 356 |
+
def __init__(self, config):
|
| 357 |
+
super().__init__()
|
| 358 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 359 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 360 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 361 |
+
|
| 362 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 363 |
+
hidden_states = self.dense(hidden_states)
|
| 364 |
+
hidden_states = self.dropout(hidden_states)
|
| 365 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 366 |
+
return hidden_states
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
REALM_SELF_ATTENTION_CLASSES = {
|
| 370 |
+
"eager": RealmSelfAttention,
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
class RealmAttention(nn.Module):
|
| 375 |
+
def __init__(self, config, position_embedding_type=None):
|
| 376 |
+
super().__init__()
|
| 377 |
+
self.self = REALM_SELF_ATTENTION_CLASSES[config._attn_implementation](
|
| 378 |
+
config, position_embedding_type=position_embedding_type
|
| 379 |
+
)
|
| 380 |
+
self.output = RealmSelfOutput(config)
|
| 381 |
+
self.pruned_heads = set()
|
| 382 |
+
|
| 383 |
+
def prune_heads(self, heads):
|
| 384 |
+
if len(heads) == 0:
|
| 385 |
+
return
|
| 386 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 387 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
# Prune linear layers
|
| 391 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 392 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 393 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 394 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 395 |
+
|
| 396 |
+
# Update hyper params and store pruned heads
|
| 397 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 398 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 399 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 400 |
+
|
| 401 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 402 |
+
def forward(
|
| 403 |
+
self,
|
| 404 |
+
hidden_states: torch.Tensor,
|
| 405 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 406 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 407 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 408 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 409 |
+
past_key_values: Optional[Cache] = None,
|
| 410 |
+
output_attentions: Optional[bool] = False,
|
| 411 |
+
) -> tuple[torch.Tensor]:
|
| 412 |
+
self_outputs = self.self(
|
| 413 |
+
hidden_states,
|
| 414 |
+
attention_mask,
|
| 415 |
+
head_mask,
|
| 416 |
+
encoder_hidden_states,
|
| 417 |
+
encoder_attention_mask,
|
| 418 |
+
past_key_values,
|
| 419 |
+
output_attentions,
|
| 420 |
+
)
|
| 421 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 422 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 423 |
+
return outputs
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class RealmIntermediate(nn.Module):
|
| 427 |
+
def __init__(self, config):
|
| 428 |
+
super().__init__()
|
| 429 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 430 |
+
if isinstance(config.hidden_act, str):
|
| 431 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 432 |
+
else:
|
| 433 |
+
self.intermediate_act_fn = config.hidden_act
|
| 434 |
+
|
| 435 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 436 |
+
hidden_states = self.dense(hidden_states)
|
| 437 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 438 |
+
return hidden_states
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
class RealmOutput(nn.Module):
|
| 442 |
+
def __init__(self, config):
|
| 443 |
+
super().__init__()
|
| 444 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 445 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 446 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 447 |
+
|
| 448 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 449 |
+
hidden_states = self.dense(hidden_states)
|
| 450 |
+
hidden_states = self.dropout(hidden_states)
|
| 451 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 452 |
+
return hidden_states
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
class RealmLayer(GradientCheckpointingLayer):
|
| 456 |
+
def __init__(self, config):
|
| 457 |
+
super().__init__()
|
| 458 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 459 |
+
self.seq_len_dim = 1
|
| 460 |
+
self.attention = RealmAttention(config)
|
| 461 |
+
self.is_decoder = config.is_decoder
|
| 462 |
+
self.add_cross_attention = config.add_cross_attention
|
| 463 |
+
if self.add_cross_attention:
|
| 464 |
+
if not self.is_decoder:
|
| 465 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 466 |
+
self.crossattention = RealmAttention(config, position_embedding_type="absolute")
|
| 467 |
+
self.intermediate = RealmIntermediate(config)
|
| 468 |
+
self.output = RealmOutput(config)
|
| 469 |
+
|
| 470 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 471 |
+
def forward(
|
| 472 |
+
self,
|
| 473 |
+
hidden_states: torch.Tensor,
|
| 474 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 475 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 476 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 477 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 478 |
+
past_key_values: Optional[Cache] = None,
|
| 479 |
+
output_attentions: Optional[bool] = False,
|
| 480 |
+
) -> tuple[torch.Tensor]:
|
| 481 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 482 |
+
self_attn_past_key_value = past_key_values[:2] if past_key_values is not None else None
|
| 483 |
+
self_attention_outputs = self.attention(
|
| 484 |
+
hidden_states,
|
| 485 |
+
attention_mask,
|
| 486 |
+
head_mask,
|
| 487 |
+
output_attentions=output_attentions,
|
| 488 |
+
past_key_values=self_attn_past_key_value,
|
| 489 |
+
)
|
| 490 |
+
attention_output = self_attention_outputs[0]
|
| 491 |
+
|
| 492 |
+
# if decoder, the last output is tuple of self-attn cache
|
| 493 |
+
if self.is_decoder:
|
| 494 |
+
outputs = self_attention_outputs[1:-1]
|
| 495 |
+
present_key_value = self_attention_outputs[-1]
|
| 496 |
+
else:
|
| 497 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 498 |
+
|
| 499 |
+
cross_attn_present_key_value = None
|
| 500 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 501 |
+
if not hasattr(self, "crossattention"):
|
| 502 |
+
raise ValueError(
|
| 503 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 504 |
+
" by setting `config.add_cross_attention=True`"
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_values tuple
|
| 508 |
+
cross_attn_past_key_value = past_key_values[-2:] if past_key_values is not None else None
|
| 509 |
+
cross_attention_outputs = self.crossattention(
|
| 510 |
+
attention_output,
|
| 511 |
+
attention_mask,
|
| 512 |
+
head_mask,
|
| 513 |
+
encoder_hidden_states,
|
| 514 |
+
encoder_attention_mask,
|
| 515 |
+
cross_attn_past_key_value,
|
| 516 |
+
output_attentions,
|
| 517 |
+
)
|
| 518 |
+
attention_output = cross_attention_outputs[0]
|
| 519 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 520 |
+
|
| 521 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
| 522 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
| 523 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 524 |
+
|
| 525 |
+
layer_output = apply_chunking_to_forward(
|
| 526 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 527 |
+
)
|
| 528 |
+
outputs = (layer_output,) + outputs
|
| 529 |
+
|
| 530 |
+
# if decoder, return the attn key/values as the last output
|
| 531 |
+
if self.is_decoder:
|
| 532 |
+
outputs = outputs + (present_key_value,)
|
| 533 |
+
|
| 534 |
+
return outputs
|
| 535 |
+
|
| 536 |
+
def feed_forward_chunk(self, attention_output):
|
| 537 |
+
intermediate_output = self.intermediate(attention_output)
|
| 538 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 539 |
+
return layer_output
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
class RealmEncoder(nn.Module):
|
| 543 |
+
def __init__(self, config):
|
| 544 |
+
super().__init__()
|
| 545 |
+
self.config = config
|
| 546 |
+
self.layer = nn.ModuleList([RealmLayer(config) for _ in range(config.num_hidden_layers)])
|
| 547 |
+
self.gradient_checkpointing = False
|
| 548 |
+
|
| 549 |
+
def forward(
|
| 550 |
+
self,
|
| 551 |
+
hidden_states: torch.Tensor,
|
| 552 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 553 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 554 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 555 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 556 |
+
past_key_values: Optional[Cache] = None,
|
| 557 |
+
use_cache: Optional[bool] = None,
|
| 558 |
+
output_attentions: Optional[bool] = False,
|
| 559 |
+
output_hidden_states: Optional[bool] = False,
|
| 560 |
+
return_dict: Optional[bool] = True,
|
| 561 |
+
) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
| 562 |
+
all_hidden_states = () if output_hidden_states else None
|
| 563 |
+
all_self_attentions = () if output_attentions else None
|
| 564 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 565 |
+
|
| 566 |
+
if self.gradient_checkpointing and self.training:
|
| 567 |
+
if use_cache:
|
| 568 |
+
logger.warning_once(
|
| 569 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 570 |
+
)
|
| 571 |
+
use_cache = False
|
| 572 |
+
|
| 573 |
+
next_decoder_cache = () if use_cache else None
|
| 574 |
+
for i, layer_module in enumerate(self.layer):
|
| 575 |
+
if output_hidden_states:
|
| 576 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 577 |
+
|
| 578 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 579 |
+
|
| 580 |
+
layer_outputs = layer_module(
|
| 581 |
+
hidden_states,
|
| 582 |
+
attention_mask,
|
| 583 |
+
layer_head_mask,
|
| 584 |
+
encoder_hidden_states,
|
| 585 |
+
encoder_attention_mask,
|
| 586 |
+
past_key_values[i] if past_key_values is not None else None,
|
| 587 |
+
output_attentions,
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
hidden_states = layer_outputs[0]
|
| 591 |
+
if use_cache:
|
| 592 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 593 |
+
if output_attentions:
|
| 594 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 595 |
+
if self.config.add_cross_attention:
|
| 596 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 597 |
+
|
| 598 |
+
if output_hidden_states:
|
| 599 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 600 |
+
|
| 601 |
+
if not return_dict:
|
| 602 |
+
return tuple(
|
| 603 |
+
v
|
| 604 |
+
for v in [
|
| 605 |
+
hidden_states,
|
| 606 |
+
next_decoder_cache,
|
| 607 |
+
all_hidden_states,
|
| 608 |
+
all_self_attentions,
|
| 609 |
+
all_cross_attentions,
|
| 610 |
+
]
|
| 611 |
+
if v is not None
|
| 612 |
+
)
|
| 613 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 614 |
+
last_hidden_state=hidden_states,
|
| 615 |
+
past_key_values=next_decoder_cache,
|
| 616 |
+
hidden_states=all_hidden_states,
|
| 617 |
+
attentions=all_self_attentions,
|
| 618 |
+
cross_attentions=all_cross_attentions,
|
| 619 |
+
)
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
class RealmPooler(nn.Module):
|
| 623 |
+
def __init__(self, config):
|
| 624 |
+
super().__init__()
|
| 625 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 626 |
+
self.activation = nn.Tanh()
|
| 627 |
+
|
| 628 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 629 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 630 |
+
# to the first token.
|
| 631 |
+
first_token_tensor = hidden_states[:, 0]
|
| 632 |
+
pooled_output = self.dense(first_token_tensor)
|
| 633 |
+
pooled_output = self.activation(pooled_output)
|
| 634 |
+
return pooled_output
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
@dataclass
|
| 638 |
+
class RealmEmbedderOutput(ModelOutput):
|
| 639 |
+
"""
|
| 640 |
+
Outputs of [`RealmEmbedder`] models.
|
| 641 |
+
|
| 642 |
+
Args:
|
| 643 |
+
projected_score (`torch.FloatTensor` of shape `(batch_size, config.retriever_proj_size)`):
|
| 644 |
+
|
| 645 |
+
Projected score.
|
| 646 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 647 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 648 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
| 649 |
+
|
| 650 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 651 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 652 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 653 |
+
sequence_length)`.
|
| 654 |
+
|
| 655 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 656 |
+
heads.
|
| 657 |
+
"""
|
| 658 |
+
|
| 659 |
+
projected_score: Optional[torch.FloatTensor] = None
|
| 660 |
+
hidden_states: Optional[tuple[torch.FloatTensor]] = None
|
| 661 |
+
attentions: Optional[tuple[torch.FloatTensor]] = None
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
@dataclass
|
| 665 |
+
class RealmScorerOutput(ModelOutput):
|
| 666 |
+
"""
|
| 667 |
+
Outputs of [`RealmScorer`] models.
|
| 668 |
+
|
| 669 |
+
Args:
|
| 670 |
+
relevance_score (`torch.FloatTensor` of shape `(batch_size, config.num_candidates)`):
|
| 671 |
+
The relevance score of document candidates (before softmax).
|
| 672 |
+
query_score (`torch.FloatTensor` of shape `(batch_size, config.retriever_proj_size)`):
|
| 673 |
+
Query score derived from the query embedder.
|
| 674 |
+
candidate_score (`torch.FloatTensor` of shape `(batch_size, config.num_candidates, config.retriever_proj_size)`):
|
| 675 |
+
Candidate score derived from the embedder.
|
| 676 |
+
"""
|
| 677 |
+
|
| 678 |
+
relevance_score: Optional[torch.FloatTensor] = None
|
| 679 |
+
query_score: Optional[torch.FloatTensor] = None
|
| 680 |
+
candidate_score: Optional[torch.FloatTensor] = None
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
@dataclass
|
| 684 |
+
class RealmReaderOutput(ModelOutput):
|
| 685 |
+
"""
|
| 686 |
+
Outputs of [`RealmReader`] models.
|
| 687 |
+
|
| 688 |
+
Args:
|
| 689 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `start_positions`, `end_positions`, `has_answers` are provided):
|
| 690 |
+
Total loss.
|
| 691 |
+
retriever_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `start_positions`, `end_positions`, `has_answers` are provided):
|
| 692 |
+
Retriever loss.
|
| 693 |
+
reader_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `start_positions`, `end_positions`, `has_answers` are provided):
|
| 694 |
+
Reader loss.
|
| 695 |
+
retriever_correct (`torch.BoolTensor` of shape `(config.searcher_beam_size,)`, *optional*):
|
| 696 |
+
Whether or not an evidence block contains answer.
|
| 697 |
+
reader_correct (`torch.BoolTensor` of shape `(config.reader_beam_size, num_candidates)`, *optional*):
|
| 698 |
+
Whether or not a span candidate contains answer.
|
| 699 |
+
block_idx (`torch.LongTensor` of shape `()`):
|
| 700 |
+
The index of the retrieved evidence block in which the predicted answer is most likely.
|
| 701 |
+
candidate (`torch.LongTensor` of shape `()`):
|
| 702 |
+
The index of the retrieved span candidates in which the predicted answer is most likely.
|
| 703 |
+
start_pos (`torch.IntTensor` of shape `()`):
|
| 704 |
+
Predicted answer starting position in *RealmReader*'s inputs.
|
| 705 |
+
end_pos (`torch.IntTensor` of shape `()`):
|
| 706 |
+
Predicted answer ending position in *RealmReader*'s inputs.
|
| 707 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 708 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 709 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
| 710 |
+
|
| 711 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 712 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 713 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 714 |
+
sequence_length)`.
|
| 715 |
+
|
| 716 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 717 |
+
heads.
|
| 718 |
+
"""
|
| 719 |
+
|
| 720 |
+
loss: Optional[torch.FloatTensor] = None
|
| 721 |
+
retriever_loss: Optional[torch.FloatTensor] = None
|
| 722 |
+
reader_loss: Optional[torch.FloatTensor] = None
|
| 723 |
+
retriever_correct: Optional[torch.BoolTensor] = None
|
| 724 |
+
reader_correct: Optional[torch.BoolTensor] = None
|
| 725 |
+
block_idx: Optional[torch.LongTensor] = None
|
| 726 |
+
candidate: Optional[torch.LongTensor] = None
|
| 727 |
+
start_pos: Optional[torch.IntTensor] = None
|
| 728 |
+
end_pos: Optional[torch.IntTensor] = None
|
| 729 |
+
hidden_states: Optional[tuple[torch.FloatTensor]] = None
|
| 730 |
+
attentions: Optional[tuple[torch.FloatTensor]] = None
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
@dataclass
|
| 734 |
+
class RealmForOpenQAOutput(ModelOutput):
|
| 735 |
+
"""
|
| 736 |
+
|
| 737 |
+
Outputs of [`RealmForOpenQA`] models.
|
| 738 |
+
|
| 739 |
+
Args:
|
| 740 |
+
reader_output (`dict`):
|
| 741 |
+
Reader output.
|
| 742 |
+
predicted_answer_ids (`torch.LongTensor` of shape `(answer_sequence_length)`):
|
| 743 |
+
Predicted answer ids.
|
| 744 |
+
"""
|
| 745 |
+
|
| 746 |
+
reader_output: Optional[dict] = None
|
| 747 |
+
predicted_answer_ids: Optional[torch.LongTensor] = None
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
class RealmPredictionHeadTransform(nn.Module):
|
| 751 |
+
def __init__(self, config):
|
| 752 |
+
super().__init__()
|
| 753 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 754 |
+
if isinstance(config.hidden_act, str):
|
| 755 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 756 |
+
else:
|
| 757 |
+
self.transform_act_fn = config.hidden_act
|
| 758 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 759 |
+
|
| 760 |
+
def forward(self, hidden_states):
|
| 761 |
+
hidden_states = self.dense(hidden_states)
|
| 762 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 763 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 764 |
+
return hidden_states
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
class RealmLMPredictionHead(nn.Module):
|
| 768 |
+
def __init__(self, config):
|
| 769 |
+
super().__init__()
|
| 770 |
+
self.transform = RealmPredictionHeadTransform(config)
|
| 771 |
+
|
| 772 |
+
# The output weights are the same as the input embeddings, but there is
|
| 773 |
+
# an output-only bias for each token.
|
| 774 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 775 |
+
|
| 776 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 777 |
+
|
| 778 |
+
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
|
| 779 |
+
self.decoder.bias = self.bias
|
| 780 |
+
|
| 781 |
+
def _tie_weights(self):
|
| 782 |
+
self.decoder.bias = self.bias
|
| 783 |
+
|
| 784 |
+
def forward(self, hidden_states):
|
| 785 |
+
hidden_states = self.transform(hidden_states)
|
| 786 |
+
hidden_states = self.decoder(hidden_states)
|
| 787 |
+
return hidden_states
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
class RealmOnlyMLMHead(nn.Module):
|
| 791 |
+
def __init__(self, config):
|
| 792 |
+
super().__init__()
|
| 793 |
+
self.predictions = RealmLMPredictionHead(config)
|
| 794 |
+
|
| 795 |
+
def forward(self, sequence_output):
|
| 796 |
+
prediction_scores = self.predictions(sequence_output)
|
| 797 |
+
return prediction_scores
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
class RealmScorerProjection(nn.Module):
|
| 801 |
+
def __init__(self, config):
|
| 802 |
+
super().__init__()
|
| 803 |
+
self.predictions = RealmLMPredictionHead(config)
|
| 804 |
+
self.dense = nn.Linear(config.hidden_size, config.retriever_proj_size)
|
| 805 |
+
self.LayerNorm = nn.LayerNorm(config.retriever_proj_size, eps=config.layer_norm_eps)
|
| 806 |
+
|
| 807 |
+
def forward(self, hidden_states):
|
| 808 |
+
hidden_states = self.dense(hidden_states)
|
| 809 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 810 |
+
return hidden_states
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
class RealmReaderProjection(nn.Module):
|
| 814 |
+
def __init__(self, config):
|
| 815 |
+
super().__init__()
|
| 816 |
+
self.config = config
|
| 817 |
+
self.dense_intermediate = nn.Linear(config.hidden_size, config.span_hidden_size * 2)
|
| 818 |
+
self.dense_output = nn.Linear(config.span_hidden_size, 1)
|
| 819 |
+
self.layer_normalization = nn.LayerNorm(config.span_hidden_size, eps=config.reader_layer_norm_eps)
|
| 820 |
+
self.relu = nn.ReLU()
|
| 821 |
+
|
| 822 |
+
def forward(self, hidden_states, block_mask):
|
| 823 |
+
def span_candidates(masks):
|
| 824 |
+
"""
|
| 825 |
+
Generate span candidates.
|
| 826 |
+
|
| 827 |
+
Args:
|
| 828 |
+
masks: <bool> [num_retrievals, max_sequence_len]
|
| 829 |
+
|
| 830 |
+
Returns:
|
| 831 |
+
starts: <int32> [num_spans] ends: <int32> [num_spans] span_masks: <int32> [num_retrievals, num_spans]
|
| 832 |
+
whether spans locate in evidence block.
|
| 833 |
+
"""
|
| 834 |
+
_, max_sequence_len = masks.shape
|
| 835 |
+
|
| 836 |
+
def _spans_given_width(width):
|
| 837 |
+
current_starts = torch.arange(max_sequence_len - width + 1, device=masks.device)
|
| 838 |
+
current_ends = torch.arange(width - 1, max_sequence_len, device=masks.device)
|
| 839 |
+
return current_starts, current_ends
|
| 840 |
+
|
| 841 |
+
starts, ends = zip(*(_spans_given_width(w + 1) for w in range(self.config.max_span_width)))
|
| 842 |
+
|
| 843 |
+
# [num_spans]
|
| 844 |
+
starts = torch.cat(starts, 0)
|
| 845 |
+
ends = torch.cat(ends, 0)
|
| 846 |
+
|
| 847 |
+
# [num_retrievals, num_spans]
|
| 848 |
+
start_masks = torch.index_select(masks, dim=-1, index=starts)
|
| 849 |
+
end_masks = torch.index_select(masks, dim=-1, index=ends)
|
| 850 |
+
span_masks = start_masks * end_masks
|
| 851 |
+
|
| 852 |
+
return starts, ends, span_masks
|
| 853 |
+
|
| 854 |
+
def mask_to_score(mask, dtype=torch.float32):
|
| 855 |
+
return (1.0 - mask.type(dtype)) * torch.finfo(dtype).min
|
| 856 |
+
|
| 857 |
+
# [reader_beam_size, max_sequence_len, span_hidden_size * 2]
|
| 858 |
+
hidden_states = self.dense_intermediate(hidden_states)
|
| 859 |
+
# [reader_beam_size, max_sequence_len, span_hidden_size]
|
| 860 |
+
start_projection, end_projection = hidden_states.chunk(2, dim=-1)
|
| 861 |
+
|
| 862 |
+
candidate_starts, candidate_ends, candidate_mask = span_candidates(block_mask)
|
| 863 |
+
|
| 864 |
+
candidate_start_projections = torch.index_select(start_projection, dim=1, index=candidate_starts)
|
| 865 |
+
candidate_end_projections = torch.index_select(end_projection, dim=1, index=candidate_ends)
|
| 866 |
+
candidate_hidden = candidate_start_projections + candidate_end_projections
|
| 867 |
+
|
| 868 |
+
# [reader_beam_size, num_candidates, span_hidden_size]
|
| 869 |
+
candidate_hidden = self.relu(candidate_hidden)
|
| 870 |
+
# [reader_beam_size, num_candidates, span_hidden_size]
|
| 871 |
+
candidate_hidden = self.layer_normalization(candidate_hidden)
|
| 872 |
+
# [reader_beam_size, num_candidates]
|
| 873 |
+
reader_logits = self.dense_output(candidate_hidden).squeeze(-1)
|
| 874 |
+
# [reader_beam_size, num_candidates]
|
| 875 |
+
reader_logits += mask_to_score(candidate_mask, dtype=reader_logits.dtype)
|
| 876 |
+
|
| 877 |
+
return reader_logits, candidate_starts, candidate_ends
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
REALM_START_DOCSTRING = r"""
|
| 881 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
|
| 882 |
+
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 883 |
+
behavior.
|
| 884 |
+
|
| 885 |
+
Parameters:
|
| 886 |
+
config ([`RealmConfig`]): Model configuration class with all the parameters of the model.
|
| 887 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 888 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 889 |
+
"""
|
| 890 |
+
|
| 891 |
+
REALM_INPUTS_DOCSTRING = r"""
|
| 892 |
+
Args:
|
| 893 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
| 894 |
+
Indices of input sequence tokens in the vocabulary.
|
| 895 |
+
|
| 896 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 897 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 898 |
+
|
| 899 |
+
[What are input IDs?](../glossary#input-ids)
|
| 900 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
| 901 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 902 |
+
|
| 903 |
+
- 1 for tokens that are **not masked**,
|
| 904 |
+
- 0 for tokens that are **masked**.
|
| 905 |
+
|
| 906 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 907 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 908 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 909 |
+
1]`:
|
| 910 |
+
|
| 911 |
+
- 0 corresponds to a *sentence A* token,
|
| 912 |
+
- 1 corresponds to a *sentence B* token.
|
| 913 |
+
|
| 914 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 915 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 916 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 917 |
+
config.max_position_embeddings - 1]`.
|
| 918 |
+
|
| 919 |
+
[What are position IDs?](../glossary#position-ids)
|
| 920 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 921 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 922 |
+
|
| 923 |
+
- 1 indicates the head is **not masked**,
|
| 924 |
+
- 0 indicates the head is **masked**.
|
| 925 |
+
|
| 926 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 927 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 928 |
+
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
|
| 929 |
+
model's internal embedding lookup matrix.
|
| 930 |
+
output_attentions (`bool`, *optional*):
|
| 931 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 932 |
+
tensors for more detail.
|
| 933 |
+
output_hidden_states (`bool`, *optional*):
|
| 934 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 935 |
+
more detail.
|
| 936 |
+
return_dict (`bool`, *optional*):
|
| 937 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 938 |
+
"""
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
class RealmPreTrainedModel(PreTrainedModel):
|
| 942 |
+
"""
|
| 943 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 944 |
+
models.
|
| 945 |
+
"""
|
| 946 |
+
|
| 947 |
+
config: RealmConfig
|
| 948 |
+
load_tf_weights = load_tf_weights_in_realm
|
| 949 |
+
base_model_prefix = "realm"
|
| 950 |
+
|
| 951 |
+
def _init_weights(self, module):
|
| 952 |
+
"""Initialize the weights"""
|
| 953 |
+
if isinstance(module, nn.Linear):
|
| 954 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 955 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 956 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 957 |
+
if module.bias is not None:
|
| 958 |
+
module.bias.data.zero_()
|
| 959 |
+
elif isinstance(module, nn.Embedding):
|
| 960 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 961 |
+
if module.padding_idx is not None:
|
| 962 |
+
module.weight.data[module.padding_idx].zero_()
|
| 963 |
+
elif isinstance(module, nn.LayerNorm):
|
| 964 |
+
module.bias.data.zero_()
|
| 965 |
+
module.weight.data.fill_(1.0)
|
| 966 |
+
|
| 967 |
+
def _flatten_inputs(self, *inputs):
|
| 968 |
+
"""Flatten inputs' shape to (-1, input_shape[-1])"""
|
| 969 |
+
flattened_inputs = []
|
| 970 |
+
for tensor in inputs:
|
| 971 |
+
if tensor is None:
|
| 972 |
+
flattened_inputs.append(None)
|
| 973 |
+
else:
|
| 974 |
+
input_shape = tensor.shape
|
| 975 |
+
if len(input_shape) > 2:
|
| 976 |
+
tensor = tensor.view((-1, input_shape[-1]))
|
| 977 |
+
flattened_inputs.append(tensor)
|
| 978 |
+
return flattened_inputs
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
class RealmBertModel(RealmPreTrainedModel):
|
| 982 |
+
"""
|
| 983 |
+
Same as the original BertModel but remove docstrings.
|
| 984 |
+
"""
|
| 985 |
+
|
| 986 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 987 |
+
super().__init__(config)
|
| 988 |
+
self.config = config
|
| 989 |
+
|
| 990 |
+
self.embeddings = RealmEmbeddings(config)
|
| 991 |
+
self.encoder = RealmEncoder(config)
|
| 992 |
+
|
| 993 |
+
self.pooler = RealmPooler(config) if add_pooling_layer else None
|
| 994 |
+
|
| 995 |
+
# Weights initialization is mostly managed by other Realm models,
|
| 996 |
+
# but we also have them initialized here to keep a consistency.
|
| 997 |
+
self.post_init()
|
| 998 |
+
|
| 999 |
+
def get_input_embeddings(self):
|
| 1000 |
+
return self.embeddings.word_embeddings
|
| 1001 |
+
|
| 1002 |
+
def set_input_embeddings(self, value):
|
| 1003 |
+
self.embeddings.word_embeddings = value
|
| 1004 |
+
|
| 1005 |
+
def _prune_heads(self, heads_to_prune):
|
| 1006 |
+
"""
|
| 1007 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 1008 |
+
class PreTrainedModel
|
| 1009 |
+
"""
|
| 1010 |
+
for layer, heads in heads_to_prune.items():
|
| 1011 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 1012 |
+
|
| 1013 |
+
def forward(
|
| 1014 |
+
self,
|
| 1015 |
+
input_ids=None,
|
| 1016 |
+
attention_mask=None,
|
| 1017 |
+
token_type_ids=None,
|
| 1018 |
+
position_ids=None,
|
| 1019 |
+
head_mask=None,
|
| 1020 |
+
inputs_embeds=None,
|
| 1021 |
+
encoder_hidden_states=None,
|
| 1022 |
+
encoder_attention_mask=None,
|
| 1023 |
+
past_key_values=None,
|
| 1024 |
+
use_cache=None,
|
| 1025 |
+
output_attentions=None,
|
| 1026 |
+
output_hidden_states=None,
|
| 1027 |
+
return_dict=None,
|
| 1028 |
+
):
|
| 1029 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1030 |
+
output_hidden_states = (
|
| 1031 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1032 |
+
)
|
| 1033 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1034 |
+
|
| 1035 |
+
if self.config.is_decoder:
|
| 1036 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1037 |
+
else:
|
| 1038 |
+
use_cache = False
|
| 1039 |
+
|
| 1040 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1041 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 1042 |
+
elif input_ids is not None:
|
| 1043 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 1044 |
+
input_shape = input_ids.size()
|
| 1045 |
+
elif inputs_embeds is not None:
|
| 1046 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1047 |
+
else:
|
| 1048 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1049 |
+
|
| 1050 |
+
batch_size, seq_length = input_shape
|
| 1051 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 1052 |
+
|
| 1053 |
+
# past_key_values_length
|
| 1054 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 1055 |
+
|
| 1056 |
+
if attention_mask is None:
|
| 1057 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
| 1058 |
+
|
| 1059 |
+
if token_type_ids is None:
|
| 1060 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 1061 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 1062 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 1063 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 1064 |
+
else:
|
| 1065 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 1066 |
+
|
| 1067 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 1068 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 1069 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 1070 |
+
|
| 1071 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
| 1072 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 1073 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
| 1074 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
| 1075 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
| 1076 |
+
if encoder_attention_mask is None:
|
| 1077 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
| 1078 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
| 1079 |
+
else:
|
| 1080 |
+
encoder_extended_attention_mask = None
|
| 1081 |
+
|
| 1082 |
+
# Prepare head mask if needed
|
| 1083 |
+
# 1.0 in head_mask indicate we keep the head
|
| 1084 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 1085 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 1086 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 1087 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 1088 |
+
|
| 1089 |
+
embedding_output = self.embeddings(
|
| 1090 |
+
input_ids=input_ids,
|
| 1091 |
+
position_ids=position_ids,
|
| 1092 |
+
token_type_ids=token_type_ids,
|
| 1093 |
+
inputs_embeds=inputs_embeds,
|
| 1094 |
+
past_key_values_length=past_key_values_length,
|
| 1095 |
+
)
|
| 1096 |
+
encoder_outputs = self.encoder(
|
| 1097 |
+
embedding_output,
|
| 1098 |
+
attention_mask=extended_attention_mask,
|
| 1099 |
+
head_mask=head_mask,
|
| 1100 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1101 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 1102 |
+
past_key_values=past_key_values,
|
| 1103 |
+
use_cache=use_cache,
|
| 1104 |
+
output_attentions=output_attentions,
|
| 1105 |
+
output_hidden_states=output_hidden_states,
|
| 1106 |
+
return_dict=return_dict,
|
| 1107 |
+
)
|
| 1108 |
+
sequence_output = encoder_outputs[0]
|
| 1109 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 1110 |
+
|
| 1111 |
+
if not return_dict:
|
| 1112 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 1113 |
+
|
| 1114 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
| 1115 |
+
last_hidden_state=sequence_output,
|
| 1116 |
+
pooler_output=pooled_output,
|
| 1117 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 1118 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1119 |
+
attentions=encoder_outputs.attentions,
|
| 1120 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 1121 |
+
)
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
+
@add_start_docstrings(
|
| 1125 |
+
"The embedder of REALM outputting projected score that will be used to calculate relevance score.",
|
| 1126 |
+
REALM_START_DOCSTRING,
|
| 1127 |
+
)
|
| 1128 |
+
class RealmEmbedder(RealmPreTrainedModel):
|
| 1129 |
+
_tied_weights_keys = ["cls.predictions.decoder.bias"]
|
| 1130 |
+
|
| 1131 |
+
def __init__(self, config):
|
| 1132 |
+
super().__init__(config)
|
| 1133 |
+
|
| 1134 |
+
self.realm = RealmBertModel(self.config)
|
| 1135 |
+
self.cls = RealmScorerProjection(self.config)
|
| 1136 |
+
self.post_init()
|
| 1137 |
+
|
| 1138 |
+
def get_input_embeddings(self):
|
| 1139 |
+
return self.realm.embeddings.word_embeddings
|
| 1140 |
+
|
| 1141 |
+
def set_input_embeddings(self, value):
|
| 1142 |
+
self.realm.embeddings.word_embeddings = value
|
| 1143 |
+
|
| 1144 |
+
@add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1145 |
+
@replace_return_docstrings(output_type=RealmEmbedderOutput, config_class=_CONFIG_FOR_DOC)
|
| 1146 |
+
def forward(
|
| 1147 |
+
self,
|
| 1148 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1149 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1150 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1151 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1152 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1153 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1154 |
+
output_attentions: Optional[bool] = None,
|
| 1155 |
+
output_hidden_states: Optional[bool] = None,
|
| 1156 |
+
return_dict: Optional[bool] = None,
|
| 1157 |
+
) -> Union[tuple, RealmEmbedderOutput]:
|
| 1158 |
+
r"""
|
| 1159 |
+
Returns:
|
| 1160 |
+
|
| 1161 |
+
Example:
|
| 1162 |
+
|
| 1163 |
+
```python
|
| 1164 |
+
>>> from transformers import AutoTokenizer, RealmEmbedder
|
| 1165 |
+
>>> import torch
|
| 1166 |
+
|
| 1167 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/realm-cc-news-pretrained-embedder")
|
| 1168 |
+
>>> model = RealmEmbedder.from_pretrained("google/realm-cc-news-pretrained-embedder")
|
| 1169 |
+
|
| 1170 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 1171 |
+
>>> outputs = model(**inputs)
|
| 1172 |
+
|
| 1173 |
+
>>> projected_score = outputs.projected_score
|
| 1174 |
+
```
|
| 1175 |
+
"""
|
| 1176 |
+
|
| 1177 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1178 |
+
|
| 1179 |
+
realm_outputs = self.realm(
|
| 1180 |
+
input_ids,
|
| 1181 |
+
attention_mask=attention_mask,
|
| 1182 |
+
token_type_ids=token_type_ids,
|
| 1183 |
+
position_ids=position_ids,
|
| 1184 |
+
head_mask=head_mask,
|
| 1185 |
+
inputs_embeds=inputs_embeds,
|
| 1186 |
+
output_attentions=output_attentions,
|
| 1187 |
+
output_hidden_states=output_hidden_states,
|
| 1188 |
+
return_dict=return_dict,
|
| 1189 |
+
)
|
| 1190 |
+
|
| 1191 |
+
# [batch_size, hidden_size]
|
| 1192 |
+
pooler_output = realm_outputs[1]
|
| 1193 |
+
# [batch_size, retriever_proj_size]
|
| 1194 |
+
projected_score = self.cls(pooler_output)
|
| 1195 |
+
|
| 1196 |
+
if not return_dict:
|
| 1197 |
+
return (projected_score,) + realm_outputs[2:4]
|
| 1198 |
+
else:
|
| 1199 |
+
return RealmEmbedderOutput(
|
| 1200 |
+
projected_score=projected_score,
|
| 1201 |
+
hidden_states=realm_outputs.hidden_states,
|
| 1202 |
+
attentions=realm_outputs.attentions,
|
| 1203 |
+
)
|
| 1204 |
+
|
| 1205 |
+
|
| 1206 |
+
@add_start_docstrings(
|
| 1207 |
+
"The scorer of REALM outputting relevance scores representing the score of document candidates (before softmax).",
|
| 1208 |
+
REALM_START_DOCSTRING,
|
| 1209 |
+
)
|
| 1210 |
+
class RealmScorer(RealmPreTrainedModel):
|
| 1211 |
+
r"""
|
| 1212 |
+
Args:
|
| 1213 |
+
query_embedder ([`RealmEmbedder`]):
|
| 1214 |
+
Embedder for input sequences. If not specified, it will use the same embedder as candidate sequences.
|
| 1215 |
+
"""
|
| 1216 |
+
|
| 1217 |
+
def __init__(self, config, query_embedder=None):
|
| 1218 |
+
super().__init__(config)
|
| 1219 |
+
|
| 1220 |
+
self.embedder = RealmEmbedder(self.config)
|
| 1221 |
+
|
| 1222 |
+
self.query_embedder = query_embedder if query_embedder is not None else self.embedder
|
| 1223 |
+
|
| 1224 |
+
self.post_init()
|
| 1225 |
+
|
| 1226 |
+
@add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1227 |
+
@replace_return_docstrings(output_type=RealmScorerOutput, config_class=_CONFIG_FOR_DOC)
|
| 1228 |
+
def forward(
|
| 1229 |
+
self,
|
| 1230 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1231 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1232 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1233 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1234 |
+
candidate_input_ids: Optional[torch.LongTensor] = None,
|
| 1235 |
+
candidate_attention_mask: Optional[torch.FloatTensor] = None,
|
| 1236 |
+
candidate_token_type_ids: Optional[torch.LongTensor] = None,
|
| 1237 |
+
candidate_inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1238 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1239 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1240 |
+
output_attentions: Optional[bool] = None,
|
| 1241 |
+
output_hidden_states: Optional[bool] = None,
|
| 1242 |
+
return_dict: Optional[bool] = None,
|
| 1243 |
+
) -> Union[tuple, RealmScorerOutput]:
|
| 1244 |
+
r"""
|
| 1245 |
+
candidate_input_ids (`torch.LongTensor` of shape `(batch_size, num_candidates, sequence_length)`):
|
| 1246 |
+
Indices of candidate input sequence tokens in the vocabulary.
|
| 1247 |
+
|
| 1248 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1249 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1250 |
+
|
| 1251 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1252 |
+
candidate_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_candidates, sequence_length)`, *optional*):
|
| 1253 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1254 |
+
|
| 1255 |
+
- 1 for tokens that are **not masked**,
|
| 1256 |
+
- 0 for tokens that are **masked**.
|
| 1257 |
+
|
| 1258 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1259 |
+
candidate_token_type_ids (`torch.LongTensor` of shape `(batch_size, num_candidates, sequence_length)`, *optional*):
|
| 1260 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 1261 |
+
1]`:
|
| 1262 |
+
|
| 1263 |
+
- 0 corresponds to a *sentence A* token,
|
| 1264 |
+
- 1 corresponds to a *sentence B* token.
|
| 1265 |
+
|
| 1266 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 1267 |
+
candidate_inputs_embeds (`torch.FloatTensor` of shape `(batch_size * num_candidates, sequence_length, hidden_size)`, *optional*):
|
| 1268 |
+
Optionally, instead of passing `candidate_input_ids` you can choose to directly pass an embedded
|
| 1269 |
+
representation. This is useful if you want more control over how to convert *candidate_input_ids* indices
|
| 1270 |
+
into associated vectors than the model's internal embedding lookup matrix.
|
| 1271 |
+
|
| 1272 |
+
Returns:
|
| 1273 |
+
|
| 1274 |
+
Example:
|
| 1275 |
+
|
| 1276 |
+
```python
|
| 1277 |
+
>>> import torch
|
| 1278 |
+
>>> from transformers import AutoTokenizer, RealmScorer
|
| 1279 |
+
|
| 1280 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/realm-cc-news-pretrained-scorer")
|
| 1281 |
+
>>> model = RealmScorer.from_pretrained("google/realm-cc-news-pretrained-scorer", num_candidates=2)
|
| 1282 |
+
|
| 1283 |
+
>>> # batch_size = 2, num_candidates = 2
|
| 1284 |
+
>>> input_texts = ["How are you?", "What is the item in the picture?"]
|
| 1285 |
+
>>> candidates_texts = [["Hello world!", "Nice to meet you!"], ["A cute cat.", "An adorable dog."]]
|
| 1286 |
+
|
| 1287 |
+
>>> inputs = tokenizer(input_texts, return_tensors="pt")
|
| 1288 |
+
>>> candidates_inputs = tokenizer.batch_encode_candidates(candidates_texts, max_length=10, return_tensors="pt")
|
| 1289 |
+
|
| 1290 |
+
>>> outputs = model(
|
| 1291 |
+
... **inputs,
|
| 1292 |
+
... candidate_input_ids=candidates_inputs.input_ids,
|
| 1293 |
+
... candidate_attention_mask=candidates_inputs.attention_mask,
|
| 1294 |
+
... candidate_token_type_ids=candidates_inputs.token_type_ids,
|
| 1295 |
+
... )
|
| 1296 |
+
>>> relevance_score = outputs.relevance_score
|
| 1297 |
+
```"""
|
| 1298 |
+
|
| 1299 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1300 |
+
|
| 1301 |
+
if input_ids is None and inputs_embeds is None:
|
| 1302 |
+
raise ValueError("You have to specify either input_ids or input_embeds.")
|
| 1303 |
+
|
| 1304 |
+
if candidate_input_ids is None and candidate_inputs_embeds is None:
|
| 1305 |
+
raise ValueError("You have to specify either candidate_input_ids or candidate_inputs_embeds.")
|
| 1306 |
+
|
| 1307 |
+
query_outputs = self.query_embedder(
|
| 1308 |
+
input_ids,
|
| 1309 |
+
attention_mask=attention_mask,
|
| 1310 |
+
token_type_ids=token_type_ids,
|
| 1311 |
+
position_ids=position_ids,
|
| 1312 |
+
head_mask=head_mask,
|
| 1313 |
+
inputs_embeds=inputs_embeds,
|
| 1314 |
+
output_attentions=output_attentions,
|
| 1315 |
+
output_hidden_states=output_hidden_states,
|
| 1316 |
+
return_dict=return_dict,
|
| 1317 |
+
)
|
| 1318 |
+
|
| 1319 |
+
# [batch_size * num_candidates, candidate_seq_len]
|
| 1320 |
+
(flattened_input_ids, flattened_attention_mask, flattened_token_type_ids) = self._flatten_inputs(
|
| 1321 |
+
candidate_input_ids, candidate_attention_mask, candidate_token_type_ids
|
| 1322 |
+
)
|
| 1323 |
+
|
| 1324 |
+
candidate_outputs = self.embedder(
|
| 1325 |
+
flattened_input_ids,
|
| 1326 |
+
attention_mask=flattened_attention_mask,
|
| 1327 |
+
token_type_ids=flattened_token_type_ids,
|
| 1328 |
+
position_ids=position_ids,
|
| 1329 |
+
head_mask=head_mask,
|
| 1330 |
+
inputs_embeds=candidate_inputs_embeds,
|
| 1331 |
+
output_attentions=output_attentions,
|
| 1332 |
+
output_hidden_states=output_hidden_states,
|
| 1333 |
+
return_dict=return_dict,
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
# [batch_size, retriever_proj_size]
|
| 1337 |
+
query_score = query_outputs[0]
|
| 1338 |
+
# [batch_size * num_candidates, retriever_proj_size]
|
| 1339 |
+
candidate_score = candidate_outputs[0]
|
| 1340 |
+
# [batch_size, num_candidates, retriever_proj_size]
|
| 1341 |
+
candidate_score = candidate_score.view(-1, self.config.num_candidates, self.config.retriever_proj_size)
|
| 1342 |
+
# [batch_size, num_candidates]
|
| 1343 |
+
relevance_score = torch.einsum("bd,bnd->bn", query_score, candidate_score)
|
| 1344 |
+
|
| 1345 |
+
if not return_dict:
|
| 1346 |
+
return relevance_score, query_score, candidate_score
|
| 1347 |
+
|
| 1348 |
+
return RealmScorerOutput(
|
| 1349 |
+
relevance_score=relevance_score, query_score=query_score, candidate_score=candidate_score
|
| 1350 |
+
)
|
| 1351 |
+
|
| 1352 |
+
|
| 1353 |
+
@add_start_docstrings(
|
| 1354 |
+
"The knowledge-augmented encoder of REALM outputting masked language model logits and marginal log-likelihood"
|
| 1355 |
+
" loss.",
|
| 1356 |
+
REALM_START_DOCSTRING,
|
| 1357 |
+
)
|
| 1358 |
+
class RealmKnowledgeAugEncoder(RealmPreTrainedModel):
|
| 1359 |
+
_tied_weights_keys = ["cls.predictions.decoder"]
|
| 1360 |
+
|
| 1361 |
+
def __init__(self, config):
|
| 1362 |
+
super().__init__(config)
|
| 1363 |
+
self.realm = RealmBertModel(self.config)
|
| 1364 |
+
self.cls = RealmOnlyMLMHead(self.config)
|
| 1365 |
+
self.post_init()
|
| 1366 |
+
|
| 1367 |
+
def get_input_embeddings(self):
|
| 1368 |
+
return self.realm.embeddings.word_embeddings
|
| 1369 |
+
|
| 1370 |
+
def set_input_embeddings(self, value):
|
| 1371 |
+
self.realm.embeddings.word_embeddings = value
|
| 1372 |
+
|
| 1373 |
+
def get_output_embeddings(self):
|
| 1374 |
+
return self.cls.predictions.decoder
|
| 1375 |
+
|
| 1376 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1377 |
+
self.cls.predictions.decoder = new_embeddings
|
| 1378 |
+
self.cls.predictions.bias = new_embeddings.bias
|
| 1379 |
+
|
| 1380 |
+
@add_start_docstrings_to_model_forward(
|
| 1381 |
+
REALM_INPUTS_DOCSTRING.format("batch_size, num_candidates, sequence_length")
|
| 1382 |
+
)
|
| 1383 |
+
@replace_return_docstrings(output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 1384 |
+
def forward(
|
| 1385 |
+
self,
|
| 1386 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1387 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1388 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1389 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1390 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1391 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1392 |
+
relevance_score: Optional[torch.FloatTensor] = None,
|
| 1393 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1394 |
+
mlm_mask: Optional[torch.LongTensor] = None,
|
| 1395 |
+
output_attentions: Optional[bool] = None,
|
| 1396 |
+
output_hidden_states: Optional[bool] = None,
|
| 1397 |
+
return_dict: Optional[bool] = None,
|
| 1398 |
+
) -> Union[tuple, MaskedLMOutput]:
|
| 1399 |
+
r"""
|
| 1400 |
+
relevance_score (`torch.FloatTensor` of shape `(batch_size, num_candidates)`, *optional*):
|
| 1401 |
+
Relevance score derived from RealmScorer, must be specified if you want to compute the masked language
|
| 1402 |
+
modeling loss.
|
| 1403 |
+
|
| 1404 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1405 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 1406 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 1407 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1408 |
+
|
| 1409 |
+
mlm_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1410 |
+
Mask to avoid calculating joint loss on certain positions. If not specified, the loss will not be masked.
|
| 1411 |
+
Mask values selected in `[0, 1]`:
|
| 1412 |
+
|
| 1413 |
+
- 1 for tokens that are **not masked**,
|
| 1414 |
+
- 0 for tokens that are **masked**.
|
| 1415 |
+
|
| 1416 |
+
Returns:
|
| 1417 |
+
|
| 1418 |
+
Example:
|
| 1419 |
+
|
| 1420 |
+
```python
|
| 1421 |
+
>>> import torch
|
| 1422 |
+
>>> from transformers import AutoTokenizer, RealmKnowledgeAugEncoder
|
| 1423 |
+
|
| 1424 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/realm-cc-news-pretrained-encoder")
|
| 1425 |
+
>>> model = RealmKnowledgeAugEncoder.from_pretrained(
|
| 1426 |
+
... "google/realm-cc-news-pretrained-encoder", num_candidates=2
|
| 1427 |
+
... )
|
| 1428 |
+
|
| 1429 |
+
>>> # batch_size = 2, num_candidates = 2
|
| 1430 |
+
>>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]]
|
| 1431 |
+
|
| 1432 |
+
>>> inputs = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt")
|
| 1433 |
+
>>> outputs = model(**inputs)
|
| 1434 |
+
>>> logits = outputs.logits
|
| 1435 |
+
```"""
|
| 1436 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1437 |
+
|
| 1438 |
+
if labels is not None and relevance_score is None:
|
| 1439 |
+
raise ValueError(
|
| 1440 |
+
"You have to specify `relevance_score` when `labels` is specified in order to compute loss."
|
| 1441 |
+
)
|
| 1442 |
+
|
| 1443 |
+
(flattened_input_ids, flattened_attention_mask, flattened_token_type_ids) = self._flatten_inputs(
|
| 1444 |
+
input_ids, attention_mask, token_type_ids
|
| 1445 |
+
)
|
| 1446 |
+
|
| 1447 |
+
joint_outputs = self.realm(
|
| 1448 |
+
flattened_input_ids,
|
| 1449 |
+
attention_mask=flattened_attention_mask,
|
| 1450 |
+
token_type_ids=flattened_token_type_ids,
|
| 1451 |
+
position_ids=position_ids,
|
| 1452 |
+
head_mask=head_mask,
|
| 1453 |
+
inputs_embeds=inputs_embeds,
|
| 1454 |
+
output_attentions=output_attentions,
|
| 1455 |
+
output_hidden_states=output_hidden_states,
|
| 1456 |
+
return_dict=return_dict,
|
| 1457 |
+
)
|
| 1458 |
+
|
| 1459 |
+
# [batch_size * num_candidates, joint_seq_len, hidden_size]
|
| 1460 |
+
joint_output = joint_outputs[0]
|
| 1461 |
+
# [batch_size * num_candidates, joint_seq_len, vocab_size]
|
| 1462 |
+
prediction_scores = self.cls(joint_output)
|
| 1463 |
+
# [batch_size, num_candidates]
|
| 1464 |
+
candidate_score = relevance_score
|
| 1465 |
+
|
| 1466 |
+
masked_lm_loss = None
|
| 1467 |
+
if labels is not None:
|
| 1468 |
+
batch_size, seq_length = labels.size()
|
| 1469 |
+
|
| 1470 |
+
if mlm_mask is None:
|
| 1471 |
+
mlm_mask = torch.ones_like(labels, dtype=torch.float32)
|
| 1472 |
+
else:
|
| 1473 |
+
mlm_mask = mlm_mask.type(torch.float32)
|
| 1474 |
+
|
| 1475 |
+
# Compute marginal log-likelihood
|
| 1476 |
+
loss_fct = CrossEntropyLoss(reduction="none") # -100 index = padding token
|
| 1477 |
+
|
| 1478 |
+
# [batch_size * num_candidates * joint_seq_len, vocab_size]
|
| 1479 |
+
mlm_logits = prediction_scores.view(-1, self.config.vocab_size)
|
| 1480 |
+
# [batch_size * num_candidates * joint_seq_len]
|
| 1481 |
+
mlm_targets = labels.tile(1, self.config.num_candidates).view(-1)
|
| 1482 |
+
# [batch_size, num_candidates, joint_seq_len]
|
| 1483 |
+
masked_lm_log_prob = -loss_fct(mlm_logits, mlm_targets).view(
|
| 1484 |
+
batch_size, self.config.num_candidates, seq_length
|
| 1485 |
+
)
|
| 1486 |
+
# [batch_size, num_candidates, 1]
|
| 1487 |
+
candidate_log_prob = candidate_score.log_softmax(-1).unsqueeze(-1)
|
| 1488 |
+
# [batch_size, num_candidates, joint_seq_len]
|
| 1489 |
+
joint_gold_log_prob = candidate_log_prob + masked_lm_log_prob
|
| 1490 |
+
# [batch_size, joint_seq_len]
|
| 1491 |
+
marginal_gold_log_probs = joint_gold_log_prob.logsumexp(1)
|
| 1492 |
+
# []
|
| 1493 |
+
masked_lm_loss = -torch.nansum(torch.sum(marginal_gold_log_probs * mlm_mask) / torch.sum(mlm_mask))
|
| 1494 |
+
|
| 1495 |
+
if not return_dict:
|
| 1496 |
+
output = (prediction_scores,) + joint_outputs[2:4]
|
| 1497 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1498 |
+
|
| 1499 |
+
return MaskedLMOutput(
|
| 1500 |
+
loss=masked_lm_loss,
|
| 1501 |
+
logits=prediction_scores,
|
| 1502 |
+
hidden_states=joint_outputs.hidden_states,
|
| 1503 |
+
attentions=joint_outputs.attentions,
|
| 1504 |
+
)
|
| 1505 |
+
|
| 1506 |
+
|
| 1507 |
+
@add_start_docstrings("The reader of REALM.", REALM_START_DOCSTRING)
|
| 1508 |
+
class RealmReader(RealmPreTrainedModel):
|
| 1509 |
+
def __init__(self, config):
|
| 1510 |
+
super().__init__(config)
|
| 1511 |
+
self.num_labels = config.num_labels
|
| 1512 |
+
|
| 1513 |
+
self.realm = RealmBertModel(config)
|
| 1514 |
+
self.cls = RealmOnlyMLMHead(config)
|
| 1515 |
+
self.qa_outputs = RealmReaderProjection(config)
|
| 1516 |
+
|
| 1517 |
+
self.post_init()
|
| 1518 |
+
|
| 1519 |
+
@add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format("reader_beam_size, sequence_length"))
|
| 1520 |
+
@replace_return_docstrings(output_type=RealmReaderOutput, config_class=_CONFIG_FOR_DOC)
|
| 1521 |
+
def forward(
|
| 1522 |
+
self,
|
| 1523 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1524 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1525 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1526 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1527 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1528 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1529 |
+
relevance_score: Optional[torch.FloatTensor] = None,
|
| 1530 |
+
block_mask: Optional[torch.BoolTensor] = None,
|
| 1531 |
+
start_positions: Optional[torch.LongTensor] = None,
|
| 1532 |
+
end_positions: Optional[torch.LongTensor] = None,
|
| 1533 |
+
has_answers: Optional[torch.BoolTensor] = None,
|
| 1534 |
+
output_attentions: Optional[bool] = None,
|
| 1535 |
+
output_hidden_states: Optional[bool] = None,
|
| 1536 |
+
return_dict: Optional[bool] = None,
|
| 1537 |
+
) -> Union[tuple, RealmReaderOutput]:
|
| 1538 |
+
r"""
|
| 1539 |
+
relevance_score (`torch.FloatTensor` of shape `(searcher_beam_size,)`, *optional*):
|
| 1540 |
+
Relevance score, which must be specified if you want to compute the logits and marginal log loss.
|
| 1541 |
+
block_mask (`torch.BoolTensor` of shape `(searcher_beam_size, sequence_length)`, *optional*):
|
| 1542 |
+
The mask of the evidence block, which must be specified if you want to compute the logits and marginal log
|
| 1543 |
+
loss.
|
| 1544 |
+
start_positions (`torch.LongTensor` of shape `(searcher_beam_size,)`, *optional*):
|
| 1545 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1546 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1547 |
+
are not taken into account for computing the loss.
|
| 1548 |
+
end_positions (`torch.LongTensor` of shape `(searcher_beam_size,)`, *optional*):
|
| 1549 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1550 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1551 |
+
are not taken into account for computing the loss.
|
| 1552 |
+
has_answers (`torch.BoolTensor` of shape `(searcher_beam_size,)`, *optional*):
|
| 1553 |
+
Whether or not the evidence block has answer(s).
|
| 1554 |
+
|
| 1555 |
+
Returns:
|
| 1556 |
+
"""
|
| 1557 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1558 |
+
|
| 1559 |
+
if relevance_score is None:
|
| 1560 |
+
raise ValueError("You have to specify `relevance_score` to calculate logits and loss.")
|
| 1561 |
+
if block_mask is None:
|
| 1562 |
+
raise ValueError("You have to specify `block_mask` to separate question block and evidence block.")
|
| 1563 |
+
if token_type_ids.size(1) < self.config.max_span_width:
|
| 1564 |
+
raise ValueError("The input sequence length must be greater than or equal to config.max_span_width.")
|
| 1565 |
+
outputs = self.realm(
|
| 1566 |
+
input_ids,
|
| 1567 |
+
attention_mask=attention_mask,
|
| 1568 |
+
token_type_ids=token_type_ids,
|
| 1569 |
+
position_ids=position_ids,
|
| 1570 |
+
head_mask=head_mask,
|
| 1571 |
+
inputs_embeds=inputs_embeds,
|
| 1572 |
+
output_attentions=output_attentions,
|
| 1573 |
+
output_hidden_states=output_hidden_states,
|
| 1574 |
+
return_dict=return_dict,
|
| 1575 |
+
)
|
| 1576 |
+
|
| 1577 |
+
# [reader_beam_size, joint_seq_len, hidden_size]
|
| 1578 |
+
sequence_output = outputs[0]
|
| 1579 |
+
|
| 1580 |
+
# [reader_beam_size, num_candidates], [num_candidates], [num_candidates]
|
| 1581 |
+
reader_logits, candidate_starts, candidate_ends = self.qa_outputs(
|
| 1582 |
+
sequence_output, block_mask[0 : self.config.reader_beam_size]
|
| 1583 |
+
)
|
| 1584 |
+
# [searcher_beam_size, 1]
|
| 1585 |
+
retriever_logits = torch.unsqueeze(relevance_score[0 : self.config.reader_beam_size], -1)
|
| 1586 |
+
# [reader_beam_size, num_candidates]
|
| 1587 |
+
reader_logits += retriever_logits
|
| 1588 |
+
# []
|
| 1589 |
+
predicted_block_index = torch.argmax(torch.max(reader_logits, dim=1).values)
|
| 1590 |
+
# []
|
| 1591 |
+
predicted_candidate = torch.argmax(torch.max(reader_logits, dim=0).values)
|
| 1592 |
+
# [1]
|
| 1593 |
+
predicted_start = torch.index_select(candidate_starts, dim=0, index=predicted_candidate)
|
| 1594 |
+
# [1]
|
| 1595 |
+
predicted_end = torch.index_select(candidate_ends, dim=0, index=predicted_candidate)
|
| 1596 |
+
|
| 1597 |
+
total_loss = None
|
| 1598 |
+
retriever_loss = None
|
| 1599 |
+
reader_loss = None
|
| 1600 |
+
retriever_correct = None
|
| 1601 |
+
reader_correct = None
|
| 1602 |
+
if start_positions is not None and end_positions is not None and has_answers is not None:
|
| 1603 |
+
|
| 1604 |
+
def compute_correct_candidates(candidate_starts, candidate_ends, gold_starts, gold_ends):
|
| 1605 |
+
"""Compute correct span."""
|
| 1606 |
+
# [reader_beam_size, num_answers, num_candidates]
|
| 1607 |
+
is_gold_start = torch.eq(
|
| 1608 |
+
torch.unsqueeze(torch.unsqueeze(candidate_starts, 0), 0), torch.unsqueeze(gold_starts, -1)
|
| 1609 |
+
)
|
| 1610 |
+
is_gold_end = torch.eq(
|
| 1611 |
+
torch.unsqueeze(torch.unsqueeze(candidate_ends, 0), 0), torch.unsqueeze(gold_ends, -1)
|
| 1612 |
+
)
|
| 1613 |
+
|
| 1614 |
+
# [reader_beam_size, num_candidates]
|
| 1615 |
+
return torch.any(torch.logical_and(is_gold_start, is_gold_end), 1)
|
| 1616 |
+
|
| 1617 |
+
def marginal_log_loss(logits, is_correct):
|
| 1618 |
+
"""Loss based on the negative marginal log-likelihood."""
|
| 1619 |
+
|
| 1620 |
+
def mask_to_score(mask, dtype=torch.float32):
|
| 1621 |
+
return (1.0 - mask.type(dtype)) * torch.finfo(dtype).min
|
| 1622 |
+
|
| 1623 |
+
# []
|
| 1624 |
+
log_numerator = torch.logsumexp(logits + mask_to_score(is_correct, dtype=logits.dtype), dim=-1)
|
| 1625 |
+
log_denominator = torch.logsumexp(logits, dim=-1)
|
| 1626 |
+
return log_denominator - log_numerator
|
| 1627 |
+
|
| 1628 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1629 |
+
# `-1` is reserved for no answer.
|
| 1630 |
+
ignored_index = sequence_output.size(1)
|
| 1631 |
+
start_positions = start_positions.clamp(-1, ignored_index)
|
| 1632 |
+
end_positions = end_positions.clamp(-1, ignored_index)
|
| 1633 |
+
|
| 1634 |
+
retriever_correct = has_answers
|
| 1635 |
+
any_retriever_correct = torch.any(retriever_correct)
|
| 1636 |
+
|
| 1637 |
+
reader_correct = compute_correct_candidates(
|
| 1638 |
+
candidate_starts=candidate_starts,
|
| 1639 |
+
candidate_ends=candidate_ends,
|
| 1640 |
+
gold_starts=start_positions[0 : self.config.reader_beam_size],
|
| 1641 |
+
gold_ends=end_positions[0 : self.config.reader_beam_size],
|
| 1642 |
+
)
|
| 1643 |
+
any_reader_correct = torch.any(reader_correct)
|
| 1644 |
+
|
| 1645 |
+
retriever_loss = marginal_log_loss(relevance_score, retriever_correct)
|
| 1646 |
+
reader_loss = marginal_log_loss(reader_logits.view(-1), reader_correct.view(-1))
|
| 1647 |
+
retriever_loss *= any_retriever_correct.type(torch.float32)
|
| 1648 |
+
reader_loss *= any_reader_correct.type(torch.float32)
|
| 1649 |
+
|
| 1650 |
+
total_loss = (retriever_loss + reader_loss).mean()
|
| 1651 |
+
|
| 1652 |
+
if not return_dict:
|
| 1653 |
+
output = (predicted_block_index, predicted_candidate, predicted_start, predicted_end) + outputs[2:]
|
| 1654 |
+
return (
|
| 1655 |
+
((total_loss, retriever_loss, reader_loss, retriever_correct, reader_correct) + output)
|
| 1656 |
+
if total_loss is not None
|
| 1657 |
+
else output
|
| 1658 |
+
)
|
| 1659 |
+
|
| 1660 |
+
return RealmReaderOutput(
|
| 1661 |
+
loss=total_loss,
|
| 1662 |
+
retriever_loss=retriever_loss,
|
| 1663 |
+
reader_loss=reader_loss,
|
| 1664 |
+
retriever_correct=retriever_correct,
|
| 1665 |
+
reader_correct=reader_correct,
|
| 1666 |
+
block_idx=predicted_block_index,
|
| 1667 |
+
candidate=predicted_candidate,
|
| 1668 |
+
start_pos=predicted_start,
|
| 1669 |
+
end_pos=predicted_end,
|
| 1670 |
+
hidden_states=outputs.hidden_states,
|
| 1671 |
+
attentions=outputs.attentions,
|
| 1672 |
+
)
|
| 1673 |
+
|
| 1674 |
+
|
| 1675 |
+
REALM_FOR_OPEN_QA_DOCSTRING = r"""
|
| 1676 |
+
Args:
|
| 1677 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
| 1678 |
+
Indices of input sequence tokens in the vocabulary.
|
| 1679 |
+
|
| 1680 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1681 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1682 |
+
|
| 1683 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1684 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
| 1685 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1686 |
+
|
| 1687 |
+
- 1 for tokens that are **not masked**,
|
| 1688 |
+
- 0 for tokens that are **masked**.
|
| 1689 |
+
|
| 1690 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1691 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 1692 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 1693 |
+
1]`:
|
| 1694 |
+
|
| 1695 |
+
- 0 corresponds to a *sentence A* token,
|
| 1696 |
+
- 1 corresponds to a *sentence B* token (should not be used in this model by design).
|
| 1697 |
+
|
| 1698 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 1699 |
+
answer_ids (`list` of shape `(num_answers, answer_length)`, *optional*):
|
| 1700 |
+
Answer ids for computing the marginal log-likelihood loss. Indices should be in `[-1, 0, ...,
|
| 1701 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-1` are ignored (masked), the
|
| 1702 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1703 |
+
return_dict (`bool`, *optional*):
|
| 1704 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 1705 |
+
"""
|
| 1706 |
+
|
| 1707 |
+
|
| 1708 |
+
@add_start_docstrings(
|
| 1709 |
+
"`RealmForOpenQA` for end-to-end open domain question answering.",
|
| 1710 |
+
REALM_START_DOCSTRING,
|
| 1711 |
+
)
|
| 1712 |
+
class RealmForOpenQA(RealmPreTrainedModel):
|
| 1713 |
+
def __init__(self, config, retriever=None):
|
| 1714 |
+
super().__init__(config)
|
| 1715 |
+
self.embedder = RealmEmbedder(config)
|
| 1716 |
+
self.reader = RealmReader(config)
|
| 1717 |
+
self.register_buffer(
|
| 1718 |
+
"block_emb",
|
| 1719 |
+
torch.zeros(()).new_empty(
|
| 1720 |
+
size=(config.num_block_records, config.retriever_proj_size),
|
| 1721 |
+
dtype=torch.float32,
|
| 1722 |
+
device=torch.device("cpu"),
|
| 1723 |
+
),
|
| 1724 |
+
)
|
| 1725 |
+
self.retriever = retriever
|
| 1726 |
+
|
| 1727 |
+
self.post_init()
|
| 1728 |
+
|
| 1729 |
+
@property
|
| 1730 |
+
def searcher_beam_size(self):
|
| 1731 |
+
if self.training:
|
| 1732 |
+
return self.config.searcher_beam_size
|
| 1733 |
+
return self.config.reader_beam_size
|
| 1734 |
+
|
| 1735 |
+
def block_embedding_to(self, device):
|
| 1736 |
+
"""Send `self.block_emb` to a specific device.
|
| 1737 |
+
|
| 1738 |
+
Args:
|
| 1739 |
+
device (`str` or `torch.device`):
|
| 1740 |
+
The device to which `self.block_emb` will be sent.
|
| 1741 |
+
"""
|
| 1742 |
+
|
| 1743 |
+
self.block_emb = self.block_emb.to(device)
|
| 1744 |
+
|
| 1745 |
+
@add_start_docstrings_to_model_forward(REALM_FOR_OPEN_QA_DOCSTRING.format("1, sequence_length"))
|
| 1746 |
+
@replace_return_docstrings(output_type=RealmForOpenQAOutput, config_class=_CONFIG_FOR_DOC)
|
| 1747 |
+
def forward(
|
| 1748 |
+
self,
|
| 1749 |
+
input_ids: Optional[torch.LongTensor],
|
| 1750 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1751 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1752 |
+
answer_ids: Optional[torch.LongTensor] = None,
|
| 1753 |
+
return_dict: Optional[bool] = None,
|
| 1754 |
+
) -> Union[tuple, RealmForOpenQAOutput]:
|
| 1755 |
+
r"""
|
| 1756 |
+
Returns:
|
| 1757 |
+
|
| 1758 |
+
Example:
|
| 1759 |
+
|
| 1760 |
+
```python
|
| 1761 |
+
>>> import torch
|
| 1762 |
+
>>> from transformers import RealmForOpenQA, RealmRetriever, AutoTokenizer
|
| 1763 |
+
|
| 1764 |
+
>>> retriever = RealmRetriever.from_pretrained("google/realm-orqa-nq-openqa")
|
| 1765 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/realm-orqa-nq-openqa")
|
| 1766 |
+
>>> model = RealmForOpenQA.from_pretrained("google/realm-orqa-nq-openqa", retriever=retriever)
|
| 1767 |
+
|
| 1768 |
+
>>> question = "Who is the pioneer in modern computer science?"
|
| 1769 |
+
>>> question_ids = tokenizer([question], return_tensors="pt")
|
| 1770 |
+
>>> answer_ids = tokenizer(
|
| 1771 |
+
... ["alan mathison turing"],
|
| 1772 |
+
... add_special_tokens=False,
|
| 1773 |
+
... return_token_type_ids=False,
|
| 1774 |
+
... return_attention_mask=False,
|
| 1775 |
+
... ).input_ids
|
| 1776 |
+
|
| 1777 |
+
>>> reader_output, predicted_answer_ids = model(**question_ids, answer_ids=answer_ids, return_dict=False)
|
| 1778 |
+
>>> predicted_answer = tokenizer.decode(predicted_answer_ids)
|
| 1779 |
+
>>> loss = reader_output.loss
|
| 1780 |
+
```"""
|
| 1781 |
+
|
| 1782 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1783 |
+
|
| 1784 |
+
if input_ids is not None and input_ids.shape[0] != 1:
|
| 1785 |
+
raise ValueError("The batch_size of the inputs must be 1.")
|
| 1786 |
+
|
| 1787 |
+
question_outputs = self.embedder(
|
| 1788 |
+
input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask, return_dict=True
|
| 1789 |
+
)
|
| 1790 |
+
# [1, projection_size]
|
| 1791 |
+
question_projection = question_outputs[0]
|
| 1792 |
+
|
| 1793 |
+
# CPU computation starts.
|
| 1794 |
+
# [1, block_emb_size]
|
| 1795 |
+
batch_scores = torch.einsum("BD,QD->QB", self.block_emb, question_projection.to(self.block_emb.device))
|
| 1796 |
+
# [1, searcher_beam_size]
|
| 1797 |
+
_, retrieved_block_ids = torch.topk(batch_scores, k=self.searcher_beam_size, dim=-1)
|
| 1798 |
+
# [searcher_beam_size]
|
| 1799 |
+
retrieved_block_ids = retrieved_block_ids.squeeze()
|
| 1800 |
+
# [searcher_beam_size, projection_size]
|
| 1801 |
+
retrieved_block_emb = torch.index_select(self.block_emb, dim=0, index=retrieved_block_ids)
|
| 1802 |
+
# CPU computation ends.
|
| 1803 |
+
|
| 1804 |
+
# Retrieve possible answers
|
| 1805 |
+
has_answers, start_pos, end_pos, concat_inputs = self.retriever(
|
| 1806 |
+
retrieved_block_ids.cpu(), input_ids, answer_ids, max_length=self.config.reader_seq_len
|
| 1807 |
+
)
|
| 1808 |
+
|
| 1809 |
+
concat_inputs = concat_inputs.to(self.reader.device)
|
| 1810 |
+
block_mask = concat_inputs.special_tokens_mask.type(torch.bool).to(device=self.reader.device)
|
| 1811 |
+
block_mask.logical_not_().logical_and_(concat_inputs.token_type_ids.type(torch.bool))
|
| 1812 |
+
|
| 1813 |
+
if has_answers is not None:
|
| 1814 |
+
has_answers = torch.tensor(has_answers, dtype=torch.bool, device=self.reader.device)
|
| 1815 |
+
start_pos = torch.tensor(start_pos, dtype=torch.long, device=self.reader.device)
|
| 1816 |
+
end_pos = torch.tensor(end_pos, dtype=torch.long, device=self.reader.device)
|
| 1817 |
+
|
| 1818 |
+
# [searcher_beam_size]
|
| 1819 |
+
retrieved_logits = torch.einsum(
|
| 1820 |
+
"D,BD->B", question_projection.squeeze(), retrieved_block_emb.to(self.reader.device)
|
| 1821 |
+
)
|
| 1822 |
+
|
| 1823 |
+
reader_output = self.reader(
|
| 1824 |
+
input_ids=concat_inputs.input_ids[0 : self.config.reader_beam_size],
|
| 1825 |
+
attention_mask=concat_inputs.attention_mask[0 : self.config.reader_beam_size],
|
| 1826 |
+
token_type_ids=concat_inputs.token_type_ids[0 : self.config.reader_beam_size],
|
| 1827 |
+
relevance_score=retrieved_logits,
|
| 1828 |
+
block_mask=block_mask,
|
| 1829 |
+
has_answers=has_answers,
|
| 1830 |
+
start_positions=start_pos,
|
| 1831 |
+
end_positions=end_pos,
|
| 1832 |
+
return_dict=True,
|
| 1833 |
+
)
|
| 1834 |
+
|
| 1835 |
+
predicted_block = concat_inputs.input_ids[reader_output.block_idx]
|
| 1836 |
+
predicted_answer_ids = predicted_block[reader_output.start_pos : reader_output.end_pos + 1]
|
| 1837 |
+
|
| 1838 |
+
if not return_dict:
|
| 1839 |
+
return reader_output, predicted_answer_ids
|
| 1840 |
+
|
| 1841 |
+
return RealmForOpenQAOutput(
|
| 1842 |
+
reader_output=reader_output,
|
| 1843 |
+
predicted_answer_ids=predicted_answer_ids,
|
| 1844 |
+
)
|
| 1845 |
+
|
| 1846 |
+
|
| 1847 |
+
__all__ = [
|
| 1848 |
+
"RealmEmbedder",
|
| 1849 |
+
"RealmForOpenQA",
|
| 1850 |
+
"RealmKnowledgeAugEncoder",
|
| 1851 |
+
"RealmPreTrainedModel",
|
| 1852 |
+
"RealmReader",
|
| 1853 |
+
"RealmScorer",
|
| 1854 |
+
"load_tf_weights_in_realm",
|
| 1855 |
+
]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/realm/retrieval_realm.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The REALM 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 |
+
"""REALM Retriever model implementation."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from typing import Optional, Union
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
from huggingface_hub import hf_hub_download
|
| 22 |
+
|
| 23 |
+
from transformers import AutoTokenizer
|
| 24 |
+
|
| 25 |
+
from ....utils import logging, strtobool
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
_REALM_BLOCK_RECORDS_FILENAME = "block_records.npy"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def convert_tfrecord_to_np(block_records_path: str, num_block_records: int) -> np.ndarray:
|
| 35 |
+
import tensorflow.compat.v1 as tf
|
| 36 |
+
|
| 37 |
+
blocks_dataset = tf.data.TFRecordDataset(block_records_path, buffer_size=512 * 1024 * 1024)
|
| 38 |
+
blocks_dataset = blocks_dataset.batch(num_block_records, drop_remainder=True)
|
| 39 |
+
np_record = next(blocks_dataset.take(1).as_numpy_iterator())
|
| 40 |
+
|
| 41 |
+
return np_record
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ScaNNSearcher:
|
| 45 |
+
"""Note that ScaNNSearcher cannot currently be used within the model. In future versions, it might however be included."""
|
| 46 |
+
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
db,
|
| 50 |
+
num_neighbors,
|
| 51 |
+
dimensions_per_block=2,
|
| 52 |
+
num_leaves=1000,
|
| 53 |
+
num_leaves_to_search=100,
|
| 54 |
+
training_sample_size=100000,
|
| 55 |
+
):
|
| 56 |
+
"""Build scann searcher."""
|
| 57 |
+
|
| 58 |
+
from scann.scann_ops.py.scann_ops_pybind import builder as Builder
|
| 59 |
+
|
| 60 |
+
builder = Builder(db=db, num_neighbors=num_neighbors, distance_measure="dot_product")
|
| 61 |
+
builder = builder.tree(
|
| 62 |
+
num_leaves=num_leaves, num_leaves_to_search=num_leaves_to_search, training_sample_size=training_sample_size
|
| 63 |
+
)
|
| 64 |
+
builder = builder.score_ah(dimensions_per_block=dimensions_per_block)
|
| 65 |
+
|
| 66 |
+
self.searcher = builder.build()
|
| 67 |
+
|
| 68 |
+
def search_batched(self, question_projection):
|
| 69 |
+
retrieved_block_ids, _ = self.searcher.search_batched(question_projection.detach().cpu())
|
| 70 |
+
return retrieved_block_ids.astype("int64")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class RealmRetriever:
|
| 74 |
+
"""The retriever of REALM outputting the retrieved evidence block and whether the block has answers as well as answer
|
| 75 |
+
positions."
|
| 76 |
+
|
| 77 |
+
Parameters:
|
| 78 |
+
block_records (`np.ndarray`):
|
| 79 |
+
A numpy array which contains evidence texts.
|
| 80 |
+
tokenizer ([`RealmTokenizer`]):
|
| 81 |
+
The tokenizer to encode retrieved texts.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
def __init__(self, block_records, tokenizer):
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.block_records = block_records
|
| 87 |
+
self.tokenizer = tokenizer
|
| 88 |
+
|
| 89 |
+
def __call__(self, retrieved_block_ids, question_input_ids, answer_ids, max_length=None, return_tensors="pt"):
|
| 90 |
+
retrieved_blocks = np.take(self.block_records, indices=retrieved_block_ids, axis=0)
|
| 91 |
+
|
| 92 |
+
question = self.tokenizer.decode(question_input_ids[0], skip_special_tokens=True)
|
| 93 |
+
|
| 94 |
+
text = []
|
| 95 |
+
text_pair = []
|
| 96 |
+
for retrieved_block in retrieved_blocks:
|
| 97 |
+
text.append(question)
|
| 98 |
+
text_pair.append(retrieved_block.decode())
|
| 99 |
+
|
| 100 |
+
concat_inputs = self.tokenizer(
|
| 101 |
+
text, text_pair, padding=True, truncation=True, return_special_tokens_mask=True, max_length=max_length
|
| 102 |
+
)
|
| 103 |
+
concat_inputs_tensors = concat_inputs.convert_to_tensors(return_tensors)
|
| 104 |
+
|
| 105 |
+
if answer_ids is not None:
|
| 106 |
+
return self.block_has_answer(concat_inputs, answer_ids) + (concat_inputs_tensors,)
|
| 107 |
+
else:
|
| 108 |
+
return (None, None, None, concat_inputs_tensors)
|
| 109 |
+
|
| 110 |
+
@classmethod
|
| 111 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *init_inputs, **kwargs):
|
| 112 |
+
if os.path.isdir(pretrained_model_name_or_path):
|
| 113 |
+
block_records_path = os.path.join(pretrained_model_name_or_path, _REALM_BLOCK_RECORDS_FILENAME)
|
| 114 |
+
else:
|
| 115 |
+
block_records_path = hf_hub_download(
|
| 116 |
+
repo_id=pretrained_model_name_or_path, filename=_REALM_BLOCK_RECORDS_FILENAME, **kwargs
|
| 117 |
+
)
|
| 118 |
+
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
|
| 119 |
+
raise ValueError(
|
| 120 |
+
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is "
|
| 121 |
+
"potentially malicious. It's recommended to never unpickle data that could have come from an "
|
| 122 |
+
"untrusted source, or that could have been tampered with. If you already verified the pickle "
|
| 123 |
+
"data and decided to use it, you can set the environment variable "
|
| 124 |
+
"`TRUST_REMOTE_CODE` to `True` to allow it."
|
| 125 |
+
)
|
| 126 |
+
block_records = np.load(block_records_path, allow_pickle=True)
|
| 127 |
+
|
| 128 |
+
tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path, *init_inputs, **kwargs)
|
| 129 |
+
|
| 130 |
+
return cls(block_records, tokenizer)
|
| 131 |
+
|
| 132 |
+
def save_pretrained(self, save_directory):
|
| 133 |
+
# save block records
|
| 134 |
+
np.save(os.path.join(save_directory, _REALM_BLOCK_RECORDS_FILENAME), self.block_records)
|
| 135 |
+
# save tokenizer
|
| 136 |
+
self.tokenizer.save_pretrained(save_directory)
|
| 137 |
+
|
| 138 |
+
def block_has_answer(self, concat_inputs, answer_ids):
|
| 139 |
+
"""check if retrieved_blocks has answers."""
|
| 140 |
+
has_answers = []
|
| 141 |
+
start_pos = []
|
| 142 |
+
end_pos = []
|
| 143 |
+
max_answers = 0
|
| 144 |
+
|
| 145 |
+
for input_id in concat_inputs.input_ids:
|
| 146 |
+
input_id_list = input_id.tolist()
|
| 147 |
+
# Check answers between two [SEP] tokens
|
| 148 |
+
first_sep_idx = input_id_list.index(self.tokenizer.sep_token_id)
|
| 149 |
+
second_sep_idx = first_sep_idx + 1 + input_id_list[first_sep_idx + 1 :].index(self.tokenizer.sep_token_id)
|
| 150 |
+
|
| 151 |
+
start_pos.append([])
|
| 152 |
+
end_pos.append([])
|
| 153 |
+
for answer in answer_ids:
|
| 154 |
+
for idx in range(first_sep_idx + 1, second_sep_idx):
|
| 155 |
+
if answer[0] == input_id_list[idx]:
|
| 156 |
+
if input_id_list[idx : idx + len(answer)] == answer:
|
| 157 |
+
start_pos[-1].append(idx)
|
| 158 |
+
end_pos[-1].append(idx + len(answer) - 1)
|
| 159 |
+
|
| 160 |
+
if len(start_pos[-1]) == 0:
|
| 161 |
+
has_answers.append(False)
|
| 162 |
+
else:
|
| 163 |
+
has_answers.append(True)
|
| 164 |
+
if len(start_pos[-1]) > max_answers:
|
| 165 |
+
max_answers = len(start_pos[-1])
|
| 166 |
+
|
| 167 |
+
# Pad -1 to max_answers
|
| 168 |
+
for start_pos_, end_pos_ in zip(start_pos, end_pos):
|
| 169 |
+
if len(start_pos_) < max_answers:
|
| 170 |
+
padded = [-1] * (max_answers - len(start_pos_))
|
| 171 |
+
start_pos_ += padded
|
| 172 |
+
end_pos_ += padded
|
| 173 |
+
return has_answers, start_pos, end_pos
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
__all__ = ["RealmRetriever"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/realm/tokenization_realm.py
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The REALM 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 REALM."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
import os
|
| 19 |
+
import unicodedata
|
| 20 |
+
from typing import Optional
|
| 21 |
+
|
| 22 |
+
from ....tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
|
| 23 |
+
from ....tokenization_utils_base import BatchEncoding
|
| 24 |
+
from ....utils import PaddingStrategy, logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def load_vocab(vocab_file):
|
| 33 |
+
"""Loads a vocabulary file into a dictionary."""
|
| 34 |
+
vocab = collections.OrderedDict()
|
| 35 |
+
with open(vocab_file, "r", encoding="utf-8") as reader:
|
| 36 |
+
tokens = reader.readlines()
|
| 37 |
+
for index, token in enumerate(tokens):
|
| 38 |
+
token = token.rstrip("\n")
|
| 39 |
+
vocab[token] = index
|
| 40 |
+
return vocab
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def whitespace_tokenize(text):
|
| 44 |
+
"""Runs basic whitespace cleaning and splitting on a piece of text."""
|
| 45 |
+
text = text.strip()
|
| 46 |
+
if not text:
|
| 47 |
+
return []
|
| 48 |
+
tokens = text.split()
|
| 49 |
+
return tokens
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class RealmTokenizer(PreTrainedTokenizer):
|
| 53 |
+
r"""
|
| 54 |
+
Construct a REALM tokenizer.
|
| 55 |
+
|
| 56 |
+
[`RealmTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation splitting and
|
| 57 |
+
wordpiece.
|
| 58 |
+
|
| 59 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 60 |
+
this superclass for more information regarding those methods.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
vocab_file (`str`):
|
| 64 |
+
File containing the vocabulary.
|
| 65 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 66 |
+
Whether or not to lowercase the input when tokenizing.
|
| 67 |
+
do_basic_tokenize (`bool`, *optional*, defaults to `True`):
|
| 68 |
+
Whether or not to do basic tokenization before WordPiece.
|
| 69 |
+
never_split (`Iterable`, *optional*):
|
| 70 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
| 71 |
+
`do_basic_tokenize=True`
|
| 72 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 73 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 74 |
+
token instead.
|
| 75 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 76 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 77 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 78 |
+
token of a sequence built with special tokens.
|
| 79 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 80 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 81 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 82 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 83 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 84 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 85 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 86 |
+
modeling. This is the token which the model will try to predict.
|
| 87 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 88 |
+
Whether or not to tokenize Chinese characters.
|
| 89 |
+
|
| 90 |
+
This should likely be deactivated for Japanese (see this
|
| 91 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 92 |
+
strip_accents (`bool`, *optional*):
|
| 93 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 94 |
+
value for `lowercase` (as in the original BERT).
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
vocab_file,
|
| 102 |
+
do_lower_case=True,
|
| 103 |
+
do_basic_tokenize=True,
|
| 104 |
+
never_split=None,
|
| 105 |
+
unk_token="[UNK]",
|
| 106 |
+
sep_token="[SEP]",
|
| 107 |
+
pad_token="[PAD]",
|
| 108 |
+
cls_token="[CLS]",
|
| 109 |
+
mask_token="[MASK]",
|
| 110 |
+
tokenize_chinese_chars=True,
|
| 111 |
+
strip_accents=None,
|
| 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 = RealmTokenizer.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 |
+
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
|
| 130 |
+
super().__init__(
|
| 131 |
+
do_lower_case=do_lower_case,
|
| 132 |
+
do_basic_tokenize=do_basic_tokenize,
|
| 133 |
+
never_split=never_split,
|
| 134 |
+
unk_token=unk_token,
|
| 135 |
+
sep_token=sep_token,
|
| 136 |
+
pad_token=pad_token,
|
| 137 |
+
cls_token=cls_token,
|
| 138 |
+
mask_token=mask_token,
|
| 139 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 140 |
+
strip_accents=strip_accents,
|
| 141 |
+
**kwargs,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
@property
|
| 145 |
+
def do_lower_case(self):
|
| 146 |
+
return self.basic_tokenizer.do_lower_case
|
| 147 |
+
|
| 148 |
+
@property
|
| 149 |
+
def vocab_size(self):
|
| 150 |
+
return len(self.vocab)
|
| 151 |
+
|
| 152 |
+
def get_vocab(self):
|
| 153 |
+
return dict(self.vocab, **self.added_tokens_encoder)
|
| 154 |
+
|
| 155 |
+
def _tokenize(self, text):
|
| 156 |
+
split_tokens = []
|
| 157 |
+
if self.do_basic_tokenize:
|
| 158 |
+
for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens):
|
| 159 |
+
# If the token is part of the never_split set
|
| 160 |
+
if token in self.basic_tokenizer.never_split:
|
| 161 |
+
split_tokens.append(token)
|
| 162 |
+
else:
|
| 163 |
+
split_tokens += self.wordpiece_tokenizer.tokenize(token)
|
| 164 |
+
else:
|
| 165 |
+
split_tokens = self.wordpiece_tokenizer.tokenize(text)
|
| 166 |
+
return split_tokens
|
| 167 |
+
|
| 168 |
+
def _convert_token_to_id(self, token):
|
| 169 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 170 |
+
return self.vocab.get(token, self.vocab.get(self.unk_token))
|
| 171 |
+
|
| 172 |
+
def _convert_id_to_token(self, index):
|
| 173 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 174 |
+
return self.ids_to_tokens.get(index, self.unk_token)
|
| 175 |
+
|
| 176 |
+
def convert_tokens_to_string(self, tokens):
|
| 177 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 178 |
+
out_string = " ".join(tokens).replace(" ##", "").strip()
|
| 179 |
+
return out_string
|
| 180 |
+
|
| 181 |
+
def batch_encode_candidates(self, text, **kwargs):
|
| 182 |
+
r"""
|
| 183 |
+
Encode a batch of text or text pair. This method is similar to regular __call__ method but has the following
|
| 184 |
+
differences:
|
| 185 |
+
|
| 186 |
+
1. Handle additional num_candidate axis. (batch_size, num_candidates, text)
|
| 187 |
+
2. Always pad the sequences to *max_length*.
|
| 188 |
+
3. Must specify *max_length* in order to stack packs of candidates into a batch.
|
| 189 |
+
|
| 190 |
+
- single sequence: `[CLS] X [SEP]`
|
| 191 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
text (`List[List[str]]`):
|
| 195 |
+
The batch of sequences to be encoded. Each sequence must be in this format: (batch_size,
|
| 196 |
+
num_candidates, text).
|
| 197 |
+
text_pair (`List[List[str]]`, *optional*):
|
| 198 |
+
The batch of sequences to be encoded. Each sequence must be in this format: (batch_size,
|
| 199 |
+
num_candidates, text).
|
| 200 |
+
**kwargs:
|
| 201 |
+
Keyword arguments of the __call__ method.
|
| 202 |
+
|
| 203 |
+
Returns:
|
| 204 |
+
[`BatchEncoding`]: Encoded text or text pair.
|
| 205 |
+
|
| 206 |
+
Example:
|
| 207 |
+
|
| 208 |
+
```python
|
| 209 |
+
>>> from transformers import RealmTokenizer
|
| 210 |
+
|
| 211 |
+
>>> # batch_size = 2, num_candidates = 2
|
| 212 |
+
>>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]]
|
| 213 |
+
|
| 214 |
+
>>> tokenizer = RealmTokenizer.from_pretrained("google/realm-cc-news-pretrained-encoder")
|
| 215 |
+
>>> tokenized_text = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt")
|
| 216 |
+
```"""
|
| 217 |
+
|
| 218 |
+
# Always using a fixed sequence length to encode in order to stack candidates into a batch.
|
| 219 |
+
kwargs["padding"] = PaddingStrategy.MAX_LENGTH
|
| 220 |
+
|
| 221 |
+
batch_text = text
|
| 222 |
+
batch_text_pair = kwargs.pop("text_pair", None)
|
| 223 |
+
return_tensors = kwargs.pop("return_tensors", None)
|
| 224 |
+
|
| 225 |
+
output_data = {
|
| 226 |
+
"input_ids": [],
|
| 227 |
+
"attention_mask": [],
|
| 228 |
+
"token_type_ids": [],
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
for idx, candidate_text in enumerate(batch_text):
|
| 232 |
+
if batch_text_pair is not None:
|
| 233 |
+
candidate_text_pair = batch_text_pair[idx]
|
| 234 |
+
else:
|
| 235 |
+
candidate_text_pair = None
|
| 236 |
+
|
| 237 |
+
encoded_candidates = super().__call__(candidate_text, candidate_text_pair, return_tensors=None, **kwargs)
|
| 238 |
+
|
| 239 |
+
encoded_input_ids = encoded_candidates.get("input_ids")
|
| 240 |
+
encoded_attention_mask = encoded_candidates.get("attention_mask")
|
| 241 |
+
encoded_token_type_ids = encoded_candidates.get("token_type_ids")
|
| 242 |
+
|
| 243 |
+
if encoded_input_ids is not None:
|
| 244 |
+
output_data["input_ids"].append(encoded_input_ids)
|
| 245 |
+
if encoded_attention_mask is not None:
|
| 246 |
+
output_data["attention_mask"].append(encoded_attention_mask)
|
| 247 |
+
if encoded_token_type_ids is not None:
|
| 248 |
+
output_data["token_type_ids"].append(encoded_token_type_ids)
|
| 249 |
+
|
| 250 |
+
output_data = {key: item for key, item in output_data.items() if len(item) != 0}
|
| 251 |
+
|
| 252 |
+
return BatchEncoding(output_data, tensor_type=return_tensors)
|
| 253 |
+
|
| 254 |
+
def build_inputs_with_special_tokens(
|
| 255 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 256 |
+
) -> list[int]:
|
| 257 |
+
"""
|
| 258 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 259 |
+
adding special tokens. A REALM sequence has the following format:
|
| 260 |
+
|
| 261 |
+
- single sequence: `[CLS] X [SEP]`
|
| 262 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 263 |
+
|
| 264 |
+
Args:
|
| 265 |
+
token_ids_0 (`List[int]`):
|
| 266 |
+
List of IDs to which the special tokens will be added.
|
| 267 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 268 |
+
Optional second list of IDs for sequence pairs.
|
| 269 |
+
|
| 270 |
+
Returns:
|
| 271 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 272 |
+
"""
|
| 273 |
+
if token_ids_1 is None:
|
| 274 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 275 |
+
cls = [self.cls_token_id]
|
| 276 |
+
sep = [self.sep_token_id]
|
| 277 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 278 |
+
|
| 279 |
+
def get_special_tokens_mask(
|
| 280 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
|
| 281 |
+
) -> list[int]:
|
| 282 |
+
"""
|
| 283 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 284 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 285 |
+
|
| 286 |
+
Args:
|
| 287 |
+
token_ids_0 (`List[int]`):
|
| 288 |
+
List of IDs.
|
| 289 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 290 |
+
Optional second list of IDs for sequence pairs.
|
| 291 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 292 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 293 |
+
|
| 294 |
+
Returns:
|
| 295 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
if already_has_special_tokens:
|
| 299 |
+
return super().get_special_tokens_mask(
|
| 300 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
if token_ids_1 is not None:
|
| 304 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 305 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 306 |
+
|
| 307 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 308 |
+
index = 0
|
| 309 |
+
if os.path.isdir(save_directory):
|
| 310 |
+
vocab_file = os.path.join(
|
| 311 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 312 |
+
)
|
| 313 |
+
else:
|
| 314 |
+
vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
|
| 315 |
+
with open(vocab_file, "w", encoding="utf-8") as writer:
|
| 316 |
+
for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
|
| 317 |
+
if index != token_index:
|
| 318 |
+
logger.warning(
|
| 319 |
+
f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
|
| 320 |
+
" Please check that the vocabulary is not corrupted!"
|
| 321 |
+
)
|
| 322 |
+
index = token_index
|
| 323 |
+
writer.write(token + "\n")
|
| 324 |
+
index += 1
|
| 325 |
+
return (vocab_file,)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class BasicTokenizer:
|
| 329 |
+
"""
|
| 330 |
+
Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 334 |
+
Whether or not to lowercase the input when tokenizing.
|
| 335 |
+
never_split (`Iterable`, *optional*):
|
| 336 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
| 337 |
+
`do_basic_tokenize=True`
|
| 338 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 339 |
+
Whether or not to tokenize Chinese characters.
|
| 340 |
+
|
| 341 |
+
This should likely be deactivated for Japanese (see this
|
| 342 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 343 |
+
strip_accents (`bool`, *optional*):
|
| 344 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 345 |
+
value for `lowercase` (as in the original BERT).
|
| 346 |
+
"""
|
| 347 |
+
|
| 348 |
+
def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True, strip_accents=None):
|
| 349 |
+
if never_split is None:
|
| 350 |
+
never_split = []
|
| 351 |
+
self.do_lower_case = do_lower_case
|
| 352 |
+
self.never_split = set(never_split)
|
| 353 |
+
self.tokenize_chinese_chars = tokenize_chinese_chars
|
| 354 |
+
self.strip_accents = strip_accents
|
| 355 |
+
|
| 356 |
+
def tokenize(self, text, never_split=None):
|
| 357 |
+
"""
|
| 358 |
+
Basic Tokenization of a piece of text. Split on "white spaces" only, for sub-word tokenization, see
|
| 359 |
+
WordPieceTokenizer.
|
| 360 |
+
|
| 361 |
+
Args:
|
| 362 |
+
never_split (`List[str]`, *optional*)
|
| 363 |
+
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
|
| 364 |
+
[`PreTrainedTokenizer.tokenize`]) List of token not to split.
|
| 365 |
+
"""
|
| 366 |
+
# union() returns a new set by concatenating the two sets.
|
| 367 |
+
never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
|
| 368 |
+
text = self._clean_text(text)
|
| 369 |
+
|
| 370 |
+
# This was added on November 1st, 2018 for the multilingual and Chinese
|
| 371 |
+
# models. This is also applied to the English models now, but it doesn't
|
| 372 |
+
# matter since the English models were not trained on any Chinese data
|
| 373 |
+
# and generally don't have any Chinese data in them (there are Chinese
|
| 374 |
+
# characters in the vocabulary because Wikipedia does have some Chinese
|
| 375 |
+
# words in the English Wikipedia.).
|
| 376 |
+
if self.tokenize_chinese_chars:
|
| 377 |
+
text = self._tokenize_chinese_chars(text)
|
| 378 |
+
orig_tokens = whitespace_tokenize(text)
|
| 379 |
+
split_tokens = []
|
| 380 |
+
for token in orig_tokens:
|
| 381 |
+
if token not in never_split:
|
| 382 |
+
if self.do_lower_case:
|
| 383 |
+
token = token.lower()
|
| 384 |
+
if self.strip_accents is not False:
|
| 385 |
+
token = self._run_strip_accents(token)
|
| 386 |
+
elif self.strip_accents:
|
| 387 |
+
token = self._run_strip_accents(token)
|
| 388 |
+
split_tokens.extend(self._run_split_on_punc(token, never_split))
|
| 389 |
+
|
| 390 |
+
output_tokens = whitespace_tokenize(" ".join(split_tokens))
|
| 391 |
+
return output_tokens
|
| 392 |
+
|
| 393 |
+
def _run_strip_accents(self, text):
|
| 394 |
+
"""Strips accents from a piece of text."""
|
| 395 |
+
text = unicodedata.normalize("NFD", text)
|
| 396 |
+
output = []
|
| 397 |
+
for char in text:
|
| 398 |
+
cat = unicodedata.category(char)
|
| 399 |
+
if cat == "Mn":
|
| 400 |
+
continue
|
| 401 |
+
output.append(char)
|
| 402 |
+
return "".join(output)
|
| 403 |
+
|
| 404 |
+
def _run_split_on_punc(self, text, never_split=None):
|
| 405 |
+
"""Splits punctuation on a piece of text."""
|
| 406 |
+
if never_split is not None and text in never_split:
|
| 407 |
+
return [text]
|
| 408 |
+
chars = list(text)
|
| 409 |
+
i = 0
|
| 410 |
+
start_new_word = True
|
| 411 |
+
output = []
|
| 412 |
+
while i < len(chars):
|
| 413 |
+
char = chars[i]
|
| 414 |
+
if _is_punctuation(char):
|
| 415 |
+
output.append([char])
|
| 416 |
+
start_new_word = True
|
| 417 |
+
else:
|
| 418 |
+
if start_new_word:
|
| 419 |
+
output.append([])
|
| 420 |
+
start_new_word = False
|
| 421 |
+
output[-1].append(char)
|
| 422 |
+
i += 1
|
| 423 |
+
|
| 424 |
+
return ["".join(x) for x in output]
|
| 425 |
+
|
| 426 |
+
def _tokenize_chinese_chars(self, text):
|
| 427 |
+
"""Adds whitespace around any CJK character."""
|
| 428 |
+
output = []
|
| 429 |
+
for char in text:
|
| 430 |
+
cp = ord(char)
|
| 431 |
+
if self._is_chinese_char(cp):
|
| 432 |
+
output.append(" ")
|
| 433 |
+
output.append(char)
|
| 434 |
+
output.append(" ")
|
| 435 |
+
else:
|
| 436 |
+
output.append(char)
|
| 437 |
+
return "".join(output)
|
| 438 |
+
|
| 439 |
+
def _is_chinese_char(self, cp):
|
| 440 |
+
"""Checks whether CP is the codepoint of a CJK character."""
|
| 441 |
+
# This defines a "chinese character" as anything in the CJK Unicode block:
|
| 442 |
+
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
|
| 443 |
+
#
|
| 444 |
+
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
|
| 445 |
+
# despite its name. The modern Korean Hangul alphabet is a different block,
|
| 446 |
+
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
|
| 447 |
+
# space-separated words, so they are not treated specially and handled
|
| 448 |
+
# like the all of the other languages.
|
| 449 |
+
if (
|
| 450 |
+
(cp >= 0x4E00 and cp <= 0x9FFF)
|
| 451 |
+
or (cp >= 0x3400 and cp <= 0x4DBF)
|
| 452 |
+
or (cp >= 0x20000 and cp <= 0x2A6DF)
|
| 453 |
+
or (cp >= 0x2A700 and cp <= 0x2B73F)
|
| 454 |
+
or (cp >= 0x2B740 and cp <= 0x2B81F)
|
| 455 |
+
or (cp >= 0x2B820 and cp <= 0x2CEAF)
|
| 456 |
+
or (cp >= 0xF900 and cp <= 0xFAFF)
|
| 457 |
+
or (cp >= 0x2F800 and cp <= 0x2FA1F)
|
| 458 |
+
):
|
| 459 |
+
return True
|
| 460 |
+
|
| 461 |
+
return False
|
| 462 |
+
|
| 463 |
+
def _clean_text(self, text):
|
| 464 |
+
"""Performs invalid character removal and whitespace cleanup on text."""
|
| 465 |
+
output = []
|
| 466 |
+
for char in text:
|
| 467 |
+
cp = ord(char)
|
| 468 |
+
if cp == 0 or cp == 0xFFFD or _is_control(char):
|
| 469 |
+
continue
|
| 470 |
+
if _is_whitespace(char):
|
| 471 |
+
output.append(" ")
|
| 472 |
+
else:
|
| 473 |
+
output.append(char)
|
| 474 |
+
return "".join(output)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
class WordpieceTokenizer:
|
| 478 |
+
"""Runs WordPiece tokenization."""
|
| 479 |
+
|
| 480 |
+
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
|
| 481 |
+
self.vocab = vocab
|
| 482 |
+
self.unk_token = unk_token
|
| 483 |
+
self.max_input_chars_per_word = max_input_chars_per_word
|
| 484 |
+
|
| 485 |
+
def tokenize(self, text):
|
| 486 |
+
"""
|
| 487 |
+
Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
|
| 488 |
+
tokenization using the given vocabulary.
|
| 489 |
+
|
| 490 |
+
For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
|
| 491 |
+
|
| 492 |
+
Args:
|
| 493 |
+
text: A single token or whitespace separated tokens. This should have
|
| 494 |
+
already been passed through *BasicTokenizer*.
|
| 495 |
+
|
| 496 |
+
Returns:
|
| 497 |
+
A list of wordpiece tokens.
|
| 498 |
+
"""
|
| 499 |
+
|
| 500 |
+
output_tokens = []
|
| 501 |
+
for token in whitespace_tokenize(text):
|
| 502 |
+
chars = list(token)
|
| 503 |
+
if len(chars) > self.max_input_chars_per_word:
|
| 504 |
+
output_tokens.append(self.unk_token)
|
| 505 |
+
continue
|
| 506 |
+
|
| 507 |
+
is_bad = False
|
| 508 |
+
start = 0
|
| 509 |
+
sub_tokens = []
|
| 510 |
+
while start < len(chars):
|
| 511 |
+
end = len(chars)
|
| 512 |
+
cur_substr = None
|
| 513 |
+
while start < end:
|
| 514 |
+
substr = "".join(chars[start:end])
|
| 515 |
+
if start > 0:
|
| 516 |
+
substr = "##" + substr
|
| 517 |
+
if substr in self.vocab:
|
| 518 |
+
cur_substr = substr
|
| 519 |
+
break
|
| 520 |
+
end -= 1
|
| 521 |
+
if cur_substr is None:
|
| 522 |
+
is_bad = True
|
| 523 |
+
break
|
| 524 |
+
sub_tokens.append(cur_substr)
|
| 525 |
+
start = end
|
| 526 |
+
|
| 527 |
+
if is_bad:
|
| 528 |
+
output_tokens.append(self.unk_token)
|
| 529 |
+
else:
|
| 530 |
+
output_tokens.extend(sub_tokens)
|
| 531 |
+
return output_tokens
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
__all__ = ["RealmTokenizer"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/realm/tokenization_realm_fast.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The REALM 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 REALM."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
from tokenizers import normalizers
|
| 21 |
+
|
| 22 |
+
from ....tokenization_utils_base import BatchEncoding
|
| 23 |
+
from ....tokenization_utils_fast import PreTrainedTokenizerFast
|
| 24 |
+
from ....utils import PaddingStrategy, logging
|
| 25 |
+
from .tokenization_realm import RealmTokenizer
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class RealmTokenizerFast(PreTrainedTokenizerFast):
|
| 34 |
+
r"""
|
| 35 |
+
Construct a "fast" REALM tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
|
| 36 |
+
|
| 37 |
+
[`RealmTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization: punctuation
|
| 38 |
+
splitting and wordpiece.
|
| 39 |
+
|
| 40 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
| 41 |
+
refer to this superclass for more information regarding those methods.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
vocab_file (`str`):
|
| 45 |
+
File containing the vocabulary.
|
| 46 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 47 |
+
Whether or not to lowercase the input when tokenizing.
|
| 48 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 49 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 50 |
+
token instead.
|
| 51 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 52 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 53 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 54 |
+
token of a sequence built with special tokens.
|
| 55 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 56 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 57 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 58 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 59 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 60 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 61 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 62 |
+
modeling. This is the token which the model will try to predict.
|
| 63 |
+
clean_text (`bool`, *optional*, defaults to `True`):
|
| 64 |
+
Whether or not to clean the text before tokenization by removing any control characters and replacing all
|
| 65 |
+
whitespaces by the classic one.
|
| 66 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
|
| 68 |
+
issue](https://github.com/huggingface/transformers/issues/328)).
|
| 69 |
+
strip_accents (`bool`, *optional*):
|
| 70 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 71 |
+
value for `lowercase` (as in the original BERT).
|
| 72 |
+
wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
|
| 73 |
+
The prefix for subwords.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 77 |
+
slow_tokenizer_class = RealmTokenizer
|
| 78 |
+
|
| 79 |
+
def __init__(
|
| 80 |
+
self,
|
| 81 |
+
vocab_file=None,
|
| 82 |
+
tokenizer_file=None,
|
| 83 |
+
do_lower_case=True,
|
| 84 |
+
unk_token="[UNK]",
|
| 85 |
+
sep_token="[SEP]",
|
| 86 |
+
pad_token="[PAD]",
|
| 87 |
+
cls_token="[CLS]",
|
| 88 |
+
mask_token="[MASK]",
|
| 89 |
+
tokenize_chinese_chars=True,
|
| 90 |
+
strip_accents=None,
|
| 91 |
+
**kwargs,
|
| 92 |
+
):
|
| 93 |
+
super().__init__(
|
| 94 |
+
vocab_file,
|
| 95 |
+
tokenizer_file=tokenizer_file,
|
| 96 |
+
do_lower_case=do_lower_case,
|
| 97 |
+
unk_token=unk_token,
|
| 98 |
+
sep_token=sep_token,
|
| 99 |
+
pad_token=pad_token,
|
| 100 |
+
cls_token=cls_token,
|
| 101 |
+
mask_token=mask_token,
|
| 102 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 103 |
+
strip_accents=strip_accents,
|
| 104 |
+
**kwargs,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
|
| 108 |
+
if (
|
| 109 |
+
normalizer_state.get("lowercase", do_lower_case) != do_lower_case
|
| 110 |
+
or normalizer_state.get("strip_accents", strip_accents) != strip_accents
|
| 111 |
+
or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
|
| 112 |
+
):
|
| 113 |
+
normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
|
| 114 |
+
normalizer_state["lowercase"] = do_lower_case
|
| 115 |
+
normalizer_state["strip_accents"] = strip_accents
|
| 116 |
+
normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
|
| 117 |
+
self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
|
| 118 |
+
|
| 119 |
+
self.do_lower_case = do_lower_case
|
| 120 |
+
|
| 121 |
+
def batch_encode_candidates(self, text, **kwargs):
|
| 122 |
+
r"""
|
| 123 |
+
Encode a batch of text or text pair. This method is similar to regular __call__ method but has the following
|
| 124 |
+
differences:
|
| 125 |
+
|
| 126 |
+
1. Handle additional num_candidate axis. (batch_size, num_candidates, text)
|
| 127 |
+
2. Always pad the sequences to *max_length*.
|
| 128 |
+
3. Must specify *max_length* in order to stack packs of candidates into a batch.
|
| 129 |
+
|
| 130 |
+
- single sequence: `[CLS] X [SEP]`
|
| 131 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
text (`List[List[str]]`):
|
| 135 |
+
The batch of sequences to be encoded. Each sequence must be in this format: (batch_size,
|
| 136 |
+
num_candidates, text).
|
| 137 |
+
text_pair (`List[List[str]]`, *optional*):
|
| 138 |
+
The batch of sequences to be encoded. Each sequence must be in this format: (batch_size,
|
| 139 |
+
num_candidates, text).
|
| 140 |
+
**kwargs:
|
| 141 |
+
Keyword arguments of the __call__ method.
|
| 142 |
+
|
| 143 |
+
Returns:
|
| 144 |
+
[`BatchEncoding`]: Encoded text or text pair.
|
| 145 |
+
|
| 146 |
+
Example:
|
| 147 |
+
|
| 148 |
+
```python
|
| 149 |
+
>>> from transformers import RealmTokenizerFast
|
| 150 |
+
|
| 151 |
+
>>> # batch_size = 2, num_candidates = 2
|
| 152 |
+
>>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]]
|
| 153 |
+
|
| 154 |
+
>>> tokenizer = RealmTokenizerFast.from_pretrained("google/realm-cc-news-pretrained-encoder")
|
| 155 |
+
>>> tokenized_text = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt")
|
| 156 |
+
```"""
|
| 157 |
+
|
| 158 |
+
# Always using a fixed sequence length to encode in order to stack candidates into a batch.
|
| 159 |
+
kwargs["padding"] = PaddingStrategy.MAX_LENGTH
|
| 160 |
+
|
| 161 |
+
batch_text = text
|
| 162 |
+
batch_text_pair = kwargs.pop("text_pair", None)
|
| 163 |
+
return_tensors = kwargs.pop("return_tensors", None)
|
| 164 |
+
|
| 165 |
+
output_data = {
|
| 166 |
+
"input_ids": [],
|
| 167 |
+
"attention_mask": [],
|
| 168 |
+
"token_type_ids": [],
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
for idx, candidate_text in enumerate(batch_text):
|
| 172 |
+
if batch_text_pair is not None:
|
| 173 |
+
candidate_text_pair = batch_text_pair[idx]
|
| 174 |
+
else:
|
| 175 |
+
candidate_text_pair = None
|
| 176 |
+
|
| 177 |
+
encoded_candidates = super().__call__(candidate_text, candidate_text_pair, return_tensors=None, **kwargs)
|
| 178 |
+
|
| 179 |
+
encoded_input_ids = encoded_candidates.get("input_ids")
|
| 180 |
+
encoded_attention_mask = encoded_candidates.get("attention_mask")
|
| 181 |
+
encoded_token_type_ids = encoded_candidates.get("token_type_ids")
|
| 182 |
+
|
| 183 |
+
if encoded_input_ids is not None:
|
| 184 |
+
output_data["input_ids"].append(encoded_input_ids)
|
| 185 |
+
if encoded_attention_mask is not None:
|
| 186 |
+
output_data["attention_mask"].append(encoded_attention_mask)
|
| 187 |
+
if encoded_token_type_ids is not None:
|
| 188 |
+
output_data["token_type_ids"].append(encoded_token_type_ids)
|
| 189 |
+
|
| 190 |
+
output_data = {key: item for key, item in output_data.items() if len(item) != 0}
|
| 191 |
+
|
| 192 |
+
return BatchEncoding(output_data, tensor_type=return_tensors)
|
| 193 |
+
|
| 194 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
| 195 |
+
"""
|
| 196 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 197 |
+
adding special tokens. A REALM sequence has the following format:
|
| 198 |
+
|
| 199 |
+
- single sequence: `[CLS] X [SEP]`
|
| 200 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
token_ids_0 (`List[int]`):
|
| 204 |
+
List of IDs to which the special tokens will be added.
|
| 205 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 206 |
+
Optional second list of IDs for sequence pairs.
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 210 |
+
"""
|
| 211 |
+
output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 212 |
+
|
| 213 |
+
if token_ids_1 is not None:
|
| 214 |
+
output += token_ids_1 + [self.sep_token_id]
|
| 215 |
+
|
| 216 |
+
return output
|
| 217 |
+
|
| 218 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 219 |
+
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
|
| 220 |
+
return tuple(files)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
__all__ = ["RealmTokenizerFast"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/retribert/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ....utils import _LazyModule
|
| 17 |
+
from ....utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_retribert import *
|
| 22 |
+
from .modeling_retribert import *
|
| 23 |
+
from .tokenization_retribert import *
|
| 24 |
+
from .tokenization_retribert_fast import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/retribert/configuration_retribert.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
|
| 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 |
+
"""RetriBERT 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 RetriBertConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`RetriBertModel`]. It is used to instantiate a
|
| 27 |
+
RetriBertModel model according to the specified arguments, defining the model architecture. Instantiating a
|
| 28 |
+
configuration with the defaults will yield a similar configuration to that of the RetriBERT
|
| 29 |
+
[yjernite/retribert-base-uncased](https://huggingface.co/yjernite/retribert-base-uncased) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 37 |
+
Vocabulary size of the RetriBERT model. Defines the number of different tokens that can be represented by
|
| 38 |
+
the `inputs_ids` passed when calling [`RetriBertModel`]
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 40 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 41 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 42 |
+
Number of hidden layers in the Transformer encoder.
|
| 43 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 44 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 45 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 46 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 47 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 48 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 49 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 50 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 51 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 52 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 53 |
+
The dropout ratio for the attention probabilities.
|
| 54 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 55 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 56 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 57 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 58 |
+
The vocabulary size of the *token_type_ids* passed into [`BertModel`].
|
| 59 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 60 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 61 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 62 |
+
The epsilon used by the layer normalization layers.
|
| 63 |
+
share_encoders (`bool`, *optional*, defaults to `True`):
|
| 64 |
+
Whether or not to use the same Bert-type encoder for the queries and document
|
| 65 |
+
projection_dim (`int`, *optional*, defaults to 128):
|
| 66 |
+
Final dimension of the query and document representation after projection
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
model_type = "retribert"
|
| 70 |
+
|
| 71 |
+
def __init__(
|
| 72 |
+
self,
|
| 73 |
+
vocab_size=30522,
|
| 74 |
+
hidden_size=768,
|
| 75 |
+
num_hidden_layers=8,
|
| 76 |
+
num_attention_heads=12,
|
| 77 |
+
intermediate_size=3072,
|
| 78 |
+
hidden_act="gelu",
|
| 79 |
+
hidden_dropout_prob=0.1,
|
| 80 |
+
attention_probs_dropout_prob=0.1,
|
| 81 |
+
max_position_embeddings=512,
|
| 82 |
+
type_vocab_size=2,
|
| 83 |
+
initializer_range=0.02,
|
| 84 |
+
layer_norm_eps=1e-12,
|
| 85 |
+
share_encoders=True,
|
| 86 |
+
projection_dim=128,
|
| 87 |
+
pad_token_id=0,
|
| 88 |
+
**kwargs,
|
| 89 |
+
):
|
| 90 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
| 91 |
+
|
| 92 |
+
self.vocab_size = vocab_size
|
| 93 |
+
self.hidden_size = hidden_size
|
| 94 |
+
self.num_hidden_layers = num_hidden_layers
|
| 95 |
+
self.num_attention_heads = num_attention_heads
|
| 96 |
+
self.hidden_act = hidden_act
|
| 97 |
+
self.intermediate_size = intermediate_size
|
| 98 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 99 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 100 |
+
self.max_position_embeddings = max_position_embeddings
|
| 101 |
+
self.type_vocab_size = type_vocab_size
|
| 102 |
+
self.initializer_range = initializer_range
|
| 103 |
+
self.layer_norm_eps = layer_norm_eps
|
| 104 |
+
self.share_encoders = share_encoders
|
| 105 |
+
self.projection_dim = projection_dim
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
__all__ = ["RetriBertConfig"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/retribert/modeling_retribert.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
|
| 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 |
+
RetriBERT model
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
from typing import Optional
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.utils.checkpoint as checkpoint
|
| 24 |
+
from torch import nn
|
| 25 |
+
|
| 26 |
+
from ....modeling_utils import PreTrainedModel
|
| 27 |
+
from ....utils import add_start_docstrings, logging
|
| 28 |
+
from ...bert.modeling_bert import BertModel
|
| 29 |
+
from .configuration_retribert import RetriBertConfig
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #
|
| 36 |
+
class RetriBertPreTrainedModel(PreTrainedModel):
|
| 37 |
+
"""
|
| 38 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 39 |
+
models.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
config: RetriBertConfig
|
| 43 |
+
load_tf_weights = None
|
| 44 |
+
base_model_prefix = "retribert"
|
| 45 |
+
|
| 46 |
+
def _init_weights(self, module):
|
| 47 |
+
"""Initialize the weights"""
|
| 48 |
+
if isinstance(module, nn.Linear):
|
| 49 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 50 |
+
if module.bias is not None:
|
| 51 |
+
module.bias.data.zero_()
|
| 52 |
+
elif isinstance(module, nn.Embedding):
|
| 53 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 54 |
+
if module.padding_idx is not None:
|
| 55 |
+
module.weight.data[module.padding_idx].zero_()
|
| 56 |
+
elif isinstance(module, nn.LayerNorm):
|
| 57 |
+
module.bias.data.zero_()
|
| 58 |
+
module.weight.data.fill_(1.0)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
RETRIBERT_START_DOCSTRING = r"""
|
| 62 |
+
|
| 63 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 64 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 65 |
+
etc.)
|
| 66 |
+
|
| 67 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 68 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 69 |
+
and behavior.
|
| 70 |
+
|
| 71 |
+
Parameters:
|
| 72 |
+
config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.
|
| 73 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 74 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@add_start_docstrings(
|
| 79 |
+
"""Bert Based model to embed queries or document for document retrieval.""",
|
| 80 |
+
RETRIBERT_START_DOCSTRING,
|
| 81 |
+
)
|
| 82 |
+
class RetriBertModel(RetriBertPreTrainedModel):
|
| 83 |
+
def __init__(self, config: RetriBertConfig) -> None:
|
| 84 |
+
super().__init__(config)
|
| 85 |
+
self.projection_dim = config.projection_dim
|
| 86 |
+
|
| 87 |
+
self.bert_query = BertModel(config)
|
| 88 |
+
self.bert_doc = None if config.share_encoders else BertModel(config)
|
| 89 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 90 |
+
self.project_query = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
|
| 91 |
+
self.project_doc = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
|
| 92 |
+
|
| 93 |
+
self.ce_loss = nn.CrossEntropyLoss(reduction="mean")
|
| 94 |
+
|
| 95 |
+
# Initialize weights and apply final processing
|
| 96 |
+
self.post_init()
|
| 97 |
+
|
| 98 |
+
def embed_sentences_checkpointed(
|
| 99 |
+
self,
|
| 100 |
+
input_ids,
|
| 101 |
+
attention_mask,
|
| 102 |
+
sent_encoder,
|
| 103 |
+
checkpoint_batch_size=-1,
|
| 104 |
+
):
|
| 105 |
+
# reproduces BERT forward pass with checkpointing
|
| 106 |
+
if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
|
| 107 |
+
return sent_encoder(input_ids, attention_mask=attention_mask)[1]
|
| 108 |
+
else:
|
| 109 |
+
# prepare implicit variables
|
| 110 |
+
device = input_ids.device
|
| 111 |
+
input_shape = input_ids.size()
|
| 112 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 113 |
+
head_mask = [None] * sent_encoder.config.num_hidden_layers
|
| 114 |
+
extended_attention_mask: torch.Tensor = sent_encoder.get_extended_attention_mask(
|
| 115 |
+
attention_mask, input_shape
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
# define function for checkpointing
|
| 119 |
+
def partial_encode(*inputs):
|
| 120 |
+
encoder_outputs = sent_encoder.encoder(
|
| 121 |
+
inputs[0],
|
| 122 |
+
attention_mask=inputs[1],
|
| 123 |
+
head_mask=head_mask,
|
| 124 |
+
)
|
| 125 |
+
sequence_output = encoder_outputs[0]
|
| 126 |
+
pooled_output = sent_encoder.pooler(sequence_output)
|
| 127 |
+
return pooled_output
|
| 128 |
+
|
| 129 |
+
# run embedding layer on everything at once
|
| 130 |
+
embedding_output = sent_encoder.embeddings(
|
| 131 |
+
input_ids=input_ids, position_ids=None, token_type_ids=token_type_ids, inputs_embeds=None
|
| 132 |
+
)
|
| 133 |
+
# run encoding and pooling on one mini-batch at a time
|
| 134 |
+
pooled_output_list = []
|
| 135 |
+
for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size)):
|
| 136 |
+
b_embedding_output = embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
|
| 137 |
+
b_attention_mask = extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
|
| 138 |
+
pooled_output = checkpoint.checkpoint(partial_encode, b_embedding_output, b_attention_mask)
|
| 139 |
+
pooled_output_list.append(pooled_output)
|
| 140 |
+
return torch.cat(pooled_output_list, dim=0)
|
| 141 |
+
|
| 142 |
+
def embed_questions(
|
| 143 |
+
self,
|
| 144 |
+
input_ids,
|
| 145 |
+
attention_mask=None,
|
| 146 |
+
checkpoint_batch_size=-1,
|
| 147 |
+
):
|
| 148 |
+
q_reps = self.embed_sentences_checkpointed(
|
| 149 |
+
input_ids,
|
| 150 |
+
attention_mask,
|
| 151 |
+
self.bert_query,
|
| 152 |
+
checkpoint_batch_size,
|
| 153 |
+
)
|
| 154 |
+
return self.project_query(q_reps)
|
| 155 |
+
|
| 156 |
+
def embed_answers(
|
| 157 |
+
self,
|
| 158 |
+
input_ids,
|
| 159 |
+
attention_mask=None,
|
| 160 |
+
checkpoint_batch_size=-1,
|
| 161 |
+
):
|
| 162 |
+
a_reps = self.embed_sentences_checkpointed(
|
| 163 |
+
input_ids,
|
| 164 |
+
attention_mask,
|
| 165 |
+
self.bert_query if self.bert_doc is None else self.bert_doc,
|
| 166 |
+
checkpoint_batch_size,
|
| 167 |
+
)
|
| 168 |
+
return self.project_doc(a_reps)
|
| 169 |
+
|
| 170 |
+
def forward(
|
| 171 |
+
self,
|
| 172 |
+
input_ids_query: torch.LongTensor,
|
| 173 |
+
attention_mask_query: Optional[torch.FloatTensor],
|
| 174 |
+
input_ids_doc: torch.LongTensor,
|
| 175 |
+
attention_mask_doc: Optional[torch.FloatTensor],
|
| 176 |
+
checkpoint_batch_size: int = -1,
|
| 177 |
+
) -> torch.FloatTensor:
|
| 178 |
+
r"""
|
| 179 |
+
Args:
|
| 180 |
+
input_ids_query (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 181 |
+
Indices of input sequence tokens in the vocabulary for the queries in a batch.
|
| 182 |
+
|
| 183 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 184 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 185 |
+
|
| 186 |
+
[What are input IDs?](../glossary#input-ids)
|
| 187 |
+
attention_mask_query (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 188 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 189 |
+
|
| 190 |
+
- 1 for tokens that are **not masked**,
|
| 191 |
+
- 0 for tokens that are **masked**.
|
| 192 |
+
|
| 193 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 194 |
+
input_ids_doc (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 195 |
+
Indices of input sequence tokens in the vocabulary for the documents in a batch.
|
| 196 |
+
attention_mask_doc (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 197 |
+
Mask to avoid performing attention on documents padding token indices.
|
| 198 |
+
checkpoint_batch_size (`int`, *optional*, defaults to `-1`):
|
| 199 |
+
If greater than 0, uses gradient checkpointing to only compute sequence representation on
|
| 200 |
+
`checkpoint_batch_size` examples at a time on the GPU. All query representations are still compared to
|
| 201 |
+
all document representations in the batch.
|
| 202 |
+
|
| 203 |
+
Return:
|
| 204 |
+
`torch.FloatTensor``: The bidirectional cross-entropy loss obtained while trying to match each query to its
|
| 205 |
+
corresponding document and each document to its corresponding query in the batch
|
| 206 |
+
"""
|
| 207 |
+
device = input_ids_query.device
|
| 208 |
+
q_reps = self.embed_questions(input_ids_query, attention_mask_query, checkpoint_batch_size)
|
| 209 |
+
a_reps = self.embed_answers(input_ids_doc, attention_mask_doc, checkpoint_batch_size)
|
| 210 |
+
compare_scores = torch.mm(q_reps, a_reps.t())
|
| 211 |
+
loss_qa = self.ce_loss(compare_scores, torch.arange(compare_scores.shape[1]).to(device))
|
| 212 |
+
loss_aq = self.ce_loss(compare_scores.t(), torch.arange(compare_scores.shape[0]).to(device))
|
| 213 |
+
loss = (loss_qa + loss_aq) / 2
|
| 214 |
+
return loss
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
__all__ = ["RetriBertModel", "RetriBertPreTrainedModel"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/retribert/tokenization_retribert.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Tokenization classes for RetriBERT."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
import os
|
| 19 |
+
import unicodedata
|
| 20 |
+
from typing import Optional
|
| 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 RetriBertTokenizer(PreTrainedTokenizer):
|
| 52 |
+
r"""
|
| 53 |
+
Constructs a RetriBERT tokenizer.
|
| 54 |
+
|
| 55 |
+
[`RetriBertTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation splitting
|
| 56 |
+
and wordpiece.
|
| 57 |
+
|
| 58 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer
|
| 59 |
+
to: this superclass for more information regarding those methods.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
vocab_file (`str`):
|
| 63 |
+
File containing the vocabulary.
|
| 64 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 65 |
+
Whether or not to lowercase the input when tokenizing.
|
| 66 |
+
do_basic_tokenize (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether or not to do basic tokenization before WordPiece.
|
| 68 |
+
never_split (`Iterable`, *optional*):
|
| 69 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
| 70 |
+
`do_basic_tokenize=True`
|
| 71 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 72 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 73 |
+
token instead.
|
| 74 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 75 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 76 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 77 |
+
token of a sequence built with special tokens.
|
| 78 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 79 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 80 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 81 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 82 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 83 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 84 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 85 |
+
modeling. This is the token which the model will try to predict.
|
| 86 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 87 |
+
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see this
|
| 88 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 89 |
+
strip_accents (`bool`, *optional*):
|
| 90 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 91 |
+
value for `lowercase` (as in the original BERT).
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 95 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 96 |
+
|
| 97 |
+
def __init__(
|
| 98 |
+
self,
|
| 99 |
+
vocab_file,
|
| 100 |
+
do_lower_case=True,
|
| 101 |
+
do_basic_tokenize=True,
|
| 102 |
+
never_split=None,
|
| 103 |
+
unk_token="[UNK]",
|
| 104 |
+
sep_token="[SEP]",
|
| 105 |
+
pad_token="[PAD]",
|
| 106 |
+
cls_token="[CLS]",
|
| 107 |
+
mask_token="[MASK]",
|
| 108 |
+
tokenize_chinese_chars=True,
|
| 109 |
+
strip_accents=None,
|
| 110 |
+
**kwargs,
|
| 111 |
+
):
|
| 112 |
+
if not os.path.isfile(vocab_file):
|
| 113 |
+
raise ValueError(
|
| 114 |
+
f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
|
| 115 |
+
" model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
|
| 116 |
+
)
|
| 117 |
+
self.vocab = load_vocab(vocab_file)
|
| 118 |
+
self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
|
| 119 |
+
self.do_basic_tokenize = do_basic_tokenize
|
| 120 |
+
if do_basic_tokenize:
|
| 121 |
+
self.basic_tokenizer = BasicTokenizer(
|
| 122 |
+
do_lower_case=do_lower_case,
|
| 123 |
+
never_split=never_split,
|
| 124 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 125 |
+
strip_accents=strip_accents,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
|
| 129 |
+
|
| 130 |
+
super().__init__(
|
| 131 |
+
do_lower_case=do_lower_case,
|
| 132 |
+
do_basic_tokenize=do_basic_tokenize,
|
| 133 |
+
never_split=never_split,
|
| 134 |
+
unk_token=unk_token,
|
| 135 |
+
sep_token=sep_token,
|
| 136 |
+
pad_token=pad_token,
|
| 137 |
+
cls_token=cls_token,
|
| 138 |
+
mask_token=mask_token,
|
| 139 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 140 |
+
strip_accents=strip_accents,
|
| 141 |
+
**kwargs,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
@property
|
| 145 |
+
def do_lower_case(self):
|
| 146 |
+
return self.basic_tokenizer.do_lower_case
|
| 147 |
+
|
| 148 |
+
@property
|
| 149 |
+
def vocab_size(self):
|
| 150 |
+
return len(self.vocab)
|
| 151 |
+
|
| 152 |
+
def get_vocab(self):
|
| 153 |
+
return dict(self.vocab, **self.added_tokens_encoder)
|
| 154 |
+
|
| 155 |
+
def _tokenize(self, text, split_special_tokens=False):
|
| 156 |
+
split_tokens = []
|
| 157 |
+
if self.do_basic_tokenize:
|
| 158 |
+
for token in self.basic_tokenizer.tokenize(
|
| 159 |
+
text, never_split=self.all_special_tokens if not split_special_tokens else None
|
| 160 |
+
):
|
| 161 |
+
# If the token is part of the never_split set
|
| 162 |
+
if token in self.basic_tokenizer.never_split:
|
| 163 |
+
split_tokens.append(token)
|
| 164 |
+
else:
|
| 165 |
+
split_tokens += self.wordpiece_tokenizer.tokenize(token)
|
| 166 |
+
else:
|
| 167 |
+
split_tokens = self.wordpiece_tokenizer.tokenize(text)
|
| 168 |
+
return split_tokens
|
| 169 |
+
|
| 170 |
+
def _convert_token_to_id(self, token):
|
| 171 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 172 |
+
return self.vocab.get(token, self.vocab.get(self.unk_token))
|
| 173 |
+
|
| 174 |
+
def _convert_id_to_token(self, index):
|
| 175 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 176 |
+
return self.ids_to_tokens.get(index, self.unk_token)
|
| 177 |
+
|
| 178 |
+
def convert_tokens_to_string(self, tokens):
|
| 179 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 180 |
+
out_string = " ".join(tokens).replace(" ##", "").strip()
|
| 181 |
+
return out_string
|
| 182 |
+
|
| 183 |
+
def build_inputs_with_special_tokens(
|
| 184 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 185 |
+
) -> list[int]:
|
| 186 |
+
"""
|
| 187 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 188 |
+
adding special tokens. A BERT sequence has the following format:
|
| 189 |
+
|
| 190 |
+
- single sequence: `[CLS] X [SEP]`
|
| 191 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
token_ids_0 (`List[int]`):
|
| 195 |
+
List of IDs to which the special tokens will be added.
|
| 196 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 197 |
+
Optional second list of IDs for sequence pairs.
|
| 198 |
+
|
| 199 |
+
Returns:
|
| 200 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 201 |
+
"""
|
| 202 |
+
if token_ids_1 is None:
|
| 203 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 204 |
+
cls = [self.cls_token_id]
|
| 205 |
+
sep = [self.sep_token_id]
|
| 206 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 207 |
+
|
| 208 |
+
def get_special_tokens_mask(
|
| 209 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
|
| 210 |
+
) -> list[int]:
|
| 211 |
+
"""
|
| 212 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 213 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 214 |
+
|
| 215 |
+
Args:
|
| 216 |
+
token_ids_0 (`List[int]`):
|
| 217 |
+
List of IDs.
|
| 218 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 219 |
+
Optional second list of IDs for sequence pairs.
|
| 220 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 221 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
if already_has_special_tokens:
|
| 228 |
+
return super().get_special_tokens_mask(
|
| 229 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
if token_ids_1 is not None:
|
| 233 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 234 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 235 |
+
|
| 236 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 237 |
+
index = 0
|
| 238 |
+
if os.path.isdir(save_directory):
|
| 239 |
+
vocab_file = os.path.join(
|
| 240 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 241 |
+
)
|
| 242 |
+
else:
|
| 243 |
+
vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
|
| 244 |
+
with open(vocab_file, "w", encoding="utf-8") as writer:
|
| 245 |
+
for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
|
| 246 |
+
if index != token_index:
|
| 247 |
+
logger.warning(
|
| 248 |
+
f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
|
| 249 |
+
" Please check that the vocabulary is not corrupted!"
|
| 250 |
+
)
|
| 251 |
+
index = token_index
|
| 252 |
+
writer.write(token + "\n")
|
| 253 |
+
index += 1
|
| 254 |
+
return (vocab_file,)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class BasicTokenizer:
|
| 258 |
+
"""
|
| 259 |
+
Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 263 |
+
Whether or not to lowercase the input when tokenizing.
|
| 264 |
+
never_split (`Iterable`, *optional*):
|
| 265 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
| 266 |
+
`do_basic_tokenize=True`
|
| 267 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 268 |
+
Whether or not to tokenize Chinese characters.
|
| 269 |
+
|
| 270 |
+
This should likely be deactivated for Japanese (see this
|
| 271 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 272 |
+
strip_accents (`bool`, *optional*):
|
| 273 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 274 |
+
value for `lowercase` (as in the original BERT).
|
| 275 |
+
do_split_on_punc (`bool`, *optional*, defaults to `True`):
|
| 276 |
+
In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
|
| 277 |
+
the full context of the words, such as contractions.
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
def __init__(
|
| 281 |
+
self,
|
| 282 |
+
do_lower_case=True,
|
| 283 |
+
never_split=None,
|
| 284 |
+
tokenize_chinese_chars=True,
|
| 285 |
+
strip_accents=None,
|
| 286 |
+
do_split_on_punc=True,
|
| 287 |
+
):
|
| 288 |
+
if never_split is None:
|
| 289 |
+
never_split = []
|
| 290 |
+
self.do_lower_case = do_lower_case
|
| 291 |
+
self.never_split = set(never_split)
|
| 292 |
+
self.tokenize_chinese_chars = tokenize_chinese_chars
|
| 293 |
+
self.strip_accents = strip_accents
|
| 294 |
+
self.do_split_on_punc = do_split_on_punc
|
| 295 |
+
|
| 296 |
+
def tokenize(self, text, never_split=None):
|
| 297 |
+
"""
|
| 298 |
+
Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
|
| 299 |
+
|
| 300 |
+
Args:
|
| 301 |
+
never_split (`List[str]`, *optional*)
|
| 302 |
+
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
|
| 303 |
+
[`PreTrainedTokenizer.tokenize`]) List of token not to split.
|
| 304 |
+
"""
|
| 305 |
+
# union() returns a new set by concatenating the two sets.
|
| 306 |
+
never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
|
| 307 |
+
text = self._clean_text(text)
|
| 308 |
+
|
| 309 |
+
# This was added on November 1st, 2018 for the multilingual and Chinese
|
| 310 |
+
# models. This is also applied to the English models now, but it doesn't
|
| 311 |
+
# matter since the English models were not trained on any Chinese data
|
| 312 |
+
# and generally don't have any Chinese data in them (there are Chinese
|
| 313 |
+
# characters in the vocabulary because Wikipedia does have some Chinese
|
| 314 |
+
# words in the English Wikipedia.).
|
| 315 |
+
if self.tokenize_chinese_chars:
|
| 316 |
+
text = self._tokenize_chinese_chars(text)
|
| 317 |
+
# prevents treating the same character with different unicode codepoints as different characters
|
| 318 |
+
unicode_normalized_text = unicodedata.normalize("NFC", text)
|
| 319 |
+
orig_tokens = whitespace_tokenize(unicode_normalized_text)
|
| 320 |
+
split_tokens = []
|
| 321 |
+
for token in orig_tokens:
|
| 322 |
+
if token not in never_split:
|
| 323 |
+
if self.do_lower_case:
|
| 324 |
+
token = token.lower()
|
| 325 |
+
if self.strip_accents is not False:
|
| 326 |
+
token = self._run_strip_accents(token)
|
| 327 |
+
elif self.strip_accents:
|
| 328 |
+
token = self._run_strip_accents(token)
|
| 329 |
+
split_tokens.extend(self._run_split_on_punc(token, never_split))
|
| 330 |
+
|
| 331 |
+
output_tokens = whitespace_tokenize(" ".join(split_tokens))
|
| 332 |
+
return output_tokens
|
| 333 |
+
|
| 334 |
+
def _run_strip_accents(self, text):
|
| 335 |
+
"""Strips accents from a piece of text."""
|
| 336 |
+
text = unicodedata.normalize("NFD", text)
|
| 337 |
+
output = []
|
| 338 |
+
for char in text:
|
| 339 |
+
cat = unicodedata.category(char)
|
| 340 |
+
if cat == "Mn":
|
| 341 |
+
continue
|
| 342 |
+
output.append(char)
|
| 343 |
+
return "".join(output)
|
| 344 |
+
|
| 345 |
+
def _run_split_on_punc(self, text, never_split=None):
|
| 346 |
+
"""Splits punctuation on a piece of text."""
|
| 347 |
+
if not self.do_split_on_punc or (never_split is not None and text in never_split):
|
| 348 |
+
return [text]
|
| 349 |
+
chars = list(text)
|
| 350 |
+
i = 0
|
| 351 |
+
start_new_word = True
|
| 352 |
+
output = []
|
| 353 |
+
while i < len(chars):
|
| 354 |
+
char = chars[i]
|
| 355 |
+
if _is_punctuation(char):
|
| 356 |
+
output.append([char])
|
| 357 |
+
start_new_word = True
|
| 358 |
+
else:
|
| 359 |
+
if start_new_word:
|
| 360 |
+
output.append([])
|
| 361 |
+
start_new_word = False
|
| 362 |
+
output[-1].append(char)
|
| 363 |
+
i += 1
|
| 364 |
+
|
| 365 |
+
return ["".join(x) for x in output]
|
| 366 |
+
|
| 367 |
+
def _tokenize_chinese_chars(self, text):
|
| 368 |
+
"""Adds whitespace around any CJK character."""
|
| 369 |
+
output = []
|
| 370 |
+
for char in text:
|
| 371 |
+
cp = ord(char)
|
| 372 |
+
if self._is_chinese_char(cp):
|
| 373 |
+
output.append(" ")
|
| 374 |
+
output.append(char)
|
| 375 |
+
output.append(" ")
|
| 376 |
+
else:
|
| 377 |
+
output.append(char)
|
| 378 |
+
return "".join(output)
|
| 379 |
+
|
| 380 |
+
def _is_chinese_char(self, cp):
|
| 381 |
+
"""Checks whether CP is the codepoint of a CJK character."""
|
| 382 |
+
# This defines a "chinese character" as anything in the CJK Unicode block:
|
| 383 |
+
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
|
| 384 |
+
#
|
| 385 |
+
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
|
| 386 |
+
# despite its name. The modern Korean Hangul alphabet is a different block,
|
| 387 |
+
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
|
| 388 |
+
# space-separated words, so they are not treated specially and handled
|
| 389 |
+
# like the all of the other languages.
|
| 390 |
+
if (
|
| 391 |
+
(cp >= 0x4E00 and cp <= 0x9FFF)
|
| 392 |
+
or (cp >= 0x3400 and cp <= 0x4DBF)
|
| 393 |
+
or (cp >= 0x20000 and cp <= 0x2A6DF)
|
| 394 |
+
or (cp >= 0x2A700 and cp <= 0x2B73F)
|
| 395 |
+
or (cp >= 0x2B740 and cp <= 0x2B81F)
|
| 396 |
+
or (cp >= 0x2B820 and cp <= 0x2CEAF)
|
| 397 |
+
or (cp >= 0xF900 and cp <= 0xFAFF)
|
| 398 |
+
or (cp >= 0x2F800 and cp <= 0x2FA1F)
|
| 399 |
+
):
|
| 400 |
+
return True
|
| 401 |
+
|
| 402 |
+
return False
|
| 403 |
+
|
| 404 |
+
def _clean_text(self, text):
|
| 405 |
+
"""Performs invalid character removal and whitespace cleanup on text."""
|
| 406 |
+
output = []
|
| 407 |
+
for char in text:
|
| 408 |
+
cp = ord(char)
|
| 409 |
+
if cp == 0 or cp == 0xFFFD or _is_control(char):
|
| 410 |
+
continue
|
| 411 |
+
if _is_whitespace(char):
|
| 412 |
+
output.append(" ")
|
| 413 |
+
else:
|
| 414 |
+
output.append(char)
|
| 415 |
+
return "".join(output)
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
class WordpieceTokenizer:
|
| 419 |
+
"""Runs WordPiece tokenization."""
|
| 420 |
+
|
| 421 |
+
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
|
| 422 |
+
self.vocab = vocab
|
| 423 |
+
self.unk_token = unk_token
|
| 424 |
+
self.max_input_chars_per_word = max_input_chars_per_word
|
| 425 |
+
|
| 426 |
+
def tokenize(self, text):
|
| 427 |
+
"""
|
| 428 |
+
Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
|
| 429 |
+
tokenization using the given vocabulary.
|
| 430 |
+
|
| 431 |
+
For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
|
| 432 |
+
|
| 433 |
+
Args:
|
| 434 |
+
text: A single token or whitespace separated tokens. This should have
|
| 435 |
+
already been passed through *BasicTokenizer*.
|
| 436 |
+
|
| 437 |
+
Returns:
|
| 438 |
+
A list of wordpiece tokens.
|
| 439 |
+
"""
|
| 440 |
+
|
| 441 |
+
output_tokens = []
|
| 442 |
+
for token in whitespace_tokenize(text):
|
| 443 |
+
chars = list(token)
|
| 444 |
+
if len(chars) > self.max_input_chars_per_word:
|
| 445 |
+
output_tokens.append(self.unk_token)
|
| 446 |
+
continue
|
| 447 |
+
|
| 448 |
+
is_bad = False
|
| 449 |
+
start = 0
|
| 450 |
+
sub_tokens = []
|
| 451 |
+
while start < len(chars):
|
| 452 |
+
end = len(chars)
|
| 453 |
+
cur_substr = None
|
| 454 |
+
while start < end:
|
| 455 |
+
substr = "".join(chars[start:end])
|
| 456 |
+
if start > 0:
|
| 457 |
+
substr = "##" + substr
|
| 458 |
+
if substr in self.vocab:
|
| 459 |
+
cur_substr = substr
|
| 460 |
+
break
|
| 461 |
+
end -= 1
|
| 462 |
+
if cur_substr is None:
|
| 463 |
+
is_bad = True
|
| 464 |
+
break
|
| 465 |
+
sub_tokens.append(cur_substr)
|
| 466 |
+
start = end
|
| 467 |
+
|
| 468 |
+
if is_bad:
|
| 469 |
+
output_tokens.append(self.unk_token)
|
| 470 |
+
else:
|
| 471 |
+
output_tokens.extend(sub_tokens)
|
| 472 |
+
return output_tokens
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
__all__ = ["RetriBertTokenizer"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/retribert/tokenization_retribert_fast.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Tokenization classes for RetriBERT."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
from tokenizers import normalizers
|
| 21 |
+
|
| 22 |
+
from ....tokenization_utils_fast import PreTrainedTokenizerFast
|
| 23 |
+
from ....utils import logging
|
| 24 |
+
from .tokenization_retribert import RetriBertTokenizer
|
| 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 RetriBertTokenizerFast(PreTrainedTokenizerFast):
|
| 33 |
+
r"""
|
| 34 |
+
Construct a "fast" RetriBERT tokenizer (backed by HuggingFace's *tokenizers* library).
|
| 35 |
+
|
| 36 |
+
[`RetriBertTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization: punctuation
|
| 37 |
+
splitting and wordpiece.
|
| 38 |
+
|
| 39 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
| 40 |
+
refer to this superclass for more information regarding those methods.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
vocab_file (`str`):
|
| 44 |
+
File containing the vocabulary.
|
| 45 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 46 |
+
Whether or not to lowercase the input when tokenizing.
|
| 47 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 48 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 49 |
+
token instead.
|
| 50 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 51 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 52 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 53 |
+
token of a sequence built with special tokens.
|
| 54 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 55 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 56 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 57 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 58 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 59 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 60 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 61 |
+
modeling. This is the token which the model will try to predict.
|
| 62 |
+
clean_text (`bool`, *optional*, defaults to `True`):
|
| 63 |
+
Whether or not to clean the text before tokenization by removing any control characters and replacing all
|
| 64 |
+
whitespaces by the classic one.
|
| 65 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 66 |
+
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
|
| 67 |
+
issue](https://github.com/huggingface/transformers/issues/328)).
|
| 68 |
+
strip_accents (`bool`, *optional*):
|
| 69 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 70 |
+
value for `lowercase` (as in the original BERT).
|
| 71 |
+
wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
|
| 72 |
+
The prefix for subwords.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 76 |
+
slow_tokenizer_class = RetriBertTokenizer
|
| 77 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 78 |
+
|
| 79 |
+
def __init__(
|
| 80 |
+
self,
|
| 81 |
+
vocab_file=None,
|
| 82 |
+
tokenizer_file=None,
|
| 83 |
+
do_lower_case=True,
|
| 84 |
+
unk_token="[UNK]",
|
| 85 |
+
sep_token="[SEP]",
|
| 86 |
+
pad_token="[PAD]",
|
| 87 |
+
cls_token="[CLS]",
|
| 88 |
+
mask_token="[MASK]",
|
| 89 |
+
tokenize_chinese_chars=True,
|
| 90 |
+
strip_accents=None,
|
| 91 |
+
**kwargs,
|
| 92 |
+
):
|
| 93 |
+
super().__init__(
|
| 94 |
+
vocab_file,
|
| 95 |
+
tokenizer_file=tokenizer_file,
|
| 96 |
+
do_lower_case=do_lower_case,
|
| 97 |
+
unk_token=unk_token,
|
| 98 |
+
sep_token=sep_token,
|
| 99 |
+
pad_token=pad_token,
|
| 100 |
+
cls_token=cls_token,
|
| 101 |
+
mask_token=mask_token,
|
| 102 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 103 |
+
strip_accents=strip_accents,
|
| 104 |
+
**kwargs,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
|
| 108 |
+
if (
|
| 109 |
+
normalizer_state.get("lowercase", do_lower_case) != do_lower_case
|
| 110 |
+
or normalizer_state.get("strip_accents", strip_accents) != strip_accents
|
| 111 |
+
or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
|
| 112 |
+
):
|
| 113 |
+
normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
|
| 114 |
+
normalizer_state["lowercase"] = do_lower_case
|
| 115 |
+
normalizer_state["strip_accents"] = strip_accents
|
| 116 |
+
normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
|
| 117 |
+
self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
|
| 118 |
+
|
| 119 |
+
self.do_lower_case = do_lower_case
|
| 120 |
+
|
| 121 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
| 122 |
+
"""
|
| 123 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 124 |
+
adding special tokens. A BERT sequence has the following format:
|
| 125 |
+
|
| 126 |
+
- single sequence: `[CLS] X [SEP]`
|
| 127 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 128 |
+
|
| 129 |
+
Args:
|
| 130 |
+
token_ids_0 (`List[int]`):
|
| 131 |
+
List of IDs to which the special tokens will be added.
|
| 132 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 133 |
+
Optional second list of IDs for sequence pairs.
|
| 134 |
+
|
| 135 |
+
Returns:
|
| 136 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 137 |
+
"""
|
| 138 |
+
output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 139 |
+
|
| 140 |
+
if token_ids_1 is not None:
|
| 141 |
+
output += token_ids_1 + [self.sep_token_id]
|
| 142 |
+
|
| 143 |
+
return output
|
| 144 |
+
|
| 145 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 146 |
+
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
|
| 147 |
+
return tuple(files)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
__all__ = ["RetriBertTokenizerFast"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ....utils import _LazyModule
|
| 17 |
+
from ....utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_speech_to_text_2 import *
|
| 22 |
+
from .modeling_speech_to_text_2 import *
|
| 23 |
+
from .processing_speech_to_text_2 import *
|
| 24 |
+
from .tokenization_speech_to_text_2 import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/configuration_speech_to_text_2.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Speech2Text 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 Speech2Text2Config(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`Speech2Text2ForCausalLM`]. It is used to
|
| 27 |
+
instantiate an Speech2Text2 model according to the specified arguments, defining the model architecture.
|
| 28 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the Speech2Text2
|
| 29 |
+
[facebook/s2t-wav2vec2-large-en-de](https://huggingface.co/facebook/s2t-wav2vec2-large-en-de) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 50265):
|
| 37 |
+
Vocabulary size of the Speech2Text model. Defines the number of different tokens that can be represented by
|
| 38 |
+
the `inputs_ids` passed when calling [`Speech2TextModel`]
|
| 39 |
+
d_model (`int`, *optional*, defaults to 1024):
|
| 40 |
+
Dimensionality of the layers and the pooler layer.
|
| 41 |
+
decoder_layers (`int`, *optional*, defaults to 12):
|
| 42 |
+
Number of decoder layers.
|
| 43 |
+
decoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 44 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 45 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 46 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
|
| 47 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 48 |
+
The non-linear activation function (function or string) in the pooler. If string, `"gelu"`, `"relu"`,
|
| 49 |
+
`"silu"` and `"gelu_new"` are supported.
|
| 50 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 51 |
+
The dropout probability for all fully connected layers in the embeddings, and pooler.
|
| 52 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 53 |
+
The dropout ratio for the attention probabilities.
|
| 54 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 55 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 56 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 57 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 58 |
+
https://huggingface.co/papers/1909.11556>`__ for more details.
|
| 59 |
+
decoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 60 |
+
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
|
| 61 |
+
for more details.
|
| 62 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 63 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
| 64 |
+
max_target_positions (`int`, *optional*, defaults to 1024):
|
| 65 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 66 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 67 |
+
|
| 68 |
+
Example:
|
| 69 |
+
|
| 70 |
+
```python
|
| 71 |
+
>>> from transformers import Speech2Text2Config, Speech2Text2ForCausalLM
|
| 72 |
+
|
| 73 |
+
>>> # Initializing a Speech2Text2 s2t_transformer_s style configuration
|
| 74 |
+
>>> configuration = Speech2Text2Config()
|
| 75 |
+
|
| 76 |
+
>>> # Initializing a model (with random weights) from the s2t_transformer_s style configuration
|
| 77 |
+
>>> model = Speech2Text2ForCausalLM(configuration)
|
| 78 |
+
|
| 79 |
+
>>> # Accessing the model configuration
|
| 80 |
+
>>> configuration = model.config
|
| 81 |
+
```"""
|
| 82 |
+
|
| 83 |
+
model_type = "speech_to_text_2"
|
| 84 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 85 |
+
attribute_map = {"num_attention_heads": "decoder_attention_heads", "hidden_size": "d_model"}
|
| 86 |
+
|
| 87 |
+
def __init__(
|
| 88 |
+
self,
|
| 89 |
+
vocab_size=10000,
|
| 90 |
+
decoder_layers=6,
|
| 91 |
+
decoder_ffn_dim=2048,
|
| 92 |
+
decoder_attention_heads=4,
|
| 93 |
+
decoder_layerdrop=0.0,
|
| 94 |
+
use_cache=True,
|
| 95 |
+
activation_function="relu",
|
| 96 |
+
d_model=256,
|
| 97 |
+
dropout=0.1,
|
| 98 |
+
attention_dropout=0.0,
|
| 99 |
+
activation_dropout=0.0,
|
| 100 |
+
init_std=0.02,
|
| 101 |
+
decoder_start_token_id=2,
|
| 102 |
+
scale_embedding=True,
|
| 103 |
+
pad_token_id=1,
|
| 104 |
+
bos_token_id=0,
|
| 105 |
+
eos_token_id=2,
|
| 106 |
+
max_target_positions=1024,
|
| 107 |
+
**kwargs,
|
| 108 |
+
):
|
| 109 |
+
self.vocab_size = vocab_size
|
| 110 |
+
self.d_model = d_model
|
| 111 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 112 |
+
self.decoder_layers = decoder_layers
|
| 113 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 114 |
+
self.dropout = dropout
|
| 115 |
+
self.attention_dropout = attention_dropout
|
| 116 |
+
self.activation_dropout = activation_dropout
|
| 117 |
+
self.activation_function = activation_function
|
| 118 |
+
self.init_std = init_std
|
| 119 |
+
self.decoder_layerdrop = decoder_layerdrop
|
| 120 |
+
self.use_cache = use_cache
|
| 121 |
+
self.num_hidden_layers = decoder_layers
|
| 122 |
+
self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
|
| 123 |
+
self.max_target_positions = max_target_positions
|
| 124 |
+
|
| 125 |
+
super().__init__(
|
| 126 |
+
pad_token_id=pad_token_id,
|
| 127 |
+
bos_token_id=bos_token_id,
|
| 128 |
+
eos_token_id=eos_token_id,
|
| 129 |
+
decoder_start_token_id=decoder_start_token_id,
|
| 130 |
+
**kwargs,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
__all__ = ["Speech2Text2Config"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/modeling_speech_to_text_2.py
ADDED
|
@@ -0,0 +1,905 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch Speech2Text2 model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from typing import Optional, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
from torch.nn import CrossEntropyLoss
|
| 23 |
+
|
| 24 |
+
from ....activations import ACT2FN
|
| 25 |
+
from ....cache_utils import Cache
|
| 26 |
+
from ....modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
|
| 27 |
+
from ....modeling_layers import GradientCheckpointingLayer
|
| 28 |
+
from ....modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
|
| 29 |
+
from ....modeling_utils import PreTrainedModel
|
| 30 |
+
from ....utils import add_start_docstrings, logging, replace_return_docstrings
|
| 31 |
+
from ....utils.deprecation import deprecate_kwarg
|
| 32 |
+
from .configuration_speech_to_text_2 import Speech2Text2Config
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
_CONFIG_FOR_DOC = "Speech2Text2Config"
|
| 38 |
+
_CHECKPOINT_FOR_DOC = "facebook/s2t-wav2vec2-large-en-de"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Speech2Text2SinusoidalPositionalEmbedding(nn.Module):
|
| 42 |
+
"""This module produces sinusoidal positional embeddings of any length."""
|
| 43 |
+
|
| 44 |
+
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 45 |
+
super().__init__()
|
| 46 |
+
self.offset = 2
|
| 47 |
+
self.embedding_dim = embedding_dim
|
| 48 |
+
self.padding_idx = padding_idx
|
| 49 |
+
|
| 50 |
+
def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 51 |
+
emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
|
| 52 |
+
if hasattr(self, "weights"):
|
| 53 |
+
# in forward put the weights on the correct dtype and device of the param
|
| 54 |
+
emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
|
| 55 |
+
|
| 56 |
+
self.weights = nn.Parameter(emb_weights)
|
| 57 |
+
self.weights.requires_grad = False
|
| 58 |
+
self.weights.detach_()
|
| 59 |
+
|
| 60 |
+
@staticmethod
|
| 61 |
+
def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 62 |
+
"""
|
| 63 |
+
Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the
|
| 64 |
+
description in Section 3.5 of "Attention Is All You Need".
|
| 65 |
+
"""
|
| 66 |
+
half_dim = embedding_dim // 2
|
| 67 |
+
emb = math.log(10000) / (half_dim - 1)
|
| 68 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
|
| 69 |
+
emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
|
| 70 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
|
| 71 |
+
if embedding_dim % 2 == 1:
|
| 72 |
+
# zero pad
|
| 73 |
+
emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
|
| 74 |
+
if padding_idx is not None:
|
| 75 |
+
emb[padding_idx, :] = 0
|
| 76 |
+
return emb.to(torch.get_default_dtype())
|
| 77 |
+
|
| 78 |
+
@torch.no_grad()
|
| 79 |
+
def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0):
|
| 80 |
+
bsz, seq_len = input_ids.size()
|
| 81 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
| 82 |
+
position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length).to(
|
| 83 |
+
input_ids.device
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
# expand embeddings if needed
|
| 87 |
+
max_pos = self.padding_idx + 1 + seq_len
|
| 88 |
+
if max_pos > self.weights.size(0):
|
| 89 |
+
self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
|
| 90 |
+
|
| 91 |
+
return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, -1).detach()
|
| 92 |
+
|
| 93 |
+
def create_position_ids_from_input_ids(
|
| 94 |
+
self, input_ids: torch.Tensor, padding_idx: int, past_key_values_length: Optional[int] = 0
|
| 95 |
+
):
|
| 96 |
+
"""
|
| 97 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
|
| 98 |
+
symbols are ignored. This is modified from fairseq's `utils.make_positions`.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
x: torch.Tensor x:
|
| 102 |
+
Returns: torch.Tensor
|
| 103 |
+
"""
|
| 104 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
| 105 |
+
mask = input_ids.ne(padding_idx).int()
|
| 106 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
| 107 |
+
return incremental_indices.long() + padding_idx
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class Speech2Text2Attention(nn.Module):
|
| 111 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 112 |
+
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
embed_dim: int,
|
| 116 |
+
num_heads: int,
|
| 117 |
+
dropout: float = 0.0,
|
| 118 |
+
is_decoder: bool = False,
|
| 119 |
+
bias: bool = True,
|
| 120 |
+
is_causal: bool = False,
|
| 121 |
+
config: Optional[Speech2Text2Config] = None,
|
| 122 |
+
):
|
| 123 |
+
super().__init__()
|
| 124 |
+
self.embed_dim = embed_dim
|
| 125 |
+
self.num_heads = num_heads
|
| 126 |
+
self.dropout = dropout
|
| 127 |
+
self.head_dim = embed_dim // num_heads
|
| 128 |
+
self.config = config
|
| 129 |
+
|
| 130 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 131 |
+
raise ValueError(
|
| 132 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 133 |
+
f" and `num_heads`: {num_heads})."
|
| 134 |
+
)
|
| 135 |
+
self.scaling = self.head_dim**-0.5
|
| 136 |
+
self.is_decoder = is_decoder
|
| 137 |
+
self.is_causal = is_causal
|
| 138 |
+
|
| 139 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 140 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 141 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 142 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 143 |
+
|
| 144 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 145 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 146 |
+
|
| 147 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 148 |
+
def forward(
|
| 149 |
+
self,
|
| 150 |
+
hidden_states: torch.Tensor,
|
| 151 |
+
key_value_states: Optional[torch.Tensor] = None,
|
| 152 |
+
past_key_values: Optional[Cache] = None,
|
| 153 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 154 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 155 |
+
output_attentions: bool = False,
|
| 156 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
|
| 157 |
+
"""Input shape: Batch x Time x Channel"""
|
| 158 |
+
|
| 159 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 160 |
+
# for the decoder
|
| 161 |
+
is_cross_attention = key_value_states is not None
|
| 162 |
+
|
| 163 |
+
bsz, tgt_len, _ = hidden_states.size()
|
| 164 |
+
|
| 165 |
+
# get query proj
|
| 166 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 167 |
+
# get key, value proj
|
| 168 |
+
# `past_key_values[0].shape[2] == key_value_states.shape[1]`
|
| 169 |
+
# is checking that the `sequence_length` of the `past_key_values` is the same as
|
| 170 |
+
# the provided `key_value_states` to support prefix tuning
|
| 171 |
+
if (
|
| 172 |
+
is_cross_attention
|
| 173 |
+
and past_key_values is not None
|
| 174 |
+
and past_key_values[0].shape[2] == key_value_states.shape[1]
|
| 175 |
+
):
|
| 176 |
+
# reuse k,v, cross_attentions
|
| 177 |
+
key_states = past_key_values[0]
|
| 178 |
+
value_states = past_key_values[1]
|
| 179 |
+
elif is_cross_attention:
|
| 180 |
+
# cross_attentions
|
| 181 |
+
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
|
| 182 |
+
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
|
| 183 |
+
elif past_key_values is not None:
|
| 184 |
+
# reuse k, v, self_attention
|
| 185 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 186 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 187 |
+
key_states = torch.cat([past_key_values[0], key_states], dim=2)
|
| 188 |
+
value_states = torch.cat([past_key_values[1], value_states], dim=2)
|
| 189 |
+
else:
|
| 190 |
+
# self_attention
|
| 191 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 192 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 193 |
+
|
| 194 |
+
if self.is_decoder:
|
| 195 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 196 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 197 |
+
# key/value_states (first "if" case)
|
| 198 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 199 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 200 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 201 |
+
# if encoder bi-directional self-attention `past_key_values` is always `None`
|
| 202 |
+
past_key_values = (key_states, value_states)
|
| 203 |
+
|
| 204 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 205 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 206 |
+
key_states = key_states.reshape(*proj_shape)
|
| 207 |
+
value_states = value_states.reshape(*proj_shape)
|
| 208 |
+
|
| 209 |
+
src_len = key_states.size(1)
|
| 210 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 211 |
+
|
| 212 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 213 |
+
raise ValueError(
|
| 214 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 215 |
+
f" {attn_weights.size()}"
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
if attention_mask is not None:
|
| 219 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 220 |
+
raise ValueError(
|
| 221 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 222 |
+
)
|
| 223 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 224 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 225 |
+
|
| 226 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 227 |
+
|
| 228 |
+
if layer_head_mask is not None:
|
| 229 |
+
if layer_head_mask.size() != (self.num_heads,):
|
| 230 |
+
raise ValueError(
|
| 231 |
+
f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
|
| 232 |
+
f" {layer_head_mask.size()}"
|
| 233 |
+
)
|
| 234 |
+
attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 235 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 236 |
+
|
| 237 |
+
if output_attentions:
|
| 238 |
+
# this operation is a bit awkward, but it's required to
|
| 239 |
+
# make sure that attn_weights keeps its gradient.
|
| 240 |
+
# In order to do so, attn_weights have to be reshaped
|
| 241 |
+
# twice and have to be reused in the following
|
| 242 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 243 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 244 |
+
else:
|
| 245 |
+
attn_weights_reshaped = None
|
| 246 |
+
|
| 247 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 248 |
+
|
| 249 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 250 |
+
|
| 251 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 252 |
+
raise ValueError(
|
| 253 |
+
f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 254 |
+
f" {attn_output.size()}"
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 258 |
+
attn_output = attn_output.transpose(1, 2)
|
| 259 |
+
|
| 260 |
+
# Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
|
| 261 |
+
# partitioned across GPUs when using tensor-parallelism.
|
| 262 |
+
attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
|
| 263 |
+
|
| 264 |
+
attn_output = self.out_proj(attn_output)
|
| 265 |
+
|
| 266 |
+
return attn_output, attn_weights_reshaped, past_key_values
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class Speech2Text2DecoderLayer(GradientCheckpointingLayer):
|
| 270 |
+
def __init__(self, config: Speech2Text2Config):
|
| 271 |
+
super().__init__()
|
| 272 |
+
self.embed_dim = config.d_model
|
| 273 |
+
|
| 274 |
+
self.self_attn = Speech2Text2Attention(
|
| 275 |
+
embed_dim=self.embed_dim,
|
| 276 |
+
num_heads=config.decoder_attention_heads,
|
| 277 |
+
dropout=config.attention_dropout,
|
| 278 |
+
is_decoder=True,
|
| 279 |
+
)
|
| 280 |
+
self.dropout = config.dropout
|
| 281 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 282 |
+
self.activation_dropout = config.activation_dropout
|
| 283 |
+
|
| 284 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 285 |
+
|
| 286 |
+
if config.is_decoder:
|
| 287 |
+
self.encoder_attn = Speech2Text2Attention(
|
| 288 |
+
self.embed_dim,
|
| 289 |
+
config.decoder_attention_heads,
|
| 290 |
+
dropout=config.attention_dropout,
|
| 291 |
+
is_decoder=True,
|
| 292 |
+
)
|
| 293 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 294 |
+
|
| 295 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 296 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 297 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 298 |
+
|
| 299 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 300 |
+
def forward(
|
| 301 |
+
self,
|
| 302 |
+
hidden_states: torch.Tensor,
|
| 303 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 304 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 305 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 306 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 307 |
+
cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
|
| 308 |
+
past_key_values: Optional[Cache] = None,
|
| 309 |
+
output_attentions: Optional[bool] = False,
|
| 310 |
+
use_cache: Optional[bool] = True,
|
| 311 |
+
):
|
| 312 |
+
"""
|
| 313 |
+
Args:
|
| 314 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 315 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 316 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 317 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 318 |
+
cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 319 |
+
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
|
| 320 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 321 |
+
layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
|
| 322 |
+
`(encoder_attention_heads,)`.
|
| 323 |
+
cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
|
| 324 |
+
size *(decoder_attention_heads,)*.
|
| 325 |
+
past_key_values (`Tuple(torch.FloatTensor)`): cached past key and value projection states
|
| 326 |
+
output_attentions (`bool`, *optional*):
|
| 327 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 328 |
+
returned tensors for more detail.
|
| 329 |
+
"""
|
| 330 |
+
residual = hidden_states
|
| 331 |
+
|
| 332 |
+
# Self Attention
|
| 333 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 334 |
+
self_attn_past_key_value = past_key_values[:2] if past_key_values is not None else None
|
| 335 |
+
# add present self-attn cache to positions 1,2 of present_key_value tuple
|
| 336 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 337 |
+
hidden_states=hidden_states,
|
| 338 |
+
past_key_values=self_attn_past_key_value,
|
| 339 |
+
attention_mask=attention_mask,
|
| 340 |
+
layer_head_mask=layer_head_mask,
|
| 341 |
+
output_attentions=output_attentions,
|
| 342 |
+
)
|
| 343 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 344 |
+
hidden_states = residual + hidden_states
|
| 345 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 346 |
+
|
| 347 |
+
# Cross-Attention Block
|
| 348 |
+
cross_attn_present_key_value = None
|
| 349 |
+
cross_attn_weights = None
|
| 350 |
+
if encoder_hidden_states is not None:
|
| 351 |
+
residual = hidden_states
|
| 352 |
+
|
| 353 |
+
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
|
| 354 |
+
cross_attn_past_key_value = past_key_values[-2:] if past_key_values is not None else None
|
| 355 |
+
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
|
| 356 |
+
hidden_states=hidden_states,
|
| 357 |
+
key_value_states=encoder_hidden_states,
|
| 358 |
+
attention_mask=encoder_attention_mask,
|
| 359 |
+
layer_head_mask=cross_attn_layer_head_mask,
|
| 360 |
+
past_key_values=cross_attn_past_key_value,
|
| 361 |
+
output_attentions=output_attentions,
|
| 362 |
+
)
|
| 363 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 364 |
+
hidden_states = residual + hidden_states
|
| 365 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 366 |
+
|
| 367 |
+
# add cross-attn to positions 3,4 of present_key_value tuple
|
| 368 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 369 |
+
|
| 370 |
+
# Fully Connected
|
| 371 |
+
residual = hidden_states
|
| 372 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 373 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 374 |
+
hidden_states = self.fc2(hidden_states)
|
| 375 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 376 |
+
hidden_states = residual + hidden_states
|
| 377 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 378 |
+
|
| 379 |
+
outputs = (hidden_states,)
|
| 380 |
+
|
| 381 |
+
if output_attentions:
|
| 382 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 383 |
+
|
| 384 |
+
if use_cache:
|
| 385 |
+
outputs += (present_key_value,)
|
| 386 |
+
|
| 387 |
+
return outputs
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
class Speech2Text2PreTrainedModel(PreTrainedModel):
|
| 391 |
+
config: Speech2Text2Config
|
| 392 |
+
base_model_prefix = "model"
|
| 393 |
+
supports_gradient_checkpointing = True
|
| 394 |
+
|
| 395 |
+
def _init_weights(self, module):
|
| 396 |
+
std = self.config.init_std
|
| 397 |
+
if isinstance(module, (nn.Linear, nn.Conv1d)):
|
| 398 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 399 |
+
if module.bias is not None:
|
| 400 |
+
module.bias.data.zero_()
|
| 401 |
+
elif isinstance(module, nn.Embedding):
|
| 402 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 403 |
+
if module.padding_idx is not None:
|
| 404 |
+
module.weight.data[module.padding_idx].zero_()
|
| 405 |
+
elif isinstance(module, Speech2Text2SinusoidalPositionalEmbedding):
|
| 406 |
+
weight = module.get_embedding(*module.weight.shape, module.padding_idx)
|
| 407 |
+
weight = nn.Parameter(weight, requires_grad=False)
|
| 408 |
+
weight.detach_()
|
| 409 |
+
module.weight = weight
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
SPEECH_TO_TEXT_2_START_DOCSTRING = r"""
|
| 413 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 414 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 415 |
+
etc.)
|
| 416 |
+
|
| 417 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 418 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 419 |
+
and behavior.
|
| 420 |
+
|
| 421 |
+
Parameters:
|
| 422 |
+
config ([`Speech2Text2Config`]):
|
| 423 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 424 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 425 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 426 |
+
"""
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
class Speech2Text2Decoder(Speech2Text2PreTrainedModel):
|
| 430 |
+
"""
|
| 431 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`Speech2Text2DecoderLayer`]
|
| 432 |
+
|
| 433 |
+
Args:
|
| 434 |
+
config: Speech2Text2Config
|
| 435 |
+
embed_tokens (nn.Embedding): output embedding
|
| 436 |
+
"""
|
| 437 |
+
|
| 438 |
+
def __init__(self, config: Speech2Text2Config):
|
| 439 |
+
super().__init__(config)
|
| 440 |
+
self.dropout = config.dropout
|
| 441 |
+
self.layerdrop = config.decoder_layerdrop
|
| 442 |
+
self.padding_idx = config.pad_token_id
|
| 443 |
+
self.max_target_positions = config.max_target_positions
|
| 444 |
+
self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 445 |
+
|
| 446 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
|
| 447 |
+
|
| 448 |
+
self.embed_positions = Speech2Text2SinusoidalPositionalEmbedding(
|
| 449 |
+
self.max_target_positions,
|
| 450 |
+
config.d_model,
|
| 451 |
+
self.padding_idx,
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
self.layers = nn.ModuleList([Speech2Text2DecoderLayer(config) for _ in range(config.decoder_layers)])
|
| 455 |
+
|
| 456 |
+
self.gradient_checkpointing = False
|
| 457 |
+
# Initialize weights and apply final processing
|
| 458 |
+
self.post_init()
|
| 459 |
+
|
| 460 |
+
def forward(
|
| 461 |
+
self,
|
| 462 |
+
input_ids=None,
|
| 463 |
+
attention_mask=None,
|
| 464 |
+
encoder_hidden_states=None,
|
| 465 |
+
encoder_attention_mask=None,
|
| 466 |
+
head_mask=None,
|
| 467 |
+
cross_attn_head_mask=None,
|
| 468 |
+
past_key_values=None,
|
| 469 |
+
inputs_embeds=None,
|
| 470 |
+
use_cache=None,
|
| 471 |
+
output_attentions=None,
|
| 472 |
+
output_hidden_states=None,
|
| 473 |
+
return_dict=None,
|
| 474 |
+
):
|
| 475 |
+
r"""
|
| 476 |
+
Args:
|
| 477 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 478 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 479 |
+
provide it.
|
| 480 |
+
|
| 481 |
+
Indices can be obtained using [`Speech2Text2Tokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 482 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 483 |
+
|
| 484 |
+
[What are input IDs?](../glossary#input-ids)
|
| 485 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 486 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 487 |
+
|
| 488 |
+
- 1 for tokens that are **not masked**,
|
| 489 |
+
- 0 for tokens that are **masked**.
|
| 490 |
+
|
| 491 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 492 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 493 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 494 |
+
of the decoder.
|
| 495 |
+
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 496 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 497 |
+
selected in `[0, 1]`:
|
| 498 |
+
|
| 499 |
+
- 1 for tokens that are **not masked**,
|
| 500 |
+
- 0 for tokens that are **masked**.
|
| 501 |
+
|
| 502 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 503 |
+
head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 504 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 505 |
+
|
| 506 |
+
- 1 indicates the head is **not masked**,
|
| 507 |
+
- 0 indicates the head is **masked**.
|
| 508 |
+
|
| 509 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 510 |
+
Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention
|
| 511 |
+
on hidden heads. Mask values selected in `[0, 1]`:
|
| 512 |
+
|
| 513 |
+
- 1 indicates the head is **not masked**,
|
| 514 |
+
- 0 indicates the head is **masked**.
|
| 515 |
+
|
| 516 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 517 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 518 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
|
| 519 |
+
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 520 |
+
|
| 521 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 522 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 523 |
+
|
| 524 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 525 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 526 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 527 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 528 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 529 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 530 |
+
than the model's internal embedding lookup matrix.
|
| 531 |
+
output_attentions (`bool`, *optional*):
|
| 532 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 533 |
+
returned tensors for more detail.
|
| 534 |
+
output_hidden_states (`bool`, *optional*):
|
| 535 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 536 |
+
for more detail.
|
| 537 |
+
return_dict (`bool`, *optional*):
|
| 538 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 539 |
+
"""
|
| 540 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 541 |
+
output_hidden_states = (
|
| 542 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 543 |
+
)
|
| 544 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 545 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 546 |
+
|
| 547 |
+
# retrieve input_ids and inputs_embeds
|
| 548 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 549 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 550 |
+
elif input_ids is not None:
|
| 551 |
+
input_shape = input_ids.size()
|
| 552 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 553 |
+
elif inputs_embeds is not None:
|
| 554 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 555 |
+
else:
|
| 556 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 557 |
+
|
| 558 |
+
# past_key_values_length
|
| 559 |
+
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 560 |
+
|
| 561 |
+
if inputs_embeds is None:
|
| 562 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 563 |
+
|
| 564 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
| 565 |
+
attention_mask, input_shape, inputs_embeds, past_key_values_length
|
| 566 |
+
)
|
| 567 |
+
|
| 568 |
+
# expand encoder attention mask
|
| 569 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 570 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 571 |
+
encoder_attention_mask = _prepare_4d_attention_mask(
|
| 572 |
+
encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
# embed positions
|
| 576 |
+
positions = self.embed_positions(input_ids, past_key_values_length=past_key_values_length)
|
| 577 |
+
|
| 578 |
+
hidden_states = inputs_embeds + positions
|
| 579 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 580 |
+
|
| 581 |
+
if self.gradient_checkpointing and self.training:
|
| 582 |
+
if use_cache:
|
| 583 |
+
logger.warning_once(
|
| 584 |
+
"`use_cache = True` is incompatible with gradient checkpointing. Setting `use_cache = False`..."
|
| 585 |
+
)
|
| 586 |
+
use_cache = False
|
| 587 |
+
|
| 588 |
+
# decoder layers
|
| 589 |
+
all_hidden_states = () if output_hidden_states else None
|
| 590 |
+
all_self_attns = () if output_attentions else None
|
| 591 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 592 |
+
next_decoder_cache = () if use_cache else None
|
| 593 |
+
|
| 594 |
+
# check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
|
| 595 |
+
for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
|
| 596 |
+
if attn_mask is not None:
|
| 597 |
+
if attn_mask.size()[0] != (len(self.layers)):
|
| 598 |
+
raise ValueError(
|
| 599 |
+
f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
|
| 600 |
+
f" {head_mask.size()[0]}."
|
| 601 |
+
)
|
| 602 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 603 |
+
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
|
| 604 |
+
if output_hidden_states:
|
| 605 |
+
all_hidden_states += (hidden_states,)
|
| 606 |
+
if self.training:
|
| 607 |
+
dropout_probability = torch.rand([])
|
| 608 |
+
if dropout_probability < self.layerdrop:
|
| 609 |
+
continue
|
| 610 |
+
|
| 611 |
+
layer_outputs = decoder_layer(
|
| 612 |
+
hidden_states,
|
| 613 |
+
attention_mask=attention_mask,
|
| 614 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 615 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 616 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 617 |
+
cross_attn_layer_head_mask=(cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None),
|
| 618 |
+
past_key_values=past_key_values[idx] if past_key_values is not None else None,
|
| 619 |
+
output_attentions=output_attentions,
|
| 620 |
+
use_cache=use_cache,
|
| 621 |
+
)
|
| 622 |
+
hidden_states = layer_outputs[0]
|
| 623 |
+
|
| 624 |
+
if use_cache:
|
| 625 |
+
next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
|
| 626 |
+
|
| 627 |
+
if output_attentions:
|
| 628 |
+
all_self_attns += (layer_outputs[1],)
|
| 629 |
+
|
| 630 |
+
if encoder_hidden_states is not None:
|
| 631 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 632 |
+
|
| 633 |
+
# add hidden states from the last decoder layer
|
| 634 |
+
if output_hidden_states:
|
| 635 |
+
all_hidden_states += (hidden_states,)
|
| 636 |
+
|
| 637 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 638 |
+
if not return_dict:
|
| 639 |
+
return tuple(
|
| 640 |
+
v
|
| 641 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 642 |
+
if v is not None
|
| 643 |
+
)
|
| 644 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 645 |
+
last_hidden_state=hidden_states,
|
| 646 |
+
past_key_values=next_cache,
|
| 647 |
+
hidden_states=all_hidden_states,
|
| 648 |
+
attentions=all_self_attns,
|
| 649 |
+
cross_attentions=all_cross_attentions,
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
@add_start_docstrings(
|
| 654 |
+
"The Speech2Text2 Model with a language modeling head. Can be used for summarization.",
|
| 655 |
+
SPEECH_TO_TEXT_2_START_DOCSTRING,
|
| 656 |
+
)
|
| 657 |
+
class Speech2Text2DecoderWrapper(Speech2Text2PreTrainedModel):
|
| 658 |
+
"""
|
| 659 |
+
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
|
| 660 |
+
used in combination with the [`EncoderDecoderModel`] framework.
|
| 661 |
+
"""
|
| 662 |
+
|
| 663 |
+
def __init__(self, config):
|
| 664 |
+
super().__init__(config)
|
| 665 |
+
self.decoder = Speech2Text2Decoder(config)
|
| 666 |
+
|
| 667 |
+
def forward(self, *args, **kwargs):
|
| 668 |
+
return self.decoder(*args, **kwargs)
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
@add_start_docstrings(
|
| 672 |
+
"The Speech2Text2 Decoder with a language modeling head. Can be used as the decoder part of"
|
| 673 |
+
" [`EncoderDecoderModel`] and [`SpeechEncoderDecoder`].",
|
| 674 |
+
SPEECH_TO_TEXT_2_START_DOCSTRING,
|
| 675 |
+
)
|
| 676 |
+
class Speech2Text2ForCausalLM(Speech2Text2PreTrainedModel):
|
| 677 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 678 |
+
|
| 679 |
+
def __init__(self, config):
|
| 680 |
+
config.is_decoder = True
|
| 681 |
+
config.is_encoder_decoder = False
|
| 682 |
+
super().__init__(config)
|
| 683 |
+
self.model = Speech2Text2DecoderWrapper(config)
|
| 684 |
+
|
| 685 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 686 |
+
|
| 687 |
+
# Initialize weights and apply final processing
|
| 688 |
+
self.post_init()
|
| 689 |
+
|
| 690 |
+
def get_input_embeddings(self):
|
| 691 |
+
return self.model.decoder.embed_tokens
|
| 692 |
+
|
| 693 |
+
def set_input_embeddings(self, value):
|
| 694 |
+
self.model.decoder.embed_tokens = value
|
| 695 |
+
|
| 696 |
+
def set_decoder(self, decoder):
|
| 697 |
+
self.model.decoder = decoder
|
| 698 |
+
|
| 699 |
+
def get_decoder(self):
|
| 700 |
+
return self.model.decoder
|
| 701 |
+
|
| 702 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
|
| 703 |
+
def forward(
|
| 704 |
+
self,
|
| 705 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 706 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 707 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 708 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 709 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 710 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 711 |
+
past_key_values: Optional[Cache] = None,
|
| 712 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 713 |
+
labels: Optional[torch.LongTensor] = None,
|
| 714 |
+
use_cache: Optional[bool] = None,
|
| 715 |
+
output_attentions: Optional[bool] = None,
|
| 716 |
+
output_hidden_states: Optional[bool] = None,
|
| 717 |
+
return_dict: Optional[bool] = None,
|
| 718 |
+
) -> Union[tuple[torch.FloatTensor], CausalLMOutputWithCrossAttentions]:
|
| 719 |
+
r"""
|
| 720 |
+
Args:
|
| 721 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 722 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 723 |
+
provide it.
|
| 724 |
+
|
| 725 |
+
Indices can be obtained using [`Speech2Text2Tokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 726 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 727 |
+
|
| 728 |
+
[What are input IDs?](../glossary#input-ids)
|
| 729 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 730 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 731 |
+
|
| 732 |
+
- 1 for tokens that are **not masked**,
|
| 733 |
+
- 0 for tokens that are **masked**.
|
| 734 |
+
|
| 735 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 736 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 737 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 738 |
+
if the model is configured as a decoder.
|
| 739 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 740 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
|
| 741 |
+
in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 742 |
+
head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 743 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 744 |
+
|
| 745 |
+
- 1 indicates the head is **not masked**,
|
| 746 |
+
- 0 indicates the head is **masked**.
|
| 747 |
+
|
| 748 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 749 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 750 |
+
|
| 751 |
+
- 1 indicates the head is **not masked**,
|
| 752 |
+
- 0 indicates the head is **masked**.
|
| 753 |
+
|
| 754 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 755 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 756 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
|
| 757 |
+
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
|
| 758 |
+
tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
|
| 759 |
+
|
| 760 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 761 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 762 |
+
|
| 763 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 764 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 765 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 766 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 767 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 768 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 769 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 770 |
+
use_cache (`bool`, *optional*):
|
| 771 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 772 |
+
(see `past_key_values`).
|
| 773 |
+
|
| 774 |
+
- 1 for tokens that are **not masked**,
|
| 775 |
+
- 0 for tokens that are **masked**.
|
| 776 |
+
output_attentions (`bool`, *optional*):
|
| 777 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 778 |
+
returned tensors for more detail.
|
| 779 |
+
output_hidden_states (`bool`, *optional*):
|
| 780 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 781 |
+
for more detail.
|
| 782 |
+
return_dict (`bool`, *optional*):
|
| 783 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 784 |
+
|
| 785 |
+
Returns:
|
| 786 |
+
|
| 787 |
+
Example:
|
| 788 |
+
|
| 789 |
+
```python
|
| 790 |
+
>>> from transformers import (
|
| 791 |
+
... SpeechEncoderDecoderModel,
|
| 792 |
+
... Speech2Text2ForCausalLM,
|
| 793 |
+
... Wav2Vec2Model,
|
| 794 |
+
... Speech2Text2Config,
|
| 795 |
+
... Wav2Vec2Config,
|
| 796 |
+
... Wav2Vec2FeatureExtractor,
|
| 797 |
+
... Speech2Text2Tokenizer,
|
| 798 |
+
... )
|
| 799 |
+
>>> from datasets import load_dataset
|
| 800 |
+
|
| 801 |
+
>>> feature_extractor = Wav2Vec2FeatureExtractor()
|
| 802 |
+
>>> tokenizer = Speech2Text2Tokenizer.from_pretrained("facebook/s2t-wav2vec2-large-en-de")
|
| 803 |
+
|
| 804 |
+
>>> encoder = Wav2Vec2Model(Wav2Vec2Config())
|
| 805 |
+
>>> decoder = Speech2Text2ForCausalLM(Speech2Text2Config())
|
| 806 |
+
>>> # init random speech2text model
|
| 807 |
+
|
| 808 |
+
>>> model = SpeechEncoderDecoderModel(encoder=encoder, decoder=decoder)
|
| 809 |
+
>>> model.config.pad_token_id = tokenizer.pad_token_id
|
| 810 |
+
>>> model.config.decoder_start_token_id = tokenizer.bos_token_id
|
| 811 |
+
>>> # pre-process inputs and labels
|
| 812 |
+
|
| 813 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 814 |
+
>>> inputs = feature_extractor(
|
| 815 |
+
... ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], return_tensors="pt"
|
| 816 |
+
... )
|
| 817 |
+
>>> input_values = inputs.input_values
|
| 818 |
+
>>> decoder_input_ids = tokenizer(ds[0]["text"], return_tensors="pt").input_ids
|
| 819 |
+
>>> # compute loss
|
| 820 |
+
|
| 821 |
+
>>> loss = model(inputs=input_values, labels=decoder_input_ids).loss
|
| 822 |
+
>>> # backprop loss
|
| 823 |
+
|
| 824 |
+
>>> loss.backward() # doctest: +IGNORE_RESULT
|
| 825 |
+
```"""
|
| 826 |
+
|
| 827 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 828 |
+
output_hidden_states = (
|
| 829 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 830 |
+
)
|
| 831 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 832 |
+
|
| 833 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 834 |
+
outputs = self.model.decoder(
|
| 835 |
+
input_ids=input_ids,
|
| 836 |
+
attention_mask=attention_mask,
|
| 837 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 838 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 839 |
+
head_mask=head_mask,
|
| 840 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 841 |
+
past_key_values=past_key_values,
|
| 842 |
+
inputs_embeds=inputs_embeds,
|
| 843 |
+
use_cache=use_cache,
|
| 844 |
+
output_attentions=output_attentions,
|
| 845 |
+
output_hidden_states=output_hidden_states,
|
| 846 |
+
return_dict=return_dict,
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
logits = self.lm_head(outputs[0])
|
| 850 |
+
|
| 851 |
+
loss = None
|
| 852 |
+
if labels is not None:
|
| 853 |
+
loss_fct = CrossEntropyLoss()
|
| 854 |
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 855 |
+
|
| 856 |
+
if not return_dict:
|
| 857 |
+
output = (logits,) + outputs[1:]
|
| 858 |
+
return (loss,) + output if loss is not None else output
|
| 859 |
+
|
| 860 |
+
return CausalLMOutputWithCrossAttentions(
|
| 861 |
+
loss=loss,
|
| 862 |
+
logits=logits,
|
| 863 |
+
past_key_values=outputs.past_key_values,
|
| 864 |
+
hidden_states=outputs.hidden_states,
|
| 865 |
+
attentions=outputs.attentions,
|
| 866 |
+
cross_attentions=outputs.cross_attentions,
|
| 867 |
+
)
|
| 868 |
+
|
| 869 |
+
def prepare_inputs_for_generation(
|
| 870 |
+
self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
|
| 871 |
+
):
|
| 872 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
| 873 |
+
if attention_mask is None:
|
| 874 |
+
attention_mask = input_ids.new_ones(input_ids.shape)
|
| 875 |
+
|
| 876 |
+
if past_key_values:
|
| 877 |
+
past_length = past_key_values.get_seq_length()
|
| 878 |
+
|
| 879 |
+
# Some generation methods already pass only the last input ID
|
| 880 |
+
if input_ids.shape[1] > past_length:
|
| 881 |
+
remove_prefix_length = past_length
|
| 882 |
+
else:
|
| 883 |
+
# Default to old behavior: keep only final ID
|
| 884 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
| 885 |
+
|
| 886 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
| 887 |
+
# first step, decoder_cached_states are empty
|
| 888 |
+
return {
|
| 889 |
+
"input_ids": input_ids, # encoder_outputs is defined. input_ids not needed
|
| 890 |
+
"attention_mask": attention_mask,
|
| 891 |
+
"past_key_values": past_key_values,
|
| 892 |
+
"use_cache": use_cache,
|
| 893 |
+
}
|
| 894 |
+
|
| 895 |
+
@staticmethod
|
| 896 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 897 |
+
reordered_past = ()
|
| 898 |
+
for layer_past in past_key_values:
|
| 899 |
+
reordered_past += (
|
| 900 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 901 |
+
)
|
| 902 |
+
return reordered_past
|
| 903 |
+
|
| 904 |
+
|
| 905 |
+
__all__ = ["Speech2Text2ForCausalLM", "Speech2Text2PreTrainedModel"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/processing_speech_to_text_2.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Speech processor class for Speech2Text2
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import warnings
|
| 20 |
+
from contextlib import contextmanager
|
| 21 |
+
|
| 22 |
+
from ....processing_utils import ProcessorMixin
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Speech2Text2Processor(ProcessorMixin):
|
| 26 |
+
r"""
|
| 27 |
+
Constructs a Speech2Text2 processor which wraps a Speech2Text2 feature extractor and a Speech2Text2 tokenizer into
|
| 28 |
+
a single processor.
|
| 29 |
+
|
| 30 |
+
[`Speech2Text2Processor`] offers all the functionalities of [`AutoFeatureExtractor`] and [`Speech2Text2Tokenizer`].
|
| 31 |
+
See the [`~Speech2Text2Processor.__call__`] and [`~Speech2Text2Processor.decode`] for more information.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
feature_extractor (`AutoFeatureExtractor`):
|
| 35 |
+
An instance of [`AutoFeatureExtractor`]. The feature extractor is a required input.
|
| 36 |
+
tokenizer (`Speech2Text2Tokenizer`):
|
| 37 |
+
An instance of [`Speech2Text2Tokenizer`]. The tokenizer is a required input.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
feature_extractor_class = "AutoFeatureExtractor"
|
| 41 |
+
tokenizer_class = "Speech2Text2Tokenizer"
|
| 42 |
+
|
| 43 |
+
def __init__(self, feature_extractor, tokenizer):
|
| 44 |
+
super().__init__(feature_extractor, tokenizer)
|
| 45 |
+
self.current_processor = self.feature_extractor
|
| 46 |
+
self._in_target_context_manager = False
|
| 47 |
+
|
| 48 |
+
def __call__(self, *args, **kwargs):
|
| 49 |
+
"""
|
| 50 |
+
When used in normal mode, this method forwards all its arguments to AutoFeatureExtractor's
|
| 51 |
+
[`~AutoFeatureExtractor.__call__`] and returns its output. If used in the context
|
| 52 |
+
[`~Speech2Text2Processor.as_target_processor`] this method forwards all its arguments to
|
| 53 |
+
Speech2Text2Tokenizer's [`~Speech2Text2Tokenizer.__call__`]. Please refer to the docstring of the above two
|
| 54 |
+
methods for more information.
|
| 55 |
+
"""
|
| 56 |
+
# For backward compatibility
|
| 57 |
+
if self._in_target_context_manager:
|
| 58 |
+
return self.current_processor(*args, **kwargs)
|
| 59 |
+
|
| 60 |
+
if "raw_speech" in kwargs:
|
| 61 |
+
warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.")
|
| 62 |
+
audio = kwargs.pop("raw_speech")
|
| 63 |
+
else:
|
| 64 |
+
audio = kwargs.pop("audio", None)
|
| 65 |
+
sampling_rate = kwargs.pop("sampling_rate", None)
|
| 66 |
+
text = kwargs.pop("text", None)
|
| 67 |
+
if len(args) > 0:
|
| 68 |
+
audio = args[0]
|
| 69 |
+
args = args[1:]
|
| 70 |
+
|
| 71 |
+
if audio is None and text is None:
|
| 72 |
+
raise ValueError("You need to specify either an `audio` or `text` input to process.")
|
| 73 |
+
|
| 74 |
+
if audio is not None:
|
| 75 |
+
inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
|
| 76 |
+
if text is not None:
|
| 77 |
+
encodings = self.tokenizer(text, **kwargs)
|
| 78 |
+
|
| 79 |
+
if text is None:
|
| 80 |
+
return inputs
|
| 81 |
+
elif audio is None:
|
| 82 |
+
return encodings
|
| 83 |
+
else:
|
| 84 |
+
inputs["labels"] = encodings["input_ids"]
|
| 85 |
+
return inputs
|
| 86 |
+
|
| 87 |
+
@contextmanager
|
| 88 |
+
def as_target_processor(self):
|
| 89 |
+
"""
|
| 90 |
+
Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning
|
| 91 |
+
Speech2Text2.
|
| 92 |
+
"""
|
| 93 |
+
warnings.warn(
|
| 94 |
+
"`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
|
| 95 |
+
"labels by using the argument `text` of the regular `__call__` method (either in the same call as "
|
| 96 |
+
"your audio inputs, or in a separate call."
|
| 97 |
+
)
|
| 98 |
+
self._in_target_context_manager = True
|
| 99 |
+
self.current_processor = self.tokenizer
|
| 100 |
+
yield
|
| 101 |
+
self.current_processor = self.feature_extractor
|
| 102 |
+
self._in_target_context_manager = False
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
__all__ = ["Speech2Text2Processor"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/tokenization_speech_to_text_2.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization class for Speech2Text2."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
from ....tokenization_utils import PreTrainedTokenizer
|
| 22 |
+
from ....utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
VOCAB_FILES_NAMES = {
|
| 29 |
+
"vocab_file": "vocab.json",
|
| 30 |
+
"tokenizer_config_file": "tokenizer_config.json",
|
| 31 |
+
"merges_file": "merges.txt",
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
BPE_TOKEN_MERGES = "</w>"
|
| 36 |
+
BPE_TOKEN_VOCAB = "@@ "
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def get_pairs(word):
|
| 40 |
+
"""
|
| 41 |
+
Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
|
| 42 |
+
strings)
|
| 43 |
+
"""
|
| 44 |
+
pairs = set()
|
| 45 |
+
prev_char = word[0]
|
| 46 |
+
for char in word[1:]:
|
| 47 |
+
pairs.add((prev_char, char))
|
| 48 |
+
prev_char = char
|
| 49 |
+
return pairs
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# Speech2Text2 has no max input length
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class Speech2Text2Tokenizer(PreTrainedTokenizer):
|
| 56 |
+
"""
|
| 57 |
+
Constructs a Speech2Text2Tokenizer.
|
| 58 |
+
|
| 59 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains some of the main methods. Users should refer to
|
| 60 |
+
the superclass for more information regarding such methods.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
vocab_file (`str`):
|
| 64 |
+
File containing the vocabulary.
|
| 65 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 66 |
+
The beginning of sentence token.
|
| 67 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 68 |
+
The end of sentence token.
|
| 69 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 70 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 71 |
+
token instead.
|
| 72 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 73 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 74 |
+
|
| 75 |
+
**kwargs
|
| 76 |
+
Additional keyword arguments passed along to [`PreTrainedTokenizer`]
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 80 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 81 |
+
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
vocab_file,
|
| 85 |
+
bos_token="<s>",
|
| 86 |
+
pad_token="<pad>",
|
| 87 |
+
eos_token="</s>",
|
| 88 |
+
unk_token="<unk>",
|
| 89 |
+
do_lower_case=False,
|
| 90 |
+
merges_file=None,
|
| 91 |
+
**kwargs,
|
| 92 |
+
):
|
| 93 |
+
self.do_lower_case = do_lower_case
|
| 94 |
+
|
| 95 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
| 96 |
+
self.encoder = json.load(vocab_handle)
|
| 97 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 98 |
+
|
| 99 |
+
if merges_file is None:
|
| 100 |
+
logger.info(f"No merges files provided. {self.__class__.__name__} can only be used for decoding.")
|
| 101 |
+
|
| 102 |
+
self.bpe_ranks = None
|
| 103 |
+
self.cache = None
|
| 104 |
+
else:
|
| 105 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
| 106 |
+
merges = merges_handle.read().split("\n")[:-1]
|
| 107 |
+
|
| 108 |
+
merges = [tuple(merge.split()[:2]) for merge in merges]
|
| 109 |
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
| 110 |
+
self.cache = {}
|
| 111 |
+
super().__init__(
|
| 112 |
+
unk_token=unk_token,
|
| 113 |
+
bos_token=bos_token,
|
| 114 |
+
eos_token=eos_token,
|
| 115 |
+
pad_token=pad_token,
|
| 116 |
+
do_lower_case=do_lower_case,
|
| 117 |
+
**kwargs,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
@property
|
| 121 |
+
def vocab_size(self) -> int:
|
| 122 |
+
return len(self.decoder)
|
| 123 |
+
|
| 124 |
+
def get_vocab(self) -> dict:
|
| 125 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 126 |
+
|
| 127 |
+
def bpe(self, token):
|
| 128 |
+
word = tuple(token[:-1]) + (token[-1] + BPE_TOKEN_MERGES,)
|
| 129 |
+
if token in self.cache:
|
| 130 |
+
return self.cache[token]
|
| 131 |
+
pairs = get_pairs(word)
|
| 132 |
+
|
| 133 |
+
if not pairs:
|
| 134 |
+
return token
|
| 135 |
+
|
| 136 |
+
while True:
|
| 137 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 138 |
+
if bigram not in self.bpe_ranks:
|
| 139 |
+
break
|
| 140 |
+
first, second = bigram
|
| 141 |
+
new_word = []
|
| 142 |
+
i = 0
|
| 143 |
+
while i < len(word):
|
| 144 |
+
try:
|
| 145 |
+
j = word.index(first, i)
|
| 146 |
+
except ValueError:
|
| 147 |
+
new_word.extend(word[i:])
|
| 148 |
+
break
|
| 149 |
+
else:
|
| 150 |
+
new_word.extend(word[i:j])
|
| 151 |
+
i = j
|
| 152 |
+
|
| 153 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 154 |
+
new_word.append(first + second)
|
| 155 |
+
i += 2
|
| 156 |
+
else:
|
| 157 |
+
new_word.append(word[i])
|
| 158 |
+
i += 1
|
| 159 |
+
new_word = tuple(new_word)
|
| 160 |
+
word = new_word
|
| 161 |
+
if len(word) == 1:
|
| 162 |
+
break
|
| 163 |
+
else:
|
| 164 |
+
pairs = get_pairs(word)
|
| 165 |
+
word = " ".join(word)
|
| 166 |
+
if word == "\n " + BPE_TOKEN_MERGES:
|
| 167 |
+
word = "\n" + BPE_TOKEN_MERGES
|
| 168 |
+
|
| 169 |
+
if word.endswith(BPE_TOKEN_MERGES):
|
| 170 |
+
word = word.replace(BPE_TOKEN_MERGES, "")
|
| 171 |
+
|
| 172 |
+
word = word.replace(" ", BPE_TOKEN_VOCAB)
|
| 173 |
+
self.cache[token] = word
|
| 174 |
+
return word
|
| 175 |
+
|
| 176 |
+
def _tokenize(self, text):
|
| 177 |
+
"""Tokenize a string."""
|
| 178 |
+
|
| 179 |
+
if self.bpe_ranks is None:
|
| 180 |
+
raise ValueError(
|
| 181 |
+
"This tokenizer was instantiated without a `merges.txt` file, so"
|
| 182 |
+
" that it can only be used for decoding, not for encoding. "
|
| 183 |
+
"Make sure to provide `merges.txt` file at instantiation to enable "
|
| 184 |
+
"encoding."
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
if self.do_lower_case:
|
| 188 |
+
text = text.lower()
|
| 189 |
+
|
| 190 |
+
text = text.split()
|
| 191 |
+
|
| 192 |
+
split_tokens = []
|
| 193 |
+
for token in text:
|
| 194 |
+
if token:
|
| 195 |
+
split_tokens.extend(list(self.bpe(token).split(" ")))
|
| 196 |
+
|
| 197 |
+
return split_tokens
|
| 198 |
+
|
| 199 |
+
def _convert_token_to_id(self, token: str) -> int:
|
| 200 |
+
"""Converts a token (str) in an index (integer) using the vocab."""
|
| 201 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 202 |
+
|
| 203 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 204 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 205 |
+
result = self.decoder.get(index, self.unk_token)
|
| 206 |
+
return result
|
| 207 |
+
|
| 208 |
+
def convert_tokens_to_string(self, tokens: list[str]) -> str:
|
| 209 |
+
"""
|
| 210 |
+
Converts a list of output tokens into a single string.
|
| 211 |
+
"""
|
| 212 |
+
# combine tokens
|
| 213 |
+
string = " ".join(tokens)
|
| 214 |
+
|
| 215 |
+
# make sure @@ tokens are concatenated
|
| 216 |
+
string = "".join(string.split(BPE_TOKEN_VOCAB))
|
| 217 |
+
|
| 218 |
+
return string
|
| 219 |
+
|
| 220 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 221 |
+
if not os.path.isdir(save_directory):
|
| 222 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 223 |
+
return
|
| 224 |
+
vocab_file = os.path.join(
|
| 225 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 226 |
+
)
|
| 227 |
+
merges_file = os.path.join(
|
| 228 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 232 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
| 233 |
+
|
| 234 |
+
index = 0
|
| 235 |
+
if self.bpe_ranks is None:
|
| 236 |
+
return (vocab_file,)
|
| 237 |
+
|
| 238 |
+
with open(merges_file, "w", encoding="utf-8") as writer:
|
| 239 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
| 240 |
+
if index != token_index:
|
| 241 |
+
logger.warning(
|
| 242 |
+
f"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive."
|
| 243 |
+
" Please check that the tokenizer is not corrupted!"
|
| 244 |
+
)
|
| 245 |
+
index = token_index
|
| 246 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
| 247 |
+
index += 1
|
| 248 |
+
|
| 249 |
+
return (vocab_file, merges_file)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
__all__ = ["Speech2Text2Tokenizer"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tapex/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
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 .tokenization_tapex import *
|
| 22 |
+
else:
|
| 23 |
+
import sys
|
| 24 |
+
|
| 25 |
+
_file = globals()["__file__"]
|
| 26 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tapex/tokenization_tapex.py
ADDED
|
@@ -0,0 +1,1470 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes for TAPEX."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import random
|
| 20 |
+
from functools import lru_cache
|
| 21 |
+
from typing import Optional, Union
|
| 22 |
+
|
| 23 |
+
import regex as re
|
| 24 |
+
|
| 25 |
+
from ....file_utils import ExplicitEnum, PaddingStrategy, TensorType, add_end_docstrings, is_pandas_available
|
| 26 |
+
from ....tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 27 |
+
from ....tokenization_utils_base import ENCODE_KWARGS_DOCSTRING, BatchEncoding, TextInput, TruncationStrategy
|
| 28 |
+
from ....utils import logging
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if is_pandas_available():
|
| 32 |
+
import pandas as pd
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TapexTruncationStrategy(ExplicitEnum):
|
| 41 |
+
"""
|
| 42 |
+
Possible values for the `truncation` argument in [`~TapasTokenizer.__call__`]. Useful for tab-completion in an IDE.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
DROP_ROWS_TO_FIT = "drop_rows_to_fit"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
|
| 49 |
+
add_special_tokens (`bool`, *optional*, defaults to `True`):
|
| 50 |
+
Whether or not to encode the sequences with the special tokens relative to their model.
|
| 51 |
+
padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
|
| 52 |
+
Activates and controls padding. Accepts the following values:
|
| 53 |
+
|
| 54 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 55 |
+
sequence if provided).
|
| 56 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 57 |
+
acceptable input length for the model if that argument is not provided.
|
| 58 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 59 |
+
lengths).
|
| 60 |
+
truncation (`bool`, `str`, [`TapexTruncationStrategy`] or [`~tokenization_utils_base.TruncationStrategy`],
|
| 61 |
+
*optional*, defaults to `False`):
|
| 62 |
+
|
| 63 |
+
Activates and controls truncation. Accepts the following values:
|
| 64 |
+
|
| 65 |
+
- `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length` or to the
|
| 66 |
+
maximum acceptable input length for the model if that argument is not provided. This will truncate
|
| 67 |
+
row by row, removing rows from the table.
|
| 68 |
+
- `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
|
| 69 |
+
to the maximum acceptable input length for the model if that argument is not provided. This will
|
| 70 |
+
truncate token by token, removing a token from the longest sequence in the pair if a pair of
|
| 71 |
+
sequences (or a batch of pairs) is provided.
|
| 72 |
+
- `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
|
| 73 |
+
maximum acceptable input length for the model if that argument is not provided. This will only
|
| 74 |
+
truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 75 |
+
- `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
|
| 76 |
+
maximum acceptable input length for the model if that argument is not provided. This will only
|
| 77 |
+
truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 78 |
+
- `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
|
| 79 |
+
greater than the model maximum admissible input size).
|
| 80 |
+
max_length (`int`, *optional*):
|
| 81 |
+
Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to
|
| 82 |
+
`None`, this will use the predefined model maximum length if a maximum length is required by one of the
|
| 83 |
+
truncation/padding parameters. If the model has no specific maximum input length (like XLNet)
|
| 84 |
+
truncation/padding to a maximum length will be deactivated.
|
| 85 |
+
stride (`int`, *optional*, defaults to 0):
|
| 86 |
+
If set to a number along with `max_length`, the overflowing tokens returned when
|
| 87 |
+
`return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
|
| 88 |
+
returned to provide some overlap between truncated and overflowing sequences. The value of this
|
| 89 |
+
argument defines the number of overlapping tokens.
|
| 90 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 91 |
+
If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
|
| 92 |
+
the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
|
| 93 |
+
return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
|
| 94 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 95 |
+
|
| 96 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 97 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 98 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@lru_cache
|
| 103 |
+
def bytes_to_unicode():
|
| 104 |
+
"""
|
| 105 |
+
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
|
| 106 |
+
characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large #
|
| 107 |
+
of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset
|
| 108 |
+
you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe
|
| 109 |
+
vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
|
| 110 |
+
"""
|
| 111 |
+
bs = (
|
| 112 |
+
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
| 113 |
+
)
|
| 114 |
+
cs = bs[:]
|
| 115 |
+
n = 0
|
| 116 |
+
for b in range(2**8):
|
| 117 |
+
if b not in bs:
|
| 118 |
+
bs.append(b)
|
| 119 |
+
cs.append(2**8 + n)
|
| 120 |
+
n += 1
|
| 121 |
+
cs = [chr(n) for n in cs]
|
| 122 |
+
return dict(zip(bs, cs))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def get_pairs(word):
|
| 126 |
+
"""
|
| 127 |
+
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length
|
| 128 |
+
strings).
|
| 129 |
+
"""
|
| 130 |
+
pairs = set()
|
| 131 |
+
prev_char = word[0]
|
| 132 |
+
for char in word[1:]:
|
| 133 |
+
pairs.add((prev_char, char))
|
| 134 |
+
prev_char = char
|
| 135 |
+
return pairs
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class IndexedRowTableLinearize:
|
| 139 |
+
"""
|
| 140 |
+
FORMAT: col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
def process_table(self, table_content: dict):
|
| 144 |
+
"""
|
| 145 |
+
Given a table, TableLinearize aims at converting it into a flatten sequence with special symbols.
|
| 146 |
+
"""
|
| 147 |
+
assert "header" in table_content and "rows" in table_content, self.PROMPT_MESSAGE
|
| 148 |
+
# process header
|
| 149 |
+
table_str = self.process_header(table_content["header"]) + " "
|
| 150 |
+
# process rows
|
| 151 |
+
for i, row_example in enumerate(table_content["rows"]):
|
| 152 |
+
# NOTE: the row should start from row 1 instead of 0
|
| 153 |
+
table_str += self.process_row(row_example, row_index=i + 1) + " "
|
| 154 |
+
return table_str.strip()
|
| 155 |
+
|
| 156 |
+
def process_header(self, headers: list):
|
| 157 |
+
"""
|
| 158 |
+
Given a list of headers, TableLinearize aims at converting it into a flatten sequence with special symbols.
|
| 159 |
+
"""
|
| 160 |
+
return "col : " + " | ".join(headers)
|
| 161 |
+
|
| 162 |
+
def process_row(self, row: list, row_index: int):
|
| 163 |
+
"""
|
| 164 |
+
Given a row, TableLinearize aims at converting it into a flatten sequence with special symbols.
|
| 165 |
+
"""
|
| 166 |
+
row_str = ""
|
| 167 |
+
row_cell_values = []
|
| 168 |
+
for cell_value in row:
|
| 169 |
+
if isinstance(cell_value, int):
|
| 170 |
+
row_cell_values.append(str(cell_value))
|
| 171 |
+
else:
|
| 172 |
+
row_cell_values.append(cell_value)
|
| 173 |
+
row_str += " | ".join(row_cell_values)
|
| 174 |
+
return "row " + str(row_index) + " : " + row_str
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class TapexTokenizer(PreTrainedTokenizer):
|
| 178 |
+
r"""
|
| 179 |
+
Construct a TAPEX tokenizer. Based on byte-level Byte-Pair-Encoding (BPE).
|
| 180 |
+
|
| 181 |
+
This tokenizer can be used to flatten one or more table(s) and concatenate them with one or more related sentences
|
| 182 |
+
to be used by TAPEX models. The format that the TAPEX tokenizer creates is the following:
|
| 183 |
+
|
| 184 |
+
sentence col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...
|
| 185 |
+
|
| 186 |
+
The tokenizer supports a single table + single query, a single table and multiple queries (in which case the table
|
| 187 |
+
will be duplicated for every query), a single query and multiple tables (in which case the query will be duplicated
|
| 188 |
+
for every table), and multiple tables and queries. In other words, you can provide a batch of tables + questions to
|
| 189 |
+
the tokenizer for instance to prepare them for the model.
|
| 190 |
+
|
| 191 |
+
Tokenization itself is based on the BPE algorithm. It is identical to the one used by BART, RoBERTa and GPT-2.
|
| 192 |
+
|
| 193 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 194 |
+
this superclass for more information regarding those methods.
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
vocab_file (`str`):
|
| 198 |
+
Path to the vocabulary file.
|
| 199 |
+
merges_file (`str`):
|
| 200 |
+
Path to the merges file.
|
| 201 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 202 |
+
Whether or not to lowercase the input when tokenizing.
|
| 203 |
+
errors (`str`, *optional*, defaults to `"replace"`):
|
| 204 |
+
Paradigm to follow when decoding bytes to UTF-8. See
|
| 205 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
| 206 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 207 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 208 |
+
|
| 209 |
+
<Tip>
|
| 210 |
+
|
| 211 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 212 |
+
sequence. The token used is the `cls_token`.
|
| 213 |
+
|
| 214 |
+
</Tip>
|
| 215 |
+
|
| 216 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 217 |
+
The end of sequence token.
|
| 218 |
+
|
| 219 |
+
<Tip>
|
| 220 |
+
|
| 221 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 222 |
+
The token used is the `sep_token`.
|
| 223 |
+
|
| 224 |
+
</Tip>
|
| 225 |
+
|
| 226 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
| 227 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 228 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 229 |
+
token of a sequence built with special tokens.
|
| 230 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
| 231 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 232 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 233 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 234 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 235 |
+
token instead.
|
| 236 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 237 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 238 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 239 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 240 |
+
modeling. This is the token which the model will try to predict.
|
| 241 |
+
add_prefix_space (`bool`, *optional*, defaults to `False`):
|
| 242 |
+
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
|
| 243 |
+
other word. (BART tokenizer detect beginning of words by the preceding space).
|
| 244 |
+
max_cell_length (`int`, *optional*, defaults to 15):
|
| 245 |
+
Maximum number of characters per cell when linearizing a table. If this number is exceeded, truncation
|
| 246 |
+
takes place.
|
| 247 |
+
"""
|
| 248 |
+
|
| 249 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 250 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 251 |
+
|
| 252 |
+
def __init__(
|
| 253 |
+
self,
|
| 254 |
+
vocab_file,
|
| 255 |
+
merges_file,
|
| 256 |
+
do_lower_case=True,
|
| 257 |
+
errors="replace",
|
| 258 |
+
bos_token="<s>",
|
| 259 |
+
eos_token="</s>",
|
| 260 |
+
sep_token="</s>",
|
| 261 |
+
cls_token="<s>",
|
| 262 |
+
unk_token="<unk>",
|
| 263 |
+
pad_token="<pad>",
|
| 264 |
+
mask_token="<mask>",
|
| 265 |
+
add_prefix_space=False,
|
| 266 |
+
max_cell_length=15,
|
| 267 |
+
**kwargs,
|
| 268 |
+
):
|
| 269 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
| 270 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
| 271 |
+
sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
|
| 272 |
+
cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
|
| 273 |
+
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
| 274 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
| 275 |
+
|
| 276 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 277 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 278 |
+
|
| 279 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
| 280 |
+
self.encoder = json.load(vocab_handle)
|
| 281 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 282 |
+
self.errors = errors # how to handle errors in decoding
|
| 283 |
+
self.byte_encoder = bytes_to_unicode()
|
| 284 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
| 285 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
| 286 |
+
bpe_merges = merges_handle.read().split("\n")[1:-1]
|
| 287 |
+
bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
|
| 288 |
+
self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
|
| 289 |
+
self.cache = {}
|
| 290 |
+
self.add_prefix_space = add_prefix_space
|
| 291 |
+
self.do_lower_case = do_lower_case
|
| 292 |
+
|
| 293 |
+
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
|
| 294 |
+
self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
|
| 295 |
+
|
| 296 |
+
# additional properties
|
| 297 |
+
|
| 298 |
+
super().__init__(
|
| 299 |
+
vocab_file=vocab_file,
|
| 300 |
+
merges_file=merges_file,
|
| 301 |
+
do_lower_case=do_lower_case,
|
| 302 |
+
errors=errors,
|
| 303 |
+
bos_token=bos_token,
|
| 304 |
+
eos_token=eos_token,
|
| 305 |
+
unk_token=unk_token,
|
| 306 |
+
sep_token=sep_token,
|
| 307 |
+
cls_token=cls_token,
|
| 308 |
+
pad_token=pad_token,
|
| 309 |
+
mask_token=mask_token,
|
| 310 |
+
add_prefix_space=add_prefix_space,
|
| 311 |
+
max_cell_length=max_cell_length,
|
| 312 |
+
**kwargs,
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
self.max_cell_length = max_cell_length
|
| 316 |
+
self.table_linearize = IndexedRowTableLinearize()
|
| 317 |
+
|
| 318 |
+
def build_inputs_with_special_tokens(
|
| 319 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 320 |
+
) -> list[int]:
|
| 321 |
+
"""
|
| 322 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 323 |
+
adding special tokens. A TAPEX sequence has the following format:
|
| 324 |
+
- single sequence: `<s> X </s>`
|
| 325 |
+
- pair of sequences: `<s> A </s></s> B </s>`
|
| 326 |
+
|
| 327 |
+
Args:
|
| 328 |
+
token_ids_0 (`list[int]`):
|
| 329 |
+
List of IDs to which the special tokens will be added.
|
| 330 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 331 |
+
Optional second list of IDs for sequence pairs.
|
| 332 |
+
Returns:
|
| 333 |
+
`list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 334 |
+
"""
|
| 335 |
+
if token_ids_1 is None:
|
| 336 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 337 |
+
cls = [self.cls_token_id]
|
| 338 |
+
sep = [self.sep_token_id]
|
| 339 |
+
return cls + token_ids_0 + sep + sep + token_ids_1 + sep
|
| 340 |
+
|
| 341 |
+
def get_special_tokens_mask(
|
| 342 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
|
| 343 |
+
) -> list[int]:
|
| 344 |
+
"""
|
| 345 |
+
Args:
|
| 346 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 347 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 348 |
+
token_ids_0 (`list[int]`):
|
| 349 |
+
List of IDs.
|
| 350 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 351 |
+
Optional second list of IDs for sequence pairs.
|
| 352 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 353 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 354 |
+
Returns:
|
| 355 |
+
`list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 356 |
+
"""
|
| 357 |
+
if already_has_special_tokens:
|
| 358 |
+
return super().get_special_tokens_mask(
|
| 359 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
if token_ids_1 is None:
|
| 363 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 364 |
+
return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
|
| 365 |
+
|
| 366 |
+
def create_token_type_ids_from_sequences(
|
| 367 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 368 |
+
) -> list[int]:
|
| 369 |
+
"""
|
| 370 |
+
Args:
|
| 371 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. TAPEX does not:
|
| 372 |
+
make use of token type ids, therefore a list of zeros is returned.
|
| 373 |
+
token_ids_0 (`list[int]`):
|
| 374 |
+
List of IDs.
|
| 375 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 376 |
+
Optional second list of IDs for sequence pairs.
|
| 377 |
+
Returns:
|
| 378 |
+
`list[int]`: List of zeros.
|
| 379 |
+
"""
|
| 380 |
+
sep = [self.sep_token_id]
|
| 381 |
+
cls = [self.cls_token_id]
|
| 382 |
+
|
| 383 |
+
if token_ids_1 is None:
|
| 384 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 385 |
+
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
|
| 386 |
+
|
| 387 |
+
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
|
| 388 |
+
add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
|
| 389 |
+
if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
|
| 390 |
+
text = " " + text
|
| 391 |
+
return (text, kwargs)
|
| 392 |
+
|
| 393 |
+
@property
|
| 394 |
+
def vocab_size(self):
|
| 395 |
+
return len(self.encoder)
|
| 396 |
+
|
| 397 |
+
def get_vocab(self):
|
| 398 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 399 |
+
|
| 400 |
+
def bpe(self, token):
|
| 401 |
+
if token in self.cache:
|
| 402 |
+
return self.cache[token]
|
| 403 |
+
word = tuple(token)
|
| 404 |
+
pairs = get_pairs(word)
|
| 405 |
+
|
| 406 |
+
if not pairs:
|
| 407 |
+
return token
|
| 408 |
+
|
| 409 |
+
while True:
|
| 410 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 411 |
+
if bigram not in self.bpe_ranks:
|
| 412 |
+
break
|
| 413 |
+
first, second = bigram
|
| 414 |
+
new_word = []
|
| 415 |
+
i = 0
|
| 416 |
+
while i < len(word):
|
| 417 |
+
try:
|
| 418 |
+
j = word.index(first, i)
|
| 419 |
+
except ValueError:
|
| 420 |
+
new_word.extend(word[i:])
|
| 421 |
+
break
|
| 422 |
+
else:
|
| 423 |
+
new_word.extend(word[i:j])
|
| 424 |
+
i = j
|
| 425 |
+
|
| 426 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 427 |
+
new_word.append(first + second)
|
| 428 |
+
i += 2
|
| 429 |
+
else:
|
| 430 |
+
new_word.append(word[i])
|
| 431 |
+
i += 1
|
| 432 |
+
new_word = tuple(new_word)
|
| 433 |
+
word = new_word
|
| 434 |
+
if len(word) == 1:
|
| 435 |
+
break
|
| 436 |
+
else:
|
| 437 |
+
pairs = get_pairs(word)
|
| 438 |
+
word = " ".join(word)
|
| 439 |
+
self.cache[token] = word
|
| 440 |
+
return word
|
| 441 |
+
|
| 442 |
+
def _tokenize(self, text):
|
| 443 |
+
"""Tokenize a string."""
|
| 444 |
+
bpe_tokens = []
|
| 445 |
+
for token in re.findall(self.pat, text):
|
| 446 |
+
token = "".join(
|
| 447 |
+
self.byte_encoder[b] for b in token.encode("utf-8")
|
| 448 |
+
) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
|
| 449 |
+
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
|
| 450 |
+
return bpe_tokens
|
| 451 |
+
|
| 452 |
+
def _convert_token_to_id(self, token):
|
| 453 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 454 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 455 |
+
|
| 456 |
+
def _convert_id_to_token(self, index):
|
| 457 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 458 |
+
return self.decoder.get(index)
|
| 459 |
+
|
| 460 |
+
def convert_tokens_to_string(self, tokens):
|
| 461 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 462 |
+
text = "".join(tokens)
|
| 463 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
|
| 464 |
+
return text
|
| 465 |
+
|
| 466 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 467 |
+
if not os.path.isdir(save_directory):
|
| 468 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 469 |
+
return
|
| 470 |
+
vocab_file = os.path.join(
|
| 471 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 472 |
+
)
|
| 473 |
+
merge_file = os.path.join(
|
| 474 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 478 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
| 479 |
+
|
| 480 |
+
index = 0
|
| 481 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
| 482 |
+
writer.write("#version: 0.2\n")
|
| 483 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
| 484 |
+
if index != token_index:
|
| 485 |
+
logger.warning(
|
| 486 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
| 487 |
+
" Please check that the tokenizer is not corrupted!"
|
| 488 |
+
)
|
| 489 |
+
index = token_index
|
| 490 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
| 491 |
+
index += 1
|
| 492 |
+
|
| 493 |
+
return vocab_file, merge_file
|
| 494 |
+
|
| 495 |
+
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
|
| 496 |
+
def __call__(
|
| 497 |
+
self,
|
| 498 |
+
table: Union["pd.DataFrame", list["pd.DataFrame"]] = None,
|
| 499 |
+
query: Optional[Union[TextInput, list[TextInput]]] = None,
|
| 500 |
+
answer: Optional[Union[str, list[str]]] = None,
|
| 501 |
+
add_special_tokens: bool = True,
|
| 502 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 503 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
| 504 |
+
max_length: Optional[int] = None,
|
| 505 |
+
stride: int = 0,
|
| 506 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 507 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 508 |
+
return_token_type_ids: Optional[bool] = None,
|
| 509 |
+
return_attention_mask: Optional[bool] = None,
|
| 510 |
+
return_overflowing_tokens: bool = False,
|
| 511 |
+
return_special_tokens_mask: bool = False,
|
| 512 |
+
return_offsets_mapping: bool = False,
|
| 513 |
+
return_length: bool = False,
|
| 514 |
+
verbose: bool = True,
|
| 515 |
+
**kwargs,
|
| 516 |
+
) -> BatchEncoding:
|
| 517 |
+
"""
|
| 518 |
+
Main method to tokenize and prepare for the model one or several table-sequence pair(s).
|
| 519 |
+
|
| 520 |
+
Args:
|
| 521 |
+
table (`pd.DataFrame`, `list[pd.DataFrame]`):
|
| 522 |
+
Table(s) containing tabular data.
|
| 523 |
+
query (`str` or `list[str]`, *optional*):
|
| 524 |
+
Sentence or batch of sentences related to one or more table(s) to be encoded. Note that the number of
|
| 525 |
+
sentences must match the number of tables.
|
| 526 |
+
answer (`str` or `list[str]`, *optional*):
|
| 527 |
+
Optionally, the corresponding answer to the questions as supervision.
|
| 528 |
+
"""
|
| 529 |
+
|
| 530 |
+
if table is not None:
|
| 531 |
+
return self.source_call_func(
|
| 532 |
+
table=table,
|
| 533 |
+
query=query,
|
| 534 |
+
answer=answer,
|
| 535 |
+
add_special_tokens=add_special_tokens,
|
| 536 |
+
padding=padding,
|
| 537 |
+
truncation=truncation,
|
| 538 |
+
max_length=max_length,
|
| 539 |
+
stride=stride,
|
| 540 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 541 |
+
return_tensors=return_tensors,
|
| 542 |
+
return_token_type_ids=return_token_type_ids,
|
| 543 |
+
return_attention_mask=return_attention_mask,
|
| 544 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 545 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 546 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 547 |
+
return_length=return_length,
|
| 548 |
+
verbose=verbose,
|
| 549 |
+
**kwargs,
|
| 550 |
+
)
|
| 551 |
+
elif answer is not None:
|
| 552 |
+
return self.target_call_func(
|
| 553 |
+
answer=answer,
|
| 554 |
+
add_special_tokens=add_special_tokens,
|
| 555 |
+
padding=padding,
|
| 556 |
+
truncation=truncation,
|
| 557 |
+
max_length=max_length,
|
| 558 |
+
stride=stride,
|
| 559 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 560 |
+
return_tensors=return_tensors,
|
| 561 |
+
return_token_type_ids=return_token_type_ids,
|
| 562 |
+
return_attention_mask=return_attention_mask,
|
| 563 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 564 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 565 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 566 |
+
return_length=return_length,
|
| 567 |
+
verbose=verbose,
|
| 568 |
+
**kwargs,
|
| 569 |
+
)
|
| 570 |
+
else:
|
| 571 |
+
raise ValueError("You need to provide either a `table` or an `answer`.")
|
| 572 |
+
|
| 573 |
+
def source_call_func(
|
| 574 |
+
self,
|
| 575 |
+
table: Union["pd.DataFrame", list["pd.DataFrame"]],
|
| 576 |
+
query: Optional[Union[TextInput, list[TextInput]]] = None,
|
| 577 |
+
answer: Optional[Union[str, list[str]]] = None,
|
| 578 |
+
add_special_tokens: bool = True,
|
| 579 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 580 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
| 581 |
+
max_length: Optional[int] = None,
|
| 582 |
+
stride: int = 0,
|
| 583 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 584 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 585 |
+
return_token_type_ids: Optional[bool] = None,
|
| 586 |
+
return_attention_mask: Optional[bool] = None,
|
| 587 |
+
return_overflowing_tokens: bool = False,
|
| 588 |
+
return_special_tokens_mask: bool = False,
|
| 589 |
+
return_offsets_mapping: bool = False,
|
| 590 |
+
return_length: bool = False,
|
| 591 |
+
verbose: bool = True,
|
| 592 |
+
**kwargs,
|
| 593 |
+
) -> BatchEncoding:
|
| 594 |
+
# Input type checking for clearer error
|
| 595 |
+
valid_table = False
|
| 596 |
+
valid_query = False
|
| 597 |
+
|
| 598 |
+
# Check that table have a valid type
|
| 599 |
+
if isinstance(table, pd.DataFrame):
|
| 600 |
+
valid_table = True
|
| 601 |
+
elif isinstance(table, (list, tuple)) and isinstance(table[0], pd.DataFrame):
|
| 602 |
+
valid_table = True
|
| 603 |
+
|
| 604 |
+
# Check that query have a valid type
|
| 605 |
+
if query is None or isinstance(query, str):
|
| 606 |
+
valid_query = True
|
| 607 |
+
elif isinstance(query, (list, tuple)):
|
| 608 |
+
if len(query) == 0 or isinstance(query[0], str):
|
| 609 |
+
valid_query = True
|
| 610 |
+
|
| 611 |
+
if not valid_table:
|
| 612 |
+
raise ValueError(
|
| 613 |
+
"table input must of type `pd.DataFrame` (single example), `list[pd.DataFrame]` (batch of examples). "
|
| 614 |
+
)
|
| 615 |
+
if not valid_query:
|
| 616 |
+
raise ValueError("query input must of type `str` (single example), `list[str]` (batch of examples). ")
|
| 617 |
+
is_batched = isinstance(table, (list, tuple)) or isinstance(query, (list, tuple))
|
| 618 |
+
|
| 619 |
+
if is_batched:
|
| 620 |
+
return self.batch_encode_plus(
|
| 621 |
+
table=table,
|
| 622 |
+
query=query,
|
| 623 |
+
answer=answer,
|
| 624 |
+
add_special_tokens=add_special_tokens,
|
| 625 |
+
padding=padding,
|
| 626 |
+
truncation=truncation,
|
| 627 |
+
max_length=max_length,
|
| 628 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 629 |
+
return_tensors=return_tensors,
|
| 630 |
+
return_token_type_ids=return_token_type_ids,
|
| 631 |
+
return_attention_mask=return_attention_mask,
|
| 632 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 633 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 634 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 635 |
+
return_length=return_length,
|
| 636 |
+
verbose=verbose,
|
| 637 |
+
**kwargs,
|
| 638 |
+
)
|
| 639 |
+
else:
|
| 640 |
+
return self.encode_plus(
|
| 641 |
+
table=table,
|
| 642 |
+
query=query,
|
| 643 |
+
answer=answer,
|
| 644 |
+
add_special_tokens=add_special_tokens,
|
| 645 |
+
padding=padding,
|
| 646 |
+
truncation=truncation,
|
| 647 |
+
max_length=max_length,
|
| 648 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 649 |
+
return_tensors=return_tensors,
|
| 650 |
+
return_token_type_ids=return_token_type_ids,
|
| 651 |
+
return_attention_mask=return_attention_mask,
|
| 652 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 653 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 654 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 655 |
+
return_length=return_length,
|
| 656 |
+
verbose=verbose,
|
| 657 |
+
**kwargs,
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
|
| 661 |
+
def batch_encode_plus(
|
| 662 |
+
self,
|
| 663 |
+
table: Union["pd.DataFrame", list["pd.DataFrame"]],
|
| 664 |
+
query: Optional[list[TextInput]] = None,
|
| 665 |
+
answer: Optional[list[str]] = None,
|
| 666 |
+
add_special_tokens: bool = True,
|
| 667 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 668 |
+
truncation: Optional[Union[bool, str]] = None,
|
| 669 |
+
max_length: Optional[int] = None,
|
| 670 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 671 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 672 |
+
return_token_type_ids: Optional[bool] = None,
|
| 673 |
+
return_attention_mask: Optional[bool] = None,
|
| 674 |
+
return_overflowing_tokens: bool = False,
|
| 675 |
+
return_special_tokens_mask: bool = False,
|
| 676 |
+
return_offsets_mapping: bool = False,
|
| 677 |
+
return_length: bool = False,
|
| 678 |
+
verbose: bool = True,
|
| 679 |
+
**kwargs,
|
| 680 |
+
) -> BatchEncoding:
|
| 681 |
+
"""
|
| 682 |
+
<Tip warning={true}>
|
| 683 |
+
|
| 684 |
+
This method is deprecated, `__call__` should be used instead.
|
| 685 |
+
|
| 686 |
+
</Tip>
|
| 687 |
+
"""
|
| 688 |
+
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
|
| 689 |
+
padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
|
| 690 |
+
padding=padding,
|
| 691 |
+
truncation=truncation,
|
| 692 |
+
max_length=max_length,
|
| 693 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 694 |
+
verbose=verbose,
|
| 695 |
+
**kwargs,
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
return self._batch_encode_plus(
|
| 699 |
+
table=table,
|
| 700 |
+
query=query,
|
| 701 |
+
answer=answer,
|
| 702 |
+
add_special_tokens=add_special_tokens,
|
| 703 |
+
padding_strategy=padding_strategy,
|
| 704 |
+
truncation_strategy=truncation_strategy,
|
| 705 |
+
max_length=max_length,
|
| 706 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 707 |
+
return_tensors=return_tensors,
|
| 708 |
+
return_token_type_ids=return_token_type_ids,
|
| 709 |
+
return_attention_mask=return_attention_mask,
|
| 710 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 711 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 712 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 713 |
+
return_length=return_length,
|
| 714 |
+
verbose=verbose,
|
| 715 |
+
**kwargs,
|
| 716 |
+
)
|
| 717 |
+
|
| 718 |
+
def _batch_encode_plus(
|
| 719 |
+
self,
|
| 720 |
+
table: Union["pd.DataFrame", list["pd.DataFrame"]],
|
| 721 |
+
query: Optional[list[TextInput]] = None,
|
| 722 |
+
answer: Optional[list[str]] = None,
|
| 723 |
+
add_special_tokens: bool = True,
|
| 724 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 725 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 726 |
+
max_length: Optional[int] = None,
|
| 727 |
+
stride: int = 0,
|
| 728 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 729 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 730 |
+
return_token_type_ids: Optional[bool] = None,
|
| 731 |
+
return_attention_mask: Optional[bool] = None,
|
| 732 |
+
return_overflowing_tokens: bool = False,
|
| 733 |
+
return_special_tokens_mask: bool = False,
|
| 734 |
+
return_offsets_mapping: bool = False,
|
| 735 |
+
return_length: bool = False,
|
| 736 |
+
verbose: bool = True,
|
| 737 |
+
**kwargs,
|
| 738 |
+
) -> BatchEncoding:
|
| 739 |
+
if return_offsets_mapping:
|
| 740 |
+
raise NotImplementedError(
|
| 741 |
+
"return_offset_mapping is not available when using Python tokenizers. "
|
| 742 |
+
"To use this feature, change your tokenizer to one deriving from "
|
| 743 |
+
"transformers.PreTrainedTokenizerFast."
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
if isinstance(table, pd.DataFrame) and isinstance(query, (list, tuple)):
|
| 747 |
+
# single table, many queries case
|
| 748 |
+
# duplicate table for every query
|
| 749 |
+
table = [table] * len(query)
|
| 750 |
+
if isinstance(table, (list, tuple)) and isinstance(query, str):
|
| 751 |
+
# many tables, single query case
|
| 752 |
+
# duplicate query for every table
|
| 753 |
+
query = [query] * len(table)
|
| 754 |
+
|
| 755 |
+
batch_outputs = self._batch_prepare_for_model(
|
| 756 |
+
table=table,
|
| 757 |
+
query=query,
|
| 758 |
+
answer=answer,
|
| 759 |
+
add_special_tokens=add_special_tokens,
|
| 760 |
+
padding_strategy=padding_strategy,
|
| 761 |
+
truncation_strategy=truncation_strategy,
|
| 762 |
+
max_length=max_length,
|
| 763 |
+
stride=stride,
|
| 764 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 765 |
+
return_attention_mask=return_attention_mask,
|
| 766 |
+
return_token_type_ids=return_token_type_ids,
|
| 767 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 768 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 769 |
+
return_length=return_length,
|
| 770 |
+
return_tensors=return_tensors,
|
| 771 |
+
verbose=verbose,
|
| 772 |
+
)
|
| 773 |
+
|
| 774 |
+
return BatchEncoding(batch_outputs)
|
| 775 |
+
|
| 776 |
+
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
|
| 777 |
+
def _batch_prepare_for_model(
|
| 778 |
+
self,
|
| 779 |
+
table: Union["pd.DataFrame", list["pd.DataFrame"]],
|
| 780 |
+
query: Optional[Union[TextInput, list[TextInput]]] = None,
|
| 781 |
+
answer: Optional[Union[str, list[str]]] = None,
|
| 782 |
+
add_special_tokens: bool = True,
|
| 783 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 784 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 785 |
+
max_length: Optional[int] = None,
|
| 786 |
+
stride: int = 0,
|
| 787 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 788 |
+
return_tensors: Optional[str] = None,
|
| 789 |
+
return_token_type_ids: Optional[bool] = None,
|
| 790 |
+
return_attention_mask: Optional[bool] = None,
|
| 791 |
+
return_overflowing_tokens: bool = False,
|
| 792 |
+
return_special_tokens_mask: bool = False,
|
| 793 |
+
return_length: bool = False,
|
| 794 |
+
verbose: bool = True,
|
| 795 |
+
) -> BatchEncoding:
|
| 796 |
+
"""
|
| 797 |
+
This method adds special tokens, truncates sequences if overflowing while taking into account the special
|
| 798 |
+
tokens and manages a moving window (with user defined stride) for overflowing tokens.
|
| 799 |
+
"""
|
| 800 |
+
batch_outputs = {}
|
| 801 |
+
if answer is None:
|
| 802 |
+
answer = [None] * len(table)
|
| 803 |
+
for _table, _query, _answer in zip(table, query, answer):
|
| 804 |
+
text = self.prepare_table_query(
|
| 805 |
+
_table, _query, _answer, truncation_strategy=truncation_strategy, max_length=max_length
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
if self.do_lower_case:
|
| 809 |
+
text = text.lower()
|
| 810 |
+
|
| 811 |
+
tokens = self.tokenize(text)
|
| 812 |
+
outputs = self.prepare_for_model(
|
| 813 |
+
ids=self.convert_tokens_to_ids(tokens),
|
| 814 |
+
add_special_tokens=add_special_tokens,
|
| 815 |
+
padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards
|
| 816 |
+
truncation=truncation_strategy.value,
|
| 817 |
+
max_length=max_length,
|
| 818 |
+
stride=stride,
|
| 819 |
+
pad_to_multiple_of=None, # we pad in batch afterwards
|
| 820 |
+
return_attention_mask=False, # we pad in batch afterwards
|
| 821 |
+
return_token_type_ids=return_token_type_ids,
|
| 822 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 823 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 824 |
+
return_length=return_length,
|
| 825 |
+
return_tensors=None, # We convert the whole batch to tensors at the end
|
| 826 |
+
prepend_batch_axis=False,
|
| 827 |
+
verbose=verbose,
|
| 828 |
+
)
|
| 829 |
+
|
| 830 |
+
for key, value in outputs.items():
|
| 831 |
+
if key not in batch_outputs:
|
| 832 |
+
batch_outputs[key] = []
|
| 833 |
+
batch_outputs[key].append(value)
|
| 834 |
+
|
| 835 |
+
batch_outputs = self.pad(
|
| 836 |
+
batch_outputs,
|
| 837 |
+
padding=padding_strategy.value,
|
| 838 |
+
max_length=max_length,
|
| 839 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 840 |
+
return_attention_mask=return_attention_mask,
|
| 841 |
+
)
|
| 842 |
+
|
| 843 |
+
batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
|
| 844 |
+
|
| 845 |
+
return batch_outputs
|
| 846 |
+
|
| 847 |
+
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING)
|
| 848 |
+
def encode(
|
| 849 |
+
self,
|
| 850 |
+
table: "pd.DataFrame",
|
| 851 |
+
query: Optional[TextInput] = None,
|
| 852 |
+
answer: Optional[str] = None,
|
| 853 |
+
add_special_tokens: bool = True,
|
| 854 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 855 |
+
truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy] = None,
|
| 856 |
+
max_length: Optional[int] = None,
|
| 857 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 858 |
+
**kwargs,
|
| 859 |
+
) -> list[int]:
|
| 860 |
+
"""
|
| 861 |
+
Prepare a table, a string and possible answer for the model. This method does not return token type IDs,
|
| 862 |
+
attention masks, etc. which are necessary for the model to work correctly. Use this method if you want to build
|
| 863 |
+
your processing on your own, otherwise refer to `__call__`.
|
| 864 |
+
"""
|
| 865 |
+
encoded_inputs = self.encode_plus(
|
| 866 |
+
table,
|
| 867 |
+
query=query,
|
| 868 |
+
answer=answer,
|
| 869 |
+
add_special_tokens=add_special_tokens,
|
| 870 |
+
padding=padding,
|
| 871 |
+
truncation=truncation,
|
| 872 |
+
max_length=max_length,
|
| 873 |
+
return_tensors=return_tensors,
|
| 874 |
+
**kwargs,
|
| 875 |
+
)
|
| 876 |
+
|
| 877 |
+
return encoded_inputs["input_ids"]
|
| 878 |
+
|
| 879 |
+
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
|
| 880 |
+
def encode_plus(
|
| 881 |
+
self,
|
| 882 |
+
table: "pd.DataFrame",
|
| 883 |
+
query: Optional[TextInput] = None,
|
| 884 |
+
answer: Optional[str] = None,
|
| 885 |
+
add_special_tokens: bool = True,
|
| 886 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 887 |
+
truncation: Optional[Union[bool, str]] = None,
|
| 888 |
+
max_length: Optional[int] = None,
|
| 889 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 890 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 891 |
+
return_token_type_ids: Optional[bool] = None,
|
| 892 |
+
return_attention_mask: Optional[bool] = None,
|
| 893 |
+
return_special_tokens_mask: bool = False,
|
| 894 |
+
return_offsets_mapping: bool = False,
|
| 895 |
+
return_length: bool = False,
|
| 896 |
+
verbose: bool = True,
|
| 897 |
+
**kwargs,
|
| 898 |
+
) -> BatchEncoding:
|
| 899 |
+
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
|
| 900 |
+
padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
|
| 901 |
+
padding=padding,
|
| 902 |
+
truncation=truncation,
|
| 903 |
+
max_length=max_length,
|
| 904 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 905 |
+
verbose=verbose,
|
| 906 |
+
**kwargs,
|
| 907 |
+
)
|
| 908 |
+
|
| 909 |
+
return self._encode_plus(
|
| 910 |
+
table=table,
|
| 911 |
+
query=query,
|
| 912 |
+
answer=answer,
|
| 913 |
+
add_special_tokens=add_special_tokens,
|
| 914 |
+
padding_strategy=padding_strategy,
|
| 915 |
+
truncation_strategy=truncation_strategy,
|
| 916 |
+
max_length=max_length,
|
| 917 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 918 |
+
return_tensors=return_tensors,
|
| 919 |
+
return_token_type_ids=return_token_type_ids,
|
| 920 |
+
return_attention_mask=return_attention_mask,
|
| 921 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 922 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 923 |
+
return_length=return_length,
|
| 924 |
+
verbose=verbose,
|
| 925 |
+
**kwargs,
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
def _encode_plus(
|
| 929 |
+
self,
|
| 930 |
+
table: "pd.DataFrame",
|
| 931 |
+
query: Optional[TextInput] = None,
|
| 932 |
+
answer: Optional[str] = None,
|
| 933 |
+
add_special_tokens: bool = True,
|
| 934 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 935 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 936 |
+
max_length: Optional[int] = None,
|
| 937 |
+
stride: int = 0,
|
| 938 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 939 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 940 |
+
return_token_type_ids: Optional[bool] = None,
|
| 941 |
+
return_attention_mask: Optional[bool] = None,
|
| 942 |
+
return_overflowing_tokens: bool = False,
|
| 943 |
+
return_special_tokens_mask: bool = False,
|
| 944 |
+
return_offsets_mapping: bool = False,
|
| 945 |
+
return_length: bool = False,
|
| 946 |
+
verbose: bool = True,
|
| 947 |
+
**kwargs,
|
| 948 |
+
) -> BatchEncoding:
|
| 949 |
+
if return_offsets_mapping:
|
| 950 |
+
raise NotImplementedError(
|
| 951 |
+
"return_offset_mapping is not available when using Python tokenizers. "
|
| 952 |
+
"To use this feature, change your tokenizer to one deriving from "
|
| 953 |
+
"transformers.PreTrainedTokenizerFast. "
|
| 954 |
+
"More information on available tokenizers at "
|
| 955 |
+
"https://github.com/huggingface/transformers/pull/2674"
|
| 956 |
+
)
|
| 957 |
+
|
| 958 |
+
text = self.prepare_table_query(
|
| 959 |
+
table, query, answer, truncation_strategy=truncation_strategy, max_length=max_length
|
| 960 |
+
)
|
| 961 |
+
|
| 962 |
+
# if necessary, perform lower case
|
| 963 |
+
if self.do_lower_case:
|
| 964 |
+
text = text.lower()
|
| 965 |
+
|
| 966 |
+
tokens = self.tokenize(text)
|
| 967 |
+
|
| 968 |
+
return self.prepare_for_model(
|
| 969 |
+
ids=self.convert_tokens_to_ids(tokens),
|
| 970 |
+
add_special_tokens=add_special_tokens,
|
| 971 |
+
padding=padding_strategy.value,
|
| 972 |
+
truncation=truncation_strategy.value,
|
| 973 |
+
max_length=max_length,
|
| 974 |
+
stride=stride,
|
| 975 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 976 |
+
return_tensors=return_tensors,
|
| 977 |
+
prepend_batch_axis=True,
|
| 978 |
+
return_attention_mask=return_attention_mask,
|
| 979 |
+
return_token_type_ids=return_token_type_ids,
|
| 980 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 981 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 982 |
+
return_length=return_length,
|
| 983 |
+
verbose=verbose,
|
| 984 |
+
)
|
| 985 |
+
|
| 986 |
+
def target_call_func(
|
| 987 |
+
self,
|
| 988 |
+
answer: Union[str, list[str]],
|
| 989 |
+
add_special_tokens: bool = True,
|
| 990 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 991 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
| 992 |
+
max_length: Optional[int] = None,
|
| 993 |
+
stride: int = 0,
|
| 994 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 995 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 996 |
+
return_token_type_ids: Optional[bool] = None,
|
| 997 |
+
return_attention_mask: Optional[bool] = None,
|
| 998 |
+
return_overflowing_tokens: bool = False,
|
| 999 |
+
return_special_tokens_mask: bool = False,
|
| 1000 |
+
return_offsets_mapping: bool = False,
|
| 1001 |
+
return_length: bool = False,
|
| 1002 |
+
verbose: bool = True,
|
| 1003 |
+
**kwargs,
|
| 1004 |
+
) -> BatchEncoding:
|
| 1005 |
+
"""
|
| 1006 |
+
The method tokenizes and prepares the answer label for the model.
|
| 1007 |
+
|
| 1008 |
+
Args:
|
| 1009 |
+
answer (`str` or `list[str]`):
|
| 1010 |
+
Corresponding answer supervision to the queries for training the model.
|
| 1011 |
+
"""
|
| 1012 |
+
is_batched = isinstance(answer, (list, tuple))
|
| 1013 |
+
|
| 1014 |
+
if is_batched:
|
| 1015 |
+
return self.target_batch_encode_plus(
|
| 1016 |
+
answer=answer,
|
| 1017 |
+
add_special_tokens=add_special_tokens,
|
| 1018 |
+
padding=padding,
|
| 1019 |
+
truncation=truncation,
|
| 1020 |
+
max_length=max_length,
|
| 1021 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1022 |
+
return_tensors=return_tensors,
|
| 1023 |
+
return_token_type_ids=return_token_type_ids,
|
| 1024 |
+
return_attention_mask=return_attention_mask,
|
| 1025 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 1026 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 1027 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 1028 |
+
return_length=return_length,
|
| 1029 |
+
verbose=verbose,
|
| 1030 |
+
**kwargs,
|
| 1031 |
+
)
|
| 1032 |
+
else:
|
| 1033 |
+
return self.target_encode_plus(
|
| 1034 |
+
answer=answer,
|
| 1035 |
+
add_special_tokens=add_special_tokens,
|
| 1036 |
+
padding=padding,
|
| 1037 |
+
truncation=truncation,
|
| 1038 |
+
max_length=max_length,
|
| 1039 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1040 |
+
return_tensors=return_tensors,
|
| 1041 |
+
return_token_type_ids=return_token_type_ids,
|
| 1042 |
+
return_attention_mask=return_attention_mask,
|
| 1043 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 1044 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 1045 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 1046 |
+
return_length=return_length,
|
| 1047 |
+
verbose=verbose,
|
| 1048 |
+
**kwargs,
|
| 1049 |
+
)
|
| 1050 |
+
|
| 1051 |
+
def target_batch_encode_plus(
|
| 1052 |
+
self,
|
| 1053 |
+
answer: list[str],
|
| 1054 |
+
add_special_tokens: bool = True,
|
| 1055 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 1056 |
+
truncation: Optional[Union[bool, str]] = None,
|
| 1057 |
+
max_length: Optional[int] = None,
|
| 1058 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 1059 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 1060 |
+
return_token_type_ids: Optional[bool] = None,
|
| 1061 |
+
return_attention_mask: Optional[bool] = None,
|
| 1062 |
+
return_overflowing_tokens: bool = False,
|
| 1063 |
+
return_special_tokens_mask: bool = False,
|
| 1064 |
+
return_offsets_mapping: bool = False,
|
| 1065 |
+
return_length: bool = False,
|
| 1066 |
+
verbose: bool = True,
|
| 1067 |
+
**kwargs,
|
| 1068 |
+
) -> BatchEncoding:
|
| 1069 |
+
"""
|
| 1070 |
+
Prepare answer strings for the model.
|
| 1071 |
+
|
| 1072 |
+
Args:
|
| 1073 |
+
answer `list[str]`:
|
| 1074 |
+
Corresponding answer supervision to the queries for training the model.
|
| 1075 |
+
"""
|
| 1076 |
+
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
|
| 1077 |
+
padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
|
| 1078 |
+
padding=padding,
|
| 1079 |
+
truncation=truncation,
|
| 1080 |
+
max_length=max_length,
|
| 1081 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1082 |
+
verbose=verbose,
|
| 1083 |
+
**kwargs,
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
return self._target_batch_encode_plus(
|
| 1087 |
+
answer=answer,
|
| 1088 |
+
add_special_tokens=add_special_tokens,
|
| 1089 |
+
padding_strategy=padding_strategy,
|
| 1090 |
+
truncation_strategy=truncation_strategy,
|
| 1091 |
+
max_length=max_length,
|
| 1092 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1093 |
+
return_tensors=return_tensors,
|
| 1094 |
+
return_token_type_ids=return_token_type_ids,
|
| 1095 |
+
return_attention_mask=return_attention_mask,
|
| 1096 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 1097 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 1098 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 1099 |
+
return_length=return_length,
|
| 1100 |
+
verbose=verbose,
|
| 1101 |
+
**kwargs,
|
| 1102 |
+
)
|
| 1103 |
+
|
| 1104 |
+
def _target_batch_encode_plus(
|
| 1105 |
+
self,
|
| 1106 |
+
answer: list[str],
|
| 1107 |
+
add_special_tokens: bool = True,
|
| 1108 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 1109 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 1110 |
+
max_length: Optional[int] = None,
|
| 1111 |
+
stride: int = 0,
|
| 1112 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 1113 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 1114 |
+
return_token_type_ids: Optional[bool] = None,
|
| 1115 |
+
return_attention_mask: Optional[bool] = None,
|
| 1116 |
+
return_overflowing_tokens: bool = False,
|
| 1117 |
+
return_special_tokens_mask: bool = False,
|
| 1118 |
+
return_offsets_mapping: bool = False,
|
| 1119 |
+
return_length: bool = False,
|
| 1120 |
+
verbose: bool = True,
|
| 1121 |
+
**kwargs,
|
| 1122 |
+
) -> BatchEncoding:
|
| 1123 |
+
batch_outputs = {}
|
| 1124 |
+
for text in answer:
|
| 1125 |
+
if self.do_lower_case:
|
| 1126 |
+
text = text.lower()
|
| 1127 |
+
|
| 1128 |
+
tokens = self.tokenize(text)
|
| 1129 |
+
outputs = self.prepare_for_model(
|
| 1130 |
+
ids=self.convert_tokens_to_ids(tokens),
|
| 1131 |
+
add_special_tokens=add_special_tokens,
|
| 1132 |
+
padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards
|
| 1133 |
+
truncation=truncation_strategy.value,
|
| 1134 |
+
max_length=max_length,
|
| 1135 |
+
stride=stride,
|
| 1136 |
+
pad_to_multiple_of=None, # we pad in batch afterwards
|
| 1137 |
+
return_attention_mask=False, # we pad in batch afterwards
|
| 1138 |
+
return_token_type_ids=return_token_type_ids,
|
| 1139 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 1140 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 1141 |
+
return_length=return_length,
|
| 1142 |
+
return_tensors=None, # We convert the whole batch to tensors at the end
|
| 1143 |
+
prepend_batch_axis=False,
|
| 1144 |
+
verbose=verbose,
|
| 1145 |
+
)
|
| 1146 |
+
|
| 1147 |
+
for key, value in outputs.items():
|
| 1148 |
+
if key not in batch_outputs:
|
| 1149 |
+
batch_outputs[key] = []
|
| 1150 |
+
batch_outputs[key].append(value)
|
| 1151 |
+
|
| 1152 |
+
batch_outputs = self.pad(
|
| 1153 |
+
batch_outputs,
|
| 1154 |
+
padding=padding_strategy.value,
|
| 1155 |
+
max_length=max_length,
|
| 1156 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1157 |
+
return_attention_mask=return_attention_mask,
|
| 1158 |
+
)
|
| 1159 |
+
|
| 1160 |
+
batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
|
| 1161 |
+
|
| 1162 |
+
return BatchEncoding(batch_outputs)
|
| 1163 |
+
|
| 1164 |
+
def target_encode(
|
| 1165 |
+
self,
|
| 1166 |
+
answer: str,
|
| 1167 |
+
add_special_tokens: bool = True,
|
| 1168 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 1169 |
+
truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy] = None,
|
| 1170 |
+
max_length: Optional[int] = None,
|
| 1171 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 1172 |
+
**kwargs,
|
| 1173 |
+
) -> list[int]:
|
| 1174 |
+
"""
|
| 1175 |
+
Prepare the answer string for the model. This method does not return token type IDs, attention masks, etc.
|
| 1176 |
+
which are necessary for the model to work correctly. Use this method if you want to build your processing on
|
| 1177 |
+
your own, otherwise refer to `__call__`.
|
| 1178 |
+
|
| 1179 |
+
Args:
|
| 1180 |
+
answer `str`:
|
| 1181 |
+
Corresponding answer supervision to the queries for training the model
|
| 1182 |
+
"""
|
| 1183 |
+
encoded_outputs = self.target_encode_plus(
|
| 1184 |
+
answer=answer,
|
| 1185 |
+
add_special_tokens=add_special_tokens,
|
| 1186 |
+
padding=padding,
|
| 1187 |
+
truncation=truncation,
|
| 1188 |
+
max_length=max_length,
|
| 1189 |
+
return_tensors=return_tensors,
|
| 1190 |
+
**kwargs,
|
| 1191 |
+
)
|
| 1192 |
+
|
| 1193 |
+
return encoded_outputs["input_ids"]
|
| 1194 |
+
|
| 1195 |
+
def target_encode_plus(
|
| 1196 |
+
self,
|
| 1197 |
+
answer: str,
|
| 1198 |
+
add_special_tokens: bool = True,
|
| 1199 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 1200 |
+
truncation: Optional[Union[bool, str]] = None,
|
| 1201 |
+
max_length: Optional[int] = None,
|
| 1202 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 1203 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 1204 |
+
return_token_type_ids: Optional[bool] = None,
|
| 1205 |
+
return_attention_mask: Optional[bool] = None,
|
| 1206 |
+
return_special_tokens_mask: bool = False,
|
| 1207 |
+
return_offsets_mapping: bool = False,
|
| 1208 |
+
return_length: bool = False,
|
| 1209 |
+
verbose: bool = True,
|
| 1210 |
+
**kwargs,
|
| 1211 |
+
) -> BatchEncoding:
|
| 1212 |
+
"""
|
| 1213 |
+
Prepare a answer string for the model.
|
| 1214 |
+
|
| 1215 |
+
Args:
|
| 1216 |
+
answer `str`:
|
| 1217 |
+
Corresponding answer supervision to the queries for training the model.
|
| 1218 |
+
"""
|
| 1219 |
+
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
|
| 1220 |
+
padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
|
| 1221 |
+
padding=padding,
|
| 1222 |
+
truncation=truncation,
|
| 1223 |
+
max_length=max_length,
|
| 1224 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1225 |
+
verbose=verbose,
|
| 1226 |
+
**kwargs,
|
| 1227 |
+
)
|
| 1228 |
+
|
| 1229 |
+
return self._target_encode_plus(
|
| 1230 |
+
answer=answer,
|
| 1231 |
+
add_special_tokens=add_special_tokens,
|
| 1232 |
+
padding_strategy=padding_strategy,
|
| 1233 |
+
truncation_strategy=truncation_strategy,
|
| 1234 |
+
max_length=max_length,
|
| 1235 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1236 |
+
return_tensors=return_tensors,
|
| 1237 |
+
return_token_type_ids=return_token_type_ids,
|
| 1238 |
+
return_attention_mask=return_attention_mask,
|
| 1239 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 1240 |
+
return_offsets_mapping=return_offsets_mapping,
|
| 1241 |
+
return_length=return_length,
|
| 1242 |
+
verbose=verbose,
|
| 1243 |
+
**kwargs,
|
| 1244 |
+
)
|
| 1245 |
+
|
| 1246 |
+
def _target_encode_plus(
|
| 1247 |
+
self,
|
| 1248 |
+
answer: str,
|
| 1249 |
+
add_special_tokens: bool = True,
|
| 1250 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 1251 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
| 1252 |
+
max_length: Optional[int] = None,
|
| 1253 |
+
stride: int = 0,
|
| 1254 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 1255 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 1256 |
+
return_token_type_ids: Optional[bool] = None,
|
| 1257 |
+
return_attention_mask: Optional[bool] = None,
|
| 1258 |
+
return_overflowing_tokens: bool = False,
|
| 1259 |
+
return_special_tokens_mask: bool = False,
|
| 1260 |
+
return_offsets_mapping: bool = False,
|
| 1261 |
+
return_length: bool = False,
|
| 1262 |
+
verbose: bool = True,
|
| 1263 |
+
**kwargs,
|
| 1264 |
+
) -> BatchEncoding:
|
| 1265 |
+
if return_offsets_mapping:
|
| 1266 |
+
raise NotImplementedError(
|
| 1267 |
+
"return_offset_mapping is not available when using Python tokenizers. "
|
| 1268 |
+
"To use this feature, change your tokenizer to one deriving from "
|
| 1269 |
+
"transformers.PreTrainedTokenizerFast. "
|
| 1270 |
+
"More information on available tokenizers at "
|
| 1271 |
+
"https://github.com/huggingface/transformers/pull/2674"
|
| 1272 |
+
)
|
| 1273 |
+
|
| 1274 |
+
text = answer
|
| 1275 |
+
|
| 1276 |
+
# if necessary, perform lower case
|
| 1277 |
+
if self.do_lower_case:
|
| 1278 |
+
text = text.lower()
|
| 1279 |
+
|
| 1280 |
+
tokens = self.tokenize(text)
|
| 1281 |
+
|
| 1282 |
+
return self.prepare_for_model(
|
| 1283 |
+
ids=self.convert_tokens_to_ids(tokens),
|
| 1284 |
+
add_special_tokens=add_special_tokens,
|
| 1285 |
+
padding=padding_strategy.value,
|
| 1286 |
+
truncation=truncation_strategy.value,
|
| 1287 |
+
max_length=max_length,
|
| 1288 |
+
stride=stride,
|
| 1289 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 1290 |
+
return_tensors=return_tensors,
|
| 1291 |
+
prepend_batch_axis=True,
|
| 1292 |
+
return_attention_mask=return_attention_mask,
|
| 1293 |
+
return_token_type_ids=return_token_type_ids,
|
| 1294 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
| 1295 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
| 1296 |
+
return_length=return_length,
|
| 1297 |
+
verbose=verbose,
|
| 1298 |
+
)
|
| 1299 |
+
|
| 1300 |
+
def prepare_table_query(
|
| 1301 |
+
self,
|
| 1302 |
+
table,
|
| 1303 |
+
query,
|
| 1304 |
+
answer=None,
|
| 1305 |
+
truncation_strategy=Union[str, TruncationStrategy, TapexTruncationStrategy],
|
| 1306 |
+
max_length=None,
|
| 1307 |
+
):
|
| 1308 |
+
"""
|
| 1309 |
+
This method can be used to linearize a table and add a corresponding query.
|
| 1310 |
+
|
| 1311 |
+
Optionally, it also handles truncation of the table (cells).
|
| 1312 |
+
|
| 1313 |
+
An answer can be provided for more precise truncation.
|
| 1314 |
+
"""
|
| 1315 |
+
if not table.empty:
|
| 1316 |
+
# step 1: create table dictionary
|
| 1317 |
+
table_content = {"header": list(table.columns), "rows": [list(row.values) for i, row in table.iterrows()]}
|
| 1318 |
+
|
| 1319 |
+
# step 2: modify table internally
|
| 1320 |
+
# always truncate table cells based on self.max_cell_length
|
| 1321 |
+
# optionally truncate rows if truncation_strategy is set to it
|
| 1322 |
+
self.truncate_table_cells(table_content, query, answer)
|
| 1323 |
+
if truncation_strategy == TapexTruncationStrategy.DROP_ROWS_TO_FIT:
|
| 1324 |
+
self.truncate_table_rows(table_content, query, answer, max_length=max_length)
|
| 1325 |
+
|
| 1326 |
+
# step 3: linearize table
|
| 1327 |
+
linear_table = self.table_linearize.process_table(table_content)
|
| 1328 |
+
else:
|
| 1329 |
+
linear_table = ""
|
| 1330 |
+
|
| 1331 |
+
if linear_table == "":
|
| 1332 |
+
logger.warning(
|
| 1333 |
+
"You provide an empty table, or all cells contain much tokens (e.g., >= 1024 tokens). "
|
| 1334 |
+
+ f"Please carefully check the corresponding table with the query : {query}."
|
| 1335 |
+
)
|
| 1336 |
+
if query == "":
|
| 1337 |
+
logger.warning("You provide nothing to query with respect to the table.")
|
| 1338 |
+
# step 4: concatenate query with linear_table
|
| 1339 |
+
separator = " " if query and linear_table else ""
|
| 1340 |
+
joint_input = (query + separator + linear_table) if query else linear_table
|
| 1341 |
+
|
| 1342 |
+
return joint_input
|
| 1343 |
+
|
| 1344 |
+
def truncate_table_cells(self, table_content: dict, question: str, answer: list):
|
| 1345 |
+
# TODO (Qian): is it possible to revert the original cell if it is in the final answer?
|
| 1346 |
+
cell_mapping = {}
|
| 1347 |
+
for row in table_content["rows"]:
|
| 1348 |
+
for i, cell in enumerate(row):
|
| 1349 |
+
truncate_cell = self.truncate_cell(cell)
|
| 1350 |
+
if truncate_cell is not None:
|
| 1351 |
+
cell_mapping[cell] = truncate_cell
|
| 1352 |
+
row[i] = truncate_cell
|
| 1353 |
+
|
| 1354 |
+
# modify the answer list
|
| 1355 |
+
if answer is not None:
|
| 1356 |
+
for i, case in enumerate(answer):
|
| 1357 |
+
if case in cell_mapping:
|
| 1358 |
+
answer[i] = cell_mapping[case]
|
| 1359 |
+
|
| 1360 |
+
def truncate_cell(self, cell_value):
|
| 1361 |
+
# do not process on these cases
|
| 1362 |
+
if isinstance(cell_value, (int, float)):
|
| 1363 |
+
return cell_value
|
| 1364 |
+
if cell_value.strip() != "":
|
| 1365 |
+
try_tokens = self.tokenize(cell_value)
|
| 1366 |
+
if len(try_tokens) >= self.max_cell_length:
|
| 1367 |
+
retain_tokens = try_tokens[: self.max_cell_length]
|
| 1368 |
+
retain_cell_value = self.convert_tokens_to_string(retain_tokens)
|
| 1369 |
+
return retain_cell_value
|
| 1370 |
+
else:
|
| 1371 |
+
return None
|
| 1372 |
+
else:
|
| 1373 |
+
return cell_value
|
| 1374 |
+
|
| 1375 |
+
def truncate_table_rows(
|
| 1376 |
+
self, table_content: dict, question: str, answer: Optional[Union[str, list[str]]] = None, max_length=None
|
| 1377 |
+
):
|
| 1378 |
+
"""
|
| 1379 |
+
Args:
|
| 1380 |
+
table_content:
|
| 1381 |
+
{"header": xxx, "rows": xxx, "id" (Optionally): xxx}
|
| 1382 |
+
|
| 1383 |
+
question:
|
| 1384 |
+
natural language sentence
|
| 1385 |
+
|
| 1386 |
+
answer:
|
| 1387 |
+
if for training, is the supervision; otherwise will be empty
|
| 1388 |
+
"""
|
| 1389 |
+
delete_ratio, remain_token_len = self.estimate_delete_ratio(table_content, question, max_length)
|
| 1390 |
+
# randomly delete unrelated rows
|
| 1391 |
+
self.delete_unrelated_rows(table_content, question, answer, delete_ratio)
|
| 1392 |
+
# guarantee the result < max_length
|
| 1393 |
+
maximum_keep_rows = 0
|
| 1394 |
+
for ind, row_example in enumerate(table_content["rows"]):
|
| 1395 |
+
value_string = self.table_linearize.process_row(row_example, ind + 1)
|
| 1396 |
+
value_token_len = len(self.tokenize(value_string))
|
| 1397 |
+
# over the size limit, and take action
|
| 1398 |
+
if value_token_len > remain_token_len:
|
| 1399 |
+
break
|
| 1400 |
+
remain_token_len -= value_token_len
|
| 1401 |
+
maximum_keep_rows += 1
|
| 1402 |
+
del table_content["rows"][maximum_keep_rows:]
|
| 1403 |
+
|
| 1404 |
+
def estimate_delete_ratio(self, table_content: dict, question: str, max_length=None):
|
| 1405 |
+
if "header" not in table_content or "rows" not in table_content:
|
| 1406 |
+
raise ValueError("The table content should contain both 'header' and 'rows' keys.")
|
| 1407 |
+
# calculate the tokens of header, special tokens will only be pre-prepended into question
|
| 1408 |
+
question_tokens = self.tokenize(question, add_special_tokens=True)
|
| 1409 |
+
# calculate the tokens of header
|
| 1410 |
+
header_string = self.table_linearize.process_header(table_content["header"])
|
| 1411 |
+
header_tokens = self.tokenize(header_string, add_special_tokens=False)
|
| 1412 |
+
# split all cell values into tokens and see how many can be accommodated
|
| 1413 |
+
used_token_len = len(question_tokens) + len(header_tokens)
|
| 1414 |
+
# remaining token space for rows
|
| 1415 |
+
remain_token_len = max_length - used_token_len
|
| 1416 |
+
|
| 1417 |
+
value_string = ""
|
| 1418 |
+
for _, row_example in enumerate(table_content["rows"]):
|
| 1419 |
+
# use a general index to roughly estimate the overall token len
|
| 1420 |
+
value_string += self.table_linearize.process_row(row_example, 100) + " "
|
| 1421 |
+
value_token_len = len(self.tokenize(value_string))
|
| 1422 |
+
|
| 1423 |
+
if value_token_len < remain_token_len:
|
| 1424 |
+
# no row will be deleted
|
| 1425 |
+
return 0.0, remain_token_len
|
| 1426 |
+
else:
|
| 1427 |
+
# calc a roughly delete rate
|
| 1428 |
+
return 1.0 - remain_token_len / value_token_len, remain_token_len
|
| 1429 |
+
|
| 1430 |
+
def delete_unrelated_rows(self, table_content: dict, question: str, answer: list, delete_ratio: float):
|
| 1431 |
+
"""
|
| 1432 |
+
The argument answer is used only during training.
|
| 1433 |
+
"""
|
| 1434 |
+
truncated_unrelated_indices = []
|
| 1435 |
+
related_indices = []
|
| 1436 |
+
if answer is None or len(answer) == 0:
|
| 1437 |
+
answer_set = set()
|
| 1438 |
+
else:
|
| 1439 |
+
answer_set = {ans_ex.lower() for ans_ex in answer}
|
| 1440 |
+
# add question key words into answer set
|
| 1441 |
+
if question is not None:
|
| 1442 |
+
answer_set.update(question.split())
|
| 1443 |
+
question_set = set(question.strip("?!.,").split(" "))
|
| 1444 |
+
row_max_len = len(table_content["rows"])
|
| 1445 |
+
for _row_idx, row in enumerate(table_content["rows"]):
|
| 1446 |
+
lower_row = {str(cell).lower() for cell in row}
|
| 1447 |
+
if len(lower_row & answer_set) == 0 and len(lower_row & question_set) == 0:
|
| 1448 |
+
truncated_unrelated_indices.append(_row_idx)
|
| 1449 |
+
else:
|
| 1450 |
+
# add neighbours to preserve information aggressively
|
| 1451 |
+
related_indices.extend([_row_idx - 2, _row_idx - 1, _row_idx, _row_idx + 1, _row_idx + 2])
|
| 1452 |
+
|
| 1453 |
+
# remove the neighbours
|
| 1454 |
+
truncated_unrelated_indices = [
|
| 1455 |
+
_row_idx for _row_idx in truncated_unrelated_indices if _row_idx not in related_indices
|
| 1456 |
+
]
|
| 1457 |
+
# select some cases to drop
|
| 1458 |
+
drop_items = min(len(truncated_unrelated_indices), int(len(table_content["rows"]) * delete_ratio))
|
| 1459 |
+
drop_row_indices = random.choices(truncated_unrelated_indices, k=drop_items)
|
| 1460 |
+
|
| 1461 |
+
for _row_idx in reversed(range(row_max_len)):
|
| 1462 |
+
if _row_idx in drop_row_indices:
|
| 1463 |
+
del table_content["rows"][_row_idx]
|
| 1464 |
+
|
| 1465 |
+
# only when the drop ratio is too large, logging for warning.
|
| 1466 |
+
if "id" in table_content and len(drop_row_indices) > 0:
|
| 1467 |
+
logger.warning("Delete {:.2f} rows in table {}".format(len(drop_row_indices), table_content["id"]))
|
| 1468 |
+
|
| 1469 |
+
|
| 1470 |
+
__all__ = ["TapexTokenizer"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/trajectory_transformer/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
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_trajectory_transformer import *
|
| 22 |
+
from .modeling_trajectory_transformer 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__)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/trajectory_transformer/configuration_trajectory_transformer.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The Trajectory Transformers paper authors and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""TrajectoryTransformer 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 TrajectoryTransformerConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`TrajectoryTransformerModel`]. It is used to
|
| 27 |
+
instantiate an TrajectoryTransformer model according to the specified arguments, defining the model architecture.
|
| 28 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the
|
| 29 |
+
TrajectoryTransformer
|
| 30 |
+
[CarlCochet/trajectory-transformer-halfcheetah-medium-v2](https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2)
|
| 31 |
+
architecture.
|
| 32 |
+
|
| 33 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 34 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
vocab_size (`int`, *optional*, defaults to 100):
|
| 39 |
+
Vocabulary size of the TrajectoryTransformer model. Defines the number of different tokens that can be
|
| 40 |
+
represented by the `trajectories` passed when calling [`TrajectoryTransformerModel`]
|
| 41 |
+
action_weight (`int`, *optional*, defaults to 5):
|
| 42 |
+
Weight of the action in the loss function
|
| 43 |
+
reward_weight (`int`, *optional*, defaults to 1):
|
| 44 |
+
Weight of the reward in the loss function
|
| 45 |
+
value_weight (`int`, *optional*, defaults to 1):
|
| 46 |
+
Weight of the value in the loss function
|
| 47 |
+
block_size (`int`, *optional*, defaults to 249):
|
| 48 |
+
Size of the blocks in the trajectory transformer.
|
| 49 |
+
action_dim (`int`, *optional*, defaults to 6):
|
| 50 |
+
Dimension of the action space.
|
| 51 |
+
observation_dim (`int`, *optional*, defaults to 17):
|
| 52 |
+
Dimension of the observation space.
|
| 53 |
+
transition_dim (`int`, *optional*, defaults to 25):
|
| 54 |
+
Dimension of the transition space.
|
| 55 |
+
n_layer (`int`, *optional*, defaults to 4):
|
| 56 |
+
Number of hidden layers in the Transformer encoder.
|
| 57 |
+
n_head (`int`, *optional*, defaults to 4):
|
| 58 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 59 |
+
n_embd (`int`, *optional*, defaults to 128):
|
| 60 |
+
Dimensionality of the embeddings and hidden states.
|
| 61 |
+
resid_pdrop (`float`, *optional*, defaults to 0.1):
|
| 62 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 63 |
+
embd_pdrop (`int`, *optional*, defaults to 0.1):
|
| 64 |
+
The dropout ratio for the embeddings.
|
| 65 |
+
attn_pdrop (`float`, *optional*, defaults to 0.1):
|
| 66 |
+
The dropout ratio for the attention.
|
| 67 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 68 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 69 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 70 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 71 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 72 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 73 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 74 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 75 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 76 |
+
The epsilon used by the layer normalization layers.
|
| 77 |
+
kaiming_initializer_range (`float, *optional*, defaults to 1):
|
| 78 |
+
A coefficient scaling the negative slope of the kaiming initializer rectifier for EinLinear layers.
|
| 79 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 80 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 81 |
+
relevant if `config.is_decoder=True`.
|
| 82 |
+
Example:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
>>> from transformers import TrajectoryTransformerConfig, TrajectoryTransformerModel
|
| 86 |
+
|
| 87 |
+
>>> # Initializing a TrajectoryTransformer CarlCochet/trajectory-transformer-halfcheetah-medium-v2 style configuration
|
| 88 |
+
>>> configuration = TrajectoryTransformerConfig()
|
| 89 |
+
|
| 90 |
+
>>> # Initializing a model (with random weights) from the CarlCochet/trajectory-transformer-halfcheetah-medium-v2 style configuration
|
| 91 |
+
>>> model = TrajectoryTransformerModel(configuration)
|
| 92 |
+
|
| 93 |
+
>>> # Accessing the model configuration
|
| 94 |
+
>>> configuration = model.config
|
| 95 |
+
```"""
|
| 96 |
+
|
| 97 |
+
model_type = "trajectory_transformer"
|
| 98 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 99 |
+
attribute_map = {
|
| 100 |
+
"hidden_size": "n_embd",
|
| 101 |
+
"num_attention_heads": "n_head",
|
| 102 |
+
"num_hidden_layers": "n_layer",
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
def __init__(
|
| 106 |
+
self,
|
| 107 |
+
vocab_size=100,
|
| 108 |
+
action_weight=5,
|
| 109 |
+
reward_weight=1,
|
| 110 |
+
value_weight=1,
|
| 111 |
+
block_size=249,
|
| 112 |
+
action_dim=6,
|
| 113 |
+
observation_dim=17,
|
| 114 |
+
transition_dim=25,
|
| 115 |
+
n_layer=4,
|
| 116 |
+
n_head=4,
|
| 117 |
+
n_embd=128,
|
| 118 |
+
embd_pdrop=0.1,
|
| 119 |
+
attn_pdrop=0.1,
|
| 120 |
+
resid_pdrop=0.1,
|
| 121 |
+
learning_rate=0.0006,
|
| 122 |
+
max_position_embeddings=512,
|
| 123 |
+
initializer_range=0.02,
|
| 124 |
+
layer_norm_eps=1e-12,
|
| 125 |
+
kaiming_initializer_range=1,
|
| 126 |
+
use_cache=True,
|
| 127 |
+
pad_token_id=1,
|
| 128 |
+
bos_token_id=50256,
|
| 129 |
+
eos_token_id=50256,
|
| 130 |
+
**kwargs,
|
| 131 |
+
):
|
| 132 |
+
self.vocab_size = vocab_size
|
| 133 |
+
self.action_weight = action_weight
|
| 134 |
+
self.reward_weight = reward_weight
|
| 135 |
+
self.value_weight = value_weight
|
| 136 |
+
self.max_position_embeddings = max_position_embeddings
|
| 137 |
+
self.block_size = block_size
|
| 138 |
+
self.action_dim = action_dim
|
| 139 |
+
self.observation_dim = observation_dim
|
| 140 |
+
self.transition_dim = transition_dim
|
| 141 |
+
self.learning_rate = learning_rate
|
| 142 |
+
self.n_layer = n_layer
|
| 143 |
+
self.n_head = n_head
|
| 144 |
+
self.n_embd = n_embd
|
| 145 |
+
self.embd_pdrop = embd_pdrop
|
| 146 |
+
self.attn_pdrop = attn_pdrop
|
| 147 |
+
self.resid_pdrop = resid_pdrop
|
| 148 |
+
self.initializer_range = initializer_range
|
| 149 |
+
self.layer_norm_eps = layer_norm_eps
|
| 150 |
+
self.kaiming_initializer_range = kaiming_initializer_range
|
| 151 |
+
self.use_cache = use_cache
|
| 152 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
__all__ = ["TrajectoryTransformerConfig"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The Trajectory Transformers paper authors and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch TrajectoryTransformer model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import Optional, Union
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import torch
|
| 24 |
+
from torch import nn
|
| 25 |
+
from torch.nn import functional as F
|
| 26 |
+
|
| 27 |
+
from ....cache_utils import Cache
|
| 28 |
+
from ....modeling_layers import GradientCheckpointingLayer
|
| 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 |
+
)
|
| 37 |
+
from .configuration_trajectory_transformer import TrajectoryTransformerConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
_CHECKPOINT_FOR_DOC = "CarlCochet/trajectory-transformer-halfcheetah-medium-v2"
|
| 43 |
+
_CONFIG_FOR_DOC = "TrajectoryTransformerConfig"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def load_tf_weights_in_trajectory_transformer(model, config, tf_checkpoint_path):
|
| 47 |
+
"""Load tf checkpoints in a pytorch model."""
|
| 48 |
+
try:
|
| 49 |
+
import re
|
| 50 |
+
|
| 51 |
+
import numpy as np
|
| 52 |
+
import tensorflow as tf
|
| 53 |
+
except ImportError:
|
| 54 |
+
logger.error(
|
| 55 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
| 56 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
| 57 |
+
)
|
| 58 |
+
raise
|
| 59 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
| 60 |
+
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
|
| 61 |
+
# Load weights from TF model
|
| 62 |
+
init_vars = tf.train.list_variables(tf_path)
|
| 63 |
+
names = []
|
| 64 |
+
arrays = []
|
| 65 |
+
for name, shape in init_vars:
|
| 66 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
| 67 |
+
array = tf.train.load_variable(tf_path, name)
|
| 68 |
+
names.append(name)
|
| 69 |
+
arrays.append(array)
|
| 70 |
+
|
| 71 |
+
for name, array in zip(names, arrays):
|
| 72 |
+
name = name.split("/")
|
| 73 |
+
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
|
| 74 |
+
# which are not required for using pretrained model
|
| 75 |
+
if any(
|
| 76 |
+
n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
|
| 77 |
+
for n in name
|
| 78 |
+
):
|
| 79 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
| 80 |
+
continue
|
| 81 |
+
pointer = model
|
| 82 |
+
for m_name in name:
|
| 83 |
+
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
|
| 84 |
+
scope_names = re.split(r"_(\d+)", m_name)
|
| 85 |
+
else:
|
| 86 |
+
scope_names = [m_name]
|
| 87 |
+
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
|
| 88 |
+
pointer = getattr(pointer, "weight")
|
| 89 |
+
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
|
| 90 |
+
pointer = getattr(pointer, "bias")
|
| 91 |
+
elif scope_names[0] == "output_weights":
|
| 92 |
+
pointer = getattr(pointer, "weight")
|
| 93 |
+
elif scope_names[0] == "squad":
|
| 94 |
+
pointer = getattr(pointer, "classifier")
|
| 95 |
+
else:
|
| 96 |
+
try:
|
| 97 |
+
pointer = getattr(pointer, scope_names[0])
|
| 98 |
+
except AttributeError:
|
| 99 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
| 100 |
+
continue
|
| 101 |
+
if len(scope_names) >= 2:
|
| 102 |
+
num = int(scope_names[1])
|
| 103 |
+
pointer = pointer[num]
|
| 104 |
+
if m_name[-11:] == "_embeddings":
|
| 105 |
+
pointer = getattr(pointer, "weight")
|
| 106 |
+
elif m_name == "kernel":
|
| 107 |
+
array = np.transpose(array)
|
| 108 |
+
try:
|
| 109 |
+
if pointer.shape != array.shape:
|
| 110 |
+
raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
|
| 111 |
+
except AssertionError as e:
|
| 112 |
+
e.args += (pointer.shape, array.shape)
|
| 113 |
+
raise
|
| 114 |
+
logger.info(f"Initialize PyTorch weight {name}")
|
| 115 |
+
pointer.data = torch.from_numpy(array)
|
| 116 |
+
return model
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@dataclass
|
| 120 |
+
class TrajectoryTransformerOutput(ModelOutput):
|
| 121 |
+
"""
|
| 122 |
+
Base class for model's outputs that also contains a pooling of the last hidden states.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 126 |
+
Language modeling loss.
|
| 127 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 128 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 129 |
+
past_key_values (`tuple[tuple[torch.Tensor]]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 130 |
+
Tuple of length `config.n_layers`, containing tuples of tensors of shape `(batch_size, num_heads,
|
| 131 |
+
sequence_length, embed_size_per_head)`). Contains pre-computed hidden-states (key and values in the
|
| 132 |
+
attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 133 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 134 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 135 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 136 |
+
plus the initial embedding outputs.
|
| 137 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 138 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 139 |
+
sequence_length)`. GPT2Attentions weights after the attention softmax, used to compute the weighted average
|
| 140 |
+
in the self-attention heads.
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
loss: Optional[torch.FloatTensor] = None
|
| 144 |
+
logits: Optional[torch.FloatTensor] = None
|
| 145 |
+
past_key_values: Optional[Cache] = None
|
| 146 |
+
hidden_states: Optional[tuple[torch.FloatTensor]] = None
|
| 147 |
+
attentions: Optional[tuple[torch.FloatTensor]] = None
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class TrajectoryTransformerPreTrainedModel(PreTrainedModel):
|
| 151 |
+
"""
|
| 152 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 153 |
+
models.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
config: TrajectoryTransformerConfig
|
| 157 |
+
load_tf_weights = load_tf_weights_in_trajectory_transformer
|
| 158 |
+
base_model_prefix = "trajectory_transformer"
|
| 159 |
+
main_input_name = "trajectories"
|
| 160 |
+
supports_gradient_checkpointing = True
|
| 161 |
+
|
| 162 |
+
def _init_weights(self, module):
|
| 163 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
| 164 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 165 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 166 |
+
module.bias.data.zero_()
|
| 167 |
+
elif isinstance(module, nn.LayerNorm):
|
| 168 |
+
module.bias.data.zero_()
|
| 169 |
+
module.weight.data.fill_(1.0)
|
| 170 |
+
elif isinstance(module, EinLinear):
|
| 171 |
+
for i in range(module.n_models):
|
| 172 |
+
nn.init.kaiming_uniform_(module.weight[i], a=math.sqrt(5) / self.config.kaiming_initializer_range)
|
| 173 |
+
if module.bias is not None:
|
| 174 |
+
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(module.weight[i])
|
| 175 |
+
bound = (1 / math.sqrt(fan_in)) * self.config.initializer_range
|
| 176 |
+
nn.init.uniform_(module.bias[i], -bound, bound)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
TRAJECTORY_TRANSFORMER_START_DOCSTRING = r"""
|
| 180 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
|
| 181 |
+
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 182 |
+
behavior.
|
| 183 |
+
|
| 184 |
+
Parameters:
|
| 185 |
+
config ([`TrajectoryTransformerConfig`]): Model configuration class with all the parameters of the model.
|
| 186 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 187 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
TRAJECTORY_TRANSFORMER_INPUTS_DOCSTRING = r"""
|
| 191 |
+
Args:
|
| 192 |
+
trajectories (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 193 |
+
Batch of trajectories, where a trajectory is a sequence of states, actions and rewards.
|
| 194 |
+
past_key_values (`tuple[tuple[torch.Tensor]]` of length `config.n_layers`, *optional*):
|
| 195 |
+
Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
|
| 196 |
+
`past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
|
| 197 |
+
their past given to this model should not be passed as `input_ids` as they have already been computed.
|
| 198 |
+
targets (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 199 |
+
Desired targets used to compute the loss.
|
| 200 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 201 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 202 |
+
|
| 203 |
+
- 1 for tokens that are **not masked**,
|
| 204 |
+
- 0 for tokens that are **masked**.
|
| 205 |
+
|
| 206 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 207 |
+
use_cache (`bool`, *optional*):
|
| 208 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 209 |
+
`past_key_values`).
|
| 210 |
+
output_attentions (`bool`, *optional*):
|
| 211 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 212 |
+
tensors for more detail.
|
| 213 |
+
output_hidden_states (`bool`, *optional*):
|
| 214 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 215 |
+
more detail.
|
| 216 |
+
return_dict (`bool`, *optional*):
|
| 217 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 218 |
+
"""
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
class EinLinear(nn.Module):
|
| 222 |
+
def __init__(self, n_models, in_features, out_features, bias):
|
| 223 |
+
super().__init__()
|
| 224 |
+
self.n_models = n_models
|
| 225 |
+
self.out_features = out_features
|
| 226 |
+
self.in_features = in_features
|
| 227 |
+
self.weight = nn.Parameter(torch.Tensor(n_models, out_features, in_features))
|
| 228 |
+
if bias:
|
| 229 |
+
self.bias = nn.Parameter(torch.Tensor(n_models, out_features))
|
| 230 |
+
else:
|
| 231 |
+
self.register_parameter("bias", None)
|
| 232 |
+
|
| 233 |
+
def reset_parameters(self):
|
| 234 |
+
for i in range(self.n_models):
|
| 235 |
+
nn.init.kaiming_uniform_(self.weight[i], a=math.sqrt(5))
|
| 236 |
+
if self.bias is not None:
|
| 237 |
+
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight[i])
|
| 238 |
+
bound = 1 / math.sqrt(fan_in)
|
| 239 |
+
nn.init.uniform_(self.bias[i], -bound, bound)
|
| 240 |
+
|
| 241 |
+
def forward(self, input):
|
| 242 |
+
"""
|
| 243 |
+
Args:
|
| 244 |
+
input (`torch.FloatTensor` of shape `(B, n_models, input_dim)`):
|
| 245 |
+
The input to the layer.
|
| 246 |
+
"""
|
| 247 |
+
# [ batch_size x n_models x output_dim ]
|
| 248 |
+
output = torch.einsum("eoi,bei->beo", self.weight, input)
|
| 249 |
+
if self.bias is not None:
|
| 250 |
+
raise RuntimeError()
|
| 251 |
+
return output
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class CausalSelfAttention(nn.Module):
|
| 255 |
+
def __init__(self, config):
|
| 256 |
+
super().__init__()
|
| 257 |
+
|
| 258 |
+
if config.n_embd % config.n_head != 0:
|
| 259 |
+
raise ValueError(f"n_head ({config.n_head}) should be a divisor of n_embd ({config.n_embd})")
|
| 260 |
+
|
| 261 |
+
# key, query, value projections for all heads
|
| 262 |
+
self.key = nn.Linear(config.n_embd, config.n_embd)
|
| 263 |
+
self.query = nn.Linear(config.n_embd, config.n_embd)
|
| 264 |
+
self.value = nn.Linear(config.n_embd, config.n_embd)
|
| 265 |
+
|
| 266 |
+
# regularization
|
| 267 |
+
self.attn_drop = nn.Dropout(config.attn_pdrop)
|
| 268 |
+
self.resid_drop = nn.Dropout(config.resid_pdrop)
|
| 269 |
+
|
| 270 |
+
# output projection
|
| 271 |
+
self.proj = nn.Linear(config.n_embd, config.n_embd)
|
| 272 |
+
|
| 273 |
+
# causal mask to ensure that attention is only applied to the left in the input sequence
|
| 274 |
+
self.register_buffer(
|
| 275 |
+
"mask",
|
| 276 |
+
torch.tril(torch.ones(config.block_size, config.block_size)).view(
|
| 277 |
+
1, 1, config.block_size, config.block_size
|
| 278 |
+
),
|
| 279 |
+
persistent=False,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
# mask previous value estimates
|
| 283 |
+
joined_dim = config.observation_dim + config.action_dim + 2
|
| 284 |
+
self.mask.squeeze()[:, joined_dim - 1 :: joined_dim] = 0
|
| 285 |
+
|
| 286 |
+
self.n_head = config.n_head
|
| 287 |
+
|
| 288 |
+
def forward(
|
| 289 |
+
self,
|
| 290 |
+
hidden_states: Optional[tuple[torch.FloatTensor]],
|
| 291 |
+
layer_past: Optional[tuple[torch.Tensor]] = None,
|
| 292 |
+
use_cache: Optional[bool] = False,
|
| 293 |
+
output_attentions: Optional[bool] = False,
|
| 294 |
+
):
|
| 295 |
+
batch_size, sequence_length, embedding_dim = hidden_states.size()
|
| 296 |
+
|
| 297 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
| 298 |
+
# [ batch_size x n_heads x sequence_length x head_dim ]
|
| 299 |
+
key = (
|
| 300 |
+
self.key(hidden_states)
|
| 301 |
+
.view(batch_size, sequence_length, self.n_head, embedding_dim // self.n_head)
|
| 302 |
+
.transpose(1, 2)
|
| 303 |
+
)
|
| 304 |
+
query = (
|
| 305 |
+
self.query(hidden_states)
|
| 306 |
+
.view(batch_size, sequence_length, self.n_head, embedding_dim // self.n_head)
|
| 307 |
+
.transpose(1, 2)
|
| 308 |
+
)
|
| 309 |
+
value = (
|
| 310 |
+
self.value(hidden_states)
|
| 311 |
+
.view(batch_size, sequence_length, self.n_head, embedding_dim // self.n_head)
|
| 312 |
+
.transpose(1, 2)
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
if layer_past is not None:
|
| 316 |
+
past_key, past_value = layer_past
|
| 317 |
+
key = torch.cat((past_key, key), dim=-2)
|
| 318 |
+
value = torch.cat((past_value, value), dim=-2)
|
| 319 |
+
|
| 320 |
+
if use_cache is True:
|
| 321 |
+
present = (key, value)
|
| 322 |
+
else:
|
| 323 |
+
present = None
|
| 324 |
+
|
| 325 |
+
# causal self-attention
|
| 326 |
+
# [ batch_size x n_heads x sequence_length x sequence_length ]
|
| 327 |
+
attn_weights = (torch.matmul(query, key.transpose(-2, -1))) * (1.0 / math.sqrt(key.size(-1)))
|
| 328 |
+
attn_weights = attn_weights.masked_fill(
|
| 329 |
+
self.mask[:, :, :sequence_length, :sequence_length] == 0, torch.finfo(attn_weights.dtype).min
|
| 330 |
+
)
|
| 331 |
+
attn_weights = F.softmax(attn_weights, dim=-1)
|
| 332 |
+
self._attn_map = attn_weights.clone()
|
| 333 |
+
attn_weights = self.attn_drop(attn_weights)
|
| 334 |
+
|
| 335 |
+
output = torch.matmul(attn_weights, value)
|
| 336 |
+
# [ batch_size x sequence_length x embedding_dim ]
|
| 337 |
+
# re-assemble all head outputs side by side
|
| 338 |
+
output = output.transpose(1, 2).contiguous().view(batch_size, sequence_length, embedding_dim)
|
| 339 |
+
|
| 340 |
+
# output projection
|
| 341 |
+
output = self.resid_drop(self.proj(output))
|
| 342 |
+
|
| 343 |
+
outputs = (output, present)
|
| 344 |
+
if output_attentions:
|
| 345 |
+
outputs += (attn_weights,)
|
| 346 |
+
|
| 347 |
+
return outputs
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
class Block(GradientCheckpointingLayer):
|
| 351 |
+
def __init__(self, config):
|
| 352 |
+
super().__init__()
|
| 353 |
+
self.ln1 = nn.LayerNorm(config.n_embd)
|
| 354 |
+
self.ln2 = nn.LayerNorm(config.n_embd)
|
| 355 |
+
self.attn = CausalSelfAttention(config)
|
| 356 |
+
|
| 357 |
+
# MLP
|
| 358 |
+
self.l1 = nn.Linear(config.n_embd, 4 * config.n_embd)
|
| 359 |
+
self.act = nn.GELU()
|
| 360 |
+
self.l2 = nn.Linear(4 * config.n_embd, config.n_embd)
|
| 361 |
+
self.drop = nn.Dropout(config.resid_pdrop)
|
| 362 |
+
|
| 363 |
+
def forward(
|
| 364 |
+
self,
|
| 365 |
+
hidden_states: Optional[tuple[torch.FloatTensor]],
|
| 366 |
+
layer_past: Optional[tuple[torch.Tensor]] = None,
|
| 367 |
+
use_cache: Optional[bool] = False,
|
| 368 |
+
output_attentions: Optional[bool] = False,
|
| 369 |
+
):
|
| 370 |
+
residual = hidden_states
|
| 371 |
+
hidden_states = self.ln1(hidden_states)
|
| 372 |
+
|
| 373 |
+
attn_outputs = self.attn(
|
| 374 |
+
hidden_states, layer_past=layer_past, use_cache=use_cache, output_attentions=output_attentions
|
| 375 |
+
)
|
| 376 |
+
attn_output = attn_outputs[0]
|
| 377 |
+
outputs = attn_outputs[1:]
|
| 378 |
+
hidden_states = attn_output + residual
|
| 379 |
+
|
| 380 |
+
residual = hidden_states
|
| 381 |
+
hidden_states = self.ln2(hidden_states)
|
| 382 |
+
hidden_states = self.l1(hidden_states)
|
| 383 |
+
hidden_states = self.act(hidden_states)
|
| 384 |
+
hidden_states = self.l2(hidden_states)
|
| 385 |
+
hidden_states = residual + self.drop(hidden_states)
|
| 386 |
+
|
| 387 |
+
if use_cache:
|
| 388 |
+
outputs = (hidden_states,) + outputs
|
| 389 |
+
else:
|
| 390 |
+
outputs = (hidden_states,) + outputs[1:]
|
| 391 |
+
|
| 392 |
+
return outputs
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
@add_start_docstrings(
|
| 396 |
+
"The bare TrajectoryTransformer Model transformer outputting raw hidden-states without any specific head on top.",
|
| 397 |
+
TRAJECTORY_TRANSFORMER_START_DOCSTRING,
|
| 398 |
+
)
|
| 399 |
+
class TrajectoryTransformerModel(TrajectoryTransformerPreTrainedModel):
|
| 400 |
+
"""the full GPT language model, with a context size of block_size"""
|
| 401 |
+
|
| 402 |
+
def __init__(self, config):
|
| 403 |
+
super().__init__(config)
|
| 404 |
+
|
| 405 |
+
# input embedding stem (+1 for stop token)
|
| 406 |
+
self.tok_emb = nn.Embedding(config.vocab_size * config.transition_dim + 1, config.n_embd)
|
| 407 |
+
|
| 408 |
+
self.pos_emb = nn.Parameter(torch.zeros(1, config.block_size, config.n_embd))
|
| 409 |
+
self.drop = nn.Dropout(config.embd_pdrop)
|
| 410 |
+
# transformer
|
| 411 |
+
self.blocks = nn.ModuleList([Block(config) for _ in range(config.n_layer)])
|
| 412 |
+
# decoder head
|
| 413 |
+
self.ln_f = nn.LayerNorm(config.n_embd)
|
| 414 |
+
self.head = EinLinear(config.transition_dim, config.n_embd, config.vocab_size + 1, bias=False)
|
| 415 |
+
|
| 416 |
+
self.vocab_size = config.vocab_size
|
| 417 |
+
self.stop_token = config.vocab_size * config.transition_dim
|
| 418 |
+
self.block_size = config.block_size
|
| 419 |
+
|
| 420 |
+
self.observation_dim = config.observation_dim
|
| 421 |
+
self.action_dim = config.action_dim
|
| 422 |
+
self.transition_dim = config.transition_dim
|
| 423 |
+
self.embedding_dim = config.n_embd
|
| 424 |
+
|
| 425 |
+
self.action_weight = config.action_weight
|
| 426 |
+
self.reward_weight = config.reward_weight
|
| 427 |
+
self.value_weight = config.value_weight
|
| 428 |
+
|
| 429 |
+
self.gradient_checkpointing = False
|
| 430 |
+
|
| 431 |
+
self.post_init()
|
| 432 |
+
|
| 433 |
+
def get_block_size(self):
|
| 434 |
+
return self.block_size
|
| 435 |
+
|
| 436 |
+
def offset_tokens(self, trajectories):
|
| 437 |
+
_, sequence_length = trajectories.shape
|
| 438 |
+
|
| 439 |
+
n_states = int(np.ceil(sequence_length / self.transition_dim))
|
| 440 |
+
|
| 441 |
+
offsets = torch.arange(self.transition_dim) * self.vocab_size
|
| 442 |
+
offsets = offsets.repeat(n_states).to(trajectories.device)
|
| 443 |
+
|
| 444 |
+
offset_trajectories = trajectories + offsets[:sequence_length]
|
| 445 |
+
offset_trajectories[trajectories == self.vocab_size] = self.stop_token
|
| 446 |
+
return offset_trajectories
|
| 447 |
+
|
| 448 |
+
def pad_to_full_observation(self, hidden_states):
|
| 449 |
+
batch_size, sequence_length, _ = hidden_states.shape
|
| 450 |
+
|
| 451 |
+
n_pad = (self.transition_dim - sequence_length % self.transition_dim) % self.transition_dim
|
| 452 |
+
padding = torch.zeros(batch_size, n_pad, self.embedding_dim, device=hidden_states.device)
|
| 453 |
+
|
| 454 |
+
# [ batch_size x padded_sequence_length' x embedding_dim ]
|
| 455 |
+
hidden_states_pad = torch.cat([hidden_states, padding], dim=1)
|
| 456 |
+
hidden_states_pad = hidden_states_pad.view(-1, self.transition_dim, self.embedding_dim)
|
| 457 |
+
|
| 458 |
+
return hidden_states_pad, n_pad
|
| 459 |
+
|
| 460 |
+
@add_start_docstrings_to_model_forward(
|
| 461 |
+
TRAJECTORY_TRANSFORMER_INPUTS_DOCSTRING.format("batch_size, sequence_length")
|
| 462 |
+
)
|
| 463 |
+
@replace_return_docstrings(output_type=TrajectoryTransformerOutput, config_class=_CONFIG_FOR_DOC)
|
| 464 |
+
def forward(
|
| 465 |
+
self,
|
| 466 |
+
trajectories: Optional[torch.LongTensor] = None,
|
| 467 |
+
past_key_values: Optional[Cache] = None,
|
| 468 |
+
targets: Optional[torch.FloatTensor] = None,
|
| 469 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 470 |
+
use_cache: Optional[bool] = None,
|
| 471 |
+
output_attentions: Optional[bool] = None,
|
| 472 |
+
output_hidden_states: Optional[bool] = None,
|
| 473 |
+
return_dict: Optional[bool] = None,
|
| 474 |
+
) -> Union[tuple[torch.Tensor], TrajectoryTransformerOutput]:
|
| 475 |
+
r"""
|
| 476 |
+
Returns:
|
| 477 |
+
|
| 478 |
+
Examples:
|
| 479 |
+
|
| 480 |
+
```python
|
| 481 |
+
>>> from transformers import TrajectoryTransformerModel
|
| 482 |
+
>>> import torch
|
| 483 |
+
|
| 484 |
+
>>> model = TrajectoryTransformerModel.from_pretrained(
|
| 485 |
+
... "CarlCochet/trajectory-transformer-halfcheetah-medium-v2"
|
| 486 |
+
... )
|
| 487 |
+
>>> model.to(device)
|
| 488 |
+
>>> model.eval()
|
| 489 |
+
|
| 490 |
+
>>> observations_dim, action_dim, batch_size = 17, 6, 256
|
| 491 |
+
>>> seq_length = observations_dim + action_dim + 1
|
| 492 |
+
|
| 493 |
+
>>> trajectories = torch.LongTensor([np.random.permutation(self.seq_length) for _ in range(batch_size)]).to(
|
| 494 |
+
... device
|
| 495 |
+
... )
|
| 496 |
+
>>> targets = torch.LongTensor([np.random.permutation(self.seq_length) for _ in range(batch_size)]).to(device)
|
| 497 |
+
|
| 498 |
+
>>> outputs = model(
|
| 499 |
+
... trajectories,
|
| 500 |
+
... targets=targets,
|
| 501 |
+
... use_cache=True,
|
| 502 |
+
... output_attentions=True,
|
| 503 |
+
... output_hidden_states=True,
|
| 504 |
+
... return_dict=True,
|
| 505 |
+
... )
|
| 506 |
+
```
|
| 507 |
+
"""
|
| 508 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 509 |
+
output_hidden_states = (
|
| 510 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
if past_key_values is None:
|
| 514 |
+
past_key_values = tuple([None] * len(self.blocks))
|
| 515 |
+
|
| 516 |
+
batch_size, sequence_length = trajectories.size()
|
| 517 |
+
|
| 518 |
+
if sequence_length > self.block_size:
|
| 519 |
+
raise ValueError("Cannot forward, model block size is exhausted.")
|
| 520 |
+
|
| 521 |
+
offset_trajectories = self.offset_tokens(trajectories)
|
| 522 |
+
# [ batch_size x sequence_length x embedding_dim ]
|
| 523 |
+
# forward the GPT model
|
| 524 |
+
token_embeddings = self.tok_emb(offset_trajectories) # each index maps to a (learnable) vector
|
| 525 |
+
position_embeddings = self.pos_emb[:, :sequence_length, :] # each position maps to a (learnable) vector
|
| 526 |
+
|
| 527 |
+
hidden_states = self.drop(token_embeddings + position_embeddings)
|
| 528 |
+
|
| 529 |
+
if self.gradient_checkpointing and self.training:
|
| 530 |
+
if use_cache:
|
| 531 |
+
logger.warning_once(
|
| 532 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 533 |
+
)
|
| 534 |
+
use_cache = False
|
| 535 |
+
|
| 536 |
+
presents = () if use_cache else None
|
| 537 |
+
all_self_attentions = () if output_attentions else None
|
| 538 |
+
all_hidden_states = () if output_hidden_states else None
|
| 539 |
+
|
| 540 |
+
for i, (block, layer_past) in enumerate(zip(self.blocks, past_key_values)):
|
| 541 |
+
if output_hidden_states:
|
| 542 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 543 |
+
|
| 544 |
+
outputs = block(hidden_states, layer_past, use_cache, output_attentions)
|
| 545 |
+
|
| 546 |
+
hidden_states = outputs[0]
|
| 547 |
+
if use_cache is True:
|
| 548 |
+
presents = presents + (outputs[1],)
|
| 549 |
+
|
| 550 |
+
if output_attentions:
|
| 551 |
+
all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
|
| 552 |
+
|
| 553 |
+
# [ batch_size x sequence_length x embedding_dim ]
|
| 554 |
+
hidden_state = self.ln_f(hidden_states)
|
| 555 |
+
|
| 556 |
+
if output_hidden_states:
|
| 557 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 558 |
+
|
| 559 |
+
hidden_states_pad, n_pad = self.pad_to_full_observation(hidden_state)
|
| 560 |
+
|
| 561 |
+
logits = self.head(hidden_states_pad)
|
| 562 |
+
logits = logits.reshape(batch_size, sequence_length + n_pad, self.vocab_size + 1)
|
| 563 |
+
logits = logits[:, :sequence_length]
|
| 564 |
+
|
| 565 |
+
# if we are given some desired targets also calculate the loss
|
| 566 |
+
if targets is not None:
|
| 567 |
+
loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.view(-1), reduction="none")
|
| 568 |
+
if self.action_weight != 1 or self.reward_weight != 1 or self.value_weight != 1:
|
| 569 |
+
# make weights
|
| 570 |
+
n_states = int(np.ceil(sequence_length / self.transition_dim))
|
| 571 |
+
weights = torch.cat(
|
| 572 |
+
[
|
| 573 |
+
torch.ones(self.observation_dim, device=trajectories.device),
|
| 574 |
+
torch.ones(self.action_dim, device=trajectories.device) * self.action_weight,
|
| 575 |
+
torch.ones(1, device=trajectories.device) * self.reward_weight,
|
| 576 |
+
torch.ones(1, device=trajectories.device) * self.value_weight,
|
| 577 |
+
]
|
| 578 |
+
)
|
| 579 |
+
weights = weights.repeat(n_states)
|
| 580 |
+
weights = weights[1:].repeat(batch_size, 1)
|
| 581 |
+
loss = loss * weights.view(-1)
|
| 582 |
+
loss = (loss * attention_mask.view(-1)).mean()
|
| 583 |
+
else:
|
| 584 |
+
loss = None
|
| 585 |
+
|
| 586 |
+
if not return_dict:
|
| 587 |
+
return tuple(v for v in [loss, logits, presents, all_hidden_states, all_self_attentions] if v is not None)
|
| 588 |
+
|
| 589 |
+
return TrajectoryTransformerOutput(
|
| 590 |
+
loss=loss,
|
| 591 |
+
logits=logits,
|
| 592 |
+
past_key_values=presents,
|
| 593 |
+
hidden_states=all_hidden_states,
|
| 594 |
+
attentions=all_self_attentions,
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
__all__ = [
|
| 599 |
+
"TrajectoryTransformerModel",
|
| 600 |
+
"TrajectoryTransformerPreTrainedModel",
|
| 601 |
+
"load_tf_weights_in_trajectory_transformer",
|
| 602 |
+
]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ....utils import _LazyModule
|
| 17 |
+
from ....utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_transfo_xl import *
|
| 22 |
+
from .modeling_tf_transfo_xl import *
|
| 23 |
+
from .modeling_transfo_xl import *
|
| 24 |
+
from .tokenization_transfo_xl import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/configuration_transfo_xl.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University 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 |
+
"""Transformer XL configuration"""
|
| 17 |
+
|
| 18 |
+
from ....configuration_utils import PretrainedConfig
|
| 19 |
+
from ....utils import logging
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class TransfoXLConfig(PretrainedConfig):
|
| 26 |
+
"""
|
| 27 |
+
This is the configuration class to store the configuration of a [`TransfoXLModel`] or a [`TFTransfoXLModel`]. It is
|
| 28 |
+
used to instantiate a Transformer-XL model according to the specified arguments, defining the model architecture.
|
| 29 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the TransfoXL
|
| 30 |
+
[transfo-xl/transfo-xl-wt103](https://huggingface.co/transfo-xl/transfo-xl-wt103) architecture.
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 267735):
|
| 37 |
+
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
|
| 38 |
+
`inputs_ids` passed when calling [`TransfoXLModel`] or [`TFTransfoXLModel`].
|
| 39 |
+
cutoffs (`list[int]`, *optional*, defaults to `[20000, 40000, 200000]`):
|
| 40 |
+
Cutoffs for the adaptive softmax.
|
| 41 |
+
d_model (`int`, *optional*, defaults to 1024):
|
| 42 |
+
Dimensionality of the model's hidden states.
|
| 43 |
+
d_embed (`int`, *optional*, defaults to 1024):
|
| 44 |
+
Dimensionality of the embeddings
|
| 45 |
+
n_head (`int`, *optional*, defaults to 16):
|
| 46 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 47 |
+
d_head (`int`, *optional*, defaults to 64):
|
| 48 |
+
Dimensionality of the model's heads.
|
| 49 |
+
d_inner (`int`, *optional*, defaults to 4096):
|
| 50 |
+
Inner dimension in FF
|
| 51 |
+
div_val (`int`, *optional*, defaults to 4):
|
| 52 |
+
Divident value for adaptive input and softmax
|
| 53 |
+
pre_lnorm (`boolean`, *optional*, defaults to `False`):
|
| 54 |
+
Whether or not to apply LayerNorm to the input instead of the output in the blocks.
|
| 55 |
+
n_layer (`int`, *optional*, defaults to 18):
|
| 56 |
+
Number of hidden layers in the Transformer encoder.
|
| 57 |
+
mem_len (`int`, *optional*, defaults to 1600):
|
| 58 |
+
Length of the retained previous heads.
|
| 59 |
+
clamp_len (`int`, *optional*, defaults to 1000):
|
| 60 |
+
Use the same pos embeddings after clamp_len.
|
| 61 |
+
same_length (`boolean`, *optional*, defaults to `True`):
|
| 62 |
+
Whether or not to use the same attn length for all tokens
|
| 63 |
+
proj_share_all_but_first (`boolean`, *optional*, defaults to `True`):
|
| 64 |
+
True to share all but first projs, False not to share.
|
| 65 |
+
attn_type (`int`, *optional*, defaults to 0):
|
| 66 |
+
Attention type. 0 for Transformer-XL, 1 for Shaw et al, 2 for Vaswani et al, 3 for Al Rfou et al.
|
| 67 |
+
sample_softmax (`int`, *optional*, defaults to -1):
|
| 68 |
+
Number of samples in the sampled softmax.
|
| 69 |
+
adaptive (`boolean`, *optional*, defaults to `True`):
|
| 70 |
+
Whether or not to use adaptive softmax.
|
| 71 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 72 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 73 |
+
dropatt (`float`, *optional*, defaults to 0.0):
|
| 74 |
+
The dropout ratio for the attention probabilities.
|
| 75 |
+
untie_r (`boolean`, *optional*, defaults to `True`):
|
| 76 |
+
Whether ot not to untie relative position biases.
|
| 77 |
+
init (`str`, *optional*, defaults to `"normal"`):
|
| 78 |
+
Parameter initializer to use.
|
| 79 |
+
init_range (`float`, *optional*, defaults to 0.01):
|
| 80 |
+
Parameters initialized by U(-init_range, init_range).
|
| 81 |
+
proj_init_std (`float`, *optional*, defaults to 0.01):
|
| 82 |
+
Parameters initialized by N(0, init_std)
|
| 83 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 84 |
+
Parameters initialized by N(0, init_std)
|
| 85 |
+
layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
|
| 86 |
+
The epsilon to use in the layer normalization layers
|
| 87 |
+
eos_token_id (`int`, *optional*, defaults to 0):
|
| 88 |
+
End of stream token id.
|
| 89 |
+
|
| 90 |
+
Examples:
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
>>> from transformers import TransfoXLConfig, TransfoXLModel
|
| 94 |
+
|
| 95 |
+
>>> # Initializing a Transformer XL configuration
|
| 96 |
+
>>> configuration = TransfoXLConfig()
|
| 97 |
+
|
| 98 |
+
>>> # Initializing a model (with random weights) from the configuration
|
| 99 |
+
>>> model = TransfoXLModel(configuration)
|
| 100 |
+
|
| 101 |
+
>>> # Accessing the model configuration
|
| 102 |
+
>>> configuration = model.config
|
| 103 |
+
```"""
|
| 104 |
+
|
| 105 |
+
model_type = "transfo-xl"
|
| 106 |
+
keys_to_ignore_at_inference = ["mems"]
|
| 107 |
+
attribute_map = {
|
| 108 |
+
"n_token": "vocab_size",
|
| 109 |
+
"hidden_size": "d_model",
|
| 110 |
+
"num_attention_heads": "n_head",
|
| 111 |
+
"num_hidden_layers": "n_layer",
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
def __init__(
|
| 115 |
+
self,
|
| 116 |
+
vocab_size=267735,
|
| 117 |
+
cutoffs=[20000, 40000, 200000],
|
| 118 |
+
d_model=1024,
|
| 119 |
+
d_embed=1024,
|
| 120 |
+
n_head=16,
|
| 121 |
+
d_head=64,
|
| 122 |
+
d_inner=4096,
|
| 123 |
+
div_val=4,
|
| 124 |
+
pre_lnorm=False,
|
| 125 |
+
n_layer=18,
|
| 126 |
+
mem_len=1600,
|
| 127 |
+
clamp_len=1000,
|
| 128 |
+
same_length=True,
|
| 129 |
+
proj_share_all_but_first=True,
|
| 130 |
+
attn_type=0,
|
| 131 |
+
sample_softmax=-1,
|
| 132 |
+
adaptive=True,
|
| 133 |
+
dropout=0.1,
|
| 134 |
+
dropatt=0.0,
|
| 135 |
+
untie_r=True,
|
| 136 |
+
init="normal",
|
| 137 |
+
init_range=0.01,
|
| 138 |
+
proj_init_std=0.01,
|
| 139 |
+
init_std=0.02,
|
| 140 |
+
layer_norm_epsilon=1e-5,
|
| 141 |
+
eos_token_id=0,
|
| 142 |
+
**kwargs,
|
| 143 |
+
):
|
| 144 |
+
self.vocab_size = vocab_size
|
| 145 |
+
self.cutoffs = []
|
| 146 |
+
self.cutoffs.extend(cutoffs)
|
| 147 |
+
if proj_share_all_but_first:
|
| 148 |
+
self.tie_projs = [False] + [True] * len(self.cutoffs)
|
| 149 |
+
else:
|
| 150 |
+
self.tie_projs = [False] + [False] * len(self.cutoffs)
|
| 151 |
+
self.d_model = d_model
|
| 152 |
+
self.d_embed = d_embed
|
| 153 |
+
self.d_head = d_head
|
| 154 |
+
self.d_inner = d_inner
|
| 155 |
+
self.div_val = div_val
|
| 156 |
+
self.pre_lnorm = pre_lnorm
|
| 157 |
+
self.n_layer = n_layer
|
| 158 |
+
self.n_head = n_head
|
| 159 |
+
self.mem_len = mem_len
|
| 160 |
+
self.same_length = same_length
|
| 161 |
+
self.attn_type = attn_type
|
| 162 |
+
self.clamp_len = clamp_len
|
| 163 |
+
self.sample_softmax = sample_softmax
|
| 164 |
+
self.adaptive = adaptive
|
| 165 |
+
self.dropout = dropout
|
| 166 |
+
self.dropatt = dropatt
|
| 167 |
+
self.untie_r = untie_r
|
| 168 |
+
self.init = init
|
| 169 |
+
self.init_range = init_range
|
| 170 |
+
self.proj_init_std = proj_init_std
|
| 171 |
+
self.init_std = init_std
|
| 172 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 173 |
+
super().__init__(eos_token_id=eos_token_id, **kwargs)
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
def max_position_embeddings(self):
|
| 177 |
+
# Message copied from Transformer-XL documentation
|
| 178 |
+
logger.info(f"The model {self.model_type} is one of the few models that has no sequence length limit.")
|
| 179 |
+
return -1
|
| 180 |
+
|
| 181 |
+
@max_position_embeddings.setter
|
| 182 |
+
def max_position_embeddings(self, value):
|
| 183 |
+
# Message copied from Transformer-XL documentation
|
| 184 |
+
raise NotImplementedError(
|
| 185 |
+
f"The model {self.model_type} is one of the few models that has no sequence length limit."
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
__all__ = ["TransfoXLConfig"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py
ADDED
|
@@ -0,0 +1,1128 @@
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University 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 |
+
"""
|
| 17 |
+
TF 2.0 Transformer XL model.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import tensorflow as tf
|
| 26 |
+
|
| 27 |
+
from ....modeling_tf_utils import (
|
| 28 |
+
TFModelInputType,
|
| 29 |
+
TFPreTrainedModel,
|
| 30 |
+
TFSequenceClassificationLoss,
|
| 31 |
+
get_initializer,
|
| 32 |
+
keras,
|
| 33 |
+
keras_serializable,
|
| 34 |
+
unpack_inputs,
|
| 35 |
+
)
|
| 36 |
+
from ....tf_utils import shape_list, stable_softmax
|
| 37 |
+
from ....utils import (
|
| 38 |
+
ModelOutput,
|
| 39 |
+
add_code_sample_docstrings,
|
| 40 |
+
add_start_docstrings,
|
| 41 |
+
add_start_docstrings_to_model_forward,
|
| 42 |
+
logging,
|
| 43 |
+
)
|
| 44 |
+
from .configuration_transfo_xl import TransfoXLConfig
|
| 45 |
+
from .modeling_tf_transfo_xl_utilities import TFAdaptiveSoftmaxMask
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
logger = logging.get_logger(__name__)
|
| 49 |
+
|
| 50 |
+
_CHECKPOINT_FOR_DOC = "transfo-xl/transfo-xl-wt103"
|
| 51 |
+
_CONFIG_FOR_DOC = "TransfoXLConfig"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class TFPositionalEmbedding(keras.layers.Layer):
|
| 55 |
+
def __init__(self, demb, **kwargs):
|
| 56 |
+
super().__init__(**kwargs)
|
| 57 |
+
|
| 58 |
+
self.inv_freq = 1 / (10000 ** (tf.range(0, demb, 2.0) / demb))
|
| 59 |
+
|
| 60 |
+
def call(self, pos_seq, bsz=None):
|
| 61 |
+
self.inv_freq = tf.cast(self.inv_freq, dtype=pos_seq.dtype)
|
| 62 |
+
sinusoid_inp = tf.einsum("i,j->ij", pos_seq, self.inv_freq)
|
| 63 |
+
pos_emb = tf.concat([tf.sin(sinusoid_inp), tf.cos(sinusoid_inp)], -1)
|
| 64 |
+
|
| 65 |
+
if bsz is not None:
|
| 66 |
+
return tf.tile(pos_emb[:, None, :], [1, bsz, 1])
|
| 67 |
+
else:
|
| 68 |
+
return pos_emb[:, None, :]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class TFPositionwiseFF(keras.layers.Layer):
|
| 72 |
+
def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5, init_std=0.02, **kwargs):
|
| 73 |
+
super().__init__(**kwargs)
|
| 74 |
+
|
| 75 |
+
self.d_model = d_model
|
| 76 |
+
self.d_inner = d_inner
|
| 77 |
+
self.dropout = dropout
|
| 78 |
+
|
| 79 |
+
self.layer_1 = keras.layers.Dense(
|
| 80 |
+
d_inner, kernel_initializer=get_initializer(init_std), activation=tf.nn.relu, name="CoreNet_._0"
|
| 81 |
+
)
|
| 82 |
+
self.drop_1 = keras.layers.Dropout(dropout)
|
| 83 |
+
self.layer_2 = keras.layers.Dense(d_model, kernel_initializer=get_initializer(init_std), name="CoreNet_._3")
|
| 84 |
+
self.drop_2 = keras.layers.Dropout(dropout)
|
| 85 |
+
|
| 86 |
+
self.layer_norm = keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name="layer_norm")
|
| 87 |
+
|
| 88 |
+
self.pre_lnorm = pre_lnorm
|
| 89 |
+
|
| 90 |
+
def call(self, inp, training=False):
|
| 91 |
+
if self.pre_lnorm:
|
| 92 |
+
# layer normalization + positionwise feed-forward
|
| 93 |
+
core_out = self.layer_norm(inp)
|
| 94 |
+
core_out = self.layer_1(core_out)
|
| 95 |
+
core_out = self.drop_1(core_out, training=training)
|
| 96 |
+
core_out = self.layer_2(core_out)
|
| 97 |
+
core_out = self.drop_2(core_out, training=training)
|
| 98 |
+
|
| 99 |
+
# residual connection
|
| 100 |
+
output = core_out + inp
|
| 101 |
+
else:
|
| 102 |
+
# positionwise feed-forward
|
| 103 |
+
core_out = self.layer_1(inp)
|
| 104 |
+
core_out = self.drop_1(core_out, training=training)
|
| 105 |
+
core_out = self.layer_2(core_out)
|
| 106 |
+
core_out = self.drop_2(core_out, training=training)
|
| 107 |
+
|
| 108 |
+
# residual connection + layer normalization
|
| 109 |
+
output = self.layer_norm(inp + core_out)
|
| 110 |
+
|
| 111 |
+
return output
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class TFRelPartialLearnableMultiHeadAttn(keras.layers.Layer):
|
| 115 |
+
def __init__(
|
| 116 |
+
self,
|
| 117 |
+
n_head,
|
| 118 |
+
d_model,
|
| 119 |
+
d_head,
|
| 120 |
+
dropout,
|
| 121 |
+
dropatt=0.0,
|
| 122 |
+
pre_lnorm=False,
|
| 123 |
+
r_r_bias=None,
|
| 124 |
+
r_w_bias=None,
|
| 125 |
+
layer_norm_epsilon=1e-5,
|
| 126 |
+
init_std=0.02,
|
| 127 |
+
output_attentions=False,
|
| 128 |
+
**kwargs,
|
| 129 |
+
):
|
| 130 |
+
super().__init__(**kwargs)
|
| 131 |
+
|
| 132 |
+
self.n_head = n_head
|
| 133 |
+
self.d_model = d_model
|
| 134 |
+
self.d_head = d_head
|
| 135 |
+
self.dropout = dropout
|
| 136 |
+
self.output_attentions = output_attentions
|
| 137 |
+
|
| 138 |
+
self.qkv_net = keras.layers.Dense(
|
| 139 |
+
3 * n_head * d_head, kernel_initializer=get_initializer(init_std), use_bias=False, name="qkv_net"
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
self.drop = keras.layers.Dropout(dropout)
|
| 143 |
+
self.dropatt = keras.layers.Dropout(dropatt)
|
| 144 |
+
self.o_net = keras.layers.Dense(
|
| 145 |
+
d_model, kernel_initializer=get_initializer(init_std), use_bias=False, name="o_net"
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
self.layer_norm = keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name="layer_norm")
|
| 149 |
+
|
| 150 |
+
self.scale = 1 / (d_head**0.5)
|
| 151 |
+
|
| 152 |
+
self.pre_lnorm = pre_lnorm
|
| 153 |
+
|
| 154 |
+
if r_r_bias is not None and r_w_bias is not None: # Biases are shared
|
| 155 |
+
self.r_r_bias = r_r_bias
|
| 156 |
+
self.r_w_bias = r_w_bias
|
| 157 |
+
else:
|
| 158 |
+
self.r_r_bias = None
|
| 159 |
+
self.r_w_bias = None
|
| 160 |
+
|
| 161 |
+
self.r_net = keras.layers.Dense(
|
| 162 |
+
self.n_head * self.d_head, kernel_initializer=get_initializer(init_std), use_bias=False, name="r_net"
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
def build(self, input_shape):
|
| 166 |
+
if self.r_r_bias is None or self.r_w_bias is None: # Biases are not shared
|
| 167 |
+
self.r_r_bias = self.add_weight(
|
| 168 |
+
shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_r_bias"
|
| 169 |
+
)
|
| 170 |
+
self.r_w_bias = self.add_weight(
|
| 171 |
+
shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_w_bias"
|
| 172 |
+
)
|
| 173 |
+
super().build(input_shape)
|
| 174 |
+
|
| 175 |
+
def _rel_shift(self, x):
|
| 176 |
+
x_size = shape_list(x)
|
| 177 |
+
|
| 178 |
+
x = tf.pad(x, [[0, 0], [1, 0], [0, 0], [0, 0]])
|
| 179 |
+
x = tf.reshape(x, [x_size[1] + 1, x_size[0], x_size[2], x_size[3]])
|
| 180 |
+
x = tf.slice(x, [1, 0, 0, 0], [-1, -1, -1, -1])
|
| 181 |
+
x = tf.reshape(x, x_size)
|
| 182 |
+
|
| 183 |
+
return x
|
| 184 |
+
|
| 185 |
+
def call(self, w, r, attn_mask, mems, head_mask, output_attentions, training=False):
|
| 186 |
+
qlen, rlen, bsz = shape_list(w)[0], shape_list(r)[0], shape_list(w)[1]
|
| 187 |
+
|
| 188 |
+
if mems is not None:
|
| 189 |
+
mems = tf.cast(mems, dtype=w.dtype)
|
| 190 |
+
cat = tf.concat([mems, w], 0)
|
| 191 |
+
if self.pre_lnorm:
|
| 192 |
+
w_heads = self.qkv_net(self.layer_norm(cat))
|
| 193 |
+
else:
|
| 194 |
+
w_heads = self.qkv_net(cat)
|
| 195 |
+
r_head_k = self.r_net(r)
|
| 196 |
+
|
| 197 |
+
w_head_q, w_head_k, w_head_v = tf.split(w_heads, 3, axis=-1)
|
| 198 |
+
w_head_q = w_head_q[-qlen:]
|
| 199 |
+
else:
|
| 200 |
+
if self.pre_lnorm:
|
| 201 |
+
w_heads = self.qkv_net(self.layer_norm(w))
|
| 202 |
+
else:
|
| 203 |
+
w_heads = self.qkv_net(w)
|
| 204 |
+
r_head_k = self.r_net(r)
|
| 205 |
+
|
| 206 |
+
w_head_q, w_head_k, w_head_v = tf.split(w_heads, 3, axis=-1)
|
| 207 |
+
|
| 208 |
+
klen = shape_list(w_head_k)[0]
|
| 209 |
+
|
| 210 |
+
w_head_q = tf.reshape(w_head_q, (qlen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head
|
| 211 |
+
w_head_k = tf.reshape(w_head_k, (klen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head
|
| 212 |
+
w_head_v = tf.reshape(w_head_v, (klen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head
|
| 213 |
+
|
| 214 |
+
r_head_k = tf.reshape(r_head_k, (rlen, self.n_head, self.d_head)) # qlen x n_head x d_head
|
| 215 |
+
|
| 216 |
+
# compute attention score
|
| 217 |
+
rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head
|
| 218 |
+
AC = tf.einsum("ibnd,jbnd->ijbn", rw_head_q, w_head_k) # qlen x klen x bsz x n_head
|
| 219 |
+
|
| 220 |
+
rr_head_q = w_head_q + self.r_r_bias
|
| 221 |
+
BD = tf.einsum("ibnd,jnd->ijbn", rr_head_q, r_head_k) # qlen x klen x bsz x n_head
|
| 222 |
+
BD = self._rel_shift(BD)
|
| 223 |
+
|
| 224 |
+
# [qlen x klen x bsz x n_head]
|
| 225 |
+
attn_score = AC + BD
|
| 226 |
+
attn_score = attn_score * self.scale
|
| 227 |
+
|
| 228 |
+
# compute attention probability
|
| 229 |
+
if attn_mask is not None:
|
| 230 |
+
attn_mask_t = attn_mask[:, :, None, None]
|
| 231 |
+
attn_mask_t = tf.cast(attn_mask_t, dtype=attn_score.dtype)
|
| 232 |
+
attn_score = attn_score * (1.0 - attn_mask_t) - 1e30 * attn_mask_t
|
| 233 |
+
|
| 234 |
+
# [qlen x klen x bsz x n_head]
|
| 235 |
+
attn_prob = stable_softmax(attn_score, axis=1)
|
| 236 |
+
attn_prob = self.dropatt(attn_prob, training=training)
|
| 237 |
+
|
| 238 |
+
# Mask heads if we want to
|
| 239 |
+
if head_mask is not None:
|
| 240 |
+
attn_prob = attn_prob * head_mask
|
| 241 |
+
|
| 242 |
+
# compute attention vector
|
| 243 |
+
attn_vec = tf.einsum("ijbn,jbnd->ibnd", attn_prob, w_head_v)
|
| 244 |
+
|
| 245 |
+
# [qlen x bsz x n_head x d_head]
|
| 246 |
+
attn_vec_sizes = shape_list(attn_vec)
|
| 247 |
+
attn_vec = tf.reshape(attn_vec, (attn_vec_sizes[0], attn_vec_sizes[1], self.n_head * self.d_head))
|
| 248 |
+
|
| 249 |
+
# linear projection
|
| 250 |
+
attn_out = self.o_net(attn_vec)
|
| 251 |
+
attn_out = self.drop(attn_out, training=training)
|
| 252 |
+
|
| 253 |
+
if self.pre_lnorm:
|
| 254 |
+
# residual connection
|
| 255 |
+
outputs = [w + attn_out]
|
| 256 |
+
else:
|
| 257 |
+
# residual connection + layer normalization
|
| 258 |
+
outputs = [self.layer_norm(w + attn_out)]
|
| 259 |
+
|
| 260 |
+
if output_attentions:
|
| 261 |
+
outputs.append(attn_prob)
|
| 262 |
+
|
| 263 |
+
return outputs
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class TFRelPartialLearnableDecoderLayer(keras.layers.Layer):
|
| 267 |
+
def __init__(
|
| 268 |
+
self,
|
| 269 |
+
n_head,
|
| 270 |
+
d_model,
|
| 271 |
+
d_head,
|
| 272 |
+
d_inner,
|
| 273 |
+
dropout,
|
| 274 |
+
dropatt=0.0,
|
| 275 |
+
pre_lnorm=False,
|
| 276 |
+
r_w_bias=None,
|
| 277 |
+
r_r_bias=None,
|
| 278 |
+
layer_norm_epsilon=1e-5,
|
| 279 |
+
init_std=0.02,
|
| 280 |
+
output_attentions=False,
|
| 281 |
+
**kwargs,
|
| 282 |
+
):
|
| 283 |
+
super().__init__(**kwargs)
|
| 284 |
+
|
| 285 |
+
self.dec_attn = TFRelPartialLearnableMultiHeadAttn(
|
| 286 |
+
n_head,
|
| 287 |
+
d_model,
|
| 288 |
+
d_head,
|
| 289 |
+
dropout,
|
| 290 |
+
dropatt=dropatt,
|
| 291 |
+
pre_lnorm=pre_lnorm,
|
| 292 |
+
r_w_bias=r_w_bias,
|
| 293 |
+
r_r_bias=r_r_bias,
|
| 294 |
+
init_std=init_std,
|
| 295 |
+
layer_norm_epsilon=layer_norm_epsilon,
|
| 296 |
+
output_attentions=output_attentions,
|
| 297 |
+
name="dec_attn",
|
| 298 |
+
)
|
| 299 |
+
self.pos_ff = TFPositionwiseFF(
|
| 300 |
+
d_model,
|
| 301 |
+
d_inner,
|
| 302 |
+
dropout,
|
| 303 |
+
pre_lnorm=pre_lnorm,
|
| 304 |
+
init_std=init_std,
|
| 305 |
+
layer_norm_epsilon=layer_norm_epsilon,
|
| 306 |
+
name="pos_ff",
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
def call(self, dec_inp, r, dec_attn_mask, mems, head_mask, output_attentions, training=False):
|
| 310 |
+
attn_outputs = self.dec_attn(dec_inp, r, dec_attn_mask, mems, head_mask, output_attentions, training=training)
|
| 311 |
+
ff_output = self.pos_ff(attn_outputs[0], training=training)
|
| 312 |
+
|
| 313 |
+
outputs = [ff_output] + attn_outputs[1:]
|
| 314 |
+
|
| 315 |
+
return outputs
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class TFTransfoEmbeddings(keras.layers.Layer):
|
| 319 |
+
def __init__(self, vocab_size, emb_size, init_std, **kwargs):
|
| 320 |
+
super().__init__(**kwargs)
|
| 321 |
+
|
| 322 |
+
self.vocab_size = vocab_size
|
| 323 |
+
self.emb_size = emb_size
|
| 324 |
+
self.init_std = init_std
|
| 325 |
+
|
| 326 |
+
def build(self, input_shape):
|
| 327 |
+
self.weight = self.add_weight(
|
| 328 |
+
shape=(self.vocab_size, self.emb_size),
|
| 329 |
+
initializer=get_initializer(self.init_std),
|
| 330 |
+
name="embeddings",
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
super().build(input_shape)
|
| 334 |
+
|
| 335 |
+
def call(self, inputs):
|
| 336 |
+
return tf.gather(self.weight, inputs)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class TFAdaptiveEmbedding(keras.layers.Layer):
|
| 340 |
+
def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, init_std=0.02, sample_softmax=False, **kwargs):
|
| 341 |
+
super().__init__(**kwargs)
|
| 342 |
+
|
| 343 |
+
self.n_token = n_token
|
| 344 |
+
self.d_embed = d_embed
|
| 345 |
+
self.init_std = init_std
|
| 346 |
+
|
| 347 |
+
self.cutoffs = cutoffs + [n_token]
|
| 348 |
+
self.div_val = div_val
|
| 349 |
+
self.d_proj = d_proj
|
| 350 |
+
|
| 351 |
+
self.emb_scale = d_proj**0.5
|
| 352 |
+
|
| 353 |
+
self.cutoff_ends = [0] + self.cutoffs
|
| 354 |
+
|
| 355 |
+
self.emb_layers = []
|
| 356 |
+
self.emb_projs = []
|
| 357 |
+
|
| 358 |
+
if div_val == 1:
|
| 359 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 360 |
+
else:
|
| 361 |
+
for i in range(len(self.cutoffs)):
|
| 362 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 363 |
+
d_emb_i = d_embed // (div_val**i)
|
| 364 |
+
self.emb_layers.append(
|
| 365 |
+
TFTransfoEmbeddings(
|
| 366 |
+
r_idx - l_idx,
|
| 367 |
+
d_emb_i,
|
| 368 |
+
init_std,
|
| 369 |
+
name=f"emb_layers_._{i}",
|
| 370 |
+
)
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
def build(self, input_shape):
|
| 374 |
+
for i in range(len(self.cutoffs)):
|
| 375 |
+
d_emb_i = self.d_embed // (self.div_val**i)
|
| 376 |
+
self.emb_projs.append(
|
| 377 |
+
self.add_weight(
|
| 378 |
+
shape=(d_emb_i, self.d_proj),
|
| 379 |
+
initializer=get_initializer(self.init_std),
|
| 380 |
+
trainable=True,
|
| 381 |
+
name=f"emb_projs_._{i}",
|
| 382 |
+
)
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
super().build(input_shape)
|
| 386 |
+
|
| 387 |
+
def call(self, inp):
|
| 388 |
+
if self.div_val == 1:
|
| 389 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 390 |
+
else:
|
| 391 |
+
inp_flat = tf.reshape(inp, (-1,))
|
| 392 |
+
emb_flat = tf.zeros([shape_list(inp_flat)[0], self.d_proj])
|
| 393 |
+
for i in range(len(self.cutoffs)):
|
| 394 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 395 |
+
|
| 396 |
+
mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx)
|
| 397 |
+
|
| 398 |
+
inp_i = tf.boolean_mask(inp_flat, mask_i) - l_idx
|
| 399 |
+
emb_i = self.emb_layers[i](inp_i)
|
| 400 |
+
emb_i = tf.einsum("id,de->ie", emb_i, self.emb_projs[i])
|
| 401 |
+
|
| 402 |
+
mask_idx = tf.where(mask_i)
|
| 403 |
+
scatter = tf.scatter_nd(mask_idx, emb_i, shape_list(emb_flat))
|
| 404 |
+
emb_flat = tf.cast(emb_flat, dtype=scatter.dtype)
|
| 405 |
+
emb_flat += scatter
|
| 406 |
+
|
| 407 |
+
embed_shape = shape_list(inp) + [self.d_proj]
|
| 408 |
+
embed = tf.reshape(emb_flat, embed_shape)
|
| 409 |
+
|
| 410 |
+
embed *= self.emb_scale
|
| 411 |
+
|
| 412 |
+
return embed
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
@keras_serializable
|
| 416 |
+
class TFTransfoXLMainLayer(keras.layers.Layer):
|
| 417 |
+
config_class = TransfoXLConfig
|
| 418 |
+
|
| 419 |
+
def __init__(self, config, **kwargs):
|
| 420 |
+
super().__init__(**kwargs)
|
| 421 |
+
|
| 422 |
+
self.config = config
|
| 423 |
+
self.output_hidden_states = config.output_hidden_states
|
| 424 |
+
self.output_attentions = config.output_attentions
|
| 425 |
+
self.return_dict = config.use_return_dict
|
| 426 |
+
|
| 427 |
+
self.n_token = config.vocab_size
|
| 428 |
+
|
| 429 |
+
self.d_embed = config.d_embed
|
| 430 |
+
self.d_model = config.d_model
|
| 431 |
+
self.n_head = config.n_head
|
| 432 |
+
self.d_head = config.d_head
|
| 433 |
+
self.untie_r = config.untie_r
|
| 434 |
+
|
| 435 |
+
self.word_emb = TFAdaptiveEmbedding(
|
| 436 |
+
config.vocab_size,
|
| 437 |
+
config.d_embed,
|
| 438 |
+
config.d_model,
|
| 439 |
+
config.cutoffs,
|
| 440 |
+
div_val=config.div_val,
|
| 441 |
+
init_std=config.init_std,
|
| 442 |
+
name="word_emb",
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
self.drop = keras.layers.Dropout(config.dropout)
|
| 446 |
+
|
| 447 |
+
self.n_layer = config.n_layer
|
| 448 |
+
self.mem_len = config.mem_len
|
| 449 |
+
self.attn_type = config.attn_type
|
| 450 |
+
|
| 451 |
+
self.layers = []
|
| 452 |
+
if config.attn_type == 0: # the default attention
|
| 453 |
+
for i in range(config.n_layer):
|
| 454 |
+
self.layers.append(
|
| 455 |
+
TFRelPartialLearnableDecoderLayer(
|
| 456 |
+
config.n_head,
|
| 457 |
+
config.d_model,
|
| 458 |
+
config.d_head,
|
| 459 |
+
config.d_inner,
|
| 460 |
+
config.dropout,
|
| 461 |
+
dropatt=config.dropatt,
|
| 462 |
+
pre_lnorm=config.pre_lnorm,
|
| 463 |
+
r_w_bias=None if self.untie_r else self.r_w_bias,
|
| 464 |
+
r_r_bias=None if self.untie_r else self.r_r_bias,
|
| 465 |
+
layer_norm_epsilon=config.layer_norm_epsilon,
|
| 466 |
+
init_std=config.init_std,
|
| 467 |
+
output_attentions=self.output_attentions,
|
| 468 |
+
name=f"layers_._{i}",
|
| 469 |
+
)
|
| 470 |
+
)
|
| 471 |
+
else: # learnable embeddings and absolute embeddings
|
| 472 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 473 |
+
|
| 474 |
+
self.same_length = config.same_length
|
| 475 |
+
self.clamp_len = config.clamp_len
|
| 476 |
+
|
| 477 |
+
if self.attn_type == 0: # default attention
|
| 478 |
+
self.pos_emb = TFPositionalEmbedding(self.d_model, name="pos_emb")
|
| 479 |
+
else: # learnable embeddings and absolute embeddings
|
| 480 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 481 |
+
|
| 482 |
+
def build(self, input_shape):
|
| 483 |
+
if not self.untie_r:
|
| 484 |
+
self.r_w_bias = self.add_weight(
|
| 485 |
+
shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_w_bias"
|
| 486 |
+
)
|
| 487 |
+
self.r_r_bias = self.add_weight(
|
| 488 |
+
shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_r_bias"
|
| 489 |
+
)
|
| 490 |
+
super().build(input_shape)
|
| 491 |
+
|
| 492 |
+
def get_input_embeddings(self):
|
| 493 |
+
return self.word_emb
|
| 494 |
+
|
| 495 |
+
def set_input_embeddings(self, value):
|
| 496 |
+
raise NotImplementedError
|
| 497 |
+
|
| 498 |
+
def backward_compatible(self):
|
| 499 |
+
self.sample_softmax = -1
|
| 500 |
+
|
| 501 |
+
def reset_memory_length(self, mem_len):
|
| 502 |
+
self.mem_len = mem_len
|
| 503 |
+
|
| 504 |
+
def _prune_heads(self, heads):
|
| 505 |
+
raise NotImplementedError
|
| 506 |
+
|
| 507 |
+
def init_mems(self, bsz):
|
| 508 |
+
if self.mem_len > 0:
|
| 509 |
+
mems = []
|
| 510 |
+
for i in range(self.n_layer):
|
| 511 |
+
empty = tf.zeros([self.mem_len, bsz, self.d_model])
|
| 512 |
+
mems.append(empty)
|
| 513 |
+
|
| 514 |
+
return mems
|
| 515 |
+
else:
|
| 516 |
+
return None
|
| 517 |
+
|
| 518 |
+
def _update_mems(self, hids, mems, mlen, qlen):
|
| 519 |
+
# does not deal with None
|
| 520 |
+
if mems is None:
|
| 521 |
+
return None
|
| 522 |
+
|
| 523 |
+
# mems is not None
|
| 524 |
+
assert len(hids) == len(mems), "len(hids) != len(mems)"
|
| 525 |
+
|
| 526 |
+
# There are `mlen + qlen` steps that can be cached into mems
|
| 527 |
+
new_mems = []
|
| 528 |
+
end_idx = mlen + tf.math.maximum(0, qlen)
|
| 529 |
+
beg_idx = tf.math.maximum(0, end_idx - tf.convert_to_tensor(self.mem_len))
|
| 530 |
+
for i in range(len(hids)):
|
| 531 |
+
mems[i] = tf.cast(mems[i], dtype=hids[i].dtype)
|
| 532 |
+
cat = tf.concat([mems[i], hids[i]], axis=0)
|
| 533 |
+
tf.stop_gradient(cat)
|
| 534 |
+
new_mems.append(cat[beg_idx:end_idx])
|
| 535 |
+
|
| 536 |
+
return new_mems
|
| 537 |
+
|
| 538 |
+
@unpack_inputs
|
| 539 |
+
def call(
|
| 540 |
+
self,
|
| 541 |
+
input_ids: TFModelInputType | None = None,
|
| 542 |
+
mems: list[tf.Tensor] | None = None,
|
| 543 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 544 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 545 |
+
output_attentions: bool | None = None,
|
| 546 |
+
output_hidden_states: bool | None = None,
|
| 547 |
+
return_dict: bool | None = None,
|
| 548 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 549 |
+
training: bool = False,
|
| 550 |
+
):
|
| 551 |
+
# the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library
|
| 552 |
+
# so we transpose here from shape [bsz, len] to shape [len, bsz]
|
| 553 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 554 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 555 |
+
elif input_ids is not None:
|
| 556 |
+
input_ids = tf.transpose(input_ids, perm=(1, 0))
|
| 557 |
+
qlen, bsz = shape_list(input_ids)
|
| 558 |
+
elif inputs_embeds is not None:
|
| 559 |
+
inputs_embeds = tf.transpose(inputs_embeds, perm=(1, 0, 2))
|
| 560 |
+
qlen, bsz = shape_list(inputs_embeds)[:2]
|
| 561 |
+
else:
|
| 562 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 563 |
+
|
| 564 |
+
if mems is None:
|
| 565 |
+
mems = self.init_mems(bsz)
|
| 566 |
+
|
| 567 |
+
# Prepare head mask if needed
|
| 568 |
+
# 1.0 in head_mask indicate we keep the head
|
| 569 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 570 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer)
|
| 571 |
+
# and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head]
|
| 572 |
+
if head_mask is not None:
|
| 573 |
+
raise NotImplementedError
|
| 574 |
+
else:
|
| 575 |
+
head_mask = [None] * self.n_layer
|
| 576 |
+
|
| 577 |
+
if inputs_embeds is not None:
|
| 578 |
+
word_emb = inputs_embeds
|
| 579 |
+
else:
|
| 580 |
+
word_emb = self.word_emb(input_ids)
|
| 581 |
+
|
| 582 |
+
mlen = shape_list(mems[0])[0] if mems is not None else 0
|
| 583 |
+
klen = mlen + qlen
|
| 584 |
+
|
| 585 |
+
# Compute decoder attention mask
|
| 586 |
+
all_ones = tf.ones([qlen, klen], dtype=tf.int32)
|
| 587 |
+
upper_mask = 1 - tf.linalg.band_part(tf.ones([qlen, klen], dtype=tf.int32), -1, mlen)
|
| 588 |
+
if self.same_length:
|
| 589 |
+
mask_len = klen - self.mem_len
|
| 590 |
+
mask_shift_len = qlen - tf.nn.relu(mask_len) # Lazy clamping of negatives to zero
|
| 591 |
+
|
| 592 |
+
# Use an indicator variable instead of a conditional to keep the compiler happy
|
| 593 |
+
lower_mask = tf.linalg.band_part(all_ones, -1, 0) - (
|
| 594 |
+
tf.linalg.band_part(all_ones, mask_shift_len - 1, 0) * tf.cast(mask_shift_len != 0, tf.int32)
|
| 595 |
+
)
|
| 596 |
+
dec_attn_mask = upper_mask + lower_mask
|
| 597 |
+
else:
|
| 598 |
+
dec_attn_mask = upper_mask
|
| 599 |
+
|
| 600 |
+
hids = []
|
| 601 |
+
attentions = [] if output_attentions else None
|
| 602 |
+
if self.attn_type == 0: # default
|
| 603 |
+
pos_seq = tf.range(klen - 1, -1, -1.0)
|
| 604 |
+
if self.clamp_len > 0:
|
| 605 |
+
pos_seq = tf.minimum(pos_seq, self.clamp_len)
|
| 606 |
+
pos_emb = self.pos_emb(pos_seq)
|
| 607 |
+
|
| 608 |
+
core_out = self.drop(word_emb, training=training)
|
| 609 |
+
pos_emb = self.drop(pos_emb, training=training)
|
| 610 |
+
|
| 611 |
+
for i, layer in enumerate(self.layers):
|
| 612 |
+
hids.append(core_out)
|
| 613 |
+
mems_i = None if mems is None else mems[i]
|
| 614 |
+
layer_outputs = layer(
|
| 615 |
+
core_out,
|
| 616 |
+
pos_emb,
|
| 617 |
+
dec_attn_mask,
|
| 618 |
+
mems_i,
|
| 619 |
+
head_mask[i],
|
| 620 |
+
output_attentions,
|
| 621 |
+
training=training,
|
| 622 |
+
)
|
| 623 |
+
core_out = layer_outputs[0]
|
| 624 |
+
if output_attentions:
|
| 625 |
+
attentions.append(layer_outputs[1])
|
| 626 |
+
else: # learnable embeddings and absolute embeddings
|
| 627 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 628 |
+
|
| 629 |
+
core_out = self.drop(core_out, training=training)
|
| 630 |
+
|
| 631 |
+
new_mems = self._update_mems(hids, mems, mlen, qlen)
|
| 632 |
+
|
| 633 |
+
# We transpose back here to shape [bsz, len, hidden_dim]
|
| 634 |
+
core_out = tf.transpose(core_out, perm=(1, 0, 2))
|
| 635 |
+
|
| 636 |
+
if output_hidden_states:
|
| 637 |
+
# Transpose to library standard shape [bsz, len, hidden_dim] and add last layer
|
| 638 |
+
hids = tuple(tf.transpose(t, perm=(1, 0, 2)) for t in hids)
|
| 639 |
+
hids = hids + (core_out,)
|
| 640 |
+
else:
|
| 641 |
+
hids = None
|
| 642 |
+
if output_attentions:
|
| 643 |
+
# Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len]
|
| 644 |
+
attentions = tuple(tf.transpose(t, perm=(2, 3, 0, 1)) for t in attentions)
|
| 645 |
+
|
| 646 |
+
if not return_dict:
|
| 647 |
+
return tuple(v for v in [core_out, new_mems, hids, attentions] if v is not None)
|
| 648 |
+
|
| 649 |
+
return TFTransfoXLModelOutput(
|
| 650 |
+
last_hidden_state=core_out,
|
| 651 |
+
mems=new_mems,
|
| 652 |
+
hidden_states=hids,
|
| 653 |
+
attentions=attentions,
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
class TFTransfoXLPreTrainedModel(TFPreTrainedModel):
|
| 658 |
+
"""
|
| 659 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 660 |
+
models.
|
| 661 |
+
"""
|
| 662 |
+
|
| 663 |
+
config_class = TransfoXLConfig
|
| 664 |
+
base_model_prefix = "transformer"
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
@dataclass
|
| 668 |
+
class TFTransfoXLModelOutput(ModelOutput):
|
| 669 |
+
"""
|
| 670 |
+
Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
|
| 671 |
+
|
| 672 |
+
Args:
|
| 673 |
+
last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 674 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 675 |
+
mems (`list[tf.Tensor]` of length `config.n_layers`):
|
| 676 |
+
Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
|
| 677 |
+
input) to speed up sequential decoding. The token ids which have their past given to this model should not
|
| 678 |
+
be passed as input ids as they have already been computed.
|
| 679 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 680 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 681 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 682 |
+
|
| 683 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 684 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 685 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 686 |
+
sequence_length)`.
|
| 687 |
+
|
| 688 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 689 |
+
heads.
|
| 690 |
+
"""
|
| 691 |
+
|
| 692 |
+
last_hidden_state: tf.Tensor | None = None
|
| 693 |
+
mems: list[tf.Tensor] = None
|
| 694 |
+
hidden_states: tuple[tf.Tensor] | None = None
|
| 695 |
+
attentions: tuple[tf.Tensor] | None = None
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
@dataclass
|
| 699 |
+
class TFTransfoXLLMHeadModelOutput(ModelOutput):
|
| 700 |
+
"""
|
| 701 |
+
Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
|
| 702 |
+
|
| 703 |
+
Args:
|
| 704 |
+
losses (`tf.Tensor` of shape *(batch_size, sequence_length-1)*, *optional*, returned when `labels` is provided):
|
| 705 |
+
Language modeling losses (not reduced).
|
| 706 |
+
prediction_scores (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 707 |
+
Prediction scores of the language modeling head (scores for each vocabulary token after SoftMax).
|
| 708 |
+
mems (`list[tf.Tensor]` of length `config.n_layers`):
|
| 709 |
+
Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
|
| 710 |
+
input) to speed up sequential decoding. The token ids which have their past given to this model should not
|
| 711 |
+
be passed as input ids as they have already been computed.
|
| 712 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 713 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 714 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 715 |
+
|
| 716 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 717 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 718 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 719 |
+
sequence_length)`.
|
| 720 |
+
|
| 721 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 722 |
+
heads.
|
| 723 |
+
"""
|
| 724 |
+
|
| 725 |
+
prediction_scores: tf.Tensor | None = None
|
| 726 |
+
mems: list[tf.Tensor] = None
|
| 727 |
+
hidden_states: tuple[tf.Tensor] | None = None
|
| 728 |
+
attentions: tuple[tf.Tensor] | None = None
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
@dataclass
|
| 732 |
+
class TFTransfoXLSequenceClassifierOutputWithPast(ModelOutput):
|
| 733 |
+
"""
|
| 734 |
+
Base class for outputs of sentence classification models.
|
| 735 |
+
|
| 736 |
+
Args:
|
| 737 |
+
loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 738 |
+
Classification (or regression if config.num_labels==1) loss.
|
| 739 |
+
logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
|
| 740 |
+
Classification (or regression if config.num_labels==1) scores (before SoftMax).
|
| 741 |
+
mems (`list[tf.Tensor]` of length `config.n_layers`):
|
| 742 |
+
Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
|
| 743 |
+
input) to speed up sequential decoding. The token ids which have their past given to this model should not
|
| 744 |
+
be passed as input ids as they have already been computed.
|
| 745 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 746 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 747 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 748 |
+
|
| 749 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 750 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 751 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 752 |
+
sequence_length)`.
|
| 753 |
+
|
| 754 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 755 |
+
heads.
|
| 756 |
+
"""
|
| 757 |
+
|
| 758 |
+
loss: tf.Tensor | None = None
|
| 759 |
+
logits: tf.Tensor | None = None
|
| 760 |
+
mems: list[tf.Tensor] = None
|
| 761 |
+
hidden_states: tuple[tf.Tensor] | None = None
|
| 762 |
+
attentions: tuple[tf.Tensor] | None = None
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
TRANSFO_XL_START_DOCSTRING = r"""
|
| 766 |
+
|
| 767 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 768 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 769 |
+
etc.)
|
| 770 |
+
|
| 771 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 772 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 773 |
+
behavior.
|
| 774 |
+
|
| 775 |
+
<Tip>
|
| 776 |
+
|
| 777 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 778 |
+
|
| 779 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 780 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 781 |
+
|
| 782 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 783 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 784 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 785 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 786 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 787 |
+
positional argument:
|
| 788 |
+
|
| 789 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 790 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 791 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 792 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 793 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 794 |
+
|
| 795 |
+
Note that when creating models and layers with
|
| 796 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 797 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 798 |
+
|
| 799 |
+
</Tip>
|
| 800 |
+
|
| 801 |
+
Parameters:
|
| 802 |
+
config ([`TransfoXLConfig`]): Model configuration class with all the parameters of the model.
|
| 803 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 804 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 805 |
+
"""
|
| 806 |
+
|
| 807 |
+
TRANSFO_XL_INPUTS_DOCSTRING = r"""
|
| 808 |
+
Args:
|
| 809 |
+
input_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`):
|
| 810 |
+
Indices of input sequence tokens in the vocabulary.
|
| 811 |
+
|
| 812 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 813 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 814 |
+
|
| 815 |
+
[What are input IDs?](../glossary#input-ids)
|
| 816 |
+
mems (`list[tf.Tensor]` of length `config.n_layers`):
|
| 817 |
+
Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
|
| 818 |
+
`mems` output below). Can be used to speed up sequential decoding. The token ids which have their mems
|
| 819 |
+
given to this model should not be passed as `input_ids` as they have already been computed.
|
| 820 |
+
head_mask (`tf.Tensor` or `Numpy array` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 821 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 822 |
+
|
| 823 |
+
- 1 indicates the head is **not masked**,
|
| 824 |
+
- 0 indicates the head is **masked**.
|
| 825 |
+
inputs_embeds (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 826 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 827 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 828 |
+
model's internal embedding lookup matrix.
|
| 829 |
+
output_attentions (`bool`, *optional*):
|
| 830 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 831 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 832 |
+
config will be used instead.
|
| 833 |
+
output_hidden_states (`bool`, *optional*):
|
| 834 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 835 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 836 |
+
used instead.
|
| 837 |
+
return_dict (`bool`, *optional*):
|
| 838 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 839 |
+
eager mode, in graph mode the value will always be set to True.
|
| 840 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 841 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 842 |
+
behaviors between training and evaluation).
|
| 843 |
+
"""
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
@add_start_docstrings(
|
| 847 |
+
"The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
|
| 848 |
+
TRANSFO_XL_START_DOCSTRING,
|
| 849 |
+
)
|
| 850 |
+
class TFTransfoXLModel(TFTransfoXLPreTrainedModel):
|
| 851 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 852 |
+
super().__init__(config, *inputs, **kwargs)
|
| 853 |
+
self.transformer = TFTransfoXLMainLayer(config, name="transformer")
|
| 854 |
+
|
| 855 |
+
@unpack_inputs
|
| 856 |
+
@add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
|
| 857 |
+
@add_code_sample_docstrings(
|
| 858 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 859 |
+
output_type=TFTransfoXLModelOutput,
|
| 860 |
+
config_class=_CONFIG_FOR_DOC,
|
| 861 |
+
)
|
| 862 |
+
def call(
|
| 863 |
+
self,
|
| 864 |
+
input_ids: TFModelInputType | None = None,
|
| 865 |
+
mems: list[tf.Tensor] | None = None,
|
| 866 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 867 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 868 |
+
output_attentions: bool | None = None,
|
| 869 |
+
output_hidden_states: bool | None = None,
|
| 870 |
+
return_dict: bool | None = None,
|
| 871 |
+
training: bool = False,
|
| 872 |
+
) -> TFTransfoXLModelOutput | tuple[tf.Tensor]:
|
| 873 |
+
outputs = self.transformer(
|
| 874 |
+
input_ids=input_ids,
|
| 875 |
+
mems=mems,
|
| 876 |
+
head_mask=head_mask,
|
| 877 |
+
inputs_embeds=inputs_embeds,
|
| 878 |
+
output_attentions=output_attentions,
|
| 879 |
+
output_hidden_states=output_hidden_states,
|
| 880 |
+
return_dict=return_dict,
|
| 881 |
+
training=training,
|
| 882 |
+
)
|
| 883 |
+
|
| 884 |
+
return outputs
|
| 885 |
+
|
| 886 |
+
|
| 887 |
+
@add_start_docstrings(
|
| 888 |
+
"""
|
| 889 |
+
The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive
|
| 890 |
+
input embeddings)
|
| 891 |
+
""",
|
| 892 |
+
TRANSFO_XL_START_DOCSTRING,
|
| 893 |
+
)
|
| 894 |
+
class TFTransfoXLLMHeadModel(TFTransfoXLPreTrainedModel):
|
| 895 |
+
def __init__(self, config):
|
| 896 |
+
super().__init__(config)
|
| 897 |
+
self.transformer = TFTransfoXLMainLayer(config, name="transformer")
|
| 898 |
+
self.sample_softmax = config.sample_softmax
|
| 899 |
+
assert self.sample_softmax <= 0, (
|
| 900 |
+
"Sampling from the softmax is not implemented yet. Please look at issue: #3310:"
|
| 901 |
+
" https://github.com/huggingface/transformers/issues/3310"
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
self.crit = TFAdaptiveSoftmaxMask(
|
| 905 |
+
config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val, name="crit"
|
| 906 |
+
)
|
| 907 |
+
|
| 908 |
+
def _resize_token_embeddings(self, new_num_tokens):
|
| 909 |
+
raise NotImplementedError()
|
| 910 |
+
|
| 911 |
+
def get_output_embeddings(self):
|
| 912 |
+
"""Double-check if you are using adaptive softmax."""
|
| 913 |
+
if len(self.crit.out_layers) > 0:
|
| 914 |
+
return self.crit.out_layers[-1]
|
| 915 |
+
return None
|
| 916 |
+
|
| 917 |
+
def reset_memory_length(self, mem_len):
|
| 918 |
+
self.transformer.reset_memory_length(mem_len)
|
| 919 |
+
|
| 920 |
+
def init_mems(self, bsz):
|
| 921 |
+
return self.transformer.init_mems(bsz)
|
| 922 |
+
|
| 923 |
+
@unpack_inputs
|
| 924 |
+
@add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
|
| 925 |
+
@add_code_sample_docstrings(
|
| 926 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 927 |
+
output_type=TFTransfoXLLMHeadModelOutput,
|
| 928 |
+
config_class=_CONFIG_FOR_DOC,
|
| 929 |
+
)
|
| 930 |
+
def call(
|
| 931 |
+
self,
|
| 932 |
+
input_ids: TFModelInputType | None = None,
|
| 933 |
+
mems: list[tf.Tensor] | None = None,
|
| 934 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 935 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 936 |
+
output_attentions: bool | None = None,
|
| 937 |
+
output_hidden_states: bool | None = None,
|
| 938 |
+
return_dict: bool | None = None,
|
| 939 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 940 |
+
training: bool = False,
|
| 941 |
+
) -> TFTransfoXLLMHeadModelOutput | tuple[tf.Tensor]:
|
| 942 |
+
if input_ids is not None:
|
| 943 |
+
bsz, tgt_len = shape_list(input_ids)[:2]
|
| 944 |
+
else:
|
| 945 |
+
bsz, tgt_len = shape_list(inputs_embeds)[:2]
|
| 946 |
+
|
| 947 |
+
transformer_outputs = self.transformer(
|
| 948 |
+
input_ids,
|
| 949 |
+
mems,
|
| 950 |
+
head_mask,
|
| 951 |
+
inputs_embeds,
|
| 952 |
+
output_attentions,
|
| 953 |
+
output_hidden_states,
|
| 954 |
+
return_dict,
|
| 955 |
+
training=training,
|
| 956 |
+
)
|
| 957 |
+
|
| 958 |
+
last_hidden = transformer_outputs[0]
|
| 959 |
+
pred_hid = last_hidden[:, -tgt_len:]
|
| 960 |
+
|
| 961 |
+
softmax_output = self.crit(pred_hid, labels, training=training)
|
| 962 |
+
prediction_scores = softmax_output if labels is None else ()
|
| 963 |
+
|
| 964 |
+
if not return_dict:
|
| 965 |
+
return (prediction_scores,) + transformer_outputs[1:]
|
| 966 |
+
|
| 967 |
+
return TFTransfoXLLMHeadModelOutput(
|
| 968 |
+
prediction_scores=prediction_scores,
|
| 969 |
+
mems=transformer_outputs.mems,
|
| 970 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 971 |
+
attentions=transformer_outputs.attentions,
|
| 972 |
+
)
|
| 973 |
+
|
| 974 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **model_kwargs):
|
| 975 |
+
inputs = {}
|
| 976 |
+
|
| 977 |
+
# if past is defined in model kwargs then use it for faster decoding
|
| 978 |
+
if past_key_values:
|
| 979 |
+
input_ids = tf.expand_dims(input_ids[:, -1], axis=-1)
|
| 980 |
+
else:
|
| 981 |
+
input_ids = input_ids
|
| 982 |
+
|
| 983 |
+
return inputs
|
| 984 |
+
|
| 985 |
+
# Adapted from the torch tie_weights function
|
| 986 |
+
def tf_to_pt_weight_rename(self, tf_weight):
|
| 987 |
+
if self.config.tie_word_embeddings and "crit.out_layers" in tf_weight:
|
| 988 |
+
return tf_weight, tf_weight.replace("crit.out_layers", "transformer.word_emb.emb_layers")
|
| 989 |
+
elif self.config.tie_projs and "crit.out_projs" in tf_weight:
|
| 990 |
+
for i, tie_proj in enumerate(self.config.tie_projs):
|
| 991 |
+
if tie_proj and self.config.div_val == 1 and self.config.d_model != self.config.d_embed:
|
| 992 |
+
# self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[0]
|
| 993 |
+
return tf_weight, tf_weight.replace(f"crit.out_projs.{i}", "transformer.word_emb.emb_projs.0")
|
| 994 |
+
elif tie_proj and self.config.div_val != 1:
|
| 995 |
+
# self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[i]
|
| 996 |
+
return tf_weight, tf_weight.replace("crit.out_projs", "transformer.word_emb.emb_projs")
|
| 997 |
+
else:
|
| 998 |
+
return (tf_weight,)
|
| 999 |
+
|
| 1000 |
+
|
| 1001 |
+
@add_start_docstrings(
|
| 1002 |
+
"""
|
| 1003 |
+
The Transfo XL Model transformer with a sequence classification head on top (linear layer).
|
| 1004 |
+
|
| 1005 |
+
[`TFTransfoXLForSequenceClassification`] uses the last token in order to do the classification, as other causal
|
| 1006 |
+
models (e.g. GPT-1,GPT-2) do.
|
| 1007 |
+
|
| 1008 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 1009 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 1010 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 1011 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 1012 |
+
each row of the batch).
|
| 1013 |
+
""",
|
| 1014 |
+
TRANSFO_XL_START_DOCSTRING,
|
| 1015 |
+
)
|
| 1016 |
+
class TFTransfoXLForSequenceClassification(TFTransfoXLPreTrainedModel, TFSequenceClassificationLoss):
|
| 1017 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1018 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1019 |
+
self.num_labels = config.num_labels
|
| 1020 |
+
self.score = keras.layers.Dense(
|
| 1021 |
+
config.num_labels,
|
| 1022 |
+
kernel_initializer=get_initializer(config.init_range),
|
| 1023 |
+
name="score",
|
| 1024 |
+
use_bias=False,
|
| 1025 |
+
)
|
| 1026 |
+
self.transformer = TFTransfoXLMainLayer(config, name="transformer")
|
| 1027 |
+
|
| 1028 |
+
def get_output_embeddings(self):
|
| 1029 |
+
# Remove after transformers v4.32. Fix this model's `test_model_common_attributes` test too.
|
| 1030 |
+
logger.warning(
|
| 1031 |
+
"Sequence classification models do not have output embeddings. `.get_output_embeddings` will be removed "
|
| 1032 |
+
"in transformers v4.32."
|
| 1033 |
+
)
|
| 1034 |
+
return self.transformer.word_emb
|
| 1035 |
+
|
| 1036 |
+
@unpack_inputs
|
| 1037 |
+
@add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
|
| 1038 |
+
@add_code_sample_docstrings(
|
| 1039 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1040 |
+
output_type=TFTransfoXLSequenceClassifierOutputWithPast,
|
| 1041 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1042 |
+
)
|
| 1043 |
+
def call(
|
| 1044 |
+
self,
|
| 1045 |
+
input_ids: TFModelInputType | None = None,
|
| 1046 |
+
mems: list[tf.Tensor] | None = None,
|
| 1047 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1048 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1049 |
+
output_attentions: bool | None = None,
|
| 1050 |
+
output_hidden_states: bool | None = None,
|
| 1051 |
+
return_dict: bool | None = None,
|
| 1052 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1053 |
+
training: bool | None = False,
|
| 1054 |
+
) -> tuple | TFTransfoXLSequenceClassifierOutputWithPast:
|
| 1055 |
+
r"""
|
| 1056 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1057 |
+
Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
|
| 1058 |
+
config.vocab_size - 1]`.
|
| 1059 |
+
"""
|
| 1060 |
+
transformer_outputs = self.transformer(
|
| 1061 |
+
input_ids=input_ids,
|
| 1062 |
+
mems=mems,
|
| 1063 |
+
head_mask=head_mask,
|
| 1064 |
+
inputs_embeds=inputs_embeds,
|
| 1065 |
+
output_attentions=output_attentions,
|
| 1066 |
+
output_hidden_states=output_hidden_states,
|
| 1067 |
+
return_dict=return_dict,
|
| 1068 |
+
training=training,
|
| 1069 |
+
)
|
| 1070 |
+
|
| 1071 |
+
hidden_states = transformer_outputs[0]
|
| 1072 |
+
logits = self.score(hidden_states)
|
| 1073 |
+
in_logits = None
|
| 1074 |
+
if self.config.pad_token_id is None:
|
| 1075 |
+
sequence_lengths = -1
|
| 1076 |
+
else:
|
| 1077 |
+
if input_ids is not None:
|
| 1078 |
+
sequence_lengths = (
|
| 1079 |
+
tf.argmax(tf.cast(tf.math.equal(input_ids, self.config.pad_token_id), input_ids.dtype), axis=-1)
|
| 1080 |
+
- 1
|
| 1081 |
+
)
|
| 1082 |
+
sequence_lengths = tf.where(sequence_lengths >= 0, sequence_lengths, input_ids.shape[-1] - 1)
|
| 1083 |
+
in_logits = tf.gather(logits, sequence_lengths, batch_dims=1, axis=1)
|
| 1084 |
+
else:
|
| 1085 |
+
sequence_lengths = -1
|
| 1086 |
+
logger.warning_once(
|
| 1087 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
| 1088 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
| 1089 |
+
)
|
| 1090 |
+
loss = None
|
| 1091 |
+
|
| 1092 |
+
if labels is not None:
|
| 1093 |
+
if input_ids is not None:
|
| 1094 |
+
batch_size, sequence_length = shape_list(input_ids)[:2]
|
| 1095 |
+
else:
|
| 1096 |
+
batch_size, sequence_length = shape_list(inputs_embeds)[:2]
|
| 1097 |
+
assert self.config.pad_token_id is not None or batch_size == 1, (
|
| 1098 |
+
"Cannot handle batch sizes > 1 if no padding token is defined."
|
| 1099 |
+
)
|
| 1100 |
+
|
| 1101 |
+
if not tf.is_tensor(sequence_lengths):
|
| 1102 |
+
in_logits = logits[0:batch_size, sequence_lengths]
|
| 1103 |
+
|
| 1104 |
+
loss = self.hf_compute_loss(tf.reshape(labels, [-1, 1]), tf.reshape(in_logits, [-1, self.num_labels]))
|
| 1105 |
+
|
| 1106 |
+
pooled_logits = in_logits if in_logits is not None else logits
|
| 1107 |
+
|
| 1108 |
+
if not return_dict:
|
| 1109 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1110 |
+
return ((loss,) + output) if loss is not None else output
|
| 1111 |
+
|
| 1112 |
+
return TFTransfoXLSequenceClassifierOutputWithPast(
|
| 1113 |
+
loss=loss,
|
| 1114 |
+
logits=pooled_logits,
|
| 1115 |
+
mems=transformer_outputs.mems,
|
| 1116 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1117 |
+
attentions=transformer_outputs.attentions,
|
| 1118 |
+
)
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
__all__ = [
|
| 1122 |
+
"TFAdaptiveEmbedding",
|
| 1123 |
+
"TFTransfoXLForSequenceClassification",
|
| 1124 |
+
"TFTransfoXLLMHeadModel",
|
| 1125 |
+
"TFTransfoXLMainLayer",
|
| 1126 |
+
"TFTransfoXLModel",
|
| 1127 |
+
"TFTransfoXLPreTrainedModel",
|
| 1128 |
+
]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University 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 |
+
"""
|
| 17 |
+
A TF 2.0 Adaptive Softmax for Transformer XL model.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import tensorflow as tf
|
| 21 |
+
|
| 22 |
+
from ....modeling_tf_utils import keras
|
| 23 |
+
from ....tf_utils import shape_list
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class TFAdaptiveSoftmaxMask(keras.layers.Layer):
|
| 27 |
+
def __init__(self, vocab_size, d_embed, d_proj, cutoffs, div_val=1, keep_order=False, **kwargs):
|
| 28 |
+
super().__init__(**kwargs)
|
| 29 |
+
|
| 30 |
+
self.vocab_size = vocab_size
|
| 31 |
+
self.d_embed = d_embed
|
| 32 |
+
self.d_proj = d_proj
|
| 33 |
+
|
| 34 |
+
self.cutoffs = cutoffs + [vocab_size]
|
| 35 |
+
self.cutoff_ends = [0] + self.cutoffs
|
| 36 |
+
self.div_val = div_val
|
| 37 |
+
|
| 38 |
+
self.shortlist_size = self.cutoffs[0]
|
| 39 |
+
self.n_clusters = len(self.cutoffs) - 1
|
| 40 |
+
self.head_size = self.shortlist_size + self.n_clusters
|
| 41 |
+
self.keep_order = keep_order
|
| 42 |
+
|
| 43 |
+
self.out_layers = []
|
| 44 |
+
self.out_projs = []
|
| 45 |
+
|
| 46 |
+
def build(self, input_shape):
|
| 47 |
+
if self.n_clusters > 0:
|
| 48 |
+
self.cluster_weight = self.add_weight(
|
| 49 |
+
shape=(self.n_clusters, self.d_embed), initializer="zeros", trainable=True, name="cluster_weight"
|
| 50 |
+
)
|
| 51 |
+
self.cluster_bias = self.add_weight(
|
| 52 |
+
shape=(self.n_clusters,), initializer="zeros", trainable=True, name="cluster_bias"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
if self.div_val == 1:
|
| 56 |
+
for i in range(len(self.cutoffs)):
|
| 57 |
+
if self.d_proj != self.d_embed:
|
| 58 |
+
weight = self.add_weight(
|
| 59 |
+
shape=(self.d_embed, self.d_proj),
|
| 60 |
+
initializer="zeros",
|
| 61 |
+
trainable=True,
|
| 62 |
+
name=f"out_projs_._{i}",
|
| 63 |
+
)
|
| 64 |
+
self.out_projs.append(weight)
|
| 65 |
+
else:
|
| 66 |
+
self.out_projs.append(None)
|
| 67 |
+
weight = self.add_weight(
|
| 68 |
+
shape=(self.vocab_size, self.d_embed),
|
| 69 |
+
initializer="zeros",
|
| 70 |
+
trainable=True,
|
| 71 |
+
name=f"out_layers_._{i}_._weight",
|
| 72 |
+
)
|
| 73 |
+
bias = self.add_weight(
|
| 74 |
+
shape=(self.vocab_size,),
|
| 75 |
+
initializer="zeros",
|
| 76 |
+
trainable=True,
|
| 77 |
+
name=f"out_layers_._{i}_._bias",
|
| 78 |
+
)
|
| 79 |
+
self.out_layers.append((weight, bias))
|
| 80 |
+
else:
|
| 81 |
+
for i in range(len(self.cutoffs)):
|
| 82 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 83 |
+
d_emb_i = self.d_embed // (self.div_val**i)
|
| 84 |
+
|
| 85 |
+
weight = self.add_weight(
|
| 86 |
+
shape=(d_emb_i, self.d_proj), initializer="zeros", trainable=True, name=f"out_projs_._{i}"
|
| 87 |
+
)
|
| 88 |
+
self.out_projs.append(weight)
|
| 89 |
+
weight = self.add_weight(
|
| 90 |
+
shape=(r_idx - l_idx, d_emb_i),
|
| 91 |
+
initializer="zeros",
|
| 92 |
+
trainable=True,
|
| 93 |
+
name=f"out_layers_._{i}_._weight",
|
| 94 |
+
)
|
| 95 |
+
bias = self.add_weight(
|
| 96 |
+
shape=(r_idx - l_idx,),
|
| 97 |
+
initializer="zeros",
|
| 98 |
+
trainable=True,
|
| 99 |
+
name=f"out_layers_._{i}_._bias",
|
| 100 |
+
)
|
| 101 |
+
self.out_layers.append((weight, bias))
|
| 102 |
+
super().build(input_shape)
|
| 103 |
+
|
| 104 |
+
@staticmethod
|
| 105 |
+
def _logit(x, W, b, proj=None):
|
| 106 |
+
y = x
|
| 107 |
+
if proj is not None:
|
| 108 |
+
y = tf.einsum("ibd,ed->ibe", y, proj)
|
| 109 |
+
return tf.einsum("ibd,nd->ibn", y, W) + b
|
| 110 |
+
|
| 111 |
+
@staticmethod
|
| 112 |
+
def _gather_logprob(logprob, target):
|
| 113 |
+
lp_size = shape_list(logprob)
|
| 114 |
+
r = tf.range(lp_size[0], dtype=target.dtype)
|
| 115 |
+
idx = tf.stack([r, target], 1)
|
| 116 |
+
return tf.gather_nd(logprob, idx)
|
| 117 |
+
|
| 118 |
+
def call(self, hidden, target, return_mean=True, training=False):
|
| 119 |
+
head_logprob = 0
|
| 120 |
+
if self.n_clusters == 0:
|
| 121 |
+
output = self._logit(hidden, self.out_layers[0][0], self.out_layers[0][1], self.out_projs[0])
|
| 122 |
+
if target is not None:
|
| 123 |
+
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=target, logits=output)
|
| 124 |
+
out = tf.nn.log_softmax(output, axis=-1)
|
| 125 |
+
else:
|
| 126 |
+
hidden_sizes = shape_list(hidden)
|
| 127 |
+
out = []
|
| 128 |
+
loss = tf.zeros(hidden_sizes[:2])
|
| 129 |
+
for i in range(len(self.cutoffs)):
|
| 130 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 131 |
+
if target is not None:
|
| 132 |
+
mask = (target >= l_idx) & (target < r_idx)
|
| 133 |
+
mask_idx = tf.where(mask)
|
| 134 |
+
cur_target = tf.boolean_mask(target, mask) - l_idx
|
| 135 |
+
|
| 136 |
+
if self.div_val == 1:
|
| 137 |
+
cur_W = self.out_layers[0][0][l_idx:r_idx]
|
| 138 |
+
cur_b = self.out_layers[0][1][l_idx:r_idx]
|
| 139 |
+
else:
|
| 140 |
+
cur_W = self.out_layers[i][0]
|
| 141 |
+
cur_b = self.out_layers[i][1]
|
| 142 |
+
|
| 143 |
+
if i == 0:
|
| 144 |
+
cur_W = tf.concat([cur_W, self.cluster_weight], 0)
|
| 145 |
+
cur_b = tf.concat([cur_b, self.cluster_bias], 0)
|
| 146 |
+
|
| 147 |
+
head_logit = self._logit(hidden, cur_W, cur_b, self.out_projs[0])
|
| 148 |
+
head_logprob = tf.nn.log_softmax(head_logit)
|
| 149 |
+
out.append(head_logprob[..., : self.cutoffs[0]])
|
| 150 |
+
if target is not None:
|
| 151 |
+
cur_head_logprob = tf.boolean_mask(head_logprob, mask)
|
| 152 |
+
cur_logprob = self._gather_logprob(cur_head_logprob, cur_target)
|
| 153 |
+
else:
|
| 154 |
+
tail_logit = self._logit(hidden, cur_W, cur_b, self.out_projs[i])
|
| 155 |
+
tail_logprob = tf.nn.log_softmax(tail_logit)
|
| 156 |
+
cluster_prob_idx = self.cutoffs[0] + i - 1 # No probability for the head cluster
|
| 157 |
+
logprob_i = head_logprob[..., cluster_prob_idx, None] + tail_logprob
|
| 158 |
+
out.append(logprob_i)
|
| 159 |
+
if target is not None:
|
| 160 |
+
cur_head_logprob = tf.boolean_mask(head_logprob, mask)
|
| 161 |
+
cur_tail_logprob = tf.boolean_mask(tail_logprob, mask)
|
| 162 |
+
cur_logprob = self._gather_logprob(cur_tail_logprob, cur_target)
|
| 163 |
+
cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
|
| 164 |
+
if target is not None:
|
| 165 |
+
loss += tf.scatter_nd(mask_idx, -cur_logprob, shape_list(loss))
|
| 166 |
+
out = tf.concat(out, axis=-1)
|
| 167 |
+
|
| 168 |
+
if target is not None:
|
| 169 |
+
if return_mean:
|
| 170 |
+
loss = tf.reduce_mean(loss)
|
| 171 |
+
# Add the training-time loss value to the layer using `self.add_loss()`.
|
| 172 |
+
self.add_loss(loss)
|
| 173 |
+
|
| 174 |
+
# Log the loss as a metric (we could log arbitrary metrics,
|
| 175 |
+
# including different metrics for training and inference.
|
| 176 |
+
self.add_metric(loss, name=self.name, aggregation="mean" if return_mean else "")
|
| 177 |
+
|
| 178 |
+
return out
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py
ADDED
|
@@ -0,0 +1,1303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University 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 |
+
"""
|
| 17 |
+
PyTorch Transformer XL model. Adapted from https://github.com/kimiyoung/transformer-xl. In particular
|
| 18 |
+
https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/mem_transformer.py
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import warnings
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Optional, Union
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
from torch import nn
|
| 27 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 28 |
+
|
| 29 |
+
from ....modeling_utils import PreTrainedModel
|
| 30 |
+
from ....utils import (
|
| 31 |
+
ModelOutput,
|
| 32 |
+
add_code_sample_docstrings,
|
| 33 |
+
add_start_docstrings,
|
| 34 |
+
add_start_docstrings_to_model_forward,
|
| 35 |
+
logging,
|
| 36 |
+
)
|
| 37 |
+
from .configuration_transfo_xl import TransfoXLConfig
|
| 38 |
+
from .modeling_transfo_xl_utilities import ProjectedAdaptiveLogSoftmax
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
_CHECKPOINT_FOR_DOC = "transfo-xl/transfo-xl-wt103"
|
| 44 |
+
_CONFIG_FOR_DOC = "TransfoXLConfig"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def build_tf_to_pytorch_map(model, config):
|
| 48 |
+
"""
|
| 49 |
+
A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original
|
| 50 |
+
PyTorch model as possible.
|
| 51 |
+
"""
|
| 52 |
+
tf_to_pt_map = {}
|
| 53 |
+
|
| 54 |
+
if hasattr(model, "transformer"):
|
| 55 |
+
# We are loading in a TransfoXLLMHeadModel => we will load also the Adaptive Softmax
|
| 56 |
+
tf_to_pt_map.update(
|
| 57 |
+
{
|
| 58 |
+
"transformer/adaptive_softmax/cutoff_0/cluster_W": model.crit.cluster_weight,
|
| 59 |
+
"transformer/adaptive_softmax/cutoff_0/cluster_b": model.crit.cluster_bias,
|
| 60 |
+
}
|
| 61 |
+
)
|
| 62 |
+
for i, (out_l, proj_l, tie_proj) in enumerate(
|
| 63 |
+
zip(model.crit.out_layers, model.crit.out_projs, config.tie_projs)
|
| 64 |
+
):
|
| 65 |
+
layer_str = f"transformer/adaptive_softmax/cutoff_{i}/"
|
| 66 |
+
if config.tie_word_embeddings:
|
| 67 |
+
tf_to_pt_map.update({layer_str + "b": out_l.bias})
|
| 68 |
+
else:
|
| 69 |
+
raise NotImplementedError
|
| 70 |
+
# I don't think this is implemented in the TF code
|
| 71 |
+
tf_to_pt_map.update({layer_str + "lookup_table": out_l.weight, layer_str + "b": out_l.bias})
|
| 72 |
+
if not tie_proj:
|
| 73 |
+
tf_to_pt_map.update({layer_str + "proj": proj_l})
|
| 74 |
+
# Now load the rest of the transformer
|
| 75 |
+
model = model.transformer
|
| 76 |
+
|
| 77 |
+
# Embeddings
|
| 78 |
+
for i, (embed_l, proj_l) in enumerate(zip(model.word_emb.emb_layers, model.word_emb.emb_projs)):
|
| 79 |
+
layer_str = f"transformer/adaptive_embed/cutoff_{i}/"
|
| 80 |
+
tf_to_pt_map.update({layer_str + "lookup_table": embed_l.weight, layer_str + "proj_W": proj_l})
|
| 81 |
+
|
| 82 |
+
# Transformer blocks
|
| 83 |
+
for i, b in enumerate(model.layers):
|
| 84 |
+
layer_str = f"transformer/layer_{i}/"
|
| 85 |
+
tf_to_pt_map.update(
|
| 86 |
+
{
|
| 87 |
+
layer_str + "rel_attn/LayerNorm/gamma": b.dec_attn.layer_norm.weight,
|
| 88 |
+
layer_str + "rel_attn/LayerNorm/beta": b.dec_attn.layer_norm.bias,
|
| 89 |
+
layer_str + "rel_attn/o/kernel": b.dec_attn.o_net.weight,
|
| 90 |
+
layer_str + "rel_attn/qkv/kernel": b.dec_attn.qkv_net.weight,
|
| 91 |
+
layer_str + "rel_attn/r/kernel": b.dec_attn.r_net.weight,
|
| 92 |
+
layer_str + "ff/LayerNorm/gamma": b.pos_ff.layer_norm.weight,
|
| 93 |
+
layer_str + "ff/LayerNorm/beta": b.pos_ff.layer_norm.bias,
|
| 94 |
+
layer_str + "ff/layer_1/kernel": b.pos_ff.CoreNet[0].weight,
|
| 95 |
+
layer_str + "ff/layer_1/bias": b.pos_ff.CoreNet[0].bias,
|
| 96 |
+
layer_str + "ff/layer_2/kernel": b.pos_ff.CoreNet[3].weight,
|
| 97 |
+
layer_str + "ff/layer_2/bias": b.pos_ff.CoreNet[3].bias,
|
| 98 |
+
}
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
# Relative positioning biases
|
| 102 |
+
if config.untie_r:
|
| 103 |
+
r_r_list = []
|
| 104 |
+
r_w_list = []
|
| 105 |
+
for b in model.layers:
|
| 106 |
+
r_r_list.append(b.dec_attn.r_r_bias)
|
| 107 |
+
r_w_list.append(b.dec_attn.r_w_bias)
|
| 108 |
+
else:
|
| 109 |
+
r_r_list = [model.r_r_bias]
|
| 110 |
+
r_w_list = [model.r_w_bias]
|
| 111 |
+
tf_to_pt_map.update({"transformer/r_r_bias": r_r_list, "transformer/r_w_bias": r_w_list})
|
| 112 |
+
return tf_to_pt_map
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def load_tf_weights_in_transfo_xl(model, config, tf_path):
|
| 116 |
+
"""Load tf checkpoints in a pytorch model"""
|
| 117 |
+
try:
|
| 118 |
+
import numpy as np
|
| 119 |
+
import tensorflow as tf
|
| 120 |
+
except ImportError:
|
| 121 |
+
logger.error(
|
| 122 |
+
"Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "
|
| 123 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
| 124 |
+
)
|
| 125 |
+
raise
|
| 126 |
+
# Build TF to PyTorch weights loading map
|
| 127 |
+
tf_to_pt_map = build_tf_to_pytorch_map(model, config)
|
| 128 |
+
|
| 129 |
+
# Load weights from TF model
|
| 130 |
+
init_vars = tf.train.list_variables(tf_path)
|
| 131 |
+
tf_weights = {}
|
| 132 |
+
for name, shape in init_vars:
|
| 133 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
| 134 |
+
array = tf.train.load_variable(tf_path, name)
|
| 135 |
+
tf_weights[name] = array
|
| 136 |
+
|
| 137 |
+
for name, pointer in tf_to_pt_map.items():
|
| 138 |
+
assert name in tf_weights
|
| 139 |
+
array = tf_weights[name]
|
| 140 |
+
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
|
| 141 |
+
# which are not required for using pretrained model
|
| 142 |
+
if "kernel" in name or "proj" in name:
|
| 143 |
+
array = np.transpose(array)
|
| 144 |
+
if ("r_r_bias" in name or "r_w_bias" in name) and len(pointer) > 1:
|
| 145 |
+
# Here we will split the TF weights
|
| 146 |
+
assert len(pointer) == array.shape[0]
|
| 147 |
+
for i, p_i in enumerate(pointer):
|
| 148 |
+
arr_i = array[i, ...]
|
| 149 |
+
try:
|
| 150 |
+
assert p_i.shape == arr_i.shape
|
| 151 |
+
except AssertionError as e:
|
| 152 |
+
e.args += (p_i.shape, arr_i.shape)
|
| 153 |
+
raise
|
| 154 |
+
logger.info(f"Initialize PyTorch weight {name} for layer {i}")
|
| 155 |
+
p_i.data = torch.from_numpy(arr_i)
|
| 156 |
+
else:
|
| 157 |
+
try:
|
| 158 |
+
assert pointer.shape == array.shape, (
|
| 159 |
+
f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
|
| 160 |
+
)
|
| 161 |
+
except AssertionError as e:
|
| 162 |
+
e.args += (pointer.shape, array.shape)
|
| 163 |
+
raise
|
| 164 |
+
logger.info(f"Initialize PyTorch weight {name}")
|
| 165 |
+
pointer.data = torch.from_numpy(array)
|
| 166 |
+
tf_weights.pop(name, None)
|
| 167 |
+
tf_weights.pop(name + "/Adam", None)
|
| 168 |
+
tf_weights.pop(name + "/Adam_1", None)
|
| 169 |
+
|
| 170 |
+
logger.info(f"Weights not copied to PyTorch model: {', '.join(tf_weights.keys())}")
|
| 171 |
+
return model
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class PositionalEmbedding(nn.Module):
|
| 175 |
+
def __init__(self, demb):
|
| 176 |
+
super().__init__()
|
| 177 |
+
|
| 178 |
+
self.demb = demb
|
| 179 |
+
|
| 180 |
+
inv_freq = 1 / (10000 ** (torch.arange(0.0, demb, 2.0) / demb))
|
| 181 |
+
self.register_buffer("inv_freq", inv_freq)
|
| 182 |
+
|
| 183 |
+
def forward(self, pos_seq, bsz=None):
|
| 184 |
+
sinusoid_inp = torch.outer(pos_seq, self.inv_freq)
|
| 185 |
+
pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1)
|
| 186 |
+
|
| 187 |
+
if bsz is not None:
|
| 188 |
+
return pos_emb[:, None, :].expand(-1, bsz, -1)
|
| 189 |
+
else:
|
| 190 |
+
return pos_emb[:, None, :]
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class PositionwiseFF(nn.Module):
|
| 194 |
+
def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5):
|
| 195 |
+
super().__init__()
|
| 196 |
+
|
| 197 |
+
self.d_model = d_model
|
| 198 |
+
self.d_inner = d_inner
|
| 199 |
+
self.dropout = dropout
|
| 200 |
+
|
| 201 |
+
self.CoreNet = nn.Sequential(
|
| 202 |
+
nn.Linear(d_model, d_inner),
|
| 203 |
+
nn.ReLU(inplace=True),
|
| 204 |
+
nn.Dropout(dropout),
|
| 205 |
+
nn.Linear(d_inner, d_model),
|
| 206 |
+
nn.Dropout(dropout),
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon)
|
| 210 |
+
|
| 211 |
+
self.pre_lnorm = pre_lnorm
|
| 212 |
+
|
| 213 |
+
def forward(self, inp):
|
| 214 |
+
if self.pre_lnorm:
|
| 215 |
+
# layer normalization + positionwise feed-forward
|
| 216 |
+
core_out = self.CoreNet(self.layer_norm(inp))
|
| 217 |
+
|
| 218 |
+
# residual connection
|
| 219 |
+
output = core_out + inp
|
| 220 |
+
else:
|
| 221 |
+
# positionwise feed-forward
|
| 222 |
+
core_out = self.CoreNet(inp)
|
| 223 |
+
|
| 224 |
+
# residual connection + layer normalization
|
| 225 |
+
output = self.layer_norm(inp + core_out)
|
| 226 |
+
|
| 227 |
+
return output
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class RelPartialLearnableMultiHeadAttn(nn.Module):
|
| 231 |
+
def __init__(
|
| 232 |
+
self,
|
| 233 |
+
n_head,
|
| 234 |
+
d_model,
|
| 235 |
+
d_head,
|
| 236 |
+
dropout,
|
| 237 |
+
dropatt=0,
|
| 238 |
+
pre_lnorm=False,
|
| 239 |
+
r_r_bias=None,
|
| 240 |
+
r_w_bias=None,
|
| 241 |
+
layer_norm_epsilon=1e-5,
|
| 242 |
+
):
|
| 243 |
+
super().__init__()
|
| 244 |
+
|
| 245 |
+
self.n_head = n_head
|
| 246 |
+
self.d_model = d_model
|
| 247 |
+
self.d_head = d_head
|
| 248 |
+
self.dropout = dropout
|
| 249 |
+
|
| 250 |
+
self.qkv_net = nn.Linear(d_model, 3 * n_head * d_head, bias=False)
|
| 251 |
+
|
| 252 |
+
self.drop = nn.Dropout(dropout)
|
| 253 |
+
self.dropatt = nn.Dropout(dropatt)
|
| 254 |
+
self.o_net = nn.Linear(n_head * d_head, d_model, bias=False)
|
| 255 |
+
|
| 256 |
+
self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon)
|
| 257 |
+
|
| 258 |
+
self.scale = 1 / (d_head**0.5)
|
| 259 |
+
|
| 260 |
+
self.pre_lnorm = pre_lnorm
|
| 261 |
+
|
| 262 |
+
if r_r_bias is None or r_w_bias is None: # Biases are not shared
|
| 263 |
+
self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
|
| 264 |
+
self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
|
| 265 |
+
else:
|
| 266 |
+
self.r_r_bias = r_r_bias
|
| 267 |
+
self.r_w_bias = r_w_bias
|
| 268 |
+
|
| 269 |
+
self.r_net = nn.Linear(self.d_model, self.n_head * self.d_head, bias=False)
|
| 270 |
+
|
| 271 |
+
def _rel_shift(self, x):
|
| 272 |
+
zero_pad_shape = (x.size(0), 1) + x.size()[2:]
|
| 273 |
+
zero_pad = torch.zeros(zero_pad_shape, device=x.device, dtype=x.dtype)
|
| 274 |
+
x_padded = torch.cat([zero_pad, x], dim=1)
|
| 275 |
+
|
| 276 |
+
x_padded_shape = (x.size(1) + 1, x.size(0)) + x.size()[2:]
|
| 277 |
+
x_padded = x_padded.view(*x_padded_shape)
|
| 278 |
+
|
| 279 |
+
x = x_padded[1:].view_as(x)
|
| 280 |
+
|
| 281 |
+
return x
|
| 282 |
+
|
| 283 |
+
def forward(self, w, r, attn_mask=None, mems=None, head_mask=None, output_attentions=False):
|
| 284 |
+
qlen, rlen, bsz = w.size(0), r.size(0), w.size(1)
|
| 285 |
+
|
| 286 |
+
if mems is not None:
|
| 287 |
+
cat = torch.cat([mems, w], 0)
|
| 288 |
+
if self.pre_lnorm:
|
| 289 |
+
w_heads = self.qkv_net(self.layer_norm(cat))
|
| 290 |
+
else:
|
| 291 |
+
w_heads = self.qkv_net(cat)
|
| 292 |
+
r_head_k = self.r_net(r)
|
| 293 |
+
|
| 294 |
+
w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)
|
| 295 |
+
w_head_q = w_head_q[-qlen:]
|
| 296 |
+
else:
|
| 297 |
+
if self.pre_lnorm:
|
| 298 |
+
w_heads = self.qkv_net(self.layer_norm(w))
|
| 299 |
+
else:
|
| 300 |
+
w_heads = self.qkv_net(w)
|
| 301 |
+
r_head_k = self.r_net(r)
|
| 302 |
+
|
| 303 |
+
w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)
|
| 304 |
+
|
| 305 |
+
klen = w_head_k.size(0)
|
| 306 |
+
|
| 307 |
+
w_head_q = w_head_q.view(qlen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
|
| 308 |
+
w_head_k = w_head_k.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
|
| 309 |
+
w_head_v = w_head_v.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
|
| 310 |
+
|
| 311 |
+
r_head_k = r_head_k.view(rlen, self.n_head, self.d_head) # qlen x n_head x d_head
|
| 312 |
+
|
| 313 |
+
# compute attention score
|
| 314 |
+
rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head
|
| 315 |
+
AC = torch.einsum("ibnd,jbnd->ijbn", (rw_head_q, w_head_k)) # qlen x klen x bsz x n_head
|
| 316 |
+
|
| 317 |
+
rr_head_q = w_head_q + self.r_r_bias
|
| 318 |
+
BD = torch.einsum("ibnd,jnd->ijbn", (rr_head_q, r_head_k)) # qlen x klen x bsz x n_head
|
| 319 |
+
BD = self._rel_shift(BD)
|
| 320 |
+
|
| 321 |
+
# [qlen x klen x bsz x n_head]
|
| 322 |
+
attn_score = AC + BD
|
| 323 |
+
attn_score.mul_(self.scale)
|
| 324 |
+
|
| 325 |
+
mask_value = torch.finfo(attn_score.dtype).min
|
| 326 |
+
|
| 327 |
+
# compute attention probability
|
| 328 |
+
if attn_mask is not None and torch.sum(attn_mask).item():
|
| 329 |
+
attn_mask = attn_mask == 1 # Switch to bool
|
| 330 |
+
if attn_mask.dim() == 2:
|
| 331 |
+
attn_score = (
|
| 332 |
+
attn_score.float().masked_fill(attn_mask[None, :, :, None], mask_value).type_as(attn_score)
|
| 333 |
+
)
|
| 334 |
+
elif attn_mask.dim() == 3:
|
| 335 |
+
attn_score = attn_score.float().masked_fill(attn_mask[:, :, :, None], mask_value).type_as(attn_score)
|
| 336 |
+
|
| 337 |
+
# [qlen x klen x bsz x n_head]
|
| 338 |
+
attn_prob = nn.functional.softmax(attn_score, dim=1)
|
| 339 |
+
attn_prob = self.dropatt(attn_prob)
|
| 340 |
+
|
| 341 |
+
# Mask heads if we want to
|
| 342 |
+
if head_mask is not None:
|
| 343 |
+
attn_prob = attn_prob * head_mask
|
| 344 |
+
|
| 345 |
+
# compute attention vector
|
| 346 |
+
attn_vec = torch.einsum("ijbn,jbnd->ibnd", (attn_prob, w_head_v))
|
| 347 |
+
|
| 348 |
+
# [qlen x bsz x n_head x d_head]
|
| 349 |
+
attn_vec = attn_vec.contiguous().view(attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head)
|
| 350 |
+
|
| 351 |
+
# linear projection
|
| 352 |
+
attn_out = self.o_net(attn_vec)
|
| 353 |
+
attn_out = self.drop(attn_out)
|
| 354 |
+
|
| 355 |
+
if self.pre_lnorm:
|
| 356 |
+
# residual connection
|
| 357 |
+
outputs = [w + attn_out]
|
| 358 |
+
else:
|
| 359 |
+
# residual connection + layer normalization
|
| 360 |
+
outputs = [self.layer_norm(w + attn_out)]
|
| 361 |
+
|
| 362 |
+
if output_attentions:
|
| 363 |
+
outputs.append(attn_prob)
|
| 364 |
+
|
| 365 |
+
return outputs
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
class RelPartialLearnableDecoderLayer(nn.Module):
|
| 369 |
+
def __init__(self, n_head, d_model, d_head, d_inner, dropout, layer_norm_epsilon=1e-5, **kwargs):
|
| 370 |
+
super().__init__()
|
| 371 |
+
|
| 372 |
+
self.dec_attn = RelPartialLearnableMultiHeadAttn(
|
| 373 |
+
n_head, d_model, d_head, dropout, layer_norm_epsilon=layer_norm_epsilon, **kwargs
|
| 374 |
+
)
|
| 375 |
+
self.pos_ff = PositionwiseFF(
|
| 376 |
+
d_model, d_inner, dropout, pre_lnorm=kwargs.get("pre_lnorm"), layer_norm_epsilon=layer_norm_epsilon
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
def forward(self, dec_inp, r, dec_attn_mask=None, mems=None, head_mask=None, output_attentions=False):
|
| 380 |
+
attn_outputs = self.dec_attn(
|
| 381 |
+
dec_inp,
|
| 382 |
+
r,
|
| 383 |
+
attn_mask=dec_attn_mask,
|
| 384 |
+
mems=mems,
|
| 385 |
+
head_mask=head_mask,
|
| 386 |
+
output_attentions=output_attentions,
|
| 387 |
+
)
|
| 388 |
+
ff_output = self.pos_ff(attn_outputs[0])
|
| 389 |
+
|
| 390 |
+
outputs = [ff_output] + attn_outputs[1:]
|
| 391 |
+
|
| 392 |
+
return outputs
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
class AdaptiveEmbedding(nn.Module):
|
| 396 |
+
def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, sample_softmax=False):
|
| 397 |
+
super().__init__()
|
| 398 |
+
|
| 399 |
+
self.n_token = n_token
|
| 400 |
+
self.d_embed = d_embed
|
| 401 |
+
|
| 402 |
+
self.cutoffs = cutoffs + [n_token]
|
| 403 |
+
self.div_val = div_val
|
| 404 |
+
self.d_proj = d_proj
|
| 405 |
+
|
| 406 |
+
self.emb_scale = d_proj**0.5
|
| 407 |
+
|
| 408 |
+
self.cutoff_ends = [0] + self.cutoffs
|
| 409 |
+
|
| 410 |
+
self.emb_layers = nn.ModuleList()
|
| 411 |
+
self.emb_projs = nn.ParameterList()
|
| 412 |
+
if div_val == 1:
|
| 413 |
+
self.emb_layers.append(nn.Embedding(n_token, d_embed, sparse=sample_softmax > 0))
|
| 414 |
+
if d_proj != d_embed:
|
| 415 |
+
self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed)))
|
| 416 |
+
else:
|
| 417 |
+
for i in range(len(self.cutoffs)):
|
| 418 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 419 |
+
d_emb_i = d_embed // (div_val**i)
|
| 420 |
+
self.emb_layers.append(nn.Embedding(r_idx - l_idx, d_emb_i))
|
| 421 |
+
self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i)))
|
| 422 |
+
|
| 423 |
+
def forward(self, inp):
|
| 424 |
+
if self.div_val == 1:
|
| 425 |
+
embed = self.emb_layers[0](inp)
|
| 426 |
+
if self.d_proj != self.d_embed:
|
| 427 |
+
embed = nn.functional.linear(embed, self.emb_projs[0])
|
| 428 |
+
else:
|
| 429 |
+
param = next(self.parameters())
|
| 430 |
+
inp_flat = inp.view(-1)
|
| 431 |
+
emb_flat = torch.zeros([inp_flat.size(0), self.d_proj], dtype=param.dtype, device=param.device)
|
| 432 |
+
for i in range(len(self.cutoffs)):
|
| 433 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 434 |
+
|
| 435 |
+
mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx)
|
| 436 |
+
indices_i = mask_i.nonzero().squeeze()
|
| 437 |
+
|
| 438 |
+
if indices_i.numel() == 0:
|
| 439 |
+
continue
|
| 440 |
+
|
| 441 |
+
inp_i = inp_flat.index_select(0, indices_i) - l_idx
|
| 442 |
+
emb_i = self.emb_layers[i](inp_i)
|
| 443 |
+
emb_i = nn.functional.linear(emb_i, self.emb_projs[i])
|
| 444 |
+
|
| 445 |
+
emb_flat.index_copy_(0, indices_i, emb_i)
|
| 446 |
+
|
| 447 |
+
embed_shape = inp.size() + (self.d_proj,)
|
| 448 |
+
embed = emb_flat.view(embed_shape)
|
| 449 |
+
|
| 450 |
+
embed.mul_(self.emb_scale)
|
| 451 |
+
|
| 452 |
+
return embed
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
class TransfoXLPreTrainedModel(PreTrainedModel):
|
| 456 |
+
"""
|
| 457 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 458 |
+
models.
|
| 459 |
+
"""
|
| 460 |
+
|
| 461 |
+
config: TransfoXLConfig
|
| 462 |
+
load_tf_weights = load_tf_weights_in_transfo_xl
|
| 463 |
+
base_model_prefix = "transformer"
|
| 464 |
+
|
| 465 |
+
def _init_weight(self, weight):
|
| 466 |
+
if self.config.init == "uniform":
|
| 467 |
+
nn.init.uniform_(weight, -self.config.init_range, self.config.init_range)
|
| 468 |
+
elif self.config.init == "normal":
|
| 469 |
+
nn.init.normal_(weight, 0.0, self.config.init_std)
|
| 470 |
+
|
| 471 |
+
def _init_bias(self, bias):
|
| 472 |
+
nn.init.constant_(bias, 0.0)
|
| 473 |
+
|
| 474 |
+
def _init_weights(self, m):
|
| 475 |
+
"""Initialize the weights."""
|
| 476 |
+
classname = m.__class__.__name__
|
| 477 |
+
if classname.find("Linear") != -1:
|
| 478 |
+
if hasattr(m, "weight") and m.weight is not None:
|
| 479 |
+
self._init_weight(m.weight)
|
| 480 |
+
if hasattr(m, "bias") and m.bias is not None:
|
| 481 |
+
self._init_bias(m.bias)
|
| 482 |
+
elif classname.find("AdaptiveEmbedding") != -1:
|
| 483 |
+
if hasattr(m, "emb_projs"):
|
| 484 |
+
for i in range(len(m.emb_projs)):
|
| 485 |
+
if m.emb_projs[i] is not None:
|
| 486 |
+
nn.init.normal_(m.emb_projs[i], 0.0, self.config.proj_init_std)
|
| 487 |
+
elif classname.find("Embedding") != -1:
|
| 488 |
+
if hasattr(m, "weight"):
|
| 489 |
+
self._init_weight(m.weight)
|
| 490 |
+
elif classname.find("ProjectedAdaptiveLogSoftmax") != -1:
|
| 491 |
+
if hasattr(m, "cluster_weight") and m.cluster_weight is not None:
|
| 492 |
+
self._init_weight(m.cluster_weight)
|
| 493 |
+
if hasattr(m, "cluster_bias") and m.cluster_bias is not None:
|
| 494 |
+
self._init_bias(m.cluster_bias)
|
| 495 |
+
if hasattr(m, "out_projs"):
|
| 496 |
+
for i in range(len(m.out_projs)):
|
| 497 |
+
if m.out_projs[i] is not None:
|
| 498 |
+
nn.init.normal_(m.out_projs[i], 0.0, self.config.proj_init_std)
|
| 499 |
+
elif classname.find("LayerNorm") != -1:
|
| 500 |
+
if hasattr(m, "weight"):
|
| 501 |
+
nn.init.normal_(m.weight, 1.0, self.config.init_std)
|
| 502 |
+
if hasattr(m, "bias") and m.bias is not None:
|
| 503 |
+
self._init_bias(m.bias)
|
| 504 |
+
else:
|
| 505 |
+
if hasattr(m, "r_emb"):
|
| 506 |
+
self._init_weight(m.r_emb)
|
| 507 |
+
if hasattr(m, "r_w_bias"):
|
| 508 |
+
self._init_weight(m.r_w_bias)
|
| 509 |
+
if hasattr(m, "r_r_bias"):
|
| 510 |
+
self._init_weight(m.r_r_bias)
|
| 511 |
+
if hasattr(m, "r_bias"):
|
| 512 |
+
self._init_bias(m.r_bias)
|
| 513 |
+
|
| 514 |
+
def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, layer: Optional[int] = -1):
|
| 515 |
+
"""
|
| 516 |
+
Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. Take care of tying
|
| 517 |
+
weights embeddings afterwards if the model class has a *tie_weights()* method.
|
| 518 |
+
|
| 519 |
+
Arguments:
|
| 520 |
+
new_num_tokens: (*optional*) int:
|
| 521 |
+
New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at
|
| 522 |
+
the end. Reducing the size will remove vectors from the end. If not provided or None: does nothing and
|
| 523 |
+
just returns a pointer to the input tokens `torch.nn.Embeddings` Module of the model.
|
| 524 |
+
layer: (*optional*) int:
|
| 525 |
+
Layer of the *AdaptiveEmbedding* where the resizing should be done. Per default the last layer will be
|
| 526 |
+
resized. Be aware that when resizing other than the last layer, you have to ensure that the new
|
| 527 |
+
token(s) in the tokenizer are at the corresponding position.
|
| 528 |
+
|
| 529 |
+
Return: `torch.nn.Embeddings` Pointer to the input tokens Embeddings Module of the model
|
| 530 |
+
"""
|
| 531 |
+
base_model = getattr(self, self.base_model_prefix, self) # get the base model if needed
|
| 532 |
+
|
| 533 |
+
if new_num_tokens is None:
|
| 534 |
+
return self.get_input_embeddings()
|
| 535 |
+
|
| 536 |
+
new_num_tokens_layer, layer = self._get_new_num_tokens_layer(new_num_tokens, layer)
|
| 537 |
+
assert new_num_tokens_layer > 0, "The size of the new embedding layer cannot be 0 or less"
|
| 538 |
+
model_embeds = base_model._resize_token_embeddings(new_num_tokens_layer, layer)
|
| 539 |
+
|
| 540 |
+
# Update base model and current model config
|
| 541 |
+
self.config.vocab_size = new_num_tokens
|
| 542 |
+
base_model.vocab_size = new_num_tokens
|
| 543 |
+
base_model.n_token = new_num_tokens
|
| 544 |
+
|
| 545 |
+
new_embedding_shapes = self._get_embedding_shapes()
|
| 546 |
+
self._resize_cutoffs(new_num_tokens, new_num_tokens_layer, new_embedding_shapes, layer)
|
| 547 |
+
|
| 548 |
+
# Tie weights again if needed
|
| 549 |
+
self.tie_weights()
|
| 550 |
+
|
| 551 |
+
return model_embeds
|
| 552 |
+
|
| 553 |
+
def _get_new_num_tokens_layer(self, new_num_tokens, layer):
|
| 554 |
+
embeddings = self.get_input_embeddings()
|
| 555 |
+
if layer == -1:
|
| 556 |
+
layer = len(embeddings.emb_layers) - 1
|
| 557 |
+
assert 0 <= layer <= len(embeddings.emb_layers) - 1
|
| 558 |
+
|
| 559 |
+
new_num_tokens_layer = (
|
| 560 |
+
new_num_tokens
|
| 561 |
+
- sum(emb.weight.shape[0] for emb in embeddings.emb_layers[:layer])
|
| 562 |
+
- sum(emb.weight.shape[0] for emb in embeddings.emb_layers[layer + 1 :])
|
| 563 |
+
)
|
| 564 |
+
return new_num_tokens_layer, layer
|
| 565 |
+
|
| 566 |
+
def _get_embedding_shapes(self):
|
| 567 |
+
embeddings = self.get_input_embeddings()
|
| 568 |
+
return [emb.weight.shape[0] for emb in embeddings.emb_layers]
|
| 569 |
+
|
| 570 |
+
def _resize_token_embeddings(self, new_num_tokens, layer=-1):
|
| 571 |
+
embeddings = self.get_input_embeddings()
|
| 572 |
+
if new_num_tokens is None:
|
| 573 |
+
return embeddings
|
| 574 |
+
new_embeddings_layer = self._get_resized_embeddings(embeddings.emb_layers[layer], new_num_tokens)
|
| 575 |
+
embeddings.emb_layers[layer] = new_embeddings_layer
|
| 576 |
+
|
| 577 |
+
self.set_input_embeddings(embeddings)
|
| 578 |
+
|
| 579 |
+
return self.get_input_embeddings()
|
| 580 |
+
|
| 581 |
+
def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer):
|
| 582 |
+
embeddings = self.get_input_embeddings()
|
| 583 |
+
|
| 584 |
+
for i in range(layer, len(embeddings.cutoffs)):
|
| 585 |
+
embeddings.cutoffs[i] = sum(new_embedding_shapes[: i + 1])
|
| 586 |
+
|
| 587 |
+
embeddings.cutoff_ends = [0] + embeddings.cutoffs
|
| 588 |
+
embeddings.n_token = new_num_tokens
|
| 589 |
+
|
| 590 |
+
self.config.cutoffs = embeddings.cutoffs[:-1]
|
| 591 |
+
|
| 592 |
+
return embeddings.cutoffs
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
@dataclass
|
| 596 |
+
class TransfoXLModelOutput(ModelOutput):
|
| 597 |
+
"""
|
| 598 |
+
Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
|
| 599 |
+
|
| 600 |
+
Args:
|
| 601 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 602 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 603 |
+
mems (`list[torch.FloatTensor]` of length `config.n_layers`):
|
| 604 |
+
Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
|
| 605 |
+
input) to speed up sequential decoding. The token ids which have their past given to this model should not
|
| 606 |
+
be passed as input ids as they have already been computed.
|
| 607 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 608 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 609 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
| 610 |
+
|
| 611 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 612 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 613 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 614 |
+
sequence_length)`.
|
| 615 |
+
|
| 616 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 617 |
+
heads.
|
| 618 |
+
"""
|
| 619 |
+
|
| 620 |
+
last_hidden_state: torch.FloatTensor
|
| 621 |
+
mems: Optional[list[torch.FloatTensor]] = None
|
| 622 |
+
hidden_states: Optional[tuple[torch.FloatTensor]] = None
|
| 623 |
+
attentions: Optional[tuple[torch.FloatTensor]] = None
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
@dataclass
|
| 627 |
+
class TransfoXLSequenceClassifierOutputWithPast(ModelOutput):
|
| 628 |
+
"""
|
| 629 |
+
Base class for outputs of sentence classification models.
|
| 630 |
+
|
| 631 |
+
Args:
|
| 632 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 633 |
+
Classification (or regression if config.num_labels==1) loss.
|
| 634 |
+
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
|
| 635 |
+
Classification (or regression if config.num_labels==1) scores (before SoftMax).
|
| 636 |
+
mems (`list[torch.FloatTensor]` of length `config.n_layers`):
|
| 637 |
+
Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
|
| 638 |
+
input) to speed up sequential decoding. The token ids which have their past given to this model should not
|
| 639 |
+
be passed as input ids as they have already been computed.
|
| 640 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 641 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 642 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
| 643 |
+
|
| 644 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 645 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 646 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 647 |
+
sequence_length)`.
|
| 648 |
+
|
| 649 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 650 |
+
heads.
|
| 651 |
+
"""
|
| 652 |
+
|
| 653 |
+
loss: Optional[torch.FloatTensor] = None
|
| 654 |
+
logits: Optional[torch.FloatTensor] = None
|
| 655 |
+
mems: Optional[list[torch.FloatTensor]] = None
|
| 656 |
+
hidden_states: Optional[tuple[torch.FloatTensor]] = None
|
| 657 |
+
attentions: Optional[tuple[torch.FloatTensor]] = None
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
@dataclass
|
| 661 |
+
class TransfoXLLMHeadModelOutput(ModelOutput):
|
| 662 |
+
"""
|
| 663 |
+
Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
|
| 664 |
+
|
| 665 |
+
Args:
|
| 666 |
+
losses (`torch.FloatTensor` of shape *(batch_size, sequence_length-1)*, *optional*, returned when `labels` is provided):
|
| 667 |
+
Language modeling losses (not reduced).
|
| 668 |
+
prediction_scores (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 669 |
+
Prediction scores of the language modeling head (scores for each vocabulary token after SoftMax).
|
| 670 |
+
mems (`list[torch.FloatTensor]` of length `config.n_layers`):
|
| 671 |
+
Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
|
| 672 |
+
input) to speed up sequential decoding. The token ids which have their past given to this model should not
|
| 673 |
+
be passed as input ids as they have already been computed.
|
| 674 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 675 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 676 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
| 677 |
+
|
| 678 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 679 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 680 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 681 |
+
sequence_length)`.
|
| 682 |
+
|
| 683 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 684 |
+
heads.
|
| 685 |
+
loss (`torch.FloatTensor` of shape `()`, *optional*, returned when `labels` is provided)
|
| 686 |
+
Reduced language modeling loss.
|
| 687 |
+
"""
|
| 688 |
+
|
| 689 |
+
losses: Optional[torch.FloatTensor] = None
|
| 690 |
+
prediction_scores: Optional[torch.FloatTensor] = None
|
| 691 |
+
mems: Optional[list[torch.FloatTensor]] = None
|
| 692 |
+
hidden_states: Optional[tuple[torch.FloatTensor]] = None
|
| 693 |
+
attentions: Optional[tuple[torch.FloatTensor]] = None
|
| 694 |
+
loss: Optional[torch.FloatTensor] = None
|
| 695 |
+
|
| 696 |
+
@property
|
| 697 |
+
def logits(self):
|
| 698 |
+
# prediction scores are the output of the adaptive softmax, see
|
| 699 |
+
# the file `modeling_transfo_xl_utilities`. Since the adaptive
|
| 700 |
+
# softmax returns the log softmax value, `self.prediction_scores`
|
| 701 |
+
# are strictly speaking not exactly `logits`, but behave the same
|
| 702 |
+
# way logits do.
|
| 703 |
+
return self.prediction_scores
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
TRANSFO_XL_START_DOCSTRING = r"""
|
| 707 |
+
|
| 708 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 709 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 710 |
+
etc.)
|
| 711 |
+
|
| 712 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 713 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 714 |
+
and behavior.
|
| 715 |
+
|
| 716 |
+
Parameters:
|
| 717 |
+
config ([`TransfoXLConfig`]): Model configuration class with all the parameters of the model.
|
| 718 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 719 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 720 |
+
"""
|
| 721 |
+
|
| 722 |
+
TRANSFO_XL_INPUTS_DOCSTRING = r"""
|
| 723 |
+
Args:
|
| 724 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 725 |
+
Indices of input sequence tokens in the vocabulary.
|
| 726 |
+
|
| 727 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 728 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 729 |
+
|
| 730 |
+
[What are input IDs?](../glossary#input-ids)
|
| 731 |
+
mems (`list[torch.FloatTensor]` of length `config.n_layers`):
|
| 732 |
+
Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
|
| 733 |
+
`mems` output below). Can be used to speed up sequential decoding. The token ids which have their mems
|
| 734 |
+
given to this model should not be passed as `input_ids` as they have already been computed.
|
| 735 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 736 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 737 |
+
|
| 738 |
+
- 1 indicates the head is **not masked**,
|
| 739 |
+
- 0 indicates the head is **masked**.
|
| 740 |
+
|
| 741 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 742 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 743 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 744 |
+
model's internal embedding lookup matrix.
|
| 745 |
+
output_attentions (`bool`, *optional*):
|
| 746 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 747 |
+
tensors for more detail.
|
| 748 |
+
output_hidden_states (`bool`, *optional*):
|
| 749 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 750 |
+
more detail.
|
| 751 |
+
return_dict (`bool`, *optional*):
|
| 752 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 753 |
+
"""
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
@add_start_docstrings(
|
| 757 |
+
"The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
|
| 758 |
+
TRANSFO_XL_START_DOCSTRING,
|
| 759 |
+
)
|
| 760 |
+
class TransfoXLModel(TransfoXLPreTrainedModel):
|
| 761 |
+
def __init__(self, config):
|
| 762 |
+
super().__init__(config)
|
| 763 |
+
|
| 764 |
+
self.n_token = config.vocab_size
|
| 765 |
+
|
| 766 |
+
self.d_embed = config.d_embed
|
| 767 |
+
self.d_model = config.d_model
|
| 768 |
+
self.n_head = config.n_head
|
| 769 |
+
self.d_head = config.d_head
|
| 770 |
+
|
| 771 |
+
self.word_emb = AdaptiveEmbedding(
|
| 772 |
+
config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
self.drop = nn.Dropout(config.dropout)
|
| 776 |
+
|
| 777 |
+
self.n_layer = config.n_layer
|
| 778 |
+
self.mem_len = config.mem_len
|
| 779 |
+
self.attn_type = config.attn_type
|
| 780 |
+
|
| 781 |
+
if not config.untie_r:
|
| 782 |
+
self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
|
| 783 |
+
self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
|
| 784 |
+
|
| 785 |
+
self.layers = nn.ModuleList()
|
| 786 |
+
if config.attn_type == 0: # the default attention
|
| 787 |
+
for i in range(config.n_layer):
|
| 788 |
+
self.layers.append(
|
| 789 |
+
RelPartialLearnableDecoderLayer(
|
| 790 |
+
config.n_head,
|
| 791 |
+
config.d_model,
|
| 792 |
+
config.d_head,
|
| 793 |
+
config.d_inner,
|
| 794 |
+
config.dropout,
|
| 795 |
+
dropatt=config.dropatt,
|
| 796 |
+
pre_lnorm=config.pre_lnorm,
|
| 797 |
+
r_w_bias=None if config.untie_r else self.r_w_bias,
|
| 798 |
+
r_r_bias=None if config.untie_r else self.r_r_bias,
|
| 799 |
+
layer_norm_epsilon=config.layer_norm_epsilon,
|
| 800 |
+
)
|
| 801 |
+
)
|
| 802 |
+
else: # learnable embeddings and absolute embeddings are not used in our pretrained checkpoints
|
| 803 |
+
raise NotImplementedError # Removed them to avoid maintaining dead code
|
| 804 |
+
|
| 805 |
+
self.same_length = config.same_length
|
| 806 |
+
self.clamp_len = config.clamp_len
|
| 807 |
+
|
| 808 |
+
if self.attn_type == 0: # default attention
|
| 809 |
+
self.pos_emb = PositionalEmbedding(self.d_model)
|
| 810 |
+
else: # learnable embeddings and absolute embeddings
|
| 811 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 812 |
+
|
| 813 |
+
# Initialize weights and apply final processing
|
| 814 |
+
self.post_init()
|
| 815 |
+
|
| 816 |
+
def get_input_embeddings(self):
|
| 817 |
+
return self.word_emb
|
| 818 |
+
|
| 819 |
+
def set_input_embeddings(self, new_embeddings):
|
| 820 |
+
self.word_emb = new_embeddings
|
| 821 |
+
|
| 822 |
+
def backward_compatible(self):
|
| 823 |
+
self.sample_softmax = -1
|
| 824 |
+
|
| 825 |
+
def reset_memory_length(self, mem_len):
|
| 826 |
+
self.mem_len = mem_len
|
| 827 |
+
|
| 828 |
+
def _prune_heads(self, heads):
|
| 829 |
+
logger.info("Head pruning is not implemented for Transformer-XL model")
|
| 830 |
+
pass
|
| 831 |
+
|
| 832 |
+
def init_mems(self, bsz):
|
| 833 |
+
if self.mem_len > 0:
|
| 834 |
+
mems = []
|
| 835 |
+
param = next(self.parameters())
|
| 836 |
+
for i in range(self.n_layer):
|
| 837 |
+
empty = torch.zeros(self.mem_len, bsz, self.config.d_model, dtype=param.dtype, device=param.device)
|
| 838 |
+
mems.append(empty)
|
| 839 |
+
|
| 840 |
+
return mems
|
| 841 |
+
else:
|
| 842 |
+
return None
|
| 843 |
+
|
| 844 |
+
def _update_mems(self, hids, mems, mlen, qlen):
|
| 845 |
+
# does not deal with None
|
| 846 |
+
if mems is None:
|
| 847 |
+
return None
|
| 848 |
+
|
| 849 |
+
# mems is not None
|
| 850 |
+
assert len(hids) == len(mems), "len(hids) != len(mems)"
|
| 851 |
+
|
| 852 |
+
# There are `mlen + qlen` steps that can be cached into mems
|
| 853 |
+
with torch.no_grad():
|
| 854 |
+
new_mems = []
|
| 855 |
+
end_idx = mlen + max(0, qlen)
|
| 856 |
+
beg_idx = max(0, end_idx - self.mem_len)
|
| 857 |
+
for i in range(len(hids)):
|
| 858 |
+
cat = torch.cat([mems[i], hids[i]], dim=0)
|
| 859 |
+
new_mems.append(cat[beg_idx:end_idx].detach())
|
| 860 |
+
|
| 861 |
+
return new_mems
|
| 862 |
+
|
| 863 |
+
@add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
|
| 864 |
+
@add_code_sample_docstrings(
|
| 865 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 866 |
+
output_type=TransfoXLModelOutput,
|
| 867 |
+
config_class=_CONFIG_FOR_DOC,
|
| 868 |
+
)
|
| 869 |
+
def forward(
|
| 870 |
+
self,
|
| 871 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 872 |
+
mems: Optional[list[torch.FloatTensor]] = None,
|
| 873 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 874 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 875 |
+
output_attentions: Optional[bool] = None,
|
| 876 |
+
output_hidden_states: Optional[bool] = None,
|
| 877 |
+
return_dict: Optional[bool] = None,
|
| 878 |
+
) -> Union[tuple, TransfoXLModelOutput]:
|
| 879 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 880 |
+
output_hidden_states = (
|
| 881 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 882 |
+
)
|
| 883 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 884 |
+
|
| 885 |
+
# the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library
|
| 886 |
+
# so we transpose here from shape [bsz, len] to shape [len, bsz]
|
| 887 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 888 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 889 |
+
elif input_ids is not None:
|
| 890 |
+
input_ids = input_ids.transpose(0, 1).contiguous()
|
| 891 |
+
qlen, bsz = input_ids.size()
|
| 892 |
+
elif inputs_embeds is not None:
|
| 893 |
+
inputs_embeds = inputs_embeds.transpose(0, 1).contiguous()
|
| 894 |
+
qlen, bsz = inputs_embeds.shape[0], inputs_embeds.shape[1]
|
| 895 |
+
else:
|
| 896 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 897 |
+
|
| 898 |
+
if mems is None:
|
| 899 |
+
mems = self.init_mems(bsz)
|
| 900 |
+
|
| 901 |
+
# Prepare head mask if needed
|
| 902 |
+
# 1.0 in head_mask indicate we keep the head
|
| 903 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 904 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer)
|
| 905 |
+
# and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head]
|
| 906 |
+
if head_mask is not None:
|
| 907 |
+
if head_mask.dim() == 1:
|
| 908 |
+
head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(0).unsqueeze(0)
|
| 909 |
+
head_mask = head_mask.expand(self.n_layer, -1, -1, -1, -1)
|
| 910 |
+
elif head_mask.dim() == 2:
|
| 911 |
+
head_mask = head_mask.unsqueeze(1).unsqueeze(1).unsqueeze(1)
|
| 912 |
+
head_mask = head_mask.to(
|
| 913 |
+
dtype=next(self.parameters()).dtype
|
| 914 |
+
) # switch to float if need + fp16 compatibility
|
| 915 |
+
else:
|
| 916 |
+
head_mask = [None] * self.n_layer
|
| 917 |
+
|
| 918 |
+
if inputs_embeds is not None:
|
| 919 |
+
word_emb = inputs_embeds
|
| 920 |
+
else:
|
| 921 |
+
word_emb = self.word_emb(input_ids)
|
| 922 |
+
|
| 923 |
+
mlen = mems[0].size(0) if mems is not None else 0
|
| 924 |
+
klen = mlen + qlen
|
| 925 |
+
if self.same_length:
|
| 926 |
+
all_ones = word_emb.new_ones((qlen, klen), dtype=torch.bool)
|
| 927 |
+
mask_len = klen - self.mem_len
|
| 928 |
+
if mask_len > 0:
|
| 929 |
+
mask_shift_len = qlen - mask_len
|
| 930 |
+
else:
|
| 931 |
+
mask_shift_len = qlen
|
| 932 |
+
dec_attn_mask = (torch.triu(all_ones, 1 + mlen) + torch.tril(all_ones, -mask_shift_len))[:, :, None] # -1
|
| 933 |
+
else:
|
| 934 |
+
dec_attn_mask = torch.triu(word_emb.new_ones((qlen, klen), dtype=torch.bool), diagonal=1 + mlen)[
|
| 935 |
+
:, :, None
|
| 936 |
+
]
|
| 937 |
+
|
| 938 |
+
hids = []
|
| 939 |
+
attentions = [] if output_attentions else None
|
| 940 |
+
if self.attn_type == 0: # default
|
| 941 |
+
pos_seq = torch.arange(klen - 1, -1, -1.0, device=word_emb.device, dtype=torch.int64).type_as(
|
| 942 |
+
dtype=word_emb.dtype
|
| 943 |
+
)
|
| 944 |
+
if self.clamp_len > 0:
|
| 945 |
+
pos_seq.clamp_(max=self.clamp_len)
|
| 946 |
+
pos_emb = self.pos_emb(pos_seq)
|
| 947 |
+
|
| 948 |
+
core_out = self.drop(word_emb)
|
| 949 |
+
pos_emb = self.drop(pos_emb)
|
| 950 |
+
|
| 951 |
+
for i, layer in enumerate(self.layers):
|
| 952 |
+
hids.append(core_out)
|
| 953 |
+
mems_i = None if mems is None else mems[i]
|
| 954 |
+
layer_outputs = layer(
|
| 955 |
+
core_out,
|
| 956 |
+
pos_emb,
|
| 957 |
+
dec_attn_mask=dec_attn_mask,
|
| 958 |
+
mems=mems_i,
|
| 959 |
+
head_mask=head_mask[i],
|
| 960 |
+
output_attentions=output_attentions,
|
| 961 |
+
)
|
| 962 |
+
core_out = layer_outputs[0]
|
| 963 |
+
if output_attentions:
|
| 964 |
+
attentions.append(layer_outputs[1])
|
| 965 |
+
else: # learnable embeddings and absolute embeddings
|
| 966 |
+
raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
|
| 967 |
+
|
| 968 |
+
core_out = self.drop(core_out)
|
| 969 |
+
|
| 970 |
+
new_mems = self._update_mems(hids, mems, mlen, qlen)
|
| 971 |
+
|
| 972 |
+
if output_hidden_states:
|
| 973 |
+
# Add last layer and transpose to library standard shape [bsz, len, hidden_dim]
|
| 974 |
+
hids.append(core_out)
|
| 975 |
+
hids = tuple(t.transpose(0, 1).contiguous() for t in hids)
|
| 976 |
+
else:
|
| 977 |
+
hids = None
|
| 978 |
+
if output_attentions:
|
| 979 |
+
# Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len]
|
| 980 |
+
attentions = tuple(t.permute(2, 3, 0, 1).contiguous() for t in attentions)
|
| 981 |
+
# We transpose back here to shape [bsz, len, hidden_dim]
|
| 982 |
+
core_out = core_out.transpose(0, 1).contiguous()
|
| 983 |
+
|
| 984 |
+
if not return_dict:
|
| 985 |
+
return tuple(v for v in [core_out, new_mems, hids, attentions] if v is not None)
|
| 986 |
+
|
| 987 |
+
return TransfoXLModelOutput(
|
| 988 |
+
last_hidden_state=core_out,
|
| 989 |
+
mems=new_mems,
|
| 990 |
+
hidden_states=hids,
|
| 991 |
+
attentions=attentions,
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
@add_start_docstrings(
|
| 996 |
+
"""
|
| 997 |
+
The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive
|
| 998 |
+
input embeddings)
|
| 999 |
+
""",
|
| 1000 |
+
TRANSFO_XL_START_DOCSTRING,
|
| 1001 |
+
)
|
| 1002 |
+
class TransfoXLLMHeadModel(TransfoXLPreTrainedModel):
|
| 1003 |
+
_tied_weights_keys = [r"crit\.out_projs\.\d+", r"crit\.out_layers\.\d+\.weight"]
|
| 1004 |
+
|
| 1005 |
+
def __init__(self, config):
|
| 1006 |
+
super().__init__(config)
|
| 1007 |
+
self.transformer = TransfoXLModel(config)
|
| 1008 |
+
self.sample_softmax = config.sample_softmax
|
| 1009 |
+
self.trainer_compatible = getattr(config, "trainer_compatible", False)
|
| 1010 |
+
|
| 1011 |
+
if not self.trainer_compatible:
|
| 1012 |
+
warnings.warn(
|
| 1013 |
+
"The output of TransfoXL will be updated in v5 to support a single loss as first argument. In order "
|
| 1014 |
+
"to use that updated output, please specify `trainer_compatible=True` as your configuration"
|
| 1015 |
+
" attribute.",
|
| 1016 |
+
DeprecationWarning,
|
| 1017 |
+
)
|
| 1018 |
+
|
| 1019 |
+
assert self.sample_softmax <= 0, (
|
| 1020 |
+
"Sampling from the softmax is not implemented yet. Please look at issue: #3310:"
|
| 1021 |
+
" https://github.com/huggingface/transformers/issues/3310"
|
| 1022 |
+
)
|
| 1023 |
+
|
| 1024 |
+
self.crit = ProjectedAdaptiveLogSoftmax(
|
| 1025 |
+
config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val
|
| 1026 |
+
)
|
| 1027 |
+
|
| 1028 |
+
# Initialize weights and apply final processing
|
| 1029 |
+
self.post_init()
|
| 1030 |
+
|
| 1031 |
+
def tie_weights(self):
|
| 1032 |
+
"""
|
| 1033 |
+
Run this to be sure output and input (adaptive) softmax weights are tied
|
| 1034 |
+
"""
|
| 1035 |
+
|
| 1036 |
+
if self.config.tie_word_embeddings:
|
| 1037 |
+
for i in range(len(self.crit.out_layers)):
|
| 1038 |
+
self._tie_or_clone_weights(self.crit.out_layers[i], self.transformer.word_emb.emb_layers[i])
|
| 1039 |
+
if self.config.tie_projs:
|
| 1040 |
+
for i, tie_proj in enumerate(self.config.tie_projs):
|
| 1041 |
+
if tie_proj and self.config.div_val == 1 and self.config.d_model != self.config.d_embed:
|
| 1042 |
+
if self.config.torchscript:
|
| 1043 |
+
self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[0].clone())
|
| 1044 |
+
else:
|
| 1045 |
+
self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[0]
|
| 1046 |
+
elif tie_proj and self.config.div_val != 1:
|
| 1047 |
+
if self.config.torchscript:
|
| 1048 |
+
self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[i].clone())
|
| 1049 |
+
else:
|
| 1050 |
+
self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[i]
|
| 1051 |
+
|
| 1052 |
+
def reset_memory_length(self, mem_len):
|
| 1053 |
+
self.transformer.reset_memory_length(mem_len)
|
| 1054 |
+
|
| 1055 |
+
def init_mems(self, bsz):
|
| 1056 |
+
return self.transformer.init_mems(bsz)
|
| 1057 |
+
|
| 1058 |
+
@add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
|
| 1059 |
+
@add_code_sample_docstrings(
|
| 1060 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1061 |
+
output_type=TransfoXLLMHeadModelOutput,
|
| 1062 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1063 |
+
)
|
| 1064 |
+
def forward(
|
| 1065 |
+
self,
|
| 1066 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1067 |
+
mems: Optional[list[torch.FloatTensor]] = None,
|
| 1068 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1069 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1070 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1071 |
+
output_attentions: Optional[bool] = None,
|
| 1072 |
+
output_hidden_states: Optional[bool] = None,
|
| 1073 |
+
return_dict: Optional[bool] = None,
|
| 1074 |
+
) -> Union[tuple, TransfoXLLMHeadModelOutput]:
|
| 1075 |
+
r"""
|
| 1076 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1077 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
| 1078 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
| 1079 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
| 1080 |
+
"""
|
| 1081 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1082 |
+
if input_ids is not None:
|
| 1083 |
+
bsz, tgt_len = input_ids.size(0), input_ids.size(1)
|
| 1084 |
+
elif inputs_embeds is not None:
|
| 1085 |
+
bsz, tgt_len = inputs_embeds.size(0), inputs_embeds.size(1)
|
| 1086 |
+
else:
|
| 1087 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1088 |
+
|
| 1089 |
+
transformer_outputs = self.transformer(
|
| 1090 |
+
input_ids,
|
| 1091 |
+
mems=mems,
|
| 1092 |
+
head_mask=head_mask,
|
| 1093 |
+
inputs_embeds=inputs_embeds,
|
| 1094 |
+
output_attentions=output_attentions,
|
| 1095 |
+
output_hidden_states=output_hidden_states,
|
| 1096 |
+
return_dict=return_dict,
|
| 1097 |
+
)
|
| 1098 |
+
|
| 1099 |
+
last_hidden = transformer_outputs[0]
|
| 1100 |
+
pred_hid = last_hidden[:, -tgt_len:]
|
| 1101 |
+
|
| 1102 |
+
if labels is not None:
|
| 1103 |
+
# Prevents all labels being -100 and throwing an error
|
| 1104 |
+
# when backwarding the loss
|
| 1105 |
+
miss_valid_label = labels[0, 1:].sum() == (labels.size(1) - 1) * -100
|
| 1106 |
+
if miss_valid_label:
|
| 1107 |
+
# Sets an <EOS> token, just to prevent loss from being NaN
|
| 1108 |
+
labels[0, 1] = self.config.eos_token_id
|
| 1109 |
+
|
| 1110 |
+
softmax_output = self.crit(pred_hid, labels)
|
| 1111 |
+
prediction_scores = softmax_output.view(bsz, tgt_len, -1) if labels is None else ()
|
| 1112 |
+
|
| 1113 |
+
if labels is not None:
|
| 1114 |
+
losses = softmax_output.view(bsz, tgt_len - 1)
|
| 1115 |
+
# Avoids from incorporating padding (-100) tokens into loss value
|
| 1116 |
+
loss = losses[losses != 0].mean()
|
| 1117 |
+
else:
|
| 1118 |
+
losses, loss = None, None
|
| 1119 |
+
|
| 1120 |
+
if not return_dict:
|
| 1121 |
+
if self.trainer_compatible:
|
| 1122 |
+
output = (prediction_scores, losses) if losses is not None else (prediction_scores,)
|
| 1123 |
+
output += transformer_outputs[1:]
|
| 1124 |
+
return ((loss,) + output) if loss is not None else output
|
| 1125 |
+
else:
|
| 1126 |
+
output = (prediction_scores, *transformer_outputs[1:])
|
| 1127 |
+
output = ((losses,) + output) if losses is not None else output
|
| 1128 |
+
return (output + (loss,)) if loss is not None else output
|
| 1129 |
+
|
| 1130 |
+
return TransfoXLLMHeadModelOutput(
|
| 1131 |
+
loss=loss,
|
| 1132 |
+
prediction_scores=prediction_scores,
|
| 1133 |
+
losses=losses,
|
| 1134 |
+
mems=transformer_outputs.mems,
|
| 1135 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1136 |
+
attentions=transformer_outputs.attentions,
|
| 1137 |
+
)
|
| 1138 |
+
|
| 1139 |
+
def get_output_embeddings(self):
|
| 1140 |
+
"""Double-check if you are using adaptive softmax."""
|
| 1141 |
+
if self.sample_softmax > 0:
|
| 1142 |
+
return self.out_layer
|
| 1143 |
+
else:
|
| 1144 |
+
return self.crit.out_layers[-1]
|
| 1145 |
+
|
| 1146 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **model_kwargs):
|
| 1147 |
+
inputs = {}
|
| 1148 |
+
|
| 1149 |
+
# if past is defined in model kwargs then use it for faster decoding
|
| 1150 |
+
if past_key_values:
|
| 1151 |
+
inputs["mems"] = past_key_values
|
| 1152 |
+
inputs["input_ids"] = input_ids[:, -1].unsqueeze(-1)
|
| 1153 |
+
else:
|
| 1154 |
+
inputs["input_ids"] = input_ids
|
| 1155 |
+
|
| 1156 |
+
return inputs
|
| 1157 |
+
|
| 1158 |
+
def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer):
|
| 1159 |
+
new_cutoffs = super()._resize_cutoffs(new_num_tokens, new_emb_size, new_embedding_shapes, layer)
|
| 1160 |
+
|
| 1161 |
+
self.crit.cutoffs = new_cutoffs
|
| 1162 |
+
self.crit.cutoff_ends = [0] + new_cutoffs
|
| 1163 |
+
self.crit.n_token = new_num_tokens
|
| 1164 |
+
|
| 1165 |
+
@staticmethod
|
| 1166 |
+
def _reorder_cache(mems: list[torch.Tensor], beam_idx: torch.Tensor) -> list[torch.Tensor]:
|
| 1167 |
+
"""
|
| 1168 |
+
This function is used to re-order the `mems` cache if [`~PreTrainedModel.beam_search`] or
|
| 1169 |
+
[`~PreTrainedModel.beam_sample`] is called. This is required to match `mems` with the correct beam_idx at every
|
| 1170 |
+
generation step.
|
| 1171 |
+
"""
|
| 1172 |
+
return [layer_past.index_select(1, beam_idx.to(layer_past.device)) for layer_past in mems]
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
@add_start_docstrings(
|
| 1176 |
+
"""
|
| 1177 |
+
The Transformer-XL Model transformer with a sequence classification head on top (linear layer).
|
| 1178 |
+
|
| 1179 |
+
[`TransfoXLForSequenceClassification`] uses the last token in order to do the classification, as other causal
|
| 1180 |
+
models (e.g. GPT-1) do.
|
| 1181 |
+
|
| 1182 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 1183 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 1184 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 1185 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 1186 |
+
each row of the batch).
|
| 1187 |
+
""",
|
| 1188 |
+
TRANSFO_XL_START_DOCSTRING,
|
| 1189 |
+
)
|
| 1190 |
+
class TransfoXLForSequenceClassification(TransfoXLPreTrainedModel):
|
| 1191 |
+
def __init__(self, config):
|
| 1192 |
+
super().__init__(config)
|
| 1193 |
+
self.num_labels = config.num_labels
|
| 1194 |
+
self.transformer = TransfoXLModel(config)
|
| 1195 |
+
self.score = nn.Linear(config.d_embed, self.num_labels, bias=False)
|
| 1196 |
+
# Initialize weights and apply final processing
|
| 1197 |
+
self.post_init()
|
| 1198 |
+
|
| 1199 |
+
@add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
|
| 1200 |
+
@add_code_sample_docstrings(
|
| 1201 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1202 |
+
output_type=TransfoXLSequenceClassifierOutputWithPast,
|
| 1203 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1204 |
+
)
|
| 1205 |
+
def forward(
|
| 1206 |
+
self,
|
| 1207 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1208 |
+
mems: Optional[list[torch.FloatTensor]] = None,
|
| 1209 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1210 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1211 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1212 |
+
output_attentions: Optional[bool] = None,
|
| 1213 |
+
output_hidden_states: Optional[bool] = None,
|
| 1214 |
+
return_dict: Optional[bool] = None,
|
| 1215 |
+
) -> Union[tuple, TransfoXLSequenceClassifierOutputWithPast]:
|
| 1216 |
+
r"""
|
| 1217 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1218 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1219 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1220 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1221 |
+
"""
|
| 1222 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1223 |
+
|
| 1224 |
+
transformer_outputs = self.transformer(
|
| 1225 |
+
input_ids,
|
| 1226 |
+
mems=mems,
|
| 1227 |
+
head_mask=head_mask,
|
| 1228 |
+
inputs_embeds=inputs_embeds,
|
| 1229 |
+
output_attentions=output_attentions,
|
| 1230 |
+
output_hidden_states=output_hidden_states,
|
| 1231 |
+
return_dict=return_dict,
|
| 1232 |
+
)
|
| 1233 |
+
hidden_states = transformer_outputs[0]
|
| 1234 |
+
logits = self.score(hidden_states)
|
| 1235 |
+
|
| 1236 |
+
if input_ids is not None:
|
| 1237 |
+
batch_size, sequence_length = input_ids.shape[:2]
|
| 1238 |
+
else:
|
| 1239 |
+
batch_size, sequence_length = inputs_embeds.shape[:2]
|
| 1240 |
+
|
| 1241 |
+
assert self.config.pad_token_id is not None or batch_size == 1, (
|
| 1242 |
+
"Cannot handle batch sizes > 1 if no padding token is defined."
|
| 1243 |
+
)
|
| 1244 |
+
if self.config.pad_token_id is None:
|
| 1245 |
+
sequence_lengths = -1
|
| 1246 |
+
else:
|
| 1247 |
+
if input_ids is not None:
|
| 1248 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
| 1249 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
| 1250 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
| 1251 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
| 1252 |
+
else:
|
| 1253 |
+
sequence_lengths = -1
|
| 1254 |
+
logger.warning_once(
|
| 1255 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
| 1256 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
| 1257 |
+
)
|
| 1258 |
+
|
| 1259 |
+
pooled_logits = logits[range(batch_size), sequence_lengths]
|
| 1260 |
+
|
| 1261 |
+
loss = None
|
| 1262 |
+
if labels is not None:
|
| 1263 |
+
if self.config.problem_type is None:
|
| 1264 |
+
if self.num_labels == 1:
|
| 1265 |
+
self.config.problem_type = "regression"
|
| 1266 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1267 |
+
self.config.problem_type = "single_label_classification"
|
| 1268 |
+
else:
|
| 1269 |
+
self.config.problem_type = "multi_label_classification"
|
| 1270 |
+
|
| 1271 |
+
if self.config.problem_type == "regression":
|
| 1272 |
+
loss_fct = MSELoss()
|
| 1273 |
+
if self.num_labels == 1:
|
| 1274 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
| 1275 |
+
else:
|
| 1276 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1277 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1278 |
+
loss_fct = CrossEntropyLoss()
|
| 1279 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
| 1280 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1281 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1282 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1283 |
+
if not return_dict:
|
| 1284 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1285 |
+
return ((loss,) + output) if loss is not None else output
|
| 1286 |
+
|
| 1287 |
+
return TransfoXLSequenceClassifierOutputWithPast(
|
| 1288 |
+
loss=loss,
|
| 1289 |
+
logits=pooled_logits,
|
| 1290 |
+
mems=transformer_outputs.mems,
|
| 1291 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1292 |
+
attentions=transformer_outputs.attentions,
|
| 1293 |
+
)
|
| 1294 |
+
|
| 1295 |
+
|
| 1296 |
+
__all__ = [
|
| 1297 |
+
"AdaptiveEmbedding",
|
| 1298 |
+
"TransfoXLForSequenceClassification",
|
| 1299 |
+
"TransfoXLLMHeadModel",
|
| 1300 |
+
"TransfoXLModel",
|
| 1301 |
+
"TransfoXLPreTrainedModel",
|
| 1302 |
+
"load_tf_weights_in_transfo_xl",
|
| 1303 |
+
]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University 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 |
+
"""
|
| 17 |
+
Utilities for PyTorch Transformer XL model. Directly adapted from https://github.com/kimiyoung/transformer-xl.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# CUDA_MAJOR = int(torch.version.cuda.split('.')[0])
|
| 25 |
+
# CUDA_MINOR = int(torch.version.cuda.split('.')[1])
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ProjectedAdaptiveLogSoftmax(nn.Module):
|
| 29 |
+
def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, keep_order=False):
|
| 30 |
+
super().__init__()
|
| 31 |
+
|
| 32 |
+
self.n_token = n_token
|
| 33 |
+
self.d_embed = d_embed
|
| 34 |
+
self.d_proj = d_proj
|
| 35 |
+
|
| 36 |
+
self.cutoffs = cutoffs + [n_token]
|
| 37 |
+
self.cutoff_ends = [0] + self.cutoffs
|
| 38 |
+
self.div_val = div_val
|
| 39 |
+
|
| 40 |
+
self.shortlist_size = self.cutoffs[0]
|
| 41 |
+
self.n_clusters = len(self.cutoffs) - 1
|
| 42 |
+
self.head_size = self.shortlist_size + self.n_clusters
|
| 43 |
+
|
| 44 |
+
if self.n_clusters > 0:
|
| 45 |
+
self.cluster_weight = nn.Parameter(torch.zeros(self.n_clusters, self.d_embed))
|
| 46 |
+
self.cluster_bias = nn.Parameter(torch.zeros(self.n_clusters))
|
| 47 |
+
|
| 48 |
+
self.out_layers = nn.ModuleList()
|
| 49 |
+
self.out_projs = nn.ParameterList()
|
| 50 |
+
|
| 51 |
+
if div_val == 1:
|
| 52 |
+
for i in range(len(self.cutoffs)):
|
| 53 |
+
if d_proj != d_embed:
|
| 54 |
+
self.out_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed)))
|
| 55 |
+
else:
|
| 56 |
+
self.out_projs.append(None)
|
| 57 |
+
|
| 58 |
+
self.out_layers.append(nn.Linear(d_embed, n_token))
|
| 59 |
+
else:
|
| 60 |
+
for i in range(len(self.cutoffs)):
|
| 61 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 62 |
+
d_emb_i = d_embed // (div_val**i)
|
| 63 |
+
|
| 64 |
+
self.out_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i)))
|
| 65 |
+
|
| 66 |
+
self.out_layers.append(nn.Linear(d_emb_i, r_idx - l_idx))
|
| 67 |
+
|
| 68 |
+
self.keep_order = keep_order
|
| 69 |
+
|
| 70 |
+
def _compute_logit(self, hidden, weight, bias, proj):
|
| 71 |
+
if proj is None:
|
| 72 |
+
logit = nn.functional.linear(hidden, weight, bias=bias)
|
| 73 |
+
else:
|
| 74 |
+
# if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
|
| 75 |
+
proj_hid = nn.functional.linear(hidden, proj.t().contiguous())
|
| 76 |
+
logit = nn.functional.linear(proj_hid, weight, bias=bias)
|
| 77 |
+
# else:
|
| 78 |
+
# logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
|
| 79 |
+
# if bias is not None:
|
| 80 |
+
# logit = logit + bias
|
| 81 |
+
|
| 82 |
+
return logit
|
| 83 |
+
|
| 84 |
+
def forward(self, hidden, labels=None, keep_order=False):
|
| 85 |
+
"""
|
| 86 |
+
Params:
|
| 87 |
+
hidden :: [len*bsz x d_proj]
|
| 88 |
+
labels :: [len*bsz]
|
| 89 |
+
|
| 90 |
+
Return:
|
| 91 |
+
if labels is None: out :: [len*bsz x n_tokens] log probabilities of tokens over the vocabulary else: out ::
|
| 92 |
+
[(len-1)*bsz] Negative log likelihood. We could replace this implementation by the native PyTorch one if
|
| 93 |
+
theirs had an option to set bias on all clusters in the native one. here:
|
| 94 |
+
https://github.com/pytorch/pytorch/blob/dbe6a7a9ff1a364a8706bf5df58a1ca96d2fd9da/torch/nn/modules/adaptive.py#L138
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
if labels is not None:
|
| 98 |
+
# Shift so that tokens < n predict n
|
| 99 |
+
hidden = hidden[..., :-1, :].contiguous()
|
| 100 |
+
labels = labels[..., 1:].contiguous()
|
| 101 |
+
hidden = hidden.view(-1, hidden.size(-1))
|
| 102 |
+
labels = labels.view(-1)
|
| 103 |
+
if hidden.size(0) != labels.size(0):
|
| 104 |
+
raise RuntimeError("Input and labels should have the same size in the batch dimension.")
|
| 105 |
+
else:
|
| 106 |
+
hidden = hidden.view(-1, hidden.size(-1))
|
| 107 |
+
|
| 108 |
+
if self.n_clusters == 0:
|
| 109 |
+
logit = self._compute_logit(hidden, self.out_layers[0].weight, self.out_layers[0].bias, self.out_projs[0])
|
| 110 |
+
if labels is not None:
|
| 111 |
+
mask = labels != -100
|
| 112 |
+
out = torch.zeros_like(labels, dtype=hidden.dtype, device=hidden.device)
|
| 113 |
+
out[mask] = (
|
| 114 |
+
-nn.functional.log_softmax(logit, dim=-1)[mask].gather(1, labels[mask].unsqueeze(1)).squeeze(1)
|
| 115 |
+
)
|
| 116 |
+
else:
|
| 117 |
+
out = nn.functional.log_softmax(logit, dim=-1)
|
| 118 |
+
else:
|
| 119 |
+
# construct weights and biases
|
| 120 |
+
weights, biases = [], []
|
| 121 |
+
for i in range(len(self.cutoffs)):
|
| 122 |
+
if self.div_val == 1:
|
| 123 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 124 |
+
weight_i = self.out_layers[0].weight[l_idx:r_idx]
|
| 125 |
+
bias_i = self.out_layers[0].bias[l_idx:r_idx]
|
| 126 |
+
else:
|
| 127 |
+
weight_i = self.out_layers[i].weight
|
| 128 |
+
bias_i = self.out_layers[i].bias
|
| 129 |
+
|
| 130 |
+
if i == 0:
|
| 131 |
+
weight_i = torch.cat([weight_i, self.cluster_weight], dim=0)
|
| 132 |
+
bias_i = torch.cat([bias_i, self.cluster_bias], dim=0)
|
| 133 |
+
|
| 134 |
+
weights.append(weight_i)
|
| 135 |
+
biases.append(bias_i)
|
| 136 |
+
|
| 137 |
+
head_weight, head_bias, head_proj = weights[0], biases[0], self.out_projs[0]
|
| 138 |
+
|
| 139 |
+
head_logit = self._compute_logit(hidden, head_weight, head_bias, head_proj)
|
| 140 |
+
head_logprob = nn.functional.log_softmax(head_logit, dim=1)
|
| 141 |
+
|
| 142 |
+
if labels is None:
|
| 143 |
+
out = hidden.new_empty((head_logit.size(0), self.n_token))
|
| 144 |
+
else:
|
| 145 |
+
out = torch.zeros_like(labels, dtype=hidden.dtype, device=hidden.device)
|
| 146 |
+
|
| 147 |
+
offset = 0
|
| 148 |
+
cutoff_values = [0] + self.cutoffs
|
| 149 |
+
for i in range(len(cutoff_values) - 1):
|
| 150 |
+
l_idx, r_idx = cutoff_values[i], cutoff_values[i + 1]
|
| 151 |
+
|
| 152 |
+
if labels is not None:
|
| 153 |
+
mask_i = (labels >= l_idx) & (labels < r_idx)
|
| 154 |
+
indices_i = mask_i.nonzero().squeeze()
|
| 155 |
+
|
| 156 |
+
if indices_i.numel() == 0:
|
| 157 |
+
continue
|
| 158 |
+
|
| 159 |
+
target_i = labels.index_select(0, indices_i) - l_idx
|
| 160 |
+
head_logprob_i = head_logprob.index_select(0, indices_i)
|
| 161 |
+
hidden_i = hidden.index_select(0, indices_i)
|
| 162 |
+
else:
|
| 163 |
+
hidden_i = hidden
|
| 164 |
+
|
| 165 |
+
if i == 0:
|
| 166 |
+
if labels is not None:
|
| 167 |
+
logprob_i = head_logprob_i.gather(1, target_i[:, None]).squeeze(1)
|
| 168 |
+
else:
|
| 169 |
+
out[:, : self.cutoffs[0]] = head_logprob[:, : self.cutoffs[0]]
|
| 170 |
+
else:
|
| 171 |
+
weight_i, bias_i, proj_i = weights[i], biases[i], self.out_projs[i]
|
| 172 |
+
|
| 173 |
+
tail_logit_i = self._compute_logit(hidden_i, weight_i, bias_i, proj_i)
|
| 174 |
+
tail_logprob_i = nn.functional.log_softmax(tail_logit_i, dim=1)
|
| 175 |
+
cluster_prob_idx = self.cutoffs[0] + i - 1 # No probability for the head cluster
|
| 176 |
+
if labels is not None:
|
| 177 |
+
logprob_i = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
|
| 178 |
+
1, target_i[:, None]
|
| 179 |
+
).squeeze(1)
|
| 180 |
+
else:
|
| 181 |
+
logprob_i = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
|
| 182 |
+
out[:, l_idx:r_idx] = logprob_i
|
| 183 |
+
|
| 184 |
+
if labels is not None:
|
| 185 |
+
if (hasattr(self, "keep_order") and self.keep_order) or keep_order:
|
| 186 |
+
out.index_copy_(0, indices_i, -logprob_i)
|
| 187 |
+
else:
|
| 188 |
+
out[offset : offset + logprob_i.size(0)].copy_(-logprob_i)
|
| 189 |
+
offset += logprob_i.size(0)
|
| 190 |
+
|
| 191 |
+
return out
|
| 192 |
+
|
| 193 |
+
def log_prob(self, hidden):
|
| 194 |
+
r"""
|
| 195 |
+
Computes log probabilities for all \\(n\_classes\\) From:
|
| 196 |
+
https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/adaptive.p
|
| 197 |
+
|
| 198 |
+
Args:
|
| 199 |
+
hidden (Tensor): a minibatch of example
|
| 200 |
+
|
| 201 |
+
Returns:
|
| 202 |
+
log-probabilities of for each class \\(c\\) in range \\(0 <= c <= n\_classes\\), where \\(n\_classes\\) is
|
| 203 |
+
a parameter passed to `AdaptiveLogSoftmaxWithLoss` constructor. Shape:
|
| 204 |
+
|
| 205 |
+
- Input: \\((N, in\_features)\\)
|
| 206 |
+
- Output: \\((N, n\_classes)\\)
|
| 207 |
+
"""
|
| 208 |
+
if self.n_clusters == 0:
|
| 209 |
+
logit = self._compute_logit(hidden, self.out_layers[0].weight, self.out_layers[0].bias, self.out_projs[0])
|
| 210 |
+
return nn.functional.log_softmax(logit, dim=-1)
|
| 211 |
+
else:
|
| 212 |
+
# construct weights and biases
|
| 213 |
+
weights, biases = [], []
|
| 214 |
+
for i in range(len(self.cutoffs)):
|
| 215 |
+
if self.div_val == 1:
|
| 216 |
+
l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
|
| 217 |
+
weight_i = self.out_layers[0].weight[l_idx:r_idx]
|
| 218 |
+
bias_i = self.out_layers[0].bias[l_idx:r_idx]
|
| 219 |
+
else:
|
| 220 |
+
weight_i = self.out_layers[i].weight
|
| 221 |
+
bias_i = self.out_layers[i].bias
|
| 222 |
+
|
| 223 |
+
if i == 0:
|
| 224 |
+
weight_i = torch.cat([weight_i, self.cluster_weight], dim=0)
|
| 225 |
+
bias_i = torch.cat([bias_i, self.cluster_bias], dim=0)
|
| 226 |
+
|
| 227 |
+
weights.append(weight_i)
|
| 228 |
+
biases.append(bias_i)
|
| 229 |
+
|
| 230 |
+
head_weight, head_bias, head_proj = weights[0], biases[0], self.out_projs[0]
|
| 231 |
+
head_logit = self._compute_logit(hidden, head_weight, head_bias, head_proj)
|
| 232 |
+
|
| 233 |
+
out = hidden.new_empty((head_logit.size(0), self.n_token))
|
| 234 |
+
head_logprob = nn.functional.log_softmax(head_logit, dim=1)
|
| 235 |
+
|
| 236 |
+
cutoff_values = [0] + self.cutoffs
|
| 237 |
+
for i in range(len(cutoff_values) - 1):
|
| 238 |
+
start_idx, stop_idx = cutoff_values[i], cutoff_values[i + 1]
|
| 239 |
+
|
| 240 |
+
if i == 0:
|
| 241 |
+
out[:, : self.cutoffs[0]] = head_logprob[:, : self.cutoffs[0]]
|
| 242 |
+
else:
|
| 243 |
+
weight_i, bias_i, proj_i = weights[i], biases[i], self.out_projs[i]
|
| 244 |
+
|
| 245 |
+
tail_logit_i = self._compute_logit(hidden, weight_i, bias_i, proj_i)
|
| 246 |
+
tail_logprob_i = nn.functional.log_softmax(tail_logit_i, dim=1)
|
| 247 |
+
|
| 248 |
+
logprob_i = head_logprob[:, -i] + tail_logprob_i
|
| 249 |
+
out[:, start_idx, stop_idx] = logprob_i
|
| 250 |
+
|
| 251 |
+
return out
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/transfo_xl/tokenization_transfo_xl.py
ADDED
|
@@ -0,0 +1,825 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University 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 |
+
"""
|
| 17 |
+
Tokenization classes for Transformer XL model. Adapted from https://github.com/kimiyoung/transformer-xl.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import glob
|
| 21 |
+
import os
|
| 22 |
+
import pickle
|
| 23 |
+
import re
|
| 24 |
+
from collections import Counter, OrderedDict
|
| 25 |
+
from typing import Optional
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
from ....tokenization_utils import PreTrainedTokenizer
|
| 30 |
+
from ....utils import (
|
| 31 |
+
cached_file,
|
| 32 |
+
check_torch_load_is_safe,
|
| 33 |
+
is_sacremoses_available,
|
| 34 |
+
is_torch_available,
|
| 35 |
+
logging,
|
| 36 |
+
requires_backends,
|
| 37 |
+
strtobool,
|
| 38 |
+
torch_only_method,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if is_sacremoses_available():
|
| 43 |
+
import sacremoses as sm
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if is_torch_available():
|
| 47 |
+
import torch
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
logger = logging.get_logger(__name__)
|
| 51 |
+
|
| 52 |
+
VOCAB_FILES_NAMES = {
|
| 53 |
+
"pretrained_vocab_file": "vocab.pkl",
|
| 54 |
+
"pretrained_vocab_file_torch": "vocab.bin",
|
| 55 |
+
"vocab_file": "vocab.txt",
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
PRETRAINED_CORPUS_ARCHIVE_MAP = {
|
| 60 |
+
"transfo-xl/transfo-xl-wt103": "https://huggingface.co/transfo-xl/transfo-xl-wt103/resolve/main/corpus.bin",
|
| 61 |
+
}
|
| 62 |
+
CORPUS_NAME = "corpus.bin"
|
| 63 |
+
|
| 64 |
+
MATCH_NUMBERS = r"(?<=\d)[,.](?=\d)", r" @\g<0>@ "
|
| 65 |
+
DETOKENIZE_NUMBERS = [(r" @\,@ ", r","), (r" @\.@ ", r".")]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def tokenize_numbers(text_array: list[str]) -> list[str]:
|
| 69 |
+
"""
|
| 70 |
+
Splits large comma-separated numbers and floating point values. This is done by replacing commas with ' @,@ ' and
|
| 71 |
+
dots with ' @.@ '.
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
text_array: An already tokenized text as list.
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
A list of strings with tokenized numbers.
|
| 78 |
+
|
| 79 |
+
Example:
|
| 80 |
+
|
| 81 |
+
```python
|
| 82 |
+
>>> tokenize_numbers(["$", "5,000", "1.73", "m"])
|
| 83 |
+
['$', '5', '@,@', '000', '1', '@.@', '73', 'm']
|
| 84 |
+
```"""
|
| 85 |
+
tokenized = []
|
| 86 |
+
for i in range(len(text_array)):
|
| 87 |
+
reg, sub = MATCH_NUMBERS
|
| 88 |
+
replaced = re.sub(reg, sub, text_array[i]).split()
|
| 89 |
+
tokenized.extend(replaced)
|
| 90 |
+
|
| 91 |
+
return tokenized
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def detokenize_numbers(text: str) -> str:
|
| 95 |
+
"""
|
| 96 |
+
Inverts the operation of *tokenize_numbers*. This is replacing ' @,@ ' and ' @.@' by ',' and '.'.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
text: A string where the number should be detokenized.
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
A detokenized string.
|
| 103 |
+
|
| 104 |
+
Example:
|
| 105 |
+
|
| 106 |
+
```python
|
| 107 |
+
>>> detokenize_numbers("$ 5 @,@ 000 1 @.@ 73 m")
|
| 108 |
+
'$ 5,000 1.73 m'
|
| 109 |
+
```"""
|
| 110 |
+
for reg, sub in DETOKENIZE_NUMBERS:
|
| 111 |
+
text = re.sub(reg, sub, text)
|
| 112 |
+
return text
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class TransfoXLTokenizer(PreTrainedTokenizer):
|
| 116 |
+
"""
|
| 117 |
+
Construct a Transformer-XL tokenizer adapted from Vocab class in [the original
|
| 118 |
+
code](https://github.com/kimiyoung/transformer-xl). The Transformer-XL tokenizer is a word-level tokenizer (no
|
| 119 |
+
sub-word tokenization).
|
| 120 |
+
|
| 121 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 122 |
+
this superclass for more information regarding those methods.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
special (`list[str]`, *optional*):
|
| 126 |
+
A list of special tokens (to be treated by the original implementation of this tokenizer).
|
| 127 |
+
min_freq (`int`, *optional*, defaults to 0):
|
| 128 |
+
The minimum number of times a token has to be present in order to be kept in the vocabulary (otherwise it
|
| 129 |
+
will be mapped to `unk_token`).
|
| 130 |
+
max_size (`int`, *optional*):
|
| 131 |
+
The maximum size of the vocabulary. If left unset, it will default to the size of the vocabulary found
|
| 132 |
+
after excluding the tokens according to the `min_freq` rule.
|
| 133 |
+
lower_case (`bool`, *optional*, defaults to `False`):
|
| 134 |
+
Whether or not to lowercase the input when tokenizing.
|
| 135 |
+
delimiter (`str`, *optional*):
|
| 136 |
+
The delimiter used between tokens.
|
| 137 |
+
vocab_file (`str`, *optional*):
|
| 138 |
+
File containing the vocabulary (from the original implementation).
|
| 139 |
+
pretrained_vocab_file (`str`, *optional*):
|
| 140 |
+
File containing the vocabulary as saved with the `save_pretrained()` method.
|
| 141 |
+
never_split (`list[str]`, *optional*):
|
| 142 |
+
List of tokens that should never be split. If no list is specified, will simply use the existing special
|
| 143 |
+
tokens.
|
| 144 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 145 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 146 |
+
token instead.
|
| 147 |
+
eos_token (`str`, *optional*, defaults to `"<eos>"`):
|
| 148 |
+
The end of sequence token.
|
| 149 |
+
additional_special_tokens (`list[str]`, *optional*, defaults to `['<formula>']`):
|
| 150 |
+
A list of additional special tokens (for the HuggingFace functionality).
|
| 151 |
+
language (`str`, *optional*, defaults to `"en"`):
|
| 152 |
+
The language of this tokenizer (used for mose preprocessing).
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 156 |
+
model_input_names = ["input_ids"]
|
| 157 |
+
|
| 158 |
+
def __init__(
|
| 159 |
+
self,
|
| 160 |
+
special=None,
|
| 161 |
+
min_freq=0,
|
| 162 |
+
max_size=None,
|
| 163 |
+
lower_case=False,
|
| 164 |
+
delimiter=None,
|
| 165 |
+
vocab_file=None,
|
| 166 |
+
pretrained_vocab_file: Optional[str] = None,
|
| 167 |
+
never_split=None,
|
| 168 |
+
unk_token="<unk>",
|
| 169 |
+
eos_token="<eos>",
|
| 170 |
+
additional_special_tokens=["<formula>"],
|
| 171 |
+
language="en",
|
| 172 |
+
**kwargs,
|
| 173 |
+
):
|
| 174 |
+
logger.error(
|
| 175 |
+
"`TransfoXL` was deprecated due to security issues linked to `pickle.load` in `TransfoXLTokenizer`. "
|
| 176 |
+
"See more details on this model's documentation page: "
|
| 177 |
+
"`https://github.com/huggingface/transformers/blob/main/docs/source/en/model_doc/transfo-xl.md`."
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
requires_backends(self, "sacremoses")
|
| 181 |
+
if special is None:
|
| 182 |
+
special = []
|
| 183 |
+
self.counter = Counter()
|
| 184 |
+
self.special = special
|
| 185 |
+
self.min_freq = min_freq
|
| 186 |
+
self.max_size = max_size
|
| 187 |
+
self.lower_case = lower_case
|
| 188 |
+
self.delimiter = delimiter
|
| 189 |
+
self.vocab_file = vocab_file
|
| 190 |
+
self.punctuation_symbols = '!"#$%&()*+,-./\\:;<=>?@[\\]^_`{|}~'
|
| 191 |
+
self.punction_without_space_before_pattern = re.compile(rf"[^\s][{self.punctuation_symbols}]")
|
| 192 |
+
self.punctuation_with_space_around_pattern = self._compile_space_around_punctuation_pattern()
|
| 193 |
+
self.language = language
|
| 194 |
+
self.moses_punct_normalizer = sm.MosesPunctNormalizer(language)
|
| 195 |
+
self.moses_tokenizer = sm.MosesTokenizer(language)
|
| 196 |
+
self.moses_detokenizer = sm.MosesDetokenizer(language)
|
| 197 |
+
self.idx2sym = []
|
| 198 |
+
self.sym2idx = OrderedDict()
|
| 199 |
+
# This try... catch... is not beautiful but honestly this tokenizer was not made to be used
|
| 200 |
+
# in a library like ours, at all.
|
| 201 |
+
try:
|
| 202 |
+
vocab_dict = None
|
| 203 |
+
if pretrained_vocab_file is not None:
|
| 204 |
+
# Priority on pickle files (support PyTorch and TF)
|
| 205 |
+
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
|
| 206 |
+
raise ValueError(
|
| 207 |
+
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is "
|
| 208 |
+
"potentially malicious. It's recommended to never unpickle data that could have come from an "
|
| 209 |
+
"untrusted source, or that could have been tampered with. If you already verified the pickle "
|
| 210 |
+
"data and decided to use it, you can set the environment variable "
|
| 211 |
+
"`TRUST_REMOTE_CODE` to `True` to allow it."
|
| 212 |
+
)
|
| 213 |
+
with open(pretrained_vocab_file, "rb") as f:
|
| 214 |
+
vocab_dict = pickle.load(f)
|
| 215 |
+
|
| 216 |
+
# Loading a torch-saved transfo-xl vocab dict with pickle results in an integer
|
| 217 |
+
# Entering this if statement means that we tried to load a torch-saved file with pickle, and we failed.
|
| 218 |
+
# We therefore load it with torch, if it's available.
|
| 219 |
+
if isinstance(vocab_dict, int):
|
| 220 |
+
if not is_torch_available():
|
| 221 |
+
raise ImportError(
|
| 222 |
+
"Not trying to load dict with PyTorch as you need to install pytorch to load "
|
| 223 |
+
"from a PyTorch pretrained vocabulary, "
|
| 224 |
+
"or activate it with environment variables USE_TORCH=1 and USE_TF=0."
|
| 225 |
+
)
|
| 226 |
+
check_torch_load_is_safe()
|
| 227 |
+
vocab_dict = torch.load(pretrained_vocab_file, weights_only=True)
|
| 228 |
+
|
| 229 |
+
if vocab_dict is not None:
|
| 230 |
+
for key, value in vocab_dict.items():
|
| 231 |
+
if key not in self.__dict__ or key in ["sym2idx", "idx2sym"]:
|
| 232 |
+
self.__dict__[key] = value
|
| 233 |
+
elif vocab_file is not None:
|
| 234 |
+
self.build_vocab()
|
| 235 |
+
|
| 236 |
+
except Exception as e:
|
| 237 |
+
raise ValueError(
|
| 238 |
+
f"Unable to parse file {pretrained_vocab_file}. Unknown format. "
|
| 239 |
+
"If you tried to load a model saved through TransfoXLTokenizerFast, "
|
| 240 |
+
"please note they are not compatible."
|
| 241 |
+
) from e
|
| 242 |
+
|
| 243 |
+
if vocab_file is not None:
|
| 244 |
+
self.build_vocab()
|
| 245 |
+
|
| 246 |
+
super().__init__(
|
| 247 |
+
special=special,
|
| 248 |
+
min_freq=min_freq,
|
| 249 |
+
max_size=max_size,
|
| 250 |
+
lower_case=lower_case,
|
| 251 |
+
delimiter=delimiter,
|
| 252 |
+
vocab_file=vocab_file,
|
| 253 |
+
pretrained_vocab_file=pretrained_vocab_file,
|
| 254 |
+
never_split=never_split,
|
| 255 |
+
unk_token=unk_token,
|
| 256 |
+
eos_token=eos_token,
|
| 257 |
+
additional_special_tokens=additional_special_tokens,
|
| 258 |
+
language=language,
|
| 259 |
+
**kwargs,
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
# these are not required to initialize the parent class as only used when tokenizing.
|
| 263 |
+
if never_split is None:
|
| 264 |
+
never_split = self.all_special_tokens
|
| 265 |
+
self.never_split = never_split
|
| 266 |
+
|
| 267 |
+
@property
|
| 268 |
+
def do_lower_case(self):
|
| 269 |
+
return self.lower_case
|
| 270 |
+
|
| 271 |
+
def _compile_space_around_punctuation_pattern(self):
|
| 272 |
+
look_ahead_for_special_token = f"(?=[{self.punctuation_symbols}])"
|
| 273 |
+
look_ahead_to_match_all_except_space = r"(?=[^\s])"
|
| 274 |
+
return re.compile(r"" + look_ahead_for_special_token + look_ahead_to_match_all_except_space)
|
| 275 |
+
|
| 276 |
+
def count_file(self, path, verbose=False, add_eos=False):
|
| 277 |
+
if verbose:
|
| 278 |
+
logger.info(f"counting file {path} ...")
|
| 279 |
+
assert os.path.exists(path), f"Input file {path} not found"
|
| 280 |
+
|
| 281 |
+
sents = []
|
| 282 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 283 |
+
for idx, line in enumerate(f):
|
| 284 |
+
if verbose and idx > 0 and idx % 500000 == 0:
|
| 285 |
+
logger.info(f" line {idx}")
|
| 286 |
+
symbols = self.tokenize(line, add_eos=add_eos)
|
| 287 |
+
self.counter.update(symbols)
|
| 288 |
+
sents.append(symbols)
|
| 289 |
+
|
| 290 |
+
return sents
|
| 291 |
+
|
| 292 |
+
def count_sents(self, sents, verbose=False):
|
| 293 |
+
"""
|
| 294 |
+
sents : a list of sentences, each a list of tokenized symbols
|
| 295 |
+
"""
|
| 296 |
+
if verbose:
|
| 297 |
+
logger.info(f"counting {len(sents)} sents ...")
|
| 298 |
+
for idx, symbols in enumerate(sents):
|
| 299 |
+
if verbose and idx > 0 and idx % 500000 == 0:
|
| 300 |
+
logger.info(f" line {idx}")
|
| 301 |
+
self.counter.update(symbols)
|
| 302 |
+
|
| 303 |
+
def _build_from_file(self, vocab_file):
|
| 304 |
+
self.idx2sym = []
|
| 305 |
+
self.sym2idx = OrderedDict()
|
| 306 |
+
|
| 307 |
+
with open(vocab_file, "r", encoding="utf-8") as f:
|
| 308 |
+
for line in f:
|
| 309 |
+
symb = line.strip().split()[0]
|
| 310 |
+
self.add_symbol(symb)
|
| 311 |
+
if "<UNK>" in self.sym2idx:
|
| 312 |
+
self.unk_idx = self.sym2idx["<UNK>"]
|
| 313 |
+
elif "<unk>" in self.sym2idx:
|
| 314 |
+
self.unk_idx = self.sym2idx["<unk>"]
|
| 315 |
+
else:
|
| 316 |
+
raise ValueError("Token not in vocabulary and no <unk> token in vocabulary for replacement.")
|
| 317 |
+
|
| 318 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 319 |
+
if os.path.isdir(save_directory):
|
| 320 |
+
vocab_file = os.path.join(
|
| 321 |
+
save_directory,
|
| 322 |
+
(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["pretrained_vocab_file"],
|
| 323 |
+
)
|
| 324 |
+
else:
|
| 325 |
+
vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
|
| 326 |
+
with open(vocab_file, "wb") as f:
|
| 327 |
+
pickle.dump(self.__dict__, f)
|
| 328 |
+
return (vocab_file,)
|
| 329 |
+
|
| 330 |
+
def build_vocab(self):
|
| 331 |
+
if self.vocab_file:
|
| 332 |
+
logger.info(f"building vocab from {self.vocab_file}")
|
| 333 |
+
self._build_from_file(self.vocab_file)
|
| 334 |
+
logger.info(f"Final vocab size {len(self.sym2idx)}")
|
| 335 |
+
else:
|
| 336 |
+
logger.info(f"building vocab with min_freq={self.min_freq}, max_size={self.max_size}")
|
| 337 |
+
self.idx2sym = []
|
| 338 |
+
self.sym2idx = OrderedDict()
|
| 339 |
+
|
| 340 |
+
for sym in self.special:
|
| 341 |
+
self.add_special(sym)
|
| 342 |
+
|
| 343 |
+
for sym, cnt in self.counter.most_common(self.max_size):
|
| 344 |
+
if cnt < self.min_freq:
|
| 345 |
+
break
|
| 346 |
+
self.add_symbol(sym)
|
| 347 |
+
|
| 348 |
+
logger.info(f"Final vocab size {len(self.sym2idx)} from {len(self.counter)} unique tokens")
|
| 349 |
+
|
| 350 |
+
@torch_only_method
|
| 351 |
+
def encode_file(self, path, ordered=False, verbose=False, add_eos=True, add_double_eos=False):
|
| 352 |
+
if verbose:
|
| 353 |
+
logger.info(f"encoding file {path} ...")
|
| 354 |
+
assert os.path.exists(path), f"Output file {path} not found"
|
| 355 |
+
encoded = []
|
| 356 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 357 |
+
for idx, line in enumerate(f):
|
| 358 |
+
if verbose and idx > 0 and idx % 500000 == 0:
|
| 359 |
+
logger.info(f" line {idx}")
|
| 360 |
+
symbols = self.tokenize(line, add_eos=add_eos, add_double_eos=add_double_eos)
|
| 361 |
+
encoded.append(self.convert_to_tensor(symbols))
|
| 362 |
+
|
| 363 |
+
if ordered:
|
| 364 |
+
encoded = torch.cat(encoded)
|
| 365 |
+
|
| 366 |
+
return encoded
|
| 367 |
+
|
| 368 |
+
@torch_only_method
|
| 369 |
+
def encode_sents(self, sents, ordered=False, verbose=False):
|
| 370 |
+
if verbose:
|
| 371 |
+
logger.info(f"encoding {len(sents)} sents ...")
|
| 372 |
+
encoded = []
|
| 373 |
+
for idx, symbols in enumerate(sents):
|
| 374 |
+
if verbose and idx > 0 and idx % 500000 == 0:
|
| 375 |
+
logger.info(f" line {idx}")
|
| 376 |
+
encoded.append(self.convert_to_tensor(symbols))
|
| 377 |
+
|
| 378 |
+
if ordered:
|
| 379 |
+
encoded = torch.cat(encoded)
|
| 380 |
+
|
| 381 |
+
return encoded
|
| 382 |
+
|
| 383 |
+
def add_special(self, sym):
|
| 384 |
+
if sym not in self.sym2idx:
|
| 385 |
+
self.idx2sym.append(sym)
|
| 386 |
+
self.sym2idx[sym] = len(self.idx2sym) - 1
|
| 387 |
+
setattr(self, f"{sym.strip('<>')}_idx", self.sym2idx[sym])
|
| 388 |
+
|
| 389 |
+
def add_symbol(self, sym):
|
| 390 |
+
if sym not in self.sym2idx:
|
| 391 |
+
self.idx2sym.append(sym)
|
| 392 |
+
self.sym2idx[sym] = len(self.idx2sym) - 1
|
| 393 |
+
|
| 394 |
+
def move_added_token(self, token: str, target_idx: int):
|
| 395 |
+
"""
|
| 396 |
+
Moves an added token to a specific position in the vocab. This method should be used when resizing an embedding
|
| 397 |
+
layer other than the last one in the `AdaptiveEmbedding` in order to move the token in the tokenizer from the
|
| 398 |
+
default position (at the very end) to the desired one.
|
| 399 |
+
|
| 400 |
+
Args:
|
| 401 |
+
token: The token to move to a specific position in the vocab.
|
| 402 |
+
target_idx: The position where the token should be moved to.
|
| 403 |
+
"""
|
| 404 |
+
assert token in self.added_tokens_encoder, "Token which should be moved has to be an added token"
|
| 405 |
+
assert token not in self.idx2sym, "Token which should be moved is already in vocab"
|
| 406 |
+
|
| 407 |
+
# Insert sym into vocab
|
| 408 |
+
self.idx2sym.insert(target_idx, token)
|
| 409 |
+
self.sym2idx[token] = target_idx
|
| 410 |
+
|
| 411 |
+
# Shift following indices in sym2idx
|
| 412 |
+
for idx in range(target_idx + 1, len(self.idx2sym)):
|
| 413 |
+
current_sym = self.idx2sym[idx]
|
| 414 |
+
self.sym2idx[current_sym] = idx
|
| 415 |
+
|
| 416 |
+
# Delete token from added_tokens
|
| 417 |
+
old_index = self._added_tokens_encoder.pop(token)
|
| 418 |
+
self._added_tokens_decoder.pop(old_index)
|
| 419 |
+
|
| 420 |
+
def moses_punct_norm(self, text):
|
| 421 |
+
return self.moses_punct_normalizer.normalize(text)
|
| 422 |
+
|
| 423 |
+
def moses_tokenize(self, text):
|
| 424 |
+
return self.moses_tokenizer.tokenize(
|
| 425 |
+
text, aggressive_dash_splits=True, return_str=False, escape=False, protected_patterns=self.never_split
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
def moses_pipeline(self, text: str) -> list[str]:
|
| 429 |
+
"""
|
| 430 |
+
Does basic tokenization using [`sacremoses.MosesPunctNormalizer`] and [`sacremoses.MosesTokenizer`] with
|
| 431 |
+
*aggressive_dash_splits=True* (see [`sacremoses.tokenize.MosesTokenizer.tokenize`]). Additionally, large
|
| 432 |
+
comma-separated numbers and floating point values are split. E.g. "23,000 people are 1.80m tall" -> "23 @,@ 000
|
| 433 |
+
people are 1 @.@ 80m tall"
|
| 434 |
+
|
| 435 |
+
Args:
|
| 436 |
+
text: Text to be tokenize
|
| 437 |
+
|
| 438 |
+
Returns:
|
| 439 |
+
A list of tokenized string
|
| 440 |
+
|
| 441 |
+
Example:
|
| 442 |
+
|
| 443 |
+
```python
|
| 444 |
+
>>> tokenizer = TransfoXLTokenizer.from_pretrained("transfo-xl/transfo-xl-wt103")
|
| 445 |
+
>>> tokenizer.moses_pipeline("23,000 people are 1.80 m tall")
|
| 446 |
+
['23', '@,@', '000', 'people', 'are', '1', '@.@', '80', 'm', 'tall']
|
| 447 |
+
```"""
|
| 448 |
+
text = self.moses_punct_norm(text)
|
| 449 |
+
text = self.moses_tokenize(text)
|
| 450 |
+
text = tokenize_numbers(text)
|
| 451 |
+
return text
|
| 452 |
+
|
| 453 |
+
def _convert_id_to_token(self, idx):
|
| 454 |
+
"""Converts an id in a token (BPE) using the vocab."""
|
| 455 |
+
assert 0 <= idx < len(self), f"Index {idx} out of vocabulary range"
|
| 456 |
+
return self.idx2sym[idx]
|
| 457 |
+
|
| 458 |
+
def _convert_token_to_id(self, sym):
|
| 459 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 460 |
+
if sym in self.sym2idx:
|
| 461 |
+
return self.sym2idx[sym]
|
| 462 |
+
else:
|
| 463 |
+
# logger.info(f'encounter unk {sym}')
|
| 464 |
+
# assert '<eos>' not in sym
|
| 465 |
+
if hasattr(self, "unk_idx"):
|
| 466 |
+
return self.sym2idx.get(sym, self.unk_idx)
|
| 467 |
+
# Backward compatibility with pre-trained models
|
| 468 |
+
elif "<unk>" in self.sym2idx:
|
| 469 |
+
return self.sym2idx["<unk>"]
|
| 470 |
+
elif "<UNK>" in self.sym2idx:
|
| 471 |
+
return self.sym2idx["<UNK>"]
|
| 472 |
+
else:
|
| 473 |
+
raise ValueError("Token not in vocabulary and no <unk> token in vocabulary for replacement.")
|
| 474 |
+
|
| 475 |
+
def convert_tokens_to_string(self, tokens):
|
| 476 |
+
"""
|
| 477 |
+
Converts a sequence of tokens (string) in a single string. Additionally, the split numbers are converted back
|
| 478 |
+
into it's original form.
|
| 479 |
+
"""
|
| 480 |
+
out_string = self.moses_detokenizer.detokenize(tokens)
|
| 481 |
+
return detokenize_numbers(out_string).strip()
|
| 482 |
+
|
| 483 |
+
@torch_only_method
|
| 484 |
+
def convert_to_tensor(self, symbols):
|
| 485 |
+
return torch.LongTensor(self.convert_tokens_to_ids(symbols))
|
| 486 |
+
|
| 487 |
+
@property
|
| 488 |
+
def vocab_size(self):
|
| 489 |
+
return len(self.idx2sym)
|
| 490 |
+
|
| 491 |
+
def get_vocab(self):
|
| 492 |
+
vocab = self.sym2idx.copy()
|
| 493 |
+
vocab.update(self.added_tokens_encoder)
|
| 494 |
+
return vocab
|
| 495 |
+
|
| 496 |
+
def _tokenize(self, line, add_eos=False, add_double_eos=False):
|
| 497 |
+
line = line.strip()
|
| 498 |
+
# convert to lower case
|
| 499 |
+
if self.lower_case:
|
| 500 |
+
line = line.lower()
|
| 501 |
+
|
| 502 |
+
# empty delimiter '' will evaluate False
|
| 503 |
+
if self.delimiter == "":
|
| 504 |
+
symbols = line
|
| 505 |
+
else:
|
| 506 |
+
symbols = self.moses_pipeline(line)
|
| 507 |
+
|
| 508 |
+
if add_double_eos: # lm1b
|
| 509 |
+
return ["<S>"] + symbols + ["<S>"]
|
| 510 |
+
elif add_eos:
|
| 511 |
+
return symbols + ["<eos>"]
|
| 512 |
+
else:
|
| 513 |
+
return symbols
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
class LMOrderedIterator:
|
| 517 |
+
def __init__(self, data, bsz, bptt, device="cpu", ext_len=None):
|
| 518 |
+
"""
|
| 519 |
+
data -- LongTensor -- the LongTensor is strictly ordered
|
| 520 |
+
"""
|
| 521 |
+
self.bsz = bsz
|
| 522 |
+
self.bptt = bptt
|
| 523 |
+
self.ext_len = ext_len if ext_len is not None else 0
|
| 524 |
+
|
| 525 |
+
self.device = device
|
| 526 |
+
|
| 527 |
+
# Work out how cleanly we can divide the dataset into bsz parts.
|
| 528 |
+
self.n_step = data.size(0) // bsz
|
| 529 |
+
|
| 530 |
+
# Trim off any extra elements that wouldn't cleanly fit (remainders).
|
| 531 |
+
data = data.narrow(0, 0, self.n_step * bsz)
|
| 532 |
+
|
| 533 |
+
# Evenly divide the data across the bsz batches.
|
| 534 |
+
self.data = data.view(bsz, -1).t().contiguous().to(device)
|
| 535 |
+
|
| 536 |
+
# Number of mini-batches
|
| 537 |
+
self.n_batch = (self.n_step + self.bptt - 1) // self.bptt
|
| 538 |
+
|
| 539 |
+
def get_batch(self, i, bptt=None):
|
| 540 |
+
if bptt is None:
|
| 541 |
+
bptt = self.bptt
|
| 542 |
+
seq_len = min(bptt, self.data.size(0) - 1 - i)
|
| 543 |
+
|
| 544 |
+
end_idx = i + seq_len
|
| 545 |
+
beg_idx = max(0, i - self.ext_len)
|
| 546 |
+
|
| 547 |
+
data = self.data[beg_idx:end_idx]
|
| 548 |
+
target = self.data[i + 1 : i + 1 + seq_len]
|
| 549 |
+
|
| 550 |
+
data_out = data.transpose(0, 1).contiguous().to(self.device)
|
| 551 |
+
target_out = target.transpose(0, 1).contiguous().to(self.device)
|
| 552 |
+
|
| 553 |
+
return data_out, target_out, seq_len
|
| 554 |
+
|
| 555 |
+
def get_fixlen_iter(self, start=0):
|
| 556 |
+
for i in range(start, self.data.size(0) - 1, self.bptt):
|
| 557 |
+
yield self.get_batch(i)
|
| 558 |
+
|
| 559 |
+
def get_varlen_iter(self, start=0, std=5, min_len=5, max_deviation=3):
|
| 560 |
+
max_len = self.bptt + max_deviation * std
|
| 561 |
+
i = start
|
| 562 |
+
while True:
|
| 563 |
+
bptt = self.bptt if np.random.random() < 0.95 else self.bptt / 2.0
|
| 564 |
+
bptt = min(max_len, max(min_len, int(np.random.normal(bptt, std))))
|
| 565 |
+
data, target, seq_len = self.get_batch(i, bptt)
|
| 566 |
+
i += seq_len
|
| 567 |
+
yield data, target, seq_len
|
| 568 |
+
if i >= self.data.size(0) - 2:
|
| 569 |
+
break
|
| 570 |
+
|
| 571 |
+
def __iter__(self):
|
| 572 |
+
return self.get_fixlen_iter()
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
class LMShuffledIterator:
|
| 576 |
+
def __init__(self, data, bsz, bptt, device="cpu", ext_len=None, shuffle=False):
|
| 577 |
+
"""
|
| 578 |
+
data -- list[LongTensor] -- there is no order among the LongTensors
|
| 579 |
+
"""
|
| 580 |
+
self.data = data
|
| 581 |
+
|
| 582 |
+
self.bsz = bsz
|
| 583 |
+
self.bptt = bptt
|
| 584 |
+
self.ext_len = ext_len if ext_len is not None else 0
|
| 585 |
+
|
| 586 |
+
self.device = device
|
| 587 |
+
self.shuffle = shuffle
|
| 588 |
+
|
| 589 |
+
def get_sent_stream(self):
|
| 590 |
+
# index iterator
|
| 591 |
+
epoch_indices = np.random.permutation(len(self.data)) if self.shuffle else np.array(range(len(self.data)))
|
| 592 |
+
|
| 593 |
+
# sentence iterator
|
| 594 |
+
for idx in epoch_indices:
|
| 595 |
+
yield self.data[idx]
|
| 596 |
+
|
| 597 |
+
@torch_only_method
|
| 598 |
+
def stream_iterator(self, sent_stream):
|
| 599 |
+
# streams for each data in the batch
|
| 600 |
+
streams = [None] * self.bsz
|
| 601 |
+
|
| 602 |
+
data = torch.LongTensor(self.bptt, self.bsz)
|
| 603 |
+
target = torch.LongTensor(self.bptt, self.bsz)
|
| 604 |
+
|
| 605 |
+
n_retain = 0
|
| 606 |
+
|
| 607 |
+
while True:
|
| 608 |
+
# data : [n_retain+bptt x bsz]
|
| 609 |
+
# target : [bptt x bsz]
|
| 610 |
+
data[n_retain:].fill_(-1)
|
| 611 |
+
target.fill_(-1)
|
| 612 |
+
|
| 613 |
+
valid_batch = True
|
| 614 |
+
|
| 615 |
+
for i in range(self.bsz):
|
| 616 |
+
n_filled = 0
|
| 617 |
+
try:
|
| 618 |
+
while n_filled < self.bptt:
|
| 619 |
+
if streams[i] is None or len(streams[i]) <= 1:
|
| 620 |
+
streams[i] = next(sent_stream)
|
| 621 |
+
# number of new tokens to fill in
|
| 622 |
+
n_new = min(len(streams[i]) - 1, self.bptt - n_filled)
|
| 623 |
+
# first n_retain tokens are retained from last batch
|
| 624 |
+
data[n_retain + n_filled : n_retain + n_filled + n_new, i] = streams[i][:n_new]
|
| 625 |
+
target[n_filled : n_filled + n_new, i] = streams[i][1 : n_new + 1]
|
| 626 |
+
streams[i] = streams[i][n_new:]
|
| 627 |
+
n_filled += n_new
|
| 628 |
+
except StopIteration:
|
| 629 |
+
valid_batch = False
|
| 630 |
+
break
|
| 631 |
+
|
| 632 |
+
if not valid_batch:
|
| 633 |
+
return
|
| 634 |
+
|
| 635 |
+
data_out = data.transpose(0, 1).contiguous().to(self.device)
|
| 636 |
+
target_out = target.transpose(0, 1).contiguous().to(self.device)
|
| 637 |
+
|
| 638 |
+
yield data_out, target_out, self.bptt
|
| 639 |
+
|
| 640 |
+
n_retain = min(data.size(0), self.ext_len)
|
| 641 |
+
if n_retain > 0:
|
| 642 |
+
data[:n_retain] = data[-n_retain:]
|
| 643 |
+
data.resize_(n_retain + self.bptt, data.size(1))
|
| 644 |
+
|
| 645 |
+
def __iter__(self):
|
| 646 |
+
# sent_stream is an iterator
|
| 647 |
+
sent_stream = self.get_sent_stream()
|
| 648 |
+
|
| 649 |
+
for batch in self.stream_iterator(sent_stream):
|
| 650 |
+
yield batch
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
class LMMultiFileIterator(LMShuffledIterator):
|
| 654 |
+
def __init__(self, paths, vocab, bsz, bptt, device="cpu", ext_len=None, shuffle=False):
|
| 655 |
+
self.paths = paths
|
| 656 |
+
self.vocab = vocab
|
| 657 |
+
|
| 658 |
+
self.bsz = bsz
|
| 659 |
+
self.bptt = bptt
|
| 660 |
+
self.ext_len = ext_len if ext_len is not None else 0
|
| 661 |
+
|
| 662 |
+
self.device = device
|
| 663 |
+
self.shuffle = shuffle
|
| 664 |
+
|
| 665 |
+
def get_sent_stream(self, path):
|
| 666 |
+
sents = self.vocab.encode_file(path, add_double_eos=True)
|
| 667 |
+
if self.shuffle:
|
| 668 |
+
np.random.shuffle(sents)
|
| 669 |
+
sent_stream = iter(sents)
|
| 670 |
+
|
| 671 |
+
return sent_stream
|
| 672 |
+
|
| 673 |
+
def __iter__(self):
|
| 674 |
+
if self.shuffle:
|
| 675 |
+
np.random.shuffle(self.paths)
|
| 676 |
+
|
| 677 |
+
for path in self.paths:
|
| 678 |
+
# sent_stream is an iterator
|
| 679 |
+
sent_stream = self.get_sent_stream(path)
|
| 680 |
+
for batch in self.stream_iterator(sent_stream):
|
| 681 |
+
yield batch
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
class TransfoXLCorpus:
|
| 685 |
+
@classmethod
|
| 686 |
+
@torch_only_method
|
| 687 |
+
def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs):
|
| 688 |
+
"""
|
| 689 |
+
Instantiate a pre-processed corpus.
|
| 690 |
+
"""
|
| 691 |
+
vocab = TransfoXLTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
|
| 692 |
+
is_local = os.path.isdir(pretrained_model_name_or_path)
|
| 693 |
+
# redirect to the cache, if necessary
|
| 694 |
+
try:
|
| 695 |
+
resolved_corpus_file = cached_file(pretrained_model_name_or_path, CORPUS_NAME, cache_dir=cache_dir)
|
| 696 |
+
except OSError:
|
| 697 |
+
logger.error(
|
| 698 |
+
f"Corpus '{pretrained_model_name_or_path}' was not found in corpus list"
|
| 699 |
+
f" ({', '.join(PRETRAINED_CORPUS_ARCHIVE_MAP.keys())}. We assumed '{pretrained_model_name_or_path}'"
|
| 700 |
+
f" was a path or url but couldn't find files {CORPUS_NAME} at this path or url."
|
| 701 |
+
)
|
| 702 |
+
return None
|
| 703 |
+
if is_local:
|
| 704 |
+
logger.info(f"loading corpus file {resolved_corpus_file}")
|
| 705 |
+
else:
|
| 706 |
+
logger.info(f"loading corpus file {CORPUS_NAME} from cache at {resolved_corpus_file}")
|
| 707 |
+
|
| 708 |
+
# Instantiate tokenizer.
|
| 709 |
+
corpus = cls(*inputs, **kwargs)
|
| 710 |
+
check_torch_load_is_safe()
|
| 711 |
+
corpus_dict = torch.load(resolved_corpus_file, weights_only=True)
|
| 712 |
+
for key, value in corpus_dict.items():
|
| 713 |
+
corpus.__dict__[key] = value
|
| 714 |
+
corpus.vocab = vocab
|
| 715 |
+
if corpus.train is not None:
|
| 716 |
+
corpus.train = torch.tensor(corpus.train, dtype=torch.long)
|
| 717 |
+
if corpus.valid is not None:
|
| 718 |
+
corpus.valid = torch.tensor(corpus.valid, dtype=torch.long)
|
| 719 |
+
if corpus.test is not None:
|
| 720 |
+
corpus.test = torch.tensor(corpus.test, dtype=torch.long)
|
| 721 |
+
return corpus
|
| 722 |
+
|
| 723 |
+
def __init__(self, *args, **kwargs):
|
| 724 |
+
self.vocab = TransfoXLTokenizer(*args, **kwargs)
|
| 725 |
+
self.dataset = None
|
| 726 |
+
self.train = None
|
| 727 |
+
self.valid = None
|
| 728 |
+
self.test = None
|
| 729 |
+
|
| 730 |
+
def build_corpus(self, path, dataset):
|
| 731 |
+
self.dataset = dataset
|
| 732 |
+
|
| 733 |
+
if self.dataset in ["ptb", "wt2", "enwik8", "text8"]:
|
| 734 |
+
self.vocab.count_file(os.path.join(path, "train.txt"))
|
| 735 |
+
self.vocab.count_file(os.path.join(path, "valid.txt"))
|
| 736 |
+
self.vocab.count_file(os.path.join(path, "test.txt"))
|
| 737 |
+
elif self.dataset == "wt103":
|
| 738 |
+
self.vocab.count_file(os.path.join(path, "train.txt"))
|
| 739 |
+
elif self.dataset == "lm1b":
|
| 740 |
+
train_path_pattern = os.path.join(
|
| 741 |
+
path,
|
| 742 |
+
"1-billion-word-language-modeling-benchmark-r13output",
|
| 743 |
+
"training-monolingual.tokenized.shuffled",
|
| 744 |
+
"news.en-*",
|
| 745 |
+
)
|
| 746 |
+
train_paths = glob.glob(train_path_pattern)
|
| 747 |
+
# the vocab will load from file when build_vocab() is called
|
| 748 |
+
|
| 749 |
+
self.vocab.build_vocab()
|
| 750 |
+
|
| 751 |
+
if self.dataset in ["ptb", "wt2", "wt103"]:
|
| 752 |
+
self.train = self.vocab.encode_file(os.path.join(path, "train.txt"), ordered=True)
|
| 753 |
+
self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=True)
|
| 754 |
+
self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=True)
|
| 755 |
+
elif self.dataset in ["enwik8", "text8"]:
|
| 756 |
+
self.train = self.vocab.encode_file(os.path.join(path, "train.txt"), ordered=True, add_eos=False)
|
| 757 |
+
self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=True, add_eos=False)
|
| 758 |
+
self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=True, add_eos=False)
|
| 759 |
+
elif self.dataset == "lm1b":
|
| 760 |
+
self.train = train_paths
|
| 761 |
+
self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=False, add_double_eos=True)
|
| 762 |
+
self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=False, add_double_eos=True)
|
| 763 |
+
|
| 764 |
+
def get_iterator(self, split, *args, **kwargs):
|
| 765 |
+
if split == "train":
|
| 766 |
+
if self.dataset in ["ptb", "wt2", "wt103", "enwik8", "text8"]:
|
| 767 |
+
data_iter = LMOrderedIterator(self.train, *args, **kwargs)
|
| 768 |
+
elif self.dataset == "lm1b":
|
| 769 |
+
kwargs["shuffle"] = True
|
| 770 |
+
data_iter = LMMultiFileIterator(self.train, self.vocab, *args, **kwargs)
|
| 771 |
+
elif split in ["valid", "test"]:
|
| 772 |
+
data = self.valid if split == "valid" else self.test
|
| 773 |
+
if self.dataset in ["ptb", "wt2", "wt103", "enwik8", "text8"]:
|
| 774 |
+
data_iter = LMOrderedIterator(data, *args, **kwargs)
|
| 775 |
+
elif self.dataset == "lm1b":
|
| 776 |
+
data_iter = LMShuffledIterator(data, *args, **kwargs)
|
| 777 |
+
else:
|
| 778 |
+
data_iter = None
|
| 779 |
+
raise ValueError(f"Split not recognized: {split}")
|
| 780 |
+
|
| 781 |
+
return data_iter
|
| 782 |
+
|
| 783 |
+
|
| 784 |
+
@torch_only_method
|
| 785 |
+
def get_lm_corpus(datadir, dataset):
|
| 786 |
+
fn = os.path.join(datadir, "cache.pt")
|
| 787 |
+
fn_pickle = os.path.join(datadir, "cache.pkl")
|
| 788 |
+
if os.path.exists(fn):
|
| 789 |
+
logger.info("Loading cached dataset...")
|
| 790 |
+
check_torch_load_is_safe()
|
| 791 |
+
corpus = torch.load(fn_pickle, weights_only=True)
|
| 792 |
+
elif os.path.exists(fn):
|
| 793 |
+
logger.info("Loading cached dataset from pickle...")
|
| 794 |
+
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
|
| 795 |
+
raise ValueError(
|
| 796 |
+
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
|
| 797 |
+
"malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
|
| 798 |
+
"that could have been tampered with. If you already verified the pickle data and decided to use it, "
|
| 799 |
+
"you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
|
| 800 |
+
)
|
| 801 |
+
with open(fn, "rb") as fp:
|
| 802 |
+
corpus = pickle.load(fp)
|
| 803 |
+
else:
|
| 804 |
+
logger.info(f"Producing dataset {dataset}...")
|
| 805 |
+
kwargs = {}
|
| 806 |
+
if dataset in ["wt103", "wt2"]:
|
| 807 |
+
kwargs["special"] = ["<eos>"]
|
| 808 |
+
kwargs["lower_case"] = False
|
| 809 |
+
elif dataset == "ptb":
|
| 810 |
+
kwargs["special"] = ["<eos>"]
|
| 811 |
+
kwargs["lower_case"] = True
|
| 812 |
+
elif dataset == "lm1b":
|
| 813 |
+
kwargs["special"] = []
|
| 814 |
+
kwargs["lower_case"] = False
|
| 815 |
+
kwargs["vocab_file"] = os.path.join(datadir, "1b_word_vocab.txt")
|
| 816 |
+
elif dataset in ["enwik8", "text8"]:
|
| 817 |
+
pass
|
| 818 |
+
|
| 819 |
+
corpus = TransfoXLCorpus(datadir, dataset, **kwargs)
|
| 820 |
+
torch.save(corpus, fn)
|
| 821 |
+
|
| 822 |
+
return corpus
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
__all__ = ["TransfoXLCorpus", "TransfoXLTokenizer"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa
|
| 2 |
+
# There's no way to ignore "F401 '...' imported but unused" warnings in this
|
| 3 |
+
# module, but to preserve other warnings. So, don't check this module at all.
|
| 4 |
+
from typing import TYPE_CHECKING
|
| 5 |
+
|
| 6 |
+
from ....utils import _LazyModule
|
| 7 |
+
from ....utils.import_utils import define_import_structure
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from .configuration_tvlt import *
|
| 12 |
+
from .feature_extraction_tvlt import *
|
| 13 |
+
from .processing_tvlt import *
|
| 14 |
+
from .modeling_tvlt import *
|
| 15 |
+
from .image_processing_tvlt import *
|
| 16 |
+
else:
|
| 17 |
+
import sys
|
| 18 |
+
|
| 19 |
+
_file = globals()["__file__"]
|
| 20 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/configuration_tvlt.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 MURGe-Lab and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""TVLT model configuration"""
|
| 16 |
+
|
| 17 |
+
from ....configuration_utils import PretrainedConfig
|
| 18 |
+
from ....utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class TvltConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`TvltModel`]. It is used to instantiate a TVLT
|
| 27 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 28 |
+
defaults will yield a similar configuration to that of the TVLT
|
| 29 |
+
[ZinengTang/tvlt-base](https://huggingface.co/ZinengTang/tvlt-base) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 36 |
+
The size (resolution) of each image.
|
| 37 |
+
spectrogram_length (`int`, *optional*, defaults to 2048):
|
| 38 |
+
The time length of each audio spectrogram.
|
| 39 |
+
frequency_length (`int`, *optional*, defaults to 128):
|
| 40 |
+
The frequency length of audio spectrogram.
|
| 41 |
+
image_patch_size (`list[int]`, *optional*, defaults to `[16, 16]`):
|
| 42 |
+
The size (resolution) of each image patch.
|
| 43 |
+
audio_patch_size (`list[int]`, *optional*, defaults to `[16, 16]`):
|
| 44 |
+
The size (resolution) of each audio patch.
|
| 45 |
+
num_image_channels (`int`, *optional*, defaults to 3):
|
| 46 |
+
The number of input image channels.
|
| 47 |
+
num_audio_channels (`int`, *optional*, defaults to 1):
|
| 48 |
+
The number of input audio channels.
|
| 49 |
+
num_frames (`int`, *optional*, defaults to 8):
|
| 50 |
+
The maximum number of frames for an input video.
|
| 51 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 52 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 53 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 54 |
+
Number of hidden layers in the Transformer encoder.
|
| 55 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 56 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 57 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 58 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 59 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 60 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 61 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 62 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 63 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 64 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 65 |
+
The dropout ratio for the attention probabilities.
|
| 66 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 67 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 68 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 69 |
+
The epsilon used by the layer normalization layers.
|
| 70 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 71 |
+
Whether to add a bias to the queries, keys and values.
|
| 72 |
+
use_mean_pooling (`bool`, *optional*, defaults to `False`):
|
| 73 |
+
Whether to mean pool the final hidden states instead of using the final hidden state of the [CLS] token.
|
| 74 |
+
decoder_num_attention_heads (`int`, *optional*, defaults to 16):
|
| 75 |
+
Number of attention heads for each attention layer in the decoder.
|
| 76 |
+
decoder_hidden_size (`int`, *optional*, defaults to 512):
|
| 77 |
+
Dimensionality of the decoder.
|
| 78 |
+
decoder_num_hidden_layers (`int`, *optional*, defaults to 8):
|
| 79 |
+
Number of hidden layers in the decoder.
|
| 80 |
+
decoder_intermediate_size (`int`, *optional*, defaults to 2048):
|
| 81 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder.
|
| 82 |
+
pixel_mask_ratio (`float`, *optional*, defaults to 0.75):
|
| 83 |
+
Image patch masking ratio.
|
| 84 |
+
audio_mask_ratio (`float`, *optional*, defaults to 0.15):
|
| 85 |
+
Audio patch masking ratio.
|
| 86 |
+
audio_mask_type (`str`, *optional*, defaults to `"frame-level"`):
|
| 87 |
+
Audio patch masking type, choose between "frame-level" and "patch-level".
|
| 88 |
+
task_matching (`bool`, *optional*, defaults to `True`):
|
| 89 |
+
Whether to use vision audio matching task in pretraining.
|
| 90 |
+
task_mae (`bool`, *optional*, defaults to `True`):
|
| 91 |
+
Whether to use the masked auto-encoder (MAE) in pretraining.
|
| 92 |
+
loss_type (`str`, *optional*, defaults to `"classification"`):
|
| 93 |
+
Loss types including regression and classification.
|
| 94 |
+
|
| 95 |
+
Example:
|
| 96 |
+
|
| 97 |
+
```python
|
| 98 |
+
>>> from transformers import TvltConfig, TvltModel
|
| 99 |
+
|
| 100 |
+
>>> # # Initializing a TVLT ZinengTang/tvlt-base style configuration
|
| 101 |
+
>>> configuration = TvltConfig()
|
| 102 |
+
|
| 103 |
+
>>> # # Initializing a model (with random weights) from the ZinengTang/tvlt-base style configuration
|
| 104 |
+
>>> model = TvltModel(configuration)
|
| 105 |
+
|
| 106 |
+
>>> # Accessing the model configuration
|
| 107 |
+
>>> configuration = model.config
|
| 108 |
+
```"""
|
| 109 |
+
|
| 110 |
+
model_type = "tvlt"
|
| 111 |
+
|
| 112 |
+
def __init__(
|
| 113 |
+
self,
|
| 114 |
+
image_size=224,
|
| 115 |
+
spectrogram_length=2048,
|
| 116 |
+
frequency_length=128,
|
| 117 |
+
image_patch_size=[16, 16],
|
| 118 |
+
audio_patch_size=[16, 16],
|
| 119 |
+
num_image_channels=3,
|
| 120 |
+
num_audio_channels=1,
|
| 121 |
+
num_frames=8,
|
| 122 |
+
hidden_size=768,
|
| 123 |
+
num_hidden_layers=12,
|
| 124 |
+
num_attention_heads=12,
|
| 125 |
+
intermediate_size=3072,
|
| 126 |
+
hidden_act="gelu",
|
| 127 |
+
hidden_dropout_prob=0.0,
|
| 128 |
+
attention_probs_dropout_prob=0.0,
|
| 129 |
+
initializer_range=0.02,
|
| 130 |
+
layer_norm_eps=1e-6,
|
| 131 |
+
qkv_bias=True,
|
| 132 |
+
use_mean_pooling=False,
|
| 133 |
+
decoder_num_attention_heads=16,
|
| 134 |
+
decoder_hidden_size=512,
|
| 135 |
+
decoder_num_hidden_layers=8,
|
| 136 |
+
decoder_intermediate_size=2048,
|
| 137 |
+
pixel_mask_ratio=0.75,
|
| 138 |
+
audio_mask_ratio=0.15,
|
| 139 |
+
audio_mask_type="frame-level",
|
| 140 |
+
task_matching=True,
|
| 141 |
+
task_mae=True,
|
| 142 |
+
loss_type="classification",
|
| 143 |
+
**kwargs,
|
| 144 |
+
):
|
| 145 |
+
super().__init__(**kwargs)
|
| 146 |
+
|
| 147 |
+
if audio_mask_type not in ("frame-level", "patch_level"):
|
| 148 |
+
raise ValueError(
|
| 149 |
+
"audio_mask_type must be one of two acceptable strategies - {'frame_level', 'patch-level') "
|
| 150 |
+
f"got {audio_mask_type}"
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
self.image_size = image_size
|
| 154 |
+
self.spectrogram_length = spectrogram_length
|
| 155 |
+
self.frequency_length = frequency_length
|
| 156 |
+
self.image_patch_size = image_patch_size
|
| 157 |
+
self.audio_patch_size = audio_patch_size
|
| 158 |
+
self.num_image_channels = num_image_channels
|
| 159 |
+
self.num_audio_channels = num_audio_channels
|
| 160 |
+
self.num_frames = num_frames
|
| 161 |
+
|
| 162 |
+
self.hidden_size = hidden_size
|
| 163 |
+
self.num_hidden_layers = num_hidden_layers
|
| 164 |
+
self.num_attention_heads = num_attention_heads
|
| 165 |
+
self.intermediate_size = intermediate_size
|
| 166 |
+
self.hidden_act = hidden_act
|
| 167 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 168 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 169 |
+
self.initializer_range = initializer_range
|
| 170 |
+
self.layer_norm_eps = layer_norm_eps
|
| 171 |
+
self.qkv_bias = qkv_bias
|
| 172 |
+
self.use_mean_pooling = use_mean_pooling
|
| 173 |
+
|
| 174 |
+
self.decoder_num_attention_heads = decoder_num_attention_heads
|
| 175 |
+
self.decoder_hidden_size = decoder_hidden_size
|
| 176 |
+
self.decoder_num_hidden_layers = decoder_num_hidden_layers
|
| 177 |
+
self.decoder_intermediate_size = decoder_intermediate_size
|
| 178 |
+
self.pixel_mask_ratio = pixel_mask_ratio
|
| 179 |
+
self.audio_mask_ratio = audio_mask_ratio
|
| 180 |
+
self.audio_mask_type = audio_mask_type
|
| 181 |
+
|
| 182 |
+
self.task_matching = task_matching
|
| 183 |
+
self.task_mae = task_mae
|
| 184 |
+
self.loss_type = loss_type
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
__all__ = ["TvltConfig"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/feature_extraction_tvlt.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Feature extractor class for TVLT."""
|
| 16 |
+
|
| 17 |
+
from math import ceil
|
| 18 |
+
from typing import Optional, Union
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from ....audio_utils import mel_filter_bank, spectrogram, window_function
|
| 23 |
+
from ....feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
|
| 24 |
+
from ....utils import TensorType, logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TvltFeatureExtractor(SequenceFeatureExtractor):
|
| 31 |
+
r"""
|
| 32 |
+
Constructs a TVLT audio feature extractor. This feature extractor can be used to prepare audios for the model.
|
| 33 |
+
|
| 34 |
+
This feature extractor inherits from [`FeatureExtractionMixin`] which contains most of the main methods. Users
|
| 35 |
+
should refer to this superclass for more information regarding those methods.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
spectrogram_length (`dict[str, int]` *optional*, defaults to 2048):
|
| 39 |
+
The time length of each audio spectrogram.
|
| 40 |
+
num_channels (`int` *optional*, defaults to 1):
|
| 41 |
+
Number of audio channels.
|
| 42 |
+
patch_size (`list[int]` *optional*, defaults to `[16, 16]`):
|
| 43 |
+
The patch size of audio patch embedding.
|
| 44 |
+
feature_size (`int`, *optional*, defaults to 128):
|
| 45 |
+
The frequency length of audio spectrogram.
|
| 46 |
+
sampling_rate (`int`, *optional*, defaults to 44100):
|
| 47 |
+
The sampling rate at which the audio files should be digitalized expressed in Hertz (Hz).
|
| 48 |
+
hop_length_to_sampling_rate (`int`, *optional*, defaults to 86):
|
| 49 |
+
Hop length is length of the overlapping windows for the STFT used to obtain the Mel Frequency coefficients.
|
| 50 |
+
For example, with sampling rate 44100, the hop length is 512, with 44100 / 512 = 86
|
| 51 |
+
n_fft (`int`, *optional*, defaults to 2048):
|
| 52 |
+
Size of the Fourier transform.
|
| 53 |
+
padding_value (`float`, *optional*, defaults to 0.0):
|
| 54 |
+
Padding value used to pad the audio. Should correspond to silences.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
model_input_names = ["audio_values", "audio_mask"]
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
spectrogram_length=2048,
|
| 62 |
+
num_channels=1,
|
| 63 |
+
patch_size=[16, 16],
|
| 64 |
+
feature_size=128,
|
| 65 |
+
sampling_rate=44100,
|
| 66 |
+
hop_length_to_sampling_rate=86,
|
| 67 |
+
n_fft=2048,
|
| 68 |
+
padding_value=0.0,
|
| 69 |
+
**kwargs,
|
| 70 |
+
):
|
| 71 |
+
super().__init__(
|
| 72 |
+
feature_size=feature_size,
|
| 73 |
+
sampling_rate=sampling_rate,
|
| 74 |
+
padding_value=padding_value,
|
| 75 |
+
**kwargs,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
self.spectrogram_length = spectrogram_length
|
| 79 |
+
self.num_channels = num_channels
|
| 80 |
+
self.patch_size = patch_size
|
| 81 |
+
self.freq_len = feature_size // self.patch_size[1]
|
| 82 |
+
self.n_fft = n_fft
|
| 83 |
+
self.hop_length = sampling_rate // hop_length_to_sampling_rate
|
| 84 |
+
self.sampling_rate = sampling_rate
|
| 85 |
+
self.padding_value = padding_value
|
| 86 |
+
self.mel_filters = mel_filter_bank(
|
| 87 |
+
num_frequency_bins=1 + n_fft // 2,
|
| 88 |
+
num_mel_filters=feature_size,
|
| 89 |
+
min_frequency=0.0,
|
| 90 |
+
max_frequency=22050.0,
|
| 91 |
+
sampling_rate=sampling_rate,
|
| 92 |
+
norm="slaney",
|
| 93 |
+
mel_scale="slaney",
|
| 94 |
+
).T
|
| 95 |
+
|
| 96 |
+
def _np_extract_fbank_features(self, waveform: np.ndarray) -> np.ndarray:
|
| 97 |
+
"""
|
| 98 |
+
Compute the log-mel spectrogram of the provided audio, gives similar results to Whisper's original torch
|
| 99 |
+
implementation with 1e-5 tolerance.
|
| 100 |
+
"""
|
| 101 |
+
log_spec = spectrogram(
|
| 102 |
+
waveform,
|
| 103 |
+
window_function(self.n_fft, "hann"),
|
| 104 |
+
frame_length=self.n_fft,
|
| 105 |
+
hop_length=self.hop_length,
|
| 106 |
+
power=2.0,
|
| 107 |
+
mel_filters=self.mel_filters.T,
|
| 108 |
+
log_mel="dB",
|
| 109 |
+
db_range=80.0,
|
| 110 |
+
)
|
| 111 |
+
log_spec = log_spec[:, :-1]
|
| 112 |
+
log_spec = log_spec - 20.0
|
| 113 |
+
log_spec = np.clip(log_spec / 40.0, -2.0, 0.0) + 1.0
|
| 114 |
+
return log_spec
|
| 115 |
+
|
| 116 |
+
def __call__(
|
| 117 |
+
self,
|
| 118 |
+
raw_speech: Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]],
|
| 119 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 120 |
+
return_attention_mask: Optional[bool] = True,
|
| 121 |
+
sampling_rate: Optional[int] = None,
|
| 122 |
+
resample: bool = False,
|
| 123 |
+
mask_audio: bool = False,
|
| 124 |
+
**kwargs,
|
| 125 |
+
) -> BatchFeature:
|
| 126 |
+
"""
|
| 127 |
+
Main method to prepare one or several audio(s) for the model.
|
| 128 |
+
|
| 129 |
+
Args:
|
| 130 |
+
raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
|
| 131 |
+
The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
|
| 132 |
+
values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
|
| 133 |
+
stereo, i.e. single float per timestep.
|
| 134 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 135 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 136 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 137 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 138 |
+
return_attention_mask (`bool`, *optional*, default to `True`):
|
| 139 |
+
Whether to return the attention mask. If left to the default, will return the attention mask according
|
| 140 |
+
to the specific feature_extractor's default. [What are attention masks?](../glossary#attention-mask)
|
| 141 |
+
|
| 142 |
+
<Tip>
|
| 143 |
+
|
| 144 |
+
For TvltTransformer models, `attention_mask` should always be passed for batched inference, to avoid
|
| 145 |
+
subtle bugs.
|
| 146 |
+
|
| 147 |
+
</Tip>
|
| 148 |
+
|
| 149 |
+
sampling_rate (`int`, *optional*):
|
| 150 |
+
The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
|
| 151 |
+
`sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
|
| 152 |
+
pipeline. Current model supports sampling rate 16000 and 44100.
|
| 153 |
+
resample (`bool`, *optional*, defaults to `False`):
|
| 154 |
+
If the sampling rate is not matched, resample the input audio to match.
|
| 155 |
+
mask_audio (`bool`, *optional*, defaults to `False`):
|
| 156 |
+
Whether or not to mask input audio for MAE task.
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 160 |
+
|
| 161 |
+
- **audio_values** -- Audio values to be fed to a model, of shape (batch_size, num_channels, height,
|
| 162 |
+
width).
|
| 163 |
+
|
| 164 |
+
- **audio_mask** -- Audio masks to be fed to a model, of shape (batch_size, num_audio_patches).
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
if sampling_rate is not None:
|
| 168 |
+
if sampling_rate != self.sampling_rate:
|
| 169 |
+
raise ValueError(
|
| 170 |
+
"This feature extractor is set to support sampling rate"
|
| 171 |
+
f" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled"
|
| 172 |
+
f" with {self.sampling_rate} and not {sampling_rate}."
|
| 173 |
+
)
|
| 174 |
+
else:
|
| 175 |
+
logger.warning(
|
| 176 |
+
"It is strongly recommended to pass the `sampling_rate` argument to this function. "
|
| 177 |
+
"Failing to do so can result in silent errors that might be hard to debug."
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
|
| 181 |
+
if is_batched_numpy and len(raw_speech.shape) > 2:
|
| 182 |
+
raise ValueError(f"Only mono-channel audio is supported for input to {self}")
|
| 183 |
+
is_batched = is_batched_numpy or (
|
| 184 |
+
isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
|
| 185 |
+
)
|
| 186 |
+
if is_batched:
|
| 187 |
+
raw_speech = [np.asarray([speech], dtype=np.float32).T for speech in raw_speech]
|
| 188 |
+
elif not is_batched and not isinstance(raw_speech, np.ndarray):
|
| 189 |
+
raw_speech = np.asarray(raw_speech, dtype=np.float32)
|
| 190 |
+
elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
|
| 191 |
+
raw_speech = raw_speech.astype(np.float32)
|
| 192 |
+
# always return batch
|
| 193 |
+
if not is_batched:
|
| 194 |
+
raw_speech = [np.asarray([raw_speech]).T]
|
| 195 |
+
|
| 196 |
+
# Convert audio signals to log mel spectrograms, truncate by time axis
|
| 197 |
+
audio_features = [
|
| 198 |
+
self._np_extract_fbank_features(waveform.squeeze()).T[: self.spectrogram_length] for waveform in raw_speech
|
| 199 |
+
]
|
| 200 |
+
if isinstance(audio_features[0], list):
|
| 201 |
+
audio_features = [np.asarray(feature, dtype=np.float32) for feature in audio_features]
|
| 202 |
+
|
| 203 |
+
# Create audio attention mask
|
| 204 |
+
max_patch_len = max(
|
| 205 |
+
ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len for feature in audio_features
|
| 206 |
+
) # The maximum number of audio patches in a batch
|
| 207 |
+
if return_attention_mask:
|
| 208 |
+
audio_mask = [
|
| 209 |
+
(ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [1]
|
| 210 |
+
+ (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [0]
|
| 211 |
+
for feature in audio_features
|
| 212 |
+
]
|
| 213 |
+
audio_mask = np.array(audio_mask).astype(np.float32)
|
| 214 |
+
|
| 215 |
+
# convert into correct format for padding
|
| 216 |
+
max_time_len = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch
|
| 217 |
+
padded_audio_features = np.ones([len(audio_features), 1, max_time_len, self.feature_size]).astype(np.float32)
|
| 218 |
+
padded_audio_features = padded_audio_features * self.padding_value
|
| 219 |
+
for i in range(len(audio_features)):
|
| 220 |
+
feature = audio_features[i]
|
| 221 |
+
padded_audio_features[i, :, : feature.shape[0], :] = feature
|
| 222 |
+
|
| 223 |
+
# return as BatchFeature
|
| 224 |
+
if return_attention_mask:
|
| 225 |
+
data = {"audio_values": padded_audio_features, "audio_mask": audio_mask}
|
| 226 |
+
else:
|
| 227 |
+
data = {"audio_values": padded_audio_features}
|
| 228 |
+
|
| 229 |
+
encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
|
| 230 |
+
return encoded_inputs
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
__all__ = ["TvltFeatureExtractor"]
|
miniconda3/envs/active_proaction/lib/python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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Image processor class for TVLT."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ....image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 22 |
+
from ....image_transforms import (
|
| 23 |
+
get_resize_output_image_size,
|
| 24 |
+
resize,
|
| 25 |
+
to_channel_dimension_format,
|
| 26 |
+
)
|
| 27 |
+
from ....image_utils import (
|
| 28 |
+
IMAGENET_STANDARD_MEAN,
|
| 29 |
+
IMAGENET_STANDARD_STD,
|
| 30 |
+
ChannelDimension,
|
| 31 |
+
ImageInput,
|
| 32 |
+
PILImageResampling,
|
| 33 |
+
infer_channel_dimension_format,
|
| 34 |
+
is_scaled_image,
|
| 35 |
+
is_valid_image,
|
| 36 |
+
to_numpy_array,
|
| 37 |
+
valid_images,
|
| 38 |
+
validate_kwargs,
|
| 39 |
+
validate_preprocess_arguments,
|
| 40 |
+
)
|
| 41 |
+
from ....utils import TensorType, logging
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def make_batched(videos) -> list[list[ImageInput]]:
|
| 48 |
+
if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)):
|
| 49 |
+
return videos
|
| 50 |
+
|
| 51 |
+
elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
|
| 52 |
+
videos_dim = np.array(videos[0]).ndim
|
| 53 |
+
if videos_dim == 3:
|
| 54 |
+
return [videos]
|
| 55 |
+
elif videos_dim == 4:
|
| 56 |
+
return videos
|
| 57 |
+
|
| 58 |
+
elif is_valid_image(videos):
|
| 59 |
+
videos_dim = np.array(videos).ndim
|
| 60 |
+
if videos_dim == 3:
|
| 61 |
+
return [[videos]]
|
| 62 |
+
elif videos_dim == 4:
|
| 63 |
+
return [videos]
|
| 64 |
+
elif videos_dim == 5:
|
| 65 |
+
return videos
|
| 66 |
+
|
| 67 |
+
raise ValueError(f"Could not make batched video from {videos}")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class TvltImageProcessor(BaseImageProcessor):
|
| 71 |
+
r"""
|
| 72 |
+
Constructs a TVLT image processor.
|
| 73 |
+
|
| 74 |
+
This processor can be used to prepare either videos or images for the model by converting images to 1-frame videos.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 78 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
|
| 79 |
+
`do_resize` parameter in the `preprocess` method.
|
| 80 |
+
size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
|
| 81 |
+
Size of the output image after resizing. The shortest edge of the image will be resized to
|
| 82 |
+
`size["shortest_edge"]` while maintaining the aspect ratio of the original image. Can be overridden by
|
| 83 |
+
`size` in the `preprocess` method.
|
| 84 |
+
patch_size (`list[int]` *optional*, defaults to [16,16]):
|
| 85 |
+
The patch size of image patch embedding.
|
| 86 |
+
num_frames (`int` *optional*, defaults to 8):
|
| 87 |
+
The maximum number of video frames.
|
| 88 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
|
| 89 |
+
Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
|
| 90 |
+
`preprocess` method.
|
| 91 |
+
do_center_crop (`bool`, *optional*, defaults to `True`):
|
| 92 |
+
Whether to center crop the image to the specified `crop_size`. Can be overridden by the `do_center_crop`
|
| 93 |
+
parameter in the `preprocess` method.
|
| 94 |
+
crop_size (`dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
|
| 95 |
+
Size of the image after applying the center crop. Can be overridden by the `crop_size` parameter in the
|
| 96 |
+
`preprocess` method.
|
| 97 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 98 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
|
| 99 |
+
parameter in the `preprocess` method.
|
| 100 |
+
rescale_factor (`int` or `float`, *optional*, defaults to 1/255):
|
| 101 |
+
Defines the scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter
|
| 102 |
+
in the `preprocess` method.
|
| 103 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 104 |
+
Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
|
| 105 |
+
method.
|
| 106 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
| 107 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 108 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 109 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
| 110 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 111 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
model_input_names = [
|
| 115 |
+
"pixel_values",
|
| 116 |
+
"pixel_mask",
|
| 117 |
+
"pixel_values_mixed",
|
| 118 |
+
"pixel_mask_mixed",
|
| 119 |
+
]
|
| 120 |
+
|
| 121 |
+
def __init__(
|
| 122 |
+
self,
|
| 123 |
+
do_resize: bool = True,
|
| 124 |
+
size: Optional[dict[str, int]] = None,
|
| 125 |
+
patch_size: list[int] = [16, 16],
|
| 126 |
+
num_frames: int = 8,
|
| 127 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 128 |
+
do_center_crop: bool = True,
|
| 129 |
+
crop_size: Optional[dict[str, int]] = None,
|
| 130 |
+
do_rescale: bool = True,
|
| 131 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 132 |
+
do_normalize: bool = True,
|
| 133 |
+
image_mean: Optional[Union[float, list[float]]] = IMAGENET_STANDARD_MEAN,
|
| 134 |
+
image_std: Optional[Union[float, list[float]]] = IMAGENET_STANDARD_STD,
|
| 135 |
+
init_mask_generator=False,
|
| 136 |
+
**kwargs,
|
| 137 |
+
) -> None:
|
| 138 |
+
super().__init__(**kwargs)
|
| 139 |
+
size = size if size is not None else {"shortest_edge": 224}
|
| 140 |
+
size = get_size_dict(size, default_to_square=False)
|
| 141 |
+
crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
|
| 142 |
+
crop_size = get_size_dict(crop_size, param_name="crop_size")
|
| 143 |
+
|
| 144 |
+
self.do_resize = do_resize
|
| 145 |
+
self.size = size
|
| 146 |
+
self.patch_size = patch_size
|
| 147 |
+
self.num_frames = num_frames
|
| 148 |
+
self.do_center_crop = do_center_crop
|
| 149 |
+
self.crop_size = crop_size
|
| 150 |
+
self.resample = resample
|
| 151 |
+
self.do_rescale = do_rescale
|
| 152 |
+
self.rescale_factor = rescale_factor
|
| 153 |
+
self.do_normalize = do_normalize
|
| 154 |
+
self.image_mean = image_mean
|
| 155 |
+
self.image_std = image_std
|
| 156 |
+
self._valid_processor_keys = [
|
| 157 |
+
"videos",
|
| 158 |
+
"do_resize",
|
| 159 |
+
"size",
|
| 160 |
+
"patch_size",
|
| 161 |
+
"num_frames",
|
| 162 |
+
"resample",
|
| 163 |
+
"do_center_crop",
|
| 164 |
+
"crop_size",
|
| 165 |
+
"do_rescale",
|
| 166 |
+
"rescale_factor",
|
| 167 |
+
"do_normalize",
|
| 168 |
+
"image_mean",
|
| 169 |
+
"image_std",
|
| 170 |
+
"is_mixed",
|
| 171 |
+
"return_tensors",
|
| 172 |
+
"data_format",
|
| 173 |
+
"input_data_format",
|
| 174 |
+
]
|
| 175 |
+
|
| 176 |
+
def resize(
|
| 177 |
+
self,
|
| 178 |
+
image: np.ndarray,
|
| 179 |
+
size: dict[str, int],
|
| 180 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 181 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 182 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 183 |
+
**kwargs,
|
| 184 |
+
) -> np.ndarray:
|
| 185 |
+
"""
|
| 186 |
+
Resize an image.
|
| 187 |
+
|
| 188 |
+
Args:
|
| 189 |
+
image (`np.ndarray`):
|
| 190 |
+
Image to resize.
|
| 191 |
+
size (`dict[str, int]`):
|
| 192 |
+
Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will
|
| 193 |
+
have the size `(h, w)`. If `size` is of the form `{"shortest_edge": s}`, the output image will have its
|
| 194 |
+
shortest edge of length `s` while keeping the aspect ratio of the original image.
|
| 195 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
|
| 196 |
+
Resampling filter to use when resiizing the image.
|
| 197 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 198 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 199 |
+
input_data_format (`str` or `ChannelDimension`, *optional*):
|
| 200 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 201 |
+
"""
|
| 202 |
+
size = get_size_dict(size, default_to_square=False)
|
| 203 |
+
if "shortest_edge" in size:
|
| 204 |
+
output_size = get_resize_output_image_size(
|
| 205 |
+
image, size["shortest_edge"], default_to_square=False, input_data_format=input_data_format
|
| 206 |
+
)
|
| 207 |
+
elif "height" in size and "width" in size:
|
| 208 |
+
output_size = (size["height"], size["width"])
|
| 209 |
+
else:
|
| 210 |
+
raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}")
|
| 211 |
+
return resize(
|
| 212 |
+
image,
|
| 213 |
+
size=output_size,
|
| 214 |
+
resample=resample,
|
| 215 |
+
data_format=data_format,
|
| 216 |
+
input_data_format=input_data_format,
|
| 217 |
+
**kwargs,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
def _preprocess_image(
|
| 221 |
+
self,
|
| 222 |
+
image: ImageInput,
|
| 223 |
+
do_resize: Optional[bool] = None,
|
| 224 |
+
size: Optional[dict[str, int]] = None,
|
| 225 |
+
resample: Optional[PILImageResampling] = None,
|
| 226 |
+
do_center_crop: Optional[bool] = None,
|
| 227 |
+
crop_size: Optional[dict[str, int]] = None,
|
| 228 |
+
do_rescale: Optional[bool] = None,
|
| 229 |
+
rescale_factor: Optional[float] = None,
|
| 230 |
+
do_normalize: Optional[bool] = None,
|
| 231 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 232 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 233 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 234 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 235 |
+
) -> np.ndarray:
|
| 236 |
+
"""Preprocesses a single image."""
|
| 237 |
+
|
| 238 |
+
validate_preprocess_arguments(
|
| 239 |
+
do_rescale=do_rescale,
|
| 240 |
+
rescale_factor=rescale_factor,
|
| 241 |
+
do_normalize=do_normalize,
|
| 242 |
+
image_mean=image_mean,
|
| 243 |
+
image_std=image_std,
|
| 244 |
+
do_center_crop=do_center_crop,
|
| 245 |
+
crop_size=crop_size,
|
| 246 |
+
do_resize=do_resize,
|
| 247 |
+
size=size,
|
| 248 |
+
resample=resample,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
# All transformations expect numpy arrays.
|
| 252 |
+
image = to_numpy_array(image)
|
| 253 |
+
|
| 254 |
+
if do_rescale and is_scaled_image(image):
|
| 255 |
+
logger.warning_once(
|
| 256 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 257 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
if input_data_format is None:
|
| 261 |
+
input_data_format = infer_channel_dimension_format(image)
|
| 262 |
+
|
| 263 |
+
if do_resize:
|
| 264 |
+
image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
| 265 |
+
|
| 266 |
+
if do_center_crop:
|
| 267 |
+
image = self.center_crop(image, size=crop_size, input_data_format=input_data_format)
|
| 268 |
+
|
| 269 |
+
if do_rescale:
|
| 270 |
+
image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 271 |
+
|
| 272 |
+
if do_normalize:
|
| 273 |
+
image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 274 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 275 |
+
return image
|
| 276 |
+
|
| 277 |
+
def preprocess(
|
| 278 |
+
self,
|
| 279 |
+
videos: ImageInput,
|
| 280 |
+
do_resize: Optional[bool] = None,
|
| 281 |
+
size: Optional[dict[str, int]] = None,
|
| 282 |
+
patch_size: Optional[list[int]] = None,
|
| 283 |
+
num_frames: Optional[int] = None,
|
| 284 |
+
resample: Optional[PILImageResampling] = None,
|
| 285 |
+
do_center_crop: Optional[bool] = None,
|
| 286 |
+
crop_size: Optional[dict[str, int]] = None,
|
| 287 |
+
do_rescale: Optional[bool] = None,
|
| 288 |
+
rescale_factor: Optional[float] = None,
|
| 289 |
+
do_normalize: Optional[bool] = None,
|
| 290 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 291 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 292 |
+
is_mixed: bool = False,
|
| 293 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 294 |
+
data_format: ChannelDimension = ChannelDimension.FIRST,
|
| 295 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 296 |
+
**kwargs,
|
| 297 |
+
) -> BatchFeature:
|
| 298 |
+
"""
|
| 299 |
+
Preprocess an videos or image or batch of videos or images.
|
| 300 |
+
|
| 301 |
+
Args:
|
| 302 |
+
videos (`ImageInput`):
|
| 303 |
+
Images or videos to preprocess. Expects a single or batch of frames with pixel values ranging from 0 to
|
| 304 |
+
255. If passing in frames with pixel values between 0 and 1, set `do_rescale=False`.
|
| 305 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 306 |
+
Whether to resize the image.
|
| 307 |
+
size (`dict[str, int]`, *optional*, defaults to `self.size`):
|
| 308 |
+
Size of the image after applying resize.
|
| 309 |
+
patch_size (`list[int]` *optional*, defaults to self.patch_size):
|
| 310 |
+
The patch size of image patch embedding.
|
| 311 |
+
num_frames (`int` *optional*, defaults to self.num_frames):
|
| 312 |
+
The maximum number of video frames.
|
| 313 |
+
resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
|
| 314 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
|
| 315 |
+
has an effect if `do_resize` is set to `True`.
|
| 316 |
+
do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):
|
| 317 |
+
Whether to centre crop the image.
|
| 318 |
+
crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
|
| 319 |
+
Size of the image after applying the centre crop.
|
| 320 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 321 |
+
Whether to rescale the image values between [0 - 1].
|
| 322 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 323 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 324 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 325 |
+
Whether to normalize the image.
|
| 326 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
|
| 327 |
+
Image mean.
|
| 328 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
|
| 329 |
+
Image standard deviation.
|
| 330 |
+
is_mixed (`bool`, *optional*):
|
| 331 |
+
If the input video has negative samples.
|
| 332 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 333 |
+
The type of tensors to return. Can be one of:
|
| 334 |
+
- Unset: Return a list of `np.ndarray`.
|
| 335 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 336 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 337 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 338 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 339 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 340 |
+
The channel dimension format for the output image. Can be one of:
|
| 341 |
+
- `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 342 |
+
- `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 343 |
+
- Unset: Use the inferred channel dimension format of the input image.
|
| 344 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 345 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 346 |
+
from the input image. Can be one of:
|
| 347 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 348 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 349 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 350 |
+
|
| 351 |
+
Returns:
|
| 352 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 353 |
+
|
| 354 |
+
- **pixel_values** -- Pixel values to be fed to a model, of shape (batch_size, num_channels, height,
|
| 355 |
+
width).
|
| 356 |
+
|
| 357 |
+
- **pixel_mask** -- Pixel masks to be fed to a model, of shape (batch_size, num_pixel_patches).
|
| 358 |
+
|
| 359 |
+
- **pixel_values_mixed** -- Pixel values with both positive or negative to be fed to a model, of shape
|
| 360 |
+
(batch_size, num_channels, height, width).
|
| 361 |
+
|
| 362 |
+
- **pixel_mask_mixed** -- Pixel masks with both positive or negative to be fed to a model, of shape
|
| 363 |
+
(batch_size, num_pixel_patches).
|
| 364 |
+
"""
|
| 365 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 366 |
+
resample = resample if resample is not None else self.resample
|
| 367 |
+
do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
|
| 368 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 369 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 370 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 371 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 372 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 373 |
+
|
| 374 |
+
size = size if size is not None else self.size
|
| 375 |
+
size = get_size_dict(size, default_to_square=False)
|
| 376 |
+
crop_size = crop_size if crop_size is not None else self.crop_size
|
| 377 |
+
crop_size = get_size_dict(crop_size, param_name="crop_size")
|
| 378 |
+
patch_size = patch_size if patch_size is not None else self.patch_size
|
| 379 |
+
num_frames = num_frames if patch_size is not None else self.num_frames
|
| 380 |
+
|
| 381 |
+
validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
|
| 382 |
+
|
| 383 |
+
if not valid_images(videos):
|
| 384 |
+
raise ValueError(
|
| 385 |
+
"Invalid image or video type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 386 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
videos = make_batched(videos)
|
| 390 |
+
|
| 391 |
+
# Check number of frames is fewer than maximum frames
|
| 392 |
+
for video in videos:
|
| 393 |
+
if len(video) > self.num_frames:
|
| 394 |
+
raise ValueError(
|
| 395 |
+
f"number of frames must not be greater than the maximum frames of the model {self.num_frames}."
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
max_num_frames = max(len(video) for video in videos)
|
| 399 |
+
num_patches_per_image = (size["shortest_edge"] // patch_size[0]) ** 2
|
| 400 |
+
video_masks = np.array(
|
| 401 |
+
[
|
| 402 |
+
len(video) * num_patches_per_image * [1] + (max_num_frames - len(video)) * num_patches_per_image * [0]
|
| 403 |
+
for video in videos
|
| 404 |
+
]
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
videos = [
|
| 408 |
+
[
|
| 409 |
+
self._preprocess_image(
|
| 410 |
+
image=img,
|
| 411 |
+
do_resize=do_resize,
|
| 412 |
+
size=size,
|
| 413 |
+
resample=resample,
|
| 414 |
+
do_center_crop=do_center_crop,
|
| 415 |
+
crop_size=crop_size,
|
| 416 |
+
do_rescale=do_rescale,
|
| 417 |
+
rescale_factor=rescale_factor,
|
| 418 |
+
do_normalize=do_normalize,
|
| 419 |
+
image_mean=image_mean,
|
| 420 |
+
image_std=image_std,
|
| 421 |
+
data_format=data_format,
|
| 422 |
+
input_data_format=input_data_format,
|
| 423 |
+
)
|
| 424 |
+
for img in video
|
| 425 |
+
]
|
| 426 |
+
for video in videos
|
| 427 |
+
]
|
| 428 |
+
|
| 429 |
+
# If videos contain both positive/negative, use mixed key for video-audio matching task
|
| 430 |
+
if is_mixed:
|
| 431 |
+
data = {"pixel_values_mixed": videos, "pixel_mask_mixed": video_masks}
|
| 432 |
+
else:
|
| 433 |
+
data = {"pixel_values": videos, "pixel_mask": video_masks}
|
| 434 |
+
|
| 435 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
__all__ = ["TvltImageProcessor"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/modeling_tvlt.py
ADDED
|
@@ -0,0 +1,1274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 MURGe-Lab and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch TVLT model."""
|
| 16 |
+
|
| 17 |
+
import collections.abc
|
| 18 |
+
import math
|
| 19 |
+
from copy import deepcopy
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from typing import Optional, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from torch import nn
|
| 25 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 26 |
+
|
| 27 |
+
from ....activations import ACT2FN
|
| 28 |
+
from ....modeling_layers import GradientCheckpointingLayer
|
| 29 |
+
from ....modeling_outputs import BaseModelOutput, SequenceClassifierOutput
|
| 30 |
+
from ....modeling_utils import PreTrainedModel
|
| 31 |
+
from ....pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
|
| 32 |
+
from ....utils import (
|
| 33 |
+
ModelOutput,
|
| 34 |
+
add_start_docstrings,
|
| 35 |
+
add_start_docstrings_to_model_forward,
|
| 36 |
+
logging,
|
| 37 |
+
replace_return_docstrings,
|
| 38 |
+
)
|
| 39 |
+
from .configuration_tvlt import TvltConfig
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
_CONFIG_FOR_DOC = "TvltConfig"
|
| 45 |
+
_CHECKPOINT_FOR_DOC = "ZinengTang/tvlt-base"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@dataclass
|
| 49 |
+
class TvltModelOutput(ModelOutput):
|
| 50 |
+
"""
|
| 51 |
+
Class for TvltModel's outputs, with potential hidden states and attentions.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 55 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 56 |
+
last_pixel_hidden_state (`torch.FloatTensor` of shape `(batch_size, pixel_sequence_length, hidden_size)`):
|
| 57 |
+
Pixel sequence of hidden-states at the output of the last layer of the model.
|
| 58 |
+
last_audio_hidden_state (`torch.FloatTensor` of shape `(batch_size, audio_sequence_length, hidden_size)`):
|
| 59 |
+
Audio sequence of hidden-states at the output of the last layer of the model.
|
| 60 |
+
pixel_label_masks (`torch.FloatTensor` of shape `(batch_size, pixel_patch_length)`):
|
| 61 |
+
Tensor indicating which pixel patches are masked (1) and which are not (0).
|
| 62 |
+
audio_label_masks (`torch.FloatTensor` of shape `(batch_size, audio_patch_length)`):
|
| 63 |
+
Tensor indicating which audio patches are masked (1) and which are not (0).
|
| 64 |
+
pixel_ids_restore (`torch.LongTensor` of shape `(batch_size, pixel_patch_length)`):
|
| 65 |
+
Tensor containing the ids permutation of pixel masking.
|
| 66 |
+
audio_ids_restore (`torch.LongTensor` of shape `(batch_size, audio_patch_length)`):
|
| 67 |
+
Tensor containing the ids permutation of audio masking.
|
| 68 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 69 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
|
| 70 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 71 |
+
plus the initial embedding outputs.
|
| 72 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 73 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 74 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 75 |
+
the self-attention heads.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 79 |
+
last_pixel_hidden_state: Optional[torch.FloatTensor] = None
|
| 80 |
+
last_audio_hidden_state: Optional[torch.FloatTensor] = None
|
| 81 |
+
pixel_label_masks: Optional[torch.LongTensor] = None
|
| 82 |
+
audio_label_masks: Optional[torch.LongTensor] = None
|
| 83 |
+
pixel_ids_restore: Optional[torch.LongTensor] = None
|
| 84 |
+
audio_ids_restore: Optional[torch.LongTensor] = None
|
| 85 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 86 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@dataclass
|
| 90 |
+
class TvltDecoderOutput(ModelOutput):
|
| 91 |
+
"""
|
| 92 |
+
Class for TvltDecoder's outputs, with potential hidden states and attentions.
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
logits (`torch.FloatTensor` of shape `(batch_size, patch_size ** 2 * num_channels)`):
|
| 96 |
+
Pixel reconstruction logits.
|
| 97 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 98 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
|
| 99 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 100 |
+
plus the initial embedding outputs.
|
| 101 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 102 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 103 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 104 |
+
the self-attention heads.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
logits: Optional[torch.FloatTensor] = None
|
| 108 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 109 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@dataclass
|
| 113 |
+
class TvltForPreTrainingOutput(ModelOutput):
|
| 114 |
+
"""
|
| 115 |
+
Class for TvltForPreTraining's outputs, with potential hidden states and attentions.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
loss (`torch.FloatTensor` of shape `(1,)`):
|
| 119 |
+
Pixel reconstruction loss.
|
| 120 |
+
matching_logits (`torch.FloatTensor` of shape `(batch_size, 1)`):
|
| 121 |
+
Matching objective logits.
|
| 122 |
+
pixel_logits (`torch.FloatTensor` of shape
|
| 123 |
+
`(batch_size, pixel_patch_length, image_patch_size ** 3 * pixel_num_channels)`): Pixel reconstruction
|
| 124 |
+
logits.
|
| 125 |
+
audio_logits (`torch.FloatTensor` of shape
|
| 126 |
+
`(batch_size, audio_patch_length, image_patch_size[0] * image_patch_size[1])`): Audio reconstruction
|
| 127 |
+
logits.
|
| 128 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 129 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
|
| 130 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 131 |
+
plus the initial embedding outputs.
|
| 132 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 133 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 134 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 135 |
+
the self-attention heads.
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
loss: Optional[torch.FloatTensor] = None
|
| 139 |
+
matching_logits: Optional[torch.FloatTensor] = None
|
| 140 |
+
pixel_logits: Optional[torch.FloatTensor] = None
|
| 141 |
+
audio_logits: Optional[torch.FloatTensor] = None
|
| 142 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 143 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def generate_pixel_mask_noise(pixel_values, pixel_mask=None, mask_ratio=0.75):
|
| 147 |
+
"""Generate noise for audio masking."""
|
| 148 |
+
|
| 149 |
+
batch_size, seq_len = pixel_values.shape[:2]
|
| 150 |
+
noise = torch.rand((batch_size, seq_len), device=pixel_values.device) # noise in [0, 1]
|
| 151 |
+
len_keep = int(seq_len * (1 - mask_ratio))
|
| 152 |
+
return noise, len_keep
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def generate_audio_mask_noise(audio_values, audio_mask=None, mask_ratio=0.75, mask_type="patch-level", freq_len=8):
|
| 156 |
+
"""Generate noise for audio masking."""
|
| 157 |
+
|
| 158 |
+
batch_size, seq_len = audio_values.shape[:2]
|
| 159 |
+
if mask_type == "frame-level":
|
| 160 |
+
num_time_patches = seq_len // freq_len
|
| 161 |
+
noise = (
|
| 162 |
+
torch.rand(batch_size, num_time_patches, device=audio_values.device)
|
| 163 |
+
.unsqueeze(-1)
|
| 164 |
+
.repeat(1, 1, freq_len)
|
| 165 |
+
.view(batch_size, seq_len)
|
| 166 |
+
) # noise in [0, 1]
|
| 167 |
+
elif mask_type == "patch-level":
|
| 168 |
+
noise = torch.rand(batch_size, seq_len, device=audio_values.device) # noise in [0, 1]
|
| 169 |
+
len_keep = int(seq_len * (1 - mask_ratio))
|
| 170 |
+
return noise, len_keep
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def random_masking(sequence, noise, len_keep, attention_masks=None):
|
| 174 |
+
"""
|
| 175 |
+
Perform random masking by per-sample shuffling on frame-level. Per-sample shuffling is done by argsort random
|
| 176 |
+
noise. sequence: [batch_size, seq_len, hidden_dim], sequence
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
batch_size, seq_len, hidden_dim = sequence.shape
|
| 180 |
+
|
| 181 |
+
# sort noise for each sample
|
| 182 |
+
ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove
|
| 183 |
+
ids_restore = torch.argsort(ids_shuffle, dim=1)
|
| 184 |
+
|
| 185 |
+
# keep the first subset
|
| 186 |
+
ids_keep = ids_shuffle[:, :len_keep]
|
| 187 |
+
sequence_masked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, hidden_dim))
|
| 188 |
+
|
| 189 |
+
# generate the binary mask: 0 is keep, 1 is remove
|
| 190 |
+
label_masks = torch.ones([batch_size, seq_len], device=sequence.device)
|
| 191 |
+
label_masks[:, :len_keep] = 0
|
| 192 |
+
# unshuffle to get the binary mask
|
| 193 |
+
label_masks = torch.gather(label_masks, dim=1, index=ids_restore)
|
| 194 |
+
|
| 195 |
+
if attention_masks is not None:
|
| 196 |
+
label_masks *= attention_masks
|
| 197 |
+
attention_masks = torch.gather(attention_masks, dim=1, index=ids_keep)
|
| 198 |
+
|
| 199 |
+
return sequence_masked, attention_masks, label_masks, ids_restore
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class TvltPixelEmbeddings(nn.Module):
|
| 203 |
+
"""Construct the patch and position embeddings."""
|
| 204 |
+
|
| 205 |
+
def __init__(self, config):
|
| 206 |
+
super().__init__()
|
| 207 |
+
|
| 208 |
+
self.patch_embeddings = TvltPixelPatchEmbeddings(config)
|
| 209 |
+
self.num_patches_per_image = self.patch_embeddings.num_patches_per_image
|
| 210 |
+
|
| 211 |
+
self.type_embed_v = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 212 |
+
self.temporal_embed = nn.Parameter(torch.zeros(1, config.num_frames, config.hidden_size))
|
| 213 |
+
self.pos_embed_v = nn.Parameter(torch.zeros(1, self.num_patches_per_image, config.hidden_size))
|
| 214 |
+
|
| 215 |
+
self.config = config
|
| 216 |
+
|
| 217 |
+
def forward(self, pixel_values, attention_masks=None):
|
| 218 |
+
# create patch embeddings
|
| 219 |
+
batch_size, num_frames, num_channels, height, width = pixel_values.shape
|
| 220 |
+
|
| 221 |
+
embeddings = self.patch_embeddings(pixel_values)
|
| 222 |
+
embeddings += self.pos_embed_v.repeat(1, num_frames, 1)
|
| 223 |
+
embeddings += torch.repeat_interleave(self.temporal_embed[:, :num_frames], self.num_patches_per_image, dim=1)
|
| 224 |
+
embeddings += self.type_embed_v
|
| 225 |
+
|
| 226 |
+
return embeddings, attention_masks
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class TvltAudioEmbeddings(nn.Module):
|
| 230 |
+
"""Construct the patch and position embeddings."""
|
| 231 |
+
|
| 232 |
+
def __init__(self, config):
|
| 233 |
+
super().__init__()
|
| 234 |
+
|
| 235 |
+
self.patch_embeddings = TvltAudioPatchEmbeddings(config)
|
| 236 |
+
self.num_patches = self.patch_embeddings.num_patches
|
| 237 |
+
|
| 238 |
+
self.type_embed_a = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 239 |
+
self.num_freq_patches = config.frequency_length // config.audio_patch_size[1]
|
| 240 |
+
self.pos_embed_a = nn.Parameter(torch.zeros(1, self.num_patches // self.num_freq_patches, config.hidden_size))
|
| 241 |
+
self.freq_embed = nn.Parameter(torch.zeros(1, self.num_freq_patches, config.hidden_size))
|
| 242 |
+
|
| 243 |
+
self.num_freq_patches = config.frequency_length // config.audio_patch_size[1]
|
| 244 |
+
self.config = config
|
| 245 |
+
|
| 246 |
+
def forward(self, audio_values, attention_masks=None):
|
| 247 |
+
# create patch embeddings
|
| 248 |
+
embeddings = self.patch_embeddings(audio_values)
|
| 249 |
+
|
| 250 |
+
num_time_patches = embeddings.size(1) // self.num_freq_patches
|
| 251 |
+
embeddings += self.freq_embed.repeat(1, num_time_patches, 1)
|
| 252 |
+
embeddings += torch.repeat_interleave(self.pos_embed_a[:, :num_time_patches], self.num_freq_patches, dim=1)
|
| 253 |
+
embeddings += self.type_embed_a
|
| 254 |
+
|
| 255 |
+
return embeddings, attention_masks
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class TvltPixelPatchEmbeddings(nn.Module):
|
| 259 |
+
"""
|
| 260 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 261 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 262 |
+
Transformer.
|
| 263 |
+
"""
|
| 264 |
+
|
| 265 |
+
def __init__(self, config):
|
| 266 |
+
super().__init__()
|
| 267 |
+
image_size, patch_size = config.image_size, config.image_patch_size
|
| 268 |
+
num_channels, hidden_size = config.num_image_channels, config.hidden_size
|
| 269 |
+
|
| 270 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 271 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 272 |
+
num_patches_per_image = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 273 |
+
self.image_size = image_size
|
| 274 |
+
self.patch_size = patch_size
|
| 275 |
+
self.num_channels = num_channels
|
| 276 |
+
self.num_patches_per_image = num_patches_per_image
|
| 277 |
+
self.hidden_size = hidden_size
|
| 278 |
+
|
| 279 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 280 |
+
|
| 281 |
+
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
|
| 282 |
+
batch_size, num_frames, num_channels, height, width = pixel_values.shape
|
| 283 |
+
if num_channels != self.num_channels:
|
| 284 |
+
raise ValueError(
|
| 285 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 286 |
+
)
|
| 287 |
+
if height != self.image_size[0] or width != self.image_size[1]:
|
| 288 |
+
raise ValueError(
|
| 289 |
+
f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
pixel_values = pixel_values.reshape(batch_size * num_frames, num_channels, height, width)
|
| 293 |
+
embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
|
| 294 |
+
embeddings = embeddings.reshape(batch_size, num_frames * self.num_patches_per_image, self.hidden_size)
|
| 295 |
+
|
| 296 |
+
return embeddings
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class TvltAudioPatchEmbeddings(nn.Module):
|
| 300 |
+
"""
|
| 301 |
+
This class turns `audio_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 302 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 303 |
+
Transformer.
|
| 304 |
+
"""
|
| 305 |
+
|
| 306 |
+
def __init__(self, config):
|
| 307 |
+
super().__init__()
|
| 308 |
+
spectrogram_length, frequency_length, patch_size = (
|
| 309 |
+
config.spectrogram_length,
|
| 310 |
+
config.frequency_length,
|
| 311 |
+
config.audio_patch_size,
|
| 312 |
+
)
|
| 313 |
+
num_channels, hidden_size = config.num_audio_channels, config.hidden_size
|
| 314 |
+
|
| 315 |
+
spectrogram_size = (spectrogram_length, frequency_length)
|
| 316 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 317 |
+
num_patches = (spectrogram_size[1] // patch_size[1]) * (spectrogram_size[0] // patch_size[0])
|
| 318 |
+
patch_shape = (spectrogram_size[0] // patch_size[0], spectrogram_size[1] // patch_size[1])
|
| 319 |
+
self.spectrogram_size = spectrogram_size
|
| 320 |
+
self.patch_size = patch_size
|
| 321 |
+
self.num_channels = num_channels
|
| 322 |
+
self.num_patches = num_patches
|
| 323 |
+
self.patch_shape = patch_shape
|
| 324 |
+
|
| 325 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 326 |
+
|
| 327 |
+
def forward(self, audio_values: torch.Tensor) -> torch.Tensor:
|
| 328 |
+
batch_size, num_channels, height, width = audio_values.shape
|
| 329 |
+
if num_channels != self.num_channels:
|
| 330 |
+
raise ValueError(
|
| 331 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 332 |
+
)
|
| 333 |
+
if height > self.spectrogram_size[0] or width != self.spectrogram_size[1]:
|
| 334 |
+
raise ValueError(
|
| 335 |
+
f"Input audio size ({height}*{width}) doesn't match model"
|
| 336 |
+
f" ({self.spectrogram_size[0]}*{self.spectrogram_size[1]})."
|
| 337 |
+
)
|
| 338 |
+
embeddings = self.projection(audio_values).flatten(2).transpose(1, 2)
|
| 339 |
+
|
| 340 |
+
return embeddings
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class TvltSelfAttention(nn.Module):
|
| 344 |
+
def __init__(self, config):
|
| 345 |
+
super().__init__()
|
| 346 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 347 |
+
raise ValueError(
|
| 348 |
+
f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
|
| 349 |
+
f"heads {config.num_attention_heads}."
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
self.num_attention_heads = config.num_attention_heads
|
| 353 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 354 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 355 |
+
|
| 356 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 357 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 358 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 359 |
+
|
| 360 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 361 |
+
|
| 362 |
+
def transpose_for_scores(self, x):
|
| 363 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 364 |
+
x = x.view(*new_x_shape)
|
| 365 |
+
return x.permute(0, 2, 1, 3)
|
| 366 |
+
|
| 367 |
+
def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
|
| 368 |
+
mixed_query_layer = self.query(hidden_states)
|
| 369 |
+
|
| 370 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 371 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 372 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 373 |
+
|
| 374 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 375 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 376 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 377 |
+
if attention_mask is not None:
|
| 378 |
+
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
|
| 379 |
+
attention_scores = attention_scores + attention_mask
|
| 380 |
+
|
| 381 |
+
# Normalize the attention scores to probabilities.
|
| 382 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
| 383 |
+
|
| 384 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 385 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 386 |
+
attention_probs = self.dropout(attention_probs)
|
| 387 |
+
|
| 388 |
+
# Mask heads if we want to
|
| 389 |
+
if head_mask is not None:
|
| 390 |
+
attention_probs = attention_probs * head_mask
|
| 391 |
+
|
| 392 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 393 |
+
|
| 394 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 395 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 396 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
| 397 |
+
|
| 398 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 399 |
+
|
| 400 |
+
return outputs
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
class TvltSelfOutput(nn.Module):
|
| 404 |
+
"""
|
| 405 |
+
The residual connection is defined in TvltLayer instead of here (as is the case with other models), due to the
|
| 406 |
+
layernorm applied before each block.
|
| 407 |
+
"""
|
| 408 |
+
|
| 409 |
+
def __init__(self, config: TvltConfig) -> None:
|
| 410 |
+
super().__init__()
|
| 411 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 412 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 413 |
+
|
| 414 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 415 |
+
hidden_states = self.dense(hidden_states)
|
| 416 |
+
hidden_states = self.dropout(hidden_states)
|
| 417 |
+
|
| 418 |
+
return hidden_states
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class TvltAttention(nn.Module):
|
| 422 |
+
def __init__(self, config):
|
| 423 |
+
super().__init__()
|
| 424 |
+
self.attention = TvltSelfAttention(config)
|
| 425 |
+
self.output = TvltSelfOutput(config)
|
| 426 |
+
self.pruned_heads = set()
|
| 427 |
+
|
| 428 |
+
def prune_heads(self, heads):
|
| 429 |
+
if len(heads) == 0:
|
| 430 |
+
return
|
| 431 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 432 |
+
heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# Prune linear layers
|
| 436 |
+
self.attention.query = prune_linear_layer(self.attention.query, index)
|
| 437 |
+
self.attention.key = prune_linear_layer(self.attention.key, index)
|
| 438 |
+
self.attention.value = prune_linear_layer(self.attention.value, index)
|
| 439 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 440 |
+
|
| 441 |
+
# Update hyper params and store pruned heads
|
| 442 |
+
self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
|
| 443 |
+
self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
|
| 444 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 445 |
+
|
| 446 |
+
def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
|
| 447 |
+
self_outputs = self.attention(hidden_states, attention_mask, head_mask, output_attentions)
|
| 448 |
+
|
| 449 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 450 |
+
|
| 451 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 452 |
+
return outputs
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
class TvltIntermediate(nn.Module):
|
| 456 |
+
def __init__(self, config: TvltConfig) -> None:
|
| 457 |
+
super().__init__()
|
| 458 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 459 |
+
if isinstance(config.hidden_act, str):
|
| 460 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 461 |
+
else:
|
| 462 |
+
self.intermediate_act_fn = config.hidden_act
|
| 463 |
+
|
| 464 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 465 |
+
hidden_states = self.dense(hidden_states)
|
| 466 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 467 |
+
|
| 468 |
+
return hidden_states
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
class TvltOutput(nn.Module):
|
| 472 |
+
def __init__(self, config: TvltConfig) -> None:
|
| 473 |
+
super().__init__()
|
| 474 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 475 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 476 |
+
|
| 477 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 478 |
+
hidden_states = self.dense(hidden_states)
|
| 479 |
+
hidden_states = self.dropout(hidden_states)
|
| 480 |
+
|
| 481 |
+
hidden_states = hidden_states + input_tensor
|
| 482 |
+
|
| 483 |
+
return hidden_states
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
class TvltLayer(GradientCheckpointingLayer):
|
| 487 |
+
"""This corresponds to the Block class in the timm implementation."""
|
| 488 |
+
|
| 489 |
+
def __init__(self, config):
|
| 490 |
+
super().__init__()
|
| 491 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 492 |
+
self.seq_len_dim = 1
|
| 493 |
+
self.attention = TvltAttention(config)
|
| 494 |
+
self.intermediate = TvltIntermediate(config)
|
| 495 |
+
self.output = TvltOutput(config)
|
| 496 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 497 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 498 |
+
|
| 499 |
+
def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
|
| 500 |
+
self_attention_outputs = self.attention(
|
| 501 |
+
self.layernorm_before(hidden_states), # in ViLT, layernorm is applied before self-attention
|
| 502 |
+
attention_mask,
|
| 503 |
+
head_mask,
|
| 504 |
+
output_attentions=output_attentions,
|
| 505 |
+
)
|
| 506 |
+
attention_output = self_attention_outputs[0]
|
| 507 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 508 |
+
|
| 509 |
+
# first residual connection
|
| 510 |
+
hidden_states = attention_output + hidden_states.to(attention_output.device)
|
| 511 |
+
|
| 512 |
+
# in ViLT, layernorm is also applied after self-attention
|
| 513 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 514 |
+
layer_output = self.intermediate(layer_output)
|
| 515 |
+
|
| 516 |
+
# second residual connection is done here
|
| 517 |
+
layer_output = self.output(layer_output, hidden_states)
|
| 518 |
+
|
| 519 |
+
outputs = (layer_output,) + outputs
|
| 520 |
+
|
| 521 |
+
return outputs
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
class TvltEncoder(nn.Module):
|
| 525 |
+
def __init__(self, config):
|
| 526 |
+
super().__init__()
|
| 527 |
+
self.config = config
|
| 528 |
+
self.layer = nn.ModuleList([TvltLayer(config) for _ in range(config.num_hidden_layers)])
|
| 529 |
+
self.gradient_checkpointing = False
|
| 530 |
+
|
| 531 |
+
def forward(
|
| 532 |
+
self,
|
| 533 |
+
hidden_states,
|
| 534 |
+
attention_mask=None,
|
| 535 |
+
head_mask=None,
|
| 536 |
+
output_attentions=False,
|
| 537 |
+
output_hidden_states=False,
|
| 538 |
+
return_dict=True,
|
| 539 |
+
):
|
| 540 |
+
all_hidden_states = () if output_hidden_states else None
|
| 541 |
+
all_self_attentions = () if output_attentions else None
|
| 542 |
+
|
| 543 |
+
for i, layer_module in enumerate(self.layer):
|
| 544 |
+
if output_hidden_states:
|
| 545 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 546 |
+
|
| 547 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 548 |
+
|
| 549 |
+
layer_outputs = layer_module(hidden_states, attention_mask, layer_head_mask, output_attentions)
|
| 550 |
+
|
| 551 |
+
hidden_states = layer_outputs[0]
|
| 552 |
+
|
| 553 |
+
if output_attentions:
|
| 554 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 555 |
+
|
| 556 |
+
if output_hidden_states:
|
| 557 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 558 |
+
|
| 559 |
+
if not return_dict:
|
| 560 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
| 561 |
+
return BaseModelOutput(
|
| 562 |
+
last_hidden_state=hidden_states,
|
| 563 |
+
hidden_states=all_hidden_states,
|
| 564 |
+
attentions=all_self_attentions,
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
class TvltPreTrainedModel(PreTrainedModel):
|
| 569 |
+
"""
|
| 570 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 571 |
+
models.
|
| 572 |
+
"""
|
| 573 |
+
|
| 574 |
+
config: TvltConfig
|
| 575 |
+
base_model_prefix = "tvlt"
|
| 576 |
+
main_input_name = "pixel_values"
|
| 577 |
+
supports_gradient_checkpointing = True
|
| 578 |
+
|
| 579 |
+
def _init_weights(self, module):
|
| 580 |
+
"""Initialize the weights"""
|
| 581 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 582 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 583 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 584 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 585 |
+
if module.bias is not None:
|
| 586 |
+
module.bias.data.zero_()
|
| 587 |
+
elif isinstance(module, nn.LayerNorm):
|
| 588 |
+
module.bias.data.zero_()
|
| 589 |
+
module.weight.data.fill_(1.0)
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
TVLT_START_DOCSTRING = r"""
|
| 593 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 594 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 595 |
+
behavior.
|
| 596 |
+
|
| 597 |
+
Parameters:
|
| 598 |
+
config ([`TvltConfig`]): Model configuration class with all the parameters of the model.
|
| 599 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 600 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 601 |
+
"""
|
| 602 |
+
|
| 603 |
+
TVLT_INPUTS_DOCSTRING = r"""
|
| 604 |
+
Args:
|
| 605 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
|
| 606 |
+
Pixel values. Pixel values can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
|
| 607 |
+
details.
|
| 608 |
+
|
| 609 |
+
audio_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 610 |
+
Audio values. Audio values can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
|
| 611 |
+
details.
|
| 612 |
+
|
| 613 |
+
pixel_mask (`torch.FloatTensor` of shape `(batch_size, num_pixel_patches)`):
|
| 614 |
+
Pixel masks. Pixel masks can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
|
| 615 |
+
details.
|
| 616 |
+
|
| 617 |
+
audio_mask (`torch.FloatTensor` of shape `(batch_size, num_audio_patches)`):
|
| 618 |
+
Audio masks. Audio masks can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
|
| 619 |
+
details.
|
| 620 |
+
|
| 621 |
+
pixel_values_mixed (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
|
| 622 |
+
Pixel values that mix positive and negative samples in Tvlt vision-audio matching. Pixel values mixed can
|
| 623 |
+
be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for details.
|
| 624 |
+
|
| 625 |
+
pixel_mask_mixed (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 626 |
+
Pixel masks of pixel_values_mixed. Pixel masks mixed can be obtained using [`TvltProcessor`]. See
|
| 627 |
+
[`TvltProcessor.__call__`] for details.
|
| 628 |
+
|
| 629 |
+
mask_pixel (`bool`, *optional*):
|
| 630 |
+
Whether to mask pixel for MAE tasks. Only set to True in TvltForPreTraining.
|
| 631 |
+
|
| 632 |
+
mask_audio (`bool`, *optional*):
|
| 633 |
+
Whether to mask audio for MAE tasks. Only set to True in TvltForPreTraining.
|
| 634 |
+
|
| 635 |
+
output_attentions (`bool`, *optional*):
|
| 636 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 637 |
+
tensors for more detail.
|
| 638 |
+
|
| 639 |
+
output_hidden_states (`bool`, *optional*):
|
| 640 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 641 |
+
more detail.
|
| 642 |
+
|
| 643 |
+
return_dict (`bool`, *optional*):
|
| 644 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 645 |
+
"""
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
@add_start_docstrings(
|
| 649 |
+
"The bare TVLT Model transformer outputting raw hidden-states without any specific head on top.",
|
| 650 |
+
TVLT_START_DOCSTRING,
|
| 651 |
+
)
|
| 652 |
+
class TvltModel(TvltPreTrainedModel):
|
| 653 |
+
def __init__(self, config):
|
| 654 |
+
super().__init__(config)
|
| 655 |
+
self.config = config
|
| 656 |
+
|
| 657 |
+
self.pixel_embeddings = TvltPixelEmbeddings(config)
|
| 658 |
+
self.audio_embeddings = TvltAudioEmbeddings(config)
|
| 659 |
+
self.encoder = TvltEncoder(config)
|
| 660 |
+
|
| 661 |
+
self.cls_embedding = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 662 |
+
|
| 663 |
+
if config.use_mean_pooling:
|
| 664 |
+
self.layernorm = None
|
| 665 |
+
else:
|
| 666 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 667 |
+
|
| 668 |
+
# Initialize weights and apply final processing
|
| 669 |
+
self.post_init()
|
| 670 |
+
|
| 671 |
+
def get_input_embeddings(self):
|
| 672 |
+
return self.pixel_embeddings.patch_embeddings, self.audio_embeddings.patch_embeddings
|
| 673 |
+
|
| 674 |
+
def _prune_heads(self, heads_to_prune):
|
| 675 |
+
"""
|
| 676 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 677 |
+
class PreTrainedModel
|
| 678 |
+
"""
|
| 679 |
+
for layer, heads in heads_to_prune.items():
|
| 680 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 681 |
+
|
| 682 |
+
@add_start_docstrings_to_model_forward(TVLT_INPUTS_DOCSTRING)
|
| 683 |
+
@replace_return_docstrings(output_type=TvltModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 684 |
+
def forward(
|
| 685 |
+
self,
|
| 686 |
+
pixel_values: torch.FloatTensor,
|
| 687 |
+
audio_values: torch.FloatTensor,
|
| 688 |
+
pixel_mask: Optional[torch.FloatTensor] = None,
|
| 689 |
+
audio_mask: Optional[torch.FloatTensor] = None,
|
| 690 |
+
mask_pixel: bool = False,
|
| 691 |
+
mask_audio: bool = False,
|
| 692 |
+
output_attentions: Optional[bool] = None,
|
| 693 |
+
output_hidden_states: Optional[bool] = None,
|
| 694 |
+
return_dict: Optional[bool] = None,
|
| 695 |
+
) -> Union[tuple[torch.FloatTensor], TvltModelOutput]:
|
| 696 |
+
r"""
|
| 697 |
+
Returns:
|
| 698 |
+
|
| 699 |
+
Examples:
|
| 700 |
+
|
| 701 |
+
```python
|
| 702 |
+
>>> from transformers import TvltProcessor, TvltModel
|
| 703 |
+
>>> import numpy as np
|
| 704 |
+
>>> import torch
|
| 705 |
+
|
| 706 |
+
>>> num_frames = 8
|
| 707 |
+
>>> images = list(np.random.randn(num_frames, 3, 224, 224))
|
| 708 |
+
>>> audio = list(np.random.randn(10000))
|
| 709 |
+
|
| 710 |
+
>>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
|
| 711 |
+
>>> model = TvltModel.from_pretrained("ZinengTang/tvlt-base")
|
| 712 |
+
|
| 713 |
+
>>> input_dict = processor(images, audio, sampling_rate=44100, return_tensors="pt")
|
| 714 |
+
|
| 715 |
+
>>> outputs = model(**input_dict)
|
| 716 |
+
>>> loss = outputs.loss
|
| 717 |
+
```"""
|
| 718 |
+
|
| 719 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 720 |
+
output_hidden_states = (
|
| 721 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 722 |
+
)
|
| 723 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 724 |
+
|
| 725 |
+
pixel_embedding_output, pixel_mask = self.pixel_embeddings(pixel_values, pixel_mask)
|
| 726 |
+
|
| 727 |
+
audio_embedding_output, audio_mask = self.audio_embeddings(audio_values, audio_mask)
|
| 728 |
+
|
| 729 |
+
# Mask pixel if mask_pixel is True
|
| 730 |
+
pixel_label_masks = None
|
| 731 |
+
pixel_ids_restore = None
|
| 732 |
+
if mask_pixel:
|
| 733 |
+
pixel_mask_noise, pixel_len_keep = generate_pixel_mask_noise(
|
| 734 |
+
pixel_embedding_output, pixel_mask=pixel_mask, mask_ratio=self.config.pixel_mask_ratio
|
| 735 |
+
)
|
| 736 |
+
pixel_embedding_output, pixel_mask, pixel_label_masks, pixel_ids_restore = random_masking(
|
| 737 |
+
pixel_embedding_output,
|
| 738 |
+
pixel_mask_noise,
|
| 739 |
+
pixel_len_keep,
|
| 740 |
+
attention_masks=pixel_mask,
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
# Mask audio if mask_audio is True
|
| 744 |
+
audio_label_masks = None
|
| 745 |
+
audio_ids_restore = None
|
| 746 |
+
if mask_audio:
|
| 747 |
+
num_freq_patches = self.config.frequency_length // self.config.audio_patch_size[1]
|
| 748 |
+
audio_mask_noise, audio_len_keep = generate_audio_mask_noise(
|
| 749 |
+
audio_embedding_output,
|
| 750 |
+
audio_mask=audio_mask,
|
| 751 |
+
mask_ratio=self.config.audio_mask_ratio,
|
| 752 |
+
mask_type=self.config.audio_mask_type,
|
| 753 |
+
freq_len=num_freq_patches,
|
| 754 |
+
)
|
| 755 |
+
audio_embedding_output, audio_mask, audio_label_masks, audio_ids_restore = random_masking(
|
| 756 |
+
audio_embedding_output,
|
| 757 |
+
audio_mask_noise,
|
| 758 |
+
audio_len_keep,
|
| 759 |
+
attention_masks=audio_mask,
|
| 760 |
+
)
|
| 761 |
+
|
| 762 |
+
# Prepare for encoder inputs and attention masks
|
| 763 |
+
batch_size = pixel_values.size(0)
|
| 764 |
+
embedding_output = torch.cat(
|
| 765 |
+
[self.cls_embedding.repeat(batch_size, 1, 1), pixel_embedding_output, audio_embedding_output], 1
|
| 766 |
+
)
|
| 767 |
+
masked_pixel_len = pixel_embedding_output.size(1)
|
| 768 |
+
|
| 769 |
+
attention_mask = None
|
| 770 |
+
if pixel_mask is not None and audio_mask is not None:
|
| 771 |
+
attention_mask = torch.cat([pixel_mask[:, :1], pixel_mask, audio_mask], 1)
|
| 772 |
+
|
| 773 |
+
input_shape = embedding_output.size()
|
| 774 |
+
extended_attention_mask = None
|
| 775 |
+
if attention_mask is not None:
|
| 776 |
+
extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 777 |
+
|
| 778 |
+
encoder_outputs = self.encoder(
|
| 779 |
+
embedding_output,
|
| 780 |
+
attention_mask=extended_attention_mask,
|
| 781 |
+
output_attentions=output_attentions,
|
| 782 |
+
output_hidden_states=output_hidden_states,
|
| 783 |
+
return_dict=return_dict,
|
| 784 |
+
)
|
| 785 |
+
sequence_output = encoder_outputs[0]
|
| 786 |
+
if self.layernorm is not None:
|
| 787 |
+
sequence_output = self.layernorm(sequence_output)
|
| 788 |
+
|
| 789 |
+
pixel_sequence_output = sequence_output[:, 1 : 1 + masked_pixel_len]
|
| 790 |
+
audio_sequence_output = sequence_output[:, 1 + masked_pixel_len :]
|
| 791 |
+
if not return_dict:
|
| 792 |
+
return (
|
| 793 |
+
sequence_output,
|
| 794 |
+
pixel_sequence_output,
|
| 795 |
+
audio_sequence_output,
|
| 796 |
+
pixel_label_masks,
|
| 797 |
+
audio_label_masks,
|
| 798 |
+
pixel_ids_restore,
|
| 799 |
+
audio_ids_restore,
|
| 800 |
+
) + encoder_outputs[1:]
|
| 801 |
+
|
| 802 |
+
return TvltModelOutput(
|
| 803 |
+
last_hidden_state=sequence_output,
|
| 804 |
+
last_pixel_hidden_state=pixel_sequence_output,
|
| 805 |
+
last_audio_hidden_state=audio_sequence_output,
|
| 806 |
+
pixel_label_masks=pixel_label_masks,
|
| 807 |
+
audio_label_masks=audio_label_masks,
|
| 808 |
+
pixel_ids_restore=pixel_ids_restore,
|
| 809 |
+
audio_ids_restore=audio_ids_restore,
|
| 810 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 811 |
+
attentions=encoder_outputs.attentions,
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
class TvltDecoder(nn.Module):
|
| 816 |
+
def __init__(self, config):
|
| 817 |
+
super().__init__()
|
| 818 |
+
|
| 819 |
+
decoder_config = deepcopy(config)
|
| 820 |
+
decoder_config.hidden_size = config.decoder_hidden_size
|
| 821 |
+
decoder_config.num_hidden_layers = config.decoder_num_hidden_layers
|
| 822 |
+
decoder_config.num_attention_heads = config.decoder_num_attention_heads
|
| 823 |
+
decoder_config.intermediate_size = config.decoder_intermediate_size
|
| 824 |
+
self.decoder_layers = nn.ModuleList(
|
| 825 |
+
[TvltLayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)]
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
self.layernorm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps)
|
| 829 |
+
|
| 830 |
+
self.gradient_checkpointing = False
|
| 831 |
+
self.config = config
|
| 832 |
+
|
| 833 |
+
def forward(
|
| 834 |
+
self,
|
| 835 |
+
hidden_states,
|
| 836 |
+
output_attentions=False,
|
| 837 |
+
output_hidden_states=False,
|
| 838 |
+
return_dict=True,
|
| 839 |
+
):
|
| 840 |
+
# apply Transformer layers (blocks)
|
| 841 |
+
all_hidden_states = () if output_hidden_states else None
|
| 842 |
+
all_self_attentions = () if output_attentions else None
|
| 843 |
+
for i, layer_module in enumerate(self.decoder_layers):
|
| 844 |
+
if output_hidden_states:
|
| 845 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 846 |
+
|
| 847 |
+
layer_outputs = layer_module(hidden_states, output_attentions=output_attentions)
|
| 848 |
+
|
| 849 |
+
hidden_states = layer_outputs[0]
|
| 850 |
+
|
| 851 |
+
if output_attentions:
|
| 852 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 853 |
+
|
| 854 |
+
if output_hidden_states:
|
| 855 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 856 |
+
|
| 857 |
+
# predictor projection
|
| 858 |
+
logits = self.layernorm(hidden_states)
|
| 859 |
+
|
| 860 |
+
if not return_dict:
|
| 861 |
+
return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None)
|
| 862 |
+
return TvltDecoderOutput(logits=logits, hidden_states=all_hidden_states, attentions=all_self_attentions)
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
@add_start_docstrings(
|
| 866 |
+
"The TVLT Model transformer with the decoder on top for self-supervised pre-training.",
|
| 867 |
+
TVLT_START_DOCSTRING,
|
| 868 |
+
)
|
| 869 |
+
class TvltForPreTraining(TvltPreTrainedModel):
|
| 870 |
+
def __init__(self, config):
|
| 871 |
+
super().__init__(config)
|
| 872 |
+
self.config = config
|
| 873 |
+
|
| 874 |
+
self.task_matching = config.task_matching
|
| 875 |
+
self.task_mae = config.task_mae
|
| 876 |
+
if not (self.task_matching or self.task_mae):
|
| 877 |
+
raise ValueError("Must set at least one of matching task and MAE task to true")
|
| 878 |
+
|
| 879 |
+
self.tvlt = TvltModel(config)
|
| 880 |
+
|
| 881 |
+
if self.task_matching:
|
| 882 |
+
self.matching_head = TvltMatchingHead(config)
|
| 883 |
+
|
| 884 |
+
if self.task_mae:
|
| 885 |
+
self.encoder_to_decoder = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=True)
|
| 886 |
+
|
| 887 |
+
self.pixel_mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
|
| 888 |
+
self.audio_mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
|
| 889 |
+
|
| 890 |
+
self.decoder = TvltDecoder(config)
|
| 891 |
+
|
| 892 |
+
decoder_hidden_size = config.decoder_hidden_size
|
| 893 |
+
|
| 894 |
+
num_frames = config.num_frames
|
| 895 |
+
num_patches_per_image = self.tvlt.pixel_embeddings.num_patches_per_image
|
| 896 |
+
self.decoder_pixel_pos_embed = nn.Parameter(torch.zeros(1, num_patches_per_image, decoder_hidden_size))
|
| 897 |
+
self.decoder_temporal_embed = nn.Parameter(torch.zeros(1, config.num_frames, decoder_hidden_size))
|
| 898 |
+
self.decoder_pixel_type_embed = nn.Parameter(torch.zeros(1, 1, decoder_hidden_size))
|
| 899 |
+
|
| 900 |
+
num_audio_patches = self.tvlt.audio_embeddings.num_patches
|
| 901 |
+
num_freq_patches = config.frequency_length // config.audio_patch_size[1]
|
| 902 |
+
self.decoder_audio_pos_embed = nn.Parameter(
|
| 903 |
+
torch.zeros(1, num_audio_patches // num_freq_patches, decoder_hidden_size)
|
| 904 |
+
)
|
| 905 |
+
self.decoder_freq_embed = nn.Parameter(torch.zeros(1, num_freq_patches, decoder_hidden_size))
|
| 906 |
+
self.decoder_audio_type_embed = nn.Parameter(torch.zeros(1, 1, decoder_hidden_size))
|
| 907 |
+
|
| 908 |
+
pixel_mae_output_dim = self.config.image_patch_size[0] ** 2 * self.config.num_image_channels
|
| 909 |
+
self.pixel_mae_head = TvltMAEHead(config, pixel_mae_output_dim)
|
| 910 |
+
audio_mae_output_dim = (
|
| 911 |
+
self.config.audio_patch_size[0] * self.config.audio_patch_size[1] * self.config.num_audio_channels
|
| 912 |
+
)
|
| 913 |
+
self.audio_mae_head = TvltMAEHead(config, audio_mae_output_dim)
|
| 914 |
+
|
| 915 |
+
self.num_frames = num_frames
|
| 916 |
+
self.num_patches_per_image = num_patches_per_image
|
| 917 |
+
self.num_freq_patches = num_freq_patches
|
| 918 |
+
self.image_patch_size = config.image_patch_size
|
| 919 |
+
self.audio_patch_size = config.audio_patch_size
|
| 920 |
+
|
| 921 |
+
# Initialize weights and apply final processing
|
| 922 |
+
self.post_init()
|
| 923 |
+
|
| 924 |
+
def patchify_pixel(self, pixel_values):
|
| 925 |
+
"""
|
| 926 |
+
pixel_values: [batch_size, num_frames, 3, height, width]
|
| 927 |
+
"""
|
| 928 |
+
batch_size, num_frames, num_channels, height, width = pixel_values.shape
|
| 929 |
+
num_patches_height = pixel_values.shape[3] // self.image_patch_size[0]
|
| 930 |
+
num_patches_width = pixel_values.shape[4] // self.image_patch_size[1]
|
| 931 |
+
patchified_pixel_values = pixel_values.reshape(
|
| 932 |
+
shape=(
|
| 933 |
+
batch_size,
|
| 934 |
+
num_frames,
|
| 935 |
+
num_channels,
|
| 936 |
+
num_patches_height,
|
| 937 |
+
self.image_patch_size[0],
|
| 938 |
+
num_patches_width,
|
| 939 |
+
self.image_patch_size[1],
|
| 940 |
+
)
|
| 941 |
+
)
|
| 942 |
+
patchified_pixel_values = torch.einsum("ntchpwq->nthwpqc", patchified_pixel_values)
|
| 943 |
+
patchified_pixel_values = patchified_pixel_values.reshape(
|
| 944 |
+
shape=(
|
| 945 |
+
batch_size,
|
| 946 |
+
num_patches_height * num_patches_width * num_frames,
|
| 947 |
+
self.image_patch_size[0] * self.image_patch_size[1] * num_channels,
|
| 948 |
+
)
|
| 949 |
+
)
|
| 950 |
+
return patchified_pixel_values
|
| 951 |
+
|
| 952 |
+
def patchify_audio(self, audio_values):
|
| 953 |
+
"""
|
| 954 |
+
audio_values: [batch_size, 1, height, width]
|
| 955 |
+
"""
|
| 956 |
+
batch_size, num_channels, height, width = audio_values.shape
|
| 957 |
+
num_patches_height = height // self.audio_patch_size[0]
|
| 958 |
+
num_patches_width = width // self.audio_patch_size[1]
|
| 959 |
+
patchified_audio_values = audio_values.reshape(
|
| 960 |
+
shape=(
|
| 961 |
+
batch_size,
|
| 962 |
+
num_channels,
|
| 963 |
+
num_patches_height,
|
| 964 |
+
self.audio_patch_size[0],
|
| 965 |
+
num_patches_width,
|
| 966 |
+
self.audio_patch_size[1],
|
| 967 |
+
)
|
| 968 |
+
)
|
| 969 |
+
patchified_audio_values = torch.einsum("nchpwq->nhwpqc", patchified_audio_values)
|
| 970 |
+
patchified_audio_values = patchified_audio_values.reshape(
|
| 971 |
+
shape=(
|
| 972 |
+
batch_size,
|
| 973 |
+
num_patches_height * num_patches_width,
|
| 974 |
+
self.audio_patch_size[0] * self.audio_patch_size[1] * num_channels,
|
| 975 |
+
)
|
| 976 |
+
)
|
| 977 |
+
return patchified_audio_values
|
| 978 |
+
|
| 979 |
+
def pixel_mae_loss(self, pixel_values, pixel_predictions, mask):
|
| 980 |
+
patchified_pixel_values = self.patchify_pixel(pixel_values)
|
| 981 |
+
loss = (pixel_predictions - patchified_pixel_values) ** 2
|
| 982 |
+
loss = loss.mean(dim=-1) # [batch_size, pixel_pixel_length], mean loss per patch
|
| 983 |
+
loss = (loss * mask).sum() / mask.sum() # mean loss on removed patches
|
| 984 |
+
return loss
|
| 985 |
+
|
| 986 |
+
def audio_mae_loss(self, audio_values, audio_predictions, mask):
|
| 987 |
+
patchified_audio_values = self.patchify_audio(audio_values)
|
| 988 |
+
loss = (audio_predictions - patchified_audio_values) ** 2
|
| 989 |
+
loss = loss.mean(dim=-1) # [batch_size, audio_pixel_length], mean loss per patch
|
| 990 |
+
loss = (loss * mask).sum() / mask.sum() # mean loss on removed patches
|
| 991 |
+
return loss
|
| 992 |
+
|
| 993 |
+
def concatenate_mask(self, mask_token, sequence, ids_restore):
|
| 994 |
+
batch_size, seq_length, dim = sequence.shape
|
| 995 |
+
mask_tokens = mask_token.repeat(batch_size, ids_restore.shape[1] - seq_length, 1)
|
| 996 |
+
padded_sequence = torch.cat([sequence, mask_tokens], dim=1)
|
| 997 |
+
padded_sequence = torch.gather(
|
| 998 |
+
padded_sequence, dim=1, index=ids_restore.unsqueeze(-1).repeat(1, 1, dim)
|
| 999 |
+
) # unshuffle
|
| 1000 |
+
return padded_sequence
|
| 1001 |
+
|
| 1002 |
+
@add_start_docstrings_to_model_forward(TVLT_INPUTS_DOCSTRING)
|
| 1003 |
+
@replace_return_docstrings(output_type=TvltForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
|
| 1004 |
+
def forward(
|
| 1005 |
+
self,
|
| 1006 |
+
pixel_values: torch.FloatTensor,
|
| 1007 |
+
audio_values: torch.FloatTensor,
|
| 1008 |
+
pixel_mask: Optional[torch.FloatTensor] = None,
|
| 1009 |
+
audio_mask: Optional[torch.FloatTensor] = None,
|
| 1010 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1011 |
+
pixel_values_mixed: Optional[torch.FloatTensor] = None,
|
| 1012 |
+
pixel_mask_mixed: Optional[torch.FloatTensor] = None,
|
| 1013 |
+
output_attentions: Optional[bool] = None,
|
| 1014 |
+
output_hidden_states: Optional[bool] = None,
|
| 1015 |
+
return_dict: Optional[bool] = None,
|
| 1016 |
+
) -> Union[tuple[torch.FloatTensor], TvltForPreTrainingOutput]:
|
| 1017 |
+
r"""
|
| 1018 |
+
pixel_values_mixed (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
|
| 1019 |
+
Pixel values that mix positive and negative samples in Tvlt vision-audio matching. Audio values can be
|
| 1020 |
+
obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for details.
|
| 1021 |
+
|
| 1022 |
+
pixel_mask_mixed (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 1023 |
+
Pixel masks of pixel_values_mixed. Pixel values mixed can be obtained using [`TvltProcessor`]. See
|
| 1024 |
+
[`TvltProcessor.__call__`] for details.
|
| 1025 |
+
|
| 1026 |
+
labels (`torch.LongTensor` of shape `(batch_size, num_labels)`, *optional*):
|
| 1027 |
+
Labels for computing the vision audio matching loss. Indices should be in `[0, 1]`. num_labels has to be 1.
|
| 1028 |
+
|
| 1029 |
+
Return:
|
| 1030 |
+
|
| 1031 |
+
Examples:
|
| 1032 |
+
|
| 1033 |
+
```python
|
| 1034 |
+
>>> from transformers import TvltProcessor, TvltForPreTraining
|
| 1035 |
+
>>> import numpy as np
|
| 1036 |
+
>>> import torch
|
| 1037 |
+
|
| 1038 |
+
>>> num_frames = 8
|
| 1039 |
+
>>> images = list(np.random.randn(num_frames, 3, 224, 224))
|
| 1040 |
+
>>> images_mixed = list(np.random.randn(num_frames, 3, 224, 224))
|
| 1041 |
+
>>> audio = list(np.random.randn(10000))
|
| 1042 |
+
>>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
|
| 1043 |
+
>>> model = TvltForPreTraining.from_pretrained("ZinengTang/tvlt-base")
|
| 1044 |
+
>>> input_dict = processor(
|
| 1045 |
+
... images, audio, images_mixed, sampling_rate=44100, mask_pixel=True, mask_audio=True, return_tensors="pt"
|
| 1046 |
+
... )
|
| 1047 |
+
|
| 1048 |
+
>>> outputs = model(**input_dict)
|
| 1049 |
+
>>> loss = outputs.loss
|
| 1050 |
+
```"""
|
| 1051 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1052 |
+
total_loss = 0.0
|
| 1053 |
+
|
| 1054 |
+
if self.task_matching:
|
| 1055 |
+
if labels is None:
|
| 1056 |
+
raise ValueError("Matching task requires labels")
|
| 1057 |
+
if pixel_values_mixed is None:
|
| 1058 |
+
raise ValueError("Matching task requires pixel_values_mixed")
|
| 1059 |
+
|
| 1060 |
+
outputs = self.tvlt(
|
| 1061 |
+
pixel_values_mixed,
|
| 1062 |
+
audio_values,
|
| 1063 |
+
pixel_mask=pixel_mask_mixed,
|
| 1064 |
+
audio_mask=audio_mask,
|
| 1065 |
+
output_attentions=output_attentions,
|
| 1066 |
+
output_hidden_states=output_hidden_states,
|
| 1067 |
+
return_dict=return_dict,
|
| 1068 |
+
)
|
| 1069 |
+
|
| 1070 |
+
sequence_output = outputs[0]
|
| 1071 |
+
matching_logits = self.matching_head(sequence_output)
|
| 1072 |
+
|
| 1073 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1074 |
+
loss = loss_fct(matching_logits.view(-1), labels.view(-1))
|
| 1075 |
+
total_loss += loss
|
| 1076 |
+
|
| 1077 |
+
pixel_logits = None
|
| 1078 |
+
audio_logits = None
|
| 1079 |
+
if self.task_mae and self.training:
|
| 1080 |
+
outputs = self.tvlt(
|
| 1081 |
+
pixel_values,
|
| 1082 |
+
audio_values,
|
| 1083 |
+
pixel_mask=pixel_mask,
|
| 1084 |
+
audio_mask=audio_mask,
|
| 1085 |
+
mask_pixel=True,
|
| 1086 |
+
mask_audio=True,
|
| 1087 |
+
output_attentions=output_attentions,
|
| 1088 |
+
output_hidden_states=output_hidden_states,
|
| 1089 |
+
return_dict=return_dict,
|
| 1090 |
+
)
|
| 1091 |
+
pixel_sequence_output = outputs.last_pixel_hidden_state if return_dict else outputs[1]
|
| 1092 |
+
audio_sequence_output = outputs.last_audio_hidden_state if return_dict else outputs[2]
|
| 1093 |
+
pixel_label_masks = outputs.pixel_label_masks if return_dict else outputs[3]
|
| 1094 |
+
audio_label_masks = outputs.audio_label_masks if return_dict else outputs[4]
|
| 1095 |
+
pixel_ids_restore = outputs.pixel_ids_restore if return_dict else outputs[5]
|
| 1096 |
+
audio_ids_restore = outputs.audio_ids_restore if return_dict else outputs[6]
|
| 1097 |
+
|
| 1098 |
+
pixel_decoder_input = self.encoder_to_decoder(
|
| 1099 |
+
pixel_sequence_output
|
| 1100 |
+
) # [batch_size, num_masked_pixel_patches, decoder_hidden_size]
|
| 1101 |
+
audio_decoder_input = self.encoder_to_decoder(
|
| 1102 |
+
audio_sequence_output
|
| 1103 |
+
) # [batch_size, num_masked_audio_patches, decoder_hidden_size]
|
| 1104 |
+
num_frames = pixel_values.size(1)
|
| 1105 |
+
pixel_decoder_input = self.concatenate_mask(self.pixel_mask_token, pixel_decoder_input, pixel_ids_restore)
|
| 1106 |
+
pixel_decoder_input = pixel_decoder_input + self.decoder_pixel_pos_embed.repeat(1, num_frames, 1)
|
| 1107 |
+
pixel_decoder_input = pixel_decoder_input + torch.repeat_interleave(
|
| 1108 |
+
self.decoder_temporal_embed[:, :num_frames], self.num_patches_per_image, dim=1
|
| 1109 |
+
)
|
| 1110 |
+
pixel_decoder_input = pixel_decoder_input + self.decoder_pixel_type_embed
|
| 1111 |
+
pixel_decoder_outputs = self.decoder(pixel_decoder_input)
|
| 1112 |
+
pixel_logits = self.pixel_mae_head(pixel_decoder_outputs.logits)
|
| 1113 |
+
|
| 1114 |
+
audio_decoder_input = self.concatenate_mask(self.audio_mask_token, audio_decoder_input, audio_ids_restore)
|
| 1115 |
+
num_time_patches = audio_decoder_input.size(1) // self.num_freq_patches
|
| 1116 |
+
audio_decoder_input = audio_decoder_input + self.decoder_freq_embed.repeat(1, num_time_patches, 1)
|
| 1117 |
+
audio_decoder_input = audio_decoder_input + torch.repeat_interleave(
|
| 1118 |
+
self.decoder_audio_pos_embed[:, :num_time_patches], self.num_freq_patches, dim=1
|
| 1119 |
+
)
|
| 1120 |
+
audio_decoder_input = audio_decoder_input + self.decoder_audio_type_embed
|
| 1121 |
+
audio_decoder_outputs = self.decoder(audio_decoder_input)
|
| 1122 |
+
audio_logits = self.audio_mae_head(audio_decoder_outputs.logits)
|
| 1123 |
+
|
| 1124 |
+
loss = self.pixel_mae_loss(pixel_values, pixel_logits, pixel_label_masks) + self.audio_mae_loss(
|
| 1125 |
+
audio_values, audio_logits, audio_label_masks
|
| 1126 |
+
)
|
| 1127 |
+
total_loss += loss
|
| 1128 |
+
|
| 1129 |
+
if not return_dict:
|
| 1130 |
+
output = (matching_logits, pixel_logits, audio_logits) + outputs[7:]
|
| 1131 |
+
return ((total_loss,) + output) if loss is not None else output
|
| 1132 |
+
|
| 1133 |
+
return TvltForPreTrainingOutput(
|
| 1134 |
+
loss=total_loss,
|
| 1135 |
+
matching_logits=matching_logits,
|
| 1136 |
+
pixel_logits=pixel_logits,
|
| 1137 |
+
audio_logits=audio_logits,
|
| 1138 |
+
hidden_states=outputs.hidden_states,
|
| 1139 |
+
attentions=outputs.attentions,
|
| 1140 |
+
)
|
| 1141 |
+
|
| 1142 |
+
|
| 1143 |
+
class TvltPooler(nn.Module):
|
| 1144 |
+
def __init__(self, config):
|
| 1145 |
+
super().__init__()
|
| 1146 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 1147 |
+
self.activation = nn.Tanh()
|
| 1148 |
+
|
| 1149 |
+
def forward(self, hidden_states):
|
| 1150 |
+
first_token_tensor = hidden_states[:, 0]
|
| 1151 |
+
pooled_output = self.dense(first_token_tensor)
|
| 1152 |
+
pooled_output = self.activation(pooled_output)
|
| 1153 |
+
return pooled_output
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
class TvltMatchingHead(nn.Module):
|
| 1157 |
+
def __init__(self, config):
|
| 1158 |
+
super().__init__()
|
| 1159 |
+
self.pooler = TvltPooler(config)
|
| 1160 |
+
self.fc = nn.Linear(config.hidden_size, 1)
|
| 1161 |
+
|
| 1162 |
+
def forward(self, hidden_states):
|
| 1163 |
+
hidden_states = self.fc(self.pooler(hidden_states))
|
| 1164 |
+
return hidden_states
|
| 1165 |
+
|
| 1166 |
+
|
| 1167 |
+
class TvltMAEHead(nn.Module):
|
| 1168 |
+
def __init__(self, config, output_dim=None):
|
| 1169 |
+
super().__init__()
|
| 1170 |
+
self.config = config
|
| 1171 |
+
self.decoder = nn.Linear(config.decoder_hidden_size, output_dim)
|
| 1172 |
+
|
| 1173 |
+
def forward(self, hidden_states):
|
| 1174 |
+
hidden_states = self.decoder(hidden_states)
|
| 1175 |
+
return hidden_states
|
| 1176 |
+
|
| 1177 |
+
|
| 1178 |
+
@add_start_docstrings(
|
| 1179 |
+
"""
|
| 1180 |
+
Tvlt Model transformer with a classifier head on top (an MLP on top of the final hidden state of the [CLS] token)
|
| 1181 |
+
for audiovisual classification tasks, e.g. CMU-MOSEI Sentiment Analysis and Audio to Video Retrieval.
|
| 1182 |
+
""",
|
| 1183 |
+
TVLT_START_DOCSTRING,
|
| 1184 |
+
)
|
| 1185 |
+
class TvltForAudioVisualClassification(TvltPreTrainedModel):
|
| 1186 |
+
def __init__(self, config):
|
| 1187 |
+
super().__init__(config)
|
| 1188 |
+
|
| 1189 |
+
self.tvlt = TvltModel(config)
|
| 1190 |
+
|
| 1191 |
+
# Classifier head
|
| 1192 |
+
self.classifier = nn.Sequential(
|
| 1193 |
+
nn.Linear(config.hidden_size, config.hidden_size * 2),
|
| 1194 |
+
nn.LayerNorm(config.hidden_size * 2, eps=config.layer_norm_eps),
|
| 1195 |
+
nn.GELU(),
|
| 1196 |
+
nn.Linear(config.hidden_size * 2, config.num_labels),
|
| 1197 |
+
)
|
| 1198 |
+
self.config = config
|
| 1199 |
+
|
| 1200 |
+
# Initialize weights and apply final processing
|
| 1201 |
+
self.post_init()
|
| 1202 |
+
|
| 1203 |
+
@add_start_docstrings_to_model_forward(TVLT_INPUTS_DOCSTRING)
|
| 1204 |
+
@replace_return_docstrings(output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
|
| 1205 |
+
def forward(
|
| 1206 |
+
self,
|
| 1207 |
+
pixel_values: torch.FloatTensor,
|
| 1208 |
+
audio_values: torch.FloatTensor,
|
| 1209 |
+
pixel_mask: Optional[torch.FloatTensor] = None,
|
| 1210 |
+
audio_mask: Optional[torch.FloatTensor] = None,
|
| 1211 |
+
output_attentions: Optional[bool] = None,
|
| 1212 |
+
output_hidden_states: Optional[bool] = None,
|
| 1213 |
+
return_dict: Optional[bool] = None,
|
| 1214 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1215 |
+
) -> Union[tuple[torch.FloatTensor], SequenceClassifierOutput]:
|
| 1216 |
+
r"""
|
| 1217 |
+
labels (`torch.LongTensor` of shape `(batch_size, num_labels)`, *optional*):
|
| 1218 |
+
Labels for computing the audiovisual loss. Indices should be in `[0, ..., num_classes-1]` where num_classes
|
| 1219 |
+
refers to the number of classes in audiovisual tasks.
|
| 1220 |
+
|
| 1221 |
+
Return:
|
| 1222 |
+
|
| 1223 |
+
Examples:
|
| 1224 |
+
```python
|
| 1225 |
+
>>> from transformers import TvltProcessor, TvltForAudioVisualClassification
|
| 1226 |
+
>>> import numpy as np
|
| 1227 |
+
>>> import torch
|
| 1228 |
+
|
| 1229 |
+
>>> num_frames = 8
|
| 1230 |
+
>>> images = list(np.random.randn(num_frames, 3, 224, 224))
|
| 1231 |
+
>>> audio = list(np.random.randn(10000))
|
| 1232 |
+
>>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
|
| 1233 |
+
>>> model = TvltForAudioVisualClassification.from_pretrained("ZinengTang/tvlt-base")
|
| 1234 |
+
>>> input_dict = processor(images, audio, sampling_rate=44100, return_tensors="pt")
|
| 1235 |
+
|
| 1236 |
+
>>> outputs = model(**input_dict)
|
| 1237 |
+
>>> loss = outputs.loss
|
| 1238 |
+
```"""
|
| 1239 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1240 |
+
|
| 1241 |
+
outputs = self.tvlt(
|
| 1242 |
+
pixel_values,
|
| 1243 |
+
audio_values,
|
| 1244 |
+
pixel_mask=pixel_mask,
|
| 1245 |
+
audio_mask=audio_mask,
|
| 1246 |
+
output_attentions=output_attentions,
|
| 1247 |
+
output_hidden_states=output_hidden_states,
|
| 1248 |
+
return_dict=return_dict,
|
| 1249 |
+
)
|
| 1250 |
+
sequence_output = outputs[0][:, 0]
|
| 1251 |
+
logits = self.classifier(sequence_output) # rank value
|
| 1252 |
+
|
| 1253 |
+
loss = None
|
| 1254 |
+
if labels is not None:
|
| 1255 |
+
if self.config.loss_type == "regression":
|
| 1256 |
+
loss_fct = MSELoss()
|
| 1257 |
+
loss = loss_fct(logits, labels)
|
| 1258 |
+
elif self.config.loss_type == "classification":
|
| 1259 |
+
loss_fct = CrossEntropyLoss()
|
| 1260 |
+
loss = loss_fct(logits, labels)
|
| 1261 |
+
|
| 1262 |
+
if not return_dict:
|
| 1263 |
+
output = (logits,) + outputs[4:]
|
| 1264 |
+
return ((loss,) + output) if loss is not None else output
|
| 1265 |
+
|
| 1266 |
+
return SequenceClassifierOutput(
|
| 1267 |
+
loss=loss,
|
| 1268 |
+
logits=logits,
|
| 1269 |
+
hidden_states=outputs.hidden_states,
|
| 1270 |
+
attentions=outputs.attentions,
|
| 1271 |
+
)
|
| 1272 |
+
|
| 1273 |
+
|
| 1274 |
+
__all__ = ["TvltModel", "TvltForPreTraining", "TvltForAudioVisualClassification", "TvltPreTrainedModel"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/processing_tvlt.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Processor class for TVLT.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from ....processing_utils import ProcessorMixin
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TvltProcessor(ProcessorMixin):
|
| 23 |
+
r"""
|
| 24 |
+
Constructs a TVLT processor which wraps a TVLT image processor and TVLT feature extractor into a single processor.
|
| 25 |
+
|
| 26 |
+
[`TvltProcessor`] offers all the functionalities of [`TvltImageProcessor`] and [`TvltFeatureExtractor`]. See the
|
| 27 |
+
docstring of [`~TvltProcessor.__call__`] for more information.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
image_processor (`TvltImageProcessor`):
|
| 31 |
+
An instance of [`TvltImageProcessor`]. The image processor is a required input.
|
| 32 |
+
feature_extractor (`TvltFeatureExtractor`):
|
| 33 |
+
An instance of [`TvltFeatureExtractor`]. The feature extractor is a required input.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
attributes = ["image_processor", "feature_extractor"]
|
| 37 |
+
image_processor_class = "TvltImageProcessor"
|
| 38 |
+
feature_extractor_class = "TvltFeatureExtractor"
|
| 39 |
+
|
| 40 |
+
def __init__(self, image_processor, feature_extractor):
|
| 41 |
+
super().__init__(image_processor=image_processor, feature_extractor=feature_extractor)
|
| 42 |
+
|
| 43 |
+
self.image_processor = image_processor
|
| 44 |
+
self.feature_extractor = feature_extractor
|
| 45 |
+
|
| 46 |
+
def __call__(
|
| 47 |
+
self,
|
| 48 |
+
images=None,
|
| 49 |
+
audio=None,
|
| 50 |
+
images_mixed=None,
|
| 51 |
+
sampling_rate=None,
|
| 52 |
+
mask_audio=False,
|
| 53 |
+
mask_pixel=False,
|
| 54 |
+
*args,
|
| 55 |
+
**kwargs,
|
| 56 |
+
):
|
| 57 |
+
"""
|
| 58 |
+
Forwards the `images` argument to TvltImageProcessor's [`~TvltImageProcessor.preprocess`] and the `audio`
|
| 59 |
+
argument to TvltFeatureExtractor's [`~TvltFeatureExtractor.__call__`]. Please refer to the docstring of the
|
| 60 |
+
above two methods for more information.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
if images is None and audio is None:
|
| 64 |
+
raise ValueError("You need to specify either an `images` or `audio` input to process.")
|
| 65 |
+
|
| 66 |
+
images_mixed_dict = None
|
| 67 |
+
if images is not None:
|
| 68 |
+
images_dict = self.image_processor(images, mask_pixel=mask_pixel, *args, **kwargs)
|
| 69 |
+
if images_mixed is not None:
|
| 70 |
+
images_mixed_dict = self.image_processor(images_mixed, is_mixed=True, *args, **kwargs)
|
| 71 |
+
if audio is not None:
|
| 72 |
+
audio_dict = self.feature_extractor(
|
| 73 |
+
audio, *args, sampling_rate=sampling_rate, mask_audio=mask_audio, **kwargs
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
output_dict = {}
|
| 77 |
+
if audio is not None:
|
| 78 |
+
output_dict.update(audio_dict)
|
| 79 |
+
if images is not None:
|
| 80 |
+
output_dict.update(images_dict)
|
| 81 |
+
if images_mixed_dict is not None:
|
| 82 |
+
output_dict.update(images_mixed_dict)
|
| 83 |
+
return output_dict
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
__all__ = ["TvltProcessor"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/van/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
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_van import *
|
| 22 |
+
from .modeling_van 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__)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/van/configuration_van.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""VAN 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 VanConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`VanModel`]. It is used to instantiate a VAN model
|
| 27 |
+
according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 28 |
+
defaults will yield a similar configuration to that of the VAN
|
| 29 |
+
[Visual-Attention-Network/van-base](https://huggingface.co/Visual-Attention-Network/van-base) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 36 |
+
The size (resolution) of each image.
|
| 37 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 38 |
+
The number of input channels.
|
| 39 |
+
patch_sizes (`list[int]`, *optional*, defaults to `[7, 3, 3, 3]`):
|
| 40 |
+
Patch size to use in each stage's embedding layer.
|
| 41 |
+
strides (`list[int]`, *optional*, defaults to `[4, 2, 2, 2]`):
|
| 42 |
+
Stride size to use in each stage's embedding layer to downsample the input.
|
| 43 |
+
hidden_sizes (`list[int]`, *optional*, defaults to `[64, 128, 320, 512]`):
|
| 44 |
+
Dimensionality (hidden size) at each stage.
|
| 45 |
+
depths (`list[int]`, *optional*, defaults to `[3, 3, 12, 3]`):
|
| 46 |
+
Depth (number of layers) for each stage.
|
| 47 |
+
mlp_ratios (`list[int]`, *optional*, defaults to `[8, 8, 4, 4]`):
|
| 48 |
+
The expansion ratio for mlp layer at each stage.
|
| 49 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 50 |
+
The non-linear activation function (function or string) in each layer. If string, `"gelu"`, `"relu"`,
|
| 51 |
+
`"selu"` and `"gelu_new"` are supported.
|
| 52 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 53 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 54 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 55 |
+
The epsilon used by the layer normalization layers.
|
| 56 |
+
layer_scale_init_value (`float`, *optional*, defaults to 0.01):
|
| 57 |
+
The initial value for layer scaling.
|
| 58 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 59 |
+
The dropout probability for stochastic depth.
|
| 60 |
+
dropout_rate (`float`, *optional*, defaults to 0.0):
|
| 61 |
+
The dropout probability for dropout.
|
| 62 |
+
|
| 63 |
+
Example:
|
| 64 |
+
```python
|
| 65 |
+
>>> from transformers import VanModel, VanConfig
|
| 66 |
+
|
| 67 |
+
>>> # Initializing a VAN van-base style configuration
|
| 68 |
+
>>> configuration = VanConfig()
|
| 69 |
+
>>> # Initializing a model from the van-base style configuration
|
| 70 |
+
>>> model = VanModel(configuration)
|
| 71 |
+
>>> # Accessing the model configuration
|
| 72 |
+
>>> configuration = model.config
|
| 73 |
+
```"""
|
| 74 |
+
|
| 75 |
+
model_type = "van"
|
| 76 |
+
|
| 77 |
+
def __init__(
|
| 78 |
+
self,
|
| 79 |
+
image_size=224,
|
| 80 |
+
num_channels=3,
|
| 81 |
+
patch_sizes=[7, 3, 3, 3],
|
| 82 |
+
strides=[4, 2, 2, 2],
|
| 83 |
+
hidden_sizes=[64, 128, 320, 512],
|
| 84 |
+
depths=[3, 3, 12, 3],
|
| 85 |
+
mlp_ratios=[8, 8, 4, 4],
|
| 86 |
+
hidden_act="gelu",
|
| 87 |
+
initializer_range=0.02,
|
| 88 |
+
layer_norm_eps=1e-6,
|
| 89 |
+
layer_scale_init_value=1e-2,
|
| 90 |
+
drop_path_rate=0.0,
|
| 91 |
+
dropout_rate=0.0,
|
| 92 |
+
**kwargs,
|
| 93 |
+
):
|
| 94 |
+
super().__init__(**kwargs)
|
| 95 |
+
self.image_size = image_size
|
| 96 |
+
self.num_channels = num_channels
|
| 97 |
+
self.patch_sizes = patch_sizes
|
| 98 |
+
self.strides = strides
|
| 99 |
+
self.hidden_sizes = hidden_sizes
|
| 100 |
+
self.depths = depths
|
| 101 |
+
self.mlp_ratios = mlp_ratios
|
| 102 |
+
self.hidden_act = hidden_act
|
| 103 |
+
self.initializer_range = initializer_range
|
| 104 |
+
self.layer_norm_eps = layer_norm_eps
|
| 105 |
+
self.layer_scale_init_value = layer_scale_init_value
|
| 106 |
+
self.drop_path_rate = drop_path_rate
|
| 107 |
+
self.dropout_rate = dropout_rate
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
__all__ = ["VanConfig"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/van/modeling_van.py
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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8
|
| 2 |
+
# Copyright 2022 BNRist (Tsinghua University), TKLNDST (Nankai University) 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 Visual Attention Network (VAN) model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
from typing import Optional, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
|
| 24 |
+
from ....activations import ACT2FN
|
| 25 |
+
from ....modeling_outputs import (
|
| 26 |
+
BaseModelOutputWithNoAttention,
|
| 27 |
+
BaseModelOutputWithPoolingAndNoAttention,
|
| 28 |
+
ImageClassifierOutputWithNoAttention,
|
| 29 |
+
)
|
| 30 |
+
from ....modeling_utils import PreTrainedModel
|
| 31 |
+
from ....utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 32 |
+
from .configuration_van import VanConfig
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
# General docstring
|
| 38 |
+
_CONFIG_FOR_DOC = "VanConfig"
|
| 39 |
+
|
| 40 |
+
# Base docstring
|
| 41 |
+
_CHECKPOINT_FOR_DOC = "Visual-Attention-Network/van-base"
|
| 42 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 512, 7, 7]
|
| 43 |
+
|
| 44 |
+
# Image classification docstring
|
| 45 |
+
_IMAGE_CLASS_CHECKPOINT = "Visual-Attention-Network/van-base"
|
| 46 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 50 |
+
"""
|
| 51 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 52 |
+
|
| 53 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 54 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 55 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 56 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 57 |
+
argument.
|
| 58 |
+
"""
|
| 59 |
+
if drop_prob == 0.0 or not training:
|
| 60 |
+
return input
|
| 61 |
+
keep_prob = 1 - drop_prob
|
| 62 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 63 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 64 |
+
random_tensor.floor_() # binarize
|
| 65 |
+
output = input.div(keep_prob) * random_tensor
|
| 66 |
+
return output
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class VanDropPath(nn.Module):
|
| 70 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 71 |
+
|
| 72 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 73 |
+
super().__init__()
|
| 74 |
+
self.drop_prob = drop_prob
|
| 75 |
+
|
| 76 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 77 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 78 |
+
|
| 79 |
+
def extra_repr(self) -> str:
|
| 80 |
+
return f"p={self.drop_prob}"
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class VanOverlappingPatchEmbedder(nn.Module):
|
| 84 |
+
"""
|
| 85 |
+
Downsamples the input using a patchify operation with a `stride` of 4 by default making adjacent windows overlap by
|
| 86 |
+
half of the area. From [PVTv2: Improved Baselines with Pyramid Vision
|
| 87 |
+
Transformer](https://huggingface.co/papers/2106.13797).
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
def __init__(self, in_channels: int, hidden_size: int, patch_size: int = 7, stride: int = 4):
|
| 91 |
+
super().__init__()
|
| 92 |
+
self.convolution = nn.Conv2d(
|
| 93 |
+
in_channels, hidden_size, kernel_size=patch_size, stride=stride, padding=patch_size // 2
|
| 94 |
+
)
|
| 95 |
+
self.normalization = nn.BatchNorm2d(hidden_size)
|
| 96 |
+
|
| 97 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 98 |
+
hidden_state = self.convolution(input)
|
| 99 |
+
hidden_state = self.normalization(hidden_state)
|
| 100 |
+
return hidden_state
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class VanMlpLayer(nn.Module):
|
| 104 |
+
"""
|
| 105 |
+
MLP with depth-wise convolution, from [PVTv2: Improved Baselines with Pyramid Vision
|
| 106 |
+
Transformer](https://huggingface.co/papers/2106.13797).
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
def __init__(
|
| 110 |
+
self,
|
| 111 |
+
in_channels: int,
|
| 112 |
+
hidden_size: int,
|
| 113 |
+
out_channels: int,
|
| 114 |
+
hidden_act: str = "gelu",
|
| 115 |
+
dropout_rate: float = 0.5,
|
| 116 |
+
):
|
| 117 |
+
super().__init__()
|
| 118 |
+
self.in_dense = nn.Conv2d(in_channels, hidden_size, kernel_size=1)
|
| 119 |
+
self.depth_wise = nn.Conv2d(hidden_size, hidden_size, kernel_size=3, padding=1, groups=hidden_size)
|
| 120 |
+
self.activation = ACT2FN[hidden_act]
|
| 121 |
+
self.dropout1 = nn.Dropout(dropout_rate)
|
| 122 |
+
self.out_dense = nn.Conv2d(hidden_size, out_channels, kernel_size=1)
|
| 123 |
+
self.dropout2 = nn.Dropout(dropout_rate)
|
| 124 |
+
|
| 125 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 126 |
+
hidden_state = self.in_dense(hidden_state)
|
| 127 |
+
hidden_state = self.depth_wise(hidden_state)
|
| 128 |
+
hidden_state = self.activation(hidden_state)
|
| 129 |
+
hidden_state = self.dropout1(hidden_state)
|
| 130 |
+
hidden_state = self.out_dense(hidden_state)
|
| 131 |
+
hidden_state = self.dropout2(hidden_state)
|
| 132 |
+
return hidden_state
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class VanLargeKernelAttention(nn.Module):
|
| 136 |
+
"""
|
| 137 |
+
Basic Large Kernel Attention (LKA).
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
def __init__(self, hidden_size: int):
|
| 141 |
+
super().__init__()
|
| 142 |
+
self.depth_wise = nn.Conv2d(hidden_size, hidden_size, kernel_size=5, padding=2, groups=hidden_size)
|
| 143 |
+
self.depth_wise_dilated = nn.Conv2d(
|
| 144 |
+
hidden_size, hidden_size, kernel_size=7, dilation=3, padding=9, groups=hidden_size
|
| 145 |
+
)
|
| 146 |
+
self.point_wise = nn.Conv2d(hidden_size, hidden_size, kernel_size=1)
|
| 147 |
+
|
| 148 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 149 |
+
hidden_state = self.depth_wise(hidden_state)
|
| 150 |
+
hidden_state = self.depth_wise_dilated(hidden_state)
|
| 151 |
+
hidden_state = self.point_wise(hidden_state)
|
| 152 |
+
return hidden_state
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class VanLargeKernelAttentionLayer(nn.Module):
|
| 156 |
+
"""
|
| 157 |
+
Computes attention using Large Kernel Attention (LKA) and attends the input.
|
| 158 |
+
"""
|
| 159 |
+
|
| 160 |
+
def __init__(self, hidden_size: int):
|
| 161 |
+
super().__init__()
|
| 162 |
+
self.attention = VanLargeKernelAttention(hidden_size)
|
| 163 |
+
|
| 164 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 165 |
+
attention = self.attention(hidden_state)
|
| 166 |
+
attended = hidden_state * attention
|
| 167 |
+
return attended
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class VanSpatialAttentionLayer(nn.Module):
|
| 171 |
+
"""
|
| 172 |
+
Van spatial attention layer composed by projection (via conv) -> act -> Large Kernel Attention (LKA) attention ->
|
| 173 |
+
projection (via conv) + residual connection.
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
def __init__(self, hidden_size: int, hidden_act: str = "gelu"):
|
| 177 |
+
super().__init__()
|
| 178 |
+
self.pre_projection = nn.Sequential(
|
| 179 |
+
OrderedDict(
|
| 180 |
+
[
|
| 181 |
+
("conv", nn.Conv2d(hidden_size, hidden_size, kernel_size=1)),
|
| 182 |
+
("act", ACT2FN[hidden_act]),
|
| 183 |
+
]
|
| 184 |
+
)
|
| 185 |
+
)
|
| 186 |
+
self.attention_layer = VanLargeKernelAttentionLayer(hidden_size)
|
| 187 |
+
self.post_projection = nn.Conv2d(hidden_size, hidden_size, kernel_size=1)
|
| 188 |
+
|
| 189 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 190 |
+
residual = hidden_state
|
| 191 |
+
hidden_state = self.pre_projection(hidden_state)
|
| 192 |
+
hidden_state = self.attention_layer(hidden_state)
|
| 193 |
+
hidden_state = self.post_projection(hidden_state)
|
| 194 |
+
hidden_state = hidden_state + residual
|
| 195 |
+
return hidden_state
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class VanLayerScaling(nn.Module):
|
| 199 |
+
"""
|
| 200 |
+
Scales the inputs by a learnable parameter initialized by `initial_value`.
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
def __init__(self, hidden_size: int, initial_value: float = 1e-2):
|
| 204 |
+
super().__init__()
|
| 205 |
+
self.weight = nn.Parameter(initial_value * torch.ones(hidden_size), requires_grad=True)
|
| 206 |
+
|
| 207 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 208 |
+
# unsqueezing for broadcasting
|
| 209 |
+
hidden_state = self.weight.unsqueeze(-1).unsqueeze(-1) * hidden_state
|
| 210 |
+
return hidden_state
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class VanLayer(nn.Module):
|
| 214 |
+
"""
|
| 215 |
+
Van layer composed by normalization layers, large kernel attention (LKA) and a multi layer perceptron (MLP).
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
def __init__(
|
| 219 |
+
self,
|
| 220 |
+
config: VanConfig,
|
| 221 |
+
hidden_size: int,
|
| 222 |
+
mlp_ratio: int = 4,
|
| 223 |
+
drop_path_rate: float = 0.5,
|
| 224 |
+
):
|
| 225 |
+
super().__init__()
|
| 226 |
+
self.drop_path = VanDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
|
| 227 |
+
self.pre_normomalization = nn.BatchNorm2d(hidden_size)
|
| 228 |
+
self.attention = VanSpatialAttentionLayer(hidden_size, config.hidden_act)
|
| 229 |
+
self.attention_scaling = VanLayerScaling(hidden_size, config.layer_scale_init_value)
|
| 230 |
+
self.post_normalization = nn.BatchNorm2d(hidden_size)
|
| 231 |
+
self.mlp = VanMlpLayer(
|
| 232 |
+
hidden_size, hidden_size * mlp_ratio, hidden_size, config.hidden_act, config.dropout_rate
|
| 233 |
+
)
|
| 234 |
+
self.mlp_scaling = VanLayerScaling(hidden_size, config.layer_scale_init_value)
|
| 235 |
+
|
| 236 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 237 |
+
residual = hidden_state
|
| 238 |
+
# attention
|
| 239 |
+
hidden_state = self.pre_normomalization(hidden_state)
|
| 240 |
+
hidden_state = self.attention(hidden_state)
|
| 241 |
+
hidden_state = self.attention_scaling(hidden_state)
|
| 242 |
+
hidden_state = self.drop_path(hidden_state)
|
| 243 |
+
# residual connection
|
| 244 |
+
hidden_state = residual + hidden_state
|
| 245 |
+
residual = hidden_state
|
| 246 |
+
# mlp
|
| 247 |
+
hidden_state = self.post_normalization(hidden_state)
|
| 248 |
+
hidden_state = self.mlp(hidden_state)
|
| 249 |
+
hidden_state = self.mlp_scaling(hidden_state)
|
| 250 |
+
hidden_state = self.drop_path(hidden_state)
|
| 251 |
+
# residual connection
|
| 252 |
+
hidden_state = residual + hidden_state
|
| 253 |
+
return hidden_state
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
class VanStage(nn.Module):
|
| 257 |
+
"""
|
| 258 |
+
VanStage, consisting of multiple layers.
|
| 259 |
+
"""
|
| 260 |
+
|
| 261 |
+
def __init__(
|
| 262 |
+
self,
|
| 263 |
+
config: VanConfig,
|
| 264 |
+
in_channels: int,
|
| 265 |
+
hidden_size: int,
|
| 266 |
+
patch_size: int,
|
| 267 |
+
stride: int,
|
| 268 |
+
depth: int,
|
| 269 |
+
mlp_ratio: int = 4,
|
| 270 |
+
drop_path_rate: float = 0.0,
|
| 271 |
+
):
|
| 272 |
+
super().__init__()
|
| 273 |
+
self.embeddings = VanOverlappingPatchEmbedder(in_channels, hidden_size, patch_size, stride)
|
| 274 |
+
self.layers = nn.Sequential(
|
| 275 |
+
*[
|
| 276 |
+
VanLayer(
|
| 277 |
+
config,
|
| 278 |
+
hidden_size,
|
| 279 |
+
mlp_ratio=mlp_ratio,
|
| 280 |
+
drop_path_rate=drop_path_rate,
|
| 281 |
+
)
|
| 282 |
+
for _ in range(depth)
|
| 283 |
+
]
|
| 284 |
+
)
|
| 285 |
+
self.normalization = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
|
| 286 |
+
|
| 287 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 288 |
+
hidden_state = self.embeddings(hidden_state)
|
| 289 |
+
hidden_state = self.layers(hidden_state)
|
| 290 |
+
# rearrange b c h w -> b (h w) c
|
| 291 |
+
batch_size, hidden_size, height, width = hidden_state.shape
|
| 292 |
+
hidden_state = hidden_state.flatten(2).transpose(1, 2)
|
| 293 |
+
hidden_state = self.normalization(hidden_state)
|
| 294 |
+
# rearrange b (h w) c- > b c h w
|
| 295 |
+
hidden_state = hidden_state.view(batch_size, height, width, hidden_size).permute(0, 3, 1, 2)
|
| 296 |
+
return hidden_state
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class VanEncoder(nn.Module):
|
| 300 |
+
"""
|
| 301 |
+
VanEncoder, consisting of multiple stages.
|
| 302 |
+
"""
|
| 303 |
+
|
| 304 |
+
def __init__(self, config: VanConfig):
|
| 305 |
+
super().__init__()
|
| 306 |
+
self.stages = nn.ModuleList([])
|
| 307 |
+
patch_sizes = config.patch_sizes
|
| 308 |
+
strides = config.strides
|
| 309 |
+
hidden_sizes = config.hidden_sizes
|
| 310 |
+
depths = config.depths
|
| 311 |
+
mlp_ratios = config.mlp_ratios
|
| 312 |
+
drop_path_rates = [
|
| 313 |
+
x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")
|
| 314 |
+
]
|
| 315 |
+
|
| 316 |
+
for num_stage, (patch_size, stride, hidden_size, depth, mlp_expansion, drop_path_rate) in enumerate(
|
| 317 |
+
zip(patch_sizes, strides, hidden_sizes, depths, mlp_ratios, drop_path_rates)
|
| 318 |
+
):
|
| 319 |
+
is_first_stage = num_stage == 0
|
| 320 |
+
in_channels = hidden_sizes[num_stage - 1]
|
| 321 |
+
if is_first_stage:
|
| 322 |
+
in_channels = config.num_channels
|
| 323 |
+
self.stages.append(
|
| 324 |
+
VanStage(
|
| 325 |
+
config,
|
| 326 |
+
in_channels,
|
| 327 |
+
hidden_size,
|
| 328 |
+
patch_size=patch_size,
|
| 329 |
+
stride=stride,
|
| 330 |
+
depth=depth,
|
| 331 |
+
mlp_ratio=mlp_expansion,
|
| 332 |
+
drop_path_rate=drop_path_rate,
|
| 333 |
+
)
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
def forward(
|
| 337 |
+
self,
|
| 338 |
+
hidden_state: torch.Tensor,
|
| 339 |
+
output_hidden_states: Optional[bool] = False,
|
| 340 |
+
return_dict: Optional[bool] = True,
|
| 341 |
+
) -> Union[tuple, BaseModelOutputWithNoAttention]:
|
| 342 |
+
all_hidden_states = () if output_hidden_states else None
|
| 343 |
+
|
| 344 |
+
for _, stage_module in enumerate(self.stages):
|
| 345 |
+
hidden_state = stage_module(hidden_state)
|
| 346 |
+
|
| 347 |
+
if output_hidden_states:
|
| 348 |
+
all_hidden_states = all_hidden_states + (hidden_state,)
|
| 349 |
+
|
| 350 |
+
if not return_dict:
|
| 351 |
+
return tuple(v for v in [hidden_state, all_hidden_states] if v is not None)
|
| 352 |
+
|
| 353 |
+
return BaseModelOutputWithNoAttention(last_hidden_state=hidden_state, hidden_states=all_hidden_states)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class VanPreTrainedModel(PreTrainedModel):
|
| 357 |
+
"""
|
| 358 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 359 |
+
models.
|
| 360 |
+
"""
|
| 361 |
+
|
| 362 |
+
config: VanConfig
|
| 363 |
+
base_model_prefix = "van"
|
| 364 |
+
main_input_name = "pixel_values"
|
| 365 |
+
supports_gradient_checkpointing = True
|
| 366 |
+
|
| 367 |
+
def _init_weights(self, module):
|
| 368 |
+
"""Initialize the weights"""
|
| 369 |
+
if isinstance(module, nn.Linear):
|
| 370 |
+
nn.init.trunc_normal_(module.weight, std=self.config.initializer_range)
|
| 371 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 372 |
+
nn.init.constant_(module.bias, 0)
|
| 373 |
+
elif isinstance(module, nn.LayerNorm):
|
| 374 |
+
nn.init.constant_(module.bias, 0)
|
| 375 |
+
nn.init.constant_(module.weight, 1.0)
|
| 376 |
+
elif isinstance(module, nn.Conv2d):
|
| 377 |
+
fan_out = module.kernel_size[0] * module.kernel_size[1] * module.out_channels
|
| 378 |
+
fan_out //= module.groups
|
| 379 |
+
module.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
|
| 380 |
+
if module.bias is not None:
|
| 381 |
+
module.bias.data.zero_()
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
VAN_START_DOCSTRING = r"""
|
| 385 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 386 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 387 |
+
behavior.
|
| 388 |
+
|
| 389 |
+
Parameters:
|
| 390 |
+
config ([`VanConfig`]): Model configuration class with all the parameters of the model.
|
| 391 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 392 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 393 |
+
"""
|
| 394 |
+
|
| 395 |
+
VAN_INPUTS_DOCSTRING = r"""
|
| 396 |
+
Args:
|
| 397 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 398 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 399 |
+
[`ConvNextImageProcessor.__call__`] for details.
|
| 400 |
+
|
| 401 |
+
output_hidden_states (`bool`, *optional*):
|
| 402 |
+
Whether or not to return the hidden states of all stages. See `hidden_states` under returned tensors for
|
| 403 |
+
more detail.
|
| 404 |
+
return_dict (`bool`, *optional*):
|
| 405 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 406 |
+
"""
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@add_start_docstrings(
|
| 410 |
+
"The bare VAN model outputting raw features without any specific head on top. Note, VAN does not have an embedding"
|
| 411 |
+
" layer.",
|
| 412 |
+
VAN_START_DOCSTRING,
|
| 413 |
+
)
|
| 414 |
+
class VanModel(VanPreTrainedModel):
|
| 415 |
+
def __init__(self, config):
|
| 416 |
+
super().__init__(config)
|
| 417 |
+
self.config = config
|
| 418 |
+
self.encoder = VanEncoder(config)
|
| 419 |
+
# final layernorm layer
|
| 420 |
+
self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
|
| 421 |
+
# Initialize weights and apply final processing
|
| 422 |
+
self.post_init()
|
| 423 |
+
|
| 424 |
+
@add_start_docstrings_to_model_forward(VAN_INPUTS_DOCSTRING)
|
| 425 |
+
@add_code_sample_docstrings(
|
| 426 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 427 |
+
output_type=BaseModelOutputWithPoolingAndNoAttention,
|
| 428 |
+
config_class=_CONFIG_FOR_DOC,
|
| 429 |
+
modality="vision",
|
| 430 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 431 |
+
)
|
| 432 |
+
def forward(
|
| 433 |
+
self,
|
| 434 |
+
pixel_values: Optional[torch.FloatTensor],
|
| 435 |
+
output_hidden_states: Optional[bool] = None,
|
| 436 |
+
return_dict: Optional[bool] = None,
|
| 437 |
+
) -> Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
|
| 438 |
+
output_hidden_states = (
|
| 439 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 440 |
+
)
|
| 441 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 442 |
+
|
| 443 |
+
encoder_outputs = self.encoder(
|
| 444 |
+
pixel_values,
|
| 445 |
+
output_hidden_states=output_hidden_states,
|
| 446 |
+
return_dict=return_dict,
|
| 447 |
+
)
|
| 448 |
+
last_hidden_state = encoder_outputs[0]
|
| 449 |
+
# global average pooling, n c w h -> n c
|
| 450 |
+
pooled_output = last_hidden_state.mean(dim=[-2, -1])
|
| 451 |
+
|
| 452 |
+
if not return_dict:
|
| 453 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 454 |
+
|
| 455 |
+
return BaseModelOutputWithPoolingAndNoAttention(
|
| 456 |
+
last_hidden_state=last_hidden_state,
|
| 457 |
+
pooler_output=pooled_output,
|
| 458 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
@add_start_docstrings(
|
| 463 |
+
"""
|
| 464 |
+
VAN Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
|
| 465 |
+
ImageNet.
|
| 466 |
+
""",
|
| 467 |
+
VAN_START_DOCSTRING,
|
| 468 |
+
)
|
| 469 |
+
class VanForImageClassification(VanPreTrainedModel):
|
| 470 |
+
def __init__(self, config):
|
| 471 |
+
super().__init__(config)
|
| 472 |
+
self.van = VanModel(config)
|
| 473 |
+
# Classifier head
|
| 474 |
+
self.classifier = (
|
| 475 |
+
nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
# Initialize weights and apply final processing
|
| 479 |
+
self.post_init()
|
| 480 |
+
|
| 481 |
+
@add_start_docstrings_to_model_forward(VAN_INPUTS_DOCSTRING)
|
| 482 |
+
@add_code_sample_docstrings(
|
| 483 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
| 484 |
+
output_type=ImageClassifierOutputWithNoAttention,
|
| 485 |
+
config_class=_CONFIG_FOR_DOC,
|
| 486 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
| 487 |
+
)
|
| 488 |
+
def forward(
|
| 489 |
+
self,
|
| 490 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 491 |
+
labels: Optional[torch.LongTensor] = None,
|
| 492 |
+
output_hidden_states: Optional[bool] = None,
|
| 493 |
+
return_dict: Optional[bool] = None,
|
| 494 |
+
) -> Union[tuple, ImageClassifierOutputWithNoAttention]:
|
| 495 |
+
r"""
|
| 496 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 497 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 498 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 499 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 500 |
+
"""
|
| 501 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 502 |
+
|
| 503 |
+
outputs = self.van(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 504 |
+
|
| 505 |
+
pooled_output = outputs.pooler_output if return_dict else outputs[1]
|
| 506 |
+
|
| 507 |
+
logits = self.classifier(pooled_output)
|
| 508 |
+
|
| 509 |
+
loss = None
|
| 510 |
+
if labels is not None:
|
| 511 |
+
loss = self.loss_function(labels, logits, self.config)
|
| 512 |
+
|
| 513 |
+
if not return_dict:
|
| 514 |
+
output = (logits,) + outputs[2:]
|
| 515 |
+
return ((loss,) + output) if loss is not None else output
|
| 516 |
+
|
| 517 |
+
return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
__all__ = ["VanForImageClassification", "VanModel", "VanPreTrainedModel"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/vit_hybrid/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
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_vit_hybrid import *
|
| 22 |
+
from .image_processing_vit_hybrid import *
|
| 23 |
+
from .modeling_vit_hybrid import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/vit_hybrid/configuration_vit_hybrid.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""ViT Hybrid model configuration"""
|
| 16 |
+
|
| 17 |
+
from ....configuration_utils import PretrainedConfig
|
| 18 |
+
from ....utils import logging
|
| 19 |
+
from ...auto.configuration_auto import CONFIG_MAPPING
|
| 20 |
+
from ...bit import BitConfig
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ViTHybridConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`ViTHybridModel`]. It is used to instantiate a ViT
|
| 29 |
+
Hybrid model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 30 |
+
with the defaults will yield a similar configuration to that of the ViT Hybrid
|
| 31 |
+
[google/vit-hybrid-base-bit-384](https://huggingface.co/google/vit-hybrid-base-bit-384) architecture.
|
| 32 |
+
|
| 33 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 34 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
backbone_config (`Union[dict[str, Any], PretrainedConfig]`, *optional*):
|
| 38 |
+
The configuration of the backbone in a dictionary or the config object of the backbone.
|
| 39 |
+
backbone (`str`, *optional*):
|
| 40 |
+
Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
|
| 41 |
+
will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
|
| 42 |
+
is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
|
| 43 |
+
use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
|
| 44 |
+
Whether to use pretrained weights for the backbone.
|
| 45 |
+
use_timm_backbone (`bool`, *optional*, defaults to `False`):
|
| 46 |
+
Whether to load `backbone` from the timm library. If `False`, the backbone is loaded from the transformers
|
| 47 |
+
library.
|
| 48 |
+
backbone_kwargs (`dict`, *optional*):
|
| 49 |
+
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
|
| 50 |
+
e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
|
| 51 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 52 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 53 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 54 |
+
Number of hidden layers in the Transformer encoder.
|
| 55 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 56 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 57 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 58 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 59 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 60 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 61 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 62 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 63 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 64 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 65 |
+
The dropout ratio for the attention probabilities.
|
| 66 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 67 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 68 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 69 |
+
The epsilon used by the layer normalization layers.
|
| 70 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 71 |
+
The size (resolution) of each image.
|
| 72 |
+
patch_size (`int`, *optional*, defaults to 1):
|
| 73 |
+
The size (resolution) of each patch.
|
| 74 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 75 |
+
The number of input channels.
|
| 76 |
+
backbone_featmap_shape (`list[int]`, *optional*, defaults to `[1, 1024, 24, 24]`):
|
| 77 |
+
Used only for the `hybrid` embedding type. The shape of the feature maps of the backbone.
|
| 78 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 79 |
+
Whether to add a bias to the queries, keys and values.
|
| 80 |
+
|
| 81 |
+
Example:
|
| 82 |
+
|
| 83 |
+
```python
|
| 84 |
+
>>> from transformers import ViTHybridConfig, ViTHybridModel
|
| 85 |
+
|
| 86 |
+
>>> # Initializing a ViT Hybrid vit-hybrid-base-bit-384 style configuration
|
| 87 |
+
>>> configuration = ViTHybridConfig()
|
| 88 |
+
|
| 89 |
+
>>> # Initializing a model (with random weights) from the vit-hybrid-base-bit-384 style configuration
|
| 90 |
+
>>> model = ViTHybridModel(configuration)
|
| 91 |
+
|
| 92 |
+
>>> # Accessing the model configuration
|
| 93 |
+
>>> configuration = model.config
|
| 94 |
+
```"""
|
| 95 |
+
|
| 96 |
+
model_type = "vit-hybrid"
|
| 97 |
+
|
| 98 |
+
def __init__(
|
| 99 |
+
self,
|
| 100 |
+
backbone_config=None,
|
| 101 |
+
backbone=None,
|
| 102 |
+
use_pretrained_backbone=False,
|
| 103 |
+
use_timm_backbone=False,
|
| 104 |
+
backbone_kwargs=None,
|
| 105 |
+
hidden_size=768,
|
| 106 |
+
num_hidden_layers=12,
|
| 107 |
+
num_attention_heads=12,
|
| 108 |
+
intermediate_size=3072,
|
| 109 |
+
hidden_act="gelu",
|
| 110 |
+
hidden_dropout_prob=0.0,
|
| 111 |
+
attention_probs_dropout_prob=0.0,
|
| 112 |
+
initializer_range=0.02,
|
| 113 |
+
layer_norm_eps=1e-12,
|
| 114 |
+
image_size=224,
|
| 115 |
+
patch_size=1,
|
| 116 |
+
num_channels=3,
|
| 117 |
+
backbone_featmap_shape=[1, 1024, 24, 24],
|
| 118 |
+
qkv_bias=True,
|
| 119 |
+
**kwargs,
|
| 120 |
+
):
|
| 121 |
+
super().__init__(**kwargs)
|
| 122 |
+
if use_pretrained_backbone:
|
| 123 |
+
raise ValueError("Pretrained backbones are not supported yet.")
|
| 124 |
+
|
| 125 |
+
if backbone_config is not None and backbone is not None:
|
| 126 |
+
raise ValueError("You can't specify both `backbone` and `backbone_config`.")
|
| 127 |
+
|
| 128 |
+
if backbone_config is None and backbone is None:
|
| 129 |
+
logger.info("`backbone_config` is `None`. Initializing the config with a `BiT` backbone.")
|
| 130 |
+
backbone_config = {
|
| 131 |
+
"global_padding": "same",
|
| 132 |
+
"layer_type": "bottleneck",
|
| 133 |
+
"depths": [3, 4, 9],
|
| 134 |
+
"out_features": ["stage3"],
|
| 135 |
+
"embedding_dynamic_padding": True,
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
if backbone_kwargs is not None and backbone_kwargs and backbone_config is not None:
|
| 139 |
+
raise ValueError("You can't specify both `backbone_kwargs` and `backbone_config`.")
|
| 140 |
+
|
| 141 |
+
if isinstance(backbone_config, dict):
|
| 142 |
+
if "model_type" in backbone_config:
|
| 143 |
+
backbone_config_class = CONFIG_MAPPING[backbone_config["model_type"]]
|
| 144 |
+
else:
|
| 145 |
+
logger.info(
|
| 146 |
+
"`model_type` is not found in `backbone_config`. Use `Bit` as the backbone configuration class."
|
| 147 |
+
)
|
| 148 |
+
backbone_config_class = BitConfig
|
| 149 |
+
backbone_config = backbone_config_class(**backbone_config)
|
| 150 |
+
|
| 151 |
+
self.backbone_featmap_shape = backbone_featmap_shape
|
| 152 |
+
self.backbone_config = backbone_config
|
| 153 |
+
self.backbone = backbone
|
| 154 |
+
self.use_pretrained_backbone = use_pretrained_backbone
|
| 155 |
+
self.use_timm_backbone = use_timm_backbone
|
| 156 |
+
self.backbone_kwargs = backbone_kwargs
|
| 157 |
+
self.hidden_size = hidden_size
|
| 158 |
+
self.num_hidden_layers = num_hidden_layers
|
| 159 |
+
self.num_attention_heads = num_attention_heads
|
| 160 |
+
self.intermediate_size = intermediate_size
|
| 161 |
+
self.hidden_act = hidden_act
|
| 162 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 163 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 164 |
+
self.initializer_range = initializer_range
|
| 165 |
+
self.layer_norm_eps = layer_norm_eps
|
| 166 |
+
self.image_size = image_size
|
| 167 |
+
self.patch_size = patch_size
|
| 168 |
+
self.num_channels = num_channels
|
| 169 |
+
self.qkv_bias = qkv_bias
|
| 170 |
+
|
| 171 |
+
@property
|
| 172 |
+
def sub_configs(self):
|
| 173 |
+
return (
|
| 174 |
+
{"backbone_config": type(self.backbone_config)}
|
| 175 |
+
if getattr(self, "backbone_config", None) is not None
|
| 176 |
+
else {}
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
__all__ = ["ViTHybridConfig"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/vit_hybrid/image_processing_vit_hybrid.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 ViT hybrid."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ....image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 22 |
+
from ....image_transforms import (
|
| 23 |
+
convert_to_rgb,
|
| 24 |
+
get_resize_output_image_size,
|
| 25 |
+
resize,
|
| 26 |
+
to_channel_dimension_format,
|
| 27 |
+
)
|
| 28 |
+
from ....image_utils import (
|
| 29 |
+
OPENAI_CLIP_MEAN,
|
| 30 |
+
OPENAI_CLIP_STD,
|
| 31 |
+
ChannelDimension,
|
| 32 |
+
ImageInput,
|
| 33 |
+
PILImageResampling,
|
| 34 |
+
infer_channel_dimension_format,
|
| 35 |
+
is_scaled_image,
|
| 36 |
+
make_flat_list_of_images,
|
| 37 |
+
to_numpy_array,
|
| 38 |
+
valid_images,
|
| 39 |
+
validate_kwargs,
|
| 40 |
+
validate_preprocess_arguments,
|
| 41 |
+
)
|
| 42 |
+
from ....utils import TensorType, is_vision_available, logging
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
logger = logging.get_logger(__name__)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if is_vision_available():
|
| 49 |
+
import PIL
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class ViTHybridImageProcessor(BaseImageProcessor):
|
| 53 |
+
r"""
|
| 54 |
+
Constructs a ViT Hybrid image processor.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 58 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
|
| 59 |
+
`do_resize` in the `preprocess` method.
|
| 60 |
+
size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
|
| 61 |
+
Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
|
| 62 |
+
the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
|
| 63 |
+
method.
|
| 64 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 65 |
+
Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
|
| 66 |
+
do_center_crop (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
|
| 68 |
+
`preprocess` method.
|
| 69 |
+
crop_size (`dict[str, int]` *optional*, defaults to 224):
|
| 70 |
+
Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
|
| 71 |
+
method.
|
| 72 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
|
| 74 |
+
the `preprocess` method.
|
| 75 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 76 |
+
Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
|
| 77 |
+
method.
|
| 78 |
+
do_normalize:
|
| 79 |
+
Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
|
| 80 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
| 81 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 82 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 83 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
| 84 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 85 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 86 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 87 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
| 88 |
+
Whether to convert the image to RGB.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
model_input_names = ["pixel_values"]
|
| 92 |
+
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
do_resize: bool = True,
|
| 96 |
+
size: Optional[dict[str, int]] = None,
|
| 97 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 98 |
+
do_center_crop: bool = True,
|
| 99 |
+
crop_size: Optional[dict[str, int]] = None,
|
| 100 |
+
do_rescale: bool = True,
|
| 101 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 102 |
+
do_normalize: bool = True,
|
| 103 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 104 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 105 |
+
do_convert_rgb: bool = True,
|
| 106 |
+
**kwargs,
|
| 107 |
+
) -> None:
|
| 108 |
+
super().__init__(**kwargs)
|
| 109 |
+
size = size if size is not None else {"shortest_edge": 224}
|
| 110 |
+
size = get_size_dict(size, default_to_square=False)
|
| 111 |
+
crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
|
| 112 |
+
crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
|
| 113 |
+
|
| 114 |
+
self.do_resize = do_resize
|
| 115 |
+
self.size = size
|
| 116 |
+
self.resample = resample
|
| 117 |
+
self.do_center_crop = do_center_crop
|
| 118 |
+
self.crop_size = crop_size
|
| 119 |
+
self.do_rescale = do_rescale
|
| 120 |
+
self.rescale_factor = rescale_factor
|
| 121 |
+
self.do_normalize = do_normalize
|
| 122 |
+
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
|
| 123 |
+
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
|
| 124 |
+
self.do_convert_rgb = do_convert_rgb
|
| 125 |
+
self._valid_processor_keys = [
|
| 126 |
+
"images",
|
| 127 |
+
"do_resize",
|
| 128 |
+
"size",
|
| 129 |
+
"resample",
|
| 130 |
+
"do_center_crop",
|
| 131 |
+
"crop_size",
|
| 132 |
+
"do_rescale",
|
| 133 |
+
"rescale_factor",
|
| 134 |
+
"do_normalize",
|
| 135 |
+
"image_mean",
|
| 136 |
+
"image_std",
|
| 137 |
+
"do_convert_rgb",
|
| 138 |
+
"return_tensors",
|
| 139 |
+
"data_format",
|
| 140 |
+
"input_data_format",
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
def resize(
|
| 144 |
+
self,
|
| 145 |
+
image: np.ndarray,
|
| 146 |
+
size: dict[str, int],
|
| 147 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 148 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 149 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 150 |
+
**kwargs,
|
| 151 |
+
) -> np.ndarray:
|
| 152 |
+
"""
|
| 153 |
+
Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
|
| 154 |
+
resized to keep the input aspect ratio.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
image (`np.ndarray`):
|
| 158 |
+
Image to resize.
|
| 159 |
+
size (`dict[str, int]`):
|
| 160 |
+
Size of the output image.
|
| 161 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 162 |
+
Resampling filter to use when resiizing the image.
|
| 163 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 164 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 165 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 166 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 167 |
+
"""
|
| 168 |
+
default_to_square = True
|
| 169 |
+
if "shortest_edge" in size:
|
| 170 |
+
size = size["shortest_edge"]
|
| 171 |
+
default_to_square = False
|
| 172 |
+
elif "height" in size and "width" in size:
|
| 173 |
+
size = (size["height"], size["width"])
|
| 174 |
+
else:
|
| 175 |
+
raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
|
| 176 |
+
|
| 177 |
+
output_size = get_resize_output_image_size(
|
| 178 |
+
image,
|
| 179 |
+
size=size,
|
| 180 |
+
default_to_square=default_to_square,
|
| 181 |
+
input_data_format=input_data_format,
|
| 182 |
+
)
|
| 183 |
+
return resize(
|
| 184 |
+
image,
|
| 185 |
+
size=output_size,
|
| 186 |
+
resample=resample,
|
| 187 |
+
data_format=data_format,
|
| 188 |
+
input_data_format=input_data_format,
|
| 189 |
+
**kwargs,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
def preprocess(
|
| 193 |
+
self,
|
| 194 |
+
images: ImageInput,
|
| 195 |
+
do_resize: Optional[bool] = None,
|
| 196 |
+
size: Optional[dict[str, int]] = None,
|
| 197 |
+
resample: Optional[PILImageResampling] = None,
|
| 198 |
+
do_center_crop: Optional[bool] = None,
|
| 199 |
+
crop_size: Optional[int] = None,
|
| 200 |
+
do_rescale: Optional[bool] = None,
|
| 201 |
+
rescale_factor: Optional[float] = None,
|
| 202 |
+
do_normalize: Optional[bool] = None,
|
| 203 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 204 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 205 |
+
do_convert_rgb: Optional[bool] = None,
|
| 206 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 207 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 208 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 209 |
+
**kwargs,
|
| 210 |
+
) -> PIL.Image.Image:
|
| 211 |
+
"""
|
| 212 |
+
Preprocess an image or batch of images.
|
| 213 |
+
|
| 214 |
+
Args:
|
| 215 |
+
images (`ImageInput`):
|
| 216 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 217 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 218 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 219 |
+
Whether to resize the image.
|
| 220 |
+
size (`dict[str, int]`, *optional*, defaults to `self.size`):
|
| 221 |
+
Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
|
| 222 |
+
the longest edge resized to keep the input aspect ratio.
|
| 223 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 224 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 225 |
+
has an effect if `do_resize` is set to `True`.
|
| 226 |
+
do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
|
| 227 |
+
Whether to center crop the image.
|
| 228 |
+
crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
|
| 229 |
+
Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
|
| 230 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 231 |
+
Whether to rescale the image.
|
| 232 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 233 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 234 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 235 |
+
Whether to normalize the image.
|
| 236 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
|
| 237 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 238 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
|
| 239 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
| 240 |
+
`True`.
|
| 241 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 242 |
+
Whether to convert the image to RGB.
|
| 243 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 244 |
+
The type of tensors to return. Can be one of:
|
| 245 |
+
- Unset: Return a list of `np.ndarray`.
|
| 246 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 247 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 248 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 249 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 250 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 251 |
+
The channel dimension format for the output image. Can be one of:
|
| 252 |
+
- `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 253 |
+
- `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 254 |
+
- Unset: defaults to the channel dimension format of the input image.
|
| 255 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 256 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 257 |
+
from the input image. Can be one of:
|
| 258 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 259 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 260 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 261 |
+
"""
|
| 262 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 263 |
+
size = size if size is not None else self.size
|
| 264 |
+
size = get_size_dict(size, param_name="size", default_to_square=False)
|
| 265 |
+
resample = resample if resample is not None else self.resample
|
| 266 |
+
do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
|
| 267 |
+
crop_size = crop_size if crop_size is not None else self.crop_size
|
| 268 |
+
crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
|
| 269 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 270 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 271 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 272 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 273 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 274 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 275 |
+
|
| 276 |
+
images = make_flat_list_of_images(images)
|
| 277 |
+
|
| 278 |
+
validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
|
| 279 |
+
|
| 280 |
+
if not valid_images(images):
|
| 281 |
+
raise ValueError(
|
| 282 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 283 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 284 |
+
)
|
| 285 |
+
validate_preprocess_arguments(
|
| 286 |
+
do_rescale=do_rescale,
|
| 287 |
+
rescale_factor=rescale_factor,
|
| 288 |
+
do_normalize=do_normalize,
|
| 289 |
+
image_mean=image_mean,
|
| 290 |
+
image_std=image_std,
|
| 291 |
+
do_center_crop=do_center_crop,
|
| 292 |
+
crop_size=crop_size,
|
| 293 |
+
do_resize=do_resize,
|
| 294 |
+
size=size,
|
| 295 |
+
resample=resample,
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
# PIL RGBA images are converted to RGB
|
| 299 |
+
if do_convert_rgb:
|
| 300 |
+
images = [convert_to_rgb(image) for image in images]
|
| 301 |
+
|
| 302 |
+
# All transformations expect numpy arrays.
|
| 303 |
+
images = [to_numpy_array(image) for image in images]
|
| 304 |
+
|
| 305 |
+
if do_rescale and is_scaled_image(images[0]):
|
| 306 |
+
logger.warning_once(
|
| 307 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 308 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
if input_data_format is None:
|
| 312 |
+
# We assume that all images have the same channel dimension format.
|
| 313 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 314 |
+
|
| 315 |
+
all_images = []
|
| 316 |
+
for image in images:
|
| 317 |
+
if do_resize:
|
| 318 |
+
image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
| 319 |
+
|
| 320 |
+
if do_center_crop:
|
| 321 |
+
image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
|
| 322 |
+
|
| 323 |
+
if do_rescale:
|
| 324 |
+
image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 325 |
+
|
| 326 |
+
if do_normalize:
|
| 327 |
+
image = self.normalize(
|
| 328 |
+
image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
all_images.append(image)
|
| 332 |
+
images = [
|
| 333 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 334 |
+
for image in all_images
|
| 335 |
+
]
|
| 336 |
+
|
| 337 |
+
data = {"pixel_values": images}
|
| 338 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
__all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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 Google AI, Ross Wightman, The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch ViT Hybrid model."""
|
| 16 |
+
|
| 17 |
+
import collections.abc
|
| 18 |
+
import math
|
| 19 |
+
from typing import Optional, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
|
| 24 |
+
from ....activations import ACT2FN
|
| 25 |
+
from ....modeling_layers import GradientCheckpointingLayer
|
| 26 |
+
from ....modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
|
| 27 |
+
from ....modeling_utils import PreTrainedModel
|
| 28 |
+
from ....pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
|
| 29 |
+
from ....utils import (
|
| 30 |
+
add_code_sample_docstrings,
|
| 31 |
+
add_start_docstrings,
|
| 32 |
+
add_start_docstrings_to_model_forward,
|
| 33 |
+
logging,
|
| 34 |
+
torch_int,
|
| 35 |
+
)
|
| 36 |
+
from ....utils.backbone_utils import load_backbone
|
| 37 |
+
from .configuration_vit_hybrid import ViTHybridConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
# General docstring
|
| 43 |
+
_CONFIG_FOR_DOC = "ViTHybridConfig"
|
| 44 |
+
|
| 45 |
+
# Base docstring
|
| 46 |
+
_CHECKPOINT_FOR_DOC = "google/vit-hybrid-base-bit-384"
|
| 47 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 197, 768]
|
| 48 |
+
|
| 49 |
+
# Image classification docstring
|
| 50 |
+
_IMAGE_CLASS_CHECKPOINT = "google/vit-hybrid-base-bit-384"
|
| 51 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class ViTHybridEmbeddings(nn.Module):
|
| 55 |
+
"""
|
| 56 |
+
Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(self, config: ViTHybridConfig, use_mask_token: bool = False) -> None:
|
| 60 |
+
super().__init__()
|
| 61 |
+
|
| 62 |
+
self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 63 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None
|
| 64 |
+
self.patch_embeddings = ViTHybridPatchEmbeddings(config)
|
| 65 |
+
num_patches = self.patch_embeddings.num_patches
|
| 66 |
+
self.position_embeddings = nn.Parameter(torch.randn(1, num_patches + 1, config.hidden_size))
|
| 67 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 68 |
+
self.patch_size = config.patch_size
|
| 69 |
+
self.config = config
|
| 70 |
+
|
| 71 |
+
# Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding
|
| 72 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 73 |
+
"""
|
| 74 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
|
| 75 |
+
images. This method is also adapted to support torch.jit tracing.
|
| 76 |
+
|
| 77 |
+
Adapted from:
|
| 78 |
+
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
|
| 79 |
+
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
num_patches = embeddings.shape[1] - 1
|
| 83 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
| 84 |
+
|
| 85 |
+
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
|
| 86 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 87 |
+
return self.position_embeddings
|
| 88 |
+
|
| 89 |
+
class_pos_embed = self.position_embeddings[:, :1]
|
| 90 |
+
patch_pos_embed = self.position_embeddings[:, 1:]
|
| 91 |
+
|
| 92 |
+
dim = embeddings.shape[-1]
|
| 93 |
+
|
| 94 |
+
new_height = height // self.patch_size
|
| 95 |
+
new_width = width // self.patch_size
|
| 96 |
+
|
| 97 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 98 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 99 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 100 |
+
|
| 101 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 102 |
+
patch_pos_embed,
|
| 103 |
+
size=(new_height, new_width),
|
| 104 |
+
mode="bicubic",
|
| 105 |
+
align_corners=False,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 109 |
+
|
| 110 |
+
return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
|
| 111 |
+
|
| 112 |
+
def forward(
|
| 113 |
+
self,
|
| 114 |
+
pixel_values: torch.Tensor,
|
| 115 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
| 116 |
+
interpolate_pos_encoding: bool = False,
|
| 117 |
+
) -> torch.Tensor:
|
| 118 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 119 |
+
embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
|
| 120 |
+
|
| 121 |
+
if bool_masked_pos is not None:
|
| 122 |
+
seq_length = embeddings.shape[1]
|
| 123 |
+
mask_tokens = self.mask_token.expand(batch_size, seq_length, -1)
|
| 124 |
+
# replace the masked visual tokens by mask_tokens
|
| 125 |
+
mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
|
| 126 |
+
embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
|
| 127 |
+
|
| 128 |
+
# add the [CLS] token to the embedded patch tokens
|
| 129 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 130 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
| 131 |
+
|
| 132 |
+
# add positional encoding to each token
|
| 133 |
+
if interpolate_pos_encoding:
|
| 134 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 135 |
+
else:
|
| 136 |
+
embeddings = embeddings + self.position_embeddings
|
| 137 |
+
|
| 138 |
+
embeddings = self.dropout(embeddings)
|
| 139 |
+
|
| 140 |
+
return embeddings
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class ViTHybridPatchEmbeddings(nn.Module):
|
| 144 |
+
"""
|
| 145 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 146 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 147 |
+
Transformer.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
def __init__(self, config, feature_size=None):
|
| 151 |
+
super().__init__()
|
| 152 |
+
image_size, patch_size = config.image_size, config.patch_size
|
| 153 |
+
num_channels, hidden_size = config.num_channels, config.hidden_size
|
| 154 |
+
|
| 155 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 156 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 157 |
+
|
| 158 |
+
self.backbone = load_backbone(config)
|
| 159 |
+
if self.backbone.config.model_type != "bit":
|
| 160 |
+
raise ValueError(f"Backbone model type {self.backbone.model_type} is not supported.")
|
| 161 |
+
feature_dim = self.backbone.channels[-1]
|
| 162 |
+
|
| 163 |
+
if feature_size is None:
|
| 164 |
+
feature_map = config.backbone_featmap_shape
|
| 165 |
+
|
| 166 |
+
feature_size = feature_map[-2:]
|
| 167 |
+
feature_dim = feature_map[1]
|
| 168 |
+
else:
|
| 169 |
+
feature_size = (
|
| 170 |
+
feature_size if isinstance(feature_size, collections.abc.Iterable) else (feature_size, feature_size)
|
| 171 |
+
)
|
| 172 |
+
feature_dim = self.backbone.channels[-1]
|
| 173 |
+
|
| 174 |
+
self.grid_size = (feature_size[0] // patch_size[0], feature_size[1] // patch_size[1])
|
| 175 |
+
self.num_patches = self.grid_size[0] * self.grid_size[1]
|
| 176 |
+
self.image_size = image_size
|
| 177 |
+
self.patch_size = patch_size
|
| 178 |
+
self.num_channels = num_channels
|
| 179 |
+
|
| 180 |
+
self.projection = nn.Conv2d(feature_dim, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 181 |
+
|
| 182 |
+
def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
|
| 183 |
+
_, num_channels, height, width = pixel_values.shape
|
| 184 |
+
if num_channels != self.num_channels:
|
| 185 |
+
raise ValueError(
|
| 186 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 187 |
+
)
|
| 188 |
+
if not interpolate_pos_encoding:
|
| 189 |
+
if height != self.image_size[0] or width != self.image_size[1]:
|
| 190 |
+
raise ValueError(
|
| 191 |
+
f"Input image size ({height}*{width}) doesn't match model"
|
| 192 |
+
f" ({self.image_size[0]}*{self.image_size[1]})."
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
features = self.backbone(pixel_values).feature_maps[-1]
|
| 196 |
+
embeddings = self.projection(features).flatten(2).transpose(1, 2)
|
| 197 |
+
|
| 198 |
+
return embeddings
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class ViTHybridSelfAttention(nn.Module):
|
| 202 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 203 |
+
super().__init__()
|
| 204 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 205 |
+
raise ValueError(
|
| 206 |
+
f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
|
| 207 |
+
f"heads {config.num_attention_heads}."
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
self.num_attention_heads = config.num_attention_heads
|
| 211 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 212 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 213 |
+
|
| 214 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 215 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 216 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 217 |
+
|
| 218 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 219 |
+
|
| 220 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 221 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 222 |
+
x = x.view(new_x_shape)
|
| 223 |
+
return x.permute(0, 2, 1, 3)
|
| 224 |
+
|
| 225 |
+
def forward(
|
| 226 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 227 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
|
| 228 |
+
mixed_query_layer = self.query(hidden_states)
|
| 229 |
+
|
| 230 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 231 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 232 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 233 |
+
|
| 234 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 235 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 236 |
+
|
| 237 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 238 |
+
|
| 239 |
+
# Normalize the attention scores to probabilities.
|
| 240 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 241 |
+
|
| 242 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 243 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 244 |
+
attention_probs = self.dropout(attention_probs)
|
| 245 |
+
|
| 246 |
+
# Mask heads if we want to
|
| 247 |
+
if head_mask is not None:
|
| 248 |
+
attention_probs = attention_probs * head_mask
|
| 249 |
+
|
| 250 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 251 |
+
|
| 252 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 253 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 254 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 255 |
+
|
| 256 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 257 |
+
|
| 258 |
+
return outputs
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class ViTHybridSdpaSelfAttention(ViTHybridSelfAttention):
|
| 262 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 263 |
+
super().__init__(config)
|
| 264 |
+
self.attention_probs_dropout_prob = config.attention_probs_dropout_prob
|
| 265 |
+
|
| 266 |
+
def forward(
|
| 267 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 268 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
|
| 269 |
+
mixed_query_layer = self.query(hidden_states)
|
| 270 |
+
|
| 271 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 272 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 273 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 274 |
+
|
| 275 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(
|
| 276 |
+
query_layer,
|
| 277 |
+
key_layer,
|
| 278 |
+
value_layer,
|
| 279 |
+
head_mask,
|
| 280 |
+
self.attention_probs_dropout_prob if self.training else 0.0,
|
| 281 |
+
is_causal=False,
|
| 282 |
+
scale=None,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 286 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 287 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 288 |
+
|
| 289 |
+
return context_layer, None
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
class ViTHybridSelfOutput(nn.Module):
|
| 293 |
+
"""
|
| 294 |
+
The residual connection is defined in ViTHybridLayer instead of here (as is the case with other models), due to the
|
| 295 |
+
layernorm applied before each block.
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 299 |
+
super().__init__()
|
| 300 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 301 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 302 |
+
|
| 303 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 304 |
+
hidden_states = self.dense(hidden_states)
|
| 305 |
+
hidden_states = self.dropout(hidden_states)
|
| 306 |
+
|
| 307 |
+
return hidden_states
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
class ViTHybridAttention(nn.Module):
|
| 311 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 312 |
+
super().__init__()
|
| 313 |
+
self.attention = ViTHybridSelfAttention(config)
|
| 314 |
+
self.output = ViTHybridSelfOutput(config)
|
| 315 |
+
self.pruned_heads = set()
|
| 316 |
+
|
| 317 |
+
def prune_heads(self, heads: set[int]) -> None:
|
| 318 |
+
if len(heads) == 0:
|
| 319 |
+
return
|
| 320 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 321 |
+
heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
# Prune linear layers
|
| 325 |
+
self.attention.query = prune_linear_layer(self.attention.query, index)
|
| 326 |
+
self.attention.key = prune_linear_layer(self.attention.key, index)
|
| 327 |
+
self.attention.value = prune_linear_layer(self.attention.value, index)
|
| 328 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 329 |
+
|
| 330 |
+
# Update hyper params and store pruned heads
|
| 331 |
+
self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
|
| 332 |
+
self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
|
| 333 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 334 |
+
|
| 335 |
+
def forward(
|
| 336 |
+
self,
|
| 337 |
+
hidden_states: torch.Tensor,
|
| 338 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 339 |
+
output_attentions: bool = False,
|
| 340 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
|
| 341 |
+
self_outputs = self.attention(hidden_states, head_mask, output_attentions)
|
| 342 |
+
|
| 343 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 344 |
+
|
| 345 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 346 |
+
return outputs
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class ViTHybridSdpaAttention(ViTHybridAttention):
|
| 350 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 351 |
+
super().__init__(config)
|
| 352 |
+
self.attention = ViTHybridSdpaSelfAttention(config)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
class ViTHybridIntermediate(nn.Module):
|
| 356 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 357 |
+
super().__init__()
|
| 358 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 359 |
+
if isinstance(config.hidden_act, str):
|
| 360 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 361 |
+
else:
|
| 362 |
+
self.intermediate_act_fn = config.hidden_act
|
| 363 |
+
|
| 364 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 365 |
+
hidden_states = self.dense(hidden_states)
|
| 366 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 367 |
+
|
| 368 |
+
return hidden_states
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class ViTHybridOutput(nn.Module):
|
| 372 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 373 |
+
super().__init__()
|
| 374 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 375 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 376 |
+
|
| 377 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 378 |
+
hidden_states = self.dense(hidden_states)
|
| 379 |
+
hidden_states = self.dropout(hidden_states)
|
| 380 |
+
|
| 381 |
+
hidden_states = hidden_states + input_tensor
|
| 382 |
+
|
| 383 |
+
return hidden_states
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
VIT_HYBRID_ATTENTION_CLASSES = {
|
| 387 |
+
"eager": ViTHybridAttention,
|
| 388 |
+
"sdpa": ViTHybridSdpaAttention,
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
class ViTHybridLayer(GradientCheckpointingLayer):
|
| 393 |
+
"""This corresponds to the Block class in the timm implementation."""
|
| 394 |
+
|
| 395 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 396 |
+
super().__init__()
|
| 397 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 398 |
+
self.seq_len_dim = 1
|
| 399 |
+
self.attention = VIT_HYBRID_ATTENTION_CLASSES[config._attn_implementation](config)
|
| 400 |
+
self.intermediate = ViTHybridIntermediate(config)
|
| 401 |
+
self.output = ViTHybridOutput(config)
|
| 402 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 403 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 404 |
+
|
| 405 |
+
def forward(
|
| 406 |
+
self,
|
| 407 |
+
hidden_states: torch.Tensor,
|
| 408 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 409 |
+
output_attentions: bool = False,
|
| 410 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
|
| 411 |
+
self_attention_outputs = self.attention(
|
| 412 |
+
self.layernorm_before(hidden_states), # in ViTHybrid, layernorm is applied before self-attention
|
| 413 |
+
head_mask,
|
| 414 |
+
output_attentions=output_attentions,
|
| 415 |
+
)
|
| 416 |
+
attention_output = self_attention_outputs[0]
|
| 417 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 418 |
+
|
| 419 |
+
# first residual connection
|
| 420 |
+
# We assign to correct device for `accelerate`, check: https://github.com/huggingface/transformers/pull/20705/
|
| 421 |
+
hidden_states = attention_output + hidden_states.to(attention_output.device)
|
| 422 |
+
|
| 423 |
+
# in ViTHybrid, layernorm is also applied after self-attention
|
| 424 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 425 |
+
layer_output = self.intermediate(layer_output)
|
| 426 |
+
|
| 427 |
+
# second residual connection is done here
|
| 428 |
+
layer_output = self.output(layer_output, hidden_states)
|
| 429 |
+
|
| 430 |
+
outputs = (layer_output,) + outputs
|
| 431 |
+
|
| 432 |
+
return outputs
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
class ViTHybridEncoder(nn.Module):
|
| 436 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 437 |
+
super().__init__()
|
| 438 |
+
self.config = config
|
| 439 |
+
self.layer = nn.ModuleList([ViTHybridLayer(config) for _ in range(config.num_hidden_layers)])
|
| 440 |
+
self.gradient_checkpointing = False
|
| 441 |
+
|
| 442 |
+
def forward(
|
| 443 |
+
self,
|
| 444 |
+
hidden_states: torch.Tensor,
|
| 445 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 446 |
+
output_attentions: bool = False,
|
| 447 |
+
output_hidden_states: bool = False,
|
| 448 |
+
return_dict: bool = True,
|
| 449 |
+
) -> Union[tuple, BaseModelOutput]:
|
| 450 |
+
all_hidden_states = () if output_hidden_states else None
|
| 451 |
+
all_self_attentions = () if output_attentions else None
|
| 452 |
+
|
| 453 |
+
for i, layer_module in enumerate(self.layer):
|
| 454 |
+
if output_hidden_states:
|
| 455 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 456 |
+
|
| 457 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 458 |
+
|
| 459 |
+
layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions)
|
| 460 |
+
|
| 461 |
+
hidden_states = layer_outputs[0]
|
| 462 |
+
|
| 463 |
+
if output_attentions:
|
| 464 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 465 |
+
|
| 466 |
+
if output_hidden_states:
|
| 467 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 468 |
+
|
| 469 |
+
if not return_dict:
|
| 470 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
| 471 |
+
return BaseModelOutput(
|
| 472 |
+
last_hidden_state=hidden_states,
|
| 473 |
+
hidden_states=all_hidden_states,
|
| 474 |
+
attentions=all_self_attentions,
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class ViTHybridPreTrainedModel(PreTrainedModel):
|
| 479 |
+
"""
|
| 480 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 481 |
+
models.
|
| 482 |
+
"""
|
| 483 |
+
|
| 484 |
+
config: ViTHybridConfig
|
| 485 |
+
base_model_prefix = "vit"
|
| 486 |
+
main_input_name = "pixel_values"
|
| 487 |
+
supports_gradient_checkpointing = True
|
| 488 |
+
_no_split_modules = ["ViTHybridEmbeddings", "ViTHybridLayer"]
|
| 489 |
+
_supports_sdpa = True
|
| 490 |
+
|
| 491 |
+
def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
|
| 492 |
+
"""Initialize the weights"""
|
| 493 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 494 |
+
# Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
|
| 495 |
+
# `trunc_normal_cpu` not implemented in `half` issues
|
| 496 |
+
module.weight.data = nn.init.trunc_normal_(
|
| 497 |
+
module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
|
| 498 |
+
).to(module.weight.dtype)
|
| 499 |
+
if module.bias is not None:
|
| 500 |
+
module.bias.data.zero_()
|
| 501 |
+
elif isinstance(module, nn.LayerNorm):
|
| 502 |
+
module.bias.data.zero_()
|
| 503 |
+
module.weight.data.fill_(1.0)
|
| 504 |
+
elif isinstance(module, ViTHybridEmbeddings):
|
| 505 |
+
module.position_embeddings.data = nn.init.trunc_normal_(
|
| 506 |
+
module.position_embeddings.data.to(torch.float32),
|
| 507 |
+
mean=0.0,
|
| 508 |
+
std=self.config.initializer_range,
|
| 509 |
+
).to(module.position_embeddings.dtype)
|
| 510 |
+
module.cls_token.data = nn.init.trunc_normal_(
|
| 511 |
+
module.cls_token.data.to(torch.float32),
|
| 512 |
+
mean=0.0,
|
| 513 |
+
std=self.config.initializer_range,
|
| 514 |
+
).to(module.cls_token.dtype)
|
| 515 |
+
module.mask_token.data.zero_()
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
VIT_START_DOCSTRING = r"""
|
| 519 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 520 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 521 |
+
behavior.
|
| 522 |
+
|
| 523 |
+
Parameters:
|
| 524 |
+
config ([`ViTHybridConfig`]): Model configuration class with all the parameters of the model.
|
| 525 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 526 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 527 |
+
"""
|
| 528 |
+
|
| 529 |
+
VIT_INPUTS_DOCSTRING = r"""
|
| 530 |
+
Args:
|
| 531 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 532 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 533 |
+
[`ViTHybridImageProcessor.__call__`] for details.
|
| 534 |
+
|
| 535 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 536 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 537 |
+
|
| 538 |
+
- 1 indicates the head is **not masked**,
|
| 539 |
+
- 0 indicates the head is **masked**.
|
| 540 |
+
|
| 541 |
+
output_attentions (`bool`, *optional*):
|
| 542 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 543 |
+
tensors for more detail.
|
| 544 |
+
output_hidden_states (`bool`, *optional*):
|
| 545 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 546 |
+
more detail.
|
| 547 |
+
return_dict (`bool`, *optional*):
|
| 548 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 549 |
+
"""
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
@add_start_docstrings(
|
| 553 |
+
"The bare ViT Hybrid Model transformer outputting raw hidden-states without any specific head on top.",
|
| 554 |
+
VIT_START_DOCSTRING,
|
| 555 |
+
)
|
| 556 |
+
class ViTHybridModel(ViTHybridPreTrainedModel):
|
| 557 |
+
def __init__(self, config: ViTHybridConfig, add_pooling_layer: bool = True, use_mask_token: bool = False):
|
| 558 |
+
super().__init__(config)
|
| 559 |
+
self.config = config
|
| 560 |
+
|
| 561 |
+
self.embeddings = ViTHybridEmbeddings(config, use_mask_token=use_mask_token)
|
| 562 |
+
self.encoder = ViTHybridEncoder(config)
|
| 563 |
+
|
| 564 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 565 |
+
self.pooler = ViTHybridPooler(config) if add_pooling_layer else None
|
| 566 |
+
|
| 567 |
+
# Initialize weights and apply final processing
|
| 568 |
+
self.post_init()
|
| 569 |
+
|
| 570 |
+
def get_input_embeddings(self) -> ViTHybridPatchEmbeddings:
|
| 571 |
+
return self.embeddings.patch_embeddings
|
| 572 |
+
|
| 573 |
+
def _prune_heads(self, heads_to_prune: dict[int, list[int]]) -> None:
|
| 574 |
+
"""
|
| 575 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 576 |
+
class PreTrainedModel
|
| 577 |
+
"""
|
| 578 |
+
for layer, heads in heads_to_prune.items():
|
| 579 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 580 |
+
|
| 581 |
+
@add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING)
|
| 582 |
+
@add_code_sample_docstrings(
|
| 583 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 584 |
+
output_type=BaseModelOutputWithPooling,
|
| 585 |
+
config_class=_CONFIG_FOR_DOC,
|
| 586 |
+
modality="vision",
|
| 587 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 588 |
+
)
|
| 589 |
+
def forward(
|
| 590 |
+
self,
|
| 591 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 592 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
| 593 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 594 |
+
output_attentions: Optional[bool] = None,
|
| 595 |
+
output_hidden_states: Optional[bool] = None,
|
| 596 |
+
interpolate_pos_encoding: Optional[bool] = None,
|
| 597 |
+
return_dict: Optional[bool] = None,
|
| 598 |
+
) -> Union[tuple, BaseModelOutputWithPooling]:
|
| 599 |
+
r"""
|
| 600 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
|
| 601 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 602 |
+
"""
|
| 603 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 604 |
+
output_hidden_states = (
|
| 605 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 606 |
+
)
|
| 607 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 608 |
+
|
| 609 |
+
if pixel_values is None:
|
| 610 |
+
raise ValueError("You have to specify pixel_values")
|
| 611 |
+
|
| 612 |
+
# Prepare head mask if needed
|
| 613 |
+
# 1.0 in head_mask indicate we keep the head
|
| 614 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 615 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 616 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 617 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 618 |
+
|
| 619 |
+
# TODO: maybe have a cleaner way to cast the input (from `ImageProcessor` side?)
|
| 620 |
+
expected_dtype = self.embeddings.patch_embeddings.projection.weight.dtype
|
| 621 |
+
if pixel_values.dtype != expected_dtype:
|
| 622 |
+
pixel_values = pixel_values.to(expected_dtype)
|
| 623 |
+
|
| 624 |
+
embedding_output = self.embeddings(
|
| 625 |
+
pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
encoder_outputs = self.encoder(
|
| 629 |
+
embedding_output,
|
| 630 |
+
head_mask=head_mask,
|
| 631 |
+
output_attentions=output_attentions,
|
| 632 |
+
output_hidden_states=output_hidden_states,
|
| 633 |
+
return_dict=return_dict,
|
| 634 |
+
)
|
| 635 |
+
sequence_output = encoder_outputs[0]
|
| 636 |
+
sequence_output = self.layernorm(sequence_output)
|
| 637 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 638 |
+
|
| 639 |
+
if not return_dict:
|
| 640 |
+
head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
|
| 641 |
+
return head_outputs + encoder_outputs[1:]
|
| 642 |
+
|
| 643 |
+
return BaseModelOutputWithPooling(
|
| 644 |
+
last_hidden_state=sequence_output,
|
| 645 |
+
pooler_output=pooled_output,
|
| 646 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 647 |
+
attentions=encoder_outputs.attentions,
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
class ViTHybridPooler(nn.Module):
|
| 652 |
+
def __init__(self, config: ViTHybridConfig):
|
| 653 |
+
super().__init__()
|
| 654 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 655 |
+
self.activation = nn.Tanh()
|
| 656 |
+
|
| 657 |
+
def forward(self, hidden_states):
|
| 658 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 659 |
+
# to the first token.
|
| 660 |
+
first_token_tensor = hidden_states[:, 0]
|
| 661 |
+
pooled_output = self.dense(first_token_tensor)
|
| 662 |
+
pooled_output = self.activation(pooled_output)
|
| 663 |
+
return pooled_output
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
@add_start_docstrings(
|
| 667 |
+
"""
|
| 668 |
+
ViT Hybrid Model transformer with an image classification head on top (a linear layer on top of the final hidden
|
| 669 |
+
state of the [CLS] token) e.g. for ImageNet.
|
| 670 |
+
""",
|
| 671 |
+
VIT_START_DOCSTRING,
|
| 672 |
+
)
|
| 673 |
+
class ViTHybridForImageClassification(ViTHybridPreTrainedModel):
|
| 674 |
+
def __init__(self, config: ViTHybridConfig) -> None:
|
| 675 |
+
super().__init__(config)
|
| 676 |
+
|
| 677 |
+
self.num_labels = config.num_labels
|
| 678 |
+
self.vit = ViTHybridModel(config, add_pooling_layer=False)
|
| 679 |
+
|
| 680 |
+
# Classifier head
|
| 681 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 682 |
+
|
| 683 |
+
# Initialize weights and apply final processing
|
| 684 |
+
self.post_init()
|
| 685 |
+
|
| 686 |
+
@add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING)
|
| 687 |
+
@add_code_sample_docstrings(
|
| 688 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
| 689 |
+
output_type=ImageClassifierOutput,
|
| 690 |
+
config_class=_CONFIG_FOR_DOC,
|
| 691 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
| 692 |
+
)
|
| 693 |
+
def forward(
|
| 694 |
+
self,
|
| 695 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 696 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 697 |
+
labels: Optional[torch.Tensor] = None,
|
| 698 |
+
output_attentions: Optional[bool] = None,
|
| 699 |
+
output_hidden_states: Optional[bool] = None,
|
| 700 |
+
interpolate_pos_encoding: Optional[bool] = None,
|
| 701 |
+
return_dict: Optional[bool] = None,
|
| 702 |
+
) -> Union[tuple, ImageClassifierOutput]:
|
| 703 |
+
r"""
|
| 704 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 705 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 706 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 707 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 708 |
+
"""
|
| 709 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 710 |
+
|
| 711 |
+
outputs = self.vit(
|
| 712 |
+
pixel_values,
|
| 713 |
+
head_mask=head_mask,
|
| 714 |
+
output_attentions=output_attentions,
|
| 715 |
+
output_hidden_states=output_hidden_states,
|
| 716 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 717 |
+
return_dict=return_dict,
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
sequence_output = outputs[0]
|
| 721 |
+
|
| 722 |
+
logits = self.classifier(sequence_output[:, 0, :])
|
| 723 |
+
|
| 724 |
+
loss = None
|
| 725 |
+
if labels is not None:
|
| 726 |
+
loss = self.loss_function(labels, logits, self.config)
|
| 727 |
+
|
| 728 |
+
if not return_dict:
|
| 729 |
+
output = (logits,) + outputs[1:]
|
| 730 |
+
return ((loss,) + output) if loss is not None else output
|
| 731 |
+
|
| 732 |
+
return ImageClassifierOutput(
|
| 733 |
+
loss=loss,
|
| 734 |
+
logits=logits,
|
| 735 |
+
hidden_states=outputs.hidden_states,
|
| 736 |
+
attentions=outputs.attentions,
|
| 737 |
+
)
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
__all__ = ["ViTHybridForImageClassification", "ViTHybridModel", "ViTHybridPreTrainedModel"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/xlm_prophetnet/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ....utils import _LazyModule
|
| 17 |
+
from ....utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_xlm_prophetnet import *
|
| 22 |
+
from .modeling_xlm_prophetnet import *
|
| 23 |
+
from .tokenization_xlm_prophetnet import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/xlm_prophetnet/configuration_xlm_prophetnet.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The Microsoft 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 |
+
"""XLM-ProphetNet model configuration"""
|
| 16 |
+
|
| 17 |
+
from typing import Callable, Optional, Union
|
| 18 |
+
|
| 19 |
+
from ....configuration_utils import PretrainedConfig
|
| 20 |
+
from ....utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class XLMProphetNetConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`XLMProphetNetModel`]. It is used to instantiate a
|
| 29 |
+
XLMProphetNet model according to the specified arguments, defining the model architecture. Instantiating a
|
| 30 |
+
configuration with the defaults will yield a similar configuration to that of the XLMProphetNet
|
| 31 |
+
[microsoft/xprophetnet-large-wiki100-cased](https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased)
|
| 32 |
+
architecture.
|
| 33 |
+
|
| 34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 35 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
activation_dropout (`float`, *optional*, defaults to 0.1):
|
| 39 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 40 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 41 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 42 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 43 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 44 |
+
Vocabulary size of the ProphetNET model. Defines the number of different tokens that can be represented by
|
| 45 |
+
the `inputs_ids` passed when calling [`XLMProphetNetModel`].
|
| 46 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
| 47 |
+
Dimensionality of the layers and the pooler layer.
|
| 48 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 49 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
|
| 50 |
+
num_encoder_layers (`int`, *optional*, defaults to 12):
|
| 51 |
+
Number of encoder layers.
|
| 52 |
+
num_encoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 53 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 54 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 55 |
+
Dimensionality of the `intermediate` (often named feed-forward) layer in decoder.
|
| 56 |
+
num_decoder_layers (`int`, *optional*, defaults to 12):
|
| 57 |
+
Number of decoder layers.
|
| 58 |
+
num_decoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 59 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 60 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 61 |
+
The dropout ratio for the attention probabilities.
|
| 62 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 63 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 64 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 65 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 66 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 67 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 68 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 69 |
+
add_cross_attention (`bool`, *optional*, defaults to `True`):
|
| 70 |
+
Whether cross-attention layers should be added to the model.
|
| 71 |
+
is_encoder_decoder (`bool`, *optional*, defaults to `True`):
|
| 72 |
+
Whether this is an encoder/decoder model.
|
| 73 |
+
pad_token_id (`int`, *optional*, defaults to 1)
|
| 74 |
+
Padding token id.
|
| 75 |
+
bos_token_id (`int`, *optional*, defaults to 0)
|
| 76 |
+
Beginning of stream token id.
|
| 77 |
+
eos_token_id (`int`, *optional*, defaults to 2)
|
| 78 |
+
End of stream token id.
|
| 79 |
+
ngram (`int`, *optional*, defaults to 2)
|
| 80 |
+
Number of future tokens to predict. Set to 1 to be same as traditional Language model to predict next first
|
| 81 |
+
token.
|
| 82 |
+
num_buckets (`int`, *optional*, defaults to 32)
|
| 83 |
+
The number of buckets to use for each attention layer. This is for relative position calculation. See the
|
| 84 |
+
[T5 paper](see https://huggingface.co/papers/1910.10683) for more details.
|
| 85 |
+
relative_max_distance (`int`, *optional*, defaults to 128)
|
| 86 |
+
Relative distances greater than this number will be put into the last same bucket. This is for relative
|
| 87 |
+
position calculation. See the [T5 paper](see https://huggingface.co/papers/1910.10683) for more details.
|
| 88 |
+
disable_ngram_loss (`bool`, *optional*, defaults to `False`):
|
| 89 |
+
Whether be trained predicting only the next first token.
|
| 90 |
+
eps (`float`, *optional*, defaults to 0.0):
|
| 91 |
+
Controls the `epsilon` parameter value for label smoothing in the loss calculation. If set to 0, no label
|
| 92 |
+
smoothing is performed.
|
| 93 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 94 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
model_type = "xlm-prophetnet"
|
| 98 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 99 |
+
attribute_map = {
|
| 100 |
+
"num_attention_heads": "num_encoder_attention_heads",
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
def __init__(
|
| 104 |
+
self,
|
| 105 |
+
activation_dropout: Optional[float] = 0.1,
|
| 106 |
+
activation_function: Optional[Union[str, Callable]] = "gelu",
|
| 107 |
+
vocab_size: Optional[int] = 30522,
|
| 108 |
+
hidden_size: Optional[int] = 1024,
|
| 109 |
+
encoder_ffn_dim: Optional[int] = 4096,
|
| 110 |
+
num_encoder_layers: Optional[int] = 12,
|
| 111 |
+
num_encoder_attention_heads: Optional[int] = 16,
|
| 112 |
+
decoder_ffn_dim: Optional[int] = 4096,
|
| 113 |
+
num_decoder_layers: Optional[int] = 12,
|
| 114 |
+
num_decoder_attention_heads: Optional[int] = 16,
|
| 115 |
+
attention_dropout: Optional[float] = 0.1,
|
| 116 |
+
dropout: Optional[float] = 0.1,
|
| 117 |
+
max_position_embeddings: Optional[int] = 512,
|
| 118 |
+
init_std: Optional[float] = 0.02,
|
| 119 |
+
is_encoder_decoder: Optional[bool] = True,
|
| 120 |
+
add_cross_attention: Optional[bool] = True,
|
| 121 |
+
decoder_start_token_id: Optional[int] = 0,
|
| 122 |
+
ngram: Optional[int] = 2,
|
| 123 |
+
num_buckets: Optional[int] = 32,
|
| 124 |
+
relative_max_distance: Optional[int] = 128,
|
| 125 |
+
disable_ngram_loss: Optional[bool] = False,
|
| 126 |
+
eps: Optional[float] = 0.0,
|
| 127 |
+
use_cache: Optional[bool] = True,
|
| 128 |
+
pad_token_id: Optional[int] = 0,
|
| 129 |
+
bos_token_id: Optional[int] = 1,
|
| 130 |
+
eos_token_id: Optional[int] = 2,
|
| 131 |
+
**kwargs,
|
| 132 |
+
):
|
| 133 |
+
self.vocab_size = vocab_size
|
| 134 |
+
self.hidden_size = hidden_size
|
| 135 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 136 |
+
self.num_encoder_layers = num_encoder_layers
|
| 137 |
+
self.num_encoder_attention_heads = num_encoder_attention_heads
|
| 138 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 139 |
+
self.num_decoder_layers = num_decoder_layers
|
| 140 |
+
self.num_decoder_attention_heads = num_decoder_attention_heads
|
| 141 |
+
self.max_position_embeddings = max_position_embeddings
|
| 142 |
+
self.init_std = init_std # Normal(0, this parameter)
|
| 143 |
+
self.activation_function = activation_function
|
| 144 |
+
|
| 145 |
+
# parameters for xlmprophetnet
|
| 146 |
+
self.ngram = ngram
|
| 147 |
+
self.num_buckets = num_buckets
|
| 148 |
+
self.relative_max_distance = relative_max_distance
|
| 149 |
+
self.disable_ngram_loss = disable_ngram_loss
|
| 150 |
+
self.eps = eps
|
| 151 |
+
|
| 152 |
+
# 3 Types of Dropout
|
| 153 |
+
self.attention_dropout = attention_dropout
|
| 154 |
+
self.activation_dropout = activation_dropout
|
| 155 |
+
self.dropout = dropout
|
| 156 |
+
|
| 157 |
+
self.use_cache = use_cache
|
| 158 |
+
|
| 159 |
+
super().__init__(
|
| 160 |
+
pad_token_id=pad_token_id,
|
| 161 |
+
bos_token_id=bos_token_id,
|
| 162 |
+
eos_token_id=eos_token_id,
|
| 163 |
+
is_encoder_decoder=is_encoder_decoder,
|
| 164 |
+
add_cross_attention=add_cross_attention,
|
| 165 |
+
decoder_start_token_id=decoder_start_token_id,
|
| 166 |
+
**kwargs,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def num_hidden_layers(self) -> int:
|
| 171 |
+
return self.num_encoder_layers + self.num_decoder_layers
|
| 172 |
+
|
| 173 |
+
@num_hidden_layers.setter
|
| 174 |
+
def num_hidden_layers(self, value):
|
| 175 |
+
raise NotImplementedError(
|
| 176 |
+
"This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and"
|
| 177 |
+
" `num_decoder_layers`."
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
__all__ = ["XLMProphetNetConfig"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/xlm_prophetnet/modeling_xlm_prophetnet.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/deprecated/xlm_prophetnet/tokenization_xlm_prophetnet.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The Microsoft 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 |
+
import collections
|
| 17 |
+
import os
|
| 18 |
+
from shutil import copyfile
|
| 19 |
+
from typing import Any, Optional
|
| 20 |
+
|
| 21 |
+
from ....tokenization_utils import PreTrainedTokenizer
|
| 22 |
+
from ....utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
SPIECE_UNDERLINE = "▁"
|
| 28 |
+
|
| 29 |
+
VOCAB_FILES_NAMES = {"vocab_file": "prophetnet.tokenizer"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def load_vocab(vocab_file):
|
| 33 |
+
"""Loads a vocabulary file into a dictionary."""
|
| 34 |
+
vocab = collections.OrderedDict()
|
| 35 |
+
with open(vocab_file, "r", encoding="utf-8") as reader:
|
| 36 |
+
tokens = reader.readlines()
|
| 37 |
+
for index, token in enumerate(tokens):
|
| 38 |
+
token = token.rstrip("\n")
|
| 39 |
+
vocab[token] = index
|
| 40 |
+
return vocab
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class XLMProphetNetTokenizer(PreTrainedTokenizer):
|
| 44 |
+
"""
|
| 45 |
+
Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
|
| 46 |
+
[SentencePiece](https://github.com/google/sentencepiece).
|
| 47 |
+
|
| 48 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 49 |
+
this superclass for more information regarding those methods.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
vocab_file (`str`):
|
| 53 |
+
Path to the vocabulary file.
|
| 54 |
+
bos_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 55 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 56 |
+
|
| 57 |
+
<Tip>
|
| 58 |
+
|
| 59 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 60 |
+
sequence. The token used is the `cls_token`.
|
| 61 |
+
|
| 62 |
+
</Tip>
|
| 63 |
+
|
| 64 |
+
eos_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 65 |
+
The end of sequence token.
|
| 66 |
+
|
| 67 |
+
<Tip>
|
| 68 |
+
|
| 69 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 70 |
+
The token used is the `sep_token`.
|
| 71 |
+
|
| 72 |
+
</Tip>
|
| 73 |
+
|
| 74 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 75 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 76 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 77 |
+
token of a sequence built with special tokens.
|
| 78 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 79 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 80 |
+
token instead.
|
| 81 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 82 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 83 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 84 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 85 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 86 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 87 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 88 |
+
modeling. This is the token which the model will try to predict.
|
| 89 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 90 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 91 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 92 |
+
to set:
|
| 93 |
+
|
| 94 |
+
- `enable_sampling`: Enable subword regularization.
|
| 95 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 96 |
+
|
| 97 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 98 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 99 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 100 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 101 |
+
|
| 102 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 103 |
+
BPE-dropout.
|
| 104 |
+
|
| 105 |
+
Attributes:
|
| 106 |
+
sp_model (`SentencePieceProcessor`):
|
| 107 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 111 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 112 |
+
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
vocab_file,
|
| 116 |
+
bos_token="[SEP]",
|
| 117 |
+
eos_token="[SEP]",
|
| 118 |
+
sep_token="[SEP]",
|
| 119 |
+
unk_token="[UNK]",
|
| 120 |
+
pad_token="[PAD]",
|
| 121 |
+
cls_token="[CLS]",
|
| 122 |
+
mask_token="[MASK]",
|
| 123 |
+
sp_model_kwargs: Optional[dict[str, Any]] = None,
|
| 124 |
+
**kwargs,
|
| 125 |
+
) -> None:
|
| 126 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 127 |
+
|
| 128 |
+
try:
|
| 129 |
+
import sentencepiece as spm
|
| 130 |
+
except ImportError:
|
| 131 |
+
logger.warning(
|
| 132 |
+
"You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece"
|
| 133 |
+
" pip install sentencepiece"
|
| 134 |
+
)
|
| 135 |
+
raise
|
| 136 |
+
|
| 137 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 138 |
+
self.sp_model.Load(str(vocab_file))
|
| 139 |
+
self.vocab_file = vocab_file
|
| 140 |
+
|
| 141 |
+
# Original fairseq vocab and spm vocab must be "aligned":
|
| 142 |
+
# Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
|
| 143 |
+
# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
|
| 144 |
+
# fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-'
|
| 145 |
+
# spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
|
| 146 |
+
|
| 147 |
+
# put special tokens and [unused] tokens into the vocab
|
| 148 |
+
self.fairseq_tokens_to_ids = {"[PAD]": 0, "[CLS]": 1, "[SEP]": 2, "[UNK]": 3, "[MASK]": 4}
|
| 149 |
+
|
| 150 |
+
for i in range(10):
|
| 151 |
+
tok = f"[unused{i}]"
|
| 152 |
+
self.fairseq_tokens_to_ids[tok] = 5 + i
|
| 153 |
+
|
| 154 |
+
# The first "real" token "," has position 15 in the embedding vocab and position 3 in the spm vocab
|
| 155 |
+
self.fairseq_offset = 12
|
| 156 |
+
self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
|
| 157 |
+
|
| 158 |
+
# TODO ArthurZ fairseq_ids_to_tokens should be removed
|
| 159 |
+
|
| 160 |
+
super().__init__(
|
| 161 |
+
bos_token=bos_token,
|
| 162 |
+
eos_token=eos_token,
|
| 163 |
+
sep_token=sep_token,
|
| 164 |
+
unk_token=unk_token,
|
| 165 |
+
pad_token=pad_token,
|
| 166 |
+
cls_token=cls_token,
|
| 167 |
+
mask_token=mask_token,
|
| 168 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 169 |
+
**kwargs,
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
def __getstate__(self):
|
| 173 |
+
state = self.__dict__.copy()
|
| 174 |
+
state["sp_model"] = None
|
| 175 |
+
return state
|
| 176 |
+
|
| 177 |
+
def __setstate__(self, d):
|
| 178 |
+
self.__dict__ = d
|
| 179 |
+
try:
|
| 180 |
+
import sentencepiece as spm
|
| 181 |
+
except ImportError:
|
| 182 |
+
logger.warning(
|
| 183 |
+
"You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece"
|
| 184 |
+
" pip install sentencepiece"
|
| 185 |
+
)
|
| 186 |
+
raise
|
| 187 |
+
|
| 188 |
+
# for backward compatibility
|
| 189 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 190 |
+
self.sp_model_kwargs = {}
|
| 191 |
+
|
| 192 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 193 |
+
self.sp_model.Load(self.vocab_file)
|
| 194 |
+
|
| 195 |
+
def get_special_tokens_mask(
|
| 196 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
|
| 197 |
+
) -> list[int]:
|
| 198 |
+
"""
|
| 199 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 200 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
token_ids_0 (`list[int]`):
|
| 204 |
+
List of IDs.
|
| 205 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 206 |
+
Optional second list of IDs for sequence pairs.
|
| 207 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 208 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 209 |
+
|
| 210 |
+
Returns:
|
| 211 |
+
`list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
if already_has_special_tokens:
|
| 215 |
+
return super().get_special_tokens_mask(
|
| 216 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
if token_ids_1 is None:
|
| 220 |
+
return ([0] * len(token_ids_0)) + [1]
|
| 221 |
+
return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 222 |
+
|
| 223 |
+
def create_token_type_ids_from_sequences(
|
| 224 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 225 |
+
) -> list[int]:
|
| 226 |
+
"""
|
| 227 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLMProphetNet
|
| 228 |
+
does not make use of token type ids, therefore a list of zeros is returned.
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
token_ids_0 (`list[int]`):
|
| 232 |
+
List of IDs.
|
| 233 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 234 |
+
Optional second list of IDs for sequence pairs.
|
| 235 |
+
|
| 236 |
+
Returns:
|
| 237 |
+
`list[int]`: List of zeros.
|
| 238 |
+
|
| 239 |
+
"""
|
| 240 |
+
|
| 241 |
+
sep = [self.sep_token_id]
|
| 242 |
+
|
| 243 |
+
if token_ids_1 is None:
|
| 244 |
+
return len(token_ids_0 + sep) * [0]
|
| 245 |
+
return len(token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
|
| 246 |
+
|
| 247 |
+
@property
|
| 248 |
+
def vocab_size(self):
|
| 249 |
+
return len(self.sp_model) + self.fairseq_offset
|
| 250 |
+
|
| 251 |
+
def get_vocab(self):
|
| 252 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 253 |
+
vocab.update(self.added_tokens_encoder)
|
| 254 |
+
return vocab
|
| 255 |
+
|
| 256 |
+
def _tokenize(self, text: str) -> str:
|
| 257 |
+
return self.sp_model.encode(text, out_type=str)
|
| 258 |
+
|
| 259 |
+
def _convert_token_to_id(self, token):
|
| 260 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 261 |
+
if token in self.fairseq_tokens_to_ids:
|
| 262 |
+
return self.fairseq_tokens_to_ids[token]
|
| 263 |
+
spm_id = self.sp_model.PieceToId(token)
|
| 264 |
+
|
| 265 |
+
# Need to return unknown token if the SP model returned 0
|
| 266 |
+
return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
|
| 267 |
+
|
| 268 |
+
def _convert_id_to_token(self, index):
|
| 269 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 270 |
+
if index in self.fairseq_ids_to_tokens:
|
| 271 |
+
return self.fairseq_ids_to_tokens[index]
|
| 272 |
+
return self.sp_model.IdToPiece(index - self.fairseq_offset)
|
| 273 |
+
|
| 274 |
+
def convert_tokens_to_string(self, tokens):
|
| 275 |
+
"""Converts a sequence of tokens (strings for sub-words) in a single string."""
|
| 276 |
+
out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
|
| 277 |
+
return out_string
|
| 278 |
+
|
| 279 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 280 |
+
if not os.path.isdir(save_directory):
|
| 281 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 282 |
+
return
|
| 283 |
+
out_vocab_file = os.path.join(
|
| 284 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 288 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 289 |
+
elif not os.path.isfile(self.vocab_file):
|
| 290 |
+
with open(out_vocab_file, "wb") as fi:
|
| 291 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 292 |
+
fi.write(content_spiece_model)
|
| 293 |
+
|
| 294 |
+
return (out_vocab_file,)
|
| 295 |
+
|
| 296 |
+
def build_inputs_with_special_tokens(
|
| 297 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 298 |
+
) -> list[int]:
|
| 299 |
+
"""
|
| 300 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 301 |
+
adding special tokens. A XLMProphetNet sequence has the following format:
|
| 302 |
+
|
| 303 |
+
- single sequence: `X [SEP]`
|
| 304 |
+
- pair of sequences: `A [SEP] B [SEP]`
|
| 305 |
+
|
| 306 |
+
Args:
|
| 307 |
+
token_ids_0 (`list[int]`):
|
| 308 |
+
List of IDs to which the special tokens will be added
|
| 309 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 310 |
+
Optional second list of IDs for sequence pairs.
|
| 311 |
+
|
| 312 |
+
Returns:
|
| 313 |
+
`list[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 314 |
+
"""
|
| 315 |
+
|
| 316 |
+
if token_ids_1 is None:
|
| 317 |
+
return token_ids_0 + [self.sep_token_id]
|
| 318 |
+
sep = [self.sep_token_id]
|
| 319 |
+
return token_ids_0 + sep + token_ids_1 + sep
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
__all__ = ["XLMProphetNetTokenizer"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/depth_anything/__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_depth_anything import *
|
| 22 |
+
from .modeling_depth_anything 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__)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/depth_anything/configuration_depth_anything.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""DepthAnything model configuration"""
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PretrainedConfig
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
from ...utils.backbone_utils import verify_backbone_config_arguments
|
| 22 |
+
from ..auto.configuration_auto import CONFIG_MAPPING
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class DepthAnythingConfig(PretrainedConfig):
|
| 29 |
+
r"""
|
| 30 |
+
This is the configuration class to store the configuration of a [`DepthAnythingModel`]. It is used to instantiate a DepthAnything
|
| 31 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 32 |
+
defaults will yield a similar configuration to that of the DepthAnything
|
| 33 |
+
[LiheYoung/depth-anything-small-hf](https://huggingface.co/LiheYoung/depth-anything-small-hf) architecture.
|
| 34 |
+
|
| 35 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 36 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
backbone_config (`Union[dict[str, Any], PretrainedConfig]`, *optional*):
|
| 40 |
+
The configuration of the backbone model. Only used in case `is_hybrid` is `True` or in case you want to
|
| 41 |
+
leverage the [`AutoBackbone`] API.
|
| 42 |
+
backbone (`str`, *optional*):
|
| 43 |
+
Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
|
| 44 |
+
will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
|
| 45 |
+
is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
|
| 46 |
+
use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
|
| 47 |
+
Whether to use pretrained weights for the backbone.
|
| 48 |
+
use_timm_backbone (`bool`, *optional*, defaults to `False`):
|
| 49 |
+
Whether or not to use the `timm` library for the backbone. If set to `False`, will use the [`AutoBackbone`]
|
| 50 |
+
API.
|
| 51 |
+
backbone_kwargs (`dict`, *optional*):
|
| 52 |
+
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
|
| 53 |
+
e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
|
| 54 |
+
patch_size (`int`, *optional*, defaults to 14):
|
| 55 |
+
The size of the patches to extract from the backbone features.
|
| 56 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 57 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 58 |
+
reassemble_hidden_size (`int`, *optional*, defaults to 384):
|
| 59 |
+
The number of input channels of the reassemble layers.
|
| 60 |
+
reassemble_factors (`list[int]`, *optional*, defaults to `[4, 2, 1, 0.5]`):
|
| 61 |
+
The up/downsampling factors of the reassemble layers.
|
| 62 |
+
neck_hidden_sizes (`list[str]`, *optional*, defaults to `[48, 96, 192, 384]`):
|
| 63 |
+
The hidden sizes to project to for the feature maps of the backbone.
|
| 64 |
+
fusion_hidden_size (`int`, *optional*, defaults to 64):
|
| 65 |
+
The number of channels before fusion.
|
| 66 |
+
head_in_index (`int`, *optional*, defaults to -1):
|
| 67 |
+
The index of the features to use in the depth estimation head.
|
| 68 |
+
head_hidden_size (`int`, *optional*, defaults to 32):
|
| 69 |
+
The number of output channels in the second convolution of the depth estimation head.
|
| 70 |
+
depth_estimation_type (`str`, *optional*, defaults to `"relative"`):
|
| 71 |
+
The type of depth estimation to use. Can be one of `["relative", "metric"]`.
|
| 72 |
+
max_depth (`float`, *optional*):
|
| 73 |
+
The maximum depth to use for the "metric" depth estimation head. 20 should be used for indoor models
|
| 74 |
+
and 80 for outdoor models. For "relative" depth estimation, this value is ignored.
|
| 75 |
+
|
| 76 |
+
Example:
|
| 77 |
+
|
| 78 |
+
```python
|
| 79 |
+
>>> from transformers import DepthAnythingConfig, DepthAnythingForDepthEstimation
|
| 80 |
+
|
| 81 |
+
>>> # Initializing a DepthAnything small style configuration
|
| 82 |
+
>>> configuration = DepthAnythingConfig()
|
| 83 |
+
|
| 84 |
+
>>> # Initializing a model from the DepthAnything small style configuration
|
| 85 |
+
>>> model = DepthAnythingForDepthEstimation(configuration)
|
| 86 |
+
|
| 87 |
+
>>> # Accessing the model configuration
|
| 88 |
+
>>> configuration = model.config
|
| 89 |
+
```"""
|
| 90 |
+
|
| 91 |
+
model_type = "depth_anything"
|
| 92 |
+
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
backbone_config=None,
|
| 96 |
+
backbone=None,
|
| 97 |
+
use_pretrained_backbone=False,
|
| 98 |
+
use_timm_backbone=False,
|
| 99 |
+
backbone_kwargs=None,
|
| 100 |
+
patch_size=14,
|
| 101 |
+
initializer_range=0.02,
|
| 102 |
+
reassemble_hidden_size=384,
|
| 103 |
+
reassemble_factors=[4, 2, 1, 0.5],
|
| 104 |
+
neck_hidden_sizes=[48, 96, 192, 384],
|
| 105 |
+
fusion_hidden_size=64,
|
| 106 |
+
head_in_index=-1,
|
| 107 |
+
head_hidden_size=32,
|
| 108 |
+
depth_estimation_type="relative",
|
| 109 |
+
max_depth=None,
|
| 110 |
+
**kwargs,
|
| 111 |
+
):
|
| 112 |
+
super().__init__(**kwargs)
|
| 113 |
+
if backbone_config is None and backbone is None:
|
| 114 |
+
logger.info("`backbone_config` is `None`. Initializing the config with the default `Dinov2` backbone.")
|
| 115 |
+
backbone_config = CONFIG_MAPPING["dinov2"](
|
| 116 |
+
image_size=518,
|
| 117 |
+
hidden_size=384,
|
| 118 |
+
num_attention_heads=6,
|
| 119 |
+
out_indices=[9, 10, 11, 12],
|
| 120 |
+
apply_layernorm=True,
|
| 121 |
+
reshape_hidden_states=False,
|
| 122 |
+
)
|
| 123 |
+
elif isinstance(backbone_config, dict):
|
| 124 |
+
backbone_model_type = backbone_config.get("model_type")
|
| 125 |
+
config_class = CONFIG_MAPPING[backbone_model_type]
|
| 126 |
+
backbone_config = config_class.from_dict(backbone_config)
|
| 127 |
+
|
| 128 |
+
verify_backbone_config_arguments(
|
| 129 |
+
use_timm_backbone=use_timm_backbone,
|
| 130 |
+
use_pretrained_backbone=use_pretrained_backbone,
|
| 131 |
+
backbone=backbone,
|
| 132 |
+
backbone_config=backbone_config,
|
| 133 |
+
backbone_kwargs=backbone_kwargs,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
self.backbone_config = backbone_config
|
| 137 |
+
self.backbone = backbone
|
| 138 |
+
self.use_pretrained_backbone = use_pretrained_backbone
|
| 139 |
+
self.use_timm_backbone = use_timm_backbone
|
| 140 |
+
self.backbone_kwargs = backbone_kwargs
|
| 141 |
+
self.reassemble_hidden_size = reassemble_hidden_size
|
| 142 |
+
self.patch_size = patch_size
|
| 143 |
+
self.initializer_range = initializer_range
|
| 144 |
+
self.reassemble_factors = reassemble_factors
|
| 145 |
+
self.neck_hidden_sizes = neck_hidden_sizes
|
| 146 |
+
self.fusion_hidden_size = fusion_hidden_size
|
| 147 |
+
self.head_in_index = head_in_index
|
| 148 |
+
self.head_hidden_size = head_hidden_size
|
| 149 |
+
if depth_estimation_type not in ["relative", "metric"]:
|
| 150 |
+
raise ValueError("depth_estimation_type must be one of ['relative', 'metric']")
|
| 151 |
+
self.depth_estimation_type = depth_estimation_type
|
| 152 |
+
self.max_depth = max_depth if max_depth else 1
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def sub_configs(self):
|
| 156 |
+
return (
|
| 157 |
+
{"backbone_config": type(self.backbone_config)}
|
| 158 |
+
if getattr(self, "backbone_config", None) is not None
|
| 159 |
+
else {}
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
def to_dict(self):
|
| 163 |
+
"""
|
| 164 |
+
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`]. Returns:
|
| 165 |
+
`dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
|
| 166 |
+
"""
|
| 167 |
+
output = copy.deepcopy(self.__dict__)
|
| 168 |
+
|
| 169 |
+
if output["backbone_config"] is not None:
|
| 170 |
+
output["backbone_config"] = self.backbone_config.to_dict()
|
| 171 |
+
|
| 172 |
+
output["model_type"] = self.__class__.model_type
|
| 173 |
+
return output
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
__all__ = ["DepthAnythingConfig"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/depth_anything/modeling_depth_anything.py
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 TikTok 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 Depth Anything model."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from torch import nn
|
| 21 |
+
|
| 22 |
+
from ...modeling_outputs import DepthEstimatorOutput
|
| 23 |
+
from ...modeling_utils import PreTrainedModel
|
| 24 |
+
from ...utils import auto_docstring, logging
|
| 25 |
+
from ...utils.backbone_utils import load_backbone
|
| 26 |
+
from .configuration_depth_anything import DepthAnythingConfig
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
# General docstring
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class DepthAnythingReassembleLayer(nn.Module):
|
| 35 |
+
def __init__(self, config, channels, factor):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.projection = nn.Conv2d(in_channels=config.reassemble_hidden_size, out_channels=channels, kernel_size=1)
|
| 38 |
+
|
| 39 |
+
# up/down sampling depending on factor
|
| 40 |
+
if factor > 1:
|
| 41 |
+
self.resize = nn.ConvTranspose2d(channels, channels, kernel_size=factor, stride=factor, padding=0)
|
| 42 |
+
elif factor == 1:
|
| 43 |
+
self.resize = nn.Identity()
|
| 44 |
+
elif factor < 1:
|
| 45 |
+
# so should downsample
|
| 46 |
+
self.resize = nn.Conv2d(channels, channels, kernel_size=3, stride=int(1 / factor), padding=1)
|
| 47 |
+
|
| 48 |
+
# Copied from transformers.models.dpt.modeling_dpt.DPTReassembleLayer.forward
|
| 49 |
+
def forward(self, hidden_state):
|
| 50 |
+
hidden_state = self.projection(hidden_state)
|
| 51 |
+
hidden_state = self.resize(hidden_state)
|
| 52 |
+
|
| 53 |
+
return hidden_state
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class DepthAnythingReassembleStage(nn.Module):
|
| 57 |
+
"""
|
| 58 |
+
This class reassembles the hidden states of the backbone into image-like feature representations at various
|
| 59 |
+
resolutions.
|
| 60 |
+
|
| 61 |
+
This happens in 3 stages:
|
| 62 |
+
1. Take the patch embeddings and reshape them to image-like feature representations.
|
| 63 |
+
2. Project the channel dimension of the hidden states according to `config.neck_hidden_sizes`.
|
| 64 |
+
3. Resizing the spatial dimensions (height, width).
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
config (`[DepthAnythingConfig]`):
|
| 68 |
+
Model configuration class defining the model architecture.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
def __init__(self, config):
|
| 72 |
+
super().__init__()
|
| 73 |
+
|
| 74 |
+
self.config = config
|
| 75 |
+
self.layers = nn.ModuleList()
|
| 76 |
+
for channels, factor in zip(config.neck_hidden_sizes, config.reassemble_factors):
|
| 77 |
+
self.layers.append(DepthAnythingReassembleLayer(config, channels=channels, factor=factor))
|
| 78 |
+
|
| 79 |
+
def forward(self, hidden_states: list[torch.Tensor], patch_height=None, patch_width=None) -> list[torch.Tensor]:
|
| 80 |
+
"""
|
| 81 |
+
Args:
|
| 82 |
+
hidden_states (`list[torch.FloatTensor]`, each of shape `(batch_size, sequence_length + 1, hidden_size)`):
|
| 83 |
+
List of hidden states from the backbone.
|
| 84 |
+
"""
|
| 85 |
+
out = []
|
| 86 |
+
|
| 87 |
+
for i, hidden_state in enumerate(hidden_states):
|
| 88 |
+
# reshape to (batch_size, num_channels, height, width)
|
| 89 |
+
hidden_state = hidden_state[:, 1:]
|
| 90 |
+
batch_size, _, num_channels = hidden_state.shape
|
| 91 |
+
hidden_state = hidden_state.reshape(batch_size, patch_height, patch_width, num_channels)
|
| 92 |
+
hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
|
| 93 |
+
hidden_state = self.layers[i](hidden_state)
|
| 94 |
+
out.append(hidden_state)
|
| 95 |
+
|
| 96 |
+
return out
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class DepthAnythingPreActResidualLayer(nn.Module):
|
| 100 |
+
"""
|
| 101 |
+
ResidualConvUnit, pre-activate residual unit.
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
config (`[DepthAnythingConfig]`):
|
| 105 |
+
Model configuration class defining the model architecture.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
def __init__(self, config):
|
| 109 |
+
super().__init__()
|
| 110 |
+
|
| 111 |
+
self.activation1 = nn.ReLU()
|
| 112 |
+
self.convolution1 = nn.Conv2d(
|
| 113 |
+
config.fusion_hidden_size,
|
| 114 |
+
config.fusion_hidden_size,
|
| 115 |
+
kernel_size=3,
|
| 116 |
+
stride=1,
|
| 117 |
+
padding=1,
|
| 118 |
+
bias=True,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
self.activation2 = nn.ReLU()
|
| 122 |
+
self.convolution2 = nn.Conv2d(
|
| 123 |
+
config.fusion_hidden_size,
|
| 124 |
+
config.fusion_hidden_size,
|
| 125 |
+
kernel_size=3,
|
| 126 |
+
stride=1,
|
| 127 |
+
padding=1,
|
| 128 |
+
bias=True,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 132 |
+
residual = hidden_state
|
| 133 |
+
hidden_state = self.activation1(hidden_state)
|
| 134 |
+
hidden_state = self.convolution1(hidden_state)
|
| 135 |
+
hidden_state = self.activation2(hidden_state)
|
| 136 |
+
hidden_state = self.convolution2(hidden_state)
|
| 137 |
+
|
| 138 |
+
return hidden_state + residual
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class DepthAnythingFeatureFusionLayer(nn.Module):
|
| 142 |
+
"""Feature fusion layer, merges feature maps from different stages.
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
config (`[DepthAnythingConfig]`):
|
| 146 |
+
Model configuration class defining the model architecture.
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
def __init__(self, config):
|
| 150 |
+
super().__init__()
|
| 151 |
+
|
| 152 |
+
self.projection = nn.Conv2d(config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=1, bias=True)
|
| 153 |
+
|
| 154 |
+
self.residual_layer1 = DepthAnythingPreActResidualLayer(config)
|
| 155 |
+
self.residual_layer2 = DepthAnythingPreActResidualLayer(config)
|
| 156 |
+
|
| 157 |
+
def forward(self, hidden_state, residual=None, size=None):
|
| 158 |
+
if residual is not None:
|
| 159 |
+
if hidden_state.shape != residual.shape:
|
| 160 |
+
residual = nn.functional.interpolate(
|
| 161 |
+
residual, size=(hidden_state.shape[2], hidden_state.shape[3]), mode="bilinear", align_corners=False
|
| 162 |
+
)
|
| 163 |
+
hidden_state = hidden_state + self.residual_layer1(residual)
|
| 164 |
+
|
| 165 |
+
hidden_state = self.residual_layer2(hidden_state)
|
| 166 |
+
|
| 167 |
+
modifier = {"scale_factor": 2} if size is None else {"size": size}
|
| 168 |
+
|
| 169 |
+
hidden_state = nn.functional.interpolate(
|
| 170 |
+
hidden_state,
|
| 171 |
+
**modifier,
|
| 172 |
+
mode="bilinear",
|
| 173 |
+
align_corners=True,
|
| 174 |
+
)
|
| 175 |
+
hidden_state = self.projection(hidden_state)
|
| 176 |
+
|
| 177 |
+
return hidden_state
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class DepthAnythingFeatureFusionStage(nn.Module):
|
| 181 |
+
# Copied from transformers.models.dpt.modeling_dpt.DPTFeatureFusionStage.__init__ with DPT->DepthAnything
|
| 182 |
+
def __init__(self, config: DepthAnythingConfig):
|
| 183 |
+
super().__init__()
|
| 184 |
+
self.layers = nn.ModuleList()
|
| 185 |
+
for _ in range(len(config.neck_hidden_sizes)):
|
| 186 |
+
self.layers.append(DepthAnythingFeatureFusionLayer(config))
|
| 187 |
+
|
| 188 |
+
def forward(self, hidden_states, size=None):
|
| 189 |
+
# reversing the hidden_states, we start from the last
|
| 190 |
+
hidden_states = hidden_states[::-1]
|
| 191 |
+
|
| 192 |
+
fused_hidden_states = []
|
| 193 |
+
fused_hidden_state = None
|
| 194 |
+
|
| 195 |
+
for idx, (hidden_state, layer) in enumerate(zip(hidden_states, self.layers)):
|
| 196 |
+
size = hidden_states[idx + 1].shape[2:] if idx != (len(hidden_states) - 1) else None
|
| 197 |
+
|
| 198 |
+
if fused_hidden_state is None:
|
| 199 |
+
# first layer only uses the last hidden_state
|
| 200 |
+
fused_hidden_state = layer(hidden_state, size=size)
|
| 201 |
+
else:
|
| 202 |
+
fused_hidden_state = layer(fused_hidden_state, hidden_state, size=size)
|
| 203 |
+
|
| 204 |
+
fused_hidden_states.append(fused_hidden_state)
|
| 205 |
+
|
| 206 |
+
return fused_hidden_states
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# Modified from transformers.models.dpt.modeling_dpt.DPTPreTrainedModel with DPT->DepthAnything,dpt->depth_anything
|
| 210 |
+
# avoiding sdpa and flash_attn_2 support, it's done in the backend
|
| 211 |
+
@auto_docstring
|
| 212 |
+
class DepthAnythingPreTrainedModel(PreTrainedModel):
|
| 213 |
+
config: DepthAnythingConfig
|
| 214 |
+
base_model_prefix = "depth_anything"
|
| 215 |
+
main_input_name = "pixel_values"
|
| 216 |
+
supports_gradient_checkpointing = True
|
| 217 |
+
|
| 218 |
+
def _init_weights(self, module):
|
| 219 |
+
"""Initialize the weights"""
|
| 220 |
+
if isinstance(module, (nn.Linear, nn.Conv2d, nn.ConvTranspose2d)):
|
| 221 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 222 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 223 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 224 |
+
if module.bias is not None:
|
| 225 |
+
module.bias.data.zero_()
|
| 226 |
+
elif isinstance(module, nn.LayerNorm):
|
| 227 |
+
module.bias.data.zero_()
|
| 228 |
+
module.weight.data.fill_(1.0)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class DepthAnythingNeck(nn.Module):
|
| 232 |
+
"""
|
| 233 |
+
DepthAnythingNeck. A neck is a module that is normally used between the backbone and the head. It takes a list of tensors as
|
| 234 |
+
input and produces another list of tensors as output. For DepthAnything, it includes 2 stages:
|
| 235 |
+
|
| 236 |
+
* DepthAnythingReassembleStage
|
| 237 |
+
* DepthAnythingFeatureFusionStage.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
config (dict): config dict.
|
| 241 |
+
"""
|
| 242 |
+
|
| 243 |
+
def __init__(self, config):
|
| 244 |
+
super().__init__()
|
| 245 |
+
self.config = config
|
| 246 |
+
|
| 247 |
+
self.reassemble_stage = DepthAnythingReassembleStage(config)
|
| 248 |
+
|
| 249 |
+
self.convs = nn.ModuleList()
|
| 250 |
+
for channel in config.neck_hidden_sizes:
|
| 251 |
+
self.convs.append(nn.Conv2d(channel, config.fusion_hidden_size, kernel_size=3, padding=1, bias=False))
|
| 252 |
+
|
| 253 |
+
# fusion
|
| 254 |
+
self.fusion_stage = DepthAnythingFeatureFusionStage(config)
|
| 255 |
+
|
| 256 |
+
def forward(self, hidden_states: list[torch.Tensor], patch_height=None, patch_width=None) -> list[torch.Tensor]:
|
| 257 |
+
"""
|
| 258 |
+
Args:
|
| 259 |
+
hidden_states (`list[torch.FloatTensor]`, each of shape `(batch_size, sequence_length, hidden_size)` or `(batch_size, hidden_size, height, width)`):
|
| 260 |
+
List of hidden states from the backbone.
|
| 261 |
+
"""
|
| 262 |
+
if not isinstance(hidden_states, (tuple, list)):
|
| 263 |
+
raise TypeError("hidden_states should be a tuple or list of tensors")
|
| 264 |
+
|
| 265 |
+
if len(hidden_states) != len(self.config.neck_hidden_sizes):
|
| 266 |
+
raise ValueError("The number of hidden states should be equal to the number of neck hidden sizes.")
|
| 267 |
+
|
| 268 |
+
# postprocess hidden states
|
| 269 |
+
hidden_states = self.reassemble_stage(hidden_states, patch_height, patch_width)
|
| 270 |
+
|
| 271 |
+
features = [self.convs[i](feature) for i, feature in enumerate(hidden_states)]
|
| 272 |
+
|
| 273 |
+
# fusion blocks
|
| 274 |
+
output = self.fusion_stage(features)
|
| 275 |
+
|
| 276 |
+
return output
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class DepthAnythingDepthEstimationHead(nn.Module):
|
| 280 |
+
"""
|
| 281 |
+
Output head consisting of 3 convolutional layers. It progressively halves the feature dimension and upsamples
|
| 282 |
+
the predictions to the input resolution after the first convolutional layer (details can be found in the DPT paper's
|
| 283 |
+
supplementary material). The final activation function is either ReLU or Sigmoid, depending on the depth estimation
|
| 284 |
+
type (relative or metric). For metric depth estimation, the output is scaled by the maximum depth used during pretraining.
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
def __init__(self, config):
|
| 288 |
+
super().__init__()
|
| 289 |
+
|
| 290 |
+
self.head_in_index = config.head_in_index
|
| 291 |
+
self.patch_size = config.patch_size
|
| 292 |
+
|
| 293 |
+
features = config.fusion_hidden_size
|
| 294 |
+
self.conv1 = nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1)
|
| 295 |
+
self.conv2 = nn.Conv2d(features // 2, config.head_hidden_size, kernel_size=3, stride=1, padding=1)
|
| 296 |
+
self.activation1 = nn.ReLU()
|
| 297 |
+
self.conv3 = nn.Conv2d(config.head_hidden_size, 1, kernel_size=1, stride=1, padding=0)
|
| 298 |
+
if config.depth_estimation_type == "relative":
|
| 299 |
+
self.activation2 = nn.ReLU()
|
| 300 |
+
elif config.depth_estimation_type == "metric":
|
| 301 |
+
self.activation2 = nn.Sigmoid()
|
| 302 |
+
else:
|
| 303 |
+
raise ValueError(f"Unknown depth estimation type: {config.depth_estimation_type}")
|
| 304 |
+
self.max_depth = config.max_depth
|
| 305 |
+
|
| 306 |
+
def forward(self, hidden_states: list[torch.Tensor], patch_height, patch_width) -> torch.Tensor:
|
| 307 |
+
hidden_states = hidden_states[self.head_in_index]
|
| 308 |
+
|
| 309 |
+
predicted_depth = self.conv1(hidden_states)
|
| 310 |
+
predicted_depth = nn.functional.interpolate(
|
| 311 |
+
predicted_depth,
|
| 312 |
+
(int(patch_height * self.patch_size), int(patch_width * self.patch_size)),
|
| 313 |
+
mode="bilinear",
|
| 314 |
+
align_corners=True,
|
| 315 |
+
)
|
| 316 |
+
predicted_depth = self.conv2(predicted_depth)
|
| 317 |
+
predicted_depth = self.activation1(predicted_depth)
|
| 318 |
+
predicted_depth = self.conv3(predicted_depth)
|
| 319 |
+
predicted_depth = self.activation2(predicted_depth) * self.max_depth
|
| 320 |
+
predicted_depth = predicted_depth.squeeze(dim=1) # shape (batch_size, height, width)
|
| 321 |
+
|
| 322 |
+
return predicted_depth
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
@auto_docstring(
|
| 326 |
+
custom_intro="""
|
| 327 |
+
Depth Anything Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.
|
| 328 |
+
"""
|
| 329 |
+
)
|
| 330 |
+
class DepthAnythingForDepthEstimation(DepthAnythingPreTrainedModel):
|
| 331 |
+
_no_split_modules = ["DPTViTEmbeddings"]
|
| 332 |
+
|
| 333 |
+
def __init__(self, config):
|
| 334 |
+
super().__init__(config)
|
| 335 |
+
|
| 336 |
+
self.backbone = load_backbone(config)
|
| 337 |
+
self.neck = DepthAnythingNeck(config)
|
| 338 |
+
self.head = DepthAnythingDepthEstimationHead(config)
|
| 339 |
+
|
| 340 |
+
# Initialize weights and apply final processing
|
| 341 |
+
self.post_init()
|
| 342 |
+
|
| 343 |
+
@auto_docstring
|
| 344 |
+
def forward(
|
| 345 |
+
self,
|
| 346 |
+
pixel_values: torch.FloatTensor,
|
| 347 |
+
labels: Optional[torch.LongTensor] = None,
|
| 348 |
+
output_attentions: Optional[bool] = None,
|
| 349 |
+
output_hidden_states: Optional[bool] = None,
|
| 350 |
+
return_dict: Optional[bool] = None,
|
| 351 |
+
) -> Union[tuple[torch.Tensor], DepthEstimatorOutput]:
|
| 352 |
+
r"""
|
| 353 |
+
labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
|
| 354 |
+
Ground truth depth estimation maps for computing the loss.
|
| 355 |
+
|
| 356 |
+
Examples:
|
| 357 |
+
```python
|
| 358 |
+
>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
|
| 359 |
+
>>> import torch
|
| 360 |
+
>>> import numpy as np
|
| 361 |
+
>>> from PIL import Image
|
| 362 |
+
>>> import requests
|
| 363 |
+
|
| 364 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 365 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 366 |
+
|
| 367 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("LiheYoung/depth-anything-small-hf")
|
| 368 |
+
>>> model = AutoModelForDepthEstimation.from_pretrained("LiheYoung/depth-anything-small-hf")
|
| 369 |
+
|
| 370 |
+
>>> # prepare image for the model
|
| 371 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 372 |
+
|
| 373 |
+
>>> with torch.no_grad():
|
| 374 |
+
... outputs = model(**inputs)
|
| 375 |
+
|
| 376 |
+
>>> # interpolate to original size
|
| 377 |
+
>>> post_processed_output = image_processor.post_process_depth_estimation(
|
| 378 |
+
... outputs,
|
| 379 |
+
... target_sizes=[(image.height, image.width)],
|
| 380 |
+
... )
|
| 381 |
+
|
| 382 |
+
>>> # visualize the prediction
|
| 383 |
+
>>> predicted_depth = post_processed_output[0]["predicted_depth"]
|
| 384 |
+
>>> depth = predicted_depth * 255 / predicted_depth.max()
|
| 385 |
+
>>> depth = depth.detach().cpu().numpy()
|
| 386 |
+
>>> depth = Image.fromarray(depth.astype("uint8"))
|
| 387 |
+
```"""
|
| 388 |
+
loss = None
|
| 389 |
+
if labels is not None:
|
| 390 |
+
raise NotImplementedError("Training is not implemented yet")
|
| 391 |
+
|
| 392 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 393 |
+
output_hidden_states = (
|
| 394 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 395 |
+
)
|
| 396 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 397 |
+
|
| 398 |
+
outputs = self.backbone.forward_with_filtered_kwargs(
|
| 399 |
+
pixel_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
|
| 400 |
+
)
|
| 401 |
+
hidden_states = outputs.feature_maps
|
| 402 |
+
|
| 403 |
+
_, _, height, width = pixel_values.shape
|
| 404 |
+
patch_size = self.config.patch_size
|
| 405 |
+
patch_height = height // patch_size
|
| 406 |
+
patch_width = width // patch_size
|
| 407 |
+
|
| 408 |
+
hidden_states = self.neck(hidden_states, patch_height, patch_width)
|
| 409 |
+
|
| 410 |
+
predicted_depth = self.head(hidden_states, patch_height, patch_width)
|
| 411 |
+
|
| 412 |
+
if not return_dict:
|
| 413 |
+
if output_hidden_states:
|
| 414 |
+
output = (predicted_depth,) + outputs[1:]
|
| 415 |
+
else:
|
| 416 |
+
output = (predicted_depth,) + outputs[2:]
|
| 417 |
+
return ((loss,) + output) if loss is not None else output
|
| 418 |
+
|
| 419 |
+
return DepthEstimatorOutput(
|
| 420 |
+
loss=loss,
|
| 421 |
+
predicted_depth=predicted_depth,
|
| 422 |
+
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
| 423 |
+
attentions=outputs.attentions,
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
__all__ = ["DepthAnythingForDepthEstimation", "DepthAnythingPreTrainedModel"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/depth_pro/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_depth_pro import *
|
| 22 |
+
from .image_processing_depth_pro import *
|
| 23 |
+
from .image_processing_depth_pro_fast import *
|
| 24 |
+
from .modeling_depth_pro import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/depth_pro/configuration_depth_pro.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 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 |
+
"""DepthPro model configuration"""
|
| 16 |
+
|
| 17 |
+
from copy import deepcopy
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PretrainedConfig
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
from ..auto.configuration_auto import CONFIG_MAPPING, AutoConfig
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class DepthProConfig(PretrainedConfig):
|
| 28 |
+
r"""
|
| 29 |
+
This is the configuration class to store the configuration of a [`DepthProModel`]. It is used to instantiate a
|
| 30 |
+
DepthPro model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 31 |
+
with the defaults will yield a similar configuration to that of the DepthPro
|
| 32 |
+
[apple/DepthPro](https://huggingface.co/apple/DepthPro) architecture.
|
| 33 |
+
|
| 34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 35 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
fusion_hidden_size (`int`, *optional*, defaults to 256):
|
| 39 |
+
The number of channels before fusion.
|
| 40 |
+
patch_size (`int`, *optional*, defaults to 384):
|
| 41 |
+
The size (resolution) of each patch. This is also the image_size for backbone model.
|
| 42 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 43 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 44 |
+
intermediate_hook_ids (`list[int]`, *optional*, defaults to `[11, 5]`):
|
| 45 |
+
Indices of the intermediate hidden states from the patch encoder to use for fusion.
|
| 46 |
+
intermediate_feature_dims (`list[int]`, *optional*, defaults to `[256, 256]`):
|
| 47 |
+
Hidden state dimensions during upsampling for each intermediate hidden state in `intermediate_hook_ids`.
|
| 48 |
+
scaled_images_ratios (`list[float]`, *optional*, defaults to `[0.25, 0.5, 1]`):
|
| 49 |
+
Ratios of scaled images to be used by the patch encoder.
|
| 50 |
+
scaled_images_overlap_ratios (`list[float]`, *optional*, defaults to `[0.0, 0.5, 0.25]`):
|
| 51 |
+
Overlap ratios between patches for each scaled image in `scaled_images_ratios`.
|
| 52 |
+
scaled_images_feature_dims (`list[int]`, *optional*, defaults to `[1024, 1024, 512]`):
|
| 53 |
+
Hidden state dimensions during upsampling for each scaled image in `scaled_images_ratios`.
|
| 54 |
+
merge_padding_value (`int`, *optional*, defaults to 3):
|
| 55 |
+
When merging smaller patches back to the image size, overlapping sections of this size are removed.
|
| 56 |
+
use_batch_norm_in_fusion_residual (`bool`, *optional*, defaults to `False`):
|
| 57 |
+
Whether to use batch normalization in the pre-activate residual units of the fusion blocks.
|
| 58 |
+
use_bias_in_fusion_residual (`bool`, *optional*, defaults to `True`):
|
| 59 |
+
Whether to use bias in the pre-activate residual units of the fusion blocks.
|
| 60 |
+
use_fov_model (`bool`, *optional*, defaults to `False`):
|
| 61 |
+
Whether to use `DepthProFovModel` to generate the field of view.
|
| 62 |
+
num_fov_head_layers (`int`, *optional*, defaults to 2):
|
| 63 |
+
Number of convolution layers in the head of `DepthProFovModel`.
|
| 64 |
+
image_model_config (`Union[dict[str, Any], PretrainedConfig]`, *optional*):
|
| 65 |
+
The configuration of the image encoder model, which is loaded using the [`AutoModel`] API.
|
| 66 |
+
By default, Dinov2 model is used as backbone.
|
| 67 |
+
patch_model_config (`Union[dict[str, Any], PretrainedConfig]`, *optional*):
|
| 68 |
+
The configuration of the patch encoder model, which is loaded using the [`AutoModel`] API.
|
| 69 |
+
By default, Dinov2 model is used as backbone.
|
| 70 |
+
fov_model_config (`Union[dict[str, Any], PretrainedConfig]`, *optional*):
|
| 71 |
+
The configuration of the fov encoder model, which is loaded using the [`AutoModel`] API.
|
| 72 |
+
By default, Dinov2 model is used as backbone.
|
| 73 |
+
|
| 74 |
+
Example:
|
| 75 |
+
|
| 76 |
+
```python
|
| 77 |
+
>>> from transformers import DepthProConfig, DepthProModel
|
| 78 |
+
|
| 79 |
+
>>> # Initializing a DepthPro apple/DepthPro style configuration
|
| 80 |
+
>>> configuration = DepthProConfig()
|
| 81 |
+
|
| 82 |
+
>>> # Initializing a model (with random weights) from the apple/DepthPro style configuration
|
| 83 |
+
>>> model = DepthProModel(configuration)
|
| 84 |
+
|
| 85 |
+
>>> # Accessing the model configuration
|
| 86 |
+
>>> configuration = model.config
|
| 87 |
+
```"""
|
| 88 |
+
|
| 89 |
+
model_type = "depth_pro"
|
| 90 |
+
sub_configs = {"image_model_config": AutoConfig, "patch_model_config": AutoConfig, "fov_model_config": AutoConfig}
|
| 91 |
+
|
| 92 |
+
def __init__(
|
| 93 |
+
self,
|
| 94 |
+
fusion_hidden_size=256,
|
| 95 |
+
patch_size=384,
|
| 96 |
+
initializer_range=0.02,
|
| 97 |
+
intermediate_hook_ids=[11, 5],
|
| 98 |
+
intermediate_feature_dims=[256, 256],
|
| 99 |
+
scaled_images_ratios=[0.25, 0.5, 1],
|
| 100 |
+
scaled_images_overlap_ratios=[0.0, 0.5, 0.25],
|
| 101 |
+
scaled_images_feature_dims=[1024, 1024, 512],
|
| 102 |
+
merge_padding_value=3,
|
| 103 |
+
use_batch_norm_in_fusion_residual=False,
|
| 104 |
+
use_bias_in_fusion_residual=True,
|
| 105 |
+
use_fov_model=False,
|
| 106 |
+
num_fov_head_layers=2,
|
| 107 |
+
image_model_config=None,
|
| 108 |
+
patch_model_config=None,
|
| 109 |
+
fov_model_config=None,
|
| 110 |
+
**kwargs,
|
| 111 |
+
):
|
| 112 |
+
super().__init__(**kwargs)
|
| 113 |
+
|
| 114 |
+
# scaled_images_ratios is sorted
|
| 115 |
+
if scaled_images_ratios != sorted(scaled_images_ratios):
|
| 116 |
+
raise ValueError(
|
| 117 |
+
f"Values in scaled_images_ratios={scaled_images_ratios} should be sorted from low to high"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
# scaled_images_ratios, scaled_images_overlap_ratios, scaled_images_feature_dims should be consistent
|
| 121 |
+
if not (len(scaled_images_ratios) == len(scaled_images_overlap_ratios) == len(scaled_images_feature_dims)):
|
| 122 |
+
raise ValueError(
|
| 123 |
+
f"len(scaled_images_ratios)={len(scaled_images_ratios)} and "
|
| 124 |
+
f"len(scaled_images_overlap_ratios)={len(scaled_images_overlap_ratios)} and "
|
| 125 |
+
f"len(scaled_images_feature_dims)={len(scaled_images_feature_dims)}, "
|
| 126 |
+
f"should match in config."
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# intermediate_hook_ids, intermediate_feature_dims should be consistent
|
| 130 |
+
if not (len(intermediate_hook_ids) == len(intermediate_feature_dims)):
|
| 131 |
+
raise ValueError(
|
| 132 |
+
f"len(intermediate_hook_ids)={len(intermediate_hook_ids)} and "
|
| 133 |
+
f"len(intermediate_feature_dims)={len(intermediate_feature_dims)}, "
|
| 134 |
+
f"should match in config."
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# fusion_hidden_size should be consistent with num_fov_head_layers
|
| 138 |
+
if fusion_hidden_size // 2**num_fov_head_layers == 0:
|
| 139 |
+
raise ValueError(
|
| 140 |
+
f"fusion_hidden_size={fusion_hidden_size} should be consistent with num_fov_head_layers={num_fov_head_layers} "
|
| 141 |
+
"i.e fusion_hidden_size // 2**num_fov_head_layers > 0"
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
self.fusion_hidden_size = fusion_hidden_size
|
| 145 |
+
self.patch_size = patch_size
|
| 146 |
+
self.initializer_range = initializer_range
|
| 147 |
+
self.use_batch_norm_in_fusion_residual = use_batch_norm_in_fusion_residual
|
| 148 |
+
self.use_bias_in_fusion_residual = use_bias_in_fusion_residual
|
| 149 |
+
self.use_fov_model = use_fov_model
|
| 150 |
+
self.num_fov_head_layers = num_fov_head_layers
|
| 151 |
+
self.intermediate_hook_ids = intermediate_hook_ids
|
| 152 |
+
self.intermediate_feature_dims = intermediate_feature_dims
|
| 153 |
+
self.scaled_images_ratios = scaled_images_ratios
|
| 154 |
+
self.scaled_images_overlap_ratios = scaled_images_overlap_ratios
|
| 155 |
+
self.scaled_images_feature_dims = scaled_images_feature_dims
|
| 156 |
+
self.merge_padding_value = merge_padding_value
|
| 157 |
+
self.image_model_config = image_model_config
|
| 158 |
+
self.patch_model_config = patch_model_config
|
| 159 |
+
self.fov_model_config = fov_model_config
|
| 160 |
+
|
| 161 |
+
for sub_config_key in self.sub_configs:
|
| 162 |
+
sub_config = getattr(self, sub_config_key)
|
| 163 |
+
|
| 164 |
+
if sub_config is None:
|
| 165 |
+
sub_config = CONFIG_MAPPING["dinov2"](image_size=patch_size)
|
| 166 |
+
logger.info(
|
| 167 |
+
f"`{sub_config_key}` is `None`. Initializing `{sub_config_key}` with the `Dinov2Config` "
|
| 168 |
+
f"with default values except `{sub_config_key}.image_size` is set to `config.patch_size`."
|
| 169 |
+
)
|
| 170 |
+
elif isinstance(sub_config, dict):
|
| 171 |
+
sub_config = deepcopy(sub_config)
|
| 172 |
+
if "model_type" not in sub_config:
|
| 173 |
+
raise KeyError(
|
| 174 |
+
f"The `model_type` key is missing in the `{sub_config_key}` dictionary. Please provide the model type."
|
| 175 |
+
)
|
| 176 |
+
elif sub_config["model_type"] not in CONFIG_MAPPING:
|
| 177 |
+
raise ValueError(
|
| 178 |
+
f"The model type `{sub_config['model_type']}` in `{sub_config_key}` is not supported. Please provide a valid model type."
|
| 179 |
+
)
|
| 180 |
+
image_size = sub_config.get("image_size")
|
| 181 |
+
if image_size != patch_size:
|
| 182 |
+
logger.info(
|
| 183 |
+
f"The `image_size` in `{sub_config_key}` is set to `{image_size}`, "
|
| 184 |
+
f"but it does not match the required `patch_size` of `{patch_size}`. "
|
| 185 |
+
f"Updating `image_size` to `{patch_size}` for consistency. "
|
| 186 |
+
f"Ensure that `image_size` aligns with `patch_size` in the configuration."
|
| 187 |
+
)
|
| 188 |
+
sub_config.update({"image_size": patch_size})
|
| 189 |
+
sub_config = CONFIG_MAPPING[sub_config["model_type"]](**sub_config)
|
| 190 |
+
elif isinstance(sub_config, PretrainedConfig):
|
| 191 |
+
image_size = getattr(sub_config, "image_size", None)
|
| 192 |
+
if image_size != patch_size:
|
| 193 |
+
raise ValueError(
|
| 194 |
+
f"`config.{sub_config_key}.image_size={image_size}` should match `config.patch_size={patch_size}`."
|
| 195 |
+
)
|
| 196 |
+
else:
|
| 197 |
+
raise TypeError(
|
| 198 |
+
f"Invalid type for `sub_config`. Expected `PretrainedConfig`, `dict`, or `None`, but got {type(sub_config)}."
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
setattr(self, sub_config_key, sub_config)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
__all__ = ["DepthProConfig"]
|
miniconda3/envs/active_proaction/lib/python3.10/site-packages/transformers/models/depth_pro/image_processing_depth_pro.py
ADDED
|
@@ -0,0 +1,389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 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 |
+
"""Image processor class for DepthPro."""
|
| 16 |
+
|
| 17 |
+
from typing import TYPE_CHECKING, Optional, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ...utils.import_utils import requires
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if TYPE_CHECKING:
|
| 25 |
+
from .modeling_depth_pro import DepthProDepthEstimatorOutput
|
| 26 |
+
|
| 27 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 28 |
+
from ...image_transforms import to_channel_dimension_format
|
| 29 |
+
from ...image_utils import (
|
| 30 |
+
IMAGENET_STANDARD_MEAN,
|
| 31 |
+
IMAGENET_STANDARD_STD,
|
| 32 |
+
ChannelDimension,
|
| 33 |
+
ImageInput,
|
| 34 |
+
PILImageResampling,
|
| 35 |
+
infer_channel_dimension_format,
|
| 36 |
+
is_scaled_image,
|
| 37 |
+
is_torch_available,
|
| 38 |
+
make_flat_list_of_images,
|
| 39 |
+
to_numpy_array,
|
| 40 |
+
valid_images,
|
| 41 |
+
)
|
| 42 |
+
from ...utils import TensorType, filter_out_non_signature_kwargs, is_torchvision_available, logging, requires_backends
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if is_torch_available():
|
| 46 |
+
import torch
|
| 47 |
+
|
| 48 |
+
if is_torchvision_available():
|
| 49 |
+
from ...image_utils import pil_torch_interpolation_mapping
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
logger = logging.get_logger(__name__)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@requires(backends=("torchvision", "torch"))
|
| 56 |
+
class DepthProImageProcessor(BaseImageProcessor):
|
| 57 |
+
r"""
|
| 58 |
+
Constructs a DepthPro image processor.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 62 |
+
Whether to resize the image's (height, width) dimensions to the specified `(size["height"],
|
| 63 |
+
size["width"])`. Can be overridden by the `do_resize` parameter in the `preprocess` method.
|
| 64 |
+
size (`dict`, *optional*, defaults to `{"height": 1536, "width": 1536}`):
|
| 65 |
+
Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
|
| 66 |
+
method.
|
| 67 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
|
| 68 |
+
Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
|
| 69 |
+
`preprocess` method.
|
| 70 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 71 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
|
| 72 |
+
parameter in the `preprocess` method.
|
| 73 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 74 |
+
Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
|
| 75 |
+
`preprocess` method.
|
| 76 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 77 |
+
Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
|
| 78 |
+
method.
|
| 79 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
| 80 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 81 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 82 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
| 83 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 84 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
model_input_names = ["pixel_values"]
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
do_resize: bool = True,
|
| 92 |
+
size: Optional[dict[str, int]] = None,
|
| 93 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 94 |
+
do_rescale: bool = True,
|
| 95 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 96 |
+
do_normalize: bool = True,
|
| 97 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 98 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 99 |
+
**kwargs,
|
| 100 |
+
):
|
| 101 |
+
super().__init__(**kwargs)
|
| 102 |
+
size = size if size is not None else {"height": 1536, "width": 1536}
|
| 103 |
+
size = get_size_dict(size)
|
| 104 |
+
self.do_resize = do_resize
|
| 105 |
+
self.do_rescale = do_rescale
|
| 106 |
+
self.do_normalize = do_normalize
|
| 107 |
+
self.size = size
|
| 108 |
+
self.resample = resample
|
| 109 |
+
self.rescale_factor = rescale_factor
|
| 110 |
+
self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
|
| 111 |
+
self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
|
| 112 |
+
|
| 113 |
+
def resize(
|
| 114 |
+
self,
|
| 115 |
+
image: np.ndarray,
|
| 116 |
+
size: dict[str, int],
|
| 117 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 118 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 119 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 120 |
+
**kwargs,
|
| 121 |
+
) -> np.ndarray:
|
| 122 |
+
"""
|
| 123 |
+
Resize an image to `(size["height"], size["width"])`.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
image (`np.ndarray`):
|
| 127 |
+
Image to resize.
|
| 128 |
+
size (`dict[str, int]`):
|
| 129 |
+
Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
|
| 130 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
|
| 131 |
+
`PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
|
| 132 |
+
data_format (`ChannelDimension` or `str`, *optional*):
|
| 133 |
+
The channel dimension format for the output image. If unset, the channel dimension format of the input
|
| 134 |
+
image is used. Can be one of:
|
| 135 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 136 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 137 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 138 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 139 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 140 |
+
from the input image. Can be one of:
|
| 141 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 142 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 143 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 144 |
+
|
| 145 |
+
Returns:
|
| 146 |
+
`np.ndarray`: The resized images.
|
| 147 |
+
"""
|
| 148 |
+
requires_backends(self, "torch")
|
| 149 |
+
|
| 150 |
+
size = get_size_dict(size)
|
| 151 |
+
if "height" not in size or "width" not in size:
|
| 152 |
+
raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
|
| 153 |
+
output_size = (size["height"], size["width"])
|
| 154 |
+
|
| 155 |
+
# we use torch interpolation instead of image.resize because DepthProImageProcessor
|
| 156 |
+
# rescales, then normalizes, which may cause some values to become negative, before resizing the image.
|
| 157 |
+
# image.resize expects all values to be in range [0, 1] or [0, 255] and throws an exception otherwise,
|
| 158 |
+
# however pytorch interpolation works with negative values.
|
| 159 |
+
# relevant issue here: https://github.com/huggingface/transformers/issues/34920
|
| 160 |
+
# input should be (B, C, H, W)
|
| 161 |
+
image_tensor = torch.from_numpy(image).unsqueeze(0)
|
| 162 |
+
resized_image = torch.nn.functional.interpolate(
|
| 163 |
+
input=image_tensor,
|
| 164 |
+
size=output_size,
|
| 165 |
+
mode=pil_torch_interpolation_mapping[resample].value,
|
| 166 |
+
)
|
| 167 |
+
resized_image = resized_image.squeeze(0).numpy()
|
| 168 |
+
return resized_image
|
| 169 |
+
|
| 170 |
+
def _validate_input_arguments(
|
| 171 |
+
self,
|
| 172 |
+
do_resize: bool,
|
| 173 |
+
size: dict[str, int],
|
| 174 |
+
resample: PILImageResampling,
|
| 175 |
+
do_rescale: bool,
|
| 176 |
+
rescale_factor: float,
|
| 177 |
+
do_normalize: bool,
|
| 178 |
+
image_mean: Union[float, list[float]],
|
| 179 |
+
image_std: Union[float, list[float]],
|
| 180 |
+
data_format: Union[str, ChannelDimension],
|
| 181 |
+
):
|
| 182 |
+
if do_resize and None in (size, resample):
|
| 183 |
+
raise ValueError("Size and resample must be specified if do_resize is True.")
|
| 184 |
+
|
| 185 |
+
if do_rescale and rescale_factor is None:
|
| 186 |
+
raise ValueError("Rescale factor must be specified if do_rescale is True.")
|
| 187 |
+
|
| 188 |
+
if do_normalize and None in (image_mean, image_std):
|
| 189 |
+
raise ValueError("Image mean and standard deviation must be specified if do_normalize is True.")
|
| 190 |
+
|
| 191 |
+
@filter_out_non_signature_kwargs()
|
| 192 |
+
def preprocess(
|
| 193 |
+
self,
|
| 194 |
+
images: ImageInput,
|
| 195 |
+
do_resize: Optional[bool] = None,
|
| 196 |
+
size: Optional[dict[str, int]] = None,
|
| 197 |
+
resample: Optional[PILImageResampling] = None,
|
| 198 |
+
do_rescale: Optional[bool] = None,
|
| 199 |
+
rescale_factor: Optional[float] = None,
|
| 200 |
+
do_normalize: Optional[bool] = None,
|
| 201 |
+
image_mean: Optional[Union[float, list[float]]] = None,
|
| 202 |
+
image_std: Optional[Union[float, list[float]]] = None,
|
| 203 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 204 |
+
data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
|
| 205 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 206 |
+
):
|
| 207 |
+
"""
|
| 208 |
+
Preprocess an image or batch of images.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
images (`ImageInput`):
|
| 212 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 213 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 214 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 215 |
+
Whether to resize the image.
|
| 216 |
+
size (`dict[str, int]`, *optional*, defaults to `self.size`):
|
| 217 |
+
Dictionary in the format `{"height": h, "width": w}` specifying the size of the output image after
|
| 218 |
+
resizing.
|
| 219 |
+
resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):
|
| 220 |
+
`PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
|
| 221 |
+
an effect if `do_resize` is set to `True`.
|
| 222 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 223 |
+
Whether to rescale the image values between [0 - 1].
|
| 224 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 225 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 226 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 227 |
+
Whether to normalize the image.
|
| 228 |
+
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
|
| 229 |
+
Image mean to use if `do_normalize` is set to `True`.
|
| 230 |
+
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
|
| 231 |
+
Image standard deviation to use if `do_normalize` is set to `True`.
|
| 232 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 233 |
+
The type of tensors to return. Can be one of:
|
| 234 |
+
- Unset: Return a list of `np.ndarray`.
|
| 235 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 236 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 237 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 238 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 239 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 240 |
+
The channel dimension format for the output image. Can be one of:
|
| 241 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 242 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 243 |
+
- Unset: Use the channel dimension format of the input image.
|
| 244 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 245 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 246 |
+
from the input image. Can be one of:
|
| 247 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 248 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 249 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 250 |
+
"""
|
| 251 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 252 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 253 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 254 |
+
resample = resample if resample is not None else self.resample
|
| 255 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 256 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 257 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 258 |
+
|
| 259 |
+
size = size if size is not None else self.size
|
| 260 |
+
|
| 261 |
+
images = make_flat_list_of_images(images)
|
| 262 |
+
|
| 263 |
+
if not valid_images(images):
|
| 264 |
+
raise ValueError(
|
| 265 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 266 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 267 |
+
)
|
| 268 |
+
self._validate_input_arguments(
|
| 269 |
+
do_resize=do_resize,
|
| 270 |
+
size=size,
|
| 271 |
+
resample=resample,
|
| 272 |
+
do_rescale=do_rescale,
|
| 273 |
+
rescale_factor=rescale_factor,
|
| 274 |
+
do_normalize=do_normalize,
|
| 275 |
+
image_mean=image_mean,
|
| 276 |
+
image_std=image_std,
|
| 277 |
+
data_format=data_format,
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
# All transformations expect numpy arrays.
|
| 281 |
+
images = [to_numpy_array(image) for image in images]
|
| 282 |
+
|
| 283 |
+
if is_scaled_image(images[0]) and do_rescale:
|
| 284 |
+
logger.warning_once(
|
| 285 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 286 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
if input_data_format is None:
|
| 290 |
+
# We assume that all images have the same channel dimension format.
|
| 291 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 292 |
+
|
| 293 |
+
all_images = []
|
| 294 |
+
for image in images:
|
| 295 |
+
if do_rescale:
|
| 296 |
+
image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 297 |
+
|
| 298 |
+
if do_normalize:
|
| 299 |
+
image = self.normalize(
|
| 300 |
+
image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
# depth-pro rescales and normalizes the image before resizing it
|
| 304 |
+
# uses torch interpolation which requires ChannelDimension.FIRST
|
| 305 |
+
if do_resize:
|
| 306 |
+
image = to_channel_dimension_format(image, ChannelDimension.FIRST, input_channel_dim=input_data_format)
|
| 307 |
+
image = self.resize(image=image, size=size, resample=resample)
|
| 308 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=ChannelDimension.FIRST)
|
| 309 |
+
else:
|
| 310 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 311 |
+
|
| 312 |
+
all_images.append(image)
|
| 313 |
+
|
| 314 |
+
data = {"pixel_values": all_images}
|
| 315 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 316 |
+
|
| 317 |
+
def post_process_depth_estimation(
|
| 318 |
+
self,
|
| 319 |
+
outputs: "DepthProDepthEstimatorOutput",
|
| 320 |
+
target_sizes: Optional[Union[TensorType, list[tuple[int, int]], None]] = None,
|
| 321 |
+
) -> list[dict[str, TensorType]]:
|
| 322 |
+
"""
|
| 323 |
+
Post-processes the raw depth predictions from the model to generate
|
| 324 |
+
final depth predictions which is caliberated using the field of view if provided
|
| 325 |
+
and resized to specified target sizes if provided.
|
| 326 |
+
|
| 327 |
+
Args:
|
| 328 |
+
outputs ([`DepthProDepthEstimatorOutput`]):
|
| 329 |
+
Raw outputs of the model.
|
| 330 |
+
target_sizes (`Optional[Union[TensorType, list[tuple[int, int]], None]]`, *optional*, defaults to `None`):
|
| 331 |
+
Target sizes to resize the depth predictions. Can be a tensor of shape `(batch_size, 2)`
|
| 332 |
+
or a list of tuples `(height, width)` for each image in the batch. If `None`, no resizing
|
| 333 |
+
is performed.
|
| 334 |
+
|
| 335 |
+
Returns:
|
| 336 |
+
`list[dict[str, TensorType]]`: A list of dictionaries of tensors representing the processed depth
|
| 337 |
+
predictions, and field of view (degrees) and focal length (pixels) if `field_of_view` is given in `outputs`.
|
| 338 |
+
|
| 339 |
+
Raises:
|
| 340 |
+
`ValueError`:
|
| 341 |
+
If the lengths of `predicted_depths`, `fovs`, or `target_sizes` are mismatched.
|
| 342 |
+
"""
|
| 343 |
+
requires_backends(self, "torch")
|
| 344 |
+
|
| 345 |
+
predicted_depth = outputs.predicted_depth
|
| 346 |
+
fov = outputs.field_of_view
|
| 347 |
+
|
| 348 |
+
batch_size = len(predicted_depth)
|
| 349 |
+
|
| 350 |
+
if target_sizes is not None and batch_size != len(target_sizes):
|
| 351 |
+
raise ValueError(
|
| 352 |
+
"Make sure that you pass in as many fov values as the batch dimension of the predicted depth"
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
results = []
|
| 356 |
+
fov = [None] * batch_size if fov is None else fov
|
| 357 |
+
target_sizes = [None] * batch_size if target_sizes is None else target_sizes
|
| 358 |
+
for depth, fov_value, target_size in zip(predicted_depth, fov, target_sizes):
|
| 359 |
+
focal_length = None
|
| 360 |
+
if target_size is not None:
|
| 361 |
+
# scale image w.r.t fov
|
| 362 |
+
if fov_value is not None:
|
| 363 |
+
width = target_size[1]
|
| 364 |
+
focal_length = 0.5 * width / torch.tan(0.5 * torch.deg2rad(fov_value))
|
| 365 |
+
depth = depth * width / focal_length
|
| 366 |
+
|
| 367 |
+
# interpolate
|
| 368 |
+
depth = torch.nn.functional.interpolate(
|
| 369 |
+
# input should be (B, C, H, W)
|
| 370 |
+
input=depth.unsqueeze(0).unsqueeze(1),
|
| 371 |
+
size=target_size,
|
| 372 |
+
mode=pil_torch_interpolation_mapping[self.resample].value,
|
| 373 |
+
).squeeze()
|
| 374 |
+
|
| 375 |
+
# inverse the depth
|
| 376 |
+
depth = 1.0 / torch.clamp(depth, min=1e-4, max=1e4)
|
| 377 |
+
|
| 378 |
+
results.append(
|
| 379 |
+
{
|
| 380 |
+
"predicted_depth": depth,
|
| 381 |
+
"field_of_view": fov_value,
|
| 382 |
+
"focal_length": focal_length,
|
| 383 |
+
}
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
return results
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
__all__ = ["DepthProImageProcessor"]
|