Stage Harbor release files 25501-26000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/conditional_detr/modeling_conditional_detr.py +0 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/__init__.py +30 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/configuration_convbert.py +160 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/convert_convbert_original_tf1_checkpoint_to_pytorch_and_tf2.py +57 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/modeling_convbert.py +1346 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/modeling_tf_convbert.py +1476 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/tokenization_convbert.py +512 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/tokenization_convbert_fast.py +176 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/__init__.py +31 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/configuration_convnext.py +142 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/convert_convnext_to_pytorch.py +242 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/feature_extraction_convnext.py +36 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/image_processing_convnext.py +323 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/image_processing_convnext_fast.py +199 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/modeling_convnext.py +551 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/modeling_tf_convnext.py +669 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnextv2/__init__.py +28 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnextv2/configuration_convnextv2.py +118 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnextv2/convert_convnextv2_to_pytorch.py +286 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnextv2/modeling_convnextv2.py +574 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnextv2/modeling_tf_convnextv2.py +683 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpm/__init__.py +27 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpm/tokenization_cpm.py +348 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpm/tokenization_cpm_fast.py +241 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpmant/__init__.py +28 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpmant/configuration_cpmant.py +122 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpmant/modeling_cpmant.py +860 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpmant/tokenization_cpmant.py +270 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/ctrl/__init__.py +29 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/ctrl/configuration_ctrl.py +116 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/ctrl/modeling_ctrl.py +844 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/ctrl/modeling_tf_ctrl.py +922 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/ctrl/tokenization_ctrl.py +251 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cvt/__init__.py +28 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cvt/configuration_cvt.py +146 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cvt/convert_cvt_original_pytorch_checkpoint_to_pytorch.py +362 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cvt/modeling_cvt.py +725 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cvt/modeling_tf_cvt.py +1096 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dab_detr/__init__.py +28 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dab_detr/configuration_dab_detr.py +260 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dab_detr/convert_dab_detr_original_pytorch_checkpoint_to_pytorch.py +233 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dab_detr/modeling_dab_detr.py +1716 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dac/__init__.py +28 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dac/configuration_dac.py +114 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dac/convert_dac_checkpoint.py +261 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dac/feature_extraction_dac.py +173 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dac/modeling_dac.py +724 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/data2vec/__init__.py +32 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/data2vec/configuration_data2vec_audio.py +288 -0
- tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/data2vec/configuration_data2vec_text.py +154 -0
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/conditional_detr/modeling_conditional_detr.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_convbert import *
|
| 22 |
+
from .modeling_convbert import *
|
| 23 |
+
from .modeling_tf_convbert import *
|
| 24 |
+
from .tokenization_convbert import *
|
| 25 |
+
from .tokenization_convbert_fast import *
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
_file = globals()["__file__"]
|
| 30 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/configuration_convbert.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 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 |
+
"""ConvBERT model configuration"""
|
| 16 |
+
|
| 17 |
+
from collections import OrderedDict
|
| 18 |
+
from typing import Mapping
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PretrainedConfig
|
| 21 |
+
from ...onnx import OnnxConfig
|
| 22 |
+
from ...utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ConvBertConfig(PretrainedConfig):
|
| 29 |
+
r"""
|
| 30 |
+
This is the configuration class to store the configuration of a [`ConvBertModel`]. It is used to instantiate an
|
| 31 |
+
ConvBERT model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 32 |
+
with the defaults will yield a similar configuration to that of the ConvBERT
|
| 33 |
+
[YituTech/conv-bert-base](https://huggingface.co/YituTech/conv-bert-base) 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 |
+
|
| 39 |
+
Args:
|
| 40 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 41 |
+
Vocabulary size of the ConvBERT model. Defines the number of different tokens that can be represented by
|
| 42 |
+
the `inputs_ids` passed when calling [`ConvBertModel`] or [`TFConvBertModel`].
|
| 43 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 44 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 45 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 46 |
+
Number of hidden layers in the Transformer encoder.
|
| 47 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 48 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 49 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 50 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 51 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 52 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 53 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 54 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 55 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 56 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 57 |
+
The dropout ratio for the attention probabilities.
|
| 58 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 59 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 60 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 61 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 62 |
+
The vocabulary size of the `token_type_ids` passed when calling [`ConvBertModel`] or [`TFConvBertModel`].
|
| 63 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 64 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 65 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 66 |
+
The epsilon used by the layer normalization layers.
|
| 67 |
+
head_ratio (`int`, *optional*, defaults to 2):
|
| 68 |
+
Ratio gamma to reduce the number of attention heads.
|
| 69 |
+
num_groups (`int`, *optional*, defaults to 1):
|
| 70 |
+
The number of groups for grouped linear layers for ConvBert model
|
| 71 |
+
conv_kernel_size (`int`, *optional*, defaults to 9):
|
| 72 |
+
The size of the convolutional kernel.
|
| 73 |
+
classifier_dropout (`float`, *optional*):
|
| 74 |
+
The dropout ratio for the classification head.
|
| 75 |
+
|
| 76 |
+
Example:
|
| 77 |
+
|
| 78 |
+
```python
|
| 79 |
+
>>> from transformers import ConvBertConfig, ConvBertModel
|
| 80 |
+
|
| 81 |
+
>>> # Initializing a ConvBERT convbert-base-uncased style configuration
|
| 82 |
+
>>> configuration = ConvBertConfig()
|
| 83 |
+
|
| 84 |
+
>>> # Initializing a model (with random weights) from the convbert-base-uncased style configuration
|
| 85 |
+
>>> model = ConvBertModel(configuration)
|
| 86 |
+
|
| 87 |
+
>>> # Accessing the model configuration
|
| 88 |
+
>>> configuration = model.config
|
| 89 |
+
```"""
|
| 90 |
+
|
| 91 |
+
model_type = "convbert"
|
| 92 |
+
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
vocab_size=30522,
|
| 96 |
+
hidden_size=768,
|
| 97 |
+
num_hidden_layers=12,
|
| 98 |
+
num_attention_heads=12,
|
| 99 |
+
intermediate_size=3072,
|
| 100 |
+
hidden_act="gelu",
|
| 101 |
+
hidden_dropout_prob=0.1,
|
| 102 |
+
attention_probs_dropout_prob=0.1,
|
| 103 |
+
max_position_embeddings=512,
|
| 104 |
+
type_vocab_size=2,
|
| 105 |
+
initializer_range=0.02,
|
| 106 |
+
layer_norm_eps=1e-12,
|
| 107 |
+
pad_token_id=1,
|
| 108 |
+
bos_token_id=0,
|
| 109 |
+
eos_token_id=2,
|
| 110 |
+
embedding_size=768,
|
| 111 |
+
head_ratio=2,
|
| 112 |
+
conv_kernel_size=9,
|
| 113 |
+
num_groups=1,
|
| 114 |
+
classifier_dropout=None,
|
| 115 |
+
**kwargs,
|
| 116 |
+
):
|
| 117 |
+
super().__init__(
|
| 118 |
+
pad_token_id=pad_token_id,
|
| 119 |
+
bos_token_id=bos_token_id,
|
| 120 |
+
eos_token_id=eos_token_id,
|
| 121 |
+
**kwargs,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
self.vocab_size = vocab_size
|
| 125 |
+
self.hidden_size = hidden_size
|
| 126 |
+
self.num_hidden_layers = num_hidden_layers
|
| 127 |
+
self.num_attention_heads = num_attention_heads
|
| 128 |
+
self.intermediate_size = intermediate_size
|
| 129 |
+
self.hidden_act = hidden_act
|
| 130 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 131 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 132 |
+
self.max_position_embeddings = max_position_embeddings
|
| 133 |
+
self.type_vocab_size = type_vocab_size
|
| 134 |
+
self.initializer_range = initializer_range
|
| 135 |
+
self.layer_norm_eps = layer_norm_eps
|
| 136 |
+
self.embedding_size = embedding_size
|
| 137 |
+
self.head_ratio = head_ratio
|
| 138 |
+
self.conv_kernel_size = conv_kernel_size
|
| 139 |
+
self.num_groups = num_groups
|
| 140 |
+
self.classifier_dropout = classifier_dropout
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# Copied from transformers.models.bert.configuration_bert.BertOnnxConfig
|
| 144 |
+
class ConvBertOnnxConfig(OnnxConfig):
|
| 145 |
+
@property
|
| 146 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 147 |
+
if self.task == "multiple-choice":
|
| 148 |
+
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
|
| 149 |
+
else:
|
| 150 |
+
dynamic_axis = {0: "batch", 1: "sequence"}
|
| 151 |
+
return OrderedDict(
|
| 152 |
+
[
|
| 153 |
+
("input_ids", dynamic_axis),
|
| 154 |
+
("attention_mask", dynamic_axis),
|
| 155 |
+
("token_type_ids", dynamic_axis),
|
| 156 |
+
]
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
__all__ = ["ConvBertConfig", "ConvBertOnnxConfig"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/convert_convbert_original_tf1_checkpoint_to_pytorch_and_tf2.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert ConvBERT checkpoint."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
|
| 19 |
+
from transformers import ConvBertConfig, ConvBertModel, TFConvBertModel, load_tf_weights_in_convbert
|
| 20 |
+
from transformers.utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logging.set_verbosity_info()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def convert_orig_tf1_checkpoint_to_pytorch(tf_checkpoint_path, convbert_config_file, pytorch_dump_path):
|
| 27 |
+
conf = ConvBertConfig.from_json_file(convbert_config_file)
|
| 28 |
+
model = ConvBertModel(conf)
|
| 29 |
+
|
| 30 |
+
model = load_tf_weights_in_convbert(model, conf, tf_checkpoint_path)
|
| 31 |
+
model.save_pretrained(pytorch_dump_path)
|
| 32 |
+
|
| 33 |
+
tf_model = TFConvBertModel.from_pretrained(pytorch_dump_path, from_pt=True)
|
| 34 |
+
tf_model.save_pretrained(pytorch_dump_path)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if __name__ == "__main__":
|
| 38 |
+
parser = argparse.ArgumentParser()
|
| 39 |
+
# Required parameters
|
| 40 |
+
parser.add_argument(
|
| 41 |
+
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
|
| 42 |
+
)
|
| 43 |
+
parser.add_argument(
|
| 44 |
+
"--convbert_config_file",
|
| 45 |
+
default=None,
|
| 46 |
+
type=str,
|
| 47 |
+
required=True,
|
| 48 |
+
help=(
|
| 49 |
+
"The config json file corresponding to the pre-trained ConvBERT model. \n"
|
| 50 |
+
"This specifies the model architecture."
|
| 51 |
+
),
|
| 52 |
+
)
|
| 53 |
+
parser.add_argument(
|
| 54 |
+
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
|
| 55 |
+
)
|
| 56 |
+
args = parser.parse_args()
|
| 57 |
+
convert_orig_tf1_checkpoint_to_pytorch(args.tf_checkpoint_path, args.convbert_config_file, args.pytorch_dump_path)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/modeling_convbert.py
ADDED
|
@@ -0,0 +1,1346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch ConvBERT model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
from operator import attrgetter
|
| 20 |
+
from typing import Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.utils.checkpoint
|
| 24 |
+
from torch import nn
|
| 25 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 26 |
+
|
| 27 |
+
from ...activations import ACT2FN, get_activation
|
| 28 |
+
from ...modeling_outputs import (
|
| 29 |
+
BaseModelOutputWithCrossAttentions,
|
| 30 |
+
MaskedLMOutput,
|
| 31 |
+
MultipleChoiceModelOutput,
|
| 32 |
+
QuestionAnsweringModelOutput,
|
| 33 |
+
SequenceClassifierOutput,
|
| 34 |
+
TokenClassifierOutput,
|
| 35 |
+
)
|
| 36 |
+
from ...modeling_utils import PreTrainedModel, SequenceSummary
|
| 37 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 38 |
+
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 39 |
+
from .configuration_convbert import ConvBertConfig
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
_CHECKPOINT_FOR_DOC = "YituTech/conv-bert-base"
|
| 45 |
+
_CONFIG_FOR_DOC = "ConvBertConfig"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_tf_weights_in_convbert(model, config, tf_checkpoint_path):
|
| 49 |
+
"""Load tf checkpoints in a pytorch model."""
|
| 50 |
+
try:
|
| 51 |
+
import tensorflow as tf
|
| 52 |
+
except ImportError:
|
| 53 |
+
logger.error(
|
| 54 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
| 55 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
| 56 |
+
)
|
| 57 |
+
raise
|
| 58 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
| 59 |
+
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
|
| 60 |
+
# Load weights from TF model
|
| 61 |
+
init_vars = tf.train.list_variables(tf_path)
|
| 62 |
+
tf_data = {}
|
| 63 |
+
for name, shape in init_vars:
|
| 64 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
| 65 |
+
array = tf.train.load_variable(tf_path, name)
|
| 66 |
+
tf_data[name] = array
|
| 67 |
+
|
| 68 |
+
param_mapping = {
|
| 69 |
+
"embeddings.word_embeddings.weight": "electra/embeddings/word_embeddings",
|
| 70 |
+
"embeddings.position_embeddings.weight": "electra/embeddings/position_embeddings",
|
| 71 |
+
"embeddings.token_type_embeddings.weight": "electra/embeddings/token_type_embeddings",
|
| 72 |
+
"embeddings.LayerNorm.weight": "electra/embeddings/LayerNorm/gamma",
|
| 73 |
+
"embeddings.LayerNorm.bias": "electra/embeddings/LayerNorm/beta",
|
| 74 |
+
"embeddings_project.weight": "electra/embeddings_project/kernel",
|
| 75 |
+
"embeddings_project.bias": "electra/embeddings_project/bias",
|
| 76 |
+
}
|
| 77 |
+
if config.num_groups > 1:
|
| 78 |
+
group_dense_name = "g_dense"
|
| 79 |
+
else:
|
| 80 |
+
group_dense_name = "dense"
|
| 81 |
+
|
| 82 |
+
for j in range(config.num_hidden_layers):
|
| 83 |
+
param_mapping[f"encoder.layer.{j}.attention.self.query.weight"] = (
|
| 84 |
+
f"electra/encoder/layer_{j}/attention/self/query/kernel"
|
| 85 |
+
)
|
| 86 |
+
param_mapping[f"encoder.layer.{j}.attention.self.query.bias"] = (
|
| 87 |
+
f"electra/encoder/layer_{j}/attention/self/query/bias"
|
| 88 |
+
)
|
| 89 |
+
param_mapping[f"encoder.layer.{j}.attention.self.key.weight"] = (
|
| 90 |
+
f"electra/encoder/layer_{j}/attention/self/key/kernel"
|
| 91 |
+
)
|
| 92 |
+
param_mapping[f"encoder.layer.{j}.attention.self.key.bias"] = (
|
| 93 |
+
f"electra/encoder/layer_{j}/attention/self/key/bias"
|
| 94 |
+
)
|
| 95 |
+
param_mapping[f"encoder.layer.{j}.attention.self.value.weight"] = (
|
| 96 |
+
f"electra/encoder/layer_{j}/attention/self/value/kernel"
|
| 97 |
+
)
|
| 98 |
+
param_mapping[f"encoder.layer.{j}.attention.self.value.bias"] = (
|
| 99 |
+
f"electra/encoder/layer_{j}/attention/self/value/bias"
|
| 100 |
+
)
|
| 101 |
+
param_mapping[f"encoder.layer.{j}.attention.self.key_conv_attn_layer.depthwise.weight"] = (
|
| 102 |
+
f"electra/encoder/layer_{j}/attention/self/conv_attn_key/depthwise_kernel"
|
| 103 |
+
)
|
| 104 |
+
param_mapping[f"encoder.layer.{j}.attention.self.key_conv_attn_layer.pointwise.weight"] = (
|
| 105 |
+
f"electra/encoder/layer_{j}/attention/self/conv_attn_key/pointwise_kernel"
|
| 106 |
+
)
|
| 107 |
+
param_mapping[f"encoder.layer.{j}.attention.self.key_conv_attn_layer.bias"] = (
|
| 108 |
+
f"electra/encoder/layer_{j}/attention/self/conv_attn_key/bias"
|
| 109 |
+
)
|
| 110 |
+
param_mapping[f"encoder.layer.{j}.attention.self.conv_kernel_layer.weight"] = (
|
| 111 |
+
f"electra/encoder/layer_{j}/attention/self/conv_attn_kernel/kernel"
|
| 112 |
+
)
|
| 113 |
+
param_mapping[f"encoder.layer.{j}.attention.self.conv_kernel_layer.bias"] = (
|
| 114 |
+
f"electra/encoder/layer_{j}/attention/self/conv_attn_kernel/bias"
|
| 115 |
+
)
|
| 116 |
+
param_mapping[f"encoder.layer.{j}.attention.self.conv_out_layer.weight"] = (
|
| 117 |
+
f"electra/encoder/layer_{j}/attention/self/conv_attn_point/kernel"
|
| 118 |
+
)
|
| 119 |
+
param_mapping[f"encoder.layer.{j}.attention.self.conv_out_layer.bias"] = (
|
| 120 |
+
f"electra/encoder/layer_{j}/attention/self/conv_attn_point/bias"
|
| 121 |
+
)
|
| 122 |
+
param_mapping[f"encoder.layer.{j}.attention.output.dense.weight"] = (
|
| 123 |
+
f"electra/encoder/layer_{j}/attention/output/dense/kernel"
|
| 124 |
+
)
|
| 125 |
+
param_mapping[f"encoder.layer.{j}.attention.output.LayerNorm.weight"] = (
|
| 126 |
+
f"electra/encoder/layer_{j}/attention/output/LayerNorm/gamma"
|
| 127 |
+
)
|
| 128 |
+
param_mapping[f"encoder.layer.{j}.attention.output.dense.bias"] = (
|
| 129 |
+
f"electra/encoder/layer_{j}/attention/output/dense/bias"
|
| 130 |
+
)
|
| 131 |
+
param_mapping[f"encoder.layer.{j}.attention.output.LayerNorm.bias"] = (
|
| 132 |
+
f"electra/encoder/layer_{j}/attention/output/LayerNorm/beta"
|
| 133 |
+
)
|
| 134 |
+
param_mapping[f"encoder.layer.{j}.intermediate.dense.weight"] = (
|
| 135 |
+
f"electra/encoder/layer_{j}/intermediate/{group_dense_name}/kernel"
|
| 136 |
+
)
|
| 137 |
+
param_mapping[f"encoder.layer.{j}.intermediate.dense.bias"] = (
|
| 138 |
+
f"electra/encoder/layer_{j}/intermediate/{group_dense_name}/bias"
|
| 139 |
+
)
|
| 140 |
+
param_mapping[f"encoder.layer.{j}.output.dense.weight"] = (
|
| 141 |
+
f"electra/encoder/layer_{j}/output/{group_dense_name}/kernel"
|
| 142 |
+
)
|
| 143 |
+
param_mapping[f"encoder.layer.{j}.output.dense.bias"] = (
|
| 144 |
+
f"electra/encoder/layer_{j}/output/{group_dense_name}/bias"
|
| 145 |
+
)
|
| 146 |
+
param_mapping[f"encoder.layer.{j}.output.LayerNorm.weight"] = (
|
| 147 |
+
f"electra/encoder/layer_{j}/output/LayerNorm/gamma"
|
| 148 |
+
)
|
| 149 |
+
param_mapping[f"encoder.layer.{j}.output.LayerNorm.bias"] = f"electra/encoder/layer_{j}/output/LayerNorm/beta"
|
| 150 |
+
|
| 151 |
+
for param in model.named_parameters():
|
| 152 |
+
param_name = param[0]
|
| 153 |
+
retriever = attrgetter(param_name)
|
| 154 |
+
result = retriever(model)
|
| 155 |
+
tf_name = param_mapping[param_name]
|
| 156 |
+
value = torch.from_numpy(tf_data[tf_name])
|
| 157 |
+
logger.info(f"TF: {tf_name}, PT: {param_name} ")
|
| 158 |
+
if tf_name.endswith("/kernel"):
|
| 159 |
+
if not tf_name.endswith("/intermediate/g_dense/kernel"):
|
| 160 |
+
if not tf_name.endswith("/output/g_dense/kernel"):
|
| 161 |
+
value = value.T
|
| 162 |
+
if tf_name.endswith("/depthwise_kernel"):
|
| 163 |
+
value = value.permute(1, 2, 0) # 2, 0, 1
|
| 164 |
+
if tf_name.endswith("/pointwise_kernel"):
|
| 165 |
+
value = value.permute(2, 1, 0) # 2, 1, 0
|
| 166 |
+
if tf_name.endswith("/conv_attn_key/bias"):
|
| 167 |
+
value = value.unsqueeze(-1)
|
| 168 |
+
result.data = value
|
| 169 |
+
return model
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class ConvBertEmbeddings(nn.Module):
|
| 173 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 174 |
+
|
| 175 |
+
def __init__(self, config):
|
| 176 |
+
super().__init__()
|
| 177 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
|
| 178 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.embedding_size)
|
| 179 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.embedding_size)
|
| 180 |
+
|
| 181 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 182 |
+
# any TensorFlow checkpoint file
|
| 183 |
+
self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
|
| 184 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 185 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 186 |
+
self.register_buffer(
|
| 187 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 188 |
+
)
|
| 189 |
+
self.register_buffer(
|
| 190 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
def forward(
|
| 194 |
+
self,
|
| 195 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 196 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 197 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 198 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 199 |
+
) -> torch.LongTensor:
|
| 200 |
+
if input_ids is not None:
|
| 201 |
+
input_shape = input_ids.size()
|
| 202 |
+
else:
|
| 203 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 204 |
+
|
| 205 |
+
seq_length = input_shape[1]
|
| 206 |
+
|
| 207 |
+
if position_ids is None:
|
| 208 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 209 |
+
|
| 210 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 211 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 212 |
+
# issue #5664
|
| 213 |
+
if token_type_ids is None:
|
| 214 |
+
if hasattr(self, "token_type_ids"):
|
| 215 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 216 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 217 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 218 |
+
else:
|
| 219 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 220 |
+
|
| 221 |
+
if inputs_embeds is None:
|
| 222 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 223 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 224 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 225 |
+
|
| 226 |
+
embeddings = inputs_embeds + position_embeddings + token_type_embeddings
|
| 227 |
+
embeddings = self.LayerNorm(embeddings)
|
| 228 |
+
embeddings = self.dropout(embeddings)
|
| 229 |
+
return embeddings
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
class ConvBertPreTrainedModel(PreTrainedModel):
|
| 233 |
+
"""
|
| 234 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 235 |
+
models.
|
| 236 |
+
"""
|
| 237 |
+
|
| 238 |
+
config_class = ConvBertConfig
|
| 239 |
+
load_tf_weights = load_tf_weights_in_convbert
|
| 240 |
+
base_model_prefix = "convbert"
|
| 241 |
+
supports_gradient_checkpointing = True
|
| 242 |
+
|
| 243 |
+
def _init_weights(self, module):
|
| 244 |
+
"""Initialize the weights"""
|
| 245 |
+
if isinstance(module, nn.Linear):
|
| 246 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 247 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 248 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 249 |
+
if module.bias is not None:
|
| 250 |
+
module.bias.data.zero_()
|
| 251 |
+
elif isinstance(module, nn.Embedding):
|
| 252 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 253 |
+
if module.padding_idx is not None:
|
| 254 |
+
module.weight.data[module.padding_idx].zero_()
|
| 255 |
+
elif isinstance(module, nn.LayerNorm):
|
| 256 |
+
module.bias.data.zero_()
|
| 257 |
+
module.weight.data.fill_(1.0)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class SeparableConv1D(nn.Module):
|
| 261 |
+
"""This class implements separable convolution, i.e. a depthwise and a pointwise layer"""
|
| 262 |
+
|
| 263 |
+
def __init__(self, config, input_filters, output_filters, kernel_size, **kwargs):
|
| 264 |
+
super().__init__()
|
| 265 |
+
self.depthwise = nn.Conv1d(
|
| 266 |
+
input_filters,
|
| 267 |
+
input_filters,
|
| 268 |
+
kernel_size=kernel_size,
|
| 269 |
+
groups=input_filters,
|
| 270 |
+
padding=kernel_size // 2,
|
| 271 |
+
bias=False,
|
| 272 |
+
)
|
| 273 |
+
self.pointwise = nn.Conv1d(input_filters, output_filters, kernel_size=1, bias=False)
|
| 274 |
+
self.bias = nn.Parameter(torch.zeros(output_filters, 1))
|
| 275 |
+
|
| 276 |
+
self.depthwise.weight.data.normal_(mean=0.0, std=config.initializer_range)
|
| 277 |
+
self.pointwise.weight.data.normal_(mean=0.0, std=config.initializer_range)
|
| 278 |
+
|
| 279 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 280 |
+
x = self.depthwise(hidden_states)
|
| 281 |
+
x = self.pointwise(x)
|
| 282 |
+
x += self.bias
|
| 283 |
+
return x
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class ConvBertSelfAttention(nn.Module):
|
| 287 |
+
def __init__(self, config):
|
| 288 |
+
super().__init__()
|
| 289 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 290 |
+
raise ValueError(
|
| 291 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 292 |
+
f"heads ({config.num_attention_heads})"
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
new_num_attention_heads = config.num_attention_heads // config.head_ratio
|
| 296 |
+
if new_num_attention_heads < 1:
|
| 297 |
+
self.head_ratio = config.num_attention_heads
|
| 298 |
+
self.num_attention_heads = 1
|
| 299 |
+
else:
|
| 300 |
+
self.num_attention_heads = new_num_attention_heads
|
| 301 |
+
self.head_ratio = config.head_ratio
|
| 302 |
+
|
| 303 |
+
self.conv_kernel_size = config.conv_kernel_size
|
| 304 |
+
if config.hidden_size % self.num_attention_heads != 0:
|
| 305 |
+
raise ValueError("hidden_size should be divisible by num_attention_heads")
|
| 306 |
+
|
| 307 |
+
self.attention_head_size = (config.hidden_size // self.num_attention_heads) // 2
|
| 308 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 309 |
+
|
| 310 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 311 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 312 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 313 |
+
|
| 314 |
+
self.key_conv_attn_layer = SeparableConv1D(
|
| 315 |
+
config, config.hidden_size, self.all_head_size, self.conv_kernel_size
|
| 316 |
+
)
|
| 317 |
+
self.conv_kernel_layer = nn.Linear(self.all_head_size, self.num_attention_heads * self.conv_kernel_size)
|
| 318 |
+
self.conv_out_layer = nn.Linear(config.hidden_size, self.all_head_size)
|
| 319 |
+
|
| 320 |
+
self.unfold = nn.Unfold(
|
| 321 |
+
kernel_size=[self.conv_kernel_size, 1], padding=[int((self.conv_kernel_size - 1) / 2), 0]
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 325 |
+
|
| 326 |
+
def transpose_for_scores(self, x):
|
| 327 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 328 |
+
x = x.view(*new_x_shape)
|
| 329 |
+
return x.permute(0, 2, 1, 3)
|
| 330 |
+
|
| 331 |
+
def forward(
|
| 332 |
+
self,
|
| 333 |
+
hidden_states: torch.Tensor,
|
| 334 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 335 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 336 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 337 |
+
output_attentions: Optional[bool] = False,
|
| 338 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 339 |
+
mixed_query_layer = self.query(hidden_states)
|
| 340 |
+
batch_size = hidden_states.size(0)
|
| 341 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 342 |
+
# and values come from an encoder; the attention mask needs to be
|
| 343 |
+
# such that the encoder's padding tokens are not attended to.
|
| 344 |
+
if encoder_hidden_states is not None:
|
| 345 |
+
mixed_key_layer = self.key(encoder_hidden_states)
|
| 346 |
+
mixed_value_layer = self.value(encoder_hidden_states)
|
| 347 |
+
else:
|
| 348 |
+
mixed_key_layer = self.key(hidden_states)
|
| 349 |
+
mixed_value_layer = self.value(hidden_states)
|
| 350 |
+
|
| 351 |
+
mixed_key_conv_attn_layer = self.key_conv_attn_layer(hidden_states.transpose(1, 2))
|
| 352 |
+
mixed_key_conv_attn_layer = mixed_key_conv_attn_layer.transpose(1, 2)
|
| 353 |
+
|
| 354 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 355 |
+
key_layer = self.transpose_for_scores(mixed_key_layer)
|
| 356 |
+
value_layer = self.transpose_for_scores(mixed_value_layer)
|
| 357 |
+
conv_attn_layer = torch.multiply(mixed_key_conv_attn_layer, mixed_query_layer)
|
| 358 |
+
|
| 359 |
+
conv_kernel_layer = self.conv_kernel_layer(conv_attn_layer)
|
| 360 |
+
conv_kernel_layer = torch.reshape(conv_kernel_layer, [-1, self.conv_kernel_size, 1])
|
| 361 |
+
conv_kernel_layer = torch.softmax(conv_kernel_layer, dim=1)
|
| 362 |
+
|
| 363 |
+
conv_out_layer = self.conv_out_layer(hidden_states)
|
| 364 |
+
conv_out_layer = torch.reshape(conv_out_layer, [batch_size, -1, self.all_head_size])
|
| 365 |
+
conv_out_layer = conv_out_layer.transpose(1, 2).contiguous().unsqueeze(-1)
|
| 366 |
+
conv_out_layer = nn.functional.unfold(
|
| 367 |
+
conv_out_layer,
|
| 368 |
+
kernel_size=[self.conv_kernel_size, 1],
|
| 369 |
+
dilation=1,
|
| 370 |
+
padding=[(self.conv_kernel_size - 1) // 2, 0],
|
| 371 |
+
stride=1,
|
| 372 |
+
)
|
| 373 |
+
conv_out_layer = conv_out_layer.transpose(1, 2).reshape(
|
| 374 |
+
batch_size, -1, self.all_head_size, self.conv_kernel_size
|
| 375 |
+
)
|
| 376 |
+
conv_out_layer = torch.reshape(conv_out_layer, [-1, self.attention_head_size, self.conv_kernel_size])
|
| 377 |
+
conv_out_layer = torch.matmul(conv_out_layer, conv_kernel_layer)
|
| 378 |
+
conv_out_layer = torch.reshape(conv_out_layer, [-1, self.all_head_size])
|
| 379 |
+
|
| 380 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 381 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 382 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 383 |
+
if attention_mask is not None:
|
| 384 |
+
# Apply the attention mask is (precomputed for all layers in ConvBertModel forward() function)
|
| 385 |
+
attention_scores = attention_scores + attention_mask
|
| 386 |
+
|
| 387 |
+
# Normalize the attention scores to probabilities.
|
| 388 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 389 |
+
|
| 390 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 391 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 392 |
+
attention_probs = self.dropout(attention_probs)
|
| 393 |
+
|
| 394 |
+
# Mask heads if we want to
|
| 395 |
+
if head_mask is not None:
|
| 396 |
+
attention_probs = attention_probs * head_mask
|
| 397 |
+
|
| 398 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 399 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 400 |
+
|
| 401 |
+
conv_out = torch.reshape(conv_out_layer, [batch_size, -1, self.num_attention_heads, self.attention_head_size])
|
| 402 |
+
context_layer = torch.cat([context_layer, conv_out], 2)
|
| 403 |
+
|
| 404 |
+
# conv and context
|
| 405 |
+
new_context_layer_shape = context_layer.size()[:-2] + (
|
| 406 |
+
self.num_attention_heads * self.attention_head_size * 2,
|
| 407 |
+
)
|
| 408 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
| 409 |
+
|
| 410 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 411 |
+
return outputs
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
class ConvBertSelfOutput(nn.Module):
|
| 415 |
+
def __init__(self, config):
|
| 416 |
+
super().__init__()
|
| 417 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 418 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 419 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 420 |
+
|
| 421 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 422 |
+
hidden_states = self.dense(hidden_states)
|
| 423 |
+
hidden_states = self.dropout(hidden_states)
|
| 424 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 425 |
+
return hidden_states
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
class ConvBertAttention(nn.Module):
|
| 429 |
+
def __init__(self, config):
|
| 430 |
+
super().__init__()
|
| 431 |
+
self.self = ConvBertSelfAttention(config)
|
| 432 |
+
self.output = ConvBertSelfOutput(config)
|
| 433 |
+
self.pruned_heads = set()
|
| 434 |
+
|
| 435 |
+
def prune_heads(self, heads):
|
| 436 |
+
if len(heads) == 0:
|
| 437 |
+
return
|
| 438 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 439 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
# Prune linear layers
|
| 443 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 444 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 445 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 446 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 447 |
+
|
| 448 |
+
# Update hyper params and store pruned heads
|
| 449 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 450 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 451 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 452 |
+
|
| 453 |
+
def forward(
|
| 454 |
+
self,
|
| 455 |
+
hidden_states: torch.Tensor,
|
| 456 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 457 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 458 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 459 |
+
output_attentions: Optional[bool] = False,
|
| 460 |
+
) -> Tuple[torch.Tensor, Optional[torch.FloatTensor]]:
|
| 461 |
+
self_outputs = self.self(
|
| 462 |
+
hidden_states,
|
| 463 |
+
attention_mask,
|
| 464 |
+
head_mask,
|
| 465 |
+
encoder_hidden_states,
|
| 466 |
+
output_attentions,
|
| 467 |
+
)
|
| 468 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 469 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 470 |
+
return outputs
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
class GroupedLinearLayer(nn.Module):
|
| 474 |
+
def __init__(self, input_size, output_size, num_groups):
|
| 475 |
+
super().__init__()
|
| 476 |
+
self.input_size = input_size
|
| 477 |
+
self.output_size = output_size
|
| 478 |
+
self.num_groups = num_groups
|
| 479 |
+
self.group_in_dim = self.input_size // self.num_groups
|
| 480 |
+
self.group_out_dim = self.output_size // self.num_groups
|
| 481 |
+
self.weight = nn.Parameter(torch.empty(self.num_groups, self.group_in_dim, self.group_out_dim))
|
| 482 |
+
self.bias = nn.Parameter(torch.empty(output_size))
|
| 483 |
+
|
| 484 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 485 |
+
batch_size = list(hidden_states.size())[0]
|
| 486 |
+
x = torch.reshape(hidden_states, [-1, self.num_groups, self.group_in_dim])
|
| 487 |
+
x = x.permute(1, 0, 2)
|
| 488 |
+
x = torch.matmul(x, self.weight)
|
| 489 |
+
x = x.permute(1, 0, 2)
|
| 490 |
+
x = torch.reshape(x, [batch_size, -1, self.output_size])
|
| 491 |
+
x = x + self.bias
|
| 492 |
+
return x
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
class ConvBertIntermediate(nn.Module):
|
| 496 |
+
def __init__(self, config):
|
| 497 |
+
super().__init__()
|
| 498 |
+
if config.num_groups == 1:
|
| 499 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 500 |
+
else:
|
| 501 |
+
self.dense = GroupedLinearLayer(
|
| 502 |
+
input_size=config.hidden_size, output_size=config.intermediate_size, num_groups=config.num_groups
|
| 503 |
+
)
|
| 504 |
+
if isinstance(config.hidden_act, str):
|
| 505 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 506 |
+
else:
|
| 507 |
+
self.intermediate_act_fn = config.hidden_act
|
| 508 |
+
|
| 509 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 510 |
+
hidden_states = self.dense(hidden_states)
|
| 511 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 512 |
+
return hidden_states
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
class ConvBertOutput(nn.Module):
|
| 516 |
+
def __init__(self, config):
|
| 517 |
+
super().__init__()
|
| 518 |
+
if config.num_groups == 1:
|
| 519 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 520 |
+
else:
|
| 521 |
+
self.dense = GroupedLinearLayer(
|
| 522 |
+
input_size=config.intermediate_size, output_size=config.hidden_size, num_groups=config.num_groups
|
| 523 |
+
)
|
| 524 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 525 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 526 |
+
|
| 527 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 528 |
+
hidden_states = self.dense(hidden_states)
|
| 529 |
+
hidden_states = self.dropout(hidden_states)
|
| 530 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 531 |
+
return hidden_states
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
class ConvBertLayer(nn.Module):
|
| 535 |
+
def __init__(self, config):
|
| 536 |
+
super().__init__()
|
| 537 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 538 |
+
self.seq_len_dim = 1
|
| 539 |
+
self.attention = ConvBertAttention(config)
|
| 540 |
+
self.is_decoder = config.is_decoder
|
| 541 |
+
self.add_cross_attention = config.add_cross_attention
|
| 542 |
+
if self.add_cross_attention:
|
| 543 |
+
if not self.is_decoder:
|
| 544 |
+
raise TypeError(f"{self} should be used as a decoder model if cross attention is added")
|
| 545 |
+
self.crossattention = ConvBertAttention(config)
|
| 546 |
+
self.intermediate = ConvBertIntermediate(config)
|
| 547 |
+
self.output = ConvBertOutput(config)
|
| 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.Tensor] = None,
|
| 555 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 556 |
+
output_attentions: Optional[bool] = False,
|
| 557 |
+
) -> Tuple[torch.Tensor, Optional[torch.FloatTensor]]:
|
| 558 |
+
self_attention_outputs = self.attention(
|
| 559 |
+
hidden_states,
|
| 560 |
+
attention_mask,
|
| 561 |
+
head_mask,
|
| 562 |
+
output_attentions=output_attentions,
|
| 563 |
+
)
|
| 564 |
+
attention_output = self_attention_outputs[0]
|
| 565 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 566 |
+
|
| 567 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 568 |
+
if not hasattr(self, "crossattention"):
|
| 569 |
+
raise AttributeError(
|
| 570 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 571 |
+
" by setting `config.add_cross_attention=True`"
|
| 572 |
+
)
|
| 573 |
+
cross_attention_outputs = self.crossattention(
|
| 574 |
+
attention_output,
|
| 575 |
+
encoder_attention_mask,
|
| 576 |
+
head_mask,
|
| 577 |
+
encoder_hidden_states,
|
| 578 |
+
output_attentions,
|
| 579 |
+
)
|
| 580 |
+
attention_output = cross_attention_outputs[0]
|
| 581 |
+
outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
|
| 582 |
+
|
| 583 |
+
layer_output = apply_chunking_to_forward(
|
| 584 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 585 |
+
)
|
| 586 |
+
outputs = (layer_output,) + outputs
|
| 587 |
+
return outputs
|
| 588 |
+
|
| 589 |
+
def feed_forward_chunk(self, attention_output):
|
| 590 |
+
intermediate_output = self.intermediate(attention_output)
|
| 591 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 592 |
+
return layer_output
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
class ConvBertEncoder(nn.Module):
|
| 596 |
+
def __init__(self, config):
|
| 597 |
+
super().__init__()
|
| 598 |
+
self.config = config
|
| 599 |
+
self.layer = nn.ModuleList([ConvBertLayer(config) for _ in range(config.num_hidden_layers)])
|
| 600 |
+
self.gradient_checkpointing = False
|
| 601 |
+
|
| 602 |
+
def forward(
|
| 603 |
+
self,
|
| 604 |
+
hidden_states: torch.Tensor,
|
| 605 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 606 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 607 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 608 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 609 |
+
output_attentions: Optional[bool] = False,
|
| 610 |
+
output_hidden_states: Optional[bool] = False,
|
| 611 |
+
return_dict: Optional[bool] = True,
|
| 612 |
+
) -> Union[Tuple, BaseModelOutputWithCrossAttentions]:
|
| 613 |
+
all_hidden_states = () if output_hidden_states else None
|
| 614 |
+
all_self_attentions = () if output_attentions else None
|
| 615 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 616 |
+
for i, layer_module in enumerate(self.layer):
|
| 617 |
+
if output_hidden_states:
|
| 618 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 619 |
+
|
| 620 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 621 |
+
|
| 622 |
+
if self.gradient_checkpointing and self.training:
|
| 623 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 624 |
+
layer_module.__call__,
|
| 625 |
+
hidden_states,
|
| 626 |
+
attention_mask,
|
| 627 |
+
layer_head_mask,
|
| 628 |
+
encoder_hidden_states,
|
| 629 |
+
encoder_attention_mask,
|
| 630 |
+
output_attentions,
|
| 631 |
+
)
|
| 632 |
+
else:
|
| 633 |
+
layer_outputs = layer_module(
|
| 634 |
+
hidden_states,
|
| 635 |
+
attention_mask,
|
| 636 |
+
layer_head_mask,
|
| 637 |
+
encoder_hidden_states,
|
| 638 |
+
encoder_attention_mask,
|
| 639 |
+
output_attentions,
|
| 640 |
+
)
|
| 641 |
+
hidden_states = layer_outputs[0]
|
| 642 |
+
if output_attentions:
|
| 643 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 644 |
+
if self.config.add_cross_attention:
|
| 645 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 646 |
+
|
| 647 |
+
if output_hidden_states:
|
| 648 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 649 |
+
|
| 650 |
+
if not return_dict:
|
| 651 |
+
return tuple(
|
| 652 |
+
v
|
| 653 |
+
for v in [hidden_states, all_hidden_states, all_self_attentions, all_cross_attentions]
|
| 654 |
+
if v is not None
|
| 655 |
+
)
|
| 656 |
+
return BaseModelOutputWithCrossAttentions(
|
| 657 |
+
last_hidden_state=hidden_states,
|
| 658 |
+
hidden_states=all_hidden_states,
|
| 659 |
+
attentions=all_self_attentions,
|
| 660 |
+
cross_attentions=all_cross_attentions,
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
class ConvBertPredictionHeadTransform(nn.Module):
|
| 665 |
+
def __init__(self, config):
|
| 666 |
+
super().__init__()
|
| 667 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 668 |
+
if isinstance(config.hidden_act, str):
|
| 669 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 670 |
+
else:
|
| 671 |
+
self.transform_act_fn = config.hidden_act
|
| 672 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 673 |
+
|
| 674 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 675 |
+
hidden_states = self.dense(hidden_states)
|
| 676 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 677 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 678 |
+
return hidden_states
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
CONVBERT_START_DOCSTRING = r"""
|
| 682 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
|
| 683 |
+
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 684 |
+
behavior.
|
| 685 |
+
|
| 686 |
+
Parameters:
|
| 687 |
+
config ([`ConvBertConfig`]): Model configuration class with all the parameters of the model.
|
| 688 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 689 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 690 |
+
"""
|
| 691 |
+
|
| 692 |
+
CONVBERT_INPUTS_DOCSTRING = r"""
|
| 693 |
+
Args:
|
| 694 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
| 695 |
+
Indices of input sequence tokens in the vocabulary.
|
| 696 |
+
|
| 697 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 698 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 699 |
+
|
| 700 |
+
[What are input IDs?](../glossary#input-ids)
|
| 701 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
| 702 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
- 1 for tokens that are **not masked**,
|
| 706 |
+
- 0 for tokens that are **masked**.
|
| 707 |
+
|
| 708 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 709 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 710 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 711 |
+
1]`:
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
- 0 corresponds to a *sentence A* token,
|
| 715 |
+
- 1 corresponds to a *sentence B* token.
|
| 716 |
+
|
| 717 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 718 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 719 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 720 |
+
config.max_position_embeddings - 1]`.
|
| 721 |
+
|
| 722 |
+
[What are position IDs?](../glossary#position-ids)
|
| 723 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 724 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
- 1 indicates the head is **not masked**,
|
| 728 |
+
- 0 indicates the head is **masked**.
|
| 729 |
+
|
| 730 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 731 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 732 |
+
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
|
| 733 |
+
model's internal embedding lookup matrix.
|
| 734 |
+
output_attentions (`bool`, *optional*):
|
| 735 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 736 |
+
tensors for more detail.
|
| 737 |
+
output_hidden_states (`bool`, *optional*):
|
| 738 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 739 |
+
more detail.
|
| 740 |
+
return_dict (`bool`, *optional*):
|
| 741 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 742 |
+
"""
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
@add_start_docstrings(
|
| 746 |
+
"The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.",
|
| 747 |
+
CONVBERT_START_DOCSTRING,
|
| 748 |
+
)
|
| 749 |
+
class ConvBertModel(ConvBertPreTrainedModel):
|
| 750 |
+
def __init__(self, config):
|
| 751 |
+
super().__init__(config)
|
| 752 |
+
self.embeddings = ConvBertEmbeddings(config)
|
| 753 |
+
|
| 754 |
+
if config.embedding_size != config.hidden_size:
|
| 755 |
+
self.embeddings_project = nn.Linear(config.embedding_size, config.hidden_size)
|
| 756 |
+
|
| 757 |
+
self.encoder = ConvBertEncoder(config)
|
| 758 |
+
self.config = config
|
| 759 |
+
# Initialize weights and apply final processing
|
| 760 |
+
self.post_init()
|
| 761 |
+
|
| 762 |
+
def get_input_embeddings(self):
|
| 763 |
+
return self.embeddings.word_embeddings
|
| 764 |
+
|
| 765 |
+
def set_input_embeddings(self, value):
|
| 766 |
+
self.embeddings.word_embeddings = value
|
| 767 |
+
|
| 768 |
+
def _prune_heads(self, heads_to_prune):
|
| 769 |
+
"""
|
| 770 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 771 |
+
class PreTrainedModel
|
| 772 |
+
"""
|
| 773 |
+
for layer, heads in heads_to_prune.items():
|
| 774 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 775 |
+
|
| 776 |
+
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 777 |
+
@add_code_sample_docstrings(
|
| 778 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 779 |
+
output_type=BaseModelOutputWithCrossAttentions,
|
| 780 |
+
config_class=_CONFIG_FOR_DOC,
|
| 781 |
+
)
|
| 782 |
+
def forward(
|
| 783 |
+
self,
|
| 784 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 785 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 786 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 787 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 788 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 789 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 790 |
+
output_attentions: Optional[bool] = None,
|
| 791 |
+
output_hidden_states: Optional[bool] = None,
|
| 792 |
+
return_dict: Optional[bool] = None,
|
| 793 |
+
) -> Union[Tuple, BaseModelOutputWithCrossAttentions]:
|
| 794 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 795 |
+
output_hidden_states = (
|
| 796 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 797 |
+
)
|
| 798 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 799 |
+
|
| 800 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 801 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 802 |
+
elif input_ids is not None:
|
| 803 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 804 |
+
input_shape = input_ids.size()
|
| 805 |
+
elif inputs_embeds is not None:
|
| 806 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 807 |
+
else:
|
| 808 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 809 |
+
|
| 810 |
+
batch_size, seq_length = input_shape
|
| 811 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 812 |
+
|
| 813 |
+
if attention_mask is None:
|
| 814 |
+
attention_mask = torch.ones(input_shape, device=device)
|
| 815 |
+
if token_type_ids is None:
|
| 816 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 817 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 818 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 819 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 820 |
+
else:
|
| 821 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 822 |
+
|
| 823 |
+
extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 824 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 825 |
+
|
| 826 |
+
hidden_states = self.embeddings(
|
| 827 |
+
input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
|
| 828 |
+
)
|
| 829 |
+
|
| 830 |
+
if hasattr(self, "embeddings_project"):
|
| 831 |
+
hidden_states = self.embeddings_project(hidden_states)
|
| 832 |
+
|
| 833 |
+
hidden_states = self.encoder(
|
| 834 |
+
hidden_states,
|
| 835 |
+
attention_mask=extended_attention_mask,
|
| 836 |
+
head_mask=head_mask,
|
| 837 |
+
output_attentions=output_attentions,
|
| 838 |
+
output_hidden_states=output_hidden_states,
|
| 839 |
+
return_dict=return_dict,
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
return hidden_states
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
class ConvBertGeneratorPredictions(nn.Module):
|
| 846 |
+
"""Prediction module for the generator, made up of two dense layers."""
|
| 847 |
+
|
| 848 |
+
def __init__(self, config):
|
| 849 |
+
super().__init__()
|
| 850 |
+
|
| 851 |
+
self.activation = get_activation("gelu")
|
| 852 |
+
self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
|
| 853 |
+
self.dense = nn.Linear(config.hidden_size, config.embedding_size)
|
| 854 |
+
|
| 855 |
+
def forward(self, generator_hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
| 856 |
+
hidden_states = self.dense(generator_hidden_states)
|
| 857 |
+
hidden_states = self.activation(hidden_states)
|
| 858 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 859 |
+
|
| 860 |
+
return hidden_states
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
@add_start_docstrings("""ConvBERT Model with a `language modeling` head on top.""", CONVBERT_START_DOCSTRING)
|
| 864 |
+
class ConvBertForMaskedLM(ConvBertPreTrainedModel):
|
| 865 |
+
_tied_weights_keys = ["generator.lm_head.weight"]
|
| 866 |
+
|
| 867 |
+
def __init__(self, config):
|
| 868 |
+
super().__init__(config)
|
| 869 |
+
|
| 870 |
+
self.convbert = ConvBertModel(config)
|
| 871 |
+
self.generator_predictions = ConvBertGeneratorPredictions(config)
|
| 872 |
+
|
| 873 |
+
self.generator_lm_head = nn.Linear(config.embedding_size, config.vocab_size)
|
| 874 |
+
# Initialize weights and apply final processing
|
| 875 |
+
self.post_init()
|
| 876 |
+
|
| 877 |
+
def get_output_embeddings(self):
|
| 878 |
+
return self.generator_lm_head
|
| 879 |
+
|
| 880 |
+
def set_output_embeddings(self, word_embeddings):
|
| 881 |
+
self.generator_lm_head = word_embeddings
|
| 882 |
+
|
| 883 |
+
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 884 |
+
@add_code_sample_docstrings(
|
| 885 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 886 |
+
output_type=MaskedLMOutput,
|
| 887 |
+
config_class=_CONFIG_FOR_DOC,
|
| 888 |
+
)
|
| 889 |
+
def forward(
|
| 890 |
+
self,
|
| 891 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 892 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 893 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 894 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 895 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 896 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 897 |
+
labels: Optional[torch.LongTensor] = None,
|
| 898 |
+
output_attentions: Optional[bool] = None,
|
| 899 |
+
output_hidden_states: Optional[bool] = None,
|
| 900 |
+
return_dict: Optional[bool] = None,
|
| 901 |
+
) -> Union[Tuple, MaskedLMOutput]:
|
| 902 |
+
r"""
|
| 903 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 904 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 905 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 906 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 907 |
+
"""
|
| 908 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 909 |
+
|
| 910 |
+
generator_hidden_states = self.convbert(
|
| 911 |
+
input_ids,
|
| 912 |
+
attention_mask,
|
| 913 |
+
token_type_ids,
|
| 914 |
+
position_ids,
|
| 915 |
+
head_mask,
|
| 916 |
+
inputs_embeds,
|
| 917 |
+
output_attentions,
|
| 918 |
+
output_hidden_states,
|
| 919 |
+
return_dict,
|
| 920 |
+
)
|
| 921 |
+
generator_sequence_output = generator_hidden_states[0]
|
| 922 |
+
|
| 923 |
+
prediction_scores = self.generator_predictions(generator_sequence_output)
|
| 924 |
+
prediction_scores = self.generator_lm_head(prediction_scores)
|
| 925 |
+
|
| 926 |
+
loss = None
|
| 927 |
+
# Masked language modeling softmax layer
|
| 928 |
+
if labels is not None:
|
| 929 |
+
loss_fct = nn.CrossEntropyLoss() # -100 index = padding token
|
| 930 |
+
loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 931 |
+
|
| 932 |
+
if not return_dict:
|
| 933 |
+
output = (prediction_scores,) + generator_hidden_states[1:]
|
| 934 |
+
return ((loss,) + output) if loss is not None else output
|
| 935 |
+
|
| 936 |
+
return MaskedLMOutput(
|
| 937 |
+
loss=loss,
|
| 938 |
+
logits=prediction_scores,
|
| 939 |
+
hidden_states=generator_hidden_states.hidden_states,
|
| 940 |
+
attentions=generator_hidden_states.attentions,
|
| 941 |
+
)
|
| 942 |
+
|
| 943 |
+
|
| 944 |
+
class ConvBertClassificationHead(nn.Module):
|
| 945 |
+
"""Head for sentence-level classification tasks."""
|
| 946 |
+
|
| 947 |
+
def __init__(self, config):
|
| 948 |
+
super().__init__()
|
| 949 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 950 |
+
classifier_dropout = (
|
| 951 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 952 |
+
)
|
| 953 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 954 |
+
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
|
| 955 |
+
|
| 956 |
+
self.config = config
|
| 957 |
+
|
| 958 |
+
def forward(self, hidden_states: torch.Tensor, **kwargs) -> torch.Tensor:
|
| 959 |
+
x = hidden_states[:, 0, :] # take <s> token (equiv. to [CLS])
|
| 960 |
+
x = self.dropout(x)
|
| 961 |
+
x = self.dense(x)
|
| 962 |
+
x = ACT2FN[self.config.hidden_act](x)
|
| 963 |
+
x = self.dropout(x)
|
| 964 |
+
x = self.out_proj(x)
|
| 965 |
+
return x
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
@add_start_docstrings(
|
| 969 |
+
"""
|
| 970 |
+
ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the
|
| 971 |
+
pooled output) e.g. for GLUE tasks.
|
| 972 |
+
""",
|
| 973 |
+
CONVBERT_START_DOCSTRING,
|
| 974 |
+
)
|
| 975 |
+
class ConvBertForSequenceClassification(ConvBertPreTrainedModel):
|
| 976 |
+
def __init__(self, config):
|
| 977 |
+
super().__init__(config)
|
| 978 |
+
self.num_labels = config.num_labels
|
| 979 |
+
self.config = config
|
| 980 |
+
self.convbert = ConvBertModel(config)
|
| 981 |
+
self.classifier = ConvBertClassificationHead(config)
|
| 982 |
+
|
| 983 |
+
# Initialize weights and apply final processing
|
| 984 |
+
self.post_init()
|
| 985 |
+
|
| 986 |
+
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 987 |
+
@add_code_sample_docstrings(
|
| 988 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 989 |
+
output_type=SequenceClassifierOutput,
|
| 990 |
+
config_class=_CONFIG_FOR_DOC,
|
| 991 |
+
)
|
| 992 |
+
def forward(
|
| 993 |
+
self,
|
| 994 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 995 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 996 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 997 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 998 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 999 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1000 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1001 |
+
output_attentions: Optional[bool] = None,
|
| 1002 |
+
output_hidden_states: Optional[bool] = None,
|
| 1003 |
+
return_dict: Optional[bool] = None,
|
| 1004 |
+
) -> Union[Tuple, SequenceClassifierOutput]:
|
| 1005 |
+
r"""
|
| 1006 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1007 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1008 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1009 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1010 |
+
"""
|
| 1011 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1012 |
+
|
| 1013 |
+
outputs = self.convbert(
|
| 1014 |
+
input_ids,
|
| 1015 |
+
attention_mask=attention_mask,
|
| 1016 |
+
token_type_ids=token_type_ids,
|
| 1017 |
+
position_ids=position_ids,
|
| 1018 |
+
head_mask=head_mask,
|
| 1019 |
+
inputs_embeds=inputs_embeds,
|
| 1020 |
+
output_attentions=output_attentions,
|
| 1021 |
+
output_hidden_states=output_hidden_states,
|
| 1022 |
+
return_dict=return_dict,
|
| 1023 |
+
)
|
| 1024 |
+
|
| 1025 |
+
sequence_output = outputs[0]
|
| 1026 |
+
logits = self.classifier(sequence_output)
|
| 1027 |
+
|
| 1028 |
+
loss = None
|
| 1029 |
+
if labels is not None:
|
| 1030 |
+
if self.config.problem_type is None:
|
| 1031 |
+
if self.num_labels == 1:
|
| 1032 |
+
self.config.problem_type = "regression"
|
| 1033 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1034 |
+
self.config.problem_type = "single_label_classification"
|
| 1035 |
+
else:
|
| 1036 |
+
self.config.problem_type = "multi_label_classification"
|
| 1037 |
+
|
| 1038 |
+
if self.config.problem_type == "regression":
|
| 1039 |
+
loss_fct = MSELoss()
|
| 1040 |
+
if self.num_labels == 1:
|
| 1041 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1042 |
+
else:
|
| 1043 |
+
loss = loss_fct(logits, labels)
|
| 1044 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1045 |
+
loss_fct = CrossEntropyLoss()
|
| 1046 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1047 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1048 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1049 |
+
loss = loss_fct(logits, labels)
|
| 1050 |
+
|
| 1051 |
+
if not return_dict:
|
| 1052 |
+
output = (logits,) + outputs[1:]
|
| 1053 |
+
return ((loss,) + output) if loss is not None else output
|
| 1054 |
+
|
| 1055 |
+
return SequenceClassifierOutput(
|
| 1056 |
+
loss=loss,
|
| 1057 |
+
logits=logits,
|
| 1058 |
+
hidden_states=outputs.hidden_states,
|
| 1059 |
+
attentions=outputs.attentions,
|
| 1060 |
+
)
|
| 1061 |
+
|
| 1062 |
+
|
| 1063 |
+
@add_start_docstrings(
|
| 1064 |
+
"""
|
| 1065 |
+
ConvBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 1066 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 1067 |
+
""",
|
| 1068 |
+
CONVBERT_START_DOCSTRING,
|
| 1069 |
+
)
|
| 1070 |
+
class ConvBertForMultipleChoice(ConvBertPreTrainedModel):
|
| 1071 |
+
def __init__(self, config):
|
| 1072 |
+
super().__init__(config)
|
| 1073 |
+
|
| 1074 |
+
self.convbert = ConvBertModel(config)
|
| 1075 |
+
self.sequence_summary = SequenceSummary(config)
|
| 1076 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 1077 |
+
|
| 1078 |
+
# Initialize weights and apply final processing
|
| 1079 |
+
self.post_init()
|
| 1080 |
+
|
| 1081 |
+
@add_start_docstrings_to_model_forward(
|
| 1082 |
+
CONVBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
|
| 1083 |
+
)
|
| 1084 |
+
@add_code_sample_docstrings(
|
| 1085 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1086 |
+
output_type=MultipleChoiceModelOutput,
|
| 1087 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1088 |
+
)
|
| 1089 |
+
def forward(
|
| 1090 |
+
self,
|
| 1091 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1092 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1093 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1094 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1095 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1096 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1097 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1098 |
+
output_attentions: Optional[bool] = None,
|
| 1099 |
+
output_hidden_states: Optional[bool] = None,
|
| 1100 |
+
return_dict: Optional[bool] = None,
|
| 1101 |
+
) -> Union[Tuple, MultipleChoiceModelOutput]:
|
| 1102 |
+
r"""
|
| 1103 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1104 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
| 1105 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
| 1106 |
+
`input_ids` above)
|
| 1107 |
+
"""
|
| 1108 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1109 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
| 1110 |
+
|
| 1111 |
+
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
| 1112 |
+
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 1113 |
+
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
| 1114 |
+
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
| 1115 |
+
inputs_embeds = (
|
| 1116 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
| 1117 |
+
if inputs_embeds is not None
|
| 1118 |
+
else None
|
| 1119 |
+
)
|
| 1120 |
+
|
| 1121 |
+
outputs = self.convbert(
|
| 1122 |
+
input_ids,
|
| 1123 |
+
attention_mask=attention_mask,
|
| 1124 |
+
token_type_ids=token_type_ids,
|
| 1125 |
+
position_ids=position_ids,
|
| 1126 |
+
head_mask=head_mask,
|
| 1127 |
+
inputs_embeds=inputs_embeds,
|
| 1128 |
+
output_attentions=output_attentions,
|
| 1129 |
+
output_hidden_states=output_hidden_states,
|
| 1130 |
+
return_dict=return_dict,
|
| 1131 |
+
)
|
| 1132 |
+
|
| 1133 |
+
sequence_output = outputs[0]
|
| 1134 |
+
|
| 1135 |
+
pooled_output = self.sequence_summary(sequence_output)
|
| 1136 |
+
logits = self.classifier(pooled_output)
|
| 1137 |
+
reshaped_logits = logits.view(-1, num_choices)
|
| 1138 |
+
|
| 1139 |
+
loss = None
|
| 1140 |
+
if labels is not None:
|
| 1141 |
+
loss_fct = CrossEntropyLoss()
|
| 1142 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 1143 |
+
|
| 1144 |
+
if not return_dict:
|
| 1145 |
+
output = (reshaped_logits,) + outputs[1:]
|
| 1146 |
+
return ((loss,) + output) if loss is not None else output
|
| 1147 |
+
|
| 1148 |
+
return MultipleChoiceModelOutput(
|
| 1149 |
+
loss=loss,
|
| 1150 |
+
logits=reshaped_logits,
|
| 1151 |
+
hidden_states=outputs.hidden_states,
|
| 1152 |
+
attentions=outputs.attentions,
|
| 1153 |
+
)
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
@add_start_docstrings(
|
| 1157 |
+
"""
|
| 1158 |
+
ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1159 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1160 |
+
""",
|
| 1161 |
+
CONVBERT_START_DOCSTRING,
|
| 1162 |
+
)
|
| 1163 |
+
class ConvBertForTokenClassification(ConvBertPreTrainedModel):
|
| 1164 |
+
def __init__(self, config):
|
| 1165 |
+
super().__init__(config)
|
| 1166 |
+
self.num_labels = config.num_labels
|
| 1167 |
+
|
| 1168 |
+
self.convbert = ConvBertModel(config)
|
| 1169 |
+
classifier_dropout = (
|
| 1170 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1171 |
+
)
|
| 1172 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1173 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1174 |
+
|
| 1175 |
+
# Initialize weights and apply final processing
|
| 1176 |
+
self.post_init()
|
| 1177 |
+
|
| 1178 |
+
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1179 |
+
@add_code_sample_docstrings(
|
| 1180 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1181 |
+
output_type=TokenClassifierOutput,
|
| 1182 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1183 |
+
)
|
| 1184 |
+
def forward(
|
| 1185 |
+
self,
|
| 1186 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1187 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1188 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1189 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1190 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1191 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1192 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1193 |
+
output_attentions: Optional[bool] = None,
|
| 1194 |
+
output_hidden_states: Optional[bool] = None,
|
| 1195 |
+
return_dict: Optional[bool] = None,
|
| 1196 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
| 1197 |
+
r"""
|
| 1198 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1199 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1200 |
+
"""
|
| 1201 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1202 |
+
|
| 1203 |
+
outputs = self.convbert(
|
| 1204 |
+
input_ids,
|
| 1205 |
+
attention_mask=attention_mask,
|
| 1206 |
+
token_type_ids=token_type_ids,
|
| 1207 |
+
position_ids=position_ids,
|
| 1208 |
+
head_mask=head_mask,
|
| 1209 |
+
inputs_embeds=inputs_embeds,
|
| 1210 |
+
output_attentions=output_attentions,
|
| 1211 |
+
output_hidden_states=output_hidden_states,
|
| 1212 |
+
return_dict=return_dict,
|
| 1213 |
+
)
|
| 1214 |
+
|
| 1215 |
+
sequence_output = outputs[0]
|
| 1216 |
+
|
| 1217 |
+
sequence_output = self.dropout(sequence_output)
|
| 1218 |
+
logits = self.classifier(sequence_output)
|
| 1219 |
+
|
| 1220 |
+
loss = None
|
| 1221 |
+
if labels is not None:
|
| 1222 |
+
loss_fct = CrossEntropyLoss()
|
| 1223 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1224 |
+
|
| 1225 |
+
if not return_dict:
|
| 1226 |
+
output = (logits,) + outputs[1:]
|
| 1227 |
+
return ((loss,) + output) if loss is not None else output
|
| 1228 |
+
|
| 1229 |
+
return TokenClassifierOutput(
|
| 1230 |
+
loss=loss,
|
| 1231 |
+
logits=logits,
|
| 1232 |
+
hidden_states=outputs.hidden_states,
|
| 1233 |
+
attentions=outputs.attentions,
|
| 1234 |
+
)
|
| 1235 |
+
|
| 1236 |
+
|
| 1237 |
+
@add_start_docstrings(
|
| 1238 |
+
"""
|
| 1239 |
+
ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1240 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1241 |
+
""",
|
| 1242 |
+
CONVBERT_START_DOCSTRING,
|
| 1243 |
+
)
|
| 1244 |
+
class ConvBertForQuestionAnswering(ConvBertPreTrainedModel):
|
| 1245 |
+
def __init__(self, config):
|
| 1246 |
+
super().__init__(config)
|
| 1247 |
+
|
| 1248 |
+
self.num_labels = config.num_labels
|
| 1249 |
+
self.convbert = ConvBertModel(config)
|
| 1250 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1251 |
+
|
| 1252 |
+
# Initialize weights and apply final processing
|
| 1253 |
+
self.post_init()
|
| 1254 |
+
|
| 1255 |
+
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1256 |
+
@add_code_sample_docstrings(
|
| 1257 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1258 |
+
output_type=QuestionAnsweringModelOutput,
|
| 1259 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1260 |
+
)
|
| 1261 |
+
def forward(
|
| 1262 |
+
self,
|
| 1263 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1264 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1265 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1266 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1267 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1268 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1269 |
+
start_positions: Optional[torch.LongTensor] = None,
|
| 1270 |
+
end_positions: Optional[torch.LongTensor] = None,
|
| 1271 |
+
output_attentions: Optional[bool] = None,
|
| 1272 |
+
output_hidden_states: Optional[bool] = None,
|
| 1273 |
+
return_dict: Optional[bool] = None,
|
| 1274 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
| 1275 |
+
r"""
|
| 1276 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1277 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1278 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1279 |
+
are not taken into account for computing the loss.
|
| 1280 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1281 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1282 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1283 |
+
are not taken into account for computing the loss.
|
| 1284 |
+
"""
|
| 1285 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1286 |
+
|
| 1287 |
+
outputs = self.convbert(
|
| 1288 |
+
input_ids,
|
| 1289 |
+
attention_mask=attention_mask,
|
| 1290 |
+
token_type_ids=token_type_ids,
|
| 1291 |
+
position_ids=position_ids,
|
| 1292 |
+
head_mask=head_mask,
|
| 1293 |
+
inputs_embeds=inputs_embeds,
|
| 1294 |
+
output_attentions=output_attentions,
|
| 1295 |
+
output_hidden_states=output_hidden_states,
|
| 1296 |
+
return_dict=return_dict,
|
| 1297 |
+
)
|
| 1298 |
+
|
| 1299 |
+
sequence_output = outputs[0]
|
| 1300 |
+
|
| 1301 |
+
logits = self.qa_outputs(sequence_output)
|
| 1302 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1303 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1304 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1305 |
+
|
| 1306 |
+
total_loss = None
|
| 1307 |
+
if start_positions is not None and end_positions is not None:
|
| 1308 |
+
# If we are on multi-GPU, split add a dimension
|
| 1309 |
+
if len(start_positions.size()) > 1:
|
| 1310 |
+
start_positions = start_positions.squeeze(-1)
|
| 1311 |
+
if len(end_positions.size()) > 1:
|
| 1312 |
+
end_positions = end_positions.squeeze(-1)
|
| 1313 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1314 |
+
ignored_index = start_logits.size(1)
|
| 1315 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1316 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1317 |
+
|
| 1318 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1319 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1320 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1321 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1322 |
+
|
| 1323 |
+
if not return_dict:
|
| 1324 |
+
output = (start_logits, end_logits) + outputs[1:]
|
| 1325 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1326 |
+
|
| 1327 |
+
return QuestionAnsweringModelOutput(
|
| 1328 |
+
loss=total_loss,
|
| 1329 |
+
start_logits=start_logits,
|
| 1330 |
+
end_logits=end_logits,
|
| 1331 |
+
hidden_states=outputs.hidden_states,
|
| 1332 |
+
attentions=outputs.attentions,
|
| 1333 |
+
)
|
| 1334 |
+
|
| 1335 |
+
|
| 1336 |
+
__all__ = [
|
| 1337 |
+
"ConvBertForMaskedLM",
|
| 1338 |
+
"ConvBertForMultipleChoice",
|
| 1339 |
+
"ConvBertForQuestionAnswering",
|
| 1340 |
+
"ConvBertForSequenceClassification",
|
| 1341 |
+
"ConvBertForTokenClassification",
|
| 1342 |
+
"ConvBertLayer",
|
| 1343 |
+
"ConvBertModel",
|
| 1344 |
+
"ConvBertPreTrainedModel",
|
| 1345 |
+
"load_tf_weights_in_convbert",
|
| 1346 |
+
]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/modeling_tf_convbert.py
ADDED
|
@@ -0,0 +1,1476 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""TF 2.0 ConvBERT model."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from typing import Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import tensorflow as tf
|
| 23 |
+
|
| 24 |
+
from ...activations_tf import get_tf_activation
|
| 25 |
+
from ...modeling_tf_outputs import (
|
| 26 |
+
TFBaseModelOutput,
|
| 27 |
+
TFMaskedLMOutput,
|
| 28 |
+
TFMultipleChoiceModelOutput,
|
| 29 |
+
TFQuestionAnsweringModelOutput,
|
| 30 |
+
TFSequenceClassifierOutput,
|
| 31 |
+
TFTokenClassifierOutput,
|
| 32 |
+
)
|
| 33 |
+
from ...modeling_tf_utils import (
|
| 34 |
+
TFMaskedLanguageModelingLoss,
|
| 35 |
+
TFModelInputType,
|
| 36 |
+
TFMultipleChoiceLoss,
|
| 37 |
+
TFPreTrainedModel,
|
| 38 |
+
TFQuestionAnsweringLoss,
|
| 39 |
+
TFSequenceClassificationLoss,
|
| 40 |
+
TFSequenceSummary,
|
| 41 |
+
TFTokenClassificationLoss,
|
| 42 |
+
get_initializer,
|
| 43 |
+
keras,
|
| 44 |
+
keras_serializable,
|
| 45 |
+
unpack_inputs,
|
| 46 |
+
)
|
| 47 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
| 48 |
+
from ...utils import (
|
| 49 |
+
add_code_sample_docstrings,
|
| 50 |
+
add_start_docstrings,
|
| 51 |
+
add_start_docstrings_to_model_forward,
|
| 52 |
+
logging,
|
| 53 |
+
)
|
| 54 |
+
from .configuration_convbert import ConvBertConfig
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
logger = logging.get_logger(__name__)
|
| 58 |
+
|
| 59 |
+
_CHECKPOINT_FOR_DOC = "YituTech/conv-bert-base"
|
| 60 |
+
_CONFIG_FOR_DOC = "ConvBertConfig"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# Copied from transformers.models.albert.modeling_tf_albert.TFAlbertEmbeddings with Albert->ConvBert
|
| 64 |
+
class TFConvBertEmbeddings(keras.layers.Layer):
|
| 65 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 66 |
+
|
| 67 |
+
def __init__(self, config: ConvBertConfig, **kwargs):
|
| 68 |
+
super().__init__(**kwargs)
|
| 69 |
+
|
| 70 |
+
self.config = config
|
| 71 |
+
self.embedding_size = config.embedding_size
|
| 72 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 73 |
+
self.initializer_range = config.initializer_range
|
| 74 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 75 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 76 |
+
|
| 77 |
+
def build(self, input_shape=None):
|
| 78 |
+
with tf.name_scope("word_embeddings"):
|
| 79 |
+
self.weight = self.add_weight(
|
| 80 |
+
name="weight",
|
| 81 |
+
shape=[self.config.vocab_size, self.embedding_size],
|
| 82 |
+
initializer=get_initializer(self.initializer_range),
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
with tf.name_scope("token_type_embeddings"):
|
| 86 |
+
self.token_type_embeddings = self.add_weight(
|
| 87 |
+
name="embeddings",
|
| 88 |
+
shape=[self.config.type_vocab_size, self.embedding_size],
|
| 89 |
+
initializer=get_initializer(self.initializer_range),
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
with tf.name_scope("position_embeddings"):
|
| 93 |
+
self.position_embeddings = self.add_weight(
|
| 94 |
+
name="embeddings",
|
| 95 |
+
shape=[self.max_position_embeddings, self.embedding_size],
|
| 96 |
+
initializer=get_initializer(self.initializer_range),
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
if self.built:
|
| 100 |
+
return
|
| 101 |
+
self.built = True
|
| 102 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 103 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 104 |
+
self.LayerNorm.build([None, None, self.config.embedding_size])
|
| 105 |
+
|
| 106 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertEmbeddings.call
|
| 107 |
+
def call(
|
| 108 |
+
self,
|
| 109 |
+
input_ids: tf.Tensor = None,
|
| 110 |
+
position_ids: tf.Tensor = None,
|
| 111 |
+
token_type_ids: tf.Tensor = None,
|
| 112 |
+
inputs_embeds: tf.Tensor = None,
|
| 113 |
+
past_key_values_length=0,
|
| 114 |
+
training: bool = False,
|
| 115 |
+
) -> tf.Tensor:
|
| 116 |
+
"""
|
| 117 |
+
Applies embedding based on inputs tensor.
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
final_embeddings (`tf.Tensor`): output embedding tensor.
|
| 121 |
+
"""
|
| 122 |
+
if input_ids is None and inputs_embeds is None:
|
| 123 |
+
raise ValueError("Need to provide either `input_ids` or `input_embeds`.")
|
| 124 |
+
|
| 125 |
+
if input_ids is not None:
|
| 126 |
+
check_embeddings_within_bounds(input_ids, self.config.vocab_size)
|
| 127 |
+
inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
|
| 128 |
+
|
| 129 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 130 |
+
|
| 131 |
+
if token_type_ids is None:
|
| 132 |
+
token_type_ids = tf.fill(dims=input_shape, value=0)
|
| 133 |
+
|
| 134 |
+
if position_ids is None:
|
| 135 |
+
position_ids = tf.expand_dims(
|
| 136 |
+
tf.range(start=past_key_values_length, limit=input_shape[1] + past_key_values_length), axis=0
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
|
| 140 |
+
token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
|
| 141 |
+
final_embeddings = inputs_embeds + position_embeds + token_type_embeds
|
| 142 |
+
final_embeddings = self.LayerNorm(inputs=final_embeddings)
|
| 143 |
+
final_embeddings = self.dropout(inputs=final_embeddings, training=training)
|
| 144 |
+
|
| 145 |
+
return final_embeddings
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class TFConvBertSelfAttention(keras.layers.Layer):
|
| 149 |
+
def __init__(self, config, **kwargs):
|
| 150 |
+
super().__init__(**kwargs)
|
| 151 |
+
|
| 152 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
| 153 |
+
raise ValueError(
|
| 154 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 155 |
+
f"heads ({config.num_attention_heads})"
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
new_num_attention_heads = int(config.num_attention_heads / config.head_ratio)
|
| 159 |
+
if new_num_attention_heads < 1:
|
| 160 |
+
self.head_ratio = config.num_attention_heads
|
| 161 |
+
num_attention_heads = 1
|
| 162 |
+
else:
|
| 163 |
+
num_attention_heads = new_num_attention_heads
|
| 164 |
+
self.head_ratio = config.head_ratio
|
| 165 |
+
|
| 166 |
+
self.num_attention_heads = num_attention_heads
|
| 167 |
+
self.conv_kernel_size = config.conv_kernel_size
|
| 168 |
+
|
| 169 |
+
if config.hidden_size % self.num_attention_heads != 0:
|
| 170 |
+
raise ValueError("hidden_size should be divisible by num_attention_heads")
|
| 171 |
+
|
| 172 |
+
self.attention_head_size = config.hidden_size // config.num_attention_heads
|
| 173 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 174 |
+
self.query = keras.layers.Dense(
|
| 175 |
+
self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
|
| 176 |
+
)
|
| 177 |
+
self.key = keras.layers.Dense(
|
| 178 |
+
self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
|
| 179 |
+
)
|
| 180 |
+
self.value = keras.layers.Dense(
|
| 181 |
+
self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
self.key_conv_attn_layer = keras.layers.SeparableConv1D(
|
| 185 |
+
self.all_head_size,
|
| 186 |
+
self.conv_kernel_size,
|
| 187 |
+
padding="same",
|
| 188 |
+
activation=None,
|
| 189 |
+
depthwise_initializer=get_initializer(1 / self.conv_kernel_size),
|
| 190 |
+
pointwise_initializer=get_initializer(config.initializer_range),
|
| 191 |
+
name="key_conv_attn_layer",
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
self.conv_kernel_layer = keras.layers.Dense(
|
| 195 |
+
self.num_attention_heads * self.conv_kernel_size,
|
| 196 |
+
activation=None,
|
| 197 |
+
name="conv_kernel_layer",
|
| 198 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
self.conv_out_layer = keras.layers.Dense(
|
| 202 |
+
self.all_head_size,
|
| 203 |
+
activation=None,
|
| 204 |
+
name="conv_out_layer",
|
| 205 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
self.dropout = keras.layers.Dropout(config.attention_probs_dropout_prob)
|
| 209 |
+
self.config = config
|
| 210 |
+
|
| 211 |
+
def transpose_for_scores(self, x, batch_size):
|
| 212 |
+
# Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
|
| 213 |
+
x = tf.reshape(x, (batch_size, -1, self.num_attention_heads, self.attention_head_size))
|
| 214 |
+
return tf.transpose(x, perm=[0, 2, 1, 3])
|
| 215 |
+
|
| 216 |
+
def call(self, hidden_states, attention_mask, head_mask, output_attentions, training=False):
|
| 217 |
+
batch_size = shape_list(hidden_states)[0]
|
| 218 |
+
mixed_query_layer = self.query(hidden_states)
|
| 219 |
+
mixed_key_layer = self.key(hidden_states)
|
| 220 |
+
mixed_value_layer = self.value(hidden_states)
|
| 221 |
+
|
| 222 |
+
mixed_key_conv_attn_layer = self.key_conv_attn_layer(hidden_states)
|
| 223 |
+
|
| 224 |
+
query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
|
| 225 |
+
key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)
|
| 226 |
+
conv_attn_layer = tf.multiply(mixed_key_conv_attn_layer, mixed_query_layer)
|
| 227 |
+
|
| 228 |
+
conv_kernel_layer = self.conv_kernel_layer(conv_attn_layer)
|
| 229 |
+
conv_kernel_layer = tf.reshape(conv_kernel_layer, [-1, self.conv_kernel_size, 1])
|
| 230 |
+
conv_kernel_layer = stable_softmax(conv_kernel_layer, axis=1)
|
| 231 |
+
|
| 232 |
+
paddings = tf.constant(
|
| 233 |
+
[
|
| 234 |
+
[
|
| 235 |
+
0,
|
| 236 |
+
0,
|
| 237 |
+
],
|
| 238 |
+
[int((self.conv_kernel_size - 1) / 2), int((self.conv_kernel_size - 1) / 2)],
|
| 239 |
+
[0, 0],
|
| 240 |
+
]
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
conv_out_layer = self.conv_out_layer(hidden_states)
|
| 244 |
+
conv_out_layer = tf.reshape(conv_out_layer, [batch_size, -1, self.all_head_size])
|
| 245 |
+
conv_out_layer = tf.pad(conv_out_layer, paddings, "CONSTANT")
|
| 246 |
+
|
| 247 |
+
unfold_conv_out_layer = tf.stack(
|
| 248 |
+
[
|
| 249 |
+
tf.slice(conv_out_layer, [0, i, 0], [batch_size, shape_list(mixed_query_layer)[1], self.all_head_size])
|
| 250 |
+
for i in range(self.conv_kernel_size)
|
| 251 |
+
],
|
| 252 |
+
axis=-1,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
conv_out_layer = tf.reshape(unfold_conv_out_layer, [-1, self.attention_head_size, self.conv_kernel_size])
|
| 256 |
+
|
| 257 |
+
conv_out_layer = tf.matmul(conv_out_layer, conv_kernel_layer)
|
| 258 |
+
conv_out_layer = tf.reshape(conv_out_layer, [-1, self.all_head_size])
|
| 259 |
+
|
| 260 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 261 |
+
attention_scores = tf.matmul(
|
| 262 |
+
query_layer, key_layer, transpose_b=True
|
| 263 |
+
) # (batch size, num_heads, seq_len_q, seq_len_k)
|
| 264 |
+
dk = tf.cast(shape_list(key_layer)[-1], attention_scores.dtype) # scale attention_scores
|
| 265 |
+
attention_scores = attention_scores / tf.math.sqrt(dk)
|
| 266 |
+
|
| 267 |
+
if attention_mask is not None:
|
| 268 |
+
# Apply the attention mask is (precomputed for all layers in TFBertModel call() function)
|
| 269 |
+
attention_scores = attention_scores + attention_mask
|
| 270 |
+
|
| 271 |
+
# Normalize the attention scores to probabilities.
|
| 272 |
+
attention_probs = stable_softmax(attention_scores, axis=-1)
|
| 273 |
+
|
| 274 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 275 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 276 |
+
attention_probs = self.dropout(attention_probs, training=training)
|
| 277 |
+
|
| 278 |
+
# Mask heads if we want to
|
| 279 |
+
if head_mask is not None:
|
| 280 |
+
attention_probs = attention_probs * head_mask
|
| 281 |
+
|
| 282 |
+
value_layer = tf.reshape(
|
| 283 |
+
mixed_value_layer, [batch_size, -1, self.num_attention_heads, self.attention_head_size]
|
| 284 |
+
)
|
| 285 |
+
value_layer = tf.transpose(value_layer, [0, 2, 1, 3])
|
| 286 |
+
|
| 287 |
+
context_layer = tf.matmul(attention_probs, value_layer)
|
| 288 |
+
context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])
|
| 289 |
+
|
| 290 |
+
conv_out = tf.reshape(conv_out_layer, [batch_size, -1, self.num_attention_heads, self.attention_head_size])
|
| 291 |
+
context_layer = tf.concat([context_layer, conv_out], 2)
|
| 292 |
+
context_layer = tf.reshape(
|
| 293 |
+
context_layer, (batch_size, -1, self.head_ratio * self.all_head_size)
|
| 294 |
+
) # (batch_size, seq_len_q, all_head_size)
|
| 295 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 296 |
+
|
| 297 |
+
return outputs
|
| 298 |
+
|
| 299 |
+
def build(self, input_shape=None):
|
| 300 |
+
if self.built:
|
| 301 |
+
return
|
| 302 |
+
self.built = True
|
| 303 |
+
if getattr(self, "query", None) is not None:
|
| 304 |
+
with tf.name_scope(self.query.name):
|
| 305 |
+
self.query.build([None, None, self.config.hidden_size])
|
| 306 |
+
if getattr(self, "key", None) is not None:
|
| 307 |
+
with tf.name_scope(self.key.name):
|
| 308 |
+
self.key.build([None, None, self.config.hidden_size])
|
| 309 |
+
if getattr(self, "value", None) is not None:
|
| 310 |
+
with tf.name_scope(self.value.name):
|
| 311 |
+
self.value.build([None, None, self.config.hidden_size])
|
| 312 |
+
if getattr(self, "key_conv_attn_layer", None) is not None:
|
| 313 |
+
with tf.name_scope(self.key_conv_attn_layer.name):
|
| 314 |
+
self.key_conv_attn_layer.build([None, None, self.config.hidden_size])
|
| 315 |
+
if getattr(self, "conv_kernel_layer", None) is not None:
|
| 316 |
+
with tf.name_scope(self.conv_kernel_layer.name):
|
| 317 |
+
self.conv_kernel_layer.build([None, None, self.all_head_size])
|
| 318 |
+
if getattr(self, "conv_out_layer", None) is not None:
|
| 319 |
+
with tf.name_scope(self.conv_out_layer.name):
|
| 320 |
+
self.conv_out_layer.build([None, None, self.config.hidden_size])
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class TFConvBertSelfOutput(keras.layers.Layer):
|
| 324 |
+
def __init__(self, config, **kwargs):
|
| 325 |
+
super().__init__(**kwargs)
|
| 326 |
+
|
| 327 |
+
self.dense = keras.layers.Dense(
|
| 328 |
+
config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 329 |
+
)
|
| 330 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 331 |
+
self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
|
| 332 |
+
self.config = config
|
| 333 |
+
|
| 334 |
+
def call(self, hidden_states, input_tensor, training=False):
|
| 335 |
+
hidden_states = self.dense(hidden_states)
|
| 336 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 337 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 338 |
+
|
| 339 |
+
return hidden_states
|
| 340 |
+
|
| 341 |
+
def build(self, input_shape=None):
|
| 342 |
+
if self.built:
|
| 343 |
+
return
|
| 344 |
+
self.built = True
|
| 345 |
+
if getattr(self, "dense", None) is not None:
|
| 346 |
+
with tf.name_scope(self.dense.name):
|
| 347 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 348 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 349 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 350 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
class TFConvBertAttention(keras.layers.Layer):
|
| 354 |
+
def __init__(self, config, **kwargs):
|
| 355 |
+
super().__init__(**kwargs)
|
| 356 |
+
|
| 357 |
+
self.self_attention = TFConvBertSelfAttention(config, name="self")
|
| 358 |
+
self.dense_output = TFConvBertSelfOutput(config, name="output")
|
| 359 |
+
|
| 360 |
+
def prune_heads(self, heads):
|
| 361 |
+
raise NotImplementedError
|
| 362 |
+
|
| 363 |
+
def call(self, input_tensor, attention_mask, head_mask, output_attentions, training=False):
|
| 364 |
+
self_outputs = self.self_attention(
|
| 365 |
+
input_tensor, attention_mask, head_mask, output_attentions, training=training
|
| 366 |
+
)
|
| 367 |
+
attention_output = self.dense_output(self_outputs[0], input_tensor, training=training)
|
| 368 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 369 |
+
|
| 370 |
+
return outputs
|
| 371 |
+
|
| 372 |
+
def build(self, input_shape=None):
|
| 373 |
+
if self.built:
|
| 374 |
+
return
|
| 375 |
+
self.built = True
|
| 376 |
+
if getattr(self, "self_attention", None) is not None:
|
| 377 |
+
with tf.name_scope(self.self_attention.name):
|
| 378 |
+
self.self_attention.build(None)
|
| 379 |
+
if getattr(self, "dense_output", None) is not None:
|
| 380 |
+
with tf.name_scope(self.dense_output.name):
|
| 381 |
+
self.dense_output.build(None)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class GroupedLinearLayer(keras.layers.Layer):
|
| 385 |
+
def __init__(self, input_size, output_size, num_groups, kernel_initializer, **kwargs):
|
| 386 |
+
super().__init__(**kwargs)
|
| 387 |
+
self.input_size = input_size
|
| 388 |
+
self.output_size = output_size
|
| 389 |
+
self.num_groups = num_groups
|
| 390 |
+
self.kernel_initializer = kernel_initializer
|
| 391 |
+
self.group_in_dim = self.input_size // self.num_groups
|
| 392 |
+
self.group_out_dim = self.output_size // self.num_groups
|
| 393 |
+
|
| 394 |
+
def build(self, input_shape=None):
|
| 395 |
+
self.kernel = self.add_weight(
|
| 396 |
+
"kernel",
|
| 397 |
+
shape=[self.group_out_dim, self.group_in_dim, self.num_groups],
|
| 398 |
+
initializer=self.kernel_initializer,
|
| 399 |
+
trainable=True,
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
self.bias = self.add_weight(
|
| 403 |
+
"bias", shape=[self.output_size], initializer=self.kernel_initializer, dtype=self.dtype, trainable=True
|
| 404 |
+
)
|
| 405 |
+
super().build(input_shape)
|
| 406 |
+
|
| 407 |
+
def call(self, hidden_states):
|
| 408 |
+
batch_size = shape_list(hidden_states)[0]
|
| 409 |
+
x = tf.transpose(tf.reshape(hidden_states, [-1, self.num_groups, self.group_in_dim]), [1, 0, 2])
|
| 410 |
+
x = tf.matmul(x, tf.transpose(self.kernel, [2, 1, 0]))
|
| 411 |
+
x = tf.transpose(x, [1, 0, 2])
|
| 412 |
+
x = tf.reshape(x, [batch_size, -1, self.output_size])
|
| 413 |
+
x = tf.nn.bias_add(value=x, bias=self.bias)
|
| 414 |
+
return x
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class TFConvBertIntermediate(keras.layers.Layer):
|
| 418 |
+
def __init__(self, config, **kwargs):
|
| 419 |
+
super().__init__(**kwargs)
|
| 420 |
+
if config.num_groups == 1:
|
| 421 |
+
self.dense = keras.layers.Dense(
|
| 422 |
+
config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 423 |
+
)
|
| 424 |
+
else:
|
| 425 |
+
self.dense = GroupedLinearLayer(
|
| 426 |
+
config.hidden_size,
|
| 427 |
+
config.intermediate_size,
|
| 428 |
+
num_groups=config.num_groups,
|
| 429 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 430 |
+
name="dense",
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
if isinstance(config.hidden_act, str):
|
| 434 |
+
self.intermediate_act_fn = get_tf_activation(config.hidden_act)
|
| 435 |
+
else:
|
| 436 |
+
self.intermediate_act_fn = config.hidden_act
|
| 437 |
+
self.config = config
|
| 438 |
+
|
| 439 |
+
def call(self, hidden_states):
|
| 440 |
+
hidden_states = self.dense(hidden_states)
|
| 441 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 442 |
+
|
| 443 |
+
return hidden_states
|
| 444 |
+
|
| 445 |
+
def build(self, input_shape=None):
|
| 446 |
+
if self.built:
|
| 447 |
+
return
|
| 448 |
+
self.built = True
|
| 449 |
+
if getattr(self, "dense", None) is not None:
|
| 450 |
+
with tf.name_scope(self.dense.name):
|
| 451 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
class TFConvBertOutput(keras.layers.Layer):
|
| 455 |
+
def __init__(self, config, **kwargs):
|
| 456 |
+
super().__init__(**kwargs)
|
| 457 |
+
|
| 458 |
+
if config.num_groups == 1:
|
| 459 |
+
self.dense = keras.layers.Dense(
|
| 460 |
+
config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 461 |
+
)
|
| 462 |
+
else:
|
| 463 |
+
self.dense = GroupedLinearLayer(
|
| 464 |
+
config.intermediate_size,
|
| 465 |
+
config.hidden_size,
|
| 466 |
+
num_groups=config.num_groups,
|
| 467 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 468 |
+
name="dense",
|
| 469 |
+
)
|
| 470 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 471 |
+
self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
|
| 472 |
+
self.config = config
|
| 473 |
+
|
| 474 |
+
def call(self, hidden_states, input_tensor, training=False):
|
| 475 |
+
hidden_states = self.dense(hidden_states)
|
| 476 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 477 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 478 |
+
|
| 479 |
+
return hidden_states
|
| 480 |
+
|
| 481 |
+
def build(self, input_shape=None):
|
| 482 |
+
if self.built:
|
| 483 |
+
return
|
| 484 |
+
self.built = True
|
| 485 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 486 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 487 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 488 |
+
if getattr(self, "dense", None) is not None:
|
| 489 |
+
with tf.name_scope(self.dense.name):
|
| 490 |
+
self.dense.build([None, None, self.config.intermediate_size])
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
class TFConvBertLayer(keras.layers.Layer):
|
| 494 |
+
def __init__(self, config, **kwargs):
|
| 495 |
+
super().__init__(**kwargs)
|
| 496 |
+
|
| 497 |
+
self.attention = TFConvBertAttention(config, name="attention")
|
| 498 |
+
self.intermediate = TFConvBertIntermediate(config, name="intermediate")
|
| 499 |
+
self.bert_output = TFConvBertOutput(config, name="output")
|
| 500 |
+
|
| 501 |
+
def call(self, hidden_states, attention_mask, head_mask, output_attentions, training=False):
|
| 502 |
+
attention_outputs = self.attention(
|
| 503 |
+
hidden_states, attention_mask, head_mask, output_attentions, training=training
|
| 504 |
+
)
|
| 505 |
+
attention_output = attention_outputs[0]
|
| 506 |
+
intermediate_output = self.intermediate(attention_output)
|
| 507 |
+
layer_output = self.bert_output(intermediate_output, attention_output, training=training)
|
| 508 |
+
outputs = (layer_output,) + attention_outputs[1:] # add attentions if we output them
|
| 509 |
+
|
| 510 |
+
return outputs
|
| 511 |
+
|
| 512 |
+
def build(self, input_shape=None):
|
| 513 |
+
if self.built:
|
| 514 |
+
return
|
| 515 |
+
self.built = True
|
| 516 |
+
if getattr(self, "attention", None) is not None:
|
| 517 |
+
with tf.name_scope(self.attention.name):
|
| 518 |
+
self.attention.build(None)
|
| 519 |
+
if getattr(self, "intermediate", None) is not None:
|
| 520 |
+
with tf.name_scope(self.intermediate.name):
|
| 521 |
+
self.intermediate.build(None)
|
| 522 |
+
if getattr(self, "bert_output", None) is not None:
|
| 523 |
+
with tf.name_scope(self.bert_output.name):
|
| 524 |
+
self.bert_output.build(None)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
class TFConvBertEncoder(keras.layers.Layer):
|
| 528 |
+
def __init__(self, config, **kwargs):
|
| 529 |
+
super().__init__(**kwargs)
|
| 530 |
+
|
| 531 |
+
self.layer = [TFConvBertLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
|
| 532 |
+
|
| 533 |
+
def call(
|
| 534 |
+
self,
|
| 535 |
+
hidden_states,
|
| 536 |
+
attention_mask,
|
| 537 |
+
head_mask,
|
| 538 |
+
output_attentions,
|
| 539 |
+
output_hidden_states,
|
| 540 |
+
return_dict,
|
| 541 |
+
training=False,
|
| 542 |
+
):
|
| 543 |
+
all_hidden_states = () if output_hidden_states else None
|
| 544 |
+
all_attentions = () if output_attentions else None
|
| 545 |
+
|
| 546 |
+
for i, layer_module in enumerate(self.layer):
|
| 547 |
+
if output_hidden_states:
|
| 548 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 549 |
+
|
| 550 |
+
layer_outputs = layer_module(
|
| 551 |
+
hidden_states, attention_mask, head_mask[i], output_attentions, training=training
|
| 552 |
+
)
|
| 553 |
+
hidden_states = layer_outputs[0]
|
| 554 |
+
|
| 555 |
+
if output_attentions:
|
| 556 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 557 |
+
|
| 558 |
+
# Add last layer
|
| 559 |
+
if output_hidden_states:
|
| 560 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 561 |
+
|
| 562 |
+
if not return_dict:
|
| 563 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
|
| 564 |
+
|
| 565 |
+
return TFBaseModelOutput(
|
| 566 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
def build(self, input_shape=None):
|
| 570 |
+
if self.built:
|
| 571 |
+
return
|
| 572 |
+
self.built = True
|
| 573 |
+
if getattr(self, "layer", None) is not None:
|
| 574 |
+
for layer in self.layer:
|
| 575 |
+
with tf.name_scope(layer.name):
|
| 576 |
+
layer.build(None)
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
class TFConvBertPredictionHeadTransform(keras.layers.Layer):
|
| 580 |
+
def __init__(self, config, **kwargs):
|
| 581 |
+
super().__init__(**kwargs)
|
| 582 |
+
|
| 583 |
+
self.dense = keras.layers.Dense(
|
| 584 |
+
config.embedding_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
if isinstance(config.hidden_act, str):
|
| 588 |
+
self.transform_act_fn = get_tf_activation(config.hidden_act)
|
| 589 |
+
else:
|
| 590 |
+
self.transform_act_fn = config.hidden_act
|
| 591 |
+
|
| 592 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 593 |
+
self.config = config
|
| 594 |
+
|
| 595 |
+
def call(self, hidden_states):
|
| 596 |
+
hidden_states = self.dense(hidden_states)
|
| 597 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 598 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 599 |
+
|
| 600 |
+
return hidden_states
|
| 601 |
+
|
| 602 |
+
def build(self, input_shape=None):
|
| 603 |
+
if self.built:
|
| 604 |
+
return
|
| 605 |
+
self.built = True
|
| 606 |
+
if getattr(self, "dense", None) is not None:
|
| 607 |
+
with tf.name_scope(self.dense.name):
|
| 608 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 609 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 610 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 611 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
@keras_serializable
|
| 615 |
+
class TFConvBertMainLayer(keras.layers.Layer):
|
| 616 |
+
config_class = ConvBertConfig
|
| 617 |
+
|
| 618 |
+
def __init__(self, config, **kwargs):
|
| 619 |
+
super().__init__(**kwargs)
|
| 620 |
+
|
| 621 |
+
self.embeddings = TFConvBertEmbeddings(config, name="embeddings")
|
| 622 |
+
|
| 623 |
+
if config.embedding_size != config.hidden_size:
|
| 624 |
+
self.embeddings_project = keras.layers.Dense(config.hidden_size, name="embeddings_project")
|
| 625 |
+
|
| 626 |
+
self.encoder = TFConvBertEncoder(config, name="encoder")
|
| 627 |
+
self.config = config
|
| 628 |
+
|
| 629 |
+
def get_input_embeddings(self):
|
| 630 |
+
return self.embeddings
|
| 631 |
+
|
| 632 |
+
def set_input_embeddings(self, value):
|
| 633 |
+
self.embeddings.weight = value
|
| 634 |
+
self.embeddings.vocab_size = value.shape[0]
|
| 635 |
+
|
| 636 |
+
def _prune_heads(self, heads_to_prune):
|
| 637 |
+
"""
|
| 638 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 639 |
+
class PreTrainedModel
|
| 640 |
+
"""
|
| 641 |
+
raise NotImplementedError
|
| 642 |
+
|
| 643 |
+
def get_extended_attention_mask(self, attention_mask, input_shape, dtype):
|
| 644 |
+
if attention_mask is None:
|
| 645 |
+
attention_mask = tf.fill(input_shape, 1)
|
| 646 |
+
|
| 647 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
| 648 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
| 649 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
| 650 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
| 651 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
| 652 |
+
extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))
|
| 653 |
+
|
| 654 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 655 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 656 |
+
# positions we want to attend and -10000.0 for masked positions.
|
| 657 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 658 |
+
# effectively the same as removing these entirely.
|
| 659 |
+
extended_attention_mask = tf.cast(extended_attention_mask, dtype)
|
| 660 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
|
| 661 |
+
|
| 662 |
+
return extended_attention_mask
|
| 663 |
+
|
| 664 |
+
def get_head_mask(self, head_mask):
|
| 665 |
+
if head_mask is not None:
|
| 666 |
+
raise NotImplementedError
|
| 667 |
+
else:
|
| 668 |
+
head_mask = [None] * self.config.num_hidden_layers
|
| 669 |
+
|
| 670 |
+
return head_mask
|
| 671 |
+
|
| 672 |
+
@unpack_inputs
|
| 673 |
+
def call(
|
| 674 |
+
self,
|
| 675 |
+
input_ids=None,
|
| 676 |
+
attention_mask=None,
|
| 677 |
+
token_type_ids=None,
|
| 678 |
+
position_ids=None,
|
| 679 |
+
head_mask=None,
|
| 680 |
+
inputs_embeds=None,
|
| 681 |
+
output_attentions=None,
|
| 682 |
+
output_hidden_states=None,
|
| 683 |
+
return_dict=None,
|
| 684 |
+
training=False,
|
| 685 |
+
):
|
| 686 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 687 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 688 |
+
elif input_ids is not None:
|
| 689 |
+
input_shape = shape_list(input_ids)
|
| 690 |
+
elif inputs_embeds is not None:
|
| 691 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 692 |
+
else:
|
| 693 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 694 |
+
|
| 695 |
+
if attention_mask is None:
|
| 696 |
+
attention_mask = tf.fill(input_shape, 1)
|
| 697 |
+
|
| 698 |
+
if token_type_ids is None:
|
| 699 |
+
token_type_ids = tf.fill(input_shape, 0)
|
| 700 |
+
|
| 701 |
+
hidden_states = self.embeddings(input_ids, position_ids, token_type_ids, inputs_embeds, training=training)
|
| 702 |
+
extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, hidden_states.dtype)
|
| 703 |
+
head_mask = self.get_head_mask(head_mask)
|
| 704 |
+
|
| 705 |
+
if hasattr(self, "embeddings_project"):
|
| 706 |
+
hidden_states = self.embeddings_project(hidden_states, training=training)
|
| 707 |
+
|
| 708 |
+
hidden_states = self.encoder(
|
| 709 |
+
hidden_states,
|
| 710 |
+
extended_attention_mask,
|
| 711 |
+
head_mask,
|
| 712 |
+
output_attentions,
|
| 713 |
+
output_hidden_states,
|
| 714 |
+
return_dict,
|
| 715 |
+
training=training,
|
| 716 |
+
)
|
| 717 |
+
|
| 718 |
+
return hidden_states
|
| 719 |
+
|
| 720 |
+
def build(self, input_shape=None):
|
| 721 |
+
if self.built:
|
| 722 |
+
return
|
| 723 |
+
self.built = True
|
| 724 |
+
if getattr(self, "embeddings", None) is not None:
|
| 725 |
+
with tf.name_scope(self.embeddings.name):
|
| 726 |
+
self.embeddings.build(None)
|
| 727 |
+
if getattr(self, "encoder", None) is not None:
|
| 728 |
+
with tf.name_scope(self.encoder.name):
|
| 729 |
+
self.encoder.build(None)
|
| 730 |
+
if getattr(self, "embeddings_project", None) is not None:
|
| 731 |
+
with tf.name_scope(self.embeddings_project.name):
|
| 732 |
+
self.embeddings_project.build([None, None, self.config.embedding_size])
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
class TFConvBertPreTrainedModel(TFPreTrainedModel):
|
| 736 |
+
"""
|
| 737 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 738 |
+
models.
|
| 739 |
+
"""
|
| 740 |
+
|
| 741 |
+
config_class = ConvBertConfig
|
| 742 |
+
base_model_prefix = "convbert"
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
CONVBERT_START_DOCSTRING = r"""
|
| 746 |
+
|
| 747 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 748 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 749 |
+
etc.)
|
| 750 |
+
|
| 751 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 752 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 753 |
+
behavior.
|
| 754 |
+
|
| 755 |
+
<Tip>
|
| 756 |
+
|
| 757 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 758 |
+
|
| 759 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 760 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 761 |
+
|
| 762 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 763 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 764 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 765 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 766 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 767 |
+
positional argument:
|
| 768 |
+
|
| 769 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 770 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 771 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 772 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 773 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 774 |
+
|
| 775 |
+
Note that when creating models and layers with
|
| 776 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 777 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 778 |
+
|
| 779 |
+
</Tip>
|
| 780 |
+
|
| 781 |
+
Args:
|
| 782 |
+
config ([`ConvBertConfig`]): Model configuration class with all the parameters of the model.
|
| 783 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 784 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 785 |
+
"""
|
| 786 |
+
|
| 787 |
+
CONVBERT_INPUTS_DOCSTRING = r"""
|
| 788 |
+
Args:
|
| 789 |
+
input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
|
| 790 |
+
Indices of input sequence tokens in the vocabulary.
|
| 791 |
+
|
| 792 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 793 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 794 |
+
|
| 795 |
+
[What are input IDs?](../glossary#input-ids)
|
| 796 |
+
attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 797 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 798 |
+
|
| 799 |
+
- 1 for tokens that are **not masked**,
|
| 800 |
+
- 0 for tokens that are **masked**.
|
| 801 |
+
|
| 802 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 803 |
+
token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 804 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 805 |
+
1]`:
|
| 806 |
+
|
| 807 |
+
- 0 corresponds to a *sentence A* token,
|
| 808 |
+
- 1 corresponds to a *sentence B* token.
|
| 809 |
+
|
| 810 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 811 |
+
position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 812 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 813 |
+
config.max_position_embeddings - 1]`.
|
| 814 |
+
|
| 815 |
+
[What are position IDs?](../glossary#position-ids)
|
| 816 |
+
head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 817 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 818 |
+
|
| 819 |
+
- 1 indicates the head is **not masked**,
|
| 820 |
+
- 0 indicates the head is **masked**.
|
| 821 |
+
|
| 822 |
+
inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
|
| 823 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 824 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 825 |
+
model's internal embedding lookup matrix.
|
| 826 |
+
output_attentions (`bool`, *optional*):
|
| 827 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 828 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 829 |
+
config will be used instead.
|
| 830 |
+
output_hidden_states (`bool`, *optional*):
|
| 831 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 832 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 833 |
+
used instead.
|
| 834 |
+
return_dict (`bool`, *optional*):
|
| 835 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 836 |
+
eager mode, in graph mode the value will always be set to True.
|
| 837 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 838 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 839 |
+
behaviors between training and evaluation).
|
| 840 |
+
"""
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
@add_start_docstrings(
|
| 844 |
+
"The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.",
|
| 845 |
+
CONVBERT_START_DOCSTRING,
|
| 846 |
+
)
|
| 847 |
+
class TFConvBertModel(TFConvBertPreTrainedModel):
|
| 848 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 849 |
+
super().__init__(config, *inputs, **kwargs)
|
| 850 |
+
|
| 851 |
+
self.convbert = TFConvBertMainLayer(config, name="convbert")
|
| 852 |
+
|
| 853 |
+
@unpack_inputs
|
| 854 |
+
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 855 |
+
@add_code_sample_docstrings(
|
| 856 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 857 |
+
output_type=TFBaseModelOutput,
|
| 858 |
+
config_class=_CONFIG_FOR_DOC,
|
| 859 |
+
)
|
| 860 |
+
def call(
|
| 861 |
+
self,
|
| 862 |
+
input_ids: TFModelInputType | None = None,
|
| 863 |
+
attention_mask: Optional[Union[np.array, tf.Tensor]] = None,
|
| 864 |
+
token_type_ids: Optional[Union[np.array, tf.Tensor]] = None,
|
| 865 |
+
position_ids: Optional[Union[np.array, tf.Tensor]] = None,
|
| 866 |
+
head_mask: Optional[Union[np.array, tf.Tensor]] = None,
|
| 867 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 868 |
+
output_attentions: Optional[bool] = None,
|
| 869 |
+
output_hidden_states: Optional[bool] = None,
|
| 870 |
+
return_dict: Optional[bool] = None,
|
| 871 |
+
training: bool = False,
|
| 872 |
+
) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
|
| 873 |
+
outputs = self.convbert(
|
| 874 |
+
input_ids=input_ids,
|
| 875 |
+
attention_mask=attention_mask,
|
| 876 |
+
token_type_ids=token_type_ids,
|
| 877 |
+
position_ids=position_ids,
|
| 878 |
+
head_mask=head_mask,
|
| 879 |
+
inputs_embeds=inputs_embeds,
|
| 880 |
+
output_attentions=output_attentions,
|
| 881 |
+
output_hidden_states=output_hidden_states,
|
| 882 |
+
return_dict=return_dict,
|
| 883 |
+
training=training,
|
| 884 |
+
)
|
| 885 |
+
|
| 886 |
+
return outputs
|
| 887 |
+
|
| 888 |
+
def build(self, input_shape=None):
|
| 889 |
+
if self.built:
|
| 890 |
+
return
|
| 891 |
+
self.built = True
|
| 892 |
+
if getattr(self, "convbert", None) is not None:
|
| 893 |
+
with tf.name_scope(self.convbert.name):
|
| 894 |
+
self.convbert.build(None)
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
class TFConvBertMaskedLMHead(keras.layers.Layer):
|
| 898 |
+
def __init__(self, config, input_embeddings, **kwargs):
|
| 899 |
+
super().__init__(**kwargs)
|
| 900 |
+
|
| 901 |
+
self.config = config
|
| 902 |
+
self.embedding_size = config.embedding_size
|
| 903 |
+
self.input_embeddings = input_embeddings
|
| 904 |
+
|
| 905 |
+
def build(self, input_shape):
|
| 906 |
+
self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
|
| 907 |
+
|
| 908 |
+
super().build(input_shape)
|
| 909 |
+
|
| 910 |
+
def get_output_embeddings(self):
|
| 911 |
+
return self.input_embeddings
|
| 912 |
+
|
| 913 |
+
def set_output_embeddings(self, value):
|
| 914 |
+
self.input_embeddings.weight = value
|
| 915 |
+
self.input_embeddings.vocab_size = shape_list(value)[0]
|
| 916 |
+
|
| 917 |
+
def get_bias(self):
|
| 918 |
+
return {"bias": self.bias}
|
| 919 |
+
|
| 920 |
+
def set_bias(self, value):
|
| 921 |
+
self.bias = value["bias"]
|
| 922 |
+
self.config.vocab_size = shape_list(value["bias"])[0]
|
| 923 |
+
|
| 924 |
+
def call(self, hidden_states):
|
| 925 |
+
seq_length = shape_list(tensor=hidden_states)[1]
|
| 926 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.embedding_size])
|
| 927 |
+
hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
|
| 928 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
|
| 929 |
+
hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
|
| 930 |
+
|
| 931 |
+
return hidden_states
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
class TFConvBertGeneratorPredictions(keras.layers.Layer):
|
| 935 |
+
def __init__(self, config, **kwargs):
|
| 936 |
+
super().__init__(**kwargs)
|
| 937 |
+
|
| 938 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 939 |
+
self.dense = keras.layers.Dense(config.embedding_size, name="dense")
|
| 940 |
+
self.config = config
|
| 941 |
+
|
| 942 |
+
def call(self, generator_hidden_states, training=False):
|
| 943 |
+
hidden_states = self.dense(generator_hidden_states)
|
| 944 |
+
hidden_states = get_tf_activation("gelu")(hidden_states)
|
| 945 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 946 |
+
|
| 947 |
+
return hidden_states
|
| 948 |
+
|
| 949 |
+
def build(self, input_shape=None):
|
| 950 |
+
if self.built:
|
| 951 |
+
return
|
| 952 |
+
self.built = True
|
| 953 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 954 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 955 |
+
self.LayerNorm.build([None, None, self.config.embedding_size])
|
| 956 |
+
if getattr(self, "dense", None) is not None:
|
| 957 |
+
with tf.name_scope(self.dense.name):
|
| 958 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
@add_start_docstrings("""ConvBERT Model with a `language modeling` head on top.""", CONVBERT_START_DOCSTRING)
|
| 962 |
+
class TFConvBertForMaskedLM(TFConvBertPreTrainedModel, TFMaskedLanguageModelingLoss):
|
| 963 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 964 |
+
super().__init__(config, **kwargs)
|
| 965 |
+
|
| 966 |
+
self.config = config
|
| 967 |
+
self.convbert = TFConvBertMainLayer(config, name="convbert")
|
| 968 |
+
self.generator_predictions = TFConvBertGeneratorPredictions(config, name="generator_predictions")
|
| 969 |
+
|
| 970 |
+
if isinstance(config.hidden_act, str):
|
| 971 |
+
self.activation = get_tf_activation(config.hidden_act)
|
| 972 |
+
else:
|
| 973 |
+
self.activation = config.hidden_act
|
| 974 |
+
|
| 975 |
+
self.generator_lm_head = TFConvBertMaskedLMHead(config, self.convbert.embeddings, name="generator_lm_head")
|
| 976 |
+
|
| 977 |
+
def get_lm_head(self):
|
| 978 |
+
return self.generator_lm_head
|
| 979 |
+
|
| 980 |
+
def get_prefix_bias_name(self):
|
| 981 |
+
return self.name + "/" + self.generator_lm_head.name
|
| 982 |
+
|
| 983 |
+
@unpack_inputs
|
| 984 |
+
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 985 |
+
@add_code_sample_docstrings(
|
| 986 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 987 |
+
output_type=TFMaskedLMOutput,
|
| 988 |
+
config_class=_CONFIG_FOR_DOC,
|
| 989 |
+
)
|
| 990 |
+
def call(
|
| 991 |
+
self,
|
| 992 |
+
input_ids: TFModelInputType | None = None,
|
| 993 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 994 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 995 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 996 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 997 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 998 |
+
output_attentions: Optional[bool] = None,
|
| 999 |
+
output_hidden_states: Optional[bool] = None,
|
| 1000 |
+
return_dict: Optional[bool] = None,
|
| 1001 |
+
labels: tf.Tensor | None = None,
|
| 1002 |
+
training: Optional[bool] = False,
|
| 1003 |
+
) -> Union[Tuple, TFMaskedLMOutput]:
|
| 1004 |
+
r"""
|
| 1005 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1006 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 1007 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 1008 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1009 |
+
"""
|
| 1010 |
+
generator_hidden_states = self.convbert(
|
| 1011 |
+
input_ids=input_ids,
|
| 1012 |
+
attention_mask=attention_mask,
|
| 1013 |
+
token_type_ids=token_type_ids,
|
| 1014 |
+
position_ids=position_ids,
|
| 1015 |
+
head_mask=head_mask,
|
| 1016 |
+
inputs_embeds=inputs_embeds,
|
| 1017 |
+
output_attentions=output_attentions,
|
| 1018 |
+
output_hidden_states=output_hidden_states,
|
| 1019 |
+
return_dict=return_dict,
|
| 1020 |
+
training=training,
|
| 1021 |
+
)
|
| 1022 |
+
generator_sequence_output = generator_hidden_states[0]
|
| 1023 |
+
prediction_scores = self.generator_predictions(generator_sequence_output, training=training)
|
| 1024 |
+
prediction_scores = self.generator_lm_head(prediction_scores, training=training)
|
| 1025 |
+
loss = None if labels is None else self.hf_compute_loss(labels, prediction_scores)
|
| 1026 |
+
|
| 1027 |
+
if not return_dict:
|
| 1028 |
+
output = (prediction_scores,) + generator_hidden_states[1:]
|
| 1029 |
+
|
| 1030 |
+
return ((loss,) + output) if loss is not None else output
|
| 1031 |
+
|
| 1032 |
+
return TFMaskedLMOutput(
|
| 1033 |
+
loss=loss,
|
| 1034 |
+
logits=prediction_scores,
|
| 1035 |
+
hidden_states=generator_hidden_states.hidden_states,
|
| 1036 |
+
attentions=generator_hidden_states.attentions,
|
| 1037 |
+
)
|
| 1038 |
+
|
| 1039 |
+
def build(self, input_shape=None):
|
| 1040 |
+
if self.built:
|
| 1041 |
+
return
|
| 1042 |
+
self.built = True
|
| 1043 |
+
if getattr(self, "convbert", None) is not None:
|
| 1044 |
+
with tf.name_scope(self.convbert.name):
|
| 1045 |
+
self.convbert.build(None)
|
| 1046 |
+
if getattr(self, "generator_predictions", None) is not None:
|
| 1047 |
+
with tf.name_scope(self.generator_predictions.name):
|
| 1048 |
+
self.generator_predictions.build(None)
|
| 1049 |
+
if getattr(self, "generator_lm_head", None) is not None:
|
| 1050 |
+
with tf.name_scope(self.generator_lm_head.name):
|
| 1051 |
+
self.generator_lm_head.build(None)
|
| 1052 |
+
|
| 1053 |
+
|
| 1054 |
+
class TFConvBertClassificationHead(keras.layers.Layer):
|
| 1055 |
+
"""Head for sentence-level classification tasks."""
|
| 1056 |
+
|
| 1057 |
+
def __init__(self, config, **kwargs):
|
| 1058 |
+
super().__init__(**kwargs)
|
| 1059 |
+
|
| 1060 |
+
self.dense = keras.layers.Dense(
|
| 1061 |
+
config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 1062 |
+
)
|
| 1063 |
+
classifier_dropout = (
|
| 1064 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1065 |
+
)
|
| 1066 |
+
self.dropout = keras.layers.Dropout(classifier_dropout)
|
| 1067 |
+
self.out_proj = keras.layers.Dense(
|
| 1068 |
+
config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="out_proj"
|
| 1069 |
+
)
|
| 1070 |
+
|
| 1071 |
+
self.config = config
|
| 1072 |
+
|
| 1073 |
+
def call(self, hidden_states, **kwargs):
|
| 1074 |
+
x = hidden_states[:, 0, :] # take <s> token (equiv. to [CLS])
|
| 1075 |
+
x = self.dropout(x)
|
| 1076 |
+
x = self.dense(x)
|
| 1077 |
+
x = get_tf_activation(self.config.hidden_act)(x)
|
| 1078 |
+
x = self.dropout(x)
|
| 1079 |
+
x = self.out_proj(x)
|
| 1080 |
+
|
| 1081 |
+
return x
|
| 1082 |
+
|
| 1083 |
+
def build(self, input_shape=None):
|
| 1084 |
+
if self.built:
|
| 1085 |
+
return
|
| 1086 |
+
self.built = True
|
| 1087 |
+
if getattr(self, "dense", None) is not None:
|
| 1088 |
+
with tf.name_scope(self.dense.name):
|
| 1089 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 1090 |
+
if getattr(self, "out_proj", None) is not None:
|
| 1091 |
+
with tf.name_scope(self.out_proj.name):
|
| 1092 |
+
self.out_proj.build([None, None, self.config.hidden_size])
|
| 1093 |
+
|
| 1094 |
+
|
| 1095 |
+
@add_start_docstrings(
|
| 1096 |
+
"""
|
| 1097 |
+
ConvBERT Model transformer with a sequence classification/regression head on top e.g., for GLUE tasks.
|
| 1098 |
+
""",
|
| 1099 |
+
CONVBERT_START_DOCSTRING,
|
| 1100 |
+
)
|
| 1101 |
+
class TFConvBertForSequenceClassification(TFConvBertPreTrainedModel, TFSequenceClassificationLoss):
|
| 1102 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1103 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1104 |
+
self.num_labels = config.num_labels
|
| 1105 |
+
self.convbert = TFConvBertMainLayer(config, name="convbert")
|
| 1106 |
+
self.classifier = TFConvBertClassificationHead(config, name="classifier")
|
| 1107 |
+
|
| 1108 |
+
@unpack_inputs
|
| 1109 |
+
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1110 |
+
@add_code_sample_docstrings(
|
| 1111 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1112 |
+
output_type=TFSequenceClassifierOutput,
|
| 1113 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1114 |
+
)
|
| 1115 |
+
def call(
|
| 1116 |
+
self,
|
| 1117 |
+
input_ids: TFModelInputType | None = None,
|
| 1118 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1119 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1120 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1121 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1122 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 1123 |
+
output_attentions: Optional[bool] = None,
|
| 1124 |
+
output_hidden_states: Optional[bool] = None,
|
| 1125 |
+
return_dict: Optional[bool] = None,
|
| 1126 |
+
labels: tf.Tensor | None = None,
|
| 1127 |
+
training: Optional[bool] = False,
|
| 1128 |
+
) -> Union[Tuple, TFSequenceClassifierOutput]:
|
| 1129 |
+
r"""
|
| 1130 |
+
labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1131 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1132 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1133 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1134 |
+
"""
|
| 1135 |
+
outputs = self.convbert(
|
| 1136 |
+
input_ids,
|
| 1137 |
+
attention_mask=attention_mask,
|
| 1138 |
+
token_type_ids=token_type_ids,
|
| 1139 |
+
position_ids=position_ids,
|
| 1140 |
+
head_mask=head_mask,
|
| 1141 |
+
inputs_embeds=inputs_embeds,
|
| 1142 |
+
output_attentions=output_attentions,
|
| 1143 |
+
output_hidden_states=output_hidden_states,
|
| 1144 |
+
return_dict=return_dict,
|
| 1145 |
+
training=training,
|
| 1146 |
+
)
|
| 1147 |
+
logits = self.classifier(outputs[0], training=training)
|
| 1148 |
+
loss = None if labels is None else self.hf_compute_loss(labels, logits)
|
| 1149 |
+
|
| 1150 |
+
if not return_dict:
|
| 1151 |
+
output = (logits,) + outputs[1:]
|
| 1152 |
+
|
| 1153 |
+
return ((loss,) + output) if loss is not None else output
|
| 1154 |
+
|
| 1155 |
+
return TFSequenceClassifierOutput(
|
| 1156 |
+
loss=loss,
|
| 1157 |
+
logits=logits,
|
| 1158 |
+
hidden_states=outputs.hidden_states,
|
| 1159 |
+
attentions=outputs.attentions,
|
| 1160 |
+
)
|
| 1161 |
+
|
| 1162 |
+
def build(self, input_shape=None):
|
| 1163 |
+
if self.built:
|
| 1164 |
+
return
|
| 1165 |
+
self.built = True
|
| 1166 |
+
if getattr(self, "convbert", None) is not None:
|
| 1167 |
+
with tf.name_scope(self.convbert.name):
|
| 1168 |
+
self.convbert.build(None)
|
| 1169 |
+
if getattr(self, "classifier", None) is not None:
|
| 1170 |
+
with tf.name_scope(self.classifier.name):
|
| 1171 |
+
self.classifier.build(None)
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
@add_start_docstrings(
|
| 1175 |
+
"""
|
| 1176 |
+
ConvBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 1177 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 1178 |
+
""",
|
| 1179 |
+
CONVBERT_START_DOCSTRING,
|
| 1180 |
+
)
|
| 1181 |
+
class TFConvBertForMultipleChoice(TFConvBertPreTrainedModel, TFMultipleChoiceLoss):
|
| 1182 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1183 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1184 |
+
|
| 1185 |
+
self.convbert = TFConvBertMainLayer(config, name="convbert")
|
| 1186 |
+
self.sequence_summary = TFSequenceSummary(
|
| 1187 |
+
config, initializer_range=config.initializer_range, name="sequence_summary"
|
| 1188 |
+
)
|
| 1189 |
+
self.classifier = keras.layers.Dense(
|
| 1190 |
+
1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 1191 |
+
)
|
| 1192 |
+
self.config = config
|
| 1193 |
+
|
| 1194 |
+
@unpack_inputs
|
| 1195 |
+
@add_start_docstrings_to_model_forward(
|
| 1196 |
+
CONVBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
|
| 1197 |
+
)
|
| 1198 |
+
@add_code_sample_docstrings(
|
| 1199 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1200 |
+
output_type=TFMultipleChoiceModelOutput,
|
| 1201 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1202 |
+
)
|
| 1203 |
+
def call(
|
| 1204 |
+
self,
|
| 1205 |
+
input_ids: TFModelInputType | None = None,
|
| 1206 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1207 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1208 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1209 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1210 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 1211 |
+
output_attentions: Optional[bool] = None,
|
| 1212 |
+
output_hidden_states: Optional[bool] = None,
|
| 1213 |
+
return_dict: Optional[bool] = None,
|
| 1214 |
+
labels: tf.Tensor | None = None,
|
| 1215 |
+
training: Optional[bool] = False,
|
| 1216 |
+
) -> Union[Tuple, TFMultipleChoiceModelOutput]:
|
| 1217 |
+
r"""
|
| 1218 |
+
labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1219 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
|
| 1220 |
+
where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
|
| 1221 |
+
"""
|
| 1222 |
+
if input_ids is not None:
|
| 1223 |
+
num_choices = shape_list(input_ids)[1]
|
| 1224 |
+
seq_length = shape_list(input_ids)[2]
|
| 1225 |
+
else:
|
| 1226 |
+
num_choices = shape_list(inputs_embeds)[1]
|
| 1227 |
+
seq_length = shape_list(inputs_embeds)[2]
|
| 1228 |
+
|
| 1229 |
+
flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
|
| 1230 |
+
flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
|
| 1231 |
+
flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None
|
| 1232 |
+
flat_position_ids = tf.reshape(position_ids, (-1, seq_length)) if position_ids is not None else None
|
| 1233 |
+
flat_inputs_embeds = (
|
| 1234 |
+
tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
|
| 1235 |
+
if inputs_embeds is not None
|
| 1236 |
+
else None
|
| 1237 |
+
)
|
| 1238 |
+
outputs = self.convbert(
|
| 1239 |
+
flat_input_ids,
|
| 1240 |
+
flat_attention_mask,
|
| 1241 |
+
flat_token_type_ids,
|
| 1242 |
+
flat_position_ids,
|
| 1243 |
+
head_mask,
|
| 1244 |
+
flat_inputs_embeds,
|
| 1245 |
+
output_attentions,
|
| 1246 |
+
output_hidden_states,
|
| 1247 |
+
return_dict=return_dict,
|
| 1248 |
+
training=training,
|
| 1249 |
+
)
|
| 1250 |
+
logits = self.sequence_summary(outputs[0], training=training)
|
| 1251 |
+
logits = self.classifier(logits)
|
| 1252 |
+
reshaped_logits = tf.reshape(logits, (-1, num_choices))
|
| 1253 |
+
loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
|
| 1254 |
+
|
| 1255 |
+
if not return_dict:
|
| 1256 |
+
output = (reshaped_logits,) + outputs[1:]
|
| 1257 |
+
|
| 1258 |
+
return ((loss,) + output) if loss is not None else output
|
| 1259 |
+
|
| 1260 |
+
return TFMultipleChoiceModelOutput(
|
| 1261 |
+
loss=loss,
|
| 1262 |
+
logits=reshaped_logits,
|
| 1263 |
+
hidden_states=outputs.hidden_states,
|
| 1264 |
+
attentions=outputs.attentions,
|
| 1265 |
+
)
|
| 1266 |
+
|
| 1267 |
+
def build(self, input_shape=None):
|
| 1268 |
+
if self.built:
|
| 1269 |
+
return
|
| 1270 |
+
self.built = True
|
| 1271 |
+
if getattr(self, "convbert", None) is not None:
|
| 1272 |
+
with tf.name_scope(self.convbert.name):
|
| 1273 |
+
self.convbert.build(None)
|
| 1274 |
+
if getattr(self, "sequence_summary", None) is not None:
|
| 1275 |
+
with tf.name_scope(self.sequence_summary.name):
|
| 1276 |
+
self.sequence_summary.build(None)
|
| 1277 |
+
if getattr(self, "classifier", None) is not None:
|
| 1278 |
+
with tf.name_scope(self.classifier.name):
|
| 1279 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
| 1280 |
+
|
| 1281 |
+
|
| 1282 |
+
@add_start_docstrings(
|
| 1283 |
+
"""
|
| 1284 |
+
ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1285 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1286 |
+
""",
|
| 1287 |
+
CONVBERT_START_DOCSTRING,
|
| 1288 |
+
)
|
| 1289 |
+
class TFConvBertForTokenClassification(TFConvBertPreTrainedModel, TFTokenClassificationLoss):
|
| 1290 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1291 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1292 |
+
|
| 1293 |
+
self.num_labels = config.num_labels
|
| 1294 |
+
self.convbert = TFConvBertMainLayer(config, name="convbert")
|
| 1295 |
+
classifier_dropout = (
|
| 1296 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1297 |
+
)
|
| 1298 |
+
self.dropout = keras.layers.Dropout(classifier_dropout)
|
| 1299 |
+
self.classifier = keras.layers.Dense(
|
| 1300 |
+
config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 1301 |
+
)
|
| 1302 |
+
self.config = config
|
| 1303 |
+
|
| 1304 |
+
@unpack_inputs
|
| 1305 |
+
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1306 |
+
@add_code_sample_docstrings(
|
| 1307 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1308 |
+
output_type=TFTokenClassifierOutput,
|
| 1309 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1310 |
+
)
|
| 1311 |
+
def call(
|
| 1312 |
+
self,
|
| 1313 |
+
input_ids: TFModelInputType | None = None,
|
| 1314 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1315 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1316 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1317 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1318 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 1319 |
+
output_attentions: Optional[bool] = None,
|
| 1320 |
+
output_hidden_states: Optional[bool] = None,
|
| 1321 |
+
return_dict: Optional[bool] = None,
|
| 1322 |
+
labels: tf.Tensor | None = None,
|
| 1323 |
+
training: Optional[bool] = False,
|
| 1324 |
+
) -> Union[Tuple, TFTokenClassifierOutput]:
|
| 1325 |
+
r"""
|
| 1326 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1327 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1328 |
+
"""
|
| 1329 |
+
outputs = self.convbert(
|
| 1330 |
+
input_ids,
|
| 1331 |
+
attention_mask=attention_mask,
|
| 1332 |
+
token_type_ids=token_type_ids,
|
| 1333 |
+
position_ids=position_ids,
|
| 1334 |
+
head_mask=head_mask,
|
| 1335 |
+
inputs_embeds=inputs_embeds,
|
| 1336 |
+
output_attentions=output_attentions,
|
| 1337 |
+
output_hidden_states=output_hidden_states,
|
| 1338 |
+
return_dict=return_dict,
|
| 1339 |
+
training=training,
|
| 1340 |
+
)
|
| 1341 |
+
sequence_output = outputs[0]
|
| 1342 |
+
sequence_output = self.dropout(sequence_output, training=training)
|
| 1343 |
+
logits = self.classifier(sequence_output)
|
| 1344 |
+
loss = None if labels is None else self.hf_compute_loss(labels, logits)
|
| 1345 |
+
|
| 1346 |
+
if not return_dict:
|
| 1347 |
+
output = (logits,) + outputs[1:]
|
| 1348 |
+
return ((loss,) + output) if loss is not None else output
|
| 1349 |
+
|
| 1350 |
+
return TFTokenClassifierOutput(
|
| 1351 |
+
loss=loss,
|
| 1352 |
+
logits=logits,
|
| 1353 |
+
hidden_states=outputs.hidden_states,
|
| 1354 |
+
attentions=outputs.attentions,
|
| 1355 |
+
)
|
| 1356 |
+
|
| 1357 |
+
def build(self, input_shape=None):
|
| 1358 |
+
if self.built:
|
| 1359 |
+
return
|
| 1360 |
+
self.built = True
|
| 1361 |
+
if getattr(self, "convbert", None) is not None:
|
| 1362 |
+
with tf.name_scope(self.convbert.name):
|
| 1363 |
+
self.convbert.build(None)
|
| 1364 |
+
if getattr(self, "classifier", None) is not None:
|
| 1365 |
+
with tf.name_scope(self.classifier.name):
|
| 1366 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
| 1367 |
+
|
| 1368 |
+
|
| 1369 |
+
@add_start_docstrings(
|
| 1370 |
+
"""
|
| 1371 |
+
ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1372 |
+
layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1373 |
+
""",
|
| 1374 |
+
CONVBERT_START_DOCSTRING,
|
| 1375 |
+
)
|
| 1376 |
+
class TFConvBertForQuestionAnswering(TFConvBertPreTrainedModel, TFQuestionAnsweringLoss):
|
| 1377 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1378 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1379 |
+
|
| 1380 |
+
self.num_labels = config.num_labels
|
| 1381 |
+
self.convbert = TFConvBertMainLayer(config, name="convbert")
|
| 1382 |
+
self.qa_outputs = keras.layers.Dense(
|
| 1383 |
+
config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
|
| 1384 |
+
)
|
| 1385 |
+
self.config = config
|
| 1386 |
+
|
| 1387 |
+
@unpack_inputs
|
| 1388 |
+
@add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1389 |
+
@add_code_sample_docstrings(
|
| 1390 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1391 |
+
output_type=TFQuestionAnsweringModelOutput,
|
| 1392 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1393 |
+
)
|
| 1394 |
+
def call(
|
| 1395 |
+
self,
|
| 1396 |
+
input_ids: TFModelInputType | None = None,
|
| 1397 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1398 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1399 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1400 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1401 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 1402 |
+
output_attentions: Optional[bool] = None,
|
| 1403 |
+
output_hidden_states: Optional[bool] = None,
|
| 1404 |
+
return_dict: Optional[bool] = None,
|
| 1405 |
+
start_positions: tf.Tensor | None = None,
|
| 1406 |
+
end_positions: tf.Tensor | None = None,
|
| 1407 |
+
training: Optional[bool] = False,
|
| 1408 |
+
) -> Union[Tuple, TFQuestionAnsweringModelOutput]:
|
| 1409 |
+
r"""
|
| 1410 |
+
start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1411 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1412 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1413 |
+
are not taken into account for computing the loss.
|
| 1414 |
+
end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1415 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1416 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1417 |
+
are not taken into account for computing the loss.
|
| 1418 |
+
"""
|
| 1419 |
+
outputs = self.convbert(
|
| 1420 |
+
input_ids,
|
| 1421 |
+
attention_mask=attention_mask,
|
| 1422 |
+
token_type_ids=token_type_ids,
|
| 1423 |
+
position_ids=position_ids,
|
| 1424 |
+
head_mask=head_mask,
|
| 1425 |
+
inputs_embeds=inputs_embeds,
|
| 1426 |
+
output_attentions=output_attentions,
|
| 1427 |
+
output_hidden_states=output_hidden_states,
|
| 1428 |
+
return_dict=return_dict,
|
| 1429 |
+
training=training,
|
| 1430 |
+
)
|
| 1431 |
+
sequence_output = outputs[0]
|
| 1432 |
+
logits = self.qa_outputs(sequence_output)
|
| 1433 |
+
start_logits, end_logits = tf.split(logits, 2, axis=-1)
|
| 1434 |
+
start_logits = tf.squeeze(start_logits, axis=-1)
|
| 1435 |
+
end_logits = tf.squeeze(end_logits, axis=-1)
|
| 1436 |
+
loss = None
|
| 1437 |
+
|
| 1438 |
+
if start_positions is not None and end_positions is not None:
|
| 1439 |
+
labels = {"start_position": start_positions}
|
| 1440 |
+
labels["end_position"] = end_positions
|
| 1441 |
+
loss = self.hf_compute_loss(labels, (start_logits, end_logits))
|
| 1442 |
+
|
| 1443 |
+
if not return_dict:
|
| 1444 |
+
output = (start_logits, end_logits) + outputs[1:]
|
| 1445 |
+
return ((loss,) + output) if loss is not None else output
|
| 1446 |
+
|
| 1447 |
+
return TFQuestionAnsweringModelOutput(
|
| 1448 |
+
loss=loss,
|
| 1449 |
+
start_logits=start_logits,
|
| 1450 |
+
end_logits=end_logits,
|
| 1451 |
+
hidden_states=outputs.hidden_states,
|
| 1452 |
+
attentions=outputs.attentions,
|
| 1453 |
+
)
|
| 1454 |
+
|
| 1455 |
+
def build(self, input_shape=None):
|
| 1456 |
+
if self.built:
|
| 1457 |
+
return
|
| 1458 |
+
self.built = True
|
| 1459 |
+
if getattr(self, "convbert", None) is not None:
|
| 1460 |
+
with tf.name_scope(self.convbert.name):
|
| 1461 |
+
self.convbert.build(None)
|
| 1462 |
+
if getattr(self, "qa_outputs", None) is not None:
|
| 1463 |
+
with tf.name_scope(self.qa_outputs.name):
|
| 1464 |
+
self.qa_outputs.build([None, None, self.config.hidden_size])
|
| 1465 |
+
|
| 1466 |
+
|
| 1467 |
+
__all__ = [
|
| 1468 |
+
"TFConvBertForMaskedLM",
|
| 1469 |
+
"TFConvBertForMultipleChoice",
|
| 1470 |
+
"TFConvBertForQuestionAnswering",
|
| 1471 |
+
"TFConvBertForSequenceClassification",
|
| 1472 |
+
"TFConvBertForTokenClassification",
|
| 1473 |
+
"TFConvBertLayer",
|
| 1474 |
+
"TFConvBertModel",
|
| 1475 |
+
"TFConvBertPreTrainedModel",
|
| 1476 |
+
]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/tokenization_convbert.py
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 ConvBERT."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
import os
|
| 19 |
+
import unicodedata
|
| 20 |
+
from typing import List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Copied from transformers.models.bert.tokenization_bert.load_vocab
|
| 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 |
+
# Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
|
| 44 |
+
def whitespace_tokenize(text):
|
| 45 |
+
"""Runs basic whitespace cleaning and splitting on a piece of text."""
|
| 46 |
+
text = text.strip()
|
| 47 |
+
if not text:
|
| 48 |
+
return []
|
| 49 |
+
tokens = text.split()
|
| 50 |
+
return tokens
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# Copied from transformers.models.bert.tokenization_bert.BertTokenizer with bert-base-cased->YituTech/conv-bert-base, ConvBertTokenizer->BertTokenizer, BERT->ConvBERT
|
| 54 |
+
class ConvBertTokenizer(PreTrainedTokenizer):
|
| 55 |
+
r"""
|
| 56 |
+
Construct a ConvBERT tokenizer. Based on WordPiece.
|
| 57 |
+
|
| 58 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 59 |
+
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.
|
| 88 |
+
|
| 89 |
+
This should likely be deactivated for Japanese (see this
|
| 90 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 91 |
+
strip_accents (`bool`, *optional*):
|
| 92 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 93 |
+
value for `lowercase` (as in the original ConvBERT).
|
| 94 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
|
| 95 |
+
Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
|
| 96 |
+
extra spaces.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 100 |
+
|
| 101 |
+
def __init__(
|
| 102 |
+
self,
|
| 103 |
+
vocab_file,
|
| 104 |
+
do_lower_case=True,
|
| 105 |
+
do_basic_tokenize=True,
|
| 106 |
+
never_split=None,
|
| 107 |
+
unk_token="[UNK]",
|
| 108 |
+
sep_token="[SEP]",
|
| 109 |
+
pad_token="[PAD]",
|
| 110 |
+
cls_token="[CLS]",
|
| 111 |
+
mask_token="[MASK]",
|
| 112 |
+
tokenize_chinese_chars=True,
|
| 113 |
+
strip_accents=None,
|
| 114 |
+
clean_up_tokenization_spaces=True,
|
| 115 |
+
**kwargs,
|
| 116 |
+
):
|
| 117 |
+
if not os.path.isfile(vocab_file):
|
| 118 |
+
raise ValueError(
|
| 119 |
+
f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
|
| 120 |
+
" model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
|
| 121 |
+
)
|
| 122 |
+
self.vocab = load_vocab(vocab_file)
|
| 123 |
+
self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
|
| 124 |
+
self.do_basic_tokenize = do_basic_tokenize
|
| 125 |
+
if do_basic_tokenize:
|
| 126 |
+
self.basic_tokenizer = BasicTokenizer(
|
| 127 |
+
do_lower_case=do_lower_case,
|
| 128 |
+
never_split=never_split,
|
| 129 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 130 |
+
strip_accents=strip_accents,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
|
| 134 |
+
|
| 135 |
+
super().__init__(
|
| 136 |
+
do_lower_case=do_lower_case,
|
| 137 |
+
do_basic_tokenize=do_basic_tokenize,
|
| 138 |
+
never_split=never_split,
|
| 139 |
+
unk_token=unk_token,
|
| 140 |
+
sep_token=sep_token,
|
| 141 |
+
pad_token=pad_token,
|
| 142 |
+
cls_token=cls_token,
|
| 143 |
+
mask_token=mask_token,
|
| 144 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 145 |
+
strip_accents=strip_accents,
|
| 146 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 147 |
+
**kwargs,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
@property
|
| 151 |
+
def do_lower_case(self):
|
| 152 |
+
return self.basic_tokenizer.do_lower_case
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def vocab_size(self):
|
| 156 |
+
return len(self.vocab)
|
| 157 |
+
|
| 158 |
+
def get_vocab(self):
|
| 159 |
+
return dict(self.vocab, **self.added_tokens_encoder)
|
| 160 |
+
|
| 161 |
+
def _tokenize(self, text, split_special_tokens=False):
|
| 162 |
+
split_tokens = []
|
| 163 |
+
if self.do_basic_tokenize:
|
| 164 |
+
for token in self.basic_tokenizer.tokenize(
|
| 165 |
+
text, never_split=self.all_special_tokens if not split_special_tokens else None
|
| 166 |
+
):
|
| 167 |
+
# If the token is part of the never_split set
|
| 168 |
+
if token in self.basic_tokenizer.never_split:
|
| 169 |
+
split_tokens.append(token)
|
| 170 |
+
else:
|
| 171 |
+
split_tokens += self.wordpiece_tokenizer.tokenize(token)
|
| 172 |
+
else:
|
| 173 |
+
split_tokens = self.wordpiece_tokenizer.tokenize(text)
|
| 174 |
+
return split_tokens
|
| 175 |
+
|
| 176 |
+
def _convert_token_to_id(self, token):
|
| 177 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 178 |
+
return self.vocab.get(token, self.vocab.get(self.unk_token))
|
| 179 |
+
|
| 180 |
+
def _convert_id_to_token(self, index):
|
| 181 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 182 |
+
return self.ids_to_tokens.get(index, self.unk_token)
|
| 183 |
+
|
| 184 |
+
def convert_tokens_to_string(self, tokens):
|
| 185 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 186 |
+
out_string = " ".join(tokens).replace(" ##", "").strip()
|
| 187 |
+
return out_string
|
| 188 |
+
|
| 189 |
+
def build_inputs_with_special_tokens(
|
| 190 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 191 |
+
) -> List[int]:
|
| 192 |
+
"""
|
| 193 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 194 |
+
adding special tokens. A ConvBERT sequence has the following format:
|
| 195 |
+
|
| 196 |
+
- single sequence: `[CLS] X [SEP]`
|
| 197 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
token_ids_0 (`List[int]`):
|
| 201 |
+
List of IDs to which the special tokens will be added.
|
| 202 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 203 |
+
Optional second list of IDs for sequence pairs.
|
| 204 |
+
|
| 205 |
+
Returns:
|
| 206 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 207 |
+
"""
|
| 208 |
+
if token_ids_1 is None:
|
| 209 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 210 |
+
cls = [self.cls_token_id]
|
| 211 |
+
sep = [self.sep_token_id]
|
| 212 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 213 |
+
|
| 214 |
+
def get_special_tokens_mask(
|
| 215 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 216 |
+
) -> List[int]:
|
| 217 |
+
"""
|
| 218 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 219 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 220 |
+
|
| 221 |
+
Args:
|
| 222 |
+
token_ids_0 (`List[int]`):
|
| 223 |
+
List of IDs.
|
| 224 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 225 |
+
Optional second list of IDs for sequence pairs.
|
| 226 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 227 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 228 |
+
|
| 229 |
+
Returns:
|
| 230 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 231 |
+
"""
|
| 232 |
+
|
| 233 |
+
if already_has_special_tokens:
|
| 234 |
+
return super().get_special_tokens_mask(
|
| 235 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
if token_ids_1 is not None:
|
| 239 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 240 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 241 |
+
|
| 242 |
+
def create_token_type_ids_from_sequences(
|
| 243 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 244 |
+
) -> List[int]:
|
| 245 |
+
"""
|
| 246 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A ConvBERT sequence
|
| 247 |
+
pair mask has the following format:
|
| 248 |
+
|
| 249 |
+
```
|
| 250 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 251 |
+
| first sequence | second sequence |
|
| 252 |
+
```
|
| 253 |
+
|
| 254 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
token_ids_0 (`List[int]`):
|
| 258 |
+
List of IDs.
|
| 259 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 260 |
+
Optional second list of IDs for sequence pairs.
|
| 261 |
+
|
| 262 |
+
Returns:
|
| 263 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 264 |
+
"""
|
| 265 |
+
sep = [self.sep_token_id]
|
| 266 |
+
cls = [self.cls_token_id]
|
| 267 |
+
if token_ids_1 is None:
|
| 268 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 269 |
+
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
| 270 |
+
|
| 271 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 272 |
+
index = 0
|
| 273 |
+
if os.path.isdir(save_directory):
|
| 274 |
+
vocab_file = os.path.join(
|
| 275 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 276 |
+
)
|
| 277 |
+
else:
|
| 278 |
+
vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
|
| 279 |
+
with open(vocab_file, "w", encoding="utf-8") as writer:
|
| 280 |
+
for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
|
| 281 |
+
if index != token_index:
|
| 282 |
+
logger.warning(
|
| 283 |
+
f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
|
| 284 |
+
" Please check that the vocabulary is not corrupted!"
|
| 285 |
+
)
|
| 286 |
+
index = token_index
|
| 287 |
+
writer.write(token + "\n")
|
| 288 |
+
index += 1
|
| 289 |
+
return (vocab_file,)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
|
| 293 |
+
class BasicTokenizer:
|
| 294 |
+
"""
|
| 295 |
+
Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
|
| 296 |
+
|
| 297 |
+
Args:
|
| 298 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 299 |
+
Whether or not to lowercase the input when tokenizing.
|
| 300 |
+
never_split (`Iterable`, *optional*):
|
| 301 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
| 302 |
+
`do_basic_tokenize=True`
|
| 303 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 304 |
+
Whether or not to tokenize Chinese characters.
|
| 305 |
+
|
| 306 |
+
This should likely be deactivated for Japanese (see this
|
| 307 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 308 |
+
strip_accents (`bool`, *optional*):
|
| 309 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 310 |
+
value for `lowercase` (as in the original BERT).
|
| 311 |
+
do_split_on_punc (`bool`, *optional*, defaults to `True`):
|
| 312 |
+
In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
|
| 313 |
+
the full context of the words, such as contractions.
|
| 314 |
+
"""
|
| 315 |
+
|
| 316 |
+
def __init__(
|
| 317 |
+
self,
|
| 318 |
+
do_lower_case=True,
|
| 319 |
+
never_split=None,
|
| 320 |
+
tokenize_chinese_chars=True,
|
| 321 |
+
strip_accents=None,
|
| 322 |
+
do_split_on_punc=True,
|
| 323 |
+
):
|
| 324 |
+
if never_split is None:
|
| 325 |
+
never_split = []
|
| 326 |
+
self.do_lower_case = do_lower_case
|
| 327 |
+
self.never_split = set(never_split)
|
| 328 |
+
self.tokenize_chinese_chars = tokenize_chinese_chars
|
| 329 |
+
self.strip_accents = strip_accents
|
| 330 |
+
self.do_split_on_punc = do_split_on_punc
|
| 331 |
+
|
| 332 |
+
def tokenize(self, text, never_split=None):
|
| 333 |
+
"""
|
| 334 |
+
Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
|
| 335 |
+
|
| 336 |
+
Args:
|
| 337 |
+
never_split (`List[str]`, *optional*)
|
| 338 |
+
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
|
| 339 |
+
[`PreTrainedTokenizer.tokenize`]) List of token not to split.
|
| 340 |
+
"""
|
| 341 |
+
# union() returns a new set by concatenating the two sets.
|
| 342 |
+
never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
|
| 343 |
+
text = self._clean_text(text)
|
| 344 |
+
|
| 345 |
+
# This was added on November 1st, 2018 for the multilingual and Chinese
|
| 346 |
+
# models. This is also applied to the English models now, but it doesn't
|
| 347 |
+
# matter since the English models were not trained on any Chinese data
|
| 348 |
+
# and generally don't have any Chinese data in them (there are Chinese
|
| 349 |
+
# characters in the vocabulary because Wikipedia does have some Chinese
|
| 350 |
+
# words in the English Wikipedia.).
|
| 351 |
+
if self.tokenize_chinese_chars:
|
| 352 |
+
text = self._tokenize_chinese_chars(text)
|
| 353 |
+
# prevents treating the same character with different unicode codepoints as different characters
|
| 354 |
+
unicode_normalized_text = unicodedata.normalize("NFC", text)
|
| 355 |
+
orig_tokens = whitespace_tokenize(unicode_normalized_text)
|
| 356 |
+
split_tokens = []
|
| 357 |
+
for token in orig_tokens:
|
| 358 |
+
if token not in never_split:
|
| 359 |
+
if self.do_lower_case:
|
| 360 |
+
token = token.lower()
|
| 361 |
+
if self.strip_accents is not False:
|
| 362 |
+
token = self._run_strip_accents(token)
|
| 363 |
+
elif self.strip_accents:
|
| 364 |
+
token = self._run_strip_accents(token)
|
| 365 |
+
split_tokens.extend(self._run_split_on_punc(token, never_split))
|
| 366 |
+
|
| 367 |
+
output_tokens = whitespace_tokenize(" ".join(split_tokens))
|
| 368 |
+
return output_tokens
|
| 369 |
+
|
| 370 |
+
def _run_strip_accents(self, text):
|
| 371 |
+
"""Strips accents from a piece of text."""
|
| 372 |
+
text = unicodedata.normalize("NFD", text)
|
| 373 |
+
output = []
|
| 374 |
+
for char in text:
|
| 375 |
+
cat = unicodedata.category(char)
|
| 376 |
+
if cat == "Mn":
|
| 377 |
+
continue
|
| 378 |
+
output.append(char)
|
| 379 |
+
return "".join(output)
|
| 380 |
+
|
| 381 |
+
def _run_split_on_punc(self, text, never_split=None):
|
| 382 |
+
"""Splits punctuation on a piece of text."""
|
| 383 |
+
if not self.do_split_on_punc or (never_split is not None and text in never_split):
|
| 384 |
+
return [text]
|
| 385 |
+
chars = list(text)
|
| 386 |
+
i = 0
|
| 387 |
+
start_new_word = True
|
| 388 |
+
output = []
|
| 389 |
+
while i < len(chars):
|
| 390 |
+
char = chars[i]
|
| 391 |
+
if _is_punctuation(char):
|
| 392 |
+
output.append([char])
|
| 393 |
+
start_new_word = True
|
| 394 |
+
else:
|
| 395 |
+
if start_new_word:
|
| 396 |
+
output.append([])
|
| 397 |
+
start_new_word = False
|
| 398 |
+
output[-1].append(char)
|
| 399 |
+
i += 1
|
| 400 |
+
|
| 401 |
+
return ["".join(x) for x in output]
|
| 402 |
+
|
| 403 |
+
def _tokenize_chinese_chars(self, text):
|
| 404 |
+
"""Adds whitespace around any CJK character."""
|
| 405 |
+
output = []
|
| 406 |
+
for char in text:
|
| 407 |
+
cp = ord(char)
|
| 408 |
+
if self._is_chinese_char(cp):
|
| 409 |
+
output.append(" ")
|
| 410 |
+
output.append(char)
|
| 411 |
+
output.append(" ")
|
| 412 |
+
else:
|
| 413 |
+
output.append(char)
|
| 414 |
+
return "".join(output)
|
| 415 |
+
|
| 416 |
+
def _is_chinese_char(self, cp):
|
| 417 |
+
"""Checks whether CP is the codepoint of a CJK character."""
|
| 418 |
+
# This defines a "chinese character" as anything in the CJK Unicode block:
|
| 419 |
+
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
|
| 420 |
+
#
|
| 421 |
+
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
|
| 422 |
+
# despite its name. The modern Korean Hangul alphabet is a different block,
|
| 423 |
+
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
|
| 424 |
+
# space-separated words, so they are not treated specially and handled
|
| 425 |
+
# like the all of the other languages.
|
| 426 |
+
if (
|
| 427 |
+
(cp >= 0x4E00 and cp <= 0x9FFF)
|
| 428 |
+
or (cp >= 0x3400 and cp <= 0x4DBF) #
|
| 429 |
+
or (cp >= 0x20000 and cp <= 0x2A6DF) #
|
| 430 |
+
or (cp >= 0x2A700 and cp <= 0x2B73F) #
|
| 431 |
+
or (cp >= 0x2B740 and cp <= 0x2B81F) #
|
| 432 |
+
or (cp >= 0x2B820 and cp <= 0x2CEAF) #
|
| 433 |
+
or (cp >= 0xF900 and cp <= 0xFAFF)
|
| 434 |
+
or (cp >= 0x2F800 and cp <= 0x2FA1F) #
|
| 435 |
+
): #
|
| 436 |
+
return True
|
| 437 |
+
|
| 438 |
+
return False
|
| 439 |
+
|
| 440 |
+
def _clean_text(self, text):
|
| 441 |
+
"""Performs invalid character removal and whitespace cleanup on text."""
|
| 442 |
+
output = []
|
| 443 |
+
for char in text:
|
| 444 |
+
cp = ord(char)
|
| 445 |
+
if cp == 0 or cp == 0xFFFD or _is_control(char):
|
| 446 |
+
continue
|
| 447 |
+
if _is_whitespace(char):
|
| 448 |
+
output.append(" ")
|
| 449 |
+
else:
|
| 450 |
+
output.append(char)
|
| 451 |
+
return "".join(output)
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
# Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
|
| 455 |
+
class WordpieceTokenizer:
|
| 456 |
+
"""Runs WordPiece tokenization."""
|
| 457 |
+
|
| 458 |
+
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
|
| 459 |
+
self.vocab = vocab
|
| 460 |
+
self.unk_token = unk_token
|
| 461 |
+
self.max_input_chars_per_word = max_input_chars_per_word
|
| 462 |
+
|
| 463 |
+
def tokenize(self, text):
|
| 464 |
+
"""
|
| 465 |
+
Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
|
| 466 |
+
tokenization using the given vocabulary.
|
| 467 |
+
|
| 468 |
+
For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
|
| 469 |
+
|
| 470 |
+
Args:
|
| 471 |
+
text: A single token or whitespace separated tokens. This should have
|
| 472 |
+
already been passed through *BasicTokenizer*.
|
| 473 |
+
|
| 474 |
+
Returns:
|
| 475 |
+
A list of wordpiece tokens.
|
| 476 |
+
"""
|
| 477 |
+
|
| 478 |
+
output_tokens = []
|
| 479 |
+
for token in whitespace_tokenize(text):
|
| 480 |
+
chars = list(token)
|
| 481 |
+
if len(chars) > self.max_input_chars_per_word:
|
| 482 |
+
output_tokens.append(self.unk_token)
|
| 483 |
+
continue
|
| 484 |
+
|
| 485 |
+
is_bad = False
|
| 486 |
+
start = 0
|
| 487 |
+
sub_tokens = []
|
| 488 |
+
while start < len(chars):
|
| 489 |
+
end = len(chars)
|
| 490 |
+
cur_substr = None
|
| 491 |
+
while start < end:
|
| 492 |
+
substr = "".join(chars[start:end])
|
| 493 |
+
if start > 0:
|
| 494 |
+
substr = "##" + substr
|
| 495 |
+
if substr in self.vocab:
|
| 496 |
+
cur_substr = substr
|
| 497 |
+
break
|
| 498 |
+
end -= 1
|
| 499 |
+
if cur_substr is None:
|
| 500 |
+
is_bad = True
|
| 501 |
+
break
|
| 502 |
+
sub_tokens.append(cur_substr)
|
| 503 |
+
start = end
|
| 504 |
+
|
| 505 |
+
if is_bad:
|
| 506 |
+
output_tokens.append(self.unk_token)
|
| 507 |
+
else:
|
| 508 |
+
output_tokens.extend(sub_tokens)
|
| 509 |
+
return output_tokens
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
__all__ = ["ConvBertTokenizer"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convbert/tokenization_convbert_fast.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 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 ConvBERT."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
from typing import List, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from tokenizers import normalizers
|
| 21 |
+
|
| 22 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
from .tokenization_convbert import ConvBertTokenizer
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast with bert-base-cased->YituTech/conv-bert-base, Bert->ConvBert, BERT->ConvBERT
|
| 33 |
+
class ConvBertTokenizerFast(PreTrainedTokenizerFast):
|
| 34 |
+
r"""
|
| 35 |
+
Construct a "fast" ConvBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
|
| 36 |
+
|
| 37 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
| 38 |
+
refer to this superclass for more information regarding those methods.
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
vocab_file (`str`):
|
| 42 |
+
File containing the vocabulary.
|
| 43 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 44 |
+
Whether or not to lowercase the input when tokenizing.
|
| 45 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 46 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 47 |
+
token instead.
|
| 48 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 49 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 50 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 51 |
+
token of a sequence built with special tokens.
|
| 52 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 53 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 54 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 55 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 56 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 57 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 58 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 59 |
+
modeling. This is the token which the model will try to predict.
|
| 60 |
+
clean_text (`bool`, *optional*, defaults to `True`):
|
| 61 |
+
Whether or not to clean the text before tokenization by removing any control characters and replacing all
|
| 62 |
+
whitespaces by the classic one.
|
| 63 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 64 |
+
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
|
| 65 |
+
issue](https://github.com/huggingface/transformers/issues/328)).
|
| 66 |
+
strip_accents (`bool`, *optional*):
|
| 67 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 68 |
+
value for `lowercase` (as in the original ConvBERT).
|
| 69 |
+
wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
|
| 70 |
+
The prefix for subwords.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 74 |
+
slow_tokenizer_class = ConvBertTokenizer
|
| 75 |
+
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
vocab_file=None,
|
| 79 |
+
tokenizer_file=None,
|
| 80 |
+
do_lower_case=True,
|
| 81 |
+
unk_token="[UNK]",
|
| 82 |
+
sep_token="[SEP]",
|
| 83 |
+
pad_token="[PAD]",
|
| 84 |
+
cls_token="[CLS]",
|
| 85 |
+
mask_token="[MASK]",
|
| 86 |
+
tokenize_chinese_chars=True,
|
| 87 |
+
strip_accents=None,
|
| 88 |
+
**kwargs,
|
| 89 |
+
):
|
| 90 |
+
super().__init__(
|
| 91 |
+
vocab_file,
|
| 92 |
+
tokenizer_file=tokenizer_file,
|
| 93 |
+
do_lower_case=do_lower_case,
|
| 94 |
+
unk_token=unk_token,
|
| 95 |
+
sep_token=sep_token,
|
| 96 |
+
pad_token=pad_token,
|
| 97 |
+
cls_token=cls_token,
|
| 98 |
+
mask_token=mask_token,
|
| 99 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 100 |
+
strip_accents=strip_accents,
|
| 101 |
+
**kwargs,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
|
| 105 |
+
if (
|
| 106 |
+
normalizer_state.get("lowercase", do_lower_case) != do_lower_case
|
| 107 |
+
or normalizer_state.get("strip_accents", strip_accents) != strip_accents
|
| 108 |
+
or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
|
| 109 |
+
):
|
| 110 |
+
normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
|
| 111 |
+
normalizer_state["lowercase"] = do_lower_case
|
| 112 |
+
normalizer_state["strip_accents"] = strip_accents
|
| 113 |
+
normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
|
| 114 |
+
self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
|
| 115 |
+
|
| 116 |
+
self.do_lower_case = do_lower_case
|
| 117 |
+
|
| 118 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
| 119 |
+
"""
|
| 120 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 121 |
+
adding special tokens. A ConvBERT sequence has the following format:
|
| 122 |
+
|
| 123 |
+
- single sequence: `[CLS] X [SEP]`
|
| 124 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
token_ids_0 (`List[int]`):
|
| 128 |
+
List of IDs to which the special tokens will be added.
|
| 129 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 130 |
+
Optional second list of IDs for sequence pairs.
|
| 131 |
+
|
| 132 |
+
Returns:
|
| 133 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 134 |
+
"""
|
| 135 |
+
output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 136 |
+
|
| 137 |
+
if token_ids_1 is not None:
|
| 138 |
+
output += token_ids_1 + [self.sep_token_id]
|
| 139 |
+
|
| 140 |
+
return output
|
| 141 |
+
|
| 142 |
+
def create_token_type_ids_from_sequences(
|
| 143 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 144 |
+
) -> List[int]:
|
| 145 |
+
"""
|
| 146 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A ConvBERT sequence
|
| 147 |
+
pair mask has the following format:
|
| 148 |
+
|
| 149 |
+
```
|
| 150 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 151 |
+
| first sequence | second sequence |
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
token_ids_0 (`List[int]`):
|
| 158 |
+
List of IDs.
|
| 159 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 160 |
+
Optional second list of IDs for sequence pairs.
|
| 161 |
+
|
| 162 |
+
Returns:
|
| 163 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 164 |
+
"""
|
| 165 |
+
sep = [self.sep_token_id]
|
| 166 |
+
cls = [self.cls_token_id]
|
| 167 |
+
if token_ids_1 is None:
|
| 168 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 169 |
+
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
| 170 |
+
|
| 171 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 172 |
+
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
|
| 173 |
+
return tuple(files)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
__all__ = ["ConvBertTokenizerFast"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_convnext import *
|
| 22 |
+
from .feature_extraction_convnext import *
|
| 23 |
+
from .image_processing_convnext import *
|
| 24 |
+
from .image_processing_convnext_fast import *
|
| 25 |
+
from .modeling_convnext import *
|
| 26 |
+
from .modeling_tf_convnext import *
|
| 27 |
+
else:
|
| 28 |
+
import sys
|
| 29 |
+
|
| 30 |
+
_file = globals()["__file__"]
|
| 31 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/configuration_convnext.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 Meta Platforms, 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 |
+
"""ConvNeXT model configuration"""
|
| 16 |
+
|
| 17 |
+
from collections import OrderedDict
|
| 18 |
+
from typing import Mapping
|
| 19 |
+
|
| 20 |
+
from packaging import version
|
| 21 |
+
|
| 22 |
+
from ...configuration_utils import PretrainedConfig
|
| 23 |
+
from ...onnx import OnnxConfig
|
| 24 |
+
from ...utils import logging
|
| 25 |
+
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ConvNextConfig(BackboneConfigMixin, PretrainedConfig):
|
| 32 |
+
r"""
|
| 33 |
+
This is the configuration class to store the configuration of a [`ConvNextModel`]. It is used to instantiate an
|
| 34 |
+
ConvNeXT model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 35 |
+
with the defaults will yield a similar configuration to that of the ConvNeXT
|
| 36 |
+
[facebook/convnext-tiny-224](https://huggingface.co/facebook/convnext-tiny-224) architecture.
|
| 37 |
+
|
| 38 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 39 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 43 |
+
The number of input channels.
|
| 44 |
+
patch_size (`int`, *optional*, defaults to 4):
|
| 45 |
+
Patch size to use in the patch embedding layer.
|
| 46 |
+
num_stages (`int`, *optional*, defaults to 4):
|
| 47 |
+
The number of stages in the model.
|
| 48 |
+
hidden_sizes (`List[int]`, *optional*, defaults to [96, 192, 384, 768]):
|
| 49 |
+
Dimensionality (hidden size) at each stage.
|
| 50 |
+
depths (`List[int]`, *optional*, defaults to [3, 3, 9, 3]):
|
| 51 |
+
Depth (number of blocks) for each stage.
|
| 52 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 53 |
+
The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`,
|
| 54 |
+
`"selu"` and `"gelu_new"` are supported.
|
| 55 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 56 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 57 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 58 |
+
The epsilon used by the layer normalization layers.
|
| 59 |
+
layer_scale_init_value (`float`, *optional*, defaults to 1e-6):
|
| 60 |
+
The initial value for the layer scale.
|
| 61 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 62 |
+
The drop rate for stochastic depth.
|
| 63 |
+
out_features (`List[str]`, *optional*):
|
| 64 |
+
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
|
| 65 |
+
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
|
| 66 |
+
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
|
| 67 |
+
same order as defined in the `stage_names` attribute.
|
| 68 |
+
out_indices (`List[int]`, *optional*):
|
| 69 |
+
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
|
| 70 |
+
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
|
| 71 |
+
If unset and `out_features` is unset, will default to the last stage. Must be in the
|
| 72 |
+
same order as defined in the `stage_names` attribute.
|
| 73 |
+
|
| 74 |
+
Example:
|
| 75 |
+
```python
|
| 76 |
+
>>> from transformers import ConvNextConfig, ConvNextModel
|
| 77 |
+
|
| 78 |
+
>>> # Initializing a ConvNext convnext-tiny-224 style configuration
|
| 79 |
+
>>> configuration = ConvNextConfig()
|
| 80 |
+
|
| 81 |
+
>>> # Initializing a model (with random weights) from the convnext-tiny-224 style configuration
|
| 82 |
+
>>> model = ConvNextModel(configuration)
|
| 83 |
+
|
| 84 |
+
>>> # Accessing the model configuration
|
| 85 |
+
>>> configuration = model.config
|
| 86 |
+
```"""
|
| 87 |
+
|
| 88 |
+
model_type = "convnext"
|
| 89 |
+
|
| 90 |
+
def __init__(
|
| 91 |
+
self,
|
| 92 |
+
num_channels=3,
|
| 93 |
+
patch_size=4,
|
| 94 |
+
num_stages=4,
|
| 95 |
+
hidden_sizes=None,
|
| 96 |
+
depths=None,
|
| 97 |
+
hidden_act="gelu",
|
| 98 |
+
initializer_range=0.02,
|
| 99 |
+
layer_norm_eps=1e-12,
|
| 100 |
+
layer_scale_init_value=1e-6,
|
| 101 |
+
drop_path_rate=0.0,
|
| 102 |
+
image_size=224,
|
| 103 |
+
out_features=None,
|
| 104 |
+
out_indices=None,
|
| 105 |
+
**kwargs,
|
| 106 |
+
):
|
| 107 |
+
super().__init__(**kwargs)
|
| 108 |
+
|
| 109 |
+
self.num_channels = num_channels
|
| 110 |
+
self.patch_size = patch_size
|
| 111 |
+
self.num_stages = num_stages
|
| 112 |
+
self.hidden_sizes = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
|
| 113 |
+
self.depths = [3, 3, 9, 3] if depths is None else depths
|
| 114 |
+
self.hidden_act = hidden_act
|
| 115 |
+
self.initializer_range = initializer_range
|
| 116 |
+
self.layer_norm_eps = layer_norm_eps
|
| 117 |
+
self.layer_scale_init_value = layer_scale_init_value
|
| 118 |
+
self.drop_path_rate = drop_path_rate
|
| 119 |
+
self.image_size = image_size
|
| 120 |
+
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
|
| 121 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 122 |
+
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class ConvNextOnnxConfig(OnnxConfig):
|
| 127 |
+
torch_onnx_minimum_version = version.parse("1.11")
|
| 128 |
+
|
| 129 |
+
@property
|
| 130 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 131 |
+
return OrderedDict(
|
| 132 |
+
[
|
| 133 |
+
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
|
| 134 |
+
]
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
@property
|
| 138 |
+
def atol_for_validation(self) -> float:
|
| 139 |
+
return 1e-5
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
__all__ = ["ConvNextConfig", "ConvNextOnnxConfig"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/convert_convnext_to_pytorch.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert ConvNext checkpoints from the original repository.
|
| 16 |
+
|
| 17 |
+
URL: https://github.com/facebookresearch/ConvNeXt"""
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import json
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import requests
|
| 24 |
+
import torch
|
| 25 |
+
from huggingface_hub import hf_hub_download
|
| 26 |
+
from PIL import Image
|
| 27 |
+
|
| 28 |
+
from transformers import ConvNextConfig, ConvNextForImageClassification, ConvNextImageProcessor
|
| 29 |
+
from transformers.utils import logging
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logging.set_verbosity_info()
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_convnext_config(checkpoint_url):
|
| 37 |
+
config = ConvNextConfig()
|
| 38 |
+
|
| 39 |
+
if "tiny" in checkpoint_url:
|
| 40 |
+
depths = [3, 3, 9, 3]
|
| 41 |
+
hidden_sizes = [96, 192, 384, 768]
|
| 42 |
+
if "small" in checkpoint_url:
|
| 43 |
+
depths = [3, 3, 27, 3]
|
| 44 |
+
hidden_sizes = [96, 192, 384, 768]
|
| 45 |
+
if "base" in checkpoint_url:
|
| 46 |
+
depths = [3, 3, 27, 3]
|
| 47 |
+
hidden_sizes = [128, 256, 512, 1024]
|
| 48 |
+
if "large" in checkpoint_url:
|
| 49 |
+
depths = [3, 3, 27, 3]
|
| 50 |
+
hidden_sizes = [192, 384, 768, 1536]
|
| 51 |
+
if "xlarge" in checkpoint_url:
|
| 52 |
+
depths = [3, 3, 27, 3]
|
| 53 |
+
hidden_sizes = [256, 512, 1024, 2048]
|
| 54 |
+
|
| 55 |
+
if "1k" in checkpoint_url:
|
| 56 |
+
num_labels = 1000
|
| 57 |
+
filename = "imagenet-1k-id2label.json"
|
| 58 |
+
expected_shape = (1, 1000)
|
| 59 |
+
else:
|
| 60 |
+
num_labels = 21841
|
| 61 |
+
filename = "imagenet-22k-id2label.json"
|
| 62 |
+
expected_shape = (1, 21841)
|
| 63 |
+
|
| 64 |
+
repo_id = "huggingface/label-files"
|
| 65 |
+
config.num_labels = num_labels
|
| 66 |
+
id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
|
| 67 |
+
id2label = {int(k): v for k, v in id2label.items()}
|
| 68 |
+
if "1k" not in checkpoint_url:
|
| 69 |
+
# this dataset contains 21843 labels but the model only has 21841
|
| 70 |
+
# we delete the classes as mentioned in https://github.com/google-research/big_transfer/issues/18
|
| 71 |
+
del id2label[9205]
|
| 72 |
+
del id2label[15027]
|
| 73 |
+
config.id2label = id2label
|
| 74 |
+
config.label2id = {v: k for k, v in id2label.items()}
|
| 75 |
+
config.hidden_sizes = hidden_sizes
|
| 76 |
+
config.depths = depths
|
| 77 |
+
|
| 78 |
+
return config, expected_shape
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def rename_key(name):
|
| 82 |
+
if "downsample_layers.0.0" in name:
|
| 83 |
+
name = name.replace("downsample_layers.0.0", "embeddings.patch_embeddings")
|
| 84 |
+
if "downsample_layers.0.1" in name:
|
| 85 |
+
name = name.replace("downsample_layers.0.1", "embeddings.norm") # we rename to layernorm later on
|
| 86 |
+
if "downsample_layers.1.0" in name:
|
| 87 |
+
name = name.replace("downsample_layers.1.0", "stages.1.downsampling_layer.0")
|
| 88 |
+
if "downsample_layers.1.1" in name:
|
| 89 |
+
name = name.replace("downsample_layers.1.1", "stages.1.downsampling_layer.1")
|
| 90 |
+
if "downsample_layers.2.0" in name:
|
| 91 |
+
name = name.replace("downsample_layers.2.0", "stages.2.downsampling_layer.0")
|
| 92 |
+
if "downsample_layers.2.1" in name:
|
| 93 |
+
name = name.replace("downsample_layers.2.1", "stages.2.downsampling_layer.1")
|
| 94 |
+
if "downsample_layers.3.0" in name:
|
| 95 |
+
name = name.replace("downsample_layers.3.0", "stages.3.downsampling_layer.0")
|
| 96 |
+
if "downsample_layers.3.1" in name:
|
| 97 |
+
name = name.replace("downsample_layers.3.1", "stages.3.downsampling_layer.1")
|
| 98 |
+
if "stages" in name and "downsampling_layer" not in name:
|
| 99 |
+
# stages.0.0. for instance should be renamed to stages.0.layers.0.
|
| 100 |
+
name = name[: len("stages.0")] + ".layers" + name[len("stages.0") :]
|
| 101 |
+
if "stages" in name:
|
| 102 |
+
name = name.replace("stages", "encoder.stages")
|
| 103 |
+
if "norm" in name:
|
| 104 |
+
name = name.replace("norm", "layernorm")
|
| 105 |
+
if "gamma" in name:
|
| 106 |
+
name = name.replace("gamma", "layer_scale_parameter")
|
| 107 |
+
if "head" in name:
|
| 108 |
+
name = name.replace("head", "classifier")
|
| 109 |
+
|
| 110 |
+
return name
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# We will verify our results on an image of cute cats
|
| 114 |
+
def prepare_img():
|
| 115 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 116 |
+
im = Image.open(requests.get(url, stream=True).raw)
|
| 117 |
+
return im
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@torch.no_grad()
|
| 121 |
+
def convert_convnext_checkpoint(checkpoint_url, pytorch_dump_folder_path):
|
| 122 |
+
"""
|
| 123 |
+
Copy/paste/tweak model's weights to our ConvNext structure.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
# define ConvNext configuration based on URL
|
| 127 |
+
config, expected_shape = get_convnext_config(checkpoint_url)
|
| 128 |
+
# load original state_dict from URL
|
| 129 |
+
state_dict = torch.hub.load_state_dict_from_url(checkpoint_url)["model"]
|
| 130 |
+
# rename keys
|
| 131 |
+
for key in state_dict.copy().keys():
|
| 132 |
+
val = state_dict.pop(key)
|
| 133 |
+
state_dict[rename_key(key)] = val
|
| 134 |
+
# add prefix to all keys expect classifier head
|
| 135 |
+
for key in state_dict.copy().keys():
|
| 136 |
+
val = state_dict.pop(key)
|
| 137 |
+
if not key.startswith("classifier"):
|
| 138 |
+
key = "convnext." + key
|
| 139 |
+
state_dict[key] = val
|
| 140 |
+
|
| 141 |
+
# load HuggingFace model
|
| 142 |
+
model = ConvNextForImageClassification(config)
|
| 143 |
+
model.load_state_dict(state_dict)
|
| 144 |
+
model.eval()
|
| 145 |
+
|
| 146 |
+
# Check outputs on an image, prepared by ConvNextImageProcessor
|
| 147 |
+
size = 224 if "224" in checkpoint_url else 384
|
| 148 |
+
image_processor = ConvNextImageProcessor(size=size)
|
| 149 |
+
pixel_values = image_processor(images=prepare_img(), return_tensors="pt").pixel_values
|
| 150 |
+
|
| 151 |
+
logits = model(pixel_values).logits
|
| 152 |
+
|
| 153 |
+
# note: the logits below were obtained without center cropping
|
| 154 |
+
if checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_tiny_1k_224_ema.pth":
|
| 155 |
+
expected_logits = torch.tensor([-0.1210, -0.6605, 0.1918])
|
| 156 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_small_1k_224_ema.pth":
|
| 157 |
+
expected_logits = torch.tensor([-0.4473, -0.1847, -0.6365])
|
| 158 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_224_ema.pth":
|
| 159 |
+
expected_logits = torch.tensor([0.4525, 0.7539, 0.0308])
|
| 160 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_1k_384.pth":
|
| 161 |
+
expected_logits = torch.tensor([0.3561, 0.6350, -0.0384])
|
| 162 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_224_ema.pth":
|
| 163 |
+
expected_logits = torch.tensor([0.4174, -0.0989, 0.1489])
|
| 164 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_1k_384.pth":
|
| 165 |
+
expected_logits = torch.tensor([0.2513, -0.1349, -0.1613])
|
| 166 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_224.pth":
|
| 167 |
+
expected_logits = torch.tensor([1.2980, 0.3631, -0.1198])
|
| 168 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_224.pth":
|
| 169 |
+
expected_logits = torch.tensor([1.2963, 0.1227, 0.1723])
|
| 170 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_224.pth":
|
| 171 |
+
expected_logits = torch.tensor([1.7956, 0.8390, 0.2820])
|
| 172 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_1k_224.pth":
|
| 173 |
+
expected_logits = torch.tensor([-0.2822, -0.0502, -0.0878])
|
| 174 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_base_22k_1k_384.pth":
|
| 175 |
+
expected_logits = torch.tensor([-0.5672, -0.0730, -0.4348])
|
| 176 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_1k_224.pth":
|
| 177 |
+
expected_logits = torch.tensor([0.2681, 0.2365, 0.6246])
|
| 178 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_large_22k_1k_384.pth":
|
| 179 |
+
expected_logits = torch.tensor([-0.2642, 0.3931, 0.5116])
|
| 180 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_1k_224_ema.pth":
|
| 181 |
+
expected_logits = torch.tensor([-0.6677, -0.1873, -0.8379])
|
| 182 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnext_xlarge_22k_1k_384_ema.pth":
|
| 183 |
+
expected_logits = torch.tensor([-0.7749, -0.2967, -0.6444])
|
| 184 |
+
else:
|
| 185 |
+
raise ValueError(f"Unknown URL: {checkpoint_url}")
|
| 186 |
+
|
| 187 |
+
assert torch.allclose(logits[0, :3], expected_logits, atol=1e-3)
|
| 188 |
+
assert logits.shape == expected_shape
|
| 189 |
+
|
| 190 |
+
Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
|
| 191 |
+
print(f"Saving model to {pytorch_dump_folder_path}")
|
| 192 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 193 |
+
print(f"Saving image processor to {pytorch_dump_folder_path}")
|
| 194 |
+
image_processor.save_pretrained(pytorch_dump_folder_path)
|
| 195 |
+
|
| 196 |
+
print("Pushing model to the hub...")
|
| 197 |
+
model_name = "convnext"
|
| 198 |
+
if "tiny" in checkpoint_url:
|
| 199 |
+
model_name += "-tiny"
|
| 200 |
+
elif "small" in checkpoint_url:
|
| 201 |
+
model_name += "-small"
|
| 202 |
+
elif "base" in checkpoint_url:
|
| 203 |
+
model_name += "-base"
|
| 204 |
+
elif "xlarge" in checkpoint_url:
|
| 205 |
+
model_name += "-xlarge"
|
| 206 |
+
elif "large" in checkpoint_url:
|
| 207 |
+
model_name += "-large"
|
| 208 |
+
if "224" in checkpoint_url:
|
| 209 |
+
model_name += "-224"
|
| 210 |
+
elif "384" in checkpoint_url:
|
| 211 |
+
model_name += "-384"
|
| 212 |
+
if "22k" in checkpoint_url and "1k" not in checkpoint_url:
|
| 213 |
+
model_name += "-22k"
|
| 214 |
+
if "22k" in checkpoint_url and "1k" in checkpoint_url:
|
| 215 |
+
model_name += "-22k-1k"
|
| 216 |
+
|
| 217 |
+
model.push_to_hub(
|
| 218 |
+
repo_path_or_name=Path(pytorch_dump_folder_path, model_name),
|
| 219 |
+
organization="nielsr",
|
| 220 |
+
commit_message="Add model",
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
if __name__ == "__main__":
|
| 225 |
+
parser = argparse.ArgumentParser()
|
| 226 |
+
# Required parameters
|
| 227 |
+
parser.add_argument(
|
| 228 |
+
"--checkpoint_url",
|
| 229 |
+
default="https://dl.fbaipublicfiles.com/convnext/convnext_tiny_1k_224_ema.pth",
|
| 230 |
+
type=str,
|
| 231 |
+
help="URL of the original ConvNeXT checkpoint you'd like to convert.",
|
| 232 |
+
)
|
| 233 |
+
parser.add_argument(
|
| 234 |
+
"--pytorch_dump_folder_path",
|
| 235 |
+
default=None,
|
| 236 |
+
type=str,
|
| 237 |
+
required=True,
|
| 238 |
+
help="Path to the output PyTorch model directory.",
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
args = parser.parse_args()
|
| 242 |
+
convert_convnext_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/feature_extraction_convnext.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Feature extractor class for ConvNeXT."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
from .image_processing_convnext import ConvNextImageProcessor
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ConvNextFeatureExtractor(ConvNextImageProcessor):
|
| 27 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 28 |
+
warnings.warn(
|
| 29 |
+
"The class ConvNextFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
|
| 30 |
+
" Please use ConvNextImageProcessor instead.",
|
| 31 |
+
FutureWarning,
|
| 32 |
+
)
|
| 33 |
+
super().__init__(*args, **kwargs)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
__all__ = ["ConvNextFeatureExtractor"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/image_processing_convnext.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 ConvNeXT."""
|
| 16 |
+
|
| 17 |
+
from typing import Dict, List, Optional, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 22 |
+
from ...image_transforms import (
|
| 23 |
+
center_crop,
|
| 24 |
+
get_resize_output_image_size,
|
| 25 |
+
resize,
|
| 26 |
+
to_channel_dimension_format,
|
| 27 |
+
)
|
| 28 |
+
from ...image_utils import (
|
| 29 |
+
IMAGENET_STANDARD_MEAN,
|
| 30 |
+
IMAGENET_STANDARD_STD,
|
| 31 |
+
ChannelDimension,
|
| 32 |
+
ImageInput,
|
| 33 |
+
PILImageResampling,
|
| 34 |
+
infer_channel_dimension_format,
|
| 35 |
+
is_scaled_image,
|
| 36 |
+
make_list_of_images,
|
| 37 |
+
to_numpy_array,
|
| 38 |
+
valid_images,
|
| 39 |
+
validate_preprocess_arguments,
|
| 40 |
+
)
|
| 41 |
+
from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if is_vision_available():
|
| 45 |
+
import PIL
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
logger = logging.get_logger(__name__)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class ConvNextImageProcessor(BaseImageProcessor):
|
| 52 |
+
r"""
|
| 53 |
+
Constructs a ConvNeXT image processor.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 57 |
+
Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be overriden
|
| 58 |
+
by `do_resize` in the `preprocess` method.
|
| 59 |
+
size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 384}`):
|
| 60 |
+
Resolution of the output image after `resize` is applied. If `size["shortest_edge"]` >= 384, the image is
|
| 61 |
+
resized to `(size["shortest_edge"], size["shortest_edge"])`. Otherwise, the smaller edge of the image will
|
| 62 |
+
be matched to `int(size["shortest_edge"]/crop_pct)`, after which the image is cropped to
|
| 63 |
+
`(size["shortest_edge"], size["shortest_edge"])`. Only has an effect if `do_resize` is set to `True`. Can
|
| 64 |
+
be overriden by `size` in the `preprocess` method.
|
| 65 |
+
crop_pct (`float` *optional*, defaults to 224 / 256):
|
| 66 |
+
Percentage of the image to crop. Only has an effect if `do_resize` is `True` and size < 384. Can be
|
| 67 |
+
overriden by `crop_pct` in the `preprocess` method.
|
| 68 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
|
| 69 |
+
Resampling filter to use if resizing the image. Can be overriden by `resample` in the `preprocess` method.
|
| 70 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 71 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overriden by `do_rescale` in
|
| 72 |
+
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 overriden by `rescale_factor` in the `preprocess`
|
| 75 |
+
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: Dict[str, int] = None,
|
| 93 |
+
crop_pct: float = None,
|
| 94 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 95 |
+
do_rescale: bool = True,
|
| 96 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 97 |
+
do_normalize: bool = True,
|
| 98 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 99 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 100 |
+
**kwargs,
|
| 101 |
+
) -> None:
|
| 102 |
+
super().__init__(**kwargs)
|
| 103 |
+
size = size if size is not None else {"shortest_edge": 384}
|
| 104 |
+
size = get_size_dict(size, default_to_square=False)
|
| 105 |
+
|
| 106 |
+
self.do_resize = do_resize
|
| 107 |
+
self.size = size
|
| 108 |
+
# Default value set here for backwards compatibility where the value in config is None
|
| 109 |
+
self.crop_pct = crop_pct if crop_pct is not None else 224 / 256
|
| 110 |
+
self.resample = resample
|
| 111 |
+
self.do_rescale = do_rescale
|
| 112 |
+
self.rescale_factor = rescale_factor
|
| 113 |
+
self.do_normalize = do_normalize
|
| 114 |
+
self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
|
| 115 |
+
self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
|
| 116 |
+
|
| 117 |
+
def resize(
|
| 118 |
+
self,
|
| 119 |
+
image: np.ndarray,
|
| 120 |
+
size: Dict[str, int],
|
| 121 |
+
crop_pct: float,
|
| 122 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 123 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 124 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 125 |
+
**kwargs,
|
| 126 |
+
) -> np.ndarray:
|
| 127 |
+
"""
|
| 128 |
+
Resize an image.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
image (`np.ndarray`):
|
| 132 |
+
Image to resize.
|
| 133 |
+
size (`Dict[str, int]`):
|
| 134 |
+
Dictionary of the form `{"shortest_edge": int}`, specifying the size of the output image. If
|
| 135 |
+
`size["shortest_edge"]` >= 384 image is resized to `(size["shortest_edge"], size["shortest_edge"])`.
|
| 136 |
+
Otherwise, the smaller edge of the image will be matched to `int(size["shortest_edge"] / crop_pct)`,
|
| 137 |
+
after which the image is cropped to `(size["shortest_edge"], size["shortest_edge"])`.
|
| 138 |
+
crop_pct (`float`):
|
| 139 |
+
Percentage of the image to crop. Only has an effect if size < 384.
|
| 140 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 141 |
+
Resampling filter to use when resizing the image.
|
| 142 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 143 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 144 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 145 |
+
The channel dimension format of the input image. If not provided, it will be inferred from the input
|
| 146 |
+
image.
|
| 147 |
+
"""
|
| 148 |
+
size = get_size_dict(size, default_to_square=False)
|
| 149 |
+
if "shortest_edge" not in size:
|
| 150 |
+
raise ValueError(f"Size dictionary must contain 'shortest_edge' key. Got {size.keys()}")
|
| 151 |
+
shortest_edge = size["shortest_edge"]
|
| 152 |
+
|
| 153 |
+
if shortest_edge < 384:
|
| 154 |
+
# maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
|
| 155 |
+
resize_shortest_edge = int(shortest_edge / crop_pct)
|
| 156 |
+
resize_size = get_resize_output_image_size(
|
| 157 |
+
image, size=resize_shortest_edge, default_to_square=False, input_data_format=input_data_format
|
| 158 |
+
)
|
| 159 |
+
image = resize(
|
| 160 |
+
image=image,
|
| 161 |
+
size=resize_size,
|
| 162 |
+
resample=resample,
|
| 163 |
+
data_format=data_format,
|
| 164 |
+
input_data_format=input_data_format,
|
| 165 |
+
**kwargs,
|
| 166 |
+
)
|
| 167 |
+
# then crop to (shortest_edge, shortest_edge)
|
| 168 |
+
return center_crop(
|
| 169 |
+
image=image,
|
| 170 |
+
size=(shortest_edge, shortest_edge),
|
| 171 |
+
data_format=data_format,
|
| 172 |
+
input_data_format=input_data_format,
|
| 173 |
+
**kwargs,
|
| 174 |
+
)
|
| 175 |
+
else:
|
| 176 |
+
# warping (no cropping) when evaluated at 384 or larger
|
| 177 |
+
return resize(
|
| 178 |
+
image,
|
| 179 |
+
size=(shortest_edge, shortest_edge),
|
| 180 |
+
resample=resample,
|
| 181 |
+
data_format=data_format,
|
| 182 |
+
input_data_format=input_data_format,
|
| 183 |
+
**kwargs,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
@filter_out_non_signature_kwargs()
|
| 187 |
+
def preprocess(
|
| 188 |
+
self,
|
| 189 |
+
images: ImageInput,
|
| 190 |
+
do_resize: bool = None,
|
| 191 |
+
size: Dict[str, int] = None,
|
| 192 |
+
crop_pct: float = None,
|
| 193 |
+
resample: PILImageResampling = None,
|
| 194 |
+
do_rescale: bool = None,
|
| 195 |
+
rescale_factor: float = None,
|
| 196 |
+
do_normalize: bool = None,
|
| 197 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 198 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 199 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 200 |
+
data_format: ChannelDimension = ChannelDimension.FIRST,
|
| 201 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 202 |
+
) -> PIL.Image.Image:
|
| 203 |
+
"""
|
| 204 |
+
Preprocess an image or batch of images.
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
images (`ImageInput`):
|
| 208 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 209 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 210 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 211 |
+
Whether to resize the image.
|
| 212 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
| 213 |
+
Size of the output image after `resize` has been applied. If `size["shortest_edge"]` >= 384, the image
|
| 214 |
+
is resized to `(size["shortest_edge"], size["shortest_edge"])`. Otherwise, the smaller edge of the
|
| 215 |
+
image will be matched to `int(size["shortest_edge"]/ crop_pct)`, after which the image is cropped to
|
| 216 |
+
`(size["shortest_edge"], size["shortest_edge"])`. Only has an effect if `do_resize` is set to `True`.
|
| 217 |
+
crop_pct (`float`, *optional*, defaults to `self.crop_pct`):
|
| 218 |
+
Percentage of the image to crop if size < 384.
|
| 219 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 220 |
+
Resampling filter to use if resizing the image. This can be one of `PILImageResampling`, filters. Only
|
| 221 |
+
has 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.
|
| 230 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 231 |
+
Image standard deviation.
|
| 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 |
+
crop_pct = crop_pct if crop_pct is not None else self.crop_pct
|
| 253 |
+
resample = resample if resample is not None else self.resample
|
| 254 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 255 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 256 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 257 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 258 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 259 |
+
|
| 260 |
+
size = size if size is not None else self.size
|
| 261 |
+
size = get_size_dict(size, default_to_square=False)
|
| 262 |
+
|
| 263 |
+
images = make_list_of_images(images)
|
| 264 |
+
|
| 265 |
+
if not valid_images(images):
|
| 266 |
+
raise ValueError(
|
| 267 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 268 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
validate_preprocess_arguments(
|
| 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 |
+
do_resize=do_resize,
|
| 278 |
+
size=size,
|
| 279 |
+
resample=resample,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
# All transformations expect numpy arrays.
|
| 283 |
+
images = [to_numpy_array(image) for image in images]
|
| 284 |
+
|
| 285 |
+
if do_rescale and is_scaled_image(images[0]):
|
| 286 |
+
logger.warning_once(
|
| 287 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 288 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
if input_data_format is None:
|
| 292 |
+
# We assume that all images have the same channel dimension format.
|
| 293 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 294 |
+
|
| 295 |
+
if do_resize:
|
| 296 |
+
images = [
|
| 297 |
+
self.resize(
|
| 298 |
+
image=image, size=size, crop_pct=crop_pct, resample=resample, input_data_format=input_data_format
|
| 299 |
+
)
|
| 300 |
+
for image in images
|
| 301 |
+
]
|
| 302 |
+
|
| 303 |
+
if do_rescale:
|
| 304 |
+
images = [
|
| 305 |
+
self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 306 |
+
for image in images
|
| 307 |
+
]
|
| 308 |
+
|
| 309 |
+
if do_normalize:
|
| 310 |
+
images = [
|
| 311 |
+
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 312 |
+
for image in images
|
| 313 |
+
]
|
| 314 |
+
|
| 315 |
+
images = [
|
| 316 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
|
| 317 |
+
]
|
| 318 |
+
|
| 319 |
+
data = {"pixel_values": images}
|
| 320 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
__all__ = ["ConvNextImageProcessor"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/image_processing_convnext_fast.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Fast Image processor class for ConvNeXT."""
|
| 16 |
+
|
| 17 |
+
from typing import Dict, List, Optional, Union
|
| 18 |
+
|
| 19 |
+
from ...image_processing_utils import BatchFeature
|
| 20 |
+
from ...image_processing_utils_fast import (
|
| 21 |
+
BASE_IMAGE_PROCESSOR_FAST_DOCSTRING,
|
| 22 |
+
BASE_IMAGE_PROCESSOR_FAST_DOCSTRING_PREPROCESS,
|
| 23 |
+
BaseImageProcessorFast,
|
| 24 |
+
DefaultFastImageProcessorKwargs,
|
| 25 |
+
group_images_by_shape,
|
| 26 |
+
reorder_images,
|
| 27 |
+
)
|
| 28 |
+
from ...image_transforms import get_resize_output_image_size
|
| 29 |
+
from ...image_utils import (
|
| 30 |
+
IMAGENET_STANDARD_MEAN,
|
| 31 |
+
IMAGENET_STANDARD_STD,
|
| 32 |
+
ChannelDimension,
|
| 33 |
+
ImageInput,
|
| 34 |
+
PILImageResampling,
|
| 35 |
+
)
|
| 36 |
+
from ...processing_utils import Unpack
|
| 37 |
+
from ...utils import (
|
| 38 |
+
TensorType,
|
| 39 |
+
add_start_docstrings,
|
| 40 |
+
is_torch_available,
|
| 41 |
+
is_torchvision_available,
|
| 42 |
+
is_torchvision_v2_available,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if is_torch_available():
|
| 47 |
+
import torch
|
| 48 |
+
|
| 49 |
+
if is_torchvision_available():
|
| 50 |
+
if is_torchvision_v2_available():
|
| 51 |
+
from torchvision.transforms.v2 import functional as F
|
| 52 |
+
else:
|
| 53 |
+
from torchvision.transforms import functional as F
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class ConvNextFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
|
| 57 |
+
crop_pct: Optional[float]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@add_start_docstrings(
|
| 61 |
+
r"Constructs a fast ConvNeXT image processor.",
|
| 62 |
+
BASE_IMAGE_PROCESSOR_FAST_DOCSTRING,
|
| 63 |
+
"""
|
| 64 |
+
crop_pct (`float`, *optional*):
|
| 65 |
+
Percentage of the image to crop. Only has an effect if size < 384. Can be
|
| 66 |
+
overridden by `crop_pct` in the`preprocess` method.
|
| 67 |
+
""",
|
| 68 |
+
)
|
| 69 |
+
class ConvNextImageProcessorFast(BaseImageProcessorFast):
|
| 70 |
+
resample = PILImageResampling.BILINEAR
|
| 71 |
+
image_mean = IMAGENET_STANDARD_MEAN
|
| 72 |
+
image_std = IMAGENET_STANDARD_STD
|
| 73 |
+
size = {"shortest_edge": 384}
|
| 74 |
+
default_to_square = False
|
| 75 |
+
do_resize = True
|
| 76 |
+
do_rescale = True
|
| 77 |
+
do_normalize = True
|
| 78 |
+
crop_pct = 224 / 256
|
| 79 |
+
valid_kwargs = ConvNextFastImageProcessorKwargs
|
| 80 |
+
|
| 81 |
+
def __init__(self, **kwargs: Unpack[ConvNextFastImageProcessorKwargs]):
|
| 82 |
+
super().__init__(**kwargs)
|
| 83 |
+
|
| 84 |
+
@add_start_docstrings(
|
| 85 |
+
BASE_IMAGE_PROCESSOR_FAST_DOCSTRING_PREPROCESS,
|
| 86 |
+
"""
|
| 87 |
+
crop_pct (`float`, *optional*):
|
| 88 |
+
Percentage of the image to crop. Only has an effect if size < 384. Can be
|
| 89 |
+
overridden by `crop_pct` in the`preprocess` method.
|
| 90 |
+
""",
|
| 91 |
+
)
|
| 92 |
+
def preprocess(self, images: ImageInput, **kwargs: Unpack[ConvNextFastImageProcessorKwargs]) -> BatchFeature:
|
| 93 |
+
return super().preprocess(images, **kwargs)
|
| 94 |
+
|
| 95 |
+
def resize(
|
| 96 |
+
self,
|
| 97 |
+
image: "torch.Tensor",
|
| 98 |
+
size: Dict[str, int],
|
| 99 |
+
crop_pct: float,
|
| 100 |
+
interpolation: PILImageResampling = PILImageResampling.BICUBIC,
|
| 101 |
+
**kwargs,
|
| 102 |
+
) -> "torch.Tensor":
|
| 103 |
+
"""
|
| 104 |
+
Resize an image.
|
| 105 |
+
|
| 106 |
+
Args:
|
| 107 |
+
image (`torch.Tensor`):
|
| 108 |
+
Image to resize.
|
| 109 |
+
size (`Dict[str, int]`):
|
| 110 |
+
Dictionary of the form `{"shortest_edge": int}`, specifying the size of the output image. If
|
| 111 |
+
`size["shortest_edge"]` >= 384 image is resized to `(size["shortest_edge"], size["shortest_edge"])`.
|
| 112 |
+
Otherwise, the smaller edge of the image will be matched to `int(size["shortest_edge"] / crop_pct)`,
|
| 113 |
+
after which the image is cropped to `(size["shortest_edge"], size["shortest_edge"])`.
|
| 114 |
+
crop_pct (`float`):
|
| 115 |
+
Percentage of the image to crop. Only has an effect if size < 384.
|
| 116 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 117 |
+
Resampling filter to use when resizing the image.
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
`torch.Tensor`: Resized image.
|
| 121 |
+
"""
|
| 122 |
+
if not size.shortest_edge:
|
| 123 |
+
raise ValueError(f"Size dictionary must contain 'shortest_edge' key. Got {size.keys()}")
|
| 124 |
+
shortest_edge = size["shortest_edge"]
|
| 125 |
+
|
| 126 |
+
if shortest_edge < 384:
|
| 127 |
+
# maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
|
| 128 |
+
resize_shortest_edge = int(shortest_edge / crop_pct)
|
| 129 |
+
resize_size = get_resize_output_image_size(
|
| 130 |
+
image, size=resize_shortest_edge, default_to_square=False, input_data_format=ChannelDimension.FIRST
|
| 131 |
+
)
|
| 132 |
+
image = F.resize(
|
| 133 |
+
image,
|
| 134 |
+
resize_size,
|
| 135 |
+
interpolation=interpolation,
|
| 136 |
+
**kwargs,
|
| 137 |
+
)
|
| 138 |
+
# then crop to (shortest_edge, shortest_edge)
|
| 139 |
+
return F.center_crop(
|
| 140 |
+
image,
|
| 141 |
+
(shortest_edge, shortest_edge),
|
| 142 |
+
**kwargs,
|
| 143 |
+
)
|
| 144 |
+
else:
|
| 145 |
+
# warping (no cropping) when evaluated at 384 or larger
|
| 146 |
+
return F.resize(
|
| 147 |
+
image,
|
| 148 |
+
(shortest_edge, shortest_edge),
|
| 149 |
+
interpolation=interpolation,
|
| 150 |
+
**kwargs,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
def _preprocess(
|
| 154 |
+
self,
|
| 155 |
+
images: List["torch.Tensor"],
|
| 156 |
+
do_resize: bool,
|
| 157 |
+
size: Dict[str, int],
|
| 158 |
+
crop_pct: float,
|
| 159 |
+
interpolation: Optional["F.InterpolationMode"],
|
| 160 |
+
do_center_crop: bool,
|
| 161 |
+
crop_size: int,
|
| 162 |
+
do_rescale: bool,
|
| 163 |
+
rescale_factor: float,
|
| 164 |
+
do_normalize: bool,
|
| 165 |
+
image_mean: Optional[Union[float, List[float]]],
|
| 166 |
+
image_std: Optional[Union[float, List[float]]],
|
| 167 |
+
return_tensors: Optional[Union[str, TensorType]],
|
| 168 |
+
) -> BatchFeature:
|
| 169 |
+
# Group images by size for batched resizing
|
| 170 |
+
grouped_images, grouped_images_index = group_images_by_shape(images)
|
| 171 |
+
resized_images_grouped = {}
|
| 172 |
+
for shape, stacked_images in grouped_images.items():
|
| 173 |
+
if do_resize:
|
| 174 |
+
stacked_images = self.resize(
|
| 175 |
+
image=stacked_images, size=size, crop_pct=crop_pct, interpolation=interpolation
|
| 176 |
+
)
|
| 177 |
+
resized_images_grouped[shape] = stacked_images
|
| 178 |
+
resized_images = reorder_images(resized_images_grouped, grouped_images_index)
|
| 179 |
+
|
| 180 |
+
# Group images by size for further processing
|
| 181 |
+
# Needed in case do_resize is False, or resize returns images with different sizes
|
| 182 |
+
grouped_images, grouped_images_index = group_images_by_shape(resized_images)
|
| 183 |
+
processed_images_grouped = {}
|
| 184 |
+
for shape, stacked_images in grouped_images.items():
|
| 185 |
+
if do_center_crop:
|
| 186 |
+
stacked_images = self.center_crop(stacked_images, crop_size)
|
| 187 |
+
# Fused rescale and normalize
|
| 188 |
+
stacked_images = self.rescale_and_normalize(
|
| 189 |
+
stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
|
| 190 |
+
)
|
| 191 |
+
processed_images_grouped[shape] = stacked_images
|
| 192 |
+
|
| 193 |
+
processed_images = reorder_images(processed_images_grouped, grouped_images_index)
|
| 194 |
+
processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images
|
| 195 |
+
|
| 196 |
+
return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
|
| 197 |
+
|
| 198 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 Meta Platforms, 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 |
+
"""PyTorch ConvNext model."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.utils.checkpoint
|
| 21 |
+
from torch import nn
|
| 22 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 23 |
+
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...modeling_outputs import (
|
| 26 |
+
BackboneOutput,
|
| 27 |
+
BaseModelOutputWithNoAttention,
|
| 28 |
+
BaseModelOutputWithPoolingAndNoAttention,
|
| 29 |
+
ImageClassifierOutputWithNoAttention,
|
| 30 |
+
)
|
| 31 |
+
from ...modeling_utils import PreTrainedModel
|
| 32 |
+
from ...utils import (
|
| 33 |
+
add_code_sample_docstrings,
|
| 34 |
+
add_start_docstrings,
|
| 35 |
+
add_start_docstrings_to_model_forward,
|
| 36 |
+
logging,
|
| 37 |
+
replace_return_docstrings,
|
| 38 |
+
)
|
| 39 |
+
from ...utils.backbone_utils import BackboneMixin
|
| 40 |
+
from .configuration_convnext import ConvNextConfig
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
logger = logging.get_logger(__name__)
|
| 44 |
+
|
| 45 |
+
# General docstring
|
| 46 |
+
_CONFIG_FOR_DOC = "ConvNextConfig"
|
| 47 |
+
|
| 48 |
+
# Base docstring
|
| 49 |
+
_CHECKPOINT_FOR_DOC = "facebook/convnext-tiny-224"
|
| 50 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 768, 7, 7]
|
| 51 |
+
|
| 52 |
+
# Image classification docstring
|
| 53 |
+
_IMAGE_CLASS_CHECKPOINT = "facebook/convnext-tiny-224"
|
| 54 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# Copied from transformers.models.beit.modeling_beit.drop_path
|
| 58 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 59 |
+
"""
|
| 60 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 61 |
+
|
| 62 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 63 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 64 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 65 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 66 |
+
argument.
|
| 67 |
+
"""
|
| 68 |
+
if drop_prob == 0.0 or not training:
|
| 69 |
+
return input
|
| 70 |
+
keep_prob = 1 - drop_prob
|
| 71 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 72 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 73 |
+
random_tensor.floor_() # binarize
|
| 74 |
+
output = input.div(keep_prob) * random_tensor
|
| 75 |
+
return output
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->ConvNext
|
| 79 |
+
class ConvNextDropPath(nn.Module):
|
| 80 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 81 |
+
|
| 82 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.drop_prob = drop_prob
|
| 85 |
+
|
| 86 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 87 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 88 |
+
|
| 89 |
+
def extra_repr(self) -> str:
|
| 90 |
+
return "p={}".format(self.drop_prob)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class ConvNextLayerNorm(nn.Module):
|
| 94 |
+
r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
|
| 95 |
+
The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
|
| 96 |
+
width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
|
| 100 |
+
super().__init__()
|
| 101 |
+
self.weight = nn.Parameter(torch.ones(normalized_shape))
|
| 102 |
+
self.bias = nn.Parameter(torch.zeros(normalized_shape))
|
| 103 |
+
self.eps = eps
|
| 104 |
+
self.data_format = data_format
|
| 105 |
+
if self.data_format not in ["channels_last", "channels_first"]:
|
| 106 |
+
raise NotImplementedError(f"Unsupported data format: {self.data_format}")
|
| 107 |
+
self.normalized_shape = (normalized_shape,)
|
| 108 |
+
|
| 109 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 110 |
+
if self.data_format == "channels_last":
|
| 111 |
+
x = torch.nn.functional.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
|
| 112 |
+
elif self.data_format == "channels_first":
|
| 113 |
+
input_dtype = x.dtype
|
| 114 |
+
x = x.float()
|
| 115 |
+
u = x.mean(1, keepdim=True)
|
| 116 |
+
s = (x - u).pow(2).mean(1, keepdim=True)
|
| 117 |
+
x = (x - u) / torch.sqrt(s + self.eps)
|
| 118 |
+
x = x.to(dtype=input_dtype)
|
| 119 |
+
x = self.weight[:, None, None] * x + self.bias[:, None, None]
|
| 120 |
+
return x
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class ConvNextEmbeddings(nn.Module):
|
| 124 |
+
"""This class is comparable to (and inspired by) the SwinEmbeddings class
|
| 125 |
+
found in src/transformers/models/swin/modeling_swin.py.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
def __init__(self, config):
|
| 129 |
+
super().__init__()
|
| 130 |
+
self.patch_embeddings = nn.Conv2d(
|
| 131 |
+
config.num_channels, config.hidden_sizes[0], kernel_size=config.patch_size, stride=config.patch_size
|
| 132 |
+
)
|
| 133 |
+
self.layernorm = ConvNextLayerNorm(config.hidden_sizes[0], eps=1e-6, data_format="channels_first")
|
| 134 |
+
self.num_channels = config.num_channels
|
| 135 |
+
|
| 136 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 137 |
+
num_channels = pixel_values.shape[1]
|
| 138 |
+
if num_channels != self.num_channels:
|
| 139 |
+
raise ValueError(
|
| 140 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 141 |
+
)
|
| 142 |
+
embeddings = self.patch_embeddings(pixel_values)
|
| 143 |
+
embeddings = self.layernorm(embeddings)
|
| 144 |
+
return embeddings
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class ConvNextLayer(nn.Module):
|
| 148 |
+
"""This corresponds to the `Block` class in the original implementation.
|
| 149 |
+
|
| 150 |
+
There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,
|
| 151 |
+
H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back
|
| 152 |
+
|
| 153 |
+
The authors used (2) as they find it slightly faster in PyTorch.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
config ([`ConvNextConfig`]): Model configuration class.
|
| 157 |
+
dim (`int`): Number of input channels.
|
| 158 |
+
drop_path (`float`): Stochastic depth rate. Default: 0.0.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
def __init__(self, config, dim, drop_path=0):
|
| 162 |
+
super().__init__()
|
| 163 |
+
self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
|
| 164 |
+
self.layernorm = ConvNextLayerNorm(dim, eps=1e-6)
|
| 165 |
+
self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers
|
| 166 |
+
self.act = ACT2FN[config.hidden_act]
|
| 167 |
+
self.pwconv2 = nn.Linear(4 * dim, dim)
|
| 168 |
+
self.layer_scale_parameter = (
|
| 169 |
+
nn.Parameter(config.layer_scale_init_value * torch.ones((dim)), requires_grad=True)
|
| 170 |
+
if config.layer_scale_init_value > 0
|
| 171 |
+
else None
|
| 172 |
+
)
|
| 173 |
+
self.drop_path = ConvNextDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 174 |
+
|
| 175 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
|
| 176 |
+
input = hidden_states
|
| 177 |
+
x = self.dwconv(hidden_states)
|
| 178 |
+
x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
|
| 179 |
+
x = self.layernorm(x)
|
| 180 |
+
x = self.pwconv1(x)
|
| 181 |
+
x = self.act(x)
|
| 182 |
+
x = self.pwconv2(x)
|
| 183 |
+
if self.layer_scale_parameter is not None:
|
| 184 |
+
x = self.layer_scale_parameter * x
|
| 185 |
+
x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
|
| 186 |
+
|
| 187 |
+
x = input + self.drop_path(x)
|
| 188 |
+
return x
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class ConvNextStage(nn.Module):
|
| 192 |
+
"""ConvNeXT stage, consisting of an optional downsampling layer + multiple residual blocks.
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
config ([`ConvNextConfig`]): Model configuration class.
|
| 196 |
+
in_channels (`int`): Number of input channels.
|
| 197 |
+
out_channels (`int`): Number of output channels.
|
| 198 |
+
depth (`int`): Number of residual blocks.
|
| 199 |
+
drop_path_rates(`List[float]`): Stochastic depth rates for each layer.
|
| 200 |
+
"""
|
| 201 |
+
|
| 202 |
+
def __init__(self, config, in_channels, out_channels, kernel_size=2, stride=2, depth=2, drop_path_rates=None):
|
| 203 |
+
super().__init__()
|
| 204 |
+
|
| 205 |
+
if in_channels != out_channels or stride > 1:
|
| 206 |
+
self.downsampling_layer = nn.Sequential(
|
| 207 |
+
ConvNextLayerNorm(in_channels, eps=1e-6, data_format="channels_first"),
|
| 208 |
+
nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride),
|
| 209 |
+
)
|
| 210 |
+
else:
|
| 211 |
+
self.downsampling_layer = nn.Identity()
|
| 212 |
+
drop_path_rates = drop_path_rates or [0.0] * depth
|
| 213 |
+
self.layers = nn.Sequential(
|
| 214 |
+
*[ConvNextLayer(config, dim=out_channels, drop_path=drop_path_rates[j]) for j in range(depth)]
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
|
| 218 |
+
hidden_states = self.downsampling_layer(hidden_states)
|
| 219 |
+
hidden_states = self.layers(hidden_states)
|
| 220 |
+
return hidden_states
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class ConvNextEncoder(nn.Module):
|
| 224 |
+
def __init__(self, config):
|
| 225 |
+
super().__init__()
|
| 226 |
+
self.stages = nn.ModuleList()
|
| 227 |
+
drop_path_rates = [
|
| 228 |
+
x.tolist() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths)).split(config.depths)
|
| 229 |
+
]
|
| 230 |
+
prev_chs = config.hidden_sizes[0]
|
| 231 |
+
for i in range(config.num_stages):
|
| 232 |
+
out_chs = config.hidden_sizes[i]
|
| 233 |
+
stage = ConvNextStage(
|
| 234 |
+
config,
|
| 235 |
+
in_channels=prev_chs,
|
| 236 |
+
out_channels=out_chs,
|
| 237 |
+
stride=2 if i > 0 else 1,
|
| 238 |
+
depth=config.depths[i],
|
| 239 |
+
drop_path_rates=drop_path_rates[i],
|
| 240 |
+
)
|
| 241 |
+
self.stages.append(stage)
|
| 242 |
+
prev_chs = out_chs
|
| 243 |
+
|
| 244 |
+
def forward(
|
| 245 |
+
self,
|
| 246 |
+
hidden_states: torch.FloatTensor,
|
| 247 |
+
output_hidden_states: Optional[bool] = False,
|
| 248 |
+
return_dict: Optional[bool] = True,
|
| 249 |
+
) -> Union[Tuple, BaseModelOutputWithNoAttention]:
|
| 250 |
+
all_hidden_states = () if output_hidden_states else None
|
| 251 |
+
|
| 252 |
+
for i, layer_module in enumerate(self.stages):
|
| 253 |
+
if output_hidden_states:
|
| 254 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 255 |
+
|
| 256 |
+
hidden_states = layer_module(hidden_states)
|
| 257 |
+
|
| 258 |
+
if output_hidden_states:
|
| 259 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 260 |
+
|
| 261 |
+
if not return_dict:
|
| 262 |
+
return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
|
| 263 |
+
|
| 264 |
+
return BaseModelOutputWithNoAttention(
|
| 265 |
+
last_hidden_state=hidden_states,
|
| 266 |
+
hidden_states=all_hidden_states,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class ConvNextPreTrainedModel(PreTrainedModel):
|
| 271 |
+
"""
|
| 272 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 273 |
+
models.
|
| 274 |
+
"""
|
| 275 |
+
|
| 276 |
+
config_class = ConvNextConfig
|
| 277 |
+
base_model_prefix = "convnext"
|
| 278 |
+
main_input_name = "pixel_values"
|
| 279 |
+
_no_split_modules = ["ConvNextLayer"]
|
| 280 |
+
|
| 281 |
+
def _init_weights(self, module):
|
| 282 |
+
"""Initialize the weights"""
|
| 283 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 284 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 285 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 286 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 287 |
+
if module.bias is not None:
|
| 288 |
+
module.bias.data.zero_()
|
| 289 |
+
elif isinstance(module, nn.LayerNorm):
|
| 290 |
+
module.bias.data.zero_()
|
| 291 |
+
module.weight.data.fill_(1.0)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
CONVNEXT_START_DOCSTRING = r"""
|
| 295 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 296 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 297 |
+
behavior.
|
| 298 |
+
|
| 299 |
+
Parameters:
|
| 300 |
+
config ([`ConvNextConfig`]): Model configuration class with all the parameters of the model.
|
| 301 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 302 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 303 |
+
"""
|
| 304 |
+
|
| 305 |
+
CONVNEXT_INPUTS_DOCSTRING = r"""
|
| 306 |
+
Args:
|
| 307 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 308 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 309 |
+
[`ConvNextImageProcessor.__call__`] for details.
|
| 310 |
+
|
| 311 |
+
output_hidden_states (`bool`, *optional*):
|
| 312 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 313 |
+
more detail.
|
| 314 |
+
return_dict (`bool`, *optional*):
|
| 315 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@add_start_docstrings(
|
| 320 |
+
"The bare ConvNext model outputting raw features without any specific head on top.",
|
| 321 |
+
CONVNEXT_START_DOCSTRING,
|
| 322 |
+
)
|
| 323 |
+
class ConvNextModel(ConvNextPreTrainedModel):
|
| 324 |
+
def __init__(self, config):
|
| 325 |
+
super().__init__(config)
|
| 326 |
+
self.config = config
|
| 327 |
+
|
| 328 |
+
self.embeddings = ConvNextEmbeddings(config)
|
| 329 |
+
self.encoder = ConvNextEncoder(config)
|
| 330 |
+
|
| 331 |
+
# final layernorm layer
|
| 332 |
+
self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
|
| 333 |
+
|
| 334 |
+
# Initialize weights and apply final processing
|
| 335 |
+
self.post_init()
|
| 336 |
+
|
| 337 |
+
@add_start_docstrings_to_model_forward(CONVNEXT_INPUTS_DOCSTRING)
|
| 338 |
+
@add_code_sample_docstrings(
|
| 339 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 340 |
+
output_type=BaseModelOutputWithPoolingAndNoAttention,
|
| 341 |
+
config_class=_CONFIG_FOR_DOC,
|
| 342 |
+
modality="vision",
|
| 343 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 344 |
+
)
|
| 345 |
+
def forward(
|
| 346 |
+
self,
|
| 347 |
+
pixel_values: torch.FloatTensor = None,
|
| 348 |
+
output_hidden_states: Optional[bool] = None,
|
| 349 |
+
return_dict: Optional[bool] = None,
|
| 350 |
+
) -> Union[Tuple, BaseModelOutputWithPoolingAndNoAttention]:
|
| 351 |
+
output_hidden_states = (
|
| 352 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 353 |
+
)
|
| 354 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 355 |
+
|
| 356 |
+
if pixel_values is None:
|
| 357 |
+
raise ValueError("You have to specify pixel_values")
|
| 358 |
+
|
| 359 |
+
embedding_output = self.embeddings(pixel_values)
|
| 360 |
+
|
| 361 |
+
encoder_outputs = self.encoder(
|
| 362 |
+
embedding_output,
|
| 363 |
+
output_hidden_states=output_hidden_states,
|
| 364 |
+
return_dict=return_dict,
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
last_hidden_state = encoder_outputs[0]
|
| 368 |
+
|
| 369 |
+
# global average pooling, (N, C, H, W) -> (N, C)
|
| 370 |
+
pooled_output = self.layernorm(last_hidden_state.mean([-2, -1]))
|
| 371 |
+
|
| 372 |
+
if not return_dict:
|
| 373 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 374 |
+
|
| 375 |
+
return BaseModelOutputWithPoolingAndNoAttention(
|
| 376 |
+
last_hidden_state=last_hidden_state,
|
| 377 |
+
pooler_output=pooled_output,
|
| 378 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
@add_start_docstrings(
|
| 383 |
+
"""
|
| 384 |
+
ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
|
| 385 |
+
ImageNet.
|
| 386 |
+
""",
|
| 387 |
+
CONVNEXT_START_DOCSTRING,
|
| 388 |
+
)
|
| 389 |
+
class ConvNextForImageClassification(ConvNextPreTrainedModel):
|
| 390 |
+
def __init__(self, config):
|
| 391 |
+
super().__init__(config)
|
| 392 |
+
|
| 393 |
+
self.num_labels = config.num_labels
|
| 394 |
+
self.convnext = ConvNextModel(config)
|
| 395 |
+
|
| 396 |
+
# Classifier head
|
| 397 |
+
self.classifier = (
|
| 398 |
+
nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
# Initialize weights and apply final processing
|
| 402 |
+
self.post_init()
|
| 403 |
+
|
| 404 |
+
@add_start_docstrings_to_model_forward(CONVNEXT_INPUTS_DOCSTRING)
|
| 405 |
+
@add_code_sample_docstrings(
|
| 406 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
| 407 |
+
output_type=ImageClassifierOutputWithNoAttention,
|
| 408 |
+
config_class=_CONFIG_FOR_DOC,
|
| 409 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
| 410 |
+
)
|
| 411 |
+
def forward(
|
| 412 |
+
self,
|
| 413 |
+
pixel_values: torch.FloatTensor = None,
|
| 414 |
+
labels: Optional[torch.LongTensor] = None,
|
| 415 |
+
output_hidden_states: Optional[bool] = None,
|
| 416 |
+
return_dict: Optional[bool] = None,
|
| 417 |
+
) -> Union[Tuple, ImageClassifierOutputWithNoAttention]:
|
| 418 |
+
r"""
|
| 419 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 420 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 421 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 422 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 423 |
+
"""
|
| 424 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 425 |
+
|
| 426 |
+
outputs = self.convnext(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 427 |
+
|
| 428 |
+
pooled_output = outputs.pooler_output if return_dict else outputs[1]
|
| 429 |
+
|
| 430 |
+
logits = self.classifier(pooled_output)
|
| 431 |
+
|
| 432 |
+
loss = None
|
| 433 |
+
if labels is not None:
|
| 434 |
+
if self.config.problem_type is None:
|
| 435 |
+
if self.num_labels == 1:
|
| 436 |
+
self.config.problem_type = "regression"
|
| 437 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 438 |
+
self.config.problem_type = "single_label_classification"
|
| 439 |
+
else:
|
| 440 |
+
self.config.problem_type = "multi_label_classification"
|
| 441 |
+
|
| 442 |
+
if self.config.problem_type == "regression":
|
| 443 |
+
loss_fct = MSELoss()
|
| 444 |
+
if self.num_labels == 1:
|
| 445 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 446 |
+
else:
|
| 447 |
+
loss = loss_fct(logits, labels)
|
| 448 |
+
elif self.config.problem_type == "single_label_classification":
|
| 449 |
+
loss_fct = CrossEntropyLoss()
|
| 450 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 451 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 452 |
+
loss_fct = BCEWithLogitsLoss()
|
| 453 |
+
loss = loss_fct(logits, labels)
|
| 454 |
+
if not return_dict:
|
| 455 |
+
output = (logits,) + outputs[2:]
|
| 456 |
+
return ((loss,) + output) if loss is not None else output
|
| 457 |
+
|
| 458 |
+
return ImageClassifierOutputWithNoAttention(
|
| 459 |
+
loss=loss,
|
| 460 |
+
logits=logits,
|
| 461 |
+
hidden_states=outputs.hidden_states,
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
@add_start_docstrings(
|
| 466 |
+
"""
|
| 467 |
+
ConvNeXt backbone, to be used with frameworks like DETR and MaskFormer.
|
| 468 |
+
""",
|
| 469 |
+
CONVNEXT_START_DOCSTRING,
|
| 470 |
+
)
|
| 471 |
+
class ConvNextBackbone(ConvNextPreTrainedModel, BackboneMixin):
|
| 472 |
+
def __init__(self, config):
|
| 473 |
+
super().__init__(config)
|
| 474 |
+
super()._init_backbone(config)
|
| 475 |
+
|
| 476 |
+
self.embeddings = ConvNextEmbeddings(config)
|
| 477 |
+
self.encoder = ConvNextEncoder(config)
|
| 478 |
+
self.num_features = [config.hidden_sizes[0]] + config.hidden_sizes
|
| 479 |
+
|
| 480 |
+
# Add layer norms to hidden states of out_features
|
| 481 |
+
hidden_states_norms = {}
|
| 482 |
+
for stage, num_channels in zip(self._out_features, self.channels):
|
| 483 |
+
hidden_states_norms[stage] = ConvNextLayerNorm(num_channels, data_format="channels_first")
|
| 484 |
+
self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
|
| 485 |
+
|
| 486 |
+
# initialize weights and apply final processing
|
| 487 |
+
self.post_init()
|
| 488 |
+
|
| 489 |
+
@add_start_docstrings_to_model_forward(CONVNEXT_INPUTS_DOCSTRING)
|
| 490 |
+
@replace_return_docstrings(output_type=BackboneOutput, config_class=_CONFIG_FOR_DOC)
|
| 491 |
+
def forward(
|
| 492 |
+
self,
|
| 493 |
+
pixel_values: torch.Tensor,
|
| 494 |
+
output_hidden_states: Optional[bool] = None,
|
| 495 |
+
return_dict: Optional[bool] = None,
|
| 496 |
+
) -> BackboneOutput:
|
| 497 |
+
"""
|
| 498 |
+
Returns:
|
| 499 |
+
|
| 500 |
+
Examples:
|
| 501 |
+
|
| 502 |
+
```python
|
| 503 |
+
>>> from transformers import AutoImageProcessor, AutoBackbone
|
| 504 |
+
>>> import torch
|
| 505 |
+
>>> from PIL import Image
|
| 506 |
+
>>> import requests
|
| 507 |
+
|
| 508 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 509 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 510 |
+
|
| 511 |
+
>>> processor = AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224")
|
| 512 |
+
>>> model = AutoBackbone.from_pretrained("facebook/convnext-tiny-224")
|
| 513 |
+
|
| 514 |
+
>>> inputs = processor(image, return_tensors="pt")
|
| 515 |
+
>>> outputs = model(**inputs)
|
| 516 |
+
```"""
|
| 517 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 518 |
+
output_hidden_states = (
|
| 519 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
embedding_output = self.embeddings(pixel_values)
|
| 523 |
+
|
| 524 |
+
outputs = self.encoder(
|
| 525 |
+
embedding_output,
|
| 526 |
+
output_hidden_states=True,
|
| 527 |
+
return_dict=return_dict,
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
hidden_states = outputs.hidden_states if return_dict else outputs[1]
|
| 531 |
+
|
| 532 |
+
feature_maps = ()
|
| 533 |
+
for stage, hidden_state in zip(self.stage_names, hidden_states):
|
| 534 |
+
if stage in self.out_features:
|
| 535 |
+
hidden_state = self.hidden_states_norms[stage](hidden_state)
|
| 536 |
+
feature_maps += (hidden_state,)
|
| 537 |
+
|
| 538 |
+
if not return_dict:
|
| 539 |
+
output = (feature_maps,)
|
| 540 |
+
if output_hidden_states:
|
| 541 |
+
output += (hidden_states,)
|
| 542 |
+
return output
|
| 543 |
+
|
| 544 |
+
return BackboneOutput(
|
| 545 |
+
feature_maps=feature_maps,
|
| 546 |
+
hidden_states=hidden_states if output_hidden_states else None,
|
| 547 |
+
attentions=None,
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
__all__ = ["ConvNextForImageClassification", "ConvNextModel", "ConvNextPreTrainedModel", "ConvNextBackbone"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnext/modeling_tf_convnext.py
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 Meta Platforms 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 |
+
"""TF 2.0 ConvNext model."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from typing import List, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import tensorflow as tf
|
| 23 |
+
|
| 24 |
+
from ...activations_tf import get_tf_activation
|
| 25 |
+
from ...modeling_tf_outputs import TFBaseModelOutput, TFBaseModelOutputWithPooling, TFSequenceClassifierOutput
|
| 26 |
+
from ...modeling_tf_utils import (
|
| 27 |
+
TFModelInputType,
|
| 28 |
+
TFPreTrainedModel,
|
| 29 |
+
TFSequenceClassificationLoss,
|
| 30 |
+
get_initializer,
|
| 31 |
+
keras,
|
| 32 |
+
keras_serializable,
|
| 33 |
+
unpack_inputs,
|
| 34 |
+
)
|
| 35 |
+
from ...tf_utils import shape_list
|
| 36 |
+
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
|
| 37 |
+
from .configuration_convnext import ConvNextConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
_CONFIG_FOR_DOC = "ConvNextConfig"
|
| 44 |
+
_CHECKPOINT_FOR_DOC = "facebook/convnext-tiny-224"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class TFConvNextDropPath(keras.layers.Layer):
|
| 48 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 49 |
+
References:
|
| 50 |
+
(1) github.com:rwightman/pytorch-image-models
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def __init__(self, drop_path: float, **kwargs):
|
| 54 |
+
super().__init__(**kwargs)
|
| 55 |
+
self.drop_path = drop_path
|
| 56 |
+
|
| 57 |
+
def call(self, x: tf.Tensor, training=None):
|
| 58 |
+
if training:
|
| 59 |
+
keep_prob = 1 - self.drop_path
|
| 60 |
+
shape = (tf.shape(x)[0],) + (1,) * (len(tf.shape(x)) - 1)
|
| 61 |
+
random_tensor = keep_prob + tf.random.uniform(shape, 0, 1)
|
| 62 |
+
random_tensor = tf.floor(random_tensor)
|
| 63 |
+
return (x / keep_prob) * random_tensor
|
| 64 |
+
return x
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class TFConvNextEmbeddings(keras.layers.Layer):
|
| 68 |
+
"""This class is comparable to (and inspired by) the SwinEmbeddings class
|
| 69 |
+
found in src/transformers/models/swin/modeling_swin.py.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(self, config: ConvNextConfig, **kwargs):
|
| 73 |
+
super().__init__(**kwargs)
|
| 74 |
+
self.patch_embeddings = keras.layers.Conv2D(
|
| 75 |
+
filters=config.hidden_sizes[0],
|
| 76 |
+
kernel_size=config.patch_size,
|
| 77 |
+
strides=config.patch_size,
|
| 78 |
+
name="patch_embeddings",
|
| 79 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 80 |
+
bias_initializer=keras.initializers.Zeros(),
|
| 81 |
+
)
|
| 82 |
+
self.layernorm = keras.layers.LayerNormalization(epsilon=1e-6, name="layernorm")
|
| 83 |
+
self.num_channels = config.num_channels
|
| 84 |
+
self.config = config
|
| 85 |
+
|
| 86 |
+
def call(self, pixel_values):
|
| 87 |
+
if isinstance(pixel_values, dict):
|
| 88 |
+
pixel_values = pixel_values["pixel_values"]
|
| 89 |
+
|
| 90 |
+
tf.debugging.assert_equal(
|
| 91 |
+
shape_list(pixel_values)[1],
|
| 92 |
+
self.num_channels,
|
| 93 |
+
message="Make sure that the channel dimension of the pixel values match with the one set in the configuration.",
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# When running on CPU, `keras.layers.Conv2D` doesn't support `NCHW` format.
|
| 97 |
+
# So change the input format from `NCHW` to `NHWC`.
|
| 98 |
+
# shape = (batch_size, in_height, in_width, in_channels)
|
| 99 |
+
pixel_values = tf.transpose(pixel_values, perm=(0, 2, 3, 1))
|
| 100 |
+
|
| 101 |
+
embeddings = self.patch_embeddings(pixel_values)
|
| 102 |
+
embeddings = self.layernorm(embeddings)
|
| 103 |
+
return embeddings
|
| 104 |
+
|
| 105 |
+
def build(self, input_shape=None):
|
| 106 |
+
if self.built:
|
| 107 |
+
return
|
| 108 |
+
self.built = True
|
| 109 |
+
if getattr(self, "patch_embeddings", None) is not None:
|
| 110 |
+
with tf.name_scope(self.patch_embeddings.name):
|
| 111 |
+
self.patch_embeddings.build([None, None, None, self.config.num_channels])
|
| 112 |
+
if getattr(self, "layernorm", None) is not None:
|
| 113 |
+
with tf.name_scope(self.layernorm.name):
|
| 114 |
+
self.layernorm.build([None, None, None, self.config.hidden_sizes[0]])
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class TFConvNextLayer(keras.layers.Layer):
|
| 118 |
+
"""This corresponds to the `Block` class in the original implementation.
|
| 119 |
+
|
| 120 |
+
There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,
|
| 121 |
+
H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back
|
| 122 |
+
|
| 123 |
+
The authors used (2) as they find it slightly faster in PyTorch. Since we already permuted the inputs to follow
|
| 124 |
+
NHWC ordering, we can just apply the operations straight-away without the permutation.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
config ([`ConvNextConfig`]): Model configuration class.
|
| 128 |
+
dim (`int`): Number of input channels.
|
| 129 |
+
drop_path (`float`): Stochastic depth rate. Default: 0.0.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
def __init__(self, config, dim, drop_path=0.0, **kwargs):
|
| 133 |
+
super().__init__(**kwargs)
|
| 134 |
+
self.dim = dim
|
| 135 |
+
self.config = config
|
| 136 |
+
self.dwconv = keras.layers.Conv2D(
|
| 137 |
+
filters=dim,
|
| 138 |
+
kernel_size=7,
|
| 139 |
+
padding="same",
|
| 140 |
+
groups=dim,
|
| 141 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 142 |
+
bias_initializer="zeros",
|
| 143 |
+
name="dwconv",
|
| 144 |
+
) # depthwise conv
|
| 145 |
+
self.layernorm = keras.layers.LayerNormalization(
|
| 146 |
+
epsilon=1e-6,
|
| 147 |
+
name="layernorm",
|
| 148 |
+
)
|
| 149 |
+
self.pwconv1 = keras.layers.Dense(
|
| 150 |
+
units=4 * dim,
|
| 151 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 152 |
+
bias_initializer="zeros",
|
| 153 |
+
name="pwconv1",
|
| 154 |
+
) # pointwise/1x1 convs, implemented with linear layers
|
| 155 |
+
self.act = get_tf_activation(config.hidden_act)
|
| 156 |
+
self.pwconv2 = keras.layers.Dense(
|
| 157 |
+
units=dim,
|
| 158 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 159 |
+
bias_initializer="zeros",
|
| 160 |
+
name="pwconv2",
|
| 161 |
+
)
|
| 162 |
+
# Using `layers.Activation` instead of `tf.identity` to better control `training`
|
| 163 |
+
# behaviour.
|
| 164 |
+
self.drop_path = (
|
| 165 |
+
TFConvNextDropPath(drop_path, name="drop_path")
|
| 166 |
+
if drop_path > 0.0
|
| 167 |
+
else keras.layers.Activation("linear", name="drop_path")
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def build(self, input_shape: tf.TensorShape = None):
|
| 171 |
+
# PT's `nn.Parameters` must be mapped to a TF layer weight to inherit the same name hierarchy (and vice-versa)
|
| 172 |
+
self.layer_scale_parameter = (
|
| 173 |
+
self.add_weight(
|
| 174 |
+
shape=(self.dim,),
|
| 175 |
+
initializer=keras.initializers.Constant(value=self.config.layer_scale_init_value),
|
| 176 |
+
trainable=True,
|
| 177 |
+
name="layer_scale_parameter",
|
| 178 |
+
)
|
| 179 |
+
if self.config.layer_scale_init_value > 0
|
| 180 |
+
else None
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
if self.built:
|
| 184 |
+
return
|
| 185 |
+
self.built = True
|
| 186 |
+
if getattr(self, "dwconv", None) is not None:
|
| 187 |
+
with tf.name_scope(self.dwconv.name):
|
| 188 |
+
self.dwconv.build([None, None, None, self.dim])
|
| 189 |
+
if getattr(self, "layernorm", None) is not None:
|
| 190 |
+
with tf.name_scope(self.layernorm.name):
|
| 191 |
+
self.layernorm.build([None, None, None, self.dim])
|
| 192 |
+
if getattr(self, "pwconv1", None) is not None:
|
| 193 |
+
with tf.name_scope(self.pwconv1.name):
|
| 194 |
+
self.pwconv1.build([None, None, self.dim])
|
| 195 |
+
if getattr(self, "pwconv2", None) is not None:
|
| 196 |
+
with tf.name_scope(self.pwconv2.name):
|
| 197 |
+
self.pwconv2.build([None, None, 4 * self.dim])
|
| 198 |
+
if getattr(self, "drop_path", None) is not None:
|
| 199 |
+
with tf.name_scope(self.drop_path.name):
|
| 200 |
+
self.drop_path.build(None)
|
| 201 |
+
|
| 202 |
+
def call(self, hidden_states, training=False):
|
| 203 |
+
input = hidden_states
|
| 204 |
+
x = self.dwconv(hidden_states)
|
| 205 |
+
x = self.layernorm(x)
|
| 206 |
+
x = self.pwconv1(x)
|
| 207 |
+
x = self.act(x)
|
| 208 |
+
x = self.pwconv2(x)
|
| 209 |
+
|
| 210 |
+
if self.layer_scale_parameter is not None:
|
| 211 |
+
x = self.layer_scale_parameter * x
|
| 212 |
+
|
| 213 |
+
x = input + self.drop_path(x, training=training)
|
| 214 |
+
return x
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class TFConvNextStage(keras.layers.Layer):
|
| 218 |
+
"""ConvNext stage, consisting of an optional downsampling layer + multiple residual blocks.
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
config (`ConvNextV2Config`):
|
| 222 |
+
Model configuration class.
|
| 223 |
+
in_channels (`int`):
|
| 224 |
+
Number of input channels.
|
| 225 |
+
out_channels (`int`):
|
| 226 |
+
Number of output channels.
|
| 227 |
+
depth (`int`):
|
| 228 |
+
Number of residual blocks.
|
| 229 |
+
drop_path_rates(`List[float]`):
|
| 230 |
+
Stochastic depth rates for each layer.
|
| 231 |
+
"""
|
| 232 |
+
|
| 233 |
+
def __init__(
|
| 234 |
+
self,
|
| 235 |
+
config: ConvNextConfig,
|
| 236 |
+
in_channels: int,
|
| 237 |
+
out_channels: int,
|
| 238 |
+
kernel_size: int = 2,
|
| 239 |
+
stride: int = 2,
|
| 240 |
+
depth: int = 2,
|
| 241 |
+
drop_path_rates: Optional[List[float]] = None,
|
| 242 |
+
**kwargs,
|
| 243 |
+
):
|
| 244 |
+
super().__init__(**kwargs)
|
| 245 |
+
if in_channels != out_channels or stride > 1:
|
| 246 |
+
self.downsampling_layer = [
|
| 247 |
+
keras.layers.LayerNormalization(
|
| 248 |
+
epsilon=1e-6,
|
| 249 |
+
name="downsampling_layer.0",
|
| 250 |
+
),
|
| 251 |
+
# Inputs to this layer will follow NHWC format since we
|
| 252 |
+
# transposed the inputs from NCHW to NHWC in the `TFConvNextEmbeddings`
|
| 253 |
+
# layer. All the outputs throughout the model will be in NHWC
|
| 254 |
+
# from this point on until the output where we again change to
|
| 255 |
+
# NCHW.
|
| 256 |
+
keras.layers.Conv2D(
|
| 257 |
+
filters=out_channels,
|
| 258 |
+
kernel_size=kernel_size,
|
| 259 |
+
strides=stride,
|
| 260 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 261 |
+
bias_initializer=keras.initializers.Zeros(),
|
| 262 |
+
name="downsampling_layer.1",
|
| 263 |
+
),
|
| 264 |
+
]
|
| 265 |
+
else:
|
| 266 |
+
self.downsampling_layer = [tf.identity]
|
| 267 |
+
|
| 268 |
+
drop_path_rates = drop_path_rates or [0.0] * depth
|
| 269 |
+
self.layers = [
|
| 270 |
+
TFConvNextLayer(
|
| 271 |
+
config,
|
| 272 |
+
dim=out_channels,
|
| 273 |
+
drop_path=drop_path_rates[j],
|
| 274 |
+
name=f"layers.{j}",
|
| 275 |
+
)
|
| 276 |
+
for j in range(depth)
|
| 277 |
+
]
|
| 278 |
+
self.in_channels = in_channels
|
| 279 |
+
self.out_channels = out_channels
|
| 280 |
+
self.stride = stride
|
| 281 |
+
|
| 282 |
+
def call(self, hidden_states):
|
| 283 |
+
for layer in self.downsampling_layer:
|
| 284 |
+
hidden_states = layer(hidden_states)
|
| 285 |
+
for layer in self.layers:
|
| 286 |
+
hidden_states = layer(hidden_states)
|
| 287 |
+
return hidden_states
|
| 288 |
+
|
| 289 |
+
def build(self, input_shape=None):
|
| 290 |
+
if self.built:
|
| 291 |
+
return
|
| 292 |
+
self.built = True
|
| 293 |
+
if getattr(self, "layers", None) is not None:
|
| 294 |
+
for layer in self.layers:
|
| 295 |
+
with tf.name_scope(layer.name):
|
| 296 |
+
layer.build(None)
|
| 297 |
+
if self.in_channels != self.out_channels or self.stride > 1:
|
| 298 |
+
with tf.name_scope(self.downsampling_layer[0].name):
|
| 299 |
+
self.downsampling_layer[0].build([None, None, None, self.in_channels])
|
| 300 |
+
with tf.name_scope(self.downsampling_layer[1].name):
|
| 301 |
+
self.downsampling_layer[1].build([None, None, None, self.in_channels])
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class TFConvNextEncoder(keras.layers.Layer):
|
| 305 |
+
def __init__(self, config, **kwargs):
|
| 306 |
+
super().__init__(**kwargs)
|
| 307 |
+
self.stages = []
|
| 308 |
+
drop_path_rates = tf.linspace(0.0, config.drop_path_rate, sum(config.depths))
|
| 309 |
+
drop_path_rates = tf.split(drop_path_rates, config.depths)
|
| 310 |
+
drop_path_rates = [x.numpy().tolist() for x in drop_path_rates]
|
| 311 |
+
prev_chs = config.hidden_sizes[0]
|
| 312 |
+
for i in range(config.num_stages):
|
| 313 |
+
out_chs = config.hidden_sizes[i]
|
| 314 |
+
stage = TFConvNextStage(
|
| 315 |
+
config,
|
| 316 |
+
in_channels=prev_chs,
|
| 317 |
+
out_channels=out_chs,
|
| 318 |
+
stride=2 if i > 0 else 1,
|
| 319 |
+
depth=config.depths[i],
|
| 320 |
+
drop_path_rates=drop_path_rates[i],
|
| 321 |
+
name=f"stages.{i}",
|
| 322 |
+
)
|
| 323 |
+
self.stages.append(stage)
|
| 324 |
+
prev_chs = out_chs
|
| 325 |
+
|
| 326 |
+
def call(self, hidden_states, output_hidden_states=False, return_dict=True):
|
| 327 |
+
all_hidden_states = () if output_hidden_states else None
|
| 328 |
+
|
| 329 |
+
for i, layer_module in enumerate(self.stages):
|
| 330 |
+
if output_hidden_states:
|
| 331 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 332 |
+
|
| 333 |
+
hidden_states = layer_module(hidden_states)
|
| 334 |
+
|
| 335 |
+
if output_hidden_states:
|
| 336 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 337 |
+
|
| 338 |
+
if not return_dict:
|
| 339 |
+
return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
|
| 340 |
+
|
| 341 |
+
return TFBaseModelOutput(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
|
| 342 |
+
|
| 343 |
+
def build(self, input_shape=None):
|
| 344 |
+
for stage in self.stages:
|
| 345 |
+
with tf.name_scope(stage.name):
|
| 346 |
+
stage.build(None)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
@keras_serializable
|
| 350 |
+
class TFConvNextMainLayer(keras.layers.Layer):
|
| 351 |
+
config_class = ConvNextConfig
|
| 352 |
+
|
| 353 |
+
def __init__(self, config: ConvNextConfig, add_pooling_layer: bool = True, **kwargs):
|
| 354 |
+
super().__init__(**kwargs)
|
| 355 |
+
|
| 356 |
+
self.config = config
|
| 357 |
+
self.embeddings = TFConvNextEmbeddings(config, name="embeddings")
|
| 358 |
+
self.encoder = TFConvNextEncoder(config, name="encoder")
|
| 359 |
+
self.layernorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm")
|
| 360 |
+
# We are setting the `data_format` like so because from here on we will revert to the
|
| 361 |
+
# NCHW output format
|
| 362 |
+
self.pooler = keras.layers.GlobalAvgPool2D(data_format="channels_first") if add_pooling_layer else None
|
| 363 |
+
|
| 364 |
+
@unpack_inputs
|
| 365 |
+
def call(
|
| 366 |
+
self,
|
| 367 |
+
pixel_values: TFModelInputType | None = None,
|
| 368 |
+
output_hidden_states: Optional[bool] = None,
|
| 369 |
+
return_dict: Optional[bool] = None,
|
| 370 |
+
training: bool = False,
|
| 371 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
| 372 |
+
output_hidden_states = (
|
| 373 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 374 |
+
)
|
| 375 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 376 |
+
|
| 377 |
+
if pixel_values is None:
|
| 378 |
+
raise ValueError("You have to specify pixel_values")
|
| 379 |
+
|
| 380 |
+
embedding_output = self.embeddings(pixel_values, training=training)
|
| 381 |
+
|
| 382 |
+
encoder_outputs = self.encoder(
|
| 383 |
+
embedding_output,
|
| 384 |
+
output_hidden_states=output_hidden_states,
|
| 385 |
+
return_dict=return_dict,
|
| 386 |
+
training=training,
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
last_hidden_state = encoder_outputs[0]
|
| 390 |
+
# Change to NCHW output format have uniformity in the modules
|
| 391 |
+
last_hidden_state = tf.transpose(last_hidden_state, perm=(0, 3, 1, 2))
|
| 392 |
+
pooled_output = self.layernorm(self.pooler(last_hidden_state))
|
| 393 |
+
|
| 394 |
+
# Change the other hidden state outputs to NCHW as well
|
| 395 |
+
if output_hidden_states:
|
| 396 |
+
hidden_states = tuple([tf.transpose(h, perm=(0, 3, 1, 2)) for h in encoder_outputs[1]])
|
| 397 |
+
|
| 398 |
+
if not return_dict:
|
| 399 |
+
hidden_states = hidden_states if output_hidden_states else ()
|
| 400 |
+
return (last_hidden_state, pooled_output) + hidden_states
|
| 401 |
+
|
| 402 |
+
return TFBaseModelOutputWithPooling(
|
| 403 |
+
last_hidden_state=last_hidden_state,
|
| 404 |
+
pooler_output=pooled_output,
|
| 405 |
+
hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states,
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
def build(self, input_shape=None):
|
| 409 |
+
if self.built:
|
| 410 |
+
return
|
| 411 |
+
self.built = True
|
| 412 |
+
if getattr(self, "embeddings", None) is not None:
|
| 413 |
+
with tf.name_scope(self.embeddings.name):
|
| 414 |
+
self.embeddings.build(None)
|
| 415 |
+
if getattr(self, "encoder", None) is not None:
|
| 416 |
+
with tf.name_scope(self.encoder.name):
|
| 417 |
+
self.encoder.build(None)
|
| 418 |
+
if getattr(self, "layernorm", None) is not None:
|
| 419 |
+
with tf.name_scope(self.layernorm.name):
|
| 420 |
+
self.layernorm.build([None, self.config.hidden_sizes[-1]])
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
class TFConvNextPreTrainedModel(TFPreTrainedModel):
|
| 424 |
+
"""
|
| 425 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 426 |
+
models.
|
| 427 |
+
"""
|
| 428 |
+
|
| 429 |
+
config_class = ConvNextConfig
|
| 430 |
+
base_model_prefix = "convnext"
|
| 431 |
+
main_input_name = "pixel_values"
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
CONVNEXT_START_DOCSTRING = r"""
|
| 435 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 436 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 437 |
+
etc.)
|
| 438 |
+
|
| 439 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 440 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 441 |
+
behavior.
|
| 442 |
+
|
| 443 |
+
<Tip>
|
| 444 |
+
|
| 445 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 446 |
+
|
| 447 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 448 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 449 |
+
|
| 450 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 451 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 452 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 453 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 454 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 455 |
+
positional argument:
|
| 456 |
+
|
| 457 |
+
- a single Tensor with `pixel_values` only and nothing else: `model(pixel_values)`
|
| 458 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 459 |
+
`model([pixel_values, attention_mask])` or `model([pixel_values, attention_mask, token_type_ids])`
|
| 460 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 461 |
+
`model({"pixel_values": pixel_values, "token_type_ids": token_type_ids})`
|
| 462 |
+
|
| 463 |
+
Note that when creating models and layers with
|
| 464 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 465 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 466 |
+
|
| 467 |
+
</Tip>
|
| 468 |
+
|
| 469 |
+
Parameters:
|
| 470 |
+
config ([`ConvNextConfig`]): Model configuration class with all the parameters of the model.
|
| 471 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 472 |
+
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 473 |
+
"""
|
| 474 |
+
|
| 475 |
+
CONVNEXT_INPUTS_DOCSTRING = r"""
|
| 476 |
+
Args:
|
| 477 |
+
pixel_values (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `(batch_size, num_channels, height, width)`):
|
| 478 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 479 |
+
[`ConvNextImageProcessor.__call__`] for details.
|
| 480 |
+
|
| 481 |
+
output_hidden_states (`bool`, *optional*):
|
| 482 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 483 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 484 |
+
used instead.
|
| 485 |
+
return_dict (`bool`, *optional*):
|
| 486 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 487 |
+
eager mode, in graph mode the value will always be set to True.
|
| 488 |
+
"""
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
@add_start_docstrings(
|
| 492 |
+
"The bare ConvNext model outputting raw features without any specific head on top.",
|
| 493 |
+
CONVNEXT_START_DOCSTRING,
|
| 494 |
+
)
|
| 495 |
+
class TFConvNextModel(TFConvNextPreTrainedModel):
|
| 496 |
+
def __init__(self, config, *inputs, add_pooling_layer=True, **kwargs):
|
| 497 |
+
super().__init__(config, *inputs, **kwargs)
|
| 498 |
+
self.convnext = TFConvNextMainLayer(config, add_pooling_layer=add_pooling_layer, name="convnext")
|
| 499 |
+
|
| 500 |
+
@unpack_inputs
|
| 501 |
+
@add_start_docstrings_to_model_forward(CONVNEXT_INPUTS_DOCSTRING)
|
| 502 |
+
@replace_return_docstrings(output_type=TFBaseModelOutputWithPooling, config_class=_CONFIG_FOR_DOC)
|
| 503 |
+
def call(
|
| 504 |
+
self,
|
| 505 |
+
pixel_values: TFModelInputType | None = None,
|
| 506 |
+
output_hidden_states: Optional[bool] = None,
|
| 507 |
+
return_dict: Optional[bool] = None,
|
| 508 |
+
training: bool = False,
|
| 509 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
| 510 |
+
r"""
|
| 511 |
+
Returns:
|
| 512 |
+
|
| 513 |
+
Examples:
|
| 514 |
+
|
| 515 |
+
```python
|
| 516 |
+
>>> from transformers import AutoImageProcessor, TFConvNextModel
|
| 517 |
+
>>> from PIL import Image
|
| 518 |
+
>>> import requests
|
| 519 |
+
|
| 520 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 521 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 522 |
+
|
| 523 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224")
|
| 524 |
+
>>> model = TFConvNextModel.from_pretrained("facebook/convnext-tiny-224")
|
| 525 |
+
|
| 526 |
+
>>> inputs = image_processor(images=image, return_tensors="tf")
|
| 527 |
+
>>> outputs = model(**inputs)
|
| 528 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 529 |
+
```"""
|
| 530 |
+
output_hidden_states = (
|
| 531 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 532 |
+
)
|
| 533 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 534 |
+
|
| 535 |
+
if pixel_values is None:
|
| 536 |
+
raise ValueError("You have to specify pixel_values")
|
| 537 |
+
|
| 538 |
+
outputs = self.convnext(
|
| 539 |
+
pixel_values=pixel_values,
|
| 540 |
+
output_hidden_states=output_hidden_states,
|
| 541 |
+
return_dict=return_dict,
|
| 542 |
+
training=training,
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
if not return_dict:
|
| 546 |
+
return (outputs[0],) + outputs[1:]
|
| 547 |
+
|
| 548 |
+
return TFBaseModelOutputWithPooling(
|
| 549 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 550 |
+
pooler_output=outputs.pooler_output,
|
| 551 |
+
hidden_states=outputs.hidden_states,
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
def build(self, input_shape=None):
|
| 555 |
+
if self.built:
|
| 556 |
+
return
|
| 557 |
+
self.built = True
|
| 558 |
+
if getattr(self, "convnext", None) is not None:
|
| 559 |
+
with tf.name_scope(self.convnext.name):
|
| 560 |
+
self.convnext.build(None)
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
@add_start_docstrings(
|
| 564 |
+
"""
|
| 565 |
+
ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
|
| 566 |
+
ImageNet.
|
| 567 |
+
""",
|
| 568 |
+
CONVNEXT_START_DOCSTRING,
|
| 569 |
+
)
|
| 570 |
+
class TFConvNextForImageClassification(TFConvNextPreTrainedModel, TFSequenceClassificationLoss):
|
| 571 |
+
def __init__(self, config: ConvNextConfig, *inputs, **kwargs):
|
| 572 |
+
super().__init__(config, *inputs, **kwargs)
|
| 573 |
+
|
| 574 |
+
self.num_labels = config.num_labels
|
| 575 |
+
self.convnext = TFConvNextMainLayer(config, name="convnext")
|
| 576 |
+
|
| 577 |
+
# Classifier head
|
| 578 |
+
self.classifier = keras.layers.Dense(
|
| 579 |
+
units=config.num_labels,
|
| 580 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 581 |
+
bias_initializer="zeros",
|
| 582 |
+
name="classifier",
|
| 583 |
+
)
|
| 584 |
+
self.config = config
|
| 585 |
+
|
| 586 |
+
@unpack_inputs
|
| 587 |
+
@add_start_docstrings_to_model_forward(CONVNEXT_INPUTS_DOCSTRING)
|
| 588 |
+
@replace_return_docstrings(output_type=TFSequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
|
| 589 |
+
def call(
|
| 590 |
+
self,
|
| 591 |
+
pixel_values: TFModelInputType | None = None,
|
| 592 |
+
output_hidden_states: Optional[bool] = None,
|
| 593 |
+
return_dict: Optional[bool] = None,
|
| 594 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 595 |
+
training: Optional[bool] = False,
|
| 596 |
+
) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
|
| 597 |
+
r"""
|
| 598 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
|
| 599 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 600 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 601 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 602 |
+
|
| 603 |
+
Returns:
|
| 604 |
+
|
| 605 |
+
Examples:
|
| 606 |
+
|
| 607 |
+
```python
|
| 608 |
+
>>> from transformers import AutoImageProcessor, TFConvNextForImageClassification
|
| 609 |
+
>>> import tensorflow as tf
|
| 610 |
+
>>> from PIL import Image
|
| 611 |
+
>>> import requests
|
| 612 |
+
|
| 613 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 614 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 615 |
+
|
| 616 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/convnext-tiny-224")
|
| 617 |
+
>>> model = TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224")
|
| 618 |
+
|
| 619 |
+
>>> inputs = image_processor(images=image, return_tensors="tf")
|
| 620 |
+
>>> outputs = model(**inputs)
|
| 621 |
+
>>> logits = outputs.logits
|
| 622 |
+
>>> # model predicts one of the 1000 ImageNet classes
|
| 623 |
+
>>> predicted_class_idx = tf.math.argmax(logits, axis=-1)[0]
|
| 624 |
+
>>> print("Predicted class:", model.config.id2label[int(predicted_class_idx)])
|
| 625 |
+
```"""
|
| 626 |
+
output_hidden_states = (
|
| 627 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 628 |
+
)
|
| 629 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 630 |
+
|
| 631 |
+
if pixel_values is None:
|
| 632 |
+
raise ValueError("You have to specify pixel_values")
|
| 633 |
+
|
| 634 |
+
outputs = self.convnext(
|
| 635 |
+
pixel_values,
|
| 636 |
+
output_hidden_states=output_hidden_states,
|
| 637 |
+
return_dict=return_dict,
|
| 638 |
+
training=training,
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
pooled_output = outputs.pooler_output if return_dict else outputs[1]
|
| 642 |
+
|
| 643 |
+
logits = self.classifier(pooled_output)
|
| 644 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
|
| 645 |
+
|
| 646 |
+
if not return_dict:
|
| 647 |
+
output = (logits,) + outputs[2:]
|
| 648 |
+
return ((loss,) + output) if loss is not None else output
|
| 649 |
+
|
| 650 |
+
return TFSequenceClassifierOutput(
|
| 651 |
+
loss=loss,
|
| 652 |
+
logits=logits,
|
| 653 |
+
hidden_states=outputs.hidden_states,
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
def build(self, input_shape=None):
|
| 657 |
+
if self.built:
|
| 658 |
+
return
|
| 659 |
+
self.built = True
|
| 660 |
+
if getattr(self, "convnext", None) is not None:
|
| 661 |
+
with tf.name_scope(self.convnext.name):
|
| 662 |
+
self.convnext.build(None)
|
| 663 |
+
if getattr(self, "classifier", None) is not None:
|
| 664 |
+
if hasattr(self.classifier, "name"):
|
| 665 |
+
with tf.name_scope(self.classifier.name):
|
| 666 |
+
self.classifier.build([None, None, self.config.hidden_sizes[-1]])
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
__all__ = ["TFConvNextForImageClassification", "TFConvNextModel", "TFConvNextPreTrainedModel"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnextv2/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_convnextv2 import *
|
| 22 |
+
from .modeling_convnextv2 import *
|
| 23 |
+
from .modeling_tf_convnextv2 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__)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnextv2/configuration_convnextv2.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 Meta Platforms, 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 |
+
"""ConvNeXTV2 model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ConvNextV2Config(BackboneConfigMixin, PretrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
This is the configuration class to store the configuration of a [`ConvNextV2Model`]. It is used to instantiate an
|
| 28 |
+
ConvNeXTV2 model according to the specified arguments, defining the model architecture. Instantiating a
|
| 29 |
+
configuration with the defaults will yield a similar configuration to that of the ConvNeXTV2
|
| 30 |
+
[facebook/convnextv2-tiny-1k-224](https://huggingface.co/facebook/convnextv2-tiny-1k-224) architecture.
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 37 |
+
The number of input channels.
|
| 38 |
+
patch_size (`int`, *optional*, defaults to 4):
|
| 39 |
+
Patch size to use in the patch embedding layer.
|
| 40 |
+
num_stages (`int`, *optional*, defaults to 4):
|
| 41 |
+
The number of stages in the model.
|
| 42 |
+
hidden_sizes (`List[int]`, *optional*, defaults to `[96, 192, 384, 768]`):
|
| 43 |
+
Dimensionality (hidden size) at each stage.
|
| 44 |
+
depths (`List[int]`, *optional*, defaults to `[3, 3, 9, 3]`):
|
| 45 |
+
Depth (number of blocks) for each stage.
|
| 46 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 47 |
+
The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`,
|
| 48 |
+
`"selu"` and `"gelu_new"` are supported.
|
| 49 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 50 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 51 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 52 |
+
The epsilon used by the layer normalization layers.
|
| 53 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 54 |
+
The drop rate for stochastic depth.
|
| 55 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 56 |
+
The size (resolution) of each image.
|
| 57 |
+
out_features (`List[str]`, *optional*):
|
| 58 |
+
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
|
| 59 |
+
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
|
| 60 |
+
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
|
| 61 |
+
same order as defined in the `stage_names` attribute.
|
| 62 |
+
out_indices (`List[int]`, *optional*):
|
| 63 |
+
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
|
| 64 |
+
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
|
| 65 |
+
If unset and `out_features` is unset, will default to the last stage. Must be in the
|
| 66 |
+
same order as defined in the `stage_names` attribute.
|
| 67 |
+
|
| 68 |
+
Example:
|
| 69 |
+
```python
|
| 70 |
+
>>> from transformers import ConvNeXTV2Config, ConvNextV2Model
|
| 71 |
+
|
| 72 |
+
>>> # Initializing a ConvNeXTV2 convnextv2-tiny-1k-224 style configuration
|
| 73 |
+
>>> configuration = ConvNeXTV2Config()
|
| 74 |
+
|
| 75 |
+
>>> # Initializing a model (with random weights) from the convnextv2-tiny-1k-224 style configuration
|
| 76 |
+
>>> model = ConvNextV2Model(configuration)
|
| 77 |
+
|
| 78 |
+
>>> # Accessing the model configuration
|
| 79 |
+
>>> configuration = model.config
|
| 80 |
+
```"""
|
| 81 |
+
|
| 82 |
+
model_type = "convnextv2"
|
| 83 |
+
|
| 84 |
+
def __init__(
|
| 85 |
+
self,
|
| 86 |
+
num_channels=3,
|
| 87 |
+
patch_size=4,
|
| 88 |
+
num_stages=4,
|
| 89 |
+
hidden_sizes=None,
|
| 90 |
+
depths=None,
|
| 91 |
+
hidden_act="gelu",
|
| 92 |
+
initializer_range=0.02,
|
| 93 |
+
layer_norm_eps=1e-12,
|
| 94 |
+
drop_path_rate=0.0,
|
| 95 |
+
image_size=224,
|
| 96 |
+
out_features=None,
|
| 97 |
+
out_indices=None,
|
| 98 |
+
**kwargs,
|
| 99 |
+
):
|
| 100 |
+
super().__init__(**kwargs)
|
| 101 |
+
|
| 102 |
+
self.num_channels = num_channels
|
| 103 |
+
self.patch_size = patch_size
|
| 104 |
+
self.num_stages = num_stages
|
| 105 |
+
self.hidden_sizes = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
|
| 106 |
+
self.depths = [3, 3, 9, 3] if depths is None else depths
|
| 107 |
+
self.hidden_act = hidden_act
|
| 108 |
+
self.initializer_range = initializer_range
|
| 109 |
+
self.layer_norm_eps = layer_norm_eps
|
| 110 |
+
self.drop_path_rate = drop_path_rate
|
| 111 |
+
self.image_size = image_size
|
| 112 |
+
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
|
| 113 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 114 |
+
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
__all__ = ["ConvNextV2Config"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnextv2/convert_convnextv2_to_pytorch.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Convert ConvNeXTV2 checkpoints from the original repository.
|
| 16 |
+
|
| 17 |
+
URL: https://github.com/facebookresearch/ConvNeXt"""
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
|
| 23 |
+
import requests
|
| 24 |
+
import torch
|
| 25 |
+
from huggingface_hub import hf_hub_download
|
| 26 |
+
from PIL import Image
|
| 27 |
+
|
| 28 |
+
from transformers import ConvNextImageProcessor, ConvNextV2Config, ConvNextV2ForImageClassification
|
| 29 |
+
from transformers.image_utils import PILImageResampling
|
| 30 |
+
from transformers.utils import logging
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logging.set_verbosity_info()
|
| 34 |
+
logger = logging.get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def get_convnextv2_config(checkpoint_url):
|
| 38 |
+
config = ConvNextV2Config()
|
| 39 |
+
|
| 40 |
+
if "atto" in checkpoint_url:
|
| 41 |
+
depths = [2, 2, 6, 2]
|
| 42 |
+
hidden_sizes = [40, 80, 160, 320]
|
| 43 |
+
if "femto" in checkpoint_url:
|
| 44 |
+
depths = [2, 2, 6, 2]
|
| 45 |
+
hidden_sizes = [48, 96, 192, 384]
|
| 46 |
+
if "pico" in checkpoint_url:
|
| 47 |
+
depths = [2, 2, 6, 2]
|
| 48 |
+
hidden_sizes = [64, 128, 256, 512]
|
| 49 |
+
if "nano" in checkpoint_url:
|
| 50 |
+
depths = [2, 2, 8, 2]
|
| 51 |
+
hidden_sizes = [80, 160, 320, 640]
|
| 52 |
+
if "tiny" in checkpoint_url:
|
| 53 |
+
depths = [3, 3, 9, 3]
|
| 54 |
+
hidden_sizes = [96, 192, 384, 768]
|
| 55 |
+
if "base" in checkpoint_url:
|
| 56 |
+
depths = [3, 3, 27, 3]
|
| 57 |
+
hidden_sizes = [128, 256, 512, 1024]
|
| 58 |
+
if "large" in checkpoint_url:
|
| 59 |
+
depths = [3, 3, 27, 3]
|
| 60 |
+
hidden_sizes = [192, 384, 768, 1536]
|
| 61 |
+
if "huge" in checkpoint_url:
|
| 62 |
+
depths = [3, 3, 27, 3]
|
| 63 |
+
hidden_sizes = [352, 704, 1408, 2816]
|
| 64 |
+
|
| 65 |
+
num_labels = 1000
|
| 66 |
+
filename = "imagenet-1k-id2label.json"
|
| 67 |
+
expected_shape = (1, 1000)
|
| 68 |
+
|
| 69 |
+
repo_id = "huggingface/label-files"
|
| 70 |
+
config.num_labels = num_labels
|
| 71 |
+
id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
|
| 72 |
+
id2label = {int(k): v for k, v in id2label.items()}
|
| 73 |
+
|
| 74 |
+
config.id2label = id2label
|
| 75 |
+
config.label2id = {v: k for k, v in id2label.items()}
|
| 76 |
+
config.hidden_sizes = hidden_sizes
|
| 77 |
+
config.depths = depths
|
| 78 |
+
|
| 79 |
+
return config, expected_shape
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def rename_key(name):
|
| 83 |
+
if "downsample_layers.0.0" in name:
|
| 84 |
+
name = name.replace("downsample_layers.0.0", "embeddings.patch_embeddings")
|
| 85 |
+
if "downsample_layers.0.1" in name:
|
| 86 |
+
name = name.replace("downsample_layers.0.1", "embeddings.norm") # we rename to layernorm later on
|
| 87 |
+
if "downsample_layers.1.0" in name:
|
| 88 |
+
name = name.replace("downsample_layers.1.0", "stages.1.downsampling_layer.0")
|
| 89 |
+
if "downsample_layers.1.1" in name:
|
| 90 |
+
name = name.replace("downsample_layers.1.1", "stages.1.downsampling_layer.1")
|
| 91 |
+
if "downsample_layers.2.0" in name:
|
| 92 |
+
name = name.replace("downsample_layers.2.0", "stages.2.downsampling_layer.0")
|
| 93 |
+
if "downsample_layers.2.1" in name:
|
| 94 |
+
name = name.replace("downsample_layers.2.1", "stages.2.downsampling_layer.1")
|
| 95 |
+
if "downsample_layers.3.0" in name:
|
| 96 |
+
name = name.replace("downsample_layers.3.0", "stages.3.downsampling_layer.0")
|
| 97 |
+
if "downsample_layers.3.1" in name:
|
| 98 |
+
name = name.replace("downsample_layers.3.1", "stages.3.downsampling_layer.1")
|
| 99 |
+
if "stages" in name and "downsampling_layer" not in name:
|
| 100 |
+
# stages.0.0. for instance should be renamed to stages.0.layers.0.
|
| 101 |
+
name = name[: len("stages.0")] + ".layers" + name[len("stages.0") :]
|
| 102 |
+
if "gamma" in name:
|
| 103 |
+
name = name.replace("gamma", "weight")
|
| 104 |
+
if "beta" in name:
|
| 105 |
+
name = name.replace("beta", "bias")
|
| 106 |
+
if "stages" in name:
|
| 107 |
+
name = name.replace("stages", "encoder.stages")
|
| 108 |
+
if "norm" in name:
|
| 109 |
+
name = name.replace("norm", "layernorm")
|
| 110 |
+
if "head" in name:
|
| 111 |
+
name = name.replace("head", "classifier")
|
| 112 |
+
|
| 113 |
+
return name
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# We will verify our results on an image of cute cats
|
| 117 |
+
def prepare_img():
|
| 118 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 119 |
+
im = Image.open(requests.get(url, stream=True).raw)
|
| 120 |
+
return im
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def convert_preprocessor(checkpoint_url):
|
| 124 |
+
if "224" in checkpoint_url:
|
| 125 |
+
size = 224
|
| 126 |
+
crop_pct = 224 / 256
|
| 127 |
+
elif "384" in checkpoint_url:
|
| 128 |
+
size = 384
|
| 129 |
+
crop_pct = None
|
| 130 |
+
else:
|
| 131 |
+
size = 512
|
| 132 |
+
crop_pct = None
|
| 133 |
+
|
| 134 |
+
return ConvNextImageProcessor(
|
| 135 |
+
size=size,
|
| 136 |
+
crop_pct=crop_pct,
|
| 137 |
+
image_mean=[0.485, 0.456, 0.406],
|
| 138 |
+
image_std=[0.229, 0.224, 0.225],
|
| 139 |
+
resample=PILImageResampling.BICUBIC,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@torch.no_grad()
|
| 144 |
+
def convert_convnextv2_checkpoint(checkpoint_url, pytorch_dump_folder_path, save_model, push_to_hub):
|
| 145 |
+
"""
|
| 146 |
+
Copy/paste/tweak model's weights to our ConvNeXTV2 structure.
|
| 147 |
+
"""
|
| 148 |
+
print("Downloading original model from checkpoint...")
|
| 149 |
+
# define ConvNeXTV2 configuration based on URL
|
| 150 |
+
config, expected_shape = get_convnextv2_config(checkpoint_url)
|
| 151 |
+
# load original state_dict from URL
|
| 152 |
+
state_dict = torch.hub.load_state_dict_from_url(checkpoint_url)["model"]
|
| 153 |
+
|
| 154 |
+
print("Converting model parameters...")
|
| 155 |
+
# rename keys
|
| 156 |
+
for key in state_dict.copy().keys():
|
| 157 |
+
val = state_dict.pop(key)
|
| 158 |
+
state_dict[rename_key(key)] = val
|
| 159 |
+
# add prefix to all keys expect classifier head
|
| 160 |
+
for key in state_dict.copy().keys():
|
| 161 |
+
val = state_dict.pop(key)
|
| 162 |
+
if not key.startswith("classifier"):
|
| 163 |
+
key = "convnextv2." + key
|
| 164 |
+
state_dict[key] = val
|
| 165 |
+
|
| 166 |
+
# load HuggingFace model
|
| 167 |
+
model = ConvNextV2ForImageClassification(config)
|
| 168 |
+
model.load_state_dict(state_dict)
|
| 169 |
+
model.eval()
|
| 170 |
+
|
| 171 |
+
# Check outputs on an image, prepared by ConvNextImageProcessor
|
| 172 |
+
preprocessor = convert_preprocessor(checkpoint_url)
|
| 173 |
+
inputs = preprocessor(images=prepare_img(), return_tensors="pt")
|
| 174 |
+
logits = model(**inputs).logits
|
| 175 |
+
|
| 176 |
+
# note: the logits below were obtained without center cropping
|
| 177 |
+
if checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_atto_1k_224_ema.pt":
|
| 178 |
+
expected_logits = torch.tensor([-0.3930, 0.1747, -0.5246, 0.4177, 0.4295])
|
| 179 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_femto_1k_224_ema.pt":
|
| 180 |
+
expected_logits = torch.tensor([-0.1727, -0.5341, -0.7818, -0.4745, -0.6566])
|
| 181 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_pico_1k_224_ema.pt":
|
| 182 |
+
expected_logits = torch.tensor([-0.0333, 0.1563, -0.9137, 0.1054, 0.0381])
|
| 183 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_nano_1k_224_ema.pt":
|
| 184 |
+
expected_logits = torch.tensor([-0.1744, -0.1555, -0.0713, 0.0950, -0.1431])
|
| 185 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_tiny_1k_224_ema.pt":
|
| 186 |
+
expected_logits = torch.tensor([0.9996, 0.1966, -0.4386, -0.3472, 0.6661])
|
| 187 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_base_1k_224_ema.pt":
|
| 188 |
+
expected_logits = torch.tensor([-0.2553, -0.6708, -0.1359, 0.2518, -0.2488])
|
| 189 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_large_1k_224_ema.pt":
|
| 190 |
+
expected_logits = torch.tensor([-0.0673, -0.5627, -0.3753, -0.2722, 0.0178])
|
| 191 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_huge_1k_224_ema.pt":
|
| 192 |
+
expected_logits = torch.tensor([-0.6377, -0.7458, -0.2150, 0.1184, -0.0597])
|
| 193 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_nano_22k_224_ema.pt":
|
| 194 |
+
expected_logits = torch.tensor([1.0799, 0.2322, -0.8860, 1.0219, 0.6231])
|
| 195 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_nano_22k_384_ema.pt":
|
| 196 |
+
expected_logits = torch.tensor([0.3766, 0.4917, -1.1426, 0.9942, 0.6024])
|
| 197 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_tiny_22k_224_ema.pt":
|
| 198 |
+
expected_logits = torch.tensor([0.4220, -0.6919, -0.4317, -0.2881, -0.6609])
|
| 199 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_tiny_22k_384_ema.pt":
|
| 200 |
+
expected_logits = torch.tensor([0.1082, -0.8286, -0.5095, 0.4681, -0.8085])
|
| 201 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_base_22k_224_ema.pt":
|
| 202 |
+
expected_logits = torch.tensor([-0.2419, -0.6221, 0.2176, -0.0980, -0.7527])
|
| 203 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_base_22k_384_ema.pt":
|
| 204 |
+
expected_logits = torch.tensor([0.0391, -0.4371, 0.3786, 0.1251, -0.2784])
|
| 205 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_large_22k_224_ema.pt":
|
| 206 |
+
expected_logits = torch.tensor([-0.0504, 0.5636, -0.1729, -0.6507, -0.3949])
|
| 207 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_large_22k_384_ema.pt":
|
| 208 |
+
expected_logits = torch.tensor([0.3560, 0.9486, 0.3149, -0.2667, -0.5138])
|
| 209 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_huge_22k_384_ema.pt":
|
| 210 |
+
expected_logits = torch.tensor([-0.2469, -0.4550, -0.5853, -0.0810, 0.0309])
|
| 211 |
+
elif checkpoint_url == "https://dl.fbaipublicfiles.com/convnext/convnextv2/im22k/convnextv2_huge_22k_512_ema.pt":
|
| 212 |
+
expected_logits = torch.tensor([-0.3090, 0.0802, -0.0682, -0.1979, -0.2826])
|
| 213 |
+
else:
|
| 214 |
+
raise ValueError(f"Unknown URL: {checkpoint_url}")
|
| 215 |
+
|
| 216 |
+
assert torch.allclose(logits[0, :5], expected_logits, atol=1e-3)
|
| 217 |
+
assert logits.shape == expected_shape
|
| 218 |
+
print("Model outputs match the original results!")
|
| 219 |
+
|
| 220 |
+
if save_model:
|
| 221 |
+
print("Saving model to local...")
|
| 222 |
+
# Create folder to save model
|
| 223 |
+
if not os.path.isdir(pytorch_dump_folder_path):
|
| 224 |
+
os.mkdir(pytorch_dump_folder_path)
|
| 225 |
+
|
| 226 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 227 |
+
preprocessor.save_pretrained(pytorch_dump_folder_path)
|
| 228 |
+
|
| 229 |
+
model_name = "convnextv2"
|
| 230 |
+
if "atto" in checkpoint_url:
|
| 231 |
+
model_name += "-atto"
|
| 232 |
+
if "femto" in checkpoint_url:
|
| 233 |
+
model_name += "-femto"
|
| 234 |
+
if "pico" in checkpoint_url:
|
| 235 |
+
model_name += "-pico"
|
| 236 |
+
if "nano" in checkpoint_url:
|
| 237 |
+
model_name += "-nano"
|
| 238 |
+
elif "tiny" in checkpoint_url:
|
| 239 |
+
model_name += "-tiny"
|
| 240 |
+
elif "base" in checkpoint_url:
|
| 241 |
+
model_name += "-base"
|
| 242 |
+
elif "large" in checkpoint_url:
|
| 243 |
+
model_name += "-large"
|
| 244 |
+
elif "huge" in checkpoint_url:
|
| 245 |
+
model_name += "-huge"
|
| 246 |
+
if "22k" in checkpoint_url and "1k" not in checkpoint_url:
|
| 247 |
+
model_name += "-22k"
|
| 248 |
+
elif "22k" in checkpoint_url and "1k" in checkpoint_url:
|
| 249 |
+
model_name += "-22k-1k"
|
| 250 |
+
elif "1k" in checkpoint_url:
|
| 251 |
+
model_name += "-1k"
|
| 252 |
+
if "224" in checkpoint_url:
|
| 253 |
+
model_name += "-224"
|
| 254 |
+
elif "384" in checkpoint_url:
|
| 255 |
+
model_name += "-384"
|
| 256 |
+
elif "512" in checkpoint_url:
|
| 257 |
+
model_name += "-512"
|
| 258 |
+
|
| 259 |
+
if push_to_hub:
|
| 260 |
+
print(f"Pushing {model_name} to the hub...")
|
| 261 |
+
model.push_to_hub(model_name)
|
| 262 |
+
preprocessor.push_to_hub(model_name)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
if __name__ == "__main__":
|
| 266 |
+
parser = argparse.ArgumentParser()
|
| 267 |
+
# Required parameters
|
| 268 |
+
parser.add_argument(
|
| 269 |
+
"--checkpoint_url",
|
| 270 |
+
default="https://dl.fbaipublicfiles.com/convnext/convnextv2/im1k/convnextv2_atto_1k_224_ema.pt",
|
| 271 |
+
type=str,
|
| 272 |
+
help="URL of the original ConvNeXTV2 checkpoint you'd like to convert.",
|
| 273 |
+
)
|
| 274 |
+
parser.add_argument(
|
| 275 |
+
"--pytorch_dump_folder_path",
|
| 276 |
+
default="model",
|
| 277 |
+
type=str,
|
| 278 |
+
help="Path to the output PyTorch model directory.",
|
| 279 |
+
)
|
| 280 |
+
parser.add_argument("--save_model", action="store_true", help="Save model to local")
|
| 281 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Push model and image preprocessor to the hub")
|
| 282 |
+
|
| 283 |
+
args = parser.parse_args()
|
| 284 |
+
convert_convnextv2_checkpoint(
|
| 285 |
+
args.checkpoint_url, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub
|
| 286 |
+
)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnextv2/modeling_convnextv2.py
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 Meta Platforms, 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 |
+
"""PyTorch ConvNextV2 model."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.utils.checkpoint
|
| 21 |
+
from torch import nn
|
| 22 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 23 |
+
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...modeling_outputs import (
|
| 26 |
+
BackboneOutput,
|
| 27 |
+
BaseModelOutputWithNoAttention,
|
| 28 |
+
BaseModelOutputWithPoolingAndNoAttention,
|
| 29 |
+
ImageClassifierOutputWithNoAttention,
|
| 30 |
+
)
|
| 31 |
+
from ...modeling_utils import PreTrainedModel
|
| 32 |
+
from ...utils import (
|
| 33 |
+
add_code_sample_docstrings,
|
| 34 |
+
add_start_docstrings,
|
| 35 |
+
add_start_docstrings_to_model_forward,
|
| 36 |
+
logging,
|
| 37 |
+
replace_return_docstrings,
|
| 38 |
+
)
|
| 39 |
+
from ...utils.backbone_utils import BackboneMixin
|
| 40 |
+
from .configuration_convnextv2 import ConvNextV2Config
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
logger = logging.get_logger(__name__)
|
| 44 |
+
|
| 45 |
+
# General docstring
|
| 46 |
+
_CONFIG_FOR_DOC = "ConvNextV2Config"
|
| 47 |
+
|
| 48 |
+
# Base docstring
|
| 49 |
+
_CHECKPOINT_FOR_DOC = "facebook/convnextv2-tiny-1k-224"
|
| 50 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 768, 7, 7]
|
| 51 |
+
|
| 52 |
+
# Image classification docstring
|
| 53 |
+
_IMAGE_CLASS_CHECKPOINT = "facebook/convnextv2-tiny-1k-224"
|
| 54 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# Copied from transformers.models.beit.modeling_beit.drop_path
|
| 58 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 59 |
+
"""
|
| 60 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 61 |
+
|
| 62 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 63 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 64 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 65 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 66 |
+
argument.
|
| 67 |
+
"""
|
| 68 |
+
if drop_prob == 0.0 or not training:
|
| 69 |
+
return input
|
| 70 |
+
keep_prob = 1 - drop_prob
|
| 71 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 72 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 73 |
+
random_tensor.floor_() # binarize
|
| 74 |
+
output = input.div(keep_prob) * random_tensor
|
| 75 |
+
return output
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->ConvNextV2
|
| 79 |
+
class ConvNextV2DropPath(nn.Module):
|
| 80 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 81 |
+
|
| 82 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.drop_prob = drop_prob
|
| 85 |
+
|
| 86 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 87 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 88 |
+
|
| 89 |
+
def extra_repr(self) -> str:
|
| 90 |
+
return "p={}".format(self.drop_prob)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class ConvNextV2GRN(nn.Module):
|
| 94 |
+
"""GRN (Global Response Normalization) layer"""
|
| 95 |
+
|
| 96 |
+
def __init__(self, dim: int):
|
| 97 |
+
super().__init__()
|
| 98 |
+
self.weight = nn.Parameter(torch.zeros(1, 1, 1, dim))
|
| 99 |
+
self.bias = nn.Parameter(torch.zeros(1, 1, 1, dim))
|
| 100 |
+
|
| 101 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
|
| 102 |
+
# Compute and normalize global spatial feature maps
|
| 103 |
+
global_features = torch.norm(hidden_states, p=2, dim=(1, 2), keepdim=True)
|
| 104 |
+
norm_features = global_features / (global_features.mean(dim=-1, keepdim=True) + 1e-6)
|
| 105 |
+
hidden_states = self.weight * (hidden_states * norm_features) + self.bias + hidden_states
|
| 106 |
+
|
| 107 |
+
return hidden_states
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# Copied from transformers.models.convnext.modeling_convnext.ConvNextLayerNorm with ConvNext->ConvNextV2
|
| 111 |
+
class ConvNextV2LayerNorm(nn.Module):
|
| 112 |
+
r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
|
| 113 |
+
The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
|
| 114 |
+
width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.weight = nn.Parameter(torch.ones(normalized_shape))
|
| 120 |
+
self.bias = nn.Parameter(torch.zeros(normalized_shape))
|
| 121 |
+
self.eps = eps
|
| 122 |
+
self.data_format = data_format
|
| 123 |
+
if self.data_format not in ["channels_last", "channels_first"]:
|
| 124 |
+
raise NotImplementedError(f"Unsupported data format: {self.data_format}")
|
| 125 |
+
self.normalized_shape = (normalized_shape,)
|
| 126 |
+
|
| 127 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 128 |
+
if self.data_format == "channels_last":
|
| 129 |
+
x = torch.nn.functional.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
|
| 130 |
+
elif self.data_format == "channels_first":
|
| 131 |
+
input_dtype = x.dtype
|
| 132 |
+
x = x.float()
|
| 133 |
+
u = x.mean(1, keepdim=True)
|
| 134 |
+
s = (x - u).pow(2).mean(1, keepdim=True)
|
| 135 |
+
x = (x - u) / torch.sqrt(s + self.eps)
|
| 136 |
+
x = x.to(dtype=input_dtype)
|
| 137 |
+
x = self.weight[:, None, None] * x + self.bias[:, None, None]
|
| 138 |
+
return x
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# Copied from transformers.models.convnext.modeling_convnext.ConvNextEmbeddings with ConvNext->ConvNextV2
|
| 142 |
+
class ConvNextV2Embeddings(nn.Module):
|
| 143 |
+
"""This class is comparable to (and inspired by) the SwinEmbeddings class
|
| 144 |
+
found in src/transformers/models/swin/modeling_swin.py.
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
def __init__(self, config):
|
| 148 |
+
super().__init__()
|
| 149 |
+
self.patch_embeddings = nn.Conv2d(
|
| 150 |
+
config.num_channels, config.hidden_sizes[0], kernel_size=config.patch_size, stride=config.patch_size
|
| 151 |
+
)
|
| 152 |
+
self.layernorm = ConvNextV2LayerNorm(config.hidden_sizes[0], eps=1e-6, data_format="channels_first")
|
| 153 |
+
self.num_channels = config.num_channels
|
| 154 |
+
|
| 155 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 156 |
+
num_channels = pixel_values.shape[1]
|
| 157 |
+
if num_channels != self.num_channels:
|
| 158 |
+
raise ValueError(
|
| 159 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 160 |
+
)
|
| 161 |
+
embeddings = self.patch_embeddings(pixel_values)
|
| 162 |
+
embeddings = self.layernorm(embeddings)
|
| 163 |
+
return embeddings
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class ConvNextV2Layer(nn.Module):
|
| 167 |
+
"""This corresponds to the `Block` class in the original implementation.
|
| 168 |
+
|
| 169 |
+
There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,
|
| 170 |
+
H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back
|
| 171 |
+
|
| 172 |
+
The authors used (2) as they find it slightly faster in PyTorch.
|
| 173 |
+
|
| 174 |
+
Args:
|
| 175 |
+
config ([`ConvNextV2Config`]): Model configuration class.
|
| 176 |
+
dim (`int`): Number of input channels.
|
| 177 |
+
drop_path (`float`): Stochastic depth rate. Default: 0.0.
|
| 178 |
+
"""
|
| 179 |
+
|
| 180 |
+
def __init__(self, config, dim, drop_path=0):
|
| 181 |
+
super().__init__()
|
| 182 |
+
# depthwise conv
|
| 183 |
+
self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)
|
| 184 |
+
self.layernorm = ConvNextV2LayerNorm(dim, eps=1e-6)
|
| 185 |
+
# pointwise/1x1 convs, implemented with linear layers
|
| 186 |
+
self.pwconv1 = nn.Linear(dim, 4 * dim)
|
| 187 |
+
self.act = ACT2FN[config.hidden_act]
|
| 188 |
+
self.grn = ConvNextV2GRN(4 * dim)
|
| 189 |
+
self.pwconv2 = nn.Linear(4 * dim, dim)
|
| 190 |
+
self.drop_path = ConvNextV2DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 191 |
+
|
| 192 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
|
| 193 |
+
input = hidden_states
|
| 194 |
+
x = self.dwconv(hidden_states)
|
| 195 |
+
# (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
|
| 196 |
+
x = x.permute(0, 2, 3, 1)
|
| 197 |
+
x = self.layernorm(x)
|
| 198 |
+
x = self.pwconv1(x)
|
| 199 |
+
x = self.act(x)
|
| 200 |
+
x = self.grn(x)
|
| 201 |
+
x = self.pwconv2(x)
|
| 202 |
+
# (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
|
| 203 |
+
x = x.permute(0, 3, 1, 2)
|
| 204 |
+
|
| 205 |
+
x = input + self.drop_path(x)
|
| 206 |
+
return x
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# Copied from transformers.models.convnext.modeling_convnext.ConvNextStage with ConvNeXT->ConvNeXTV2, ConvNext->ConvNextV2
|
| 210 |
+
class ConvNextV2Stage(nn.Module):
|
| 211 |
+
"""ConvNeXTV2 stage, consisting of an optional downsampling layer + multiple residual blocks.
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
config ([`ConvNextV2Config`]): Model configuration class.
|
| 215 |
+
in_channels (`int`): Number of input channels.
|
| 216 |
+
out_channels (`int`): Number of output channels.
|
| 217 |
+
depth (`int`): Number of residual blocks.
|
| 218 |
+
drop_path_rates(`List[float]`): Stochastic depth rates for each layer.
|
| 219 |
+
"""
|
| 220 |
+
|
| 221 |
+
def __init__(self, config, in_channels, out_channels, kernel_size=2, stride=2, depth=2, drop_path_rates=None):
|
| 222 |
+
super().__init__()
|
| 223 |
+
|
| 224 |
+
if in_channels != out_channels or stride > 1:
|
| 225 |
+
self.downsampling_layer = nn.Sequential(
|
| 226 |
+
ConvNextV2LayerNorm(in_channels, eps=1e-6, data_format="channels_first"),
|
| 227 |
+
nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride),
|
| 228 |
+
)
|
| 229 |
+
else:
|
| 230 |
+
self.downsampling_layer = nn.Identity()
|
| 231 |
+
drop_path_rates = drop_path_rates or [0.0] * depth
|
| 232 |
+
self.layers = nn.Sequential(
|
| 233 |
+
*[ConvNextV2Layer(config, dim=out_channels, drop_path=drop_path_rates[j]) for j in range(depth)]
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
|
| 237 |
+
hidden_states = self.downsampling_layer(hidden_states)
|
| 238 |
+
hidden_states = self.layers(hidden_states)
|
| 239 |
+
return hidden_states
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
# Copied from transformers.models.convnext.modeling_convnext.ConvNextEncoder with ConvNext->ConvNextV2
|
| 243 |
+
class ConvNextV2Encoder(nn.Module):
|
| 244 |
+
def __init__(self, config):
|
| 245 |
+
super().__init__()
|
| 246 |
+
self.stages = nn.ModuleList()
|
| 247 |
+
drop_path_rates = [
|
| 248 |
+
x.tolist() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths)).split(config.depths)
|
| 249 |
+
]
|
| 250 |
+
prev_chs = config.hidden_sizes[0]
|
| 251 |
+
for i in range(config.num_stages):
|
| 252 |
+
out_chs = config.hidden_sizes[i]
|
| 253 |
+
stage = ConvNextV2Stage(
|
| 254 |
+
config,
|
| 255 |
+
in_channels=prev_chs,
|
| 256 |
+
out_channels=out_chs,
|
| 257 |
+
stride=2 if i > 0 else 1,
|
| 258 |
+
depth=config.depths[i],
|
| 259 |
+
drop_path_rates=drop_path_rates[i],
|
| 260 |
+
)
|
| 261 |
+
self.stages.append(stage)
|
| 262 |
+
prev_chs = out_chs
|
| 263 |
+
|
| 264 |
+
def forward(
|
| 265 |
+
self,
|
| 266 |
+
hidden_states: torch.FloatTensor,
|
| 267 |
+
output_hidden_states: Optional[bool] = False,
|
| 268 |
+
return_dict: Optional[bool] = True,
|
| 269 |
+
) -> Union[Tuple, BaseModelOutputWithNoAttention]:
|
| 270 |
+
all_hidden_states = () if output_hidden_states else None
|
| 271 |
+
|
| 272 |
+
for i, layer_module in enumerate(self.stages):
|
| 273 |
+
if output_hidden_states:
|
| 274 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 275 |
+
|
| 276 |
+
hidden_states = layer_module(hidden_states)
|
| 277 |
+
|
| 278 |
+
if output_hidden_states:
|
| 279 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 280 |
+
|
| 281 |
+
if not return_dict:
|
| 282 |
+
return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
|
| 283 |
+
|
| 284 |
+
return BaseModelOutputWithNoAttention(
|
| 285 |
+
last_hidden_state=hidden_states,
|
| 286 |
+
hidden_states=all_hidden_states,
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
# Copied from transformers.models.convnext.modeling_convnext.ConvNextPreTrainedModel with ConvNext->ConvNextV2, convnext->convnextv2
|
| 291 |
+
class ConvNextV2PreTrainedModel(PreTrainedModel):
|
| 292 |
+
"""
|
| 293 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 294 |
+
models.
|
| 295 |
+
"""
|
| 296 |
+
|
| 297 |
+
config_class = ConvNextV2Config
|
| 298 |
+
base_model_prefix = "convnextv2"
|
| 299 |
+
main_input_name = "pixel_values"
|
| 300 |
+
_no_split_modules = ["ConvNextV2Layer"]
|
| 301 |
+
|
| 302 |
+
def _init_weights(self, module):
|
| 303 |
+
"""Initialize the weights"""
|
| 304 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 305 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 306 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 307 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 308 |
+
if module.bias is not None:
|
| 309 |
+
module.bias.data.zero_()
|
| 310 |
+
elif isinstance(module, nn.LayerNorm):
|
| 311 |
+
module.bias.data.zero_()
|
| 312 |
+
module.weight.data.fill_(1.0)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
CONVNEXTV2_START_DOCSTRING = r"""
|
| 316 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 317 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 318 |
+
behavior.
|
| 319 |
+
|
| 320 |
+
Parameters:
|
| 321 |
+
config ([`ConvNextV2Config`]): Model configuration class with all the parameters of the model.
|
| 322 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 323 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
CONVNEXTV2_INPUTS_DOCSTRING = r"""
|
| 327 |
+
Args:
|
| 328 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 329 |
+
Pixel values. Pixel values can be obtained using [`ConvNextImageProcessor`]. See
|
| 330 |
+
[`ConvNextImageProcessor.__call__`] for details.
|
| 331 |
+
output_hidden_states (`bool`, *optional*):
|
| 332 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 333 |
+
more detail.
|
| 334 |
+
return_dict (`bool`, *optional*):
|
| 335 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 336 |
+
"""
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@add_start_docstrings(
|
| 340 |
+
"The bare ConvNextV2 model outputting raw features without any specific head on top.",
|
| 341 |
+
CONVNEXTV2_START_DOCSTRING,
|
| 342 |
+
)
|
| 343 |
+
# Copied from transformers.models.convnext.modeling_convnext.ConvNextModel with CONVNEXT->CONVNEXTV2, ConvNext->ConvNextV2
|
| 344 |
+
class ConvNextV2Model(ConvNextV2PreTrainedModel):
|
| 345 |
+
def __init__(self, config):
|
| 346 |
+
super().__init__(config)
|
| 347 |
+
self.config = config
|
| 348 |
+
|
| 349 |
+
self.embeddings = ConvNextV2Embeddings(config)
|
| 350 |
+
self.encoder = ConvNextV2Encoder(config)
|
| 351 |
+
|
| 352 |
+
# final layernorm layer
|
| 353 |
+
self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
|
| 354 |
+
|
| 355 |
+
# Initialize weights and apply final processing
|
| 356 |
+
self.post_init()
|
| 357 |
+
|
| 358 |
+
@add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)
|
| 359 |
+
@add_code_sample_docstrings(
|
| 360 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 361 |
+
output_type=BaseModelOutputWithPoolingAndNoAttention,
|
| 362 |
+
config_class=_CONFIG_FOR_DOC,
|
| 363 |
+
modality="vision",
|
| 364 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 365 |
+
)
|
| 366 |
+
def forward(
|
| 367 |
+
self,
|
| 368 |
+
pixel_values: torch.FloatTensor = None,
|
| 369 |
+
output_hidden_states: Optional[bool] = None,
|
| 370 |
+
return_dict: Optional[bool] = None,
|
| 371 |
+
) -> Union[Tuple, BaseModelOutputWithPoolingAndNoAttention]:
|
| 372 |
+
output_hidden_states = (
|
| 373 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 374 |
+
)
|
| 375 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 376 |
+
|
| 377 |
+
if pixel_values is None:
|
| 378 |
+
raise ValueError("You have to specify pixel_values")
|
| 379 |
+
|
| 380 |
+
embedding_output = self.embeddings(pixel_values)
|
| 381 |
+
|
| 382 |
+
encoder_outputs = self.encoder(
|
| 383 |
+
embedding_output,
|
| 384 |
+
output_hidden_states=output_hidden_states,
|
| 385 |
+
return_dict=return_dict,
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
last_hidden_state = encoder_outputs[0]
|
| 389 |
+
|
| 390 |
+
# global average pooling, (N, C, H, W) -> (N, C)
|
| 391 |
+
pooled_output = self.layernorm(last_hidden_state.mean([-2, -1]))
|
| 392 |
+
|
| 393 |
+
if not return_dict:
|
| 394 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 395 |
+
|
| 396 |
+
return BaseModelOutputWithPoolingAndNoAttention(
|
| 397 |
+
last_hidden_state=last_hidden_state,
|
| 398 |
+
pooler_output=pooled_output,
|
| 399 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
@add_start_docstrings(
|
| 404 |
+
"""
|
| 405 |
+
ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
|
| 406 |
+
ImageNet.
|
| 407 |
+
""",
|
| 408 |
+
CONVNEXTV2_START_DOCSTRING,
|
| 409 |
+
)
|
| 410 |
+
# Copied from transformers.models.convnext.modeling_convnext.ConvNextForImageClassification with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,convnext->convnextv2
|
| 411 |
+
class ConvNextV2ForImageClassification(ConvNextV2PreTrainedModel):
|
| 412 |
+
def __init__(self, config):
|
| 413 |
+
super().__init__(config)
|
| 414 |
+
|
| 415 |
+
self.num_labels = config.num_labels
|
| 416 |
+
self.convnextv2 = ConvNextV2Model(config)
|
| 417 |
+
|
| 418 |
+
# Classifier head
|
| 419 |
+
self.classifier = (
|
| 420 |
+
nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
# Initialize weights and apply final processing
|
| 424 |
+
self.post_init()
|
| 425 |
+
|
| 426 |
+
@add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)
|
| 427 |
+
@add_code_sample_docstrings(
|
| 428 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
| 429 |
+
output_type=ImageClassifierOutputWithNoAttention,
|
| 430 |
+
config_class=_CONFIG_FOR_DOC,
|
| 431 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
| 432 |
+
)
|
| 433 |
+
def forward(
|
| 434 |
+
self,
|
| 435 |
+
pixel_values: torch.FloatTensor = None,
|
| 436 |
+
labels: Optional[torch.LongTensor] = None,
|
| 437 |
+
output_hidden_states: Optional[bool] = None,
|
| 438 |
+
return_dict: Optional[bool] = None,
|
| 439 |
+
) -> Union[Tuple, ImageClassifierOutputWithNoAttention]:
|
| 440 |
+
r"""
|
| 441 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 442 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 443 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 444 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 445 |
+
"""
|
| 446 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 447 |
+
|
| 448 |
+
outputs = self.convnextv2(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 449 |
+
|
| 450 |
+
pooled_output = outputs.pooler_output if return_dict else outputs[1]
|
| 451 |
+
|
| 452 |
+
logits = self.classifier(pooled_output)
|
| 453 |
+
|
| 454 |
+
loss = None
|
| 455 |
+
if labels is not None:
|
| 456 |
+
if self.config.problem_type is None:
|
| 457 |
+
if self.num_labels == 1:
|
| 458 |
+
self.config.problem_type = "regression"
|
| 459 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 460 |
+
self.config.problem_type = "single_label_classification"
|
| 461 |
+
else:
|
| 462 |
+
self.config.problem_type = "multi_label_classification"
|
| 463 |
+
|
| 464 |
+
if self.config.problem_type == "regression":
|
| 465 |
+
loss_fct = MSELoss()
|
| 466 |
+
if self.num_labels == 1:
|
| 467 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 468 |
+
else:
|
| 469 |
+
loss = loss_fct(logits, labels)
|
| 470 |
+
elif self.config.problem_type == "single_label_classification":
|
| 471 |
+
loss_fct = CrossEntropyLoss()
|
| 472 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 473 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 474 |
+
loss_fct = BCEWithLogitsLoss()
|
| 475 |
+
loss = loss_fct(logits, labels)
|
| 476 |
+
if not return_dict:
|
| 477 |
+
output = (logits,) + outputs[2:]
|
| 478 |
+
return ((loss,) + output) if loss is not None else output
|
| 479 |
+
|
| 480 |
+
return ImageClassifierOutputWithNoAttention(
|
| 481 |
+
loss=loss,
|
| 482 |
+
logits=logits,
|
| 483 |
+
hidden_states=outputs.hidden_states,
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
@add_start_docstrings(
|
| 488 |
+
"""
|
| 489 |
+
ConvNeXT V2 backbone, to be used with frameworks like DETR and MaskFormer.
|
| 490 |
+
""",
|
| 491 |
+
CONVNEXTV2_START_DOCSTRING,
|
| 492 |
+
)
|
| 493 |
+
# Copied from transformers.models.convnext.modeling_convnext.ConvNextBackbone with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,facebook/convnext-tiny-224->facebook/convnextv2-tiny-1k-224
|
| 494 |
+
class ConvNextV2Backbone(ConvNextV2PreTrainedModel, BackboneMixin):
|
| 495 |
+
def __init__(self, config):
|
| 496 |
+
super().__init__(config)
|
| 497 |
+
super()._init_backbone(config)
|
| 498 |
+
|
| 499 |
+
self.embeddings = ConvNextV2Embeddings(config)
|
| 500 |
+
self.encoder = ConvNextV2Encoder(config)
|
| 501 |
+
self.num_features = [config.hidden_sizes[0]] + config.hidden_sizes
|
| 502 |
+
|
| 503 |
+
# Add layer norms to hidden states of out_features
|
| 504 |
+
hidden_states_norms = {}
|
| 505 |
+
for stage, num_channels in zip(self._out_features, self.channels):
|
| 506 |
+
hidden_states_norms[stage] = ConvNextV2LayerNorm(num_channels, data_format="channels_first")
|
| 507 |
+
self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
|
| 508 |
+
|
| 509 |
+
# initialize weights and apply final processing
|
| 510 |
+
self.post_init()
|
| 511 |
+
|
| 512 |
+
@add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)
|
| 513 |
+
@replace_return_docstrings(output_type=BackboneOutput, config_class=_CONFIG_FOR_DOC)
|
| 514 |
+
def forward(
|
| 515 |
+
self,
|
| 516 |
+
pixel_values: torch.Tensor,
|
| 517 |
+
output_hidden_states: Optional[bool] = None,
|
| 518 |
+
return_dict: Optional[bool] = None,
|
| 519 |
+
) -> BackboneOutput:
|
| 520 |
+
"""
|
| 521 |
+
Returns:
|
| 522 |
+
|
| 523 |
+
Examples:
|
| 524 |
+
|
| 525 |
+
```python
|
| 526 |
+
>>> from transformers import AutoImageProcessor, AutoBackbone
|
| 527 |
+
>>> import torch
|
| 528 |
+
>>> from PIL import Image
|
| 529 |
+
>>> import requests
|
| 530 |
+
|
| 531 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 532 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 533 |
+
|
| 534 |
+
>>> processor = AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224")
|
| 535 |
+
>>> model = AutoBackbone.from_pretrained("facebook/convnextv2-tiny-1k-224")
|
| 536 |
+
|
| 537 |
+
>>> inputs = processor(image, return_tensors="pt")
|
| 538 |
+
>>> outputs = model(**inputs)
|
| 539 |
+
```"""
|
| 540 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 541 |
+
output_hidden_states = (
|
| 542 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
embedding_output = self.embeddings(pixel_values)
|
| 546 |
+
|
| 547 |
+
outputs = self.encoder(
|
| 548 |
+
embedding_output,
|
| 549 |
+
output_hidden_states=True,
|
| 550 |
+
return_dict=return_dict,
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
hidden_states = outputs.hidden_states if return_dict else outputs[1]
|
| 554 |
+
|
| 555 |
+
feature_maps = ()
|
| 556 |
+
for stage, hidden_state in zip(self.stage_names, hidden_states):
|
| 557 |
+
if stage in self.out_features:
|
| 558 |
+
hidden_state = self.hidden_states_norms[stage](hidden_state)
|
| 559 |
+
feature_maps += (hidden_state,)
|
| 560 |
+
|
| 561 |
+
if not return_dict:
|
| 562 |
+
output = (feature_maps,)
|
| 563 |
+
if output_hidden_states:
|
| 564 |
+
output += (hidden_states,)
|
| 565 |
+
return output
|
| 566 |
+
|
| 567 |
+
return BackboneOutput(
|
| 568 |
+
feature_maps=feature_maps,
|
| 569 |
+
hidden_states=hidden_states if output_hidden_states else None,
|
| 570 |
+
attentions=None,
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
__all__ = ["ConvNextV2ForImageClassification", "ConvNextV2Model", "ConvNextV2PreTrainedModel", "ConvNextV2Backbone"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/convnextv2/modeling_tf_convnextv2.py
ADDED
|
@@ -0,0 +1,683 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 Meta Platforms 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 |
+
"""TF 2.0 ConvNextV2 model."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from typing import List, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import tensorflow as tf
|
| 23 |
+
|
| 24 |
+
from ...activations_tf import get_tf_activation
|
| 25 |
+
from ...modeling_tf_outputs import (
|
| 26 |
+
TFBaseModelOutputWithNoAttention,
|
| 27 |
+
TFBaseModelOutputWithPooling,
|
| 28 |
+
TFBaseModelOutputWithPoolingAndNoAttention,
|
| 29 |
+
TFImageClassifierOutputWithNoAttention,
|
| 30 |
+
)
|
| 31 |
+
from ...modeling_tf_utils import (
|
| 32 |
+
TFModelInputType,
|
| 33 |
+
TFPreTrainedModel,
|
| 34 |
+
TFSequenceClassificationLoss,
|
| 35 |
+
get_initializer,
|
| 36 |
+
keras,
|
| 37 |
+
keras_serializable,
|
| 38 |
+
unpack_inputs,
|
| 39 |
+
)
|
| 40 |
+
from ...tf_utils import shape_list
|
| 41 |
+
from ...utils import (
|
| 42 |
+
add_code_sample_docstrings,
|
| 43 |
+
add_start_docstrings,
|
| 44 |
+
add_start_docstrings_to_model_forward,
|
| 45 |
+
logging,
|
| 46 |
+
)
|
| 47 |
+
from .configuration_convnextv2 import ConvNextV2Config
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
logger = logging.get_logger(__name__)
|
| 51 |
+
|
| 52 |
+
# General docstring
|
| 53 |
+
_CONFIG_FOR_DOC = "ConvNextV2Config"
|
| 54 |
+
|
| 55 |
+
# Base docstring
|
| 56 |
+
_CHECKPOINT_FOR_DOC = "facebook/convnextv2-tiny-1k-224"
|
| 57 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 768, 7, 7]
|
| 58 |
+
|
| 59 |
+
# Image classification docstring
|
| 60 |
+
_IMAGE_CLASS_CHECKPOINT = "facebook/convnextv2-tiny-1k-224"
|
| 61 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# Copied from transformers.models.convnext.modeling_tf_convnext.TFConvNextDropPath with ConvNext->ConvNextV2
|
| 65 |
+
class TFConvNextV2DropPath(keras.layers.Layer):
|
| 66 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 67 |
+
References:
|
| 68 |
+
(1) github.com:rwightman/pytorch-image-models
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
def __init__(self, drop_path: float, **kwargs):
|
| 72 |
+
super().__init__(**kwargs)
|
| 73 |
+
self.drop_path = drop_path
|
| 74 |
+
|
| 75 |
+
def call(self, x: tf.Tensor, training=None):
|
| 76 |
+
if training:
|
| 77 |
+
keep_prob = 1 - self.drop_path
|
| 78 |
+
shape = (tf.shape(x)[0],) + (1,) * (len(tf.shape(x)) - 1)
|
| 79 |
+
random_tensor = keep_prob + tf.random.uniform(shape, 0, 1)
|
| 80 |
+
random_tensor = tf.floor(random_tensor)
|
| 81 |
+
return (x / keep_prob) * random_tensor
|
| 82 |
+
return x
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class TFConvNextV2GRN(keras.layers.Layer):
|
| 86 |
+
"""GRN (Global Response Normalization) layer"""
|
| 87 |
+
|
| 88 |
+
def __init__(self, config: ConvNextV2Config, dim: int, **kwargs):
|
| 89 |
+
super().__init__(**kwargs)
|
| 90 |
+
self.dim = dim
|
| 91 |
+
|
| 92 |
+
def build(self, input_shape: tf.TensorShape = None):
|
| 93 |
+
# PT's `nn.Parameters` must be mapped to a TF layer weight to inherit the same name hierarchy (and vice-versa)
|
| 94 |
+
self.weight = self.add_weight(
|
| 95 |
+
name="weight",
|
| 96 |
+
shape=(1, 1, 1, self.dim),
|
| 97 |
+
initializer=keras.initializers.Zeros(),
|
| 98 |
+
)
|
| 99 |
+
self.bias = self.add_weight(
|
| 100 |
+
name="bias",
|
| 101 |
+
shape=(1, 1, 1, self.dim),
|
| 102 |
+
initializer=keras.initializers.Zeros(),
|
| 103 |
+
)
|
| 104 |
+
return super().build(input_shape)
|
| 105 |
+
|
| 106 |
+
def call(self, hidden_states: tf.Tensor):
|
| 107 |
+
global_features = tf.norm(hidden_states, ord="euclidean", axis=(1, 2), keepdims=True)
|
| 108 |
+
norm_features = global_features / (tf.reduce_mean(global_features, axis=-1, keepdims=True) + 1e-6)
|
| 109 |
+
hidden_states = self.weight * (hidden_states * norm_features) + self.bias + hidden_states
|
| 110 |
+
return hidden_states
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# Copied from transformers.models.convnext.modeling_tf_convnext.TFConvNextEmbeddings with ConvNext->ConvNextV2
|
| 114 |
+
class TFConvNextV2Embeddings(keras.layers.Layer):
|
| 115 |
+
"""This class is comparable to (and inspired by) the SwinEmbeddings class
|
| 116 |
+
found in src/transformers/models/swin/modeling_swin.py.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
def __init__(self, config: ConvNextV2Config, **kwargs):
|
| 120 |
+
super().__init__(**kwargs)
|
| 121 |
+
self.patch_embeddings = keras.layers.Conv2D(
|
| 122 |
+
filters=config.hidden_sizes[0],
|
| 123 |
+
kernel_size=config.patch_size,
|
| 124 |
+
strides=config.patch_size,
|
| 125 |
+
name="patch_embeddings",
|
| 126 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 127 |
+
bias_initializer=keras.initializers.Zeros(),
|
| 128 |
+
)
|
| 129 |
+
self.layernorm = keras.layers.LayerNormalization(epsilon=1e-6, name="layernorm")
|
| 130 |
+
self.num_channels = config.num_channels
|
| 131 |
+
self.config = config
|
| 132 |
+
|
| 133 |
+
def call(self, pixel_values):
|
| 134 |
+
if isinstance(pixel_values, dict):
|
| 135 |
+
pixel_values = pixel_values["pixel_values"]
|
| 136 |
+
|
| 137 |
+
tf.debugging.assert_equal(
|
| 138 |
+
shape_list(pixel_values)[1],
|
| 139 |
+
self.num_channels,
|
| 140 |
+
message="Make sure that the channel dimension of the pixel values match with the one set in the configuration.",
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
# When running on CPU, `keras.layers.Conv2D` doesn't support `NCHW` format.
|
| 144 |
+
# So change the input format from `NCHW` to `NHWC`.
|
| 145 |
+
# shape = (batch_size, in_height, in_width, in_channels)
|
| 146 |
+
pixel_values = tf.transpose(pixel_values, perm=(0, 2, 3, 1))
|
| 147 |
+
|
| 148 |
+
embeddings = self.patch_embeddings(pixel_values)
|
| 149 |
+
embeddings = self.layernorm(embeddings)
|
| 150 |
+
return embeddings
|
| 151 |
+
|
| 152 |
+
def build(self, input_shape=None):
|
| 153 |
+
if self.built:
|
| 154 |
+
return
|
| 155 |
+
self.built = True
|
| 156 |
+
if getattr(self, "patch_embeddings", None) is not None:
|
| 157 |
+
with tf.name_scope(self.patch_embeddings.name):
|
| 158 |
+
self.patch_embeddings.build([None, None, None, self.config.num_channels])
|
| 159 |
+
if getattr(self, "layernorm", None) is not None:
|
| 160 |
+
with tf.name_scope(self.layernorm.name):
|
| 161 |
+
self.layernorm.build([None, None, None, self.config.hidden_sizes[0]])
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class TFConvNextV2Layer(keras.layers.Layer):
|
| 165 |
+
"""This corresponds to the `Block` class in the original implementation.
|
| 166 |
+
|
| 167 |
+
There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,
|
| 168 |
+
H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back
|
| 169 |
+
|
| 170 |
+
The authors used (2) as they find it slightly faster in PyTorch. Since we already permuted the inputs to follow
|
| 171 |
+
NHWC ordering, we can just apply the operations straight-away without the permutation.
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
config (`ConvNextV2Config`):
|
| 175 |
+
Model configuration class.
|
| 176 |
+
dim (`int`):
|
| 177 |
+
Number of input channels.
|
| 178 |
+
drop_path (`float`, *optional*, defaults to 0.0):
|
| 179 |
+
Stochastic depth rate.
|
| 180 |
+
"""
|
| 181 |
+
|
| 182 |
+
def __init__(self, config: ConvNextV2Config, dim: int, drop_path: float = 0.0, **kwargs):
|
| 183 |
+
super().__init__(**kwargs)
|
| 184 |
+
self.dim = dim
|
| 185 |
+
self.config = config
|
| 186 |
+
self.dwconv = keras.layers.Conv2D(
|
| 187 |
+
filters=dim,
|
| 188 |
+
kernel_size=7,
|
| 189 |
+
padding="same",
|
| 190 |
+
groups=dim,
|
| 191 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 192 |
+
bias_initializer=keras.initializers.Zeros(),
|
| 193 |
+
name="dwconv",
|
| 194 |
+
) # depthwise conv
|
| 195 |
+
self.layernorm = keras.layers.LayerNormalization(
|
| 196 |
+
epsilon=1e-6,
|
| 197 |
+
name="layernorm",
|
| 198 |
+
)
|
| 199 |
+
self.pwconv1 = keras.layers.Dense(
|
| 200 |
+
units=4 * dim,
|
| 201 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 202 |
+
bias_initializer=keras.initializers.Zeros(),
|
| 203 |
+
name="pwconv1",
|
| 204 |
+
) # pointwise/1x1 convs, implemented with linear layers
|
| 205 |
+
self.act = get_tf_activation(config.hidden_act)
|
| 206 |
+
self.grn = TFConvNextV2GRN(config, 4 * dim, dtype=tf.float32, name="grn")
|
| 207 |
+
self.pwconv2 = keras.layers.Dense(
|
| 208 |
+
units=dim,
|
| 209 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 210 |
+
bias_initializer=keras.initializers.Zeros(),
|
| 211 |
+
name="pwconv2",
|
| 212 |
+
)
|
| 213 |
+
# Using `layers.Activation` instead of `tf.identity` to better control `training`
|
| 214 |
+
# behaviour.
|
| 215 |
+
self.drop_path = (
|
| 216 |
+
TFConvNextV2DropPath(drop_path, name="drop_path")
|
| 217 |
+
if drop_path > 0.0
|
| 218 |
+
else keras.layers.Activation("linear", name="drop_path")
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
def call(self, hidden_states, training=False):
|
| 222 |
+
input = hidden_states
|
| 223 |
+
x = self.dwconv(hidden_states)
|
| 224 |
+
x = self.layernorm(x)
|
| 225 |
+
x = self.pwconv1(x)
|
| 226 |
+
x = self.act(x)
|
| 227 |
+
x = self.grn(x)
|
| 228 |
+
x = self.pwconv2(x)
|
| 229 |
+
x = self.drop_path(x, training=training)
|
| 230 |
+
x = input + x
|
| 231 |
+
return x
|
| 232 |
+
|
| 233 |
+
def build(self, input_shape=None):
|
| 234 |
+
if self.built:
|
| 235 |
+
return
|
| 236 |
+
self.built = True
|
| 237 |
+
if getattr(self, "dwconv", None) is not None:
|
| 238 |
+
with tf.name_scope(self.dwconv.name):
|
| 239 |
+
self.dwconv.build([None, None, None, self.dim])
|
| 240 |
+
if getattr(self, "layernorm", None) is not None:
|
| 241 |
+
with tf.name_scope(self.layernorm.name):
|
| 242 |
+
self.layernorm.build([None, None, None, self.dim])
|
| 243 |
+
if getattr(self, "pwconv1", None) is not None:
|
| 244 |
+
with tf.name_scope(self.pwconv1.name):
|
| 245 |
+
self.pwconv1.build([None, None, self.dim])
|
| 246 |
+
if getattr(self, "grn", None) is not None:
|
| 247 |
+
with tf.name_scope(self.grn.name):
|
| 248 |
+
self.grn.build(None)
|
| 249 |
+
if getattr(self, "pwconv2", None) is not None:
|
| 250 |
+
with tf.name_scope(self.pwconv2.name):
|
| 251 |
+
self.pwconv2.build([None, None, 4 * self.dim])
|
| 252 |
+
if getattr(self, "drop_path", None) is not None:
|
| 253 |
+
with tf.name_scope(self.drop_path.name):
|
| 254 |
+
self.drop_path.build(None)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
# Copied from transformers.models.convnext.modeling_tf_convnext.TFConvNextStage with ConvNext->ConvNextV2
|
| 258 |
+
class TFConvNextV2Stage(keras.layers.Layer):
|
| 259 |
+
"""ConvNextV2 stage, consisting of an optional downsampling layer + multiple residual blocks.
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
config (`ConvNextV2V2Config`):
|
| 263 |
+
Model configuration class.
|
| 264 |
+
in_channels (`int`):
|
| 265 |
+
Number of input channels.
|
| 266 |
+
out_channels (`int`):
|
| 267 |
+
Number of output channels.
|
| 268 |
+
depth (`int`):
|
| 269 |
+
Number of residual blocks.
|
| 270 |
+
drop_path_rates(`List[float]`):
|
| 271 |
+
Stochastic depth rates for each layer.
|
| 272 |
+
"""
|
| 273 |
+
|
| 274 |
+
def __init__(
|
| 275 |
+
self,
|
| 276 |
+
config: ConvNextV2Config,
|
| 277 |
+
in_channels: int,
|
| 278 |
+
out_channels: int,
|
| 279 |
+
kernel_size: int = 2,
|
| 280 |
+
stride: int = 2,
|
| 281 |
+
depth: int = 2,
|
| 282 |
+
drop_path_rates: Optional[List[float]] = None,
|
| 283 |
+
**kwargs,
|
| 284 |
+
):
|
| 285 |
+
super().__init__(**kwargs)
|
| 286 |
+
if in_channels != out_channels or stride > 1:
|
| 287 |
+
self.downsampling_layer = [
|
| 288 |
+
keras.layers.LayerNormalization(
|
| 289 |
+
epsilon=1e-6,
|
| 290 |
+
name="downsampling_layer.0",
|
| 291 |
+
),
|
| 292 |
+
# Inputs to this layer will follow NHWC format since we
|
| 293 |
+
# transposed the inputs from NCHW to NHWC in the `TFConvNextV2Embeddings`
|
| 294 |
+
# layer. All the outputs throughout the model will be in NHWC
|
| 295 |
+
# from this point on until the output where we again change to
|
| 296 |
+
# NCHW.
|
| 297 |
+
keras.layers.Conv2D(
|
| 298 |
+
filters=out_channels,
|
| 299 |
+
kernel_size=kernel_size,
|
| 300 |
+
strides=stride,
|
| 301 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 302 |
+
bias_initializer=keras.initializers.Zeros(),
|
| 303 |
+
name="downsampling_layer.1",
|
| 304 |
+
),
|
| 305 |
+
]
|
| 306 |
+
else:
|
| 307 |
+
self.downsampling_layer = [tf.identity]
|
| 308 |
+
|
| 309 |
+
drop_path_rates = drop_path_rates or [0.0] * depth
|
| 310 |
+
self.layers = [
|
| 311 |
+
TFConvNextV2Layer(
|
| 312 |
+
config,
|
| 313 |
+
dim=out_channels,
|
| 314 |
+
drop_path=drop_path_rates[j],
|
| 315 |
+
name=f"layers.{j}",
|
| 316 |
+
)
|
| 317 |
+
for j in range(depth)
|
| 318 |
+
]
|
| 319 |
+
self.in_channels = in_channels
|
| 320 |
+
self.out_channels = out_channels
|
| 321 |
+
self.stride = stride
|
| 322 |
+
|
| 323 |
+
def call(self, hidden_states):
|
| 324 |
+
for layer in self.downsampling_layer:
|
| 325 |
+
hidden_states = layer(hidden_states)
|
| 326 |
+
for layer in self.layers:
|
| 327 |
+
hidden_states = layer(hidden_states)
|
| 328 |
+
return hidden_states
|
| 329 |
+
|
| 330 |
+
def build(self, input_shape=None):
|
| 331 |
+
if self.built:
|
| 332 |
+
return
|
| 333 |
+
self.built = True
|
| 334 |
+
if getattr(self, "layers", None) is not None:
|
| 335 |
+
for layer in self.layers:
|
| 336 |
+
with tf.name_scope(layer.name):
|
| 337 |
+
layer.build(None)
|
| 338 |
+
if self.in_channels != self.out_channels or self.stride > 1:
|
| 339 |
+
with tf.name_scope(self.downsampling_layer[0].name):
|
| 340 |
+
self.downsampling_layer[0].build([None, None, None, self.in_channels])
|
| 341 |
+
with tf.name_scope(self.downsampling_layer[1].name):
|
| 342 |
+
self.downsampling_layer[1].build([None, None, None, self.in_channels])
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
class TFConvNextV2Encoder(keras.layers.Layer):
|
| 346 |
+
def __init__(self, config: ConvNextV2Config, **kwargs):
|
| 347 |
+
super().__init__(**kwargs)
|
| 348 |
+
self.stages = []
|
| 349 |
+
drop_path_rates = tf.linspace(0.0, config.drop_path_rate, sum(config.depths))
|
| 350 |
+
drop_path_rates = tf.split(drop_path_rates, config.depths)
|
| 351 |
+
drop_path_rates = [x.numpy().tolist() for x in drop_path_rates]
|
| 352 |
+
prev_chs = config.hidden_sizes[0]
|
| 353 |
+
for i in range(config.num_stages):
|
| 354 |
+
out_chs = config.hidden_sizes[i]
|
| 355 |
+
stage = TFConvNextV2Stage(
|
| 356 |
+
config,
|
| 357 |
+
in_channels=prev_chs,
|
| 358 |
+
out_channels=out_chs,
|
| 359 |
+
stride=2 if i > 0 else 1,
|
| 360 |
+
depth=config.depths[i],
|
| 361 |
+
drop_path_rates=drop_path_rates[i],
|
| 362 |
+
name=f"stages.{i}",
|
| 363 |
+
)
|
| 364 |
+
self.stages.append(stage)
|
| 365 |
+
prev_chs = out_chs
|
| 366 |
+
|
| 367 |
+
def call(
|
| 368 |
+
self,
|
| 369 |
+
hidden_states: tf.Tensor,
|
| 370 |
+
output_hidden_states: Optional[bool] = False,
|
| 371 |
+
return_dict: Optional[bool] = True,
|
| 372 |
+
) -> Union[Tuple, TFBaseModelOutputWithNoAttention]:
|
| 373 |
+
all_hidden_states = () if output_hidden_states else None
|
| 374 |
+
|
| 375 |
+
for i, layer_module in enumerate(self.stages):
|
| 376 |
+
if output_hidden_states:
|
| 377 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 378 |
+
|
| 379 |
+
hidden_states = layer_module(hidden_states)
|
| 380 |
+
|
| 381 |
+
if output_hidden_states:
|
| 382 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 383 |
+
|
| 384 |
+
if not return_dict:
|
| 385 |
+
return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
|
| 386 |
+
|
| 387 |
+
return TFBaseModelOutputWithNoAttention(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
|
| 388 |
+
|
| 389 |
+
def build(self, input_shape=None):
|
| 390 |
+
for stage in self.stages:
|
| 391 |
+
with tf.name_scope(stage.name):
|
| 392 |
+
stage.build(None)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
@keras_serializable
|
| 396 |
+
class TFConvNextV2MainLayer(keras.layers.Layer):
|
| 397 |
+
config_class = ConvNextV2Config
|
| 398 |
+
|
| 399 |
+
def __init__(self, config: ConvNextV2Config, **kwargs):
|
| 400 |
+
super().__init__(**kwargs)
|
| 401 |
+
|
| 402 |
+
self.config = config
|
| 403 |
+
self.embeddings = TFConvNextV2Embeddings(config, name="embeddings")
|
| 404 |
+
self.encoder = TFConvNextV2Encoder(config, name="encoder")
|
| 405 |
+
self.layernorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm")
|
| 406 |
+
# We are setting the `data_format` like so because from here on we will revert to the
|
| 407 |
+
# NCHW output format
|
| 408 |
+
self.pooler = keras.layers.GlobalAvgPool2D(data_format="channels_last")
|
| 409 |
+
|
| 410 |
+
@unpack_inputs
|
| 411 |
+
def call(
|
| 412 |
+
self,
|
| 413 |
+
pixel_values: TFModelInputType | None = None,
|
| 414 |
+
output_hidden_states: Optional[bool] = None,
|
| 415 |
+
return_dict: Optional[bool] = None,
|
| 416 |
+
training: bool = False,
|
| 417 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
| 418 |
+
output_hidden_states = (
|
| 419 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 420 |
+
)
|
| 421 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 422 |
+
|
| 423 |
+
if pixel_values is None:
|
| 424 |
+
raise ValueError("You have to specify pixel_values")
|
| 425 |
+
|
| 426 |
+
embedding_output = self.embeddings(pixel_values, training=training)
|
| 427 |
+
|
| 428 |
+
encoder_outputs = self.encoder(
|
| 429 |
+
embedding_output,
|
| 430 |
+
output_hidden_states=output_hidden_states,
|
| 431 |
+
return_dict=return_dict,
|
| 432 |
+
training=training,
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
last_hidden_state = encoder_outputs[0]
|
| 436 |
+
|
| 437 |
+
# Change to NCHW output format have uniformity in the modules
|
| 438 |
+
pooled_output = self.pooler(last_hidden_state)
|
| 439 |
+
last_hidden_state = tf.transpose(last_hidden_state, perm=(0, 3, 1, 2))
|
| 440 |
+
pooled_output = self.layernorm(pooled_output)
|
| 441 |
+
|
| 442 |
+
# Change the other hidden state outputs to NCHW as well
|
| 443 |
+
if output_hidden_states:
|
| 444 |
+
hidden_states = tuple([tf.transpose(h, perm=(0, 3, 1, 2)) for h in encoder_outputs[1]])
|
| 445 |
+
|
| 446 |
+
if not return_dict:
|
| 447 |
+
hidden_states = hidden_states if output_hidden_states else ()
|
| 448 |
+
return (last_hidden_state, pooled_output) + hidden_states
|
| 449 |
+
|
| 450 |
+
return TFBaseModelOutputWithPoolingAndNoAttention(
|
| 451 |
+
last_hidden_state=last_hidden_state,
|
| 452 |
+
pooler_output=pooled_output,
|
| 453 |
+
hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states,
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
def build(self, input_shape=None):
|
| 457 |
+
if self.built:
|
| 458 |
+
return
|
| 459 |
+
self.built = True
|
| 460 |
+
if getattr(self, "embeddings", None) is not None:
|
| 461 |
+
with tf.name_scope(self.embeddings.name):
|
| 462 |
+
self.embeddings.build(None)
|
| 463 |
+
if getattr(self, "encoder", None) is not None:
|
| 464 |
+
with tf.name_scope(self.encoder.name):
|
| 465 |
+
self.encoder.build(None)
|
| 466 |
+
if getattr(self, "layernorm", None) is not None:
|
| 467 |
+
with tf.name_scope(self.layernorm.name):
|
| 468 |
+
self.layernorm.build([None, self.config.hidden_sizes[-1]])
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
class TFConvNextV2PreTrainedModel(TFPreTrainedModel):
|
| 472 |
+
"""
|
| 473 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 474 |
+
models.
|
| 475 |
+
"""
|
| 476 |
+
|
| 477 |
+
config_class = ConvNextV2Config
|
| 478 |
+
base_model_prefix = "convnextv2"
|
| 479 |
+
main_input_name = "pixel_values"
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
CONVNEXTV2_START_DOCSTRING = r"""
|
| 483 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 484 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 485 |
+
etc.)
|
| 486 |
+
|
| 487 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 488 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 489 |
+
behavior.
|
| 490 |
+
|
| 491 |
+
<Tip>
|
| 492 |
+
|
| 493 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 494 |
+
|
| 495 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 496 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 497 |
+
|
| 498 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 499 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 500 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 501 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 502 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 503 |
+
positional argument:
|
| 504 |
+
|
| 505 |
+
- a single Tensor with `pixel_values` only and nothing else: `model(pixel_values)`
|
| 506 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 507 |
+
`model([pixel_values, attention_mask])` or `model([pixel_values, attention_mask, token_type_ids])`
|
| 508 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 509 |
+
`model({"pixel_values": pixel_values, "token_type_ids": token_type_ids})`
|
| 510 |
+
|
| 511 |
+
Note that when creating models and layers with
|
| 512 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 513 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 514 |
+
|
| 515 |
+
</Tip>
|
| 516 |
+
|
| 517 |
+
Parameters:
|
| 518 |
+
config ([`ConvNextV2Config`]): Model configuration class with all the parameters of the model.
|
| 519 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 520 |
+
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 521 |
+
"""
|
| 522 |
+
|
| 523 |
+
CONVNEXTV2_INPUTS_DOCSTRING = r"""
|
| 524 |
+
Args:
|
| 525 |
+
pixel_values (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]`, `Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `(batch_size, num_channels, height, width)`):
|
| 526 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 527 |
+
[`ConvNextImageProcessor.__call__`] for details.
|
| 528 |
+
|
| 529 |
+
output_hidden_states (`bool`, *optional*):
|
| 530 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 531 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 532 |
+
used instead.
|
| 533 |
+
return_dict (`bool`, *optional*):
|
| 534 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 535 |
+
eager mode, in graph mode the value will always be set to `True`.
|
| 536 |
+
"""
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
@add_start_docstrings(
|
| 540 |
+
"The bare ConvNextV2 model outputting raw features without any specific head on top.",
|
| 541 |
+
CONVNEXTV2_START_DOCSTRING,
|
| 542 |
+
)
|
| 543 |
+
class TFConvNextV2Model(TFConvNextV2PreTrainedModel):
|
| 544 |
+
def __init__(self, config: ConvNextV2Config, *inputs, **kwargs):
|
| 545 |
+
super().__init__(config, *inputs, **kwargs)
|
| 546 |
+
self.convnextv2 = TFConvNextV2MainLayer(config, name="convnextv2")
|
| 547 |
+
|
| 548 |
+
@unpack_inputs
|
| 549 |
+
@add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)
|
| 550 |
+
@add_code_sample_docstrings(
|
| 551 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 552 |
+
output_type=TFBaseModelOutputWithPoolingAndNoAttention,
|
| 553 |
+
config_class=_CONFIG_FOR_DOC,
|
| 554 |
+
modality="vision",
|
| 555 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 556 |
+
)
|
| 557 |
+
def call(
|
| 558 |
+
self,
|
| 559 |
+
pixel_values: TFModelInputType | None = None,
|
| 560 |
+
output_hidden_states: Optional[bool] = None,
|
| 561 |
+
return_dict: Optional[bool] = None,
|
| 562 |
+
training: bool = False,
|
| 563 |
+
) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]:
|
| 564 |
+
output_hidden_states = (
|
| 565 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 566 |
+
)
|
| 567 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 568 |
+
|
| 569 |
+
if pixel_values is None:
|
| 570 |
+
raise ValueError("You have to specify pixel_values")
|
| 571 |
+
|
| 572 |
+
outputs = self.convnextv2(
|
| 573 |
+
pixel_values=pixel_values,
|
| 574 |
+
output_hidden_states=output_hidden_states,
|
| 575 |
+
return_dict=return_dict,
|
| 576 |
+
training=training,
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
if not return_dict:
|
| 580 |
+
return outputs[:]
|
| 581 |
+
|
| 582 |
+
return TFBaseModelOutputWithPoolingAndNoAttention(
|
| 583 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 584 |
+
pooler_output=outputs.pooler_output,
|
| 585 |
+
hidden_states=outputs.hidden_states,
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
def build(self, input_shape=None):
|
| 589 |
+
if self.built:
|
| 590 |
+
return
|
| 591 |
+
self.built = True
|
| 592 |
+
if getattr(self, "convnextv2", None) is not None:
|
| 593 |
+
with tf.name_scope(self.convnextv2.name):
|
| 594 |
+
self.convnextv2.build(None)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
@add_start_docstrings(
|
| 598 |
+
"""
|
| 599 |
+
ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
|
| 600 |
+
ImageNet.
|
| 601 |
+
""",
|
| 602 |
+
CONVNEXTV2_START_DOCSTRING,
|
| 603 |
+
)
|
| 604 |
+
class TFConvNextV2ForImageClassification(TFConvNextV2PreTrainedModel, TFSequenceClassificationLoss):
|
| 605 |
+
def __init__(self, config: ConvNextV2Config, *inputs, **kwargs):
|
| 606 |
+
super().__init__(config, *inputs, **kwargs)
|
| 607 |
+
|
| 608 |
+
self.num_labels = config.num_labels
|
| 609 |
+
self.convnextv2 = TFConvNextV2MainLayer(config, name="convnextv2")
|
| 610 |
+
|
| 611 |
+
# Classifier head
|
| 612 |
+
self.classifier = keras.layers.Dense(
|
| 613 |
+
units=config.num_labels,
|
| 614 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 615 |
+
bias_initializer=keras.initializers.Zeros(),
|
| 616 |
+
name="classifier",
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
@unpack_inputs
|
| 620 |
+
@add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)
|
| 621 |
+
@add_code_sample_docstrings(
|
| 622 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
| 623 |
+
output_type=TFImageClassifierOutputWithNoAttention,
|
| 624 |
+
config_class=_CONFIG_FOR_DOC,
|
| 625 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
| 626 |
+
)
|
| 627 |
+
def call(
|
| 628 |
+
self,
|
| 629 |
+
pixel_values: TFModelInputType | None = None,
|
| 630 |
+
output_hidden_states: Optional[bool] = None,
|
| 631 |
+
return_dict: Optional[bool] = None,
|
| 632 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 633 |
+
training: Optional[bool] = False,
|
| 634 |
+
) -> Union[TFImageClassifierOutputWithNoAttention, Tuple[tf.Tensor]]:
|
| 635 |
+
r"""
|
| 636 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
|
| 637 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 638 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 639 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 640 |
+
"""
|
| 641 |
+
output_hidden_states = (
|
| 642 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 643 |
+
)
|
| 644 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 645 |
+
|
| 646 |
+
if pixel_values is None:
|
| 647 |
+
raise ValueError("You have to specify pixel_values")
|
| 648 |
+
|
| 649 |
+
outputs = self.convnextv2(
|
| 650 |
+
pixel_values,
|
| 651 |
+
output_hidden_states=output_hidden_states,
|
| 652 |
+
return_dict=return_dict,
|
| 653 |
+
training=training,
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
pooled_output = outputs.pooler_output if return_dict else outputs[1]
|
| 657 |
+
|
| 658 |
+
logits = self.classifier(pooled_output)
|
| 659 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
|
| 660 |
+
|
| 661 |
+
if not return_dict:
|
| 662 |
+
output = (logits,) + outputs[2:]
|
| 663 |
+
return ((loss,) + output) if loss is not None else output
|
| 664 |
+
|
| 665 |
+
return TFImageClassifierOutputWithNoAttention(
|
| 666 |
+
loss=loss,
|
| 667 |
+
logits=logits,
|
| 668 |
+
hidden_states=outputs.hidden_states,
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
def build(self, input_shape=None):
|
| 672 |
+
if self.built:
|
| 673 |
+
return
|
| 674 |
+
self.built = True
|
| 675 |
+
if getattr(self, "convnextv2", None) is not None:
|
| 676 |
+
with tf.name_scope(self.convnextv2.name):
|
| 677 |
+
self.convnextv2.build(None)
|
| 678 |
+
if getattr(self, "classifier", None) is not None:
|
| 679 |
+
with tf.name_scope(self.classifier.name):
|
| 680 |
+
self.classifier.build([None, None, self.config.hidden_sizes[-1]])
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
__all__ = ["TFConvNextV2ForImageClassification", "TFConvNextV2Model", "TFConvNextV2PreTrainedModel"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpm/__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 .tokenization_cpm import *
|
| 22 |
+
from .tokenization_cpm_fast 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__)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpm/tokenization_cpm.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import unicodedata
|
| 19 |
+
from shutil import copyfile
|
| 20 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import sentencepiece as spm
|
| 23 |
+
|
| 24 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 25 |
+
from ...utils import SPIECE_UNDERLINE, logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class CpmTokenizer(PreTrainedTokenizer):
|
| 34 |
+
"""Runs pre-tokenization with Jieba segmentation tool. It is used in CPM models."""
|
| 35 |
+
|
| 36 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 37 |
+
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
vocab_file,
|
| 41 |
+
do_lower_case=False,
|
| 42 |
+
remove_space=True,
|
| 43 |
+
keep_accents=False,
|
| 44 |
+
bos_token="<s>",
|
| 45 |
+
eos_token="</s>",
|
| 46 |
+
unk_token="<unk>",
|
| 47 |
+
sep_token="<sep>",
|
| 48 |
+
pad_token="<pad>",
|
| 49 |
+
cls_token="<cls>",
|
| 50 |
+
mask_token="<mask>",
|
| 51 |
+
additional_special_tokens=["<eop>", "<eod>"],
|
| 52 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
| 53 |
+
**kwargs,
|
| 54 |
+
) -> None:
|
| 55 |
+
"""
|
| 56 |
+
Construct a CPM tokenizer. Based on [Jieba](https://pypi.org/project/jieba/) and
|
| 57 |
+
[SentencePiece](https://github.com/google/sentencepiece).
|
| 58 |
+
|
| 59 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
|
| 60 |
+
refer to this superclass for more information regarding those methods.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
vocab_file (`str`):
|
| 64 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
|
| 65 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 66 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether to lowercase the input when tokenizing.
|
| 68 |
+
remove_space (`bool`, *optional*, defaults to `True`):
|
| 69 |
+
Whether to strip the text when tokenizing (removing excess spaces before and after the string).
|
| 70 |
+
keep_accents (`bool`, *optional*, defaults to `False`):
|
| 71 |
+
Whether to keep accents when tokenizing.
|
| 72 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 73 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
|
| 74 |
+
token.
|
| 75 |
+
|
| 76 |
+
<Tip>
|
| 77 |
+
|
| 78 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 79 |
+
sequence. The token used is the `cls_token`.
|
| 80 |
+
|
| 81 |
+
</Tip>
|
| 82 |
+
|
| 83 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 84 |
+
The end of sequence token.
|
| 85 |
+
|
| 86 |
+
<Tip>
|
| 87 |
+
|
| 88 |
+
When building a sequence using special tokens, this is not the token that is used for the end of
|
| 89 |
+
sequence. The token used is the `sep_token`.
|
| 90 |
+
|
| 91 |
+
</Tip>
|
| 92 |
+
|
| 93 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 94 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
|
| 95 |
+
this token instead.
|
| 96 |
+
sep_token (`str`, *optional*, defaults to `"<sep>"`):
|
| 97 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
|
| 98 |
+
for sequence classification or for a text and a question for question answering. It is also used as the
|
| 99 |
+
last token of a sequence built with special tokens.
|
| 100 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 101 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 102 |
+
cls_token (`str`, *optional*, defaults to `"<cls>"`):
|
| 103 |
+
The classifier token which is used when doing sequence classification (classification of the whole
|
| 104 |
+
sequence instead of per-token classification). It is the first token of the sequence when built with
|
| 105 |
+
special tokens.
|
| 106 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 107 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 108 |
+
modeling. This is the token which the model will try to predict.
|
| 109 |
+
additional_special_tokens (`List[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
|
| 110 |
+
Additional special tokens used by the tokenizer.
|
| 111 |
+
|
| 112 |
+
Attributes:
|
| 113 |
+
sp_model (`SentencePieceProcessor`):
|
| 114 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 115 |
+
"""
|
| 116 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 117 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 118 |
+
|
| 119 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 120 |
+
|
| 121 |
+
self.do_lower_case = do_lower_case
|
| 122 |
+
self.remove_space = remove_space
|
| 123 |
+
self.keep_accents = keep_accents
|
| 124 |
+
self.vocab_file = vocab_file
|
| 125 |
+
|
| 126 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 127 |
+
self.sp_model.Load(vocab_file)
|
| 128 |
+
|
| 129 |
+
try:
|
| 130 |
+
import jieba
|
| 131 |
+
except ModuleNotFoundError as error:
|
| 132 |
+
raise error.__class__(
|
| 133 |
+
"You need to install jieba to use CpmTokenizer or CpmTokenizerFast. "
|
| 134 |
+
"See https://pypi.org/project/jieba/ for installation."
|
| 135 |
+
)
|
| 136 |
+
self.jieba = jieba
|
| 137 |
+
self.translator = str.maketrans(" \n", "\u2582\u2583")
|
| 138 |
+
|
| 139 |
+
super().__init__(
|
| 140 |
+
do_lower_case=do_lower_case,
|
| 141 |
+
remove_space=remove_space,
|
| 142 |
+
keep_accents=keep_accents,
|
| 143 |
+
bos_token=bos_token,
|
| 144 |
+
eos_token=eos_token,
|
| 145 |
+
unk_token=unk_token,
|
| 146 |
+
sep_token=sep_token,
|
| 147 |
+
pad_token=pad_token,
|
| 148 |
+
cls_token=cls_token,
|
| 149 |
+
mask_token=mask_token,
|
| 150 |
+
additional_special_tokens=additional_special_tokens,
|
| 151 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 152 |
+
**kwargs,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
self._pad_token_type_id = 3
|
| 156 |
+
|
| 157 |
+
@property
|
| 158 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
|
| 159 |
+
def vocab_size(self):
|
| 160 |
+
return len(self.sp_model)
|
| 161 |
+
|
| 162 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.get_vocab
|
| 163 |
+
def get_vocab(self):
|
| 164 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 165 |
+
vocab.update(self.added_tokens_encoder)
|
| 166 |
+
return vocab
|
| 167 |
+
|
| 168 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.__getstate__
|
| 169 |
+
def __getstate__(self):
|
| 170 |
+
state = self.__dict__.copy()
|
| 171 |
+
state["sp_model"] = None
|
| 172 |
+
return state
|
| 173 |
+
|
| 174 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.__setstate__
|
| 175 |
+
def __setstate__(self, d):
|
| 176 |
+
self.__dict__ = d
|
| 177 |
+
|
| 178 |
+
# for backward compatibility
|
| 179 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 180 |
+
self.sp_model_kwargs = {}
|
| 181 |
+
|
| 182 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 183 |
+
self.sp_model.Load(self.vocab_file)
|
| 184 |
+
|
| 185 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.preprocess_text
|
| 186 |
+
def preprocess_text(self, inputs):
|
| 187 |
+
if self.remove_space:
|
| 188 |
+
outputs = " ".join(inputs.strip().split())
|
| 189 |
+
else:
|
| 190 |
+
outputs = inputs
|
| 191 |
+
outputs = outputs.replace("``", '"').replace("''", '"')
|
| 192 |
+
|
| 193 |
+
if not self.keep_accents:
|
| 194 |
+
outputs = unicodedata.normalize("NFKD", outputs)
|
| 195 |
+
outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
|
| 196 |
+
if self.do_lower_case:
|
| 197 |
+
outputs = outputs.lower()
|
| 198 |
+
|
| 199 |
+
return outputs
|
| 200 |
+
|
| 201 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer._tokenize
|
| 202 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 203 |
+
"""Tokenize a string."""
|
| 204 |
+
text = self.preprocess_text(text)
|
| 205 |
+
pieces = self.sp_model.encode(text, out_type=str)
|
| 206 |
+
new_pieces = []
|
| 207 |
+
for piece in pieces:
|
| 208 |
+
if len(piece) > 1 and piece[-1] == str(",") and piece[-2].isdigit():
|
| 209 |
+
cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
|
| 210 |
+
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
|
| 211 |
+
if len(cur_pieces[0]) == 1:
|
| 212 |
+
cur_pieces = cur_pieces[1:]
|
| 213 |
+
else:
|
| 214 |
+
cur_pieces[0] = cur_pieces[0][1:]
|
| 215 |
+
cur_pieces.append(piece[-1])
|
| 216 |
+
new_pieces.extend(cur_pieces)
|
| 217 |
+
else:
|
| 218 |
+
new_pieces.append(piece)
|
| 219 |
+
|
| 220 |
+
return new_pieces
|
| 221 |
+
|
| 222 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer._convert_token_to_id
|
| 223 |
+
def _convert_token_to_id(self, token):
|
| 224 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 225 |
+
return self.sp_model.PieceToId(token)
|
| 226 |
+
|
| 227 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer._convert_id_to_token
|
| 228 |
+
def _convert_id_to_token(self, index):
|
| 229 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 230 |
+
return self.sp_model.IdToPiece(index)
|
| 231 |
+
|
| 232 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.convert_tokens_to_string
|
| 233 |
+
def convert_tokens_to_string(self, tokens):
|
| 234 |
+
"""Converts a sequence of tokens (strings for sub-words) in a single string."""
|
| 235 |
+
out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
|
| 236 |
+
return out_string
|
| 237 |
+
|
| 238 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.build_inputs_with_special_tokens
|
| 239 |
+
def build_inputs_with_special_tokens(
|
| 240 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 241 |
+
) -> List[int]:
|
| 242 |
+
"""
|
| 243 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 244 |
+
adding special tokens. An XLNet sequence has the following format:
|
| 245 |
+
|
| 246 |
+
- single sequence: `X <sep> <cls>`
|
| 247 |
+
- pair of sequences: `A <sep> B <sep> <cls>`
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
token_ids_0 (`List[int]`):
|
| 251 |
+
List of IDs to which the special tokens will be added.
|
| 252 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 253 |
+
Optional second list of IDs for sequence pairs.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 257 |
+
"""
|
| 258 |
+
sep = [self.sep_token_id]
|
| 259 |
+
cls = [self.cls_token_id]
|
| 260 |
+
if token_ids_1 is None:
|
| 261 |
+
return token_ids_0 + sep + cls
|
| 262 |
+
return token_ids_0 + sep + token_ids_1 + sep + cls
|
| 263 |
+
|
| 264 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.get_special_tokens_mask
|
| 265 |
+
def get_special_tokens_mask(
|
| 266 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 267 |
+
) -> List[int]:
|
| 268 |
+
"""
|
| 269 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 270 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 271 |
+
|
| 272 |
+
Args:
|
| 273 |
+
token_ids_0 (`List[int]`):
|
| 274 |
+
List of IDs.
|
| 275 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 276 |
+
Optional second list of IDs for sequence pairs.
|
| 277 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 278 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 279 |
+
|
| 280 |
+
Returns:
|
| 281 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 282 |
+
"""
|
| 283 |
+
|
| 284 |
+
if already_has_special_tokens:
|
| 285 |
+
return super().get_special_tokens_mask(
|
| 286 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
if token_ids_1 is not None:
|
| 290 |
+
return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1, 1]
|
| 291 |
+
return ([0] * len(token_ids_0)) + [1, 1]
|
| 292 |
+
|
| 293 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.create_token_type_ids_from_sequences
|
| 294 |
+
def create_token_type_ids_from_sequences(
|
| 295 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 296 |
+
) -> List[int]:
|
| 297 |
+
"""
|
| 298 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
|
| 299 |
+
sequence pair mask has the following format:
|
| 300 |
+
|
| 301 |
+
```
|
| 302 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 303 |
+
| first sequence | second sequence |
|
| 304 |
+
```
|
| 305 |
+
|
| 306 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
token_ids_0 (`List[int]`):
|
| 310 |
+
List of IDs.
|
| 311 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 312 |
+
Optional second list of IDs for sequence pairs.
|
| 313 |
+
|
| 314 |
+
Returns:
|
| 315 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 316 |
+
"""
|
| 317 |
+
sep = [self.sep_token_id]
|
| 318 |
+
cls_segment_id = [2]
|
| 319 |
+
|
| 320 |
+
if token_ids_1 is None:
|
| 321 |
+
return len(token_ids_0 + sep) * [0] + cls_segment_id
|
| 322 |
+
return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
|
| 323 |
+
|
| 324 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.save_vocabulary
|
| 325 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 326 |
+
if not os.path.isdir(save_directory):
|
| 327 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 328 |
+
return
|
| 329 |
+
out_vocab_file = os.path.join(
|
| 330 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 334 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 335 |
+
elif not os.path.isfile(self.vocab_file):
|
| 336 |
+
with open(out_vocab_file, "wb") as fi:
|
| 337 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 338 |
+
fi.write(content_spiece_model)
|
| 339 |
+
|
| 340 |
+
return (out_vocab_file,)
|
| 341 |
+
|
| 342 |
+
def _decode(self, *args, **kwargs):
|
| 343 |
+
text = super()._decode(*args, **kwargs)
|
| 344 |
+
text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
|
| 345 |
+
return text
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
__all__ = ["CpmTokenizer"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpm/tokenization_cpm_fast.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from shutil import copyfile
|
| 19 |
+
from typing import List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
from ...tokenization_utils_fast import AddedToken, PreTrainedTokenizerFast
|
| 22 |
+
from ...utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class CpmTokenizerFast(PreTrainedTokenizerFast):
|
| 31 |
+
"""Runs pre-tokenization with Jieba segmentation tool. It is used in CPM models."""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
vocab_file=None,
|
| 36 |
+
tokenizer_file=None,
|
| 37 |
+
do_lower_case=False,
|
| 38 |
+
remove_space=True,
|
| 39 |
+
keep_accents=False,
|
| 40 |
+
bos_token="<s>",
|
| 41 |
+
eos_token="</s>",
|
| 42 |
+
unk_token="<unk>",
|
| 43 |
+
sep_token="<sep>",
|
| 44 |
+
pad_token="<pad>",
|
| 45 |
+
cls_token="<cls>",
|
| 46 |
+
mask_token="<mask>",
|
| 47 |
+
additional_special_tokens=["<eop>", "<eod>"],
|
| 48 |
+
**kwargs,
|
| 49 |
+
):
|
| 50 |
+
"""
|
| 51 |
+
Construct a CPM tokenizer. Based on [Jieba](https://pypi.org/project/jieba/) and
|
| 52 |
+
[SentencePiece](https://github.com/google/sentencepiece).
|
| 53 |
+
|
| 54 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
|
| 55 |
+
refer to this superclass for more information regarding those methods.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
vocab_file (`str`):
|
| 59 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
|
| 60 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 61 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 62 |
+
Whether to lowercase the input when tokenizing.
|
| 63 |
+
remove_space (`bool`, *optional*, defaults to `True`):
|
| 64 |
+
Whether to strip the text when tokenizing (removing excess spaces before and after the string).
|
| 65 |
+
keep_accents (`bool`, *optional*, defaults to `False`):
|
| 66 |
+
Whether to keep accents when tokenizing.
|
| 67 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 68 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
|
| 69 |
+
token.
|
| 70 |
+
|
| 71 |
+
<Tip>
|
| 72 |
+
|
| 73 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 74 |
+
sequence. The token used is the `cls_token`.
|
| 75 |
+
|
| 76 |
+
</Tip>
|
| 77 |
+
|
| 78 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 79 |
+
The end of sequence token.
|
| 80 |
+
|
| 81 |
+
<Tip>
|
| 82 |
+
|
| 83 |
+
When building a sequence using special tokens, this is not the token that is used for the end of
|
| 84 |
+
sequence. The token used is the `sep_token`.
|
| 85 |
+
|
| 86 |
+
</Tip>
|
| 87 |
+
|
| 88 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 89 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
|
| 90 |
+
this token instead.
|
| 91 |
+
sep_token (`str`, *optional*, defaults to `"<sep>"`):
|
| 92 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
|
| 93 |
+
for sequence classification or for a text and a question for question answering. It is also used as the
|
| 94 |
+
last token of a sequence built with special tokens.
|
| 95 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 96 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 97 |
+
cls_token (`str`, *optional*, defaults to `"<cls>"`):
|
| 98 |
+
The classifier token which is used when doing sequence classification (classification of the whole
|
| 99 |
+
sequence instead of per-token classification). It is the first token of the sequence when built with
|
| 100 |
+
special tokens.
|
| 101 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 102 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 103 |
+
modeling. This is the token which the model will try to predict.
|
| 104 |
+
additional_special_tokens (`List[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
|
| 105 |
+
Additional special tokens used by the tokenizer.
|
| 106 |
+
|
| 107 |
+
Attributes:
|
| 108 |
+
sp_model (`SentencePieceProcessor`):
|
| 109 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 110 |
+
"""
|
| 111 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 112 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 113 |
+
|
| 114 |
+
super().__init__(
|
| 115 |
+
vocab_file=vocab_file,
|
| 116 |
+
tokenizer_file=tokenizer_file,
|
| 117 |
+
do_lower_case=do_lower_case,
|
| 118 |
+
remove_space=remove_space,
|
| 119 |
+
keep_accents=keep_accents,
|
| 120 |
+
bos_token=bos_token,
|
| 121 |
+
eos_token=eos_token,
|
| 122 |
+
unk_token=unk_token,
|
| 123 |
+
sep_token=sep_token,
|
| 124 |
+
pad_token=pad_token,
|
| 125 |
+
cls_token=cls_token,
|
| 126 |
+
mask_token=mask_token,
|
| 127 |
+
additional_special_tokens=additional_special_tokens,
|
| 128 |
+
**kwargs,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
self._pad_token_type_id = 3
|
| 132 |
+
self.do_lower_case = do_lower_case
|
| 133 |
+
self.remove_space = remove_space
|
| 134 |
+
self.keep_accents = keep_accents
|
| 135 |
+
self.vocab_file = vocab_file
|
| 136 |
+
|
| 137 |
+
try:
|
| 138 |
+
import jieba
|
| 139 |
+
except ModuleNotFoundError as error:
|
| 140 |
+
raise error.__class__(
|
| 141 |
+
"You need to install jieba to use CpmTokenizer or CpmTokenizerFast. "
|
| 142 |
+
"See https://pypi.org/project/jieba/ for installation."
|
| 143 |
+
)
|
| 144 |
+
self.jieba = jieba
|
| 145 |
+
self.translator = str.maketrans(" \n", "\u2582\u2583")
|
| 146 |
+
|
| 147 |
+
@property
|
| 148 |
+
def can_save_slow_tokenizer(self) -> bool:
|
| 149 |
+
return os.path.isfile(self.vocab_file) if self.vocab_file else False
|
| 150 |
+
|
| 151 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet_fast.XLNetTokenizerFast.build_inputs_with_special_tokens
|
| 152 |
+
def build_inputs_with_special_tokens(
|
| 153 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 154 |
+
) -> List[int]:
|
| 155 |
+
"""
|
| 156 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 157 |
+
adding special tokens. An XLNet sequence has the following format:
|
| 158 |
+
|
| 159 |
+
- single sequence: `X <sep> <cls>`
|
| 160 |
+
- pair of sequences: `A <sep> B <sep> <cls>`
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
token_ids_0 (`List[int]`):
|
| 164 |
+
List of IDs to which the special tokens will be added.
|
| 165 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 166 |
+
Optional second list of IDs for sequence pairs.
|
| 167 |
+
|
| 168 |
+
Returns:
|
| 169 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 170 |
+
"""
|
| 171 |
+
sep = [self.sep_token_id]
|
| 172 |
+
cls = [self.cls_token_id]
|
| 173 |
+
if token_ids_1 is None:
|
| 174 |
+
return token_ids_0 + sep + cls
|
| 175 |
+
return token_ids_0 + sep + token_ids_1 + sep + cls
|
| 176 |
+
|
| 177 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet_fast.XLNetTokenizerFast.create_token_type_ids_from_sequences
|
| 178 |
+
def create_token_type_ids_from_sequences(
|
| 179 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 180 |
+
) -> List[int]:
|
| 181 |
+
"""
|
| 182 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
|
| 183 |
+
sequence pair mask has the following format:
|
| 184 |
+
|
| 185 |
+
```
|
| 186 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 187 |
+
| first sequence | second sequence |
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
token_ids_0 (`List[int]`):
|
| 194 |
+
List of IDs.
|
| 195 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 196 |
+
Optional second list of IDs for sequence pairs.
|
| 197 |
+
|
| 198 |
+
Returns:
|
| 199 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 200 |
+
"""
|
| 201 |
+
sep = [self.sep_token_id]
|
| 202 |
+
cls_segment_id = [2]
|
| 203 |
+
|
| 204 |
+
if token_ids_1 is None:
|
| 205 |
+
return len(token_ids_0 + sep) * [0] + cls_segment_id
|
| 206 |
+
return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
|
| 207 |
+
|
| 208 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet_fast.XLNetTokenizerFast.save_vocabulary
|
| 209 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 210 |
+
if not self.can_save_slow_tokenizer:
|
| 211 |
+
raise ValueError(
|
| 212 |
+
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
|
| 213 |
+
"tokenizer."
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
if not os.path.isdir(save_directory):
|
| 217 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 218 |
+
return
|
| 219 |
+
out_vocab_file = os.path.join(
|
| 220 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
| 224 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 225 |
+
|
| 226 |
+
return (out_vocab_file,)
|
| 227 |
+
|
| 228 |
+
def _batch_encode_plus(self, batch_text_or_text_pairs, *args, **kwargs):
|
| 229 |
+
batch_text_or_text_pairs = [
|
| 230 |
+
" ".join([x.translate(self.translator) for x in self.jieba.cut(text, cut_all=False)])
|
| 231 |
+
for text in batch_text_or_text_pairs
|
| 232 |
+
]
|
| 233 |
+
return super()._batch_encode_plus(batch_text_or_text_pairs, *args, **kwargs)
|
| 234 |
+
|
| 235 |
+
def _decode(self, *args, **kwargs):
|
| 236 |
+
text = super()._decode(*args, **kwargs)
|
| 237 |
+
text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
|
| 238 |
+
return text
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
__all__ = ["CpmTokenizerFast"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpmant/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_cpmant import *
|
| 22 |
+
from .modeling_cpmant import *
|
| 23 |
+
from .tokenization_cpmant 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__)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpmant/configuration_cpmant.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The OpenBMB Team 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 |
+
"""CPMAnt 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 CpmAntConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`CpmAntModel`]. It is used to instantiate an
|
| 27 |
+
CPMAnt model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 28 |
+
with the defaults will yield a similar configuration to that of the CPMAnt
|
| 29 |
+
[openbmb/cpm-ant-10b](https://huggingface.co/openbmb/cpm-ant-10b) 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 |
+
vocab_size (`int`, *optional*, defaults to 30720):
|
| 36 |
+
Vocabulary size of the CPMAnt model. Defines the number of different tokens that can be represented by the
|
| 37 |
+
`input` passed when calling [`CpmAntModel`].
|
| 38 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 39 |
+
Dimension of the encoder layers.
|
| 40 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 41 |
+
Number of attention heads in the Transformer encoder.
|
| 42 |
+
dim_head (`int`, *optional*, defaults to 128):
|
| 43 |
+
Dimension of attention heads for each attention layer in the Transformer encoder.
|
| 44 |
+
dim_ff (`int`, *optional*, defaults to 10240):
|
| 45 |
+
Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 46 |
+
num_hidden_layers (`int`, *optional*, defaults to 48):
|
| 47 |
+
Number of layers of the Transformer encoder.
|
| 48 |
+
dropout_p (`float`, *optional*, defaults to 0.0):
|
| 49 |
+
The dropout probability for all fully connected layers in the embeddings, encoder.
|
| 50 |
+
position_bias_num_buckets (`int`, *optional*, defaults to 512):
|
| 51 |
+
The number of position_bias buckets.
|
| 52 |
+
position_bias_max_distance (`int`, *optional*, defaults to 2048):
|
| 53 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 54 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 55 |
+
eps (`float`, *optional*, defaults to 1e-06):
|
| 56 |
+
The epsilon used by the layer normalization layers.
|
| 57 |
+
init_std (`float`, *optional*, defaults to 1.0):
|
| 58 |
+
Initialize parameters with std = init_std.
|
| 59 |
+
prompt_types (`int`, *optional*, defaults to 32):
|
| 60 |
+
The type of prompt.
|
| 61 |
+
prompt_length (`int`, *optional*, defaults to 32):
|
| 62 |
+
The length of prompt.
|
| 63 |
+
segment_types (`int`, *optional*, defaults to 32):
|
| 64 |
+
The type of segment.
|
| 65 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 66 |
+
Whether to use cache.
|
| 67 |
+
|
| 68 |
+
Example:
|
| 69 |
+
|
| 70 |
+
```python
|
| 71 |
+
>>> from transformers import CpmAntModel, CpmAntConfig
|
| 72 |
+
|
| 73 |
+
>>> # Initializing a CPMAnt cpm-ant-10b style configuration
|
| 74 |
+
>>> configuration = CpmAntConfig()
|
| 75 |
+
|
| 76 |
+
>>> # Initializing a model from the cpm-ant-10b style configuration
|
| 77 |
+
>>> model = CpmAntModel(configuration)
|
| 78 |
+
|
| 79 |
+
>>> # Accessing the model configuration
|
| 80 |
+
>>> configuration = model.config
|
| 81 |
+
```"""
|
| 82 |
+
|
| 83 |
+
model_type = "cpmant"
|
| 84 |
+
|
| 85 |
+
def __init__(
|
| 86 |
+
self,
|
| 87 |
+
vocab_size: int = 30720,
|
| 88 |
+
hidden_size: int = 4096,
|
| 89 |
+
num_attention_heads: int = 32,
|
| 90 |
+
dim_head: int = 128,
|
| 91 |
+
dim_ff: int = 10240,
|
| 92 |
+
num_hidden_layers: int = 48,
|
| 93 |
+
dropout_p: int = 0.0,
|
| 94 |
+
position_bias_num_buckets: int = 512,
|
| 95 |
+
position_bias_max_distance: int = 2048,
|
| 96 |
+
eps: int = 1e-6,
|
| 97 |
+
init_std: float = 1.0,
|
| 98 |
+
prompt_types: int = 32,
|
| 99 |
+
prompt_length: int = 32,
|
| 100 |
+
segment_types: int = 32,
|
| 101 |
+
use_cache: bool = True,
|
| 102 |
+
**kwargs,
|
| 103 |
+
):
|
| 104 |
+
super().__init__(**kwargs)
|
| 105 |
+
self.prompt_types = prompt_types
|
| 106 |
+
self.prompt_length = prompt_length
|
| 107 |
+
self.segment_types = segment_types
|
| 108 |
+
self.hidden_size = hidden_size
|
| 109 |
+
self.num_attention_heads = num_attention_heads
|
| 110 |
+
self.dim_head = dim_head
|
| 111 |
+
self.dim_ff = dim_ff
|
| 112 |
+
self.num_hidden_layers = num_hidden_layers
|
| 113 |
+
self.position_bias_num_buckets = position_bias_num_buckets
|
| 114 |
+
self.position_bias_max_distance = position_bias_max_distance
|
| 115 |
+
self.dropout_p = dropout_p
|
| 116 |
+
self.eps = eps
|
| 117 |
+
self.use_cache = use_cache
|
| 118 |
+
self.vocab_size = vocab_size
|
| 119 |
+
self.init_std = init_std
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
__all__ = ["CpmAntConfig"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpmant/modeling_cpmant.py
ADDED
|
@@ -0,0 +1,860 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The OpenBMB Team 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 CPMAnt"""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from typing import List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
from torch.nn import CrossEntropyLoss
|
| 25 |
+
|
| 26 |
+
from ...activations import ACT2FN
|
| 27 |
+
from ...generation import GenerationMixin
|
| 28 |
+
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 29 |
+
from ...modeling_utils import PreTrainedModel
|
| 30 |
+
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 31 |
+
from .configuration_cpmant import CpmAntConfig
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
logger = logging.get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
_CHECKPOINT_FOR_DOC = "openbmb/cpm-ant-10b"
|
| 37 |
+
_CONFIG_FOR_DOC = "CpmAntConfig"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class CpmAntLayerNorm(nn.Module):
|
| 41 |
+
"""
|
| 42 |
+
We use Root Mean Square (RMS) Layer Normalization, please see https://arxiv.org/abs/1910.07467 for details."
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(self, config: CpmAntConfig):
|
| 46 |
+
super().__init__()
|
| 47 |
+
|
| 48 |
+
self.eps = config.eps
|
| 49 |
+
self.dim_norm = config.hidden_size
|
| 50 |
+
self.weight = nn.Parameter(torch.empty(config.hidden_size))
|
| 51 |
+
|
| 52 |
+
def forward(self, hidden_states: torch.Tensor):
|
| 53 |
+
"""
|
| 54 |
+
Args:
|
| 55 |
+
hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`)
|
| 56 |
+
"""
|
| 57 |
+
if hidden_states.size(-1) != self.dim_norm:
|
| 58 |
+
raise AssertionError("hidden_states.size(-1) != self.dim_norm")
|
| 59 |
+
old_dtype = hidden_states.dtype
|
| 60 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
|
| 61 |
+
hidden_states = (hidden_states * torch.rsqrt(variance + self.eps)).to(old_dtype) * self.weight
|
| 62 |
+
return hidden_states
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class CpmAntAttention(nn.Module):
|
| 66 |
+
def __init__(self, config: CpmAntConfig):
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.dim_model = config.hidden_size
|
| 69 |
+
self.num_heads = config.num_attention_heads
|
| 70 |
+
self.dim_head = config.dim_head
|
| 71 |
+
|
| 72 |
+
self.project_q = nn.Linear(self.dim_model, self.num_heads * self.dim_head, bias=False)
|
| 73 |
+
self.project_k = nn.Linear(self.dim_model, self.num_heads * self.dim_head, bias=False)
|
| 74 |
+
self.project_v = nn.Linear(self.dim_model, self.num_heads * self.dim_head, bias=False)
|
| 75 |
+
|
| 76 |
+
self.attention_out = nn.Linear(self.num_heads * self.dim_head, self.dim_model, bias=False)
|
| 77 |
+
|
| 78 |
+
self.softmax = torch.nn.Softmax(dim=-1)
|
| 79 |
+
|
| 80 |
+
if config.dropout_p is not None:
|
| 81 |
+
self.dropout = torch.nn.Dropout(p=config.dropout_p)
|
| 82 |
+
else:
|
| 83 |
+
self.dropout = None
|
| 84 |
+
|
| 85 |
+
def forward(
|
| 86 |
+
self,
|
| 87 |
+
hidden_q: torch.Tensor,
|
| 88 |
+
hidden_kv: torch.Tensor,
|
| 89 |
+
attention_mask: torch.BoolTensor,
|
| 90 |
+
position_bias: torch.Tensor,
|
| 91 |
+
output_attentions: Optional[bool] = False,
|
| 92 |
+
past_key_values: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 93 |
+
use_cache: Optional[bool] = None,
|
| 94 |
+
):
|
| 95 |
+
"""
|
| 96 |
+
Args:
|
| 97 |
+
hidden_q (`torch.Tensor`):
|
| 98 |
+
Input of transformer block(self-attention block). It can be the raw embedding of a batch of sequences.
|
| 99 |
+
hidden_kv (`torch.Tensor` of shape `(batch, len_k, dim_model)`)):
|
| 100 |
+
Tensor *key_value* and *query* of shape `(batch, len_k, dim_model)`
|
| 101 |
+
attention_mask (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
|
| 102 |
+
Avoid invalid areas to participate in the calculation of self-attention.
|
| 103 |
+
position_bias (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
|
| 104 |
+
Provide positional information to self-attention block.
|
| 105 |
+
output_attentions (`bool`, *optional*):
|
| 106 |
+
Whether or not to return the attentions tensors of all attention layers.
|
| 107 |
+
past_key_values (`Tuple[torch.Tensor, torch.Tensor]`, *optional*):
|
| 108 |
+
Cached past key and value projection states.
|
| 109 |
+
use_cache (`bool`, *optional*):
|
| 110 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 111 |
+
(see `past_key_values`).
|
| 112 |
+
"""
|
| 113 |
+
batch_size = hidden_q.size(0)
|
| 114 |
+
len_q = hidden_q.size(1)
|
| 115 |
+
len_k = hidden_kv.size(1)
|
| 116 |
+
|
| 117 |
+
query = self.project_q(hidden_q)
|
| 118 |
+
key = self.project_k(hidden_kv)
|
| 119 |
+
value = self.project_v(hidden_kv)
|
| 120 |
+
|
| 121 |
+
query = query.view(batch_size, len_q, self.num_heads, self.dim_head).permute(0, 2, 1, 3)
|
| 122 |
+
key = key.view(batch_size, len_k, self.num_heads, self.dim_head).permute(0, 2, 1, 3)
|
| 123 |
+
value = value.view(batch_size, len_k, self.num_heads, self.dim_head).permute(0, 2, 1, 3)
|
| 124 |
+
|
| 125 |
+
if past_key_values is not None:
|
| 126 |
+
key = torch.cat([past_key_values[0], key], dim=-2)
|
| 127 |
+
value = torch.cat([past_key_values[1], value], dim=-2)
|
| 128 |
+
len_k = key.size(-2)
|
| 129 |
+
|
| 130 |
+
# (batch_size, num_heads, len_q, dim_head) @ (batch_size, num_heads, dim_head, len_k) -> (batch_size, num_heads, len_q, len_k)
|
| 131 |
+
score = torch.matmul(query, key.transpose(-1, -2)) / math.sqrt(self.dim_head)
|
| 132 |
+
score = score + position_bias
|
| 133 |
+
|
| 134 |
+
score = torch.masked_fill(
|
| 135 |
+
score,
|
| 136 |
+
attention_mask.view(batch_size, 1, len_q, len_k) == torch.tensor(False),
|
| 137 |
+
torch.scalar_tensor(float("-inf"), device=score.device, dtype=score.dtype),
|
| 138 |
+
)
|
| 139 |
+
score = self.softmax(score)
|
| 140 |
+
|
| 141 |
+
score = torch.masked_fill(
|
| 142 |
+
score,
|
| 143 |
+
attention_mask.view(batch_size, 1, len_q, len_k) == torch.tensor(False),
|
| 144 |
+
torch.scalar_tensor(0, device=score.device, dtype=score.dtype),
|
| 145 |
+
)
|
| 146 |
+
if output_attentions:
|
| 147 |
+
attn_weights = score
|
| 148 |
+
else:
|
| 149 |
+
attn_weights = None
|
| 150 |
+
|
| 151 |
+
if self.dropout is not None:
|
| 152 |
+
score = self.dropout(score)
|
| 153 |
+
|
| 154 |
+
# (batch_size, num_heads, len_q, len_k) @ (batch_size, num_heads, len_k, dim_head) -> (batch_size, num_heads, len_q, dim_head)
|
| 155 |
+
score = torch.matmul(score, value)
|
| 156 |
+
|
| 157 |
+
score = score.view(batch_size, self.num_heads, len_q, self.dim_head).permute(0, 2, 1, 3)
|
| 158 |
+
score = score.contiguous().view(batch_size, len_q, self.num_heads * self.dim_head)
|
| 159 |
+
|
| 160 |
+
score = self.attention_out(score)
|
| 161 |
+
|
| 162 |
+
past_key_values = None
|
| 163 |
+
if use_cache:
|
| 164 |
+
past_key_values = (key, value)
|
| 165 |
+
|
| 166 |
+
return score, attn_weights, past_key_values
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class CpmAntSelfAttentionBlock(nn.Module):
|
| 170 |
+
def __init__(self, config: CpmAntConfig):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.layernorm_before_attention = CpmAntLayerNorm(config)
|
| 173 |
+
self.self_attention = CpmAntAttention(config)
|
| 174 |
+
if config.dropout_p:
|
| 175 |
+
self.dropout = torch.nn.Dropout(config.dropout_p)
|
| 176 |
+
else:
|
| 177 |
+
self.dropout = None
|
| 178 |
+
|
| 179 |
+
def forward(
|
| 180 |
+
self,
|
| 181 |
+
hidden_states: torch.Tensor,
|
| 182 |
+
attention_mask: torch.Tensor,
|
| 183 |
+
position_bias: Optional[torch.Tensor] = None,
|
| 184 |
+
output_attentions: Optional[bool] = False,
|
| 185 |
+
past_key_values: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 186 |
+
use_cache: Optional[bool] = None,
|
| 187 |
+
):
|
| 188 |
+
"""
|
| 189 |
+
Args:
|
| 190 |
+
hidden_states (`torch.Tensor` of shape `(batch, len_seq, dim_model)`):
|
| 191 |
+
Input of transformer block(self-attention block). It can be the raw embedding of a batch of sequences.
|
| 192 |
+
attention_mask (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
|
| 193 |
+
Avoid invalid areas to participate in the calculation of self-attention.
|
| 194 |
+
position_bias (`torch.Tensor` of shape `(batch, len_seq, len_seq)`):
|
| 195 |
+
Provide positional information to self-attention block.
|
| 196 |
+
output_attentions (`bool`, *optional*):
|
| 197 |
+
Whether or not to return the attentions tensors of all attention layers.
|
| 198 |
+
past_key_values (`Tuple(torch.FloatTensor)`, *optional*):
|
| 199 |
+
Cached past key and value projection states.
|
| 200 |
+
use_cache (`bool`, *optional*):
|
| 201 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 202 |
+
(see `past_key_values`).
|
| 203 |
+
"""
|
| 204 |
+
outputs = self.layernorm_before_attention(hidden_states)
|
| 205 |
+
outputs = self.self_attention(
|
| 206 |
+
outputs, outputs, attention_mask, position_bias, output_attentions, past_key_values, use_cache
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
outputs, attn_weights, current_key_value = outputs
|
| 210 |
+
|
| 211 |
+
if self.dropout is not None:
|
| 212 |
+
outputs = self.dropout(outputs)
|
| 213 |
+
hidden_states = hidden_states + outputs
|
| 214 |
+
|
| 215 |
+
return hidden_states, attn_weights, current_key_value
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class CpmAntDenseGatedACT(nn.Module):
|
| 219 |
+
def __init__(self, config: CpmAntConfig):
|
| 220 |
+
super().__init__()
|
| 221 |
+
self.w_0 = nn.Linear(config.hidden_size, config.dim_ff, bias=False)
|
| 222 |
+
self.w_1 = nn.Linear(config.hidden_size, config.dim_ff, bias=False)
|
| 223 |
+
self.act = torch.nn.GELU()
|
| 224 |
+
|
| 225 |
+
def forward(self, hidden_states: torch.Tensor):
|
| 226 |
+
"""Transform an input tensor from one feature space to another via a nonlinear operation
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`)
|
| 230 |
+
"""
|
| 231 |
+
gate_score = self.act(self.w_0(hidden_states))
|
| 232 |
+
hidden_states = self.w_1(hidden_states)
|
| 233 |
+
|
| 234 |
+
hidden_states = gate_score * hidden_states
|
| 235 |
+
return hidden_states
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class CpmAntFeedForward(nn.Module):
|
| 239 |
+
def __init__(self, config: CpmAntConfig):
|
| 240 |
+
super().__init__()
|
| 241 |
+
self.w_in = CpmAntDenseGatedACT(config)
|
| 242 |
+
if config.dropout_p is not None:
|
| 243 |
+
self.dropout = torch.nn.Dropout(config.dropout_p)
|
| 244 |
+
else:
|
| 245 |
+
self.dropout = None
|
| 246 |
+
|
| 247 |
+
self.w_out = nn.Linear(config.dim_ff, config.hidden_size, bias=False)
|
| 248 |
+
|
| 249 |
+
def forward(self, hidden_states: torch.Tensor):
|
| 250 |
+
"""
|
| 251 |
+
Args:
|
| 252 |
+
hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`)
|
| 253 |
+
"""
|
| 254 |
+
hidden_states = self.w_in(hidden_states)
|
| 255 |
+
|
| 256 |
+
if self.dropout is not None:
|
| 257 |
+
hidden_states = self.dropout(hidden_states)
|
| 258 |
+
|
| 259 |
+
hidden_states = self.w_out(hidden_states)
|
| 260 |
+
|
| 261 |
+
return hidden_states
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class CpmAntFFNBlock(nn.Module):
|
| 265 |
+
def __init__(self, config: CpmAntConfig):
|
| 266 |
+
super().__init__()
|
| 267 |
+
self.layernorm_before_ffn = CpmAntLayerNorm(config)
|
| 268 |
+
self.ffn = CpmAntFeedForward(config)
|
| 269 |
+
if config.dropout_p:
|
| 270 |
+
self.dropout = torch.nn.Dropout(config.dropout_p)
|
| 271 |
+
else:
|
| 272 |
+
self.dropout = None
|
| 273 |
+
|
| 274 |
+
def forward(
|
| 275 |
+
self,
|
| 276 |
+
hidden_states: torch.Tensor,
|
| 277 |
+
):
|
| 278 |
+
"""
|
| 279 |
+
Args:
|
| 280 |
+
hidden_states (`torch.Tensor` of shape `(batch, len_seq, dim_model)`):
|
| 281 |
+
Hidden states before feed forward layer.
|
| 282 |
+
"""
|
| 283 |
+
ln_outputs = self.layernorm_before_ffn(hidden_states)
|
| 284 |
+
outputs = self.ffn(ln_outputs)
|
| 285 |
+
if self.dropout is not None:
|
| 286 |
+
outputs = self.dropout(outputs)
|
| 287 |
+
hidden_states = hidden_states + outputs
|
| 288 |
+
return hidden_states
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class CpmAntTransformerBlock(nn.Module):
|
| 292 |
+
def __init__(self, config: CpmAntConfig):
|
| 293 |
+
super().__init__()
|
| 294 |
+
self.self_att = CpmAntSelfAttentionBlock(config)
|
| 295 |
+
self.ffn = CpmAntFFNBlock(config)
|
| 296 |
+
|
| 297 |
+
def forward(
|
| 298 |
+
self,
|
| 299 |
+
hidden_states: torch.Tensor,
|
| 300 |
+
attention_mask: torch.Tensor,
|
| 301 |
+
position_bias: Optional[torch.Tensor] = None,
|
| 302 |
+
output_attentions: Optional[bool] = False,
|
| 303 |
+
past_key_values: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 304 |
+
use_cache: Optional[bool] = None,
|
| 305 |
+
):
|
| 306 |
+
"""
|
| 307 |
+
Args:
|
| 308 |
+
hidden_states (`torch.Tensor`):
|
| 309 |
+
Input to the layer of shape `(batch, seq_len, dim_model)`
|
| 310 |
+
attention_mask (`torch.Tensor`):
|
| 311 |
+
Avoid invalid areas to participate in the calculation of shape `(batch, seq_len, seq_len)`
|
| 312 |
+
position_bias (`torch.Tensor`):
|
| 313 |
+
Provides position information to attention mechanism of shape `(num_heads, seq_len, seq_len)`
|
| 314 |
+
output_attentions (`bool`, *optional*):
|
| 315 |
+
Whether or not to return the attentions tensors of all attention layers.
|
| 316 |
+
past_key_values (`Tuple[torch.Tensor, torch.Tensor])`, *optional*):
|
| 317 |
+
Cached past key and value projection states
|
| 318 |
+
use_cache (`bool`, *optional*):
|
| 319 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 320 |
+
(see `past_key_values`).
|
| 321 |
+
"""
|
| 322 |
+
hidden_states = self.self_att(
|
| 323 |
+
hidden_states,
|
| 324 |
+
attention_mask=attention_mask,
|
| 325 |
+
position_bias=position_bias,
|
| 326 |
+
output_attentions=output_attentions,
|
| 327 |
+
past_key_values=past_key_values,
|
| 328 |
+
use_cache=use_cache,
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
hidden_states, attn_weights, current_key_value = hidden_states
|
| 332 |
+
|
| 333 |
+
hidden_states = self.ffn(hidden_states)
|
| 334 |
+
|
| 335 |
+
return hidden_states, attn_weights, current_key_value
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class CpmAntEncoder(nn.Module):
|
| 339 |
+
def __init__(self, config: CpmAntConfig):
|
| 340 |
+
super().__init__()
|
| 341 |
+
self.num_layers = config.num_hidden_layers
|
| 342 |
+
self.layers = nn.ModuleList([CpmAntTransformerBlock(config) for ith in range(self.num_layers)])
|
| 343 |
+
|
| 344 |
+
self.output_layernorm = CpmAntLayerNorm(config)
|
| 345 |
+
|
| 346 |
+
def forward(
|
| 347 |
+
self,
|
| 348 |
+
hidden_states: torch.Tensor,
|
| 349 |
+
attention_mask: torch.Tensor,
|
| 350 |
+
position_bias: torch.Tensor,
|
| 351 |
+
output_attentions: Optional[bool] = None,
|
| 352 |
+
output_hidden_states: Optional[bool] = None,
|
| 353 |
+
past_key_values: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 354 |
+
use_cache: Optional[bool] = None,
|
| 355 |
+
):
|
| 356 |
+
"""
|
| 357 |
+
Args:
|
| 358 |
+
hidden_states (`torch.Tensor`):
|
| 359 |
+
Input to the layer of shape `(batch, seq_len, dim_model)`
|
| 360 |
+
attention_mask (`torch.Tensor`):
|
| 361 |
+
Avoid invalid areas to participate in the calculation of shape `(batch, seq_len, seq_len)`
|
| 362 |
+
position_bias (`torch.Tensor`):
|
| 363 |
+
Provides position information to attention mechanism of shape `(num_heads, seq_len, seq_len)`
|
| 364 |
+
output_attentions (`bool`, *optional*):
|
| 365 |
+
Whether or not to return the attentions tensors of all attention layers.
|
| 366 |
+
output_hidden_states (`bool`, *optional*):
|
| 367 |
+
Whether or not to return the hidden states of all layers.
|
| 368 |
+
past_key_values (`Tuple[torch.Tensor, torch.Tensor])`, *optional*):
|
| 369 |
+
Cached past key and value projection states
|
| 370 |
+
use_cache (`bool`, *optional*):
|
| 371 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 372 |
+
(see `past_key_values`).
|
| 373 |
+
"""
|
| 374 |
+
all_hidden_states = () if output_hidden_states else None
|
| 375 |
+
all_self_attns = () if output_attentions else None
|
| 376 |
+
current_key_values = () if use_cache else None
|
| 377 |
+
|
| 378 |
+
for i, layer in enumerate(self.layers):
|
| 379 |
+
if output_hidden_states:
|
| 380 |
+
all_hidden_states += (hidden_states,)
|
| 381 |
+
layer_outputs = layer(
|
| 382 |
+
hidden_states,
|
| 383 |
+
attention_mask,
|
| 384 |
+
position_bias,
|
| 385 |
+
output_attentions=output_attentions,
|
| 386 |
+
past_key_values=past_key_values[i] if past_key_values else None,
|
| 387 |
+
use_cache=use_cache,
|
| 388 |
+
)
|
| 389 |
+
hidden_states, attn_weights, current_key_value = layer_outputs
|
| 390 |
+
if output_attentions:
|
| 391 |
+
all_self_attns += (attn_weights,)
|
| 392 |
+
if current_key_value is not None:
|
| 393 |
+
current_key_values = current_key_values + (current_key_value,)
|
| 394 |
+
|
| 395 |
+
hidden_states = self.output_layernorm(hidden_states)
|
| 396 |
+
|
| 397 |
+
if output_hidden_states:
|
| 398 |
+
all_hidden_states += (hidden_states,)
|
| 399 |
+
|
| 400 |
+
return hidden_states, current_key_values, all_hidden_states, all_self_attns
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->CPMAnt
|
| 404 |
+
class CpmAntIntermediate(nn.Module):
|
| 405 |
+
def __init__(self, config):
|
| 406 |
+
super().__init__()
|
| 407 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 408 |
+
if isinstance(config.hidden_act, str):
|
| 409 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 410 |
+
else:
|
| 411 |
+
self.intermediate_act_fn = config.hidden_act
|
| 412 |
+
|
| 413 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 414 |
+
hidden_states = self.dense(hidden_states)
|
| 415 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 416 |
+
return hidden_states
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
class CpmAntSegmentPositionEmbedding(nn.Module):
|
| 420 |
+
def __init__(self, config: CpmAntConfig):
|
| 421 |
+
super().__init__()
|
| 422 |
+
|
| 423 |
+
self.num_heads = config.num_attention_heads
|
| 424 |
+
self.num_buckets = config.position_bias_num_buckets
|
| 425 |
+
self.max_distance = config.position_bias_max_distance
|
| 426 |
+
self.num_segments = config.segment_types
|
| 427 |
+
|
| 428 |
+
self.relative_attention_bias = nn.Parameter(
|
| 429 |
+
torch.empty(
|
| 430 |
+
config.segment_types * config.segment_types + config.position_bias_num_buckets,
|
| 431 |
+
config.num_attention_heads,
|
| 432 |
+
)
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
def forward(
|
| 436 |
+
self,
|
| 437 |
+
key_pos: torch.Tensor,
|
| 438 |
+
query_pos: torch.Tensor,
|
| 439 |
+
key_segment: torch.Tensor,
|
| 440 |
+
query_segment: torch.Tensor,
|
| 441 |
+
):
|
| 442 |
+
with torch.no_grad():
|
| 443 |
+
batch = key_pos.size(0)
|
| 444 |
+
keylen = key_pos.size(1)
|
| 445 |
+
querylen = query_pos.size(1)
|
| 446 |
+
|
| 447 |
+
if key_pos.size(0) != query_pos.size(0):
|
| 448 |
+
raise AssertionError(
|
| 449 |
+
f"key_pos.size(0) should be equal to query_pos.size(0), but got {key_pos.size(0)} and {query_pos.size(0)}!"
|
| 450 |
+
)
|
| 451 |
+
if keylen != key_segment.size(1) or querylen != query_segment.size(1):
|
| 452 |
+
raise AssertionError(
|
| 453 |
+
f"keylen should be equal to key_segment.size(1), but got {keylen} and {key_segment.size(1)}!"
|
| 454 |
+
)
|
| 455 |
+
if querylen != query_segment.size(1):
|
| 456 |
+
raise AssertionError(
|
| 457 |
+
f"querylen should be equal to query_segment.size(1), but got {querylen} and {query_segment.szie(1)}!"
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
key_pos = key_pos.view(batch, -1, keylen)
|
| 461 |
+
query_pos = query_pos.view(batch, querylen, -1)
|
| 462 |
+
key_segment = key_segment.view(batch, -1, keylen)
|
| 463 |
+
query_segment = query_segment.view(batch, querylen, -1)
|
| 464 |
+
|
| 465 |
+
relative_position_bucket = self._segment_relative_position_bucket(query_segment, key_segment)
|
| 466 |
+
relative_position_bucket = relative_position_bucket + self.num_buckets
|
| 467 |
+
|
| 468 |
+
# (batch, len_q, len_k)
|
| 469 |
+
absolute_position_bucket = self._position_bucket(
|
| 470 |
+
torch.arange(keylen, dtype=torch.int32, device=relative_position_bucket.device)[None, :]
|
| 471 |
+
- torch.arange(querylen, dtype=torch.int32, device=relative_position_bucket.device)[:, None],
|
| 472 |
+
num_buckets=self.num_buckets,
|
| 473 |
+
max_distance=self.max_distance,
|
| 474 |
+
)
|
| 475 |
+
relative_position_bucket = torch.where(
|
| 476 |
+
(key_segment == query_segment),
|
| 477 |
+
absolute_position_bucket[None, :, :],
|
| 478 |
+
relative_position_bucket,
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
# (batch, len_q, len_k, num_heads)
|
| 482 |
+
embeds = F.embedding(relative_position_bucket, self.relative_attention_bias)
|
| 483 |
+
# (batch, num_heads, len_q, len_k)
|
| 484 |
+
embeds = embeds.permute(0, 3, 1, 2).contiguous()
|
| 485 |
+
return embeds
|
| 486 |
+
|
| 487 |
+
def _segment_relative_position_bucket(self, query_segment, key_segment):
|
| 488 |
+
return query_segment * self.num_segments + key_segment
|
| 489 |
+
|
| 490 |
+
def _position_bucket(self, relative_position, num_buckets=32, max_distance=128):
|
| 491 |
+
relative_buckets = 0
|
| 492 |
+
# always bidirectional in CPMAnt
|
| 493 |
+
num_buckets //= 2
|
| 494 |
+
relative_buckets = (relative_position > 0).to(torch.int32) * num_buckets
|
| 495 |
+
relative_position = torch.abs(relative_position)
|
| 496 |
+
max_exact = num_buckets // 2
|
| 497 |
+
is_small = relative_position < max_exact
|
| 498 |
+
relative_postion_if_large = max_exact + (
|
| 499 |
+
torch.log(relative_position.float() / max_exact)
|
| 500 |
+
/ math.log(max_distance / max_exact)
|
| 501 |
+
* (num_buckets - max_exact)
|
| 502 |
+
).to(torch.int32)
|
| 503 |
+
relative_postion_if_large = torch.min(
|
| 504 |
+
relative_postion_if_large,
|
| 505 |
+
torch.full_like(relative_postion_if_large, num_buckets - 1),
|
| 506 |
+
)
|
| 507 |
+
relative_buckets += torch.where(is_small, relative_position.to(torch.int32), relative_postion_if_large)
|
| 508 |
+
return relative_buckets
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->CPMAnt
|
| 512 |
+
class CpmAntOutput(nn.Module):
|
| 513 |
+
def __init__(self, config):
|
| 514 |
+
super().__init__()
|
| 515 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 516 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 517 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 518 |
+
|
| 519 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 520 |
+
hidden_states = self.dense(hidden_states)
|
| 521 |
+
hidden_states = self.dropout(hidden_states)
|
| 522 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 523 |
+
return hidden_states
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
class CpmAntPreTrainedModel(PreTrainedModel):
|
| 527 |
+
"""
|
| 528 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 529 |
+
models.
|
| 530 |
+
"""
|
| 531 |
+
|
| 532 |
+
config_class = CpmAntConfig
|
| 533 |
+
base_model_prefix = "cpmant"
|
| 534 |
+
|
| 535 |
+
def _init_weights(self, module):
|
| 536 |
+
"""Initialize the weights"""
|
| 537 |
+
if isinstance(module, nn.Linear):
|
| 538 |
+
module.weight.data.normal_(mean=0.0, std=self.config.init_std)
|
| 539 |
+
if module.bias is not None:
|
| 540 |
+
module.bias.data.zero_()
|
| 541 |
+
elif isinstance(module, nn.Embedding):
|
| 542 |
+
module.weight.data.normal_(mean=0.0, std=self.config.init_std)
|
| 543 |
+
if module.padding_idx is not None:
|
| 544 |
+
module.weight.data[module.padding_idx].zero_()
|
| 545 |
+
elif isinstance(module, nn.LayerNorm):
|
| 546 |
+
module.bias.data.zero_()
|
| 547 |
+
module.weight.data.fill_(1.0)
|
| 548 |
+
elif isinstance(module, CpmAntLayerNorm):
|
| 549 |
+
module.weight.data.fill_(1.0)
|
| 550 |
+
elif isinstance(module, CpmAntSegmentPositionEmbedding):
|
| 551 |
+
module.relative_attention_bias.data.normal_(mean=0.0, std=self.config.init_std)
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
CPMANT_START_DOCSTRING = r"""
|
| 555 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
|
| 556 |
+
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 557 |
+
behavior.
|
| 558 |
+
|
| 559 |
+
Parameters
|
| 560 |
+
config ([`~CpmAntConfig`]): Model configuration class with all the parameters of the
|
| 561 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 562 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 563 |
+
"""
|
| 564 |
+
|
| 565 |
+
CPMANT_INPUTS_DOCSTRING = r"""
|
| 566 |
+
Args:
|
| 567 |
+
input_ids (`torch.Tensor` of shape `(batch_size, seq_len)`):
|
| 568 |
+
Indices of input sequence tokens in the vocabulary.
|
| 569 |
+
|
| 570 |
+
Indices can be obtained using [`CPMAntTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 571 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 572 |
+
|
| 573 |
+
[What are input IDs?](../glossary#input-ids)
|
| 574 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 575 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 576 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 577 |
+
use_cache (`bool`, *optional*):
|
| 578 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 579 |
+
`past_key_values`).
|
| 580 |
+
output_attentions (`bool`, *optional*):
|
| 581 |
+
Whether or not to return the attentions tensors of all attention layers.
|
| 582 |
+
output_hidden_states (`bool`, *optional*):
|
| 583 |
+
Whether or not to return the hidden states of all layers.
|
| 584 |
+
return_dict (`bool`, *optional*):
|
| 585 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 586 |
+
"""
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
@add_start_docstrings(
|
| 590 |
+
"The bare CPMAnt Model outputting raw hidden-states without any specific head on top.",
|
| 591 |
+
CPMANT_START_DOCSTRING,
|
| 592 |
+
)
|
| 593 |
+
class CpmAntModel(CpmAntPreTrainedModel):
|
| 594 |
+
def __init__(self, config: CpmAntConfig):
|
| 595 |
+
super().__init__(config)
|
| 596 |
+
self.encoder = CpmAntEncoder(config)
|
| 597 |
+
self.segment_embedding = nn.Embedding(config.segment_types, config.hidden_size)
|
| 598 |
+
self.input_embedding = nn.Embedding(
|
| 599 |
+
config.vocab_size + config.prompt_types * config.prompt_length, config.hidden_size
|
| 600 |
+
)
|
| 601 |
+
self.position_bias = CpmAntSegmentPositionEmbedding(config)
|
| 602 |
+
self.prompt_length = config.prompt_length
|
| 603 |
+
self.vocab_size = config.vocab_size
|
| 604 |
+
|
| 605 |
+
self.post_init()
|
| 606 |
+
|
| 607 |
+
def get_input_embeddings(self):
|
| 608 |
+
return self.input_embedding
|
| 609 |
+
|
| 610 |
+
def set_input_embeddings(self, embeddings, **kwargs):
|
| 611 |
+
self.input_embedding = embeddings
|
| 612 |
+
|
| 613 |
+
def _prepare_attention_mask(self, input_ids, span, context, length):
|
| 614 |
+
batch = input_ids.size(0)
|
| 615 |
+
seqlen = input_ids.size(1)
|
| 616 |
+
device = input_ids.device
|
| 617 |
+
directional_mask_2d = torch.arange(seqlen, device=device) <= torch.arange(seqlen, device=device).view(-1, 1)
|
| 618 |
+
attention_mask = context[:, None, :] | (
|
| 619 |
+
context[:, :, None].logical_not() & directional_mask_2d.view(1, seqlen, seqlen)
|
| 620 |
+
)
|
| 621 |
+
attention_mask = attention_mask & (span[:, None, :] == span[:, :, None])
|
| 622 |
+
# mask for left padding
|
| 623 |
+
mask_1d = (
|
| 624 |
+
torch.tensor(list(range(seqlen - self.prompt_length))[::-1], device=device)[None, :].repeat(batch, 1)
|
| 625 |
+
< length[:, None]
|
| 626 |
+
)
|
| 627 |
+
mask_1d = torch.cat((torch.ones(batch, self.prompt_length, device=device).bool(), mask_1d), dim=1)
|
| 628 |
+
attention_mask = mask_1d.view(batch, seqlen, 1) & mask_1d.view(batch, 1, seqlen) & attention_mask
|
| 629 |
+
return attention_mask
|
| 630 |
+
|
| 631 |
+
@add_start_docstrings_to_model_forward(CPMANT_INPUTS_DOCSTRING)
|
| 632 |
+
@add_code_sample_docstrings(
|
| 633 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 634 |
+
output_type=BaseModelOutputWithPast,
|
| 635 |
+
config_class=_CONFIG_FOR_DOC,
|
| 636 |
+
)
|
| 637 |
+
def forward(
|
| 638 |
+
self,
|
| 639 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 640 |
+
output_attentions: Optional[bool] = None,
|
| 641 |
+
output_hidden_states: Optional[bool] = None,
|
| 642 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
| 643 |
+
use_cache: Optional[bool] = None,
|
| 644 |
+
return_dict: Optional[bool] = None,
|
| 645 |
+
**kwargs,
|
| 646 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPast]:
|
| 647 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 648 |
+
output_hidden_states = (
|
| 649 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 650 |
+
)
|
| 651 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 652 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 653 |
+
|
| 654 |
+
# add prompts ahead
|
| 655 |
+
if input_ids.dtype != torch.int32:
|
| 656 |
+
input_ids = input_ids.to(torch.int32)
|
| 657 |
+
dtype, device = input_ids.dtype, input_ids.device
|
| 658 |
+
segment = torch.where(input_ids != 0, 2, 0).to(dtype=dtype, device=device)
|
| 659 |
+
length = (segment != 0).sum(-1).to(dtype=dtype, device=device)
|
| 660 |
+
input_ids = torch.cat(
|
| 661 |
+
(
|
| 662 |
+
torch.arange(
|
| 663 |
+
self.prompt_length * 2 + self.vocab_size,
|
| 664 |
+
self.prompt_length * 3 + self.vocab_size,
|
| 665 |
+
dtype=dtype,
|
| 666 |
+
device=device,
|
| 667 |
+
).repeat(input_ids.size(0), 1),
|
| 668 |
+
input_ids,
|
| 669 |
+
),
|
| 670 |
+
dim=1,
|
| 671 |
+
)
|
| 672 |
+
batch, seq_length = input_ids.size()
|
| 673 |
+
segment = torch.cat((torch.zeros(batch, self.prompt_length, dtype=dtype, device=device), segment), dim=1)
|
| 674 |
+
context = torch.full((batch, seq_length), 1, dtype=dtype, device=device)
|
| 675 |
+
position = torch.arange(seq_length, dtype=dtype, device=device).repeat(batch, 1)
|
| 676 |
+
span = torch.full((batch, seq_length), 0, dtype=dtype, device=device)
|
| 677 |
+
|
| 678 |
+
if past_key_values is None:
|
| 679 |
+
past_length = 0
|
| 680 |
+
past_key_values = tuple([None] * self.encoder.num_layers)
|
| 681 |
+
input_ids = input_ids.contiguous()
|
| 682 |
+
hidden_states = self.input_embedding(input_ids)
|
| 683 |
+
segment_states = self.segment_embedding(segment)
|
| 684 |
+
hidden_states = hidden_states + segment_states
|
| 685 |
+
else:
|
| 686 |
+
past_length = past_key_values[0][0].size(-2)
|
| 687 |
+
segment_states = self.segment_embedding(segment)
|
| 688 |
+
hidden_states = self.input_embedding(input_ids) + segment_states[:, -1:, :]
|
| 689 |
+
|
| 690 |
+
attention_mask = self._prepare_attention_mask(input_ids, span, context, length)
|
| 691 |
+
position_bias = self.position_bias(position, position, segment, segment)
|
| 692 |
+
|
| 693 |
+
attention_mask = attention_mask[:, past_length:, :]
|
| 694 |
+
position_bias = position_bias[:, :, past_length:, :]
|
| 695 |
+
hidden_states = hidden_states[:, past_length:, :]
|
| 696 |
+
|
| 697 |
+
hidden_states, present_key_values, all_hidden_states, all_attentions = self.encoder(
|
| 698 |
+
hidden_states,
|
| 699 |
+
attention_mask,
|
| 700 |
+
position_bias,
|
| 701 |
+
output_attentions,
|
| 702 |
+
output_hidden_states,
|
| 703 |
+
past_key_values,
|
| 704 |
+
use_cache,
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
if past_length == 0:
|
| 708 |
+
hidden_states = hidden_states[:, self.prompt_length :, :]
|
| 709 |
+
# drop the prompt
|
| 710 |
+
if all_attentions is not None:
|
| 711 |
+
new_attentions = ()
|
| 712 |
+
for attention in all_attentions:
|
| 713 |
+
new_attentions += (attention[:, :, self.prompt_length :, self.prompt_length :],)
|
| 714 |
+
all_attentions = new_attentions
|
| 715 |
+
if all_hidden_states is not None:
|
| 716 |
+
new_hidden_states = ()
|
| 717 |
+
for hidden_state in all_hidden_states:
|
| 718 |
+
new_hidden_states += (hidden_state[:, self.prompt_length :, :],)
|
| 719 |
+
all_hidden_states = new_hidden_states
|
| 720 |
+
|
| 721 |
+
if not return_dict:
|
| 722 |
+
return tuple(
|
| 723 |
+
v for v in [hidden_states, present_key_values, all_hidden_states, all_attentions] if v is not None
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
return BaseModelOutputWithPast(
|
| 727 |
+
last_hidden_state=hidden_states,
|
| 728 |
+
past_key_values=present_key_values,
|
| 729 |
+
hidden_states=all_hidden_states,
|
| 730 |
+
attentions=all_attentions,
|
| 731 |
+
)
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
@add_start_docstrings(
|
| 735 |
+
"""
|
| 736 |
+
The CPMAnt Model with a language modeling head on top (linear layer with weights tied to the input embeddings).
|
| 737 |
+
""",
|
| 738 |
+
CPMANT_START_DOCSTRING,
|
| 739 |
+
)
|
| 740 |
+
class CpmAntForCausalLM(CpmAntPreTrainedModel, GenerationMixin):
|
| 741 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 742 |
+
|
| 743 |
+
def __init__(self, config: CpmAntConfig):
|
| 744 |
+
super().__init__(config)
|
| 745 |
+
self.cpmant = CpmAntModel(config)
|
| 746 |
+
|
| 747 |
+
# lm_head.weight is tied to cpmant.input_embedding.weight
|
| 748 |
+
self.lm_head = nn.Linear(
|
| 749 |
+
config.hidden_size, config.vocab_size + config.prompt_types * config.prompt_length, bias=False
|
| 750 |
+
)
|
| 751 |
+
self.post_init()
|
| 752 |
+
|
| 753 |
+
@add_start_docstrings_to_model_forward(CPMANT_INPUTS_DOCSTRING)
|
| 754 |
+
@add_code_sample_docstrings(
|
| 755 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 756 |
+
output_type=CausalLMOutputWithPast,
|
| 757 |
+
config_class=_CONFIG_FOR_DOC,
|
| 758 |
+
)
|
| 759 |
+
def forward(
|
| 760 |
+
self,
|
| 761 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 762 |
+
past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
|
| 763 |
+
use_cache: Optional[bool] = None,
|
| 764 |
+
output_attentions: Optional[bool] = None,
|
| 765 |
+
output_hidden_states: Optional[bool] = None,
|
| 766 |
+
labels: Optional[torch.Tensor] = None,
|
| 767 |
+
return_dict: Optional[bool] = None,
|
| 768 |
+
attention_mask: Optional[torch.Tensor] = None, # dummy parameter for text-generation pipeline
|
| 769 |
+
**kwargs,
|
| 770 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 771 |
+
r"""
|
| 772 |
+
Args:
|
| 773 |
+
input_ids (`torch.Tensor` of shape `(batch_size, seq_len)`):
|
| 774 |
+
Indices of input sequence tokens in the vocabulary.
|
| 775 |
+
|
| 776 |
+
Indices can be obtained using [`CPMAntTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 777 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 778 |
+
|
| 779 |
+
[What are input IDs?](../glossary#input-ids)
|
| 780 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 781 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 782 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 783 |
+
use_cache (`bool`, *optional*):
|
| 784 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 785 |
+
(see `past_key_values`).
|
| 786 |
+
output_attentions (`bool`, *optional*):
|
| 787 |
+
Whether or not to return the attentions tensors of all attention layers.
|
| 788 |
+
output_hidden_states (`bool`, *optional*):
|
| 789 |
+
Whether or not to return the hidden states of all layers.
|
| 790 |
+
labels (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 791 |
+
Labels for computing the masked language modeling loss.
|
| 792 |
+
return_dict (`bool`, *optional*):
|
| 793 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 794 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 795 |
+
CPMAnt will process attention mask automatically, this parameter is a dummy parameter for
|
| 796 |
+
text-generation pipeline.
|
| 797 |
+
|
| 798 |
+
Example:
|
| 799 |
+
|
| 800 |
+
Text Generation with CpmAntForCausalLM.
|
| 801 |
+
```python
|
| 802 |
+
>>> from transformers import CPMAntTokenizer, CpmAntForCausalLM
|
| 803 |
+
|
| 804 |
+
>>> texts = "今天天气不错,"
|
| 805 |
+
>>> model = CpmAntForCausalLM.from_pretrained("openbmb/cpm-ant-10b")
|
| 806 |
+
>>> tokenizer = CPMAntTokenizer.from_pretrained("openbmb/cpm-ant-10b")
|
| 807 |
+
>>> input_ids = tokenizer(texts, return_tensors="pt")
|
| 808 |
+
>>> outputs = model.generate(**input_ids)
|
| 809 |
+
>>> output_texts = tokenizer.batch_decode(outputs)
|
| 810 |
+
>>> print(output_texts)
|
| 811 |
+
['今天天气不错,阳光明媚,我和妈妈一起去超市买东西。\n在超市里,我看到了一个很好玩的玩具,它的名字叫“机器人”。它有一个圆圆的脑袋,两只圆圆的眼睛,还有一个圆圆的']
|
| 812 |
+
```
|
| 813 |
+
"""
|
| 814 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 815 |
+
|
| 816 |
+
model_output = self.cpmant(
|
| 817 |
+
input_ids, output_attentions, output_hidden_states, past_key_values, use_cache, return_dict
|
| 818 |
+
)
|
| 819 |
+
hidden_states = model_output.last_hidden_state if return_dict else model_output[0]
|
| 820 |
+
|
| 821 |
+
logits = self.lm_head(hidden_states)
|
| 822 |
+
|
| 823 |
+
loss = None
|
| 824 |
+
if labels is not None:
|
| 825 |
+
loss_func = CrossEntropyLoss()
|
| 826 |
+
loss = loss_func(logits.view(-1, logits.size(-1)), labels.view(-1))
|
| 827 |
+
|
| 828 |
+
if not return_dict:
|
| 829 |
+
output = (logits,) + model_output[1:]
|
| 830 |
+
return ((loss,) + output) if loss is not None else output
|
| 831 |
+
|
| 832 |
+
return CausalLMOutputWithPast(
|
| 833 |
+
loss=loss,
|
| 834 |
+
logits=logits,
|
| 835 |
+
past_key_values=model_output.past_key_values,
|
| 836 |
+
hidden_states=model_output.hidden_states,
|
| 837 |
+
attentions=model_output.attentions,
|
| 838 |
+
)
|
| 839 |
+
|
| 840 |
+
def get_input_embeddings(self):
|
| 841 |
+
return self.cpmant.input_embedding
|
| 842 |
+
|
| 843 |
+
def set_input_embeddings(self, embeddings):
|
| 844 |
+
self.cpmant.input_embedding = embeddings
|
| 845 |
+
|
| 846 |
+
def get_output_embeddings(self):
|
| 847 |
+
return self.lm_head
|
| 848 |
+
|
| 849 |
+
def set_output_embeddings(self, new_embeddings):
|
| 850 |
+
self.lm_head = new_embeddings
|
| 851 |
+
|
| 852 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
| 853 |
+
past_key_values = [list(each) if each is not None else each for each in past_key_values]
|
| 854 |
+
for key_value_layer in past_key_values:
|
| 855 |
+
key_value_layer[0] = key_value_layer[0][beam_idx]
|
| 856 |
+
key_value_layer[1] = key_value_layer[1][beam_idx]
|
| 857 |
+
return past_key_values
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
__all__ = ["CpmAntForCausalLM", "CpmAntModel", "CpmAntPreTrainedModel"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cpmant/tokenization_cpmant.py
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The OpenBMB Team 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 CPMAnt."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
import os
|
| 19 |
+
from typing import List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
from transformers.utils import is_jieba_available, requires_backends
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if is_jieba_available():
|
| 25 |
+
import jieba
|
| 26 |
+
|
| 27 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 28 |
+
from ...utils import logging
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def load_vocab(vocab_file):
|
| 37 |
+
"""Loads a vocabulary file into a dictionary."""
|
| 38 |
+
vocab = collections.OrderedDict()
|
| 39 |
+
with open(vocab_file, "r", encoding="utf-8") as reader:
|
| 40 |
+
tokens = reader.readlines()
|
| 41 |
+
for index, token in enumerate(tokens):
|
| 42 |
+
token = token.rstrip("\n")
|
| 43 |
+
vocab[token] = index
|
| 44 |
+
return vocab
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class WordpieceTokenizer:
|
| 48 |
+
def __init__(self, vocab, unk_token="<unk>", max_input_chars_per_word=200):
|
| 49 |
+
self.vocab = vocab
|
| 50 |
+
self.unk_token = unk_token
|
| 51 |
+
self.max_input_chars_per_word = max_input_chars_per_word
|
| 52 |
+
|
| 53 |
+
def tokenize(self, token):
|
| 54 |
+
chars = list(token)
|
| 55 |
+
if len(chars) > self.max_input_chars_per_word:
|
| 56 |
+
return [self.unk_token]
|
| 57 |
+
|
| 58 |
+
start = 0
|
| 59 |
+
sub_tokens = []
|
| 60 |
+
while start < len(chars):
|
| 61 |
+
end = len(chars)
|
| 62 |
+
cur_substr = None
|
| 63 |
+
while start < end:
|
| 64 |
+
substr = "".join(chars[start:end])
|
| 65 |
+
if substr in self.vocab:
|
| 66 |
+
cur_substr = substr
|
| 67 |
+
break
|
| 68 |
+
end -= 1
|
| 69 |
+
if cur_substr is None:
|
| 70 |
+
sub_tokens.append(self.unk_token)
|
| 71 |
+
start += 1
|
| 72 |
+
else:
|
| 73 |
+
sub_tokens.append(cur_substr)
|
| 74 |
+
start = end
|
| 75 |
+
|
| 76 |
+
return sub_tokens
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class CpmAntTokenizer(PreTrainedTokenizer):
|
| 80 |
+
"""
|
| 81 |
+
Construct a CPMAnt tokenizer. Based on byte-level Byte-Pair-Encoding.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
vocab_file (`str`):
|
| 85 |
+
Path to the vocabulary file.
|
| 86 |
+
bod_token (`str`, *optional*, defaults to `"<d>"`):
|
| 87 |
+
The beginning of document token.
|
| 88 |
+
eod_token (`str`, *optional*, defaults to `"</d>"`):
|
| 89 |
+
The end of document token.
|
| 90 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 91 |
+
The beginning of sequence token.
|
| 92 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 93 |
+
The end of sequence token.
|
| 94 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 95 |
+
The token used for padding.
|
| 96 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 97 |
+
The unknown token.
|
| 98 |
+
line_token (`str`, *optional*, defaults to `"</n>"`):
|
| 99 |
+
The line token.
|
| 100 |
+
space_token (`str`, *optional*, defaults to `"</_>"`):
|
| 101 |
+
The space token.
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 105 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 106 |
+
add_prefix_space = False
|
| 107 |
+
|
| 108 |
+
def __init__(
|
| 109 |
+
self,
|
| 110 |
+
vocab_file,
|
| 111 |
+
bod_token="<d>",
|
| 112 |
+
eod_token="</d>",
|
| 113 |
+
bos_token="<s>",
|
| 114 |
+
eos_token="</s>",
|
| 115 |
+
pad_token="<pad>",
|
| 116 |
+
unk_token="<unk>",
|
| 117 |
+
line_token="</n>",
|
| 118 |
+
space_token="</_>",
|
| 119 |
+
padding_side="left",
|
| 120 |
+
**kwargs,
|
| 121 |
+
):
|
| 122 |
+
requires_backends(self, ["jieba"])
|
| 123 |
+
self.bod_token = bod_token
|
| 124 |
+
self.eod_token = eod_token
|
| 125 |
+
self.encoder = load_vocab(vocab_file)
|
| 126 |
+
self.encoder[" "] = self.encoder[space_token]
|
| 127 |
+
self.encoder["\n"] = self.encoder[line_token]
|
| 128 |
+
|
| 129 |
+
del self.encoder[space_token]
|
| 130 |
+
del self.encoder[line_token]
|
| 131 |
+
|
| 132 |
+
self.encoder = collections.OrderedDict(sorted(self.encoder.items(), key=lambda x: x[1]))
|
| 133 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 134 |
+
|
| 135 |
+
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.encoder, unk_token=unk_token)
|
| 136 |
+
|
| 137 |
+
super().__init__(
|
| 138 |
+
bod_token=bod_token,
|
| 139 |
+
eod_token=eod_token,
|
| 140 |
+
bos_token=bos_token,
|
| 141 |
+
eos_token=eos_token,
|
| 142 |
+
pad_token=pad_token,
|
| 143 |
+
unk_token=unk_token,
|
| 144 |
+
line_token=line_token,
|
| 145 |
+
space_token=space_token,
|
| 146 |
+
padding_side=padding_side,
|
| 147 |
+
**kwargs,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
@property
|
| 151 |
+
def bod_token_id(self):
|
| 152 |
+
return self.encoder[self.bod_token]
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def eod_token_id(self):
|
| 156 |
+
return self.encoder[self.eod_token]
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
def newline_id(self):
|
| 160 |
+
return self.encoder["\n"]
|
| 161 |
+
|
| 162 |
+
@property
|
| 163 |
+
def vocab_size(self) -> int:
|
| 164 |
+
return len(self.encoder)
|
| 165 |
+
|
| 166 |
+
def get_vocab(self):
|
| 167 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 168 |
+
|
| 169 |
+
def _tokenize(self, text):
|
| 170 |
+
"""Tokenize a string."""
|
| 171 |
+
output_tokens = []
|
| 172 |
+
for x in jieba.cut(text, cut_all=False):
|
| 173 |
+
output_tokens.extend(self.wordpiece_tokenizer.tokenize(x))
|
| 174 |
+
return output_tokens
|
| 175 |
+
|
| 176 |
+
def _decode(self, token_ids, **kwargs):
|
| 177 |
+
"""Decode ids into a string."""
|
| 178 |
+
token_ids = [i for i in token_ids if i >= 0]
|
| 179 |
+
token_ids = [
|
| 180 |
+
x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
|
| 181 |
+
]
|
| 182 |
+
return super()._decode(token_ids, **kwargs)
|
| 183 |
+
|
| 184 |
+
def check(self, token):
|
| 185 |
+
return token in self.encoder
|
| 186 |
+
|
| 187 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
| 188 |
+
return "".join(tokens)
|
| 189 |
+
|
| 190 |
+
def _convert_token_to_id(self, token):
|
| 191 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 192 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 193 |
+
|
| 194 |
+
def _convert_id_to_token(self, index):
|
| 195 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 196 |
+
return self.decoder.get(index, self.unk_token)
|
| 197 |
+
|
| 198 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 199 |
+
if os.path.isdir(save_directory):
|
| 200 |
+
vocab_file = os.path.join(
|
| 201 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 202 |
+
)
|
| 203 |
+
else:
|
| 204 |
+
vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
|
| 205 |
+
index = 0
|
| 206 |
+
if " " in self.encoder:
|
| 207 |
+
self.encoder["</_>"] = self.encoder[" "]
|
| 208 |
+
del self.encoder[" "]
|
| 209 |
+
if "\n" in self.encoder:
|
| 210 |
+
self.encoder["</n>"] = self.encoder["\n"]
|
| 211 |
+
del self.encoder["\n"]
|
| 212 |
+
self.encoder = collections.OrderedDict(sorted(self.encoder.items(), key=lambda x: x[1]))
|
| 213 |
+
with open(vocab_file, "w", encoding="utf-8") as writer:
|
| 214 |
+
for token, token_index in self.encoder.items():
|
| 215 |
+
if index != token_index:
|
| 216 |
+
logger.warning(
|
| 217 |
+
f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
|
| 218 |
+
" Please check that the vocabulary is not corrupted!"
|
| 219 |
+
)
|
| 220 |
+
index = token_index
|
| 221 |
+
writer.write(token + "\n")
|
| 222 |
+
index += 1
|
| 223 |
+
return (vocab_file,)
|
| 224 |
+
|
| 225 |
+
def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: List[int] = None) -> List[int]:
|
| 226 |
+
"""
|
| 227 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 228 |
+
adding special tokens. A CPMAnt sequence has the following format:
|
| 229 |
+
|
| 230 |
+
- single sequence: `[BOS] Sequence`.
|
| 231 |
+
|
| 232 |
+
Args:
|
| 233 |
+
token_ids_0 (`List[int]`): The first tokenized sequence that special tokens will be added.
|
| 234 |
+
token_ids_1 (`List[int]`): The optional second tokenized sequence that special tokens will be added.
|
| 235 |
+
|
| 236 |
+
Returns:
|
| 237 |
+
`List[int]`: The model input with special tokens.
|
| 238 |
+
"""
|
| 239 |
+
if token_ids_1 is None:
|
| 240 |
+
return [self.bos_token_id] + token_ids_0
|
| 241 |
+
return [self.bos_token_id] + token_ids_0 + [self.bos_token_id] + token_ids_1
|
| 242 |
+
|
| 243 |
+
def get_special_tokens_mask(
|
| 244 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 245 |
+
) -> List[int]:
|
| 246 |
+
"""
|
| 247 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 248 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 249 |
+
|
| 250 |
+
Args:
|
| 251 |
+
token_ids_0 (`List[int]`): List of IDs.
|
| 252 |
+
token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs.
|
| 253 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 254 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 255 |
+
|
| 256 |
+
Returns:
|
| 257 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
if already_has_special_tokens:
|
| 261 |
+
return super().get_special_tokens_mask(
|
| 262 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
if token_ids_1 is not None:
|
| 266 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
|
| 267 |
+
return [1] + ([0] * len(token_ids_0))
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
__all__ = ["CpmAntTokenizer"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/ctrl/__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_ctrl import *
|
| 22 |
+
from .modeling_ctrl import *
|
| 23 |
+
from .modeling_tf_ctrl import *
|
| 24 |
+
from .tokenization_ctrl 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__)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/ctrl/configuration_ctrl.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Salesforce and HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 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 |
+
"""Salesforce CTRL 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 CTRLConfig(PretrainedConfig):
|
| 25 |
+
"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`CTRLModel`] or a [`TFCTRLModel`]. It is used to
|
| 27 |
+
instantiate a CTRL 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
|
| 29 |
+
[Salesforce/ctrl](https://huggingface.co/Salesforce/ctrl) architecture from SalesForce.
|
| 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 |
+
vocab_size (`int`, *optional*, defaults to 246534):
|
| 36 |
+
Vocabulary size of the CTRL model. Defines the number of different tokens that can be represented by the
|
| 37 |
+
`inputs_ids` passed when calling [`CTRLModel`] or [`TFCTRLModel`].
|
| 38 |
+
n_positions (`int`, *optional*, defaults to 256):
|
| 39 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 40 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 41 |
+
n_embd (`int`, *optional*, defaults to 1280):
|
| 42 |
+
Dimensionality of the embeddings and hidden states.
|
| 43 |
+
dff (`int`, *optional*, defaults to 8192):
|
| 44 |
+
Dimensionality of the inner dimension of the feed forward networks (FFN).
|
| 45 |
+
n_layer (`int`, *optional*, defaults to 48):
|
| 46 |
+
Number of hidden layers in the Transformer encoder.
|
| 47 |
+
n_head (`int`, *optional*, defaults to 16):
|
| 48 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 49 |
+
resid_pdrop (`float`, *optional*, defaults to 0.1):
|
| 50 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 51 |
+
embd_pdrop (`int`, *optional*, defaults to 0.1):
|
| 52 |
+
The dropout ratio for the embeddings.
|
| 53 |
+
layer_norm_epsilon (`float`, *optional*, defaults to 1e-06):
|
| 54 |
+
The epsilon to use in the layer normalization layers
|
| 55 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 56 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 57 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 58 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
Examples:
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
>>> from transformers import CTRLConfig, CTRLModel
|
| 65 |
+
|
| 66 |
+
>>> # Initializing a CTRL configuration
|
| 67 |
+
>>> configuration = CTRLConfig()
|
| 68 |
+
|
| 69 |
+
>>> # Initializing a model (with random weights) from the configuration
|
| 70 |
+
>>> model = CTRLModel(configuration)
|
| 71 |
+
|
| 72 |
+
>>> # Accessing the model configuration
|
| 73 |
+
>>> configuration = model.config
|
| 74 |
+
```"""
|
| 75 |
+
|
| 76 |
+
model_type = "ctrl"
|
| 77 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 78 |
+
attribute_map = {
|
| 79 |
+
"max_position_embeddings": "n_positions",
|
| 80 |
+
"hidden_size": "n_embd",
|
| 81 |
+
"num_attention_heads": "n_head",
|
| 82 |
+
"num_hidden_layers": "n_layer",
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
def __init__(
|
| 86 |
+
self,
|
| 87 |
+
vocab_size=246534,
|
| 88 |
+
n_positions=256,
|
| 89 |
+
n_embd=1280,
|
| 90 |
+
dff=8192,
|
| 91 |
+
n_layer=48,
|
| 92 |
+
n_head=16,
|
| 93 |
+
resid_pdrop=0.1,
|
| 94 |
+
embd_pdrop=0.1,
|
| 95 |
+
layer_norm_epsilon=1e-6,
|
| 96 |
+
initializer_range=0.02,
|
| 97 |
+
use_cache=True,
|
| 98 |
+
**kwargs,
|
| 99 |
+
):
|
| 100 |
+
self.vocab_size = vocab_size
|
| 101 |
+
self.n_positions = n_positions
|
| 102 |
+
self.n_embd = n_embd
|
| 103 |
+
self.n_layer = n_layer
|
| 104 |
+
self.n_head = n_head
|
| 105 |
+
self.dff = dff
|
| 106 |
+
self.resid_pdrop = resid_pdrop
|
| 107 |
+
self.embd_pdrop = embd_pdrop
|
| 108 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 109 |
+
self.initializer_range = initializer_range
|
| 110 |
+
|
| 111 |
+
self.use_cache =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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Salesforce and HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""PyTorch CTRL model."""
|
| 17 |
+
|
| 18 |
+
from typing import Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 24 |
+
|
| 25 |
+
from ...generation import GenerationMixin
|
| 26 |
+
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutput
|
| 27 |
+
from ...modeling_utils import PreTrainedModel
|
| 28 |
+
from ...pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_linear_layer
|
| 29 |
+
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
|
| 30 |
+
from .configuration_ctrl import CTRLConfig
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
_CONFIG_FOR_DOC = "CTRLConfig"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def angle_defn(pos, i, d_model_size):
|
| 39 |
+
angle_rates = 1 / torch.pow(10000, (2 * (i // 2)) / d_model_size)
|
| 40 |
+
return pos * angle_rates
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def positional_encoding(position, d_model_size, dtype):
|
| 44 |
+
# create the sinusoidal pattern for the positional encoding
|
| 45 |
+
angle_rads = angle_defn(
|
| 46 |
+
torch.arange(position, dtype=torch.int64).to(dtype).unsqueeze(1),
|
| 47 |
+
torch.arange(d_model_size, dtype=torch.int64).to(dtype).unsqueeze(0),
|
| 48 |
+
d_model_size,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
sines = torch.sin(angle_rads[:, 0::2])
|
| 52 |
+
cosines = torch.cos(angle_rads[:, 1::2])
|
| 53 |
+
|
| 54 |
+
pos_encoding = torch.cat([sines, cosines], dim=-1)
|
| 55 |
+
return pos_encoding
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def scaled_dot_product_attention(q, k, v, mask, attention_mask=None, head_mask=None):
|
| 59 |
+
# calculate attention
|
| 60 |
+
matmul_qk = torch.matmul(q, k.permute(0, 1, 3, 2))
|
| 61 |
+
|
| 62 |
+
dk = k.shape[-1]
|
| 63 |
+
scaled_attention_logits = matmul_qk / np.sqrt(dk)
|
| 64 |
+
|
| 65 |
+
if mask is not None:
|
| 66 |
+
nd, ns = scaled_attention_logits.size(-2), scaled_attention_logits.size(-1)
|
| 67 |
+
scaled_attention_logits += mask[ns - nd : ns, :ns] * -1e4
|
| 68 |
+
|
| 69 |
+
if attention_mask is not None:
|
| 70 |
+
# Apply the attention mask
|
| 71 |
+
scaled_attention_logits = scaled_attention_logits + attention_mask
|
| 72 |
+
|
| 73 |
+
attention_weights = torch.softmax(scaled_attention_logits, dim=-1)
|
| 74 |
+
|
| 75 |
+
# Mask heads if we want to
|
| 76 |
+
if head_mask is not None:
|
| 77 |
+
attention_weights = attention_weights * head_mask
|
| 78 |
+
|
| 79 |
+
output = torch.matmul(attention_weights, v)
|
| 80 |
+
|
| 81 |
+
return output, attention_weights
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class MultiHeadAttention(nn.Module):
|
| 85 |
+
def __init__(self, d_model_size, num_heads):
|
| 86 |
+
super().__init__()
|
| 87 |
+
self.num_heads = num_heads
|
| 88 |
+
self.d_model_size = d_model_size
|
| 89 |
+
|
| 90 |
+
self.depth = int(d_model_size / self.num_heads)
|
| 91 |
+
|
| 92 |
+
self.Wq = nn.Linear(d_model_size, d_model_size)
|
| 93 |
+
self.Wk = nn.Linear(d_model_size, d_model_size)
|
| 94 |
+
self.Wv = nn.Linear(d_model_size, d_model_size)
|
| 95 |
+
|
| 96 |
+
self.dense = nn.Linear(d_model_size, d_model_size)
|
| 97 |
+
self.pruned_heads = set()
|
| 98 |
+
|
| 99 |
+
def prune_heads(self, heads):
|
| 100 |
+
attention_head_size = self.d_model_size // self.num_heads
|
| 101 |
+
if len(heads) == 0:
|
| 102 |
+
return
|
| 103 |
+
heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, attention_head_size, self.pruned_heads)
|
| 104 |
+
|
| 105 |
+
# Prune linear layers
|
| 106 |
+
self.Wq = prune_linear_layer(self.Wq, index)
|
| 107 |
+
self.Wk = prune_linear_layer(self.Wk, index)
|
| 108 |
+
self.Wv = prune_linear_layer(self.Wv, index)
|
| 109 |
+
self.dense = prune_linear_layer(self.dense, index, dim=1)
|
| 110 |
+
|
| 111 |
+
# Update hyper params
|
| 112 |
+
self.num_heads = self.num_heads - len(heads)
|
| 113 |
+
self.d_model_size = attention_head_size * self.num_heads
|
| 114 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 115 |
+
|
| 116 |
+
def split_into_heads(self, x, batch_size):
|
| 117 |
+
x = x.reshape(batch_size, -1, self.num_heads, self.depth)
|
| 118 |
+
return x.permute([0, 2, 1, 3])
|
| 119 |
+
|
| 120 |
+
def forward(
|
| 121 |
+
self,
|
| 122 |
+
v,
|
| 123 |
+
k,
|
| 124 |
+
q,
|
| 125 |
+
mask,
|
| 126 |
+
layer_past=None,
|
| 127 |
+
attention_mask=None,
|
| 128 |
+
head_mask=None,
|
| 129 |
+
use_cache=False,
|
| 130 |
+
output_attentions=False,
|
| 131 |
+
):
|
| 132 |
+
batch_size = q.shape[0]
|
| 133 |
+
|
| 134 |
+
q = self.Wq(q)
|
| 135 |
+
k = self.Wk(k)
|
| 136 |
+
v = self.Wv(v)
|
| 137 |
+
|
| 138 |
+
q = self.split_into_heads(q, batch_size)
|
| 139 |
+
k = self.split_into_heads(k, batch_size)
|
| 140 |
+
v = self.split_into_heads(v, batch_size)
|
| 141 |
+
if layer_past is not None:
|
| 142 |
+
past_key, past_value = layer_past[0], layer_past[1]
|
| 143 |
+
k = torch.cat((past_key, k), dim=-2)
|
| 144 |
+
v = torch.cat((past_value, v), dim=-2)
|
| 145 |
+
|
| 146 |
+
if use_cache is True:
|
| 147 |
+
present = torch.stack((k, v))
|
| 148 |
+
else:
|
| 149 |
+
present = (None,)
|
| 150 |
+
|
| 151 |
+
output = scaled_dot_product_attention(q, k, v, mask, attention_mask, head_mask)
|
| 152 |
+
scaled_attention = output[0].permute([0, 2, 1, 3])
|
| 153 |
+
attn = output[1]
|
| 154 |
+
original_size_attention = scaled_attention.reshape(batch_size, -1, self.d_model_size)
|
| 155 |
+
output = self.dense(original_size_attention)
|
| 156 |
+
|
| 157 |
+
outputs = (output, present)
|
| 158 |
+
if output_attentions:
|
| 159 |
+
outputs = outputs + (attn,)
|
| 160 |
+
return outputs
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def point_wise_feed_forward_network(d_model_size, dff):
|
| 164 |
+
return nn.Sequential(nn.Linear(d_model_size, dff), nn.ReLU(), nn.Linear(dff, d_model_size))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class EncoderLayer(nn.Module):
|
| 168 |
+
def __init__(self, d_model_size, num_heads, dff, rate=0.1):
|
| 169 |
+
super().__init__()
|
| 170 |
+
|
| 171 |
+
self.multi_head_attention = MultiHeadAttention(d_model_size, num_heads)
|
| 172 |
+
self.ffn = point_wise_feed_forward_network(d_model_size, dff)
|
| 173 |
+
|
| 174 |
+
self.layernorm1 = nn.LayerNorm(d_model_size, eps=1e-6)
|
| 175 |
+
self.layernorm2 = nn.LayerNorm(d_model_size, eps=1e-6)
|
| 176 |
+
|
| 177 |
+
self.dropout1 = nn.Dropout(rate)
|
| 178 |
+
self.dropout2 = nn.Dropout(rate)
|
| 179 |
+
|
| 180 |
+
def forward(
|
| 181 |
+
self, x, mask, layer_past=None, attention_mask=None, head_mask=None, use_cache=False, output_attentions=False
|
| 182 |
+
):
|
| 183 |
+
normed = self.layernorm1(x)
|
| 184 |
+
attn_outputs = self.multi_head_attention(
|
| 185 |
+
normed,
|
| 186 |
+
normed,
|
| 187 |
+
normed,
|
| 188 |
+
mask,
|
| 189 |
+
layer_past=layer_past,
|
| 190 |
+
attention_mask=attention_mask,
|
| 191 |
+
head_mask=head_mask,
|
| 192 |
+
use_cache=use_cache,
|
| 193 |
+
output_attentions=output_attentions,
|
| 194 |
+
)
|
| 195 |
+
attn_output = attn_outputs[0]
|
| 196 |
+
attn_output = self.dropout1(attn_output)
|
| 197 |
+
out1 = x + attn_output
|
| 198 |
+
|
| 199 |
+
out2 = self.layernorm2(out1)
|
| 200 |
+
ffn_output = self.ffn(out2)
|
| 201 |
+
ffn_output = self.dropout2(ffn_output)
|
| 202 |
+
out2 = out1 + ffn_output
|
| 203 |
+
|
| 204 |
+
outputs = (out2,) + attn_outputs[1:]
|
| 205 |
+
return outputs
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class CTRLPreTrainedModel(PreTrainedModel):
|
| 209 |
+
"""
|
| 210 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 211 |
+
models.
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
config_class = CTRLConfig
|
| 215 |
+
base_model_prefix = "transformer"
|
| 216 |
+
|
| 217 |
+
def _init_weights(self, module):
|
| 218 |
+
"""Initialize the weights."""
|
| 219 |
+
if isinstance(module, (nn.Linear, Conv1D)):
|
| 220 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 221 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 222 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 223 |
+
if module.bias is not None:
|
| 224 |
+
module.bias.data.zero_()
|
| 225 |
+
elif isinstance(module, nn.Embedding):
|
| 226 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 227 |
+
if module.padding_idx is not None:
|
| 228 |
+
module.weight.data[module.padding_idx].zero_()
|
| 229 |
+
elif isinstance(module, nn.LayerNorm):
|
| 230 |
+
module.bias.data.zero_()
|
| 231 |
+
module.weight.data.fill_(1.0)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
CTRL_START_DOCSTRING = r"""
|
| 235 |
+
|
| 236 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 237 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 238 |
+
etc.)
|
| 239 |
+
|
| 240 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 241 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 242 |
+
and behavior.
|
| 243 |
+
|
| 244 |
+
Parameters:
|
| 245 |
+
config ([`CTRLConfig`]): Model configuration class with all the parameters of the model.
|
| 246 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 247 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
CTRL_INPUTS_DOCSTRING = r"""
|
| 251 |
+
Args:
|
| 252 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 253 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0].shape[-2]`
|
| 254 |
+
(`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
|
| 255 |
+
|
| 256 |
+
If `past_key_values` is used, only input IDs that do not have their past calculated should be passed as
|
| 257 |
+
`input_ids`.
|
| 258 |
+
|
| 259 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 260 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 261 |
+
|
| 262 |
+
[What are input IDs?](../glossary#input-ids)
|
| 263 |
+
past_key_values (`Tuple[Tuple[torch.FloatTensor]]` of length `config.n_layers`):
|
| 264 |
+
Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
|
| 265 |
+
`past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
|
| 266 |
+
their past given to this model should not be passed as input ids as they have already been computed.
|
| 267 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 268 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 269 |
+
|
| 270 |
+
- 1 for tokens that are **not masked**,
|
| 271 |
+
- 0 for tokens that are **masked**.
|
| 272 |
+
|
| 273 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 274 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 275 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 276 |
+
1]`:
|
| 277 |
+
|
| 278 |
+
- 0 corresponds to a *sentence A* token,
|
| 279 |
+
- 1 corresponds to a *sentence B* token.
|
| 280 |
+
|
| 281 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 282 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 283 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 284 |
+
config.max_position_embeddings - 1]`.
|
| 285 |
+
|
| 286 |
+
[What are position IDs?](../glossary#position-ids)
|
| 287 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 288 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 289 |
+
|
| 290 |
+
- 1 indicates the head is **not masked**,
|
| 291 |
+
- 0 indicates the head is **masked**.
|
| 292 |
+
|
| 293 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 294 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 295 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 296 |
+
model's internal embedding lookup matrix.
|
| 297 |
+
use_cache (`bool`, *optional*):
|
| 298 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 299 |
+
`past_key_values`).
|
| 300 |
+
output_attentions (`bool`, *optional*):
|
| 301 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 302 |
+
tensors for more detail.
|
| 303 |
+
output_hidden_states (`bool`, *optional*):
|
| 304 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 305 |
+
more detail.
|
| 306 |
+
return_dict (`bool`, *optional*):
|
| 307 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 308 |
+
"""
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
@add_start_docstrings(
|
| 312 |
+
"The bare CTRL Model transformer outputting raw hidden-states without any specific head on top.",
|
| 313 |
+
CTRL_START_DOCSTRING,
|
| 314 |
+
)
|
| 315 |
+
class CTRLModel(CTRLPreTrainedModel):
|
| 316 |
+
def __init__(self, config):
|
| 317 |
+
super().__init__(config)
|
| 318 |
+
|
| 319 |
+
self.d_model_size = config.n_embd
|
| 320 |
+
self.num_layers = config.n_layer
|
| 321 |
+
|
| 322 |
+
self.pos_encoding = positional_encoding(config.n_positions, self.d_model_size, torch.float)
|
| 323 |
+
|
| 324 |
+
self.w = nn.Embedding(config.vocab_size, config.n_embd)
|
| 325 |
+
|
| 326 |
+
self.dropout = nn.Dropout(config.embd_pdrop)
|
| 327 |
+
self.h = nn.ModuleList(
|
| 328 |
+
[EncoderLayer(config.n_embd, config.n_head, config.dff, config.resid_pdrop) for _ in range(config.n_layer)]
|
| 329 |
+
)
|
| 330 |
+
self.layernorm = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 331 |
+
|
| 332 |
+
# Initialize weights and apply final processing
|
| 333 |
+
self.post_init()
|
| 334 |
+
|
| 335 |
+
def get_input_embeddings(self):
|
| 336 |
+
return self.w
|
| 337 |
+
|
| 338 |
+
def set_input_embeddings(self, new_embeddings):
|
| 339 |
+
self.w = new_embeddings
|
| 340 |
+
|
| 341 |
+
def _prune_heads(self, heads_to_prune):
|
| 342 |
+
"""
|
| 343 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
|
| 344 |
+
"""
|
| 345 |
+
for layer, heads in heads_to_prune.items():
|
| 346 |
+
self.h[layer].multi_head_attention.prune_heads(heads)
|
| 347 |
+
|
| 348 |
+
@add_start_docstrings_to_model_forward(CTRL_INPUTS_DOCSTRING)
|
| 349 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 350 |
+
def forward(
|
| 351 |
+
self,
|
| 352 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 353 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 354 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 355 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 356 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 357 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 358 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 359 |
+
use_cache: Optional[bool] = None,
|
| 360 |
+
output_attentions: Optional[bool] = None,
|
| 361 |
+
output_hidden_states: Optional[bool] = None,
|
| 362 |
+
return_dict: Optional[bool] = None,
|
| 363 |
+
**kwargs, # NOOP kwargs, for now
|
| 364 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPast]:
|
| 365 |
+
r"""
|
| 366 |
+
Returns:
|
| 367 |
+
|
| 368 |
+
Example:
|
| 369 |
+
|
| 370 |
+
```python
|
| 371 |
+
>>> from transformers import AutoTokenizer, CTRLModel
|
| 372 |
+
>>> import torch
|
| 373 |
+
|
| 374 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
|
| 375 |
+
>>> model = CTRLModel.from_pretrained("Salesforce/ctrl")
|
| 376 |
+
|
| 377 |
+
>>> # CTRL was trained with control codes as the first token
|
| 378 |
+
>>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
|
| 379 |
+
>>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
|
| 380 |
+
|
| 381 |
+
>>> outputs = model(**inputs)
|
| 382 |
+
|
| 383 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 384 |
+
>>> list(last_hidden_states.shape)
|
| 385 |
+
[1, 5, 1280]
|
| 386 |
+
```"""
|
| 387 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 388 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 389 |
+
output_hidden_states = (
|
| 390 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 391 |
+
)
|
| 392 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 393 |
+
|
| 394 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 395 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 396 |
+
elif input_ids is not None:
|
| 397 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 398 |
+
input_shape = input_ids.size()
|
| 399 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 400 |
+
batch_size = input_ids.shape[0]
|
| 401 |
+
elif inputs_embeds is not None:
|
| 402 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 403 |
+
batch_size = inputs_embeds.shape[0]
|
| 404 |
+
else:
|
| 405 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 406 |
+
|
| 407 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 408 |
+
|
| 409 |
+
if past_key_values is None:
|
| 410 |
+
past_length = 0
|
| 411 |
+
past_key_values = tuple([None] * len(self.h))
|
| 412 |
+
else:
|
| 413 |
+
past_length = past_key_values[0][0].size(-2)
|
| 414 |
+
if position_ids is None:
|
| 415 |
+
position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
|
| 416 |
+
position_ids = position_ids.unsqueeze(0)
|
| 417 |
+
|
| 418 |
+
# Attention mask.
|
| 419 |
+
if attention_mask is not None:
|
| 420 |
+
if batch_size <= 0:
|
| 421 |
+
raise ValueError("batch_size has to be defined and > 0")
|
| 422 |
+
attention_mask = attention_mask.view(batch_size, -1)
|
| 423 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
| 424 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
| 425 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
| 426 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
| 427 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
| 428 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 429 |
+
|
| 430 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 431 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 432 |
+
# positions we want to attend and the dtype's smallest value for masked positions.
|
| 433 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 434 |
+
# effectively the same as removing these entirely.
|
| 435 |
+
attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
| 436 |
+
attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
|
| 437 |
+
|
| 438 |
+
# Prepare head mask if needed
|
| 439 |
+
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
|
| 440 |
+
|
| 441 |
+
if token_type_ids is not None:
|
| 442 |
+
token_type_ids = token_type_ids.view(-1, input_shape[-1])
|
| 443 |
+
token_type_embeds = self.w(token_type_ids)
|
| 444 |
+
token_type_embeds *= np.sqrt(self.d_model_size)
|
| 445 |
+
else:
|
| 446 |
+
token_type_embeds = 0
|
| 447 |
+
|
| 448 |
+
if inputs_embeds is None:
|
| 449 |
+
inputs_embeds = self.w(input_ids)
|
| 450 |
+
# inputs_embeds = embedded.unsqueeze(0) if len(input_ids.shape)<2 else embedded
|
| 451 |
+
seq_len = input_shape[-1]
|
| 452 |
+
mask = torch.triu(torch.ones(seq_len + past_length, seq_len + past_length), 1).to(device)
|
| 453 |
+
|
| 454 |
+
inputs_embeds *= np.sqrt(self.d_model_size)
|
| 455 |
+
|
| 456 |
+
# `self.pos_encoding` won't be sent to the correct device along the model, so we do it manually.
|
| 457 |
+
self.pos_encoding = self.pos_encoding.to(device)
|
| 458 |
+
pos_embeds = self.pos_encoding[position_ids, :]
|
| 459 |
+
|
| 460 |
+
hidden_states = inputs_embeds + pos_embeds + token_type_embeds
|
| 461 |
+
|
| 462 |
+
hidden_states = self.dropout(hidden_states)
|
| 463 |
+
|
| 464 |
+
presents = () if use_cache else None
|
| 465 |
+
all_hidden_states = () if output_hidden_states else None
|
| 466 |
+
all_attentions = () if output_attentions else None
|
| 467 |
+
for i, (h, layer_past) in enumerate(zip(self.h, past_key_values)):
|
| 468 |
+
if output_hidden_states:
|
| 469 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 470 |
+
outputs = h(
|
| 471 |
+
hidden_states,
|
| 472 |
+
mask,
|
| 473 |
+
layer_past=layer_past,
|
| 474 |
+
attention_mask=attention_mask,
|
| 475 |
+
head_mask=head_mask[i],
|
| 476 |
+
use_cache=use_cache,
|
| 477 |
+
output_attentions=output_attentions,
|
| 478 |
+
)
|
| 479 |
+
hidden_states, present = outputs[:2]
|
| 480 |
+
if use_cache is True:
|
| 481 |
+
presents = presents + (present,)
|
| 482 |
+
|
| 483 |
+
if output_attentions:
|
| 484 |
+
all_attentions += (outputs[2],)
|
| 485 |
+
|
| 486 |
+
hidden_states = self.layernorm(hidden_states)
|
| 487 |
+
if output_hidden_states:
|
| 488 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 489 |
+
|
| 490 |
+
if not return_dict:
|
| 491 |
+
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_attentions] if v is not None)
|
| 492 |
+
|
| 493 |
+
return BaseModelOutputWithPast(
|
| 494 |
+
last_hidden_state=hidden_states,
|
| 495 |
+
past_key_values=presents,
|
| 496 |
+
hidden_states=all_hidden_states,
|
| 497 |
+
attentions=all_attentions,
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
@add_start_docstrings(
|
| 502 |
+
"""
|
| 503 |
+
The CTRL Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
| 504 |
+
embeddings).
|
| 505 |
+
""",
|
| 506 |
+
CTRL_START_DOCSTRING,
|
| 507 |
+
)
|
| 508 |
+
class CTRLLMHeadModel(CTRLPreTrainedModel, GenerationMixin):
|
| 509 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 510 |
+
|
| 511 |
+
def __init__(self, config):
|
| 512 |
+
super().__init__(config)
|
| 513 |
+
self.transformer = CTRLModel(config)
|
| 514 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=True)
|
| 515 |
+
|
| 516 |
+
# Initialize weights and apply final processing
|
| 517 |
+
self.post_init()
|
| 518 |
+
|
| 519 |
+
def get_output_embeddings(self):
|
| 520 |
+
return self.lm_head
|
| 521 |
+
|
| 522 |
+
def set_output_embeddings(self, new_embeddings):
|
| 523 |
+
self.lm_head = new_embeddings
|
| 524 |
+
|
| 525 |
+
@add_start_docstrings_to_model_forward(CTRL_INPUTS_DOCSTRING)
|
| 526 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 527 |
+
def forward(
|
| 528 |
+
self,
|
| 529 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 530 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 531 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 532 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 533 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 534 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 535 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 536 |
+
labels: Optional[torch.LongTensor] = None,
|
| 537 |
+
use_cache: Optional[bool] = None,
|
| 538 |
+
output_attentions: Optional[bool] = None,
|
| 539 |
+
output_hidden_states: Optional[bool] = None,
|
| 540 |
+
return_dict: Optional[bool] = None,
|
| 541 |
+
**kwargs,
|
| 542 |
+
) -> Union[Tuple[torch.Tensor], CausalLMOutputWithPast]:
|
| 543 |
+
r"""
|
| 544 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 545 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
| 546 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
| 547 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
| 548 |
+
|
| 549 |
+
Returns:
|
| 550 |
+
|
| 551 |
+
Example:
|
| 552 |
+
|
| 553 |
+
```python
|
| 554 |
+
>>> import torch
|
| 555 |
+
>>> from transformers import AutoTokenizer, CTRLLMHeadModel
|
| 556 |
+
|
| 557 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
|
| 558 |
+
>>> model = CTRLLMHeadModel.from_pretrained("Salesforce/ctrl")
|
| 559 |
+
|
| 560 |
+
>>> # CTRL was trained with control codes as the first token
|
| 561 |
+
>>> inputs = tokenizer("Wikipedia The llama is", return_tensors="pt")
|
| 562 |
+
>>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
|
| 563 |
+
|
| 564 |
+
>>> sequence_ids = model.generate(inputs["input_ids"])
|
| 565 |
+
>>> sequences = tokenizer.batch_decode(sequence_ids)
|
| 566 |
+
>>> sequences
|
| 567 |
+
['Wikipedia The llama is a member of the family Bovidae. It is native to the Andes of Peru,']
|
| 568 |
+
|
| 569 |
+
>>> outputs = model(**inputs, labels=inputs["input_ids"])
|
| 570 |
+
>>> round(outputs.loss.item(), 2)
|
| 571 |
+
9.21
|
| 572 |
+
|
| 573 |
+
>>> list(outputs.logits.shape)
|
| 574 |
+
[1, 5, 246534]
|
| 575 |
+
```"""
|
| 576 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 577 |
+
|
| 578 |
+
transformer_outputs = self.transformer(
|
| 579 |
+
input_ids,
|
| 580 |
+
past_key_values=past_key_values,
|
| 581 |
+
attention_mask=attention_mask,
|
| 582 |
+
token_type_ids=token_type_ids,
|
| 583 |
+
position_ids=position_ids,
|
| 584 |
+
head_mask=head_mask,
|
| 585 |
+
inputs_embeds=inputs_embeds,
|
| 586 |
+
use_cache=use_cache,
|
| 587 |
+
output_attentions=output_attentions,
|
| 588 |
+
output_hidden_states=output_hidden_states,
|
| 589 |
+
return_dict=return_dict,
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
hidden_states = transformer_outputs[0]
|
| 593 |
+
|
| 594 |
+
lm_logits = self.lm_head(hidden_states)
|
| 595 |
+
|
| 596 |
+
loss = None
|
| 597 |
+
if labels is not None:
|
| 598 |
+
loss = self.loss_function(
|
| 599 |
+
lm_logits,
|
| 600 |
+
labels,
|
| 601 |
+
vocab_size=self.config.vocab_size,
|
| 602 |
+
**kwargs,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
if not return_dict:
|
| 606 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
| 607 |
+
return ((loss,) + output) if loss is not None else output
|
| 608 |
+
|
| 609 |
+
return CausalLMOutputWithPast(
|
| 610 |
+
loss=loss,
|
| 611 |
+
logits=lm_logits,
|
| 612 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 613 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 614 |
+
attentions=transformer_outputs.attentions,
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, use_cache=None, **kwargs):
|
| 618 |
+
# Overwritten -- inputs_embeds not working properly
|
| 619 |
+
|
| 620 |
+
# only last tokens for inputs_ids if past is defined in kwargs
|
| 621 |
+
if past_key_values is not None:
|
| 622 |
+
past_length = past_key_values[0][0].shape[2]
|
| 623 |
+
|
| 624 |
+
# Some generation methods already pass only the last input ID
|
| 625 |
+
if input_ids.shape[1] > past_length:
|
| 626 |
+
remove_prefix_length = past_length
|
| 627 |
+
else:
|
| 628 |
+
# Default to old behavior: keep only final ID
|
| 629 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
| 630 |
+
|
| 631 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
| 632 |
+
|
| 633 |
+
return {"input_ids": input_ids, "past_key_values": past_key_values, "use_cache": use_cache}
|
| 634 |
+
|
| 635 |
+
@staticmethod
|
| 636 |
+
def _reorder_cache(
|
| 637 |
+
past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
|
| 638 |
+
) -> Tuple[Tuple[torch.Tensor]]:
|
| 639 |
+
"""
|
| 640 |
+
This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
|
| 641 |
+
[`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
|
| 642 |
+
beam_idx at every generation step.
|
| 643 |
+
"""
|
| 644 |
+
return tuple(
|
| 645 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
|
| 646 |
+
for layer_past in past_key_values
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
@add_start_docstrings(
|
| 651 |
+
"""
|
| 652 |
+
The CTRL Model transformer with a sequence classification head on top (linear layer).
|
| 653 |
+
[`CTRLForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 654 |
+
(e.g. GPT-2) do. Since it does classification on the last token, it requires to know the position of the last
|
| 655 |
+
token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in
|
| 656 |
+
each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot
|
| 657 |
+
guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last
|
| 658 |
+
value in each row of the batch).
|
| 659 |
+
""",
|
| 660 |
+
CTRL_START_DOCSTRING,
|
| 661 |
+
)
|
| 662 |
+
class CTRLForSequenceClassification(CTRLPreTrainedModel):
|
| 663 |
+
def __init__(self, config):
|
| 664 |
+
super().__init__(config)
|
| 665 |
+
self.num_labels = config.num_labels
|
| 666 |
+
self.transformer = CTRLModel(config)
|
| 667 |
+
self.classifier = nn.Linear(config.n_embd, self.num_labels, bias=False)
|
| 668 |
+
|
| 669 |
+
# Initialize weights and apply final processing
|
| 670 |
+
self.post_init()
|
| 671 |
+
|
| 672 |
+
@add_start_docstrings_to_model_forward(CTRL_INPUTS_DOCSTRING)
|
| 673 |
+
@replace_return_docstrings(output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
|
| 674 |
+
def forward(
|
| 675 |
+
self,
|
| 676 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 677 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 678 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 679 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 680 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 681 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 682 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 683 |
+
labels: Optional[torch.LongTensor] = None,
|
| 684 |
+
use_cache: Optional[bool] = None,
|
| 685 |
+
output_attentions: Optional[bool] = None,
|
| 686 |
+
output_hidden_states: Optional[bool] = None,
|
| 687 |
+
return_dict: Optional[bool] = None,
|
| 688 |
+
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
|
| 689 |
+
r"""
|
| 690 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 691 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 692 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 693 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 694 |
+
|
| 695 |
+
Returns:
|
| 696 |
+
|
| 697 |
+
Example of single-label classification:
|
| 698 |
+
|
| 699 |
+
```python
|
| 700 |
+
>>> import torch
|
| 701 |
+
>>> from transformers import AutoTokenizer, CTRLForSequenceClassification
|
| 702 |
+
|
| 703 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
|
| 704 |
+
>>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl")
|
| 705 |
+
|
| 706 |
+
>>> # CTRL was trained with control codes as the first token
|
| 707 |
+
>>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
|
| 708 |
+
>>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
|
| 709 |
+
|
| 710 |
+
>>> with torch.no_grad():
|
| 711 |
+
... logits = model(**inputs).logits
|
| 712 |
+
|
| 713 |
+
>>> predicted_class_id = logits.argmax().item()
|
| 714 |
+
>>> model.config.id2label[predicted_class_id]
|
| 715 |
+
'LABEL_0'
|
| 716 |
+
```
|
| 717 |
+
|
| 718 |
+
```python
|
| 719 |
+
>>> import torch
|
| 720 |
+
|
| 721 |
+
>>> torch.manual_seed(42) # doctest: +IGNORE_RESULT
|
| 722 |
+
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
|
| 723 |
+
>>> num_labels = len(model.config.id2label)
|
| 724 |
+
>>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl", num_labels=num_labels)
|
| 725 |
+
|
| 726 |
+
>>> labels = torch.tensor(1)
|
| 727 |
+
>>> loss = model(**inputs, labels=labels).loss
|
| 728 |
+
>>> round(loss.item(), 2)
|
| 729 |
+
0.93
|
| 730 |
+
```
|
| 731 |
+
|
| 732 |
+
Example of multi-label classification:
|
| 733 |
+
|
| 734 |
+
```python
|
| 735 |
+
>>> import torch
|
| 736 |
+
>>> from transformers import AutoTokenizer, CTRLForSequenceClassification
|
| 737 |
+
|
| 738 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
|
| 739 |
+
>>> model = CTRLForSequenceClassification.from_pretrained(
|
| 740 |
+
... "Salesforce/ctrl", problem_type="multi_label_classification"
|
| 741 |
+
... )
|
| 742 |
+
|
| 743 |
+
>>> # CTRL was trained with control codes as the first token
|
| 744 |
+
>>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
|
| 745 |
+
>>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()
|
| 746 |
+
|
| 747 |
+
>>> with torch.no_grad():
|
| 748 |
+
... logits = model(**inputs).logits
|
| 749 |
+
|
| 750 |
+
>>> predicted_class_id = logits.argmax().item()
|
| 751 |
+
>>> model.config.id2label[predicted_class_id]
|
| 752 |
+
'LABEL_0'
|
| 753 |
+
```
|
| 754 |
+
|
| 755 |
+
```python
|
| 756 |
+
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
|
| 757 |
+
>>> num_labels = len(model.config.id2label)
|
| 758 |
+
>>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl", num_labels=num_labels)
|
| 759 |
+
|
| 760 |
+
>>> num_labels = len(model.config.id2label)
|
| 761 |
+
>>> labels = torch.nn.functional.one_hot(torch.tensor([predicted_class_id]), num_classes=num_labels).to(
|
| 762 |
+
... torch.float
|
| 763 |
+
... )
|
| 764 |
+
>>> loss = model(**inputs, labels=labels).loss
|
| 765 |
+
>>> loss.backward() # doctest: +IGNORE_RESULT
|
| 766 |
+
```"""
|
| 767 |
+
|
| 768 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 769 |
+
|
| 770 |
+
transformer_outputs = self.transformer(
|
| 771 |
+
input_ids,
|
| 772 |
+
past_key_values=past_key_values,
|
| 773 |
+
attention_mask=attention_mask,
|
| 774 |
+
token_type_ids=token_type_ids,
|
| 775 |
+
position_ids=position_ids,
|
| 776 |
+
head_mask=head_mask,
|
| 777 |
+
inputs_embeds=inputs_embeds,
|
| 778 |
+
use_cache=use_cache,
|
| 779 |
+
output_attentions=output_attentions,
|
| 780 |
+
output_hidden_states=output_hidden_states,
|
| 781 |
+
return_dict=return_dict,
|
| 782 |
+
)
|
| 783 |
+
|
| 784 |
+
hidden_states = transformer_outputs[0]
|
| 785 |
+
logits = self.classifier(hidden_states)
|
| 786 |
+
|
| 787 |
+
if input_ids is not None:
|
| 788 |
+
batch_size, sequence_length = input_ids.shape[:2]
|
| 789 |
+
else:
|
| 790 |
+
batch_size, sequence_length = inputs_embeds.shape[:2]
|
| 791 |
+
|
| 792 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 793 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 794 |
+
if self.config.pad_token_id is None:
|
| 795 |
+
last_non_pad_token = -1
|
| 796 |
+
elif input_ids is not None:
|
| 797 |
+
# To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
|
| 798 |
+
non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
|
| 799 |
+
token_indices = torch.arange(input_ids.shape[-1], device=logits.device)
|
| 800 |
+
last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
|
| 801 |
+
else:
|
| 802 |
+
last_non_pad_token = -1
|
| 803 |
+
logger.warning_once(
|
| 804 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
| 805 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
|
| 809 |
+
|
| 810 |
+
loss = None
|
| 811 |
+
if labels is not None:
|
| 812 |
+
if self.config.problem_type is None:
|
| 813 |
+
if self.num_labels == 1:
|
| 814 |
+
self.config.problem_type = "regression"
|
| 815 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 816 |
+
self.config.problem_type = "single_label_classification"
|
| 817 |
+
else:
|
| 818 |
+
self.config.problem_type = "multi_label_classification"
|
| 819 |
+
|
| 820 |
+
if self.config.problem_type == "regression":
|
| 821 |
+
loss_fct = MSELoss()
|
| 822 |
+
if self.num_labels == 1:
|
| 823 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
| 824 |
+
else:
|
| 825 |
+
loss = loss_fct(pooled_logits, labels)
|
| 826 |
+
elif self.config.problem_type == "single_label_classification":
|
| 827 |
+
loss_fct = CrossEntropyLoss()
|
| 828 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
| 829 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 830 |
+
loss_fct = BCEWithLogitsLoss()
|
| 831 |
+
loss = loss_fct(pooled_logits, labels)
|
| 832 |
+
if not return_dict:
|
| 833 |
+
output = (pooled_logits,) + transformer_outputs[2:]
|
| 834 |
+
return ((loss,) + output) if loss is not None else output
|
| 835 |
+
|
| 836 |
+
return SequenceClassifierOutput(
|
| 837 |
+
loss=loss,
|
| 838 |
+
logits=pooled_logits,
|
| 839 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 840 |
+
attentions=transformer_outputs.attentions,
|
| 841 |
+
)
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
__all__ = ["CTRLForSequenceClassification", "CTRLLMHeadModel", "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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Salesforce and HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""TF 2.0 CTRL model."""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
from typing import Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import tensorflow as tf
|
| 24 |
+
|
| 25 |
+
from ...modeling_tf_outputs import TFBaseModelOutputWithPast, TFCausalLMOutputWithPast, TFSequenceClassifierOutput
|
| 26 |
+
from ...modeling_tf_utils import (
|
| 27 |
+
TFCausalLanguageModelingLoss,
|
| 28 |
+
TFModelInputType,
|
| 29 |
+
TFPreTrainedModel,
|
| 30 |
+
TFSequenceClassificationLoss,
|
| 31 |
+
get_initializer,
|
| 32 |
+
keras,
|
| 33 |
+
keras_serializable,
|
| 34 |
+
unpack_inputs,
|
| 35 |
+
)
|
| 36 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
| 37 |
+
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 38 |
+
from .configuration_ctrl import CTRLConfig
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
_CHECKPOINT_FOR_DOC = "Salesforce/ctrl"
|
| 44 |
+
_CONFIG_FOR_DOC = "CTRLConfig"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def angle_defn(pos, i, d_model_size):
|
| 48 |
+
angle_rates = 1 / np.power(10000, (2 * (i // 2)) / d_model_size)
|
| 49 |
+
return pos * angle_rates
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def positional_encoding(position, d_model_size):
|
| 53 |
+
# create the sinusoidal pattern for the positional encoding
|
| 54 |
+
angle_rads = angle_defn(np.arange(position)[:, np.newaxis], np.arange(d_model_size)[np.newaxis, :], d_model_size)
|
| 55 |
+
|
| 56 |
+
sines = np.sin(angle_rads[:, 0::2])
|
| 57 |
+
cosines = np.cos(angle_rads[:, 1::2])
|
| 58 |
+
pos_encoding = tf.convert_to_tensor(np.concatenate([sines, cosines], axis=-1))
|
| 59 |
+
|
| 60 |
+
return pos_encoding
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def scaled_dot_product_attention(q, k, v, mask, attention_mask=None, head_mask=None):
|
| 64 |
+
# calculate attention
|
| 65 |
+
matmul_qk = tf.matmul(q, k, transpose_b=True)
|
| 66 |
+
|
| 67 |
+
dk = tf.cast(shape_list(k)[-1], dtype=matmul_qk.dtype)
|
| 68 |
+
scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)
|
| 69 |
+
|
| 70 |
+
if mask is not None:
|
| 71 |
+
scaled_attention_logits += tf.cast(mask * -1e4, dtype=scaled_attention_logits.dtype)
|
| 72 |
+
|
| 73 |
+
if attention_mask is not None:
|
| 74 |
+
# Apply the attention mask
|
| 75 |
+
attention_mask = tf.cast(attention_mask, dtype=scaled_attention_logits.dtype)
|
| 76 |
+
scaled_attention_logits = scaled_attention_logits + attention_mask
|
| 77 |
+
|
| 78 |
+
attention_weights = stable_softmax(scaled_attention_logits, axis=-1)
|
| 79 |
+
|
| 80 |
+
# Mask heads if we want to
|
| 81 |
+
if head_mask is not None:
|
| 82 |
+
attention_weights = attention_weights * head_mask
|
| 83 |
+
|
| 84 |
+
output = tf.matmul(attention_weights, v)
|
| 85 |
+
|
| 86 |
+
return output, attention_weights
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class TFMultiHeadAttention(keras.layers.Layer):
|
| 90 |
+
def __init__(self, d_model_size, num_heads, output_attentions=False, **kwargs):
|
| 91 |
+
super().__init__(**kwargs)
|
| 92 |
+
self.num_heads = num_heads
|
| 93 |
+
self.d_model_size = d_model_size
|
| 94 |
+
self.output_attentions = output_attentions
|
| 95 |
+
|
| 96 |
+
self.depth = int(d_model_size / self.num_heads)
|
| 97 |
+
|
| 98 |
+
self.Wq = keras.layers.Dense(d_model_size, name="Wq")
|
| 99 |
+
self.Wk = keras.layers.Dense(d_model_size, name="Wk")
|
| 100 |
+
self.Wv = keras.layers.Dense(d_model_size, name="Wv")
|
| 101 |
+
|
| 102 |
+
self.dense = keras.layers.Dense(d_model_size, name="dense")
|
| 103 |
+
|
| 104 |
+
def split_into_heads(self, x, batch_size):
|
| 105 |
+
x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))
|
| 106 |
+
return tf.transpose(x, perm=[0, 2, 1, 3])
|
| 107 |
+
|
| 108 |
+
def call(self, v, k, q, mask, layer_past, attention_mask, head_mask, use_cache, output_attentions, training=False):
|
| 109 |
+
batch_size = shape_list(q)[0]
|
| 110 |
+
|
| 111 |
+
q = self.Wq(q)
|
| 112 |
+
k = self.Wk(k)
|
| 113 |
+
v = self.Wv(v)
|
| 114 |
+
|
| 115 |
+
q = self.split_into_heads(q, batch_size)
|
| 116 |
+
k = self.split_into_heads(k, batch_size)
|
| 117 |
+
v = self.split_into_heads(v, batch_size)
|
| 118 |
+
|
| 119 |
+
if layer_past is not None:
|
| 120 |
+
past_key, past_value = tf.unstack(layer_past, axis=0)
|
| 121 |
+
k = tf.concat((past_key, k), axis=-2)
|
| 122 |
+
v = tf.concat((past_value, v), axis=-2)
|
| 123 |
+
|
| 124 |
+
if use_cache:
|
| 125 |
+
present = tf.stack((k, v), axis=0)
|
| 126 |
+
else:
|
| 127 |
+
present = (None,)
|
| 128 |
+
|
| 129 |
+
output = scaled_dot_product_attention(q, k, v, mask, attention_mask, head_mask)
|
| 130 |
+
scaled_attention = tf.transpose(output[0], perm=[0, 2, 1, 3])
|
| 131 |
+
attn = output[1]
|
| 132 |
+
original_size_attention = tf.reshape(scaled_attention, (batch_size, -1, self.d_model_size))
|
| 133 |
+
output = self.dense(original_size_attention)
|
| 134 |
+
outputs = (output, present)
|
| 135 |
+
|
| 136 |
+
if output_attentions:
|
| 137 |
+
outputs = outputs + (attn,)
|
| 138 |
+
|
| 139 |
+
return outputs
|
| 140 |
+
|
| 141 |
+
def build(self, input_shape=None):
|
| 142 |
+
if self.built:
|
| 143 |
+
return
|
| 144 |
+
self.built = True
|
| 145 |
+
if getattr(self, "Wq", None) is not None:
|
| 146 |
+
with tf.name_scope(self.Wq.name):
|
| 147 |
+
self.Wq.build([None, None, self.d_model_size])
|
| 148 |
+
if getattr(self, "Wk", None) is not None:
|
| 149 |
+
with tf.name_scope(self.Wk.name):
|
| 150 |
+
self.Wk.build([None, None, self.d_model_size])
|
| 151 |
+
if getattr(self, "Wv", None) is not None:
|
| 152 |
+
with tf.name_scope(self.Wv.name):
|
| 153 |
+
self.Wv.build([None, None, self.d_model_size])
|
| 154 |
+
if getattr(self, "dense", None) is not None:
|
| 155 |
+
with tf.name_scope(self.dense.name):
|
| 156 |
+
self.dense.build([None, None, self.d_model_size])
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class TFPointWiseFeedForwardLayer(keras.layers.Layer):
|
| 160 |
+
def __init__(self, d_model_size, dff, **kwargs):
|
| 161 |
+
super().__init__(**kwargs)
|
| 162 |
+
|
| 163 |
+
self.dense_0 = keras.layers.Dense(dff, activation="relu", name="0")
|
| 164 |
+
self.dense_2 = keras.layers.Dense(d_model_size, name="2")
|
| 165 |
+
self.d_model_size = d_model_size
|
| 166 |
+
self.dff = dff
|
| 167 |
+
|
| 168 |
+
def call(self, inputs, trainable=False):
|
| 169 |
+
dense_0_output = self.dense_0(inputs)
|
| 170 |
+
dense_2_output = self.dense_2(dense_0_output)
|
| 171 |
+
|
| 172 |
+
return dense_2_output
|
| 173 |
+
|
| 174 |
+
def build(self, input_shape=None):
|
| 175 |
+
if self.built:
|
| 176 |
+
return
|
| 177 |
+
self.built = True
|
| 178 |
+
if getattr(self, "dense_0", None) is not None:
|
| 179 |
+
with tf.name_scope(self.dense_0.name):
|
| 180 |
+
self.dense_0.build([None, None, self.d_model_size])
|
| 181 |
+
if getattr(self, "dense_2", None) is not None:
|
| 182 |
+
with tf.name_scope(self.dense_2.name):
|
| 183 |
+
self.dense_2.build([None, None, self.dff])
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class TFEncoderLayer(keras.layers.Layer):
|
| 187 |
+
def __init__(
|
| 188 |
+
self, d_model_size, num_heads, dff, rate=0.1, layer_norm_epsilon=1e-6, output_attentions=False, **kwargs
|
| 189 |
+
):
|
| 190 |
+
super().__init__(**kwargs)
|
| 191 |
+
|
| 192 |
+
self.output_attentions = output_attentions
|
| 193 |
+
|
| 194 |
+
self.multi_head_attention = TFMultiHeadAttention(
|
| 195 |
+
d_model_size, num_heads, output_attentions=self.output_attentions, name="multi_head_attention"
|
| 196 |
+
)
|
| 197 |
+
self.ffn = TFPointWiseFeedForwardLayer(d_model_size, dff, name="ffn")
|
| 198 |
+
|
| 199 |
+
self.layernorm1 = keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name="layernorm1")
|
| 200 |
+
self.layernorm2 = keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name="layernorm2")
|
| 201 |
+
|
| 202 |
+
self.dropout1 = keras.layers.Dropout(rate)
|
| 203 |
+
self.dropout2 = keras.layers.Dropout(rate)
|
| 204 |
+
self.d_model_size = d_model_size
|
| 205 |
+
|
| 206 |
+
def call(self, x, mask, layer_past, attention_mask, head_mask, use_cache, output_attentions, training=False):
|
| 207 |
+
normed = self.layernorm1(x)
|
| 208 |
+
attn_outputs = self.multi_head_attention(
|
| 209 |
+
normed,
|
| 210 |
+
normed,
|
| 211 |
+
normed,
|
| 212 |
+
mask,
|
| 213 |
+
layer_past,
|
| 214 |
+
attention_mask,
|
| 215 |
+
head_mask,
|
| 216 |
+
use_cache,
|
| 217 |
+
output_attentions,
|
| 218 |
+
training=training,
|
| 219 |
+
)
|
| 220 |
+
attn_output = attn_outputs[0]
|
| 221 |
+
attn_output = self.dropout1(attn_output, training=training)
|
| 222 |
+
out1 = x + attn_output
|
| 223 |
+
|
| 224 |
+
out2 = self.layernorm2(out1)
|
| 225 |
+
ffn_output = self.ffn(out2)
|
| 226 |
+
ffn_output = self.dropout2(ffn_output, training=training)
|
| 227 |
+
out2 = out1 + ffn_output
|
| 228 |
+
|
| 229 |
+
outputs = (out2,) + attn_outputs[1:]
|
| 230 |
+
return outputs
|
| 231 |
+
|
| 232 |
+
def build(self, input_shape=None):
|
| 233 |
+
if self.built:
|
| 234 |
+
return
|
| 235 |
+
self.built = True
|
| 236 |
+
if getattr(self, "multi_head_attention", None) is not None:
|
| 237 |
+
with tf.name_scope(self.multi_head_attention.name):
|
| 238 |
+
self.multi_head_attention.build(None)
|
| 239 |
+
if getattr(self, "ffn", None) is not None:
|
| 240 |
+
with tf.name_scope(self.ffn.name):
|
| 241 |
+
self.ffn.build(None)
|
| 242 |
+
if getattr(self, "layernorm1", None) is not None:
|
| 243 |
+
with tf.name_scope(self.layernorm1.name):
|
| 244 |
+
self.layernorm1.build([None, None, self.d_model_size])
|
| 245 |
+
if getattr(self, "layernorm2", None) is not None:
|
| 246 |
+
with tf.name_scope(self.layernorm2.name):
|
| 247 |
+
self.layernorm2.build([None, None, self.d_model_size])
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
@keras_serializable
|
| 251 |
+
class TFCTRLMainLayer(keras.layers.Layer):
|
| 252 |
+
config_class = CTRLConfig
|
| 253 |
+
|
| 254 |
+
def __init__(self, config, **kwargs):
|
| 255 |
+
super().__init__(**kwargs)
|
| 256 |
+
|
| 257 |
+
self.config = config
|
| 258 |
+
self.output_hidden_states = config.output_hidden_states
|
| 259 |
+
self.output_attentions = config.output_attentions
|
| 260 |
+
self.use_cache = config.use_cache
|
| 261 |
+
self.return_dict = config.use_return_dict
|
| 262 |
+
|
| 263 |
+
self.d_model_size = config.n_embd
|
| 264 |
+
self.num_layers = config.n_layer
|
| 265 |
+
|
| 266 |
+
self.pos_encoding = positional_encoding(config.n_positions, self.d_model_size)
|
| 267 |
+
|
| 268 |
+
self.w = keras.layers.Embedding(
|
| 269 |
+
input_dim=config.vocab_size,
|
| 270 |
+
output_dim=config.n_embd,
|
| 271 |
+
embeddings_initializer=get_initializer(config.initializer_range),
|
| 272 |
+
name="w",
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
self.dropout = keras.layers.Dropout(config.embd_pdrop)
|
| 276 |
+
self.h = [
|
| 277 |
+
TFEncoderLayer(
|
| 278 |
+
config.n_embd,
|
| 279 |
+
config.n_head,
|
| 280 |
+
config.dff,
|
| 281 |
+
config.resid_pdrop,
|
| 282 |
+
config.layer_norm_epsilon,
|
| 283 |
+
self.output_attentions,
|
| 284 |
+
name=f"h_._{i}",
|
| 285 |
+
)
|
| 286 |
+
for i in range(config.n_layer)
|
| 287 |
+
]
|
| 288 |
+
self.layernorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_epsilon, name="layernorm")
|
| 289 |
+
|
| 290 |
+
def get_input_embeddings(self):
|
| 291 |
+
return self.w
|
| 292 |
+
|
| 293 |
+
def set_input_embeddings(self, new_embeddings):
|
| 294 |
+
self.w = new_embeddings
|
| 295 |
+
|
| 296 |
+
def _prune_heads(self, heads_to_prune):
|
| 297 |
+
"""
|
| 298 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
|
| 299 |
+
"""
|
| 300 |
+
raise NotImplementedError
|
| 301 |
+
|
| 302 |
+
@unpack_inputs
|
| 303 |
+
def call(
|
| 304 |
+
self,
|
| 305 |
+
input_ids: TFModelInputType | None = None,
|
| 306 |
+
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
|
| 307 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 308 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 309 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 310 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 311 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 312 |
+
use_cache: Optional[bool] = None,
|
| 313 |
+
output_attentions: Optional[bool] = None,
|
| 314 |
+
output_hidden_states: Optional[bool] = None,
|
| 315 |
+
return_dict: Optional[bool] = None,
|
| 316 |
+
training: Optional[bool] = False,
|
| 317 |
+
) -> Union[Tuple, TFBaseModelOutputWithPast]:
|
| 318 |
+
# If using past key value states, only the last tokens
|
| 319 |
+
# should be given as an input
|
| 320 |
+
if past_key_values is not None:
|
| 321 |
+
if input_ids is not None:
|
| 322 |
+
input_ids = input_ids[:, -1:]
|
| 323 |
+
if inputs_embeds is not None:
|
| 324 |
+
inputs_embeds = inputs_embeds[:, -1:]
|
| 325 |
+
if token_type_ids is not None:
|
| 326 |
+
token_type_ids = token_type_ids[:, -1:]
|
| 327 |
+
|
| 328 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 329 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 330 |
+
elif input_ids is not None:
|
| 331 |
+
input_shape = shape_list(input_ids)
|
| 332 |
+
input_ids = tf.reshape(input_ids, [-1, input_shape[-1]])
|
| 333 |
+
elif inputs_embeds is not None:
|
| 334 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 335 |
+
else:
|
| 336 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 337 |
+
|
| 338 |
+
if past_key_values is None:
|
| 339 |
+
past_length = 0
|
| 340 |
+
past_key_values = [None] * len(self.h)
|
| 341 |
+
else:
|
| 342 |
+
past_length = shape_list(past_key_values[0][0])[-2]
|
| 343 |
+
if position_ids is None:
|
| 344 |
+
position_ids = tf.expand_dims(tf.range(past_length, input_shape[-1] + past_length, dtype=tf.int32), axis=0)
|
| 345 |
+
position_ids = tf.tile(position_ids, [input_shape[0], 1])
|
| 346 |
+
|
| 347 |
+
# Attention mask.
|
| 348 |
+
if attention_mask is not None:
|
| 349 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
| 350 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
| 351 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
| 352 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
| 353 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
| 354 |
+
attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1] + past_length))
|
| 355 |
+
|
| 356 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 357 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 358 |
+
# positions we want to attend and -10000.0 for masked positions.
|
| 359 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 360 |
+
# effectively the same as removing these entirely.
|
| 361 |
+
|
| 362 |
+
one_cst = tf.constant(1.0)
|
| 363 |
+
ten_thousand_cst = tf.constant(-10000.0)
|
| 364 |
+
attention_mask = tf.cast(attention_mask, dtype=one_cst.dtype)
|
| 365 |
+
attention_mask = tf.multiply(tf.subtract(one_cst, attention_mask), ten_thousand_cst)
|
| 366 |
+
|
| 367 |
+
# Prepare head mask if needed
|
| 368 |
+
# 1.0 in head_mask indicate we keep the head
|
| 369 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 370 |
+
# head_mask has shape n_layer x batch x n_heads x N x N
|
| 371 |
+
if head_mask is not None:
|
| 372 |
+
raise NotImplementedError
|
| 373 |
+
else:
|
| 374 |
+
head_mask = [None] * self.num_layers
|
| 375 |
+
|
| 376 |
+
if token_type_ids is not None:
|
| 377 |
+
token_type_ids = tf.reshape(token_type_ids, [-1, shape_list(token_type_ids)[-1]])
|
| 378 |
+
token_type_embeds = self.w(token_type_ids)
|
| 379 |
+
token_type_embeds *= tf.math.sqrt(tf.cast(self.d_model_size, dtype=token_type_embeds.dtype))
|
| 380 |
+
else:
|
| 381 |
+
token_type_embeds = tf.constant(0.0)
|
| 382 |
+
position_ids = tf.reshape(position_ids, [-1, shape_list(position_ids)[-1]])
|
| 383 |
+
|
| 384 |
+
if inputs_embeds is None:
|
| 385 |
+
check_embeddings_within_bounds(input_ids, self.w.input_dim)
|
| 386 |
+
inputs_embeds = self.w(input_ids)
|
| 387 |
+
seq_len = input_shape[-1]
|
| 388 |
+
mask = 1 - tf.linalg.band_part(tf.ones((seq_len, seq_len)), -1, 0)
|
| 389 |
+
|
| 390 |
+
inputs_embeds *= tf.math.sqrt(tf.cast(self.d_model_size, inputs_embeds.dtype))
|
| 391 |
+
|
| 392 |
+
pos_embeds = tf.gather(self.pos_encoding, position_ids)
|
| 393 |
+
pos_embeds = tf.cast(pos_embeds, dtype=token_type_embeds.dtype)
|
| 394 |
+
hidden_states = inputs_embeds + pos_embeds + token_type_embeds
|
| 395 |
+
|
| 396 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 397 |
+
|
| 398 |
+
output_shape = input_shape + [shape_list(hidden_states)[-1]]
|
| 399 |
+
presents = () if use_cache else None
|
| 400 |
+
all_hidden_states = () if output_hidden_states else None
|
| 401 |
+
all_attentions = () if output_attentions else None
|
| 402 |
+
for i, (h, layer_past) in enumerate(zip(self.h, past_key_values)):
|
| 403 |
+
if output_hidden_states:
|
| 404 |
+
all_hidden_states = all_hidden_states + (tf.reshape(hidden_states, output_shape),)
|
| 405 |
+
outputs = h(
|
| 406 |
+
hidden_states,
|
| 407 |
+
mask,
|
| 408 |
+
layer_past,
|
| 409 |
+
attention_mask,
|
| 410 |
+
head_mask[i],
|
| 411 |
+
use_cache,
|
| 412 |
+
output_attentions,
|
| 413 |
+
training=training,
|
| 414 |
+
)
|
| 415 |
+
hidden_states, present = outputs[:2]
|
| 416 |
+
|
| 417 |
+
if use_cache:
|
| 418 |
+
presents = presents + (present,)
|
| 419 |
+
|
| 420 |
+
if output_attentions:
|
| 421 |
+
all_attentions = all_attentions + (outputs[2],)
|
| 422 |
+
|
| 423 |
+
hidden_states = self.layernorm(hidden_states)
|
| 424 |
+
hidden_states = tf.reshape(hidden_states, output_shape)
|
| 425 |
+
if output_hidden_states:
|
| 426 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 427 |
+
|
| 428 |
+
if output_attentions:
|
| 429 |
+
# let the number of heads free (-1) so we can extract attention even after head pruning
|
| 430 |
+
attention_output_shape = input_shape[:-1] + [-1] + shape_list(all_attentions[0])[-2:]
|
| 431 |
+
all_attentions = tuple(tf.reshape(t, attention_output_shape) for t in all_attentions)
|
| 432 |
+
|
| 433 |
+
if not return_dict:
|
| 434 |
+
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_attentions] if v is not None)
|
| 435 |
+
|
| 436 |
+
return TFBaseModelOutputWithPast(
|
| 437 |
+
last_hidden_state=hidden_states,
|
| 438 |
+
past_key_values=presents,
|
| 439 |
+
hidden_states=all_hidden_states,
|
| 440 |
+
attentions=all_attentions,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
def build(self, input_shape=None):
|
| 444 |
+
if self.built:
|
| 445 |
+
return
|
| 446 |
+
self.built = True
|
| 447 |
+
if getattr(self, "w", None) is not None:
|
| 448 |
+
with tf.name_scope(self.w.name):
|
| 449 |
+
self.w.build(None)
|
| 450 |
+
if getattr(self, "layernorm", None) is not None:
|
| 451 |
+
with tf.name_scope(self.layernorm.name):
|
| 452 |
+
self.layernorm.build([None, None, self.config.n_embd])
|
| 453 |
+
if getattr(self, "h", None) is not None:
|
| 454 |
+
for layer in self.h:
|
| 455 |
+
with tf.name_scope(layer.name):
|
| 456 |
+
layer.build(None)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
class TFCTRLPreTrainedModel(TFPreTrainedModel):
|
| 460 |
+
"""
|
| 461 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 462 |
+
models.
|
| 463 |
+
"""
|
| 464 |
+
|
| 465 |
+
config_class = CTRLConfig
|
| 466 |
+
base_model_prefix = "transformer"
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
CTRL_START_DOCSTRING = r"""
|
| 470 |
+
|
| 471 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 472 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 473 |
+
etc.)
|
| 474 |
+
|
| 475 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 476 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 477 |
+
behavior.
|
| 478 |
+
|
| 479 |
+
<Tip>
|
| 480 |
+
|
| 481 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 482 |
+
|
| 483 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 484 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 485 |
+
|
| 486 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 487 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 488 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 489 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 490 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 491 |
+
positional argument:
|
| 492 |
+
|
| 493 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 494 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 495 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 496 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 497 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 498 |
+
|
| 499 |
+
Note that when creating models and layers with
|
| 500 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 501 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 502 |
+
|
| 503 |
+
</Tip>
|
| 504 |
+
|
| 505 |
+
Parameters:
|
| 506 |
+
config ([`CTRLConfig`]): Model configuration class with all the parameters of the model.
|
| 507 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 508 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 509 |
+
"""
|
| 510 |
+
|
| 511 |
+
CTRL_INPUTS_DOCSTRING = r"""
|
| 512 |
+
Args:
|
| 513 |
+
input_ids (`Numpy array` or `tf.Tensor` of shape `(batch_size, input_ids_length)`):
|
| 514 |
+
`input_ids_length` = `sequence_length` if `past` is `None` else `past[0].shape[-2]` (`sequence_length` of
|
| 515 |
+
input past key value states).
|
| 516 |
+
|
| 517 |
+
Indices of input sequence tokens in the vocabulary.
|
| 518 |
+
|
| 519 |
+
If `past` is used, only input IDs that do not have their past calculated should be passed as `input_ids`.
|
| 520 |
+
|
| 521 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 522 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 523 |
+
|
| 524 |
+
[What are input IDs?](../glossary#input-ids)
|
| 525 |
+
past (`List[tf.Tensor]` of length `config.n_layers`):
|
| 526 |
+
Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
|
| 527 |
+
`past` output below). Can be used to speed up sequential decoding. The token ids which have their past
|
| 528 |
+
given to this model should not be passed as input ids as they have already been computed.
|
| 529 |
+
attention_mask (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
|
| 530 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 531 |
+
|
| 532 |
+
- 1 for tokens that are **not masked**,
|
| 533 |
+
- 0 for tokens that are **masked**.
|
| 534 |
+
|
| 535 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 536 |
+
token_type_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
|
| 537 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 538 |
+
1]`:
|
| 539 |
+
|
| 540 |
+
- 0 corresponds to a *sentence A* token,
|
| 541 |
+
- 1 corresponds to a *sentence B* token.
|
| 542 |
+
|
| 543 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 544 |
+
position_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
|
| 545 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 546 |
+
config.max_position_embeddings - 1]`.
|
| 547 |
+
|
| 548 |
+
[What are position IDs?](../glossary#position-ids)
|
| 549 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 550 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 551 |
+
|
| 552 |
+
- 1 indicates the head is **not masked**,
|
| 553 |
+
- 0 indicates the head is **masked**.
|
| 554 |
+
|
| 555 |
+
inputs_embeds (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 556 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 557 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 558 |
+
model's internal embedding lookup matrix.
|
| 559 |
+
use_cache (`bool`, *optional*):
|
| 560 |
+
If set to `True`, `past` key value states are returned and can be used to speed up decoding (see `past`).
|
| 561 |
+
output_attentions (`bool`, *optional*):
|
| 562 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 563 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 564 |
+
config will be used instead.
|
| 565 |
+
output_hidden_states (`bool`, *optional*):
|
| 566 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 567 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 568 |
+
used instead.
|
| 569 |
+
return_dict (`bool`, *optional*):
|
| 570 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 571 |
+
eager mode, in graph mode the value will always be set to True.
|
| 572 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 573 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 574 |
+
behaviors between training and evaluation).
|
| 575 |
+
"""
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
@add_start_docstrings(
|
| 579 |
+
"The bare CTRL Model transformer outputting raw hidden-states without any specific head on top.",
|
| 580 |
+
CTRL_START_DOCSTRING,
|
| 581 |
+
)
|
| 582 |
+
class TFCTRLModel(TFCTRLPreTrainedModel):
|
| 583 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 584 |
+
super().__init__(config, *inputs, **kwargs)
|
| 585 |
+
self.transformer = TFCTRLMainLayer(config, name="transformer")
|
| 586 |
+
|
| 587 |
+
@unpack_inputs
|
| 588 |
+
@add_start_docstrings_to_model_forward(CTRL_INPUTS_DOCSTRING)
|
| 589 |
+
@add_code_sample_docstrings(
|
| 590 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 591 |
+
output_type=TFBaseModelOutputWithPast,
|
| 592 |
+
config_class=_CONFIG_FOR_DOC,
|
| 593 |
+
)
|
| 594 |
+
def call(
|
| 595 |
+
self,
|
| 596 |
+
input_ids: TFModelInputType | None = None,
|
| 597 |
+
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
|
| 598 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 599 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 600 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 601 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 602 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 603 |
+
use_cache: Optional[bool] = None,
|
| 604 |
+
output_attentions: Optional[bool] = None,
|
| 605 |
+
output_hidden_states: Optional[bool] = None,
|
| 606 |
+
return_dict: Optional[bool] = None,
|
| 607 |
+
training: Optional[bool] = False,
|
| 608 |
+
) -> Union[Tuple, TFBaseModelOutputWithPast]:
|
| 609 |
+
outputs = self.transformer(
|
| 610 |
+
input_ids=input_ids,
|
| 611 |
+
past_key_values=past_key_values,
|
| 612 |
+
attention_mask=attention_mask,
|
| 613 |
+
token_type_ids=token_type_ids,
|
| 614 |
+
position_ids=position_ids,
|
| 615 |
+
head_mask=head_mask,
|
| 616 |
+
inputs_embeds=inputs_embeds,
|
| 617 |
+
use_cache=use_cache,
|
| 618 |
+
output_attentions=output_attentions,
|
| 619 |
+
output_hidden_states=output_hidden_states,
|
| 620 |
+
return_dict=return_dict,
|
| 621 |
+
training=training,
|
| 622 |
+
)
|
| 623 |
+
return outputs
|
| 624 |
+
|
| 625 |
+
def build(self, input_shape=None):
|
| 626 |
+
if self.built:
|
| 627 |
+
return
|
| 628 |
+
self.built = True
|
| 629 |
+
if getattr(self, "transformer", None) is not None:
|
| 630 |
+
with tf.name_scope(self.transformer.name):
|
| 631 |
+
self.transformer.build(None)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
class TFCTRLBiasLayer(keras.layers.Layer):
|
| 635 |
+
"""
|
| 636 |
+
Bias as a layer. It is used for serialization purposes: `keras.Model.save_weights` stores on a per-layer basis,
|
| 637 |
+
so all weights have to be registered in a layer.
|
| 638 |
+
"""
|
| 639 |
+
|
| 640 |
+
def __init__(self, shape, initializer, trainable, name, **kwargs):
|
| 641 |
+
super().__init__(name=name, **kwargs)
|
| 642 |
+
self.shape = shape
|
| 643 |
+
self.initializer = initializer
|
| 644 |
+
self.trainable = trainable
|
| 645 |
+
|
| 646 |
+
def build(self, input_shape):
|
| 647 |
+
self.bias = self.add_weight(
|
| 648 |
+
name="bias", shape=self.shape, initializer=self.initializer, trainable=self.trainable
|
| 649 |
+
)
|
| 650 |
+
super().build(input_shape)
|
| 651 |
+
|
| 652 |
+
def call(self, x):
|
| 653 |
+
return x + self.bias
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
@add_start_docstrings(
|
| 657 |
+
"""
|
| 658 |
+
The CTRL Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
| 659 |
+
embeddings).
|
| 660 |
+
""",
|
| 661 |
+
CTRL_START_DOCSTRING,
|
| 662 |
+
)
|
| 663 |
+
class TFCTRLLMHeadModel(TFCTRLPreTrainedModel, TFCausalLanguageModelingLoss):
|
| 664 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 665 |
+
super().__init__(config, *inputs, **kwargs)
|
| 666 |
+
self.transformer = TFCTRLMainLayer(config, name="transformer")
|
| 667 |
+
self.bias_layer = TFCTRLBiasLayer(
|
| 668 |
+
name="lm_head", shape=[1, config.vocab_size], initializer="zeros", trainable=True
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
def get_output_embeddings(self):
|
| 672 |
+
return self.get_input_embeddings()
|
| 673 |
+
|
| 674 |
+
def set_output_embeddings(self, value):
|
| 675 |
+
self.set_input_embeddings(value)
|
| 676 |
+
|
| 677 |
+
def get_bias(self):
|
| 678 |
+
return {"lm_head.bias": self.bias_layer.bias}
|
| 679 |
+
|
| 680 |
+
def set_bias(self, value):
|
| 681 |
+
# Replaces the existing layers containing bias for correct (de)serialization.
|
| 682 |
+
vocab_size = value["lm_head.bias"].shape[-1]
|
| 683 |
+
self.bias_layer = TFCTRLBiasLayer(
|
| 684 |
+
name="final_logits_bias", shape=[1, vocab_size], initializer="zeros", trainable=True
|
| 685 |
+
)
|
| 686 |
+
self.bias_layer.build(None)
|
| 687 |
+
self.bias_layer.bias.assign(value["lm_head.bias"])
|
| 688 |
+
|
| 689 |
+
# Copied from transformers.models.gpt2.modeling_tf_gpt2.TFGPT2LMHeadModel.prepare_inputs_for_generation
|
| 690 |
+
def prepare_inputs_for_generation(self, inputs, past_key_values=None, use_cache=None, **kwargs):
|
| 691 |
+
token_type_ids = kwargs.get("token_type_ids", None)
|
| 692 |
+
# only last token for inputs_ids if past is defined in kwargs
|
| 693 |
+
if past_key_values:
|
| 694 |
+
inputs = tf.expand_dims(inputs[:, -1], -1)
|
| 695 |
+
if token_type_ids is not None:
|
| 696 |
+
token_type_ids = tf.expand_dims(token_type_ids[:, -1], -1)
|
| 697 |
+
|
| 698 |
+
position_ids = kwargs.get("position_ids", None)
|
| 699 |
+
attention_mask = kwargs.get("attention_mask", None)
|
| 700 |
+
|
| 701 |
+
if attention_mask is not None and position_ids is None:
|
| 702 |
+
position_ids = tf.math.cumsum(attention_mask, axis=-1, exclusive=True)
|
| 703 |
+
if past_key_values:
|
| 704 |
+
position_ids = tf.expand_dims(position_ids[:, -1], -1)
|
| 705 |
+
|
| 706 |
+
return {
|
| 707 |
+
"input_ids": inputs,
|
| 708 |
+
"attention_mask": attention_mask,
|
| 709 |
+
"position_ids": position_ids,
|
| 710 |
+
"past_key_values": past_key_values,
|
| 711 |
+
"use_cache": use_cache,
|
| 712 |
+
"token_type_ids": token_type_ids,
|
| 713 |
+
}
|
| 714 |
+
|
| 715 |
+
@unpack_inputs
|
| 716 |
+
@add_start_docstrings_to_model_forward(CTRL_INPUTS_DOCSTRING)
|
| 717 |
+
@add_code_sample_docstrings(
|
| 718 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 719 |
+
output_type=TFCausalLMOutputWithPast,
|
| 720 |
+
config_class=_CONFIG_FOR_DOC,
|
| 721 |
+
)
|
| 722 |
+
def call(
|
| 723 |
+
self,
|
| 724 |
+
input_ids: TFModelInputType | None = None,
|
| 725 |
+
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
|
| 726 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 727 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 728 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 729 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 730 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 731 |
+
use_cache: Optional[bool] = None,
|
| 732 |
+
output_attentions: Optional[bool] = None,
|
| 733 |
+
output_hidden_states: Optional[bool] = None,
|
| 734 |
+
return_dict: Optional[bool] = None,
|
| 735 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 736 |
+
training: Optional[bool] = False,
|
| 737 |
+
) -> Union[Tuple, TFCausalLMOutputWithPast]:
|
| 738 |
+
r"""
|
| 739 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 740 |
+
Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
|
| 741 |
+
config.vocab_size - 1]`.
|
| 742 |
+
"""
|
| 743 |
+
transformer_outputs = self.transformer(
|
| 744 |
+
input_ids=input_ids,
|
| 745 |
+
past_key_values=past_key_values,
|
| 746 |
+
attention_mask=attention_mask,
|
| 747 |
+
token_type_ids=token_type_ids,
|
| 748 |
+
position_ids=position_ids,
|
| 749 |
+
head_mask=head_mask,
|
| 750 |
+
inputs_embeds=inputs_embeds,
|
| 751 |
+
use_cache=use_cache,
|
| 752 |
+
output_attentions=output_attentions,
|
| 753 |
+
output_hidden_states=output_hidden_states,
|
| 754 |
+
return_dict=return_dict,
|
| 755 |
+
training=training,
|
| 756 |
+
)
|
| 757 |
+
hidden_states = transformer_outputs[0]
|
| 758 |
+
logits = tf.matmul(hidden_states, self.transformer.w.weights, transpose_b=True)
|
| 759 |
+
logits = self.bias_layer(logits)
|
| 760 |
+
|
| 761 |
+
loss = None
|
| 762 |
+
if labels is not None:
|
| 763 |
+
# shift labels to the left and cut last logit token
|
| 764 |
+
shifted_logits = logits[:, :-1]
|
| 765 |
+
labels = labels[:, 1:]
|
| 766 |
+
loss = self.hf_compute_loss(labels, shifted_logits)
|
| 767 |
+
|
| 768 |
+
if not return_dict:
|
| 769 |
+
output = (logits,) + transformer_outputs[1:]
|
| 770 |
+
return ((loss,) + output) if loss is not None else output
|
| 771 |
+
|
| 772 |
+
return TFCausalLMOutputWithPast(
|
| 773 |
+
loss=loss,
|
| 774 |
+
logits=logits,
|
| 775 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 776 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 777 |
+
attentions=transformer_outputs.attentions,
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
def build(self, input_shape=None):
|
| 781 |
+
if self.built:
|
| 782 |
+
return
|
| 783 |
+
self.built = True
|
| 784 |
+
if getattr(self, "transformer", None) is not None:
|
| 785 |
+
with tf.name_scope(self.transformer.name):
|
| 786 |
+
self.transformer.build(None)
|
| 787 |
+
if getattr(self, "bias_layer", None) is not None:
|
| 788 |
+
with tf.name_scope(self.bias_layer.name):
|
| 789 |
+
self.bias_layer.build(None)
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
@add_start_docstrings(
|
| 793 |
+
"""
|
| 794 |
+
The CTRL Model transformer with a sequence classification head on top (linear layer).
|
| 795 |
+
|
| 796 |
+
[`TFCTRLForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 797 |
+
(e.g. GPT-1, GPT-2) do.
|
| 798 |
+
|
| 799 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 800 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 801 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 802 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 803 |
+
each row of the batch).
|
| 804 |
+
""",
|
| 805 |
+
CTRL_START_DOCSTRING,
|
| 806 |
+
)
|
| 807 |
+
class TFCTRLForSequenceClassification(TFCTRLPreTrainedModel, TFSequenceClassificationLoss):
|
| 808 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 809 |
+
super().__init__(config, *inputs, **kwargs)
|
| 810 |
+
self.num_labels = config.num_labels
|
| 811 |
+
self.classifier = keras.layers.Dense(
|
| 812 |
+
config.num_labels,
|
| 813 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 814 |
+
name="classifier",
|
| 815 |
+
use_bias=False,
|
| 816 |
+
)
|
| 817 |
+
self.transformer = TFCTRLMainLayer(config, name="transformer")
|
| 818 |
+
self.config = config
|
| 819 |
+
|
| 820 |
+
def get_output_embeddings(self):
|
| 821 |
+
# Remove after transformers v4.32. Fix this model's `test_model_common_attributes` test too.
|
| 822 |
+
logger.warning(
|
| 823 |
+
"Sequence classification models do not have output embeddings. `.get_output_embeddings` will be removed "
|
| 824 |
+
"in transformers v4.32."
|
| 825 |
+
)
|
| 826 |
+
return self.transformer.w
|
| 827 |
+
|
| 828 |
+
@unpack_inputs
|
| 829 |
+
@add_start_docstrings_to_model_forward(CTRL_INPUTS_DOCSTRING)
|
| 830 |
+
@add_code_sample_docstrings(
|
| 831 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 832 |
+
output_type=TFSequenceClassifierOutput,
|
| 833 |
+
config_class=_CONFIG_FOR_DOC,
|
| 834 |
+
)
|
| 835 |
+
def call(
|
| 836 |
+
self,
|
| 837 |
+
input_ids: TFModelInputType | None = None,
|
| 838 |
+
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
|
| 839 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 840 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 841 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 842 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 843 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 844 |
+
use_cache: Optional[bool] = None,
|
| 845 |
+
output_attentions: Optional[bool] = None,
|
| 846 |
+
output_hidden_states: Optional[bool] = None,
|
| 847 |
+
return_dict: Optional[bool] = None,
|
| 848 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 849 |
+
training: Optional[bool] = False,
|
| 850 |
+
) -> Union[Tuple, TFSequenceClassifierOutput]:
|
| 851 |
+
r"""
|
| 852 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 853 |
+
Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
|
| 854 |
+
config.vocab_size - 1]`.
|
| 855 |
+
"""
|
| 856 |
+
|
| 857 |
+
transformer_outputs = self.transformer(
|
| 858 |
+
input_ids=input_ids,
|
| 859 |
+
past_key_values=past_key_values,
|
| 860 |
+
attention_mask=attention_mask,
|
| 861 |
+
token_type_ids=token_type_ids,
|
| 862 |
+
position_ids=position_ids,
|
| 863 |
+
head_mask=head_mask,
|
| 864 |
+
inputs_embeds=inputs_embeds,
|
| 865 |
+
use_cache=use_cache,
|
| 866 |
+
output_attentions=output_attentions,
|
| 867 |
+
output_hidden_states=output_hidden_states,
|
| 868 |
+
return_dict=return_dict,
|
| 869 |
+
training=training,
|
| 870 |
+
)
|
| 871 |
+
hidden_states = transformer_outputs[0]
|
| 872 |
+
logits = self.classifier(hidden_states)
|
| 873 |
+
logits_shape = shape_list(logits)
|
| 874 |
+
batch_size = logits_shape[0]
|
| 875 |
+
|
| 876 |
+
if self.config.pad_token_id is None:
|
| 877 |
+
last_non_pad_token = tf.fill((batch_size,), value=logits_shape[1] - 1)
|
| 878 |
+
else:
|
| 879 |
+
if input_ids is not None:
|
| 880 |
+
token_indices = tf.range(shape_list(input_ids)[-1])
|
| 881 |
+
non_pad_mask = tf.cast(input_ids != self.config.pad_token_id, token_indices.dtype)
|
| 882 |
+
last_non_pad_token = tf.reduce_max(token_indices * non_pad_mask, axis=-1)
|
| 883 |
+
else:
|
| 884 |
+
last_non_pad_token = tf.fill((batch_size,), value=logits_shape[1] - 1)
|
| 885 |
+
logger.warning_once(
|
| 886 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
| 887 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
| 888 |
+
)
|
| 889 |
+
loss = None
|
| 890 |
+
|
| 891 |
+
pooled_logits = tf.gather(logits, last_non_pad_token, batch_dims=1, axis=1)
|
| 892 |
+
|
| 893 |
+
if labels is not None:
|
| 894 |
+
if self.config.pad_token_id is None and logits_shape[0] != 1:
|
| 895 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 896 |
+
|
| 897 |
+
loss = self.hf_compute_loss(tf.reshape(labels, [-1]), tf.reshape(pooled_logits, [-1, self.num_labels]))
|
| 898 |
+
|
| 899 |
+
if not return_dict:
|
| 900 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 901 |
+
return ((loss,) + output) if loss is not None else output
|
| 902 |
+
|
| 903 |
+
return TFSequenceClassifierOutput(
|
| 904 |
+
loss=loss,
|
| 905 |
+
logits=pooled_logits,
|
| 906 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 907 |
+
attentions=transformer_outputs.attentions,
|
| 908 |
+
)
|
| 909 |
+
|
| 910 |
+
def build(self, input_shape=None):
|
| 911 |
+
if self.built:
|
| 912 |
+
return
|
| 913 |
+
self.built = True
|
| 914 |
+
if getattr(self, "classifier", None) is not None:
|
| 915 |
+
with tf.name_scope(self.classifier.name):
|
| 916 |
+
self.classifier.build([None, None, self.config.n_embd])
|
| 917 |
+
if getattr(self, "transformer", None) is not None:
|
| 918 |
+
with tf.name_scope(self.transformer.name):
|
| 919 |
+
self.transformer.build(None)
|
| 920 |
+
|
| 921 |
+
|
| 922 |
+
__all__ = ["TFCTRLForSequenceClassification", "TFCTRLLMHeadModel", "TFCTRLModel", "TFCTRLPreTrainedModel"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/ctrl/tokenization_ctrl.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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. 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 Salesforce CTRL."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
from typing import Optional, Tuple
|
| 20 |
+
|
| 21 |
+
import regex as re
|
| 22 |
+
|
| 23 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 24 |
+
from ...utils import logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
VOCAB_FILES_NAMES = {
|
| 30 |
+
"vocab_file": "vocab.json",
|
| 31 |
+
"merges_file": "merges.txt",
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
CONTROL_CODES = {
|
| 36 |
+
"Pregnancy": 168629,
|
| 37 |
+
"Christianity": 7675,
|
| 38 |
+
"Explain": 106423,
|
| 39 |
+
"Fitness": 63440,
|
| 40 |
+
"Saving": 63163,
|
| 41 |
+
"Ask": 27171,
|
| 42 |
+
"Ass": 95985,
|
| 43 |
+
"Joke": 163509,
|
| 44 |
+
"Questions": 45622,
|
| 45 |
+
"Thoughts": 49605,
|
| 46 |
+
"Retail": 52342,
|
| 47 |
+
"Feminism": 164338,
|
| 48 |
+
"Writing": 11992,
|
| 49 |
+
"Atheism": 192263,
|
| 50 |
+
"Netflix": 48616,
|
| 51 |
+
"Computing": 39639,
|
| 52 |
+
"Opinion": 43213,
|
| 53 |
+
"Alone": 44967,
|
| 54 |
+
"Funny": 58917,
|
| 55 |
+
"Gaming": 40358,
|
| 56 |
+
"Human": 4088,
|
| 57 |
+
"India": 1331,
|
| 58 |
+
"Joker": 77138,
|
| 59 |
+
"Diet": 36206,
|
| 60 |
+
"Legal": 11859,
|
| 61 |
+
"Norman": 4939,
|
| 62 |
+
"Tip": 72689,
|
| 63 |
+
"Weight": 52343,
|
| 64 |
+
"Movies": 46273,
|
| 65 |
+
"Running": 23425,
|
| 66 |
+
"Science": 2090,
|
| 67 |
+
"Horror": 37793,
|
| 68 |
+
"Confession": 60572,
|
| 69 |
+
"Finance": 12250,
|
| 70 |
+
"Politics": 16360,
|
| 71 |
+
"Scary": 191985,
|
| 72 |
+
"Support": 12654,
|
| 73 |
+
"Technologies": 32516,
|
| 74 |
+
"Teenage": 66160,
|
| 75 |
+
"Event": 32769,
|
| 76 |
+
"Learned": 67460,
|
| 77 |
+
"Notion": 182770,
|
| 78 |
+
"Wikipedia": 37583,
|
| 79 |
+
"Books": 6665,
|
| 80 |
+
"Extract": 76050,
|
| 81 |
+
"Confessions": 102701,
|
| 82 |
+
"Conspiracy": 75932,
|
| 83 |
+
"Links": 63674,
|
| 84 |
+
"Narcissus": 150425,
|
| 85 |
+
"Relationship": 54766,
|
| 86 |
+
"Relationships": 134796,
|
| 87 |
+
"Reviews": 41671,
|
| 88 |
+
"News": 4256,
|
| 89 |
+
"Translation": 26820,
|
| 90 |
+
"multilingual": 128406,
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def get_pairs(word):
|
| 95 |
+
"""
|
| 96 |
+
Return set of symbol pairs in a word.
|
| 97 |
+
|
| 98 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
| 99 |
+
"""
|
| 100 |
+
pairs = set()
|
| 101 |
+
prev_char = word[0]
|
| 102 |
+
for char in word[1:]:
|
| 103 |
+
pairs.add((prev_char, char))
|
| 104 |
+
prev_char = char
|
| 105 |
+
|
| 106 |
+
pairs = set(pairs)
|
| 107 |
+
return pairs
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class CTRLTokenizer(PreTrainedTokenizer):
|
| 111 |
+
"""
|
| 112 |
+
Construct a CTRL tokenizer. Based on Byte-Pair-Encoding.
|
| 113 |
+
|
| 114 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 115 |
+
this superclass for more information regarding those methods.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
vocab_file (`str`):
|
| 119 |
+
Path to the vocabulary file.
|
| 120 |
+
merges_file (`str`):
|
| 121 |
+
Path to the merges file.
|
| 122 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 123 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 124 |
+
token instead.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 128 |
+
control_codes = CONTROL_CODES
|
| 129 |
+
|
| 130 |
+
def __init__(self, vocab_file, merges_file, unk_token="<unk>", **kwargs):
|
| 131 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
| 132 |
+
self.encoder = json.load(vocab_handle)
|
| 133 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 134 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
| 135 |
+
merges = merges_handle.read().split("\n")[1:-1]
|
| 136 |
+
merges = [tuple(merge.split()) for merge in merges]
|
| 137 |
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
| 138 |
+
self.cache = {}
|
| 139 |
+
super().__init__(unk_token=unk_token, **kwargs)
|
| 140 |
+
|
| 141 |
+
@property
|
| 142 |
+
def vocab_size(self):
|
| 143 |
+
return len(self.encoder)
|
| 144 |
+
|
| 145 |
+
def get_vocab(self):
|
| 146 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 147 |
+
|
| 148 |
+
def bpe(self, token):
|
| 149 |
+
if token in self.cache:
|
| 150 |
+
return self.cache[token]
|
| 151 |
+
word = tuple(token)
|
| 152 |
+
word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
|
| 153 |
+
pairs = get_pairs(word)
|
| 154 |
+
|
| 155 |
+
if not pairs:
|
| 156 |
+
return token
|
| 157 |
+
|
| 158 |
+
while True:
|
| 159 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 160 |
+
if bigram not in self.bpe_ranks:
|
| 161 |
+
break
|
| 162 |
+
first, second = bigram
|
| 163 |
+
new_word = []
|
| 164 |
+
i = 0
|
| 165 |
+
while i < len(word):
|
| 166 |
+
try:
|
| 167 |
+
j = word.index(first, i)
|
| 168 |
+
except ValueError:
|
| 169 |
+
new_word.extend(word[i:])
|
| 170 |
+
break
|
| 171 |
+
else:
|
| 172 |
+
new_word.extend(word[i:j])
|
| 173 |
+
i = j
|
| 174 |
+
|
| 175 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 176 |
+
new_word.append(first + second)
|
| 177 |
+
i += 2
|
| 178 |
+
else:
|
| 179 |
+
new_word.append(word[i])
|
| 180 |
+
i += 1
|
| 181 |
+
new_word = tuple(new_word)
|
| 182 |
+
word = new_word
|
| 183 |
+
if len(word) == 1:
|
| 184 |
+
break
|
| 185 |
+
else:
|
| 186 |
+
pairs = get_pairs(word)
|
| 187 |
+
word = "@@ ".join(word)
|
| 188 |
+
word = word[:-4]
|
| 189 |
+
self.cache[token] = word
|
| 190 |
+
return word
|
| 191 |
+
|
| 192 |
+
def _tokenize(self, text):
|
| 193 |
+
"""Tokenize a string."""
|
| 194 |
+
split_tokens = []
|
| 195 |
+
|
| 196 |
+
words = re.findall(r"\S+\n?", text)
|
| 197 |
+
|
| 198 |
+
for token in words:
|
| 199 |
+
split_tokens.extend(list(self.bpe(token).split(" ")))
|
| 200 |
+
return split_tokens
|
| 201 |
+
|
| 202 |
+
def _convert_token_to_id(self, token):
|
| 203 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 204 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 205 |
+
|
| 206 |
+
def _convert_id_to_token(self, index):
|
| 207 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 208 |
+
return self.decoder.get(index, self.unk_token)
|
| 209 |
+
|
| 210 |
+
def convert_tokens_to_string(self, tokens):
|
| 211 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 212 |
+
out_string = " ".join(tokens).replace("@@ ", "").strip()
|
| 213 |
+
return out_string
|
| 214 |
+
|
| 215 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 216 |
+
if not os.path.isdir(save_directory):
|
| 217 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 218 |
+
return
|
| 219 |
+
vocab_file = os.path.join(
|
| 220 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 221 |
+
)
|
| 222 |
+
merge_file = os.path.join(
|
| 223 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 227 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
| 228 |
+
|
| 229 |
+
index = 0
|
| 230 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
| 231 |
+
writer.write("#version: 0.2\n")
|
| 232 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
| 233 |
+
if index != token_index:
|
| 234 |
+
logger.warning(
|
| 235 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
| 236 |
+
" Please check that the tokenizer is not corrupted!"
|
| 237 |
+
)
|
| 238 |
+
index = token_index
|
| 239 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
| 240 |
+
index += 1
|
| 241 |
+
|
| 242 |
+
return vocab_file, merge_file
|
| 243 |
+
|
| 244 |
+
# def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
|
| 245 |
+
# filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
|
| 246 |
+
# tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
|
| 247 |
+
# tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
|
| 248 |
+
# return ''.join(tokens_generated_so_far)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
__all__ = ["CTRLTokenizer"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cvt/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_cvt import *
|
| 22 |
+
from .modeling_cvt import *
|
| 23 |
+
from .modeling_tf_cvt import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cvt/configuration_cvt.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""CvT model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class CvtConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`CvtModel`]. It is used to instantiate a CvT model
|
| 27 |
+
according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 28 |
+
defaults will yield a similar configuration to that of the CvT
|
| 29 |
+
[microsoft/cvt-13](https://huggingface.co/microsoft/cvt-13) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 36 |
+
The number of input channels.
|
| 37 |
+
patch_sizes (`List[int]`, *optional*, defaults to `[7, 3, 3]`):
|
| 38 |
+
The kernel size of each encoder's patch embedding.
|
| 39 |
+
patch_stride (`List[int]`, *optional*, defaults to `[4, 2, 2]`):
|
| 40 |
+
The stride size of each encoder's patch embedding.
|
| 41 |
+
patch_padding (`List[int]`, *optional*, defaults to `[2, 1, 1]`):
|
| 42 |
+
The padding size of each encoder's patch embedding.
|
| 43 |
+
embed_dim (`List[int]`, *optional*, defaults to `[64, 192, 384]`):
|
| 44 |
+
Dimension of each of the encoder blocks.
|
| 45 |
+
num_heads (`List[int]`, *optional*, defaults to `[1, 3, 6]`):
|
| 46 |
+
Number of attention heads for each attention layer in each block of the Transformer encoder.
|
| 47 |
+
depth (`List[int]`, *optional*, defaults to `[1, 2, 10]`):
|
| 48 |
+
The number of layers in each encoder block.
|
| 49 |
+
mlp_ratios (`List[float]`, *optional*, defaults to `[4.0, 4.0, 4.0, 4.0]`):
|
| 50 |
+
Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the
|
| 51 |
+
encoder blocks.
|
| 52 |
+
attention_drop_rate (`List[float]`, *optional*, defaults to `[0.0, 0.0, 0.0]`):
|
| 53 |
+
The dropout ratio for the attention probabilities.
|
| 54 |
+
drop_rate (`List[float]`, *optional*, defaults to `[0.0, 0.0, 0.0]`):
|
| 55 |
+
The dropout ratio for the patch embeddings probabilities.
|
| 56 |
+
drop_path_rate (`List[float]`, *optional*, defaults to `[0.0, 0.0, 0.1]`):
|
| 57 |
+
The dropout probability for stochastic depth, used in the blocks of the Transformer encoder.
|
| 58 |
+
qkv_bias (`List[bool]`, *optional*, defaults to `[True, True, True]`):
|
| 59 |
+
The bias bool for query, key and value in attentions
|
| 60 |
+
cls_token (`List[bool]`, *optional*, defaults to `[False, False, True]`):
|
| 61 |
+
Whether or not to add a classification token to the output of each of the last 3 stages.
|
| 62 |
+
qkv_projection_method (`List[string]`, *optional*, defaults to ["dw_bn", "dw_bn", "dw_bn"]`):
|
| 63 |
+
The projection method for query, key and value Default is depth-wise convolutions with batch norm. For
|
| 64 |
+
Linear projection use "avg".
|
| 65 |
+
kernel_qkv (`List[int]`, *optional*, defaults to `[3, 3, 3]`):
|
| 66 |
+
The kernel size for query, key and value in attention layer
|
| 67 |
+
padding_kv (`List[int]`, *optional*, defaults to `[1, 1, 1]`):
|
| 68 |
+
The padding size for key and value in attention layer
|
| 69 |
+
stride_kv (`List[int]`, *optional*, defaults to `[2, 2, 2]`):
|
| 70 |
+
The stride size for key and value in attention layer
|
| 71 |
+
padding_q (`List[int]`, *optional*, defaults to `[1, 1, 1]`):
|
| 72 |
+
The padding size for query in attention layer
|
| 73 |
+
stride_q (`List[int]`, *optional*, defaults to `[1, 1, 1]`):
|
| 74 |
+
The stride size for query in attention layer
|
| 75 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 76 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 77 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-6):
|
| 78 |
+
The epsilon used by the layer normalization layers.
|
| 79 |
+
|
| 80 |
+
Example:
|
| 81 |
+
|
| 82 |
+
```python
|
| 83 |
+
>>> from transformers import CvtConfig, CvtModel
|
| 84 |
+
|
| 85 |
+
>>> # Initializing a Cvt msft/cvt style configuration
|
| 86 |
+
>>> configuration = CvtConfig()
|
| 87 |
+
|
| 88 |
+
>>> # Initializing a model (with random weights) from the msft/cvt style configuration
|
| 89 |
+
>>> model = CvtModel(configuration)
|
| 90 |
+
|
| 91 |
+
>>> # Accessing the model configuration
|
| 92 |
+
>>> configuration = model.config
|
| 93 |
+
```"""
|
| 94 |
+
|
| 95 |
+
model_type = "cvt"
|
| 96 |
+
|
| 97 |
+
def __init__(
|
| 98 |
+
self,
|
| 99 |
+
num_channels=3,
|
| 100 |
+
patch_sizes=[7, 3, 3],
|
| 101 |
+
patch_stride=[4, 2, 2],
|
| 102 |
+
patch_padding=[2, 1, 1],
|
| 103 |
+
embed_dim=[64, 192, 384],
|
| 104 |
+
num_heads=[1, 3, 6],
|
| 105 |
+
depth=[1, 2, 10],
|
| 106 |
+
mlp_ratio=[4.0, 4.0, 4.0],
|
| 107 |
+
attention_drop_rate=[0.0, 0.0, 0.0],
|
| 108 |
+
drop_rate=[0.0, 0.0, 0.0],
|
| 109 |
+
drop_path_rate=[0.0, 0.0, 0.1],
|
| 110 |
+
qkv_bias=[True, True, True],
|
| 111 |
+
cls_token=[False, False, True],
|
| 112 |
+
qkv_projection_method=["dw_bn", "dw_bn", "dw_bn"],
|
| 113 |
+
kernel_qkv=[3, 3, 3],
|
| 114 |
+
padding_kv=[1, 1, 1],
|
| 115 |
+
stride_kv=[2, 2, 2],
|
| 116 |
+
padding_q=[1, 1, 1],
|
| 117 |
+
stride_q=[1, 1, 1],
|
| 118 |
+
initializer_range=0.02,
|
| 119 |
+
layer_norm_eps=1e-12,
|
| 120 |
+
**kwargs,
|
| 121 |
+
):
|
| 122 |
+
super().__init__(**kwargs)
|
| 123 |
+
self.num_channels = num_channels
|
| 124 |
+
self.patch_sizes = patch_sizes
|
| 125 |
+
self.patch_stride = patch_stride
|
| 126 |
+
self.patch_padding = patch_padding
|
| 127 |
+
self.embed_dim = embed_dim
|
| 128 |
+
self.num_heads = num_heads
|
| 129 |
+
self.depth = depth
|
| 130 |
+
self.mlp_ratio = mlp_ratio
|
| 131 |
+
self.attention_drop_rate = attention_drop_rate
|
| 132 |
+
self.drop_rate = drop_rate
|
| 133 |
+
self.drop_path_rate = drop_path_rate
|
| 134 |
+
self.qkv_bias = qkv_bias
|
| 135 |
+
self.cls_token = cls_token
|
| 136 |
+
self.qkv_projection_method = qkv_projection_method
|
| 137 |
+
self.kernel_qkv = kernel_qkv
|
| 138 |
+
self.padding_kv = padding_kv
|
| 139 |
+
self.stride_kv = stride_kv
|
| 140 |
+
self.padding_q = padding_q
|
| 141 |
+
self.stride_q = stride_q
|
| 142 |
+
self.initializer_range = initializer_range
|
| 143 |
+
self.layer_norm_eps = layer_norm_eps
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
__all__ = ["CvtConfig"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cvt/convert_cvt_original_pytorch_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert CvT checkpoints from the original repository.
|
| 16 |
+
|
| 17 |
+
URL: https://github.com/microsoft/CvT"""
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import json
|
| 21 |
+
from collections import OrderedDict
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
from huggingface_hub import hf_hub_download
|
| 26 |
+
|
| 27 |
+
from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def embeddings(idx):
|
| 31 |
+
"""
|
| 32 |
+
The function helps in renaming embedding layer weights.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
idx: stage number in original model
|
| 36 |
+
"""
|
| 37 |
+
embed = []
|
| 38 |
+
embed.append(
|
| 39 |
+
(
|
| 40 |
+
f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight",
|
| 41 |
+
f"stage{idx}.patch_embed.proj.weight",
|
| 42 |
+
)
|
| 43 |
+
)
|
| 44 |
+
embed.append(
|
| 45 |
+
(
|
| 46 |
+
f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias",
|
| 47 |
+
f"stage{idx}.patch_embed.proj.bias",
|
| 48 |
+
)
|
| 49 |
+
)
|
| 50 |
+
embed.append(
|
| 51 |
+
(
|
| 52 |
+
f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight",
|
| 53 |
+
f"stage{idx}.patch_embed.norm.weight",
|
| 54 |
+
)
|
| 55 |
+
)
|
| 56 |
+
embed.append(
|
| 57 |
+
(
|
| 58 |
+
f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias",
|
| 59 |
+
f"stage{idx}.patch_embed.norm.bias",
|
| 60 |
+
)
|
| 61 |
+
)
|
| 62 |
+
return embed
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def attention(idx, cnt):
|
| 66 |
+
"""
|
| 67 |
+
The function helps in renaming attention block layers weights.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
idx: stage number in original model
|
| 71 |
+
cnt: count of blocks in each stage
|
| 72 |
+
"""
|
| 73 |
+
attention_weights = []
|
| 74 |
+
attention_weights.append(
|
| 75 |
+
(
|
| 76 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight",
|
| 77 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight",
|
| 78 |
+
)
|
| 79 |
+
)
|
| 80 |
+
attention_weights.append(
|
| 81 |
+
(
|
| 82 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight",
|
| 83 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight",
|
| 84 |
+
)
|
| 85 |
+
)
|
| 86 |
+
attention_weights.append(
|
| 87 |
+
(
|
| 88 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias",
|
| 89 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias",
|
| 90 |
+
)
|
| 91 |
+
)
|
| 92 |
+
attention_weights.append(
|
| 93 |
+
(
|
| 94 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean",
|
| 95 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean",
|
| 96 |
+
)
|
| 97 |
+
)
|
| 98 |
+
attention_weights.append(
|
| 99 |
+
(
|
| 100 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var",
|
| 101 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var",
|
| 102 |
+
)
|
| 103 |
+
)
|
| 104 |
+
attention_weights.append(
|
| 105 |
+
(
|
| 106 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked",
|
| 107 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked",
|
| 108 |
+
)
|
| 109 |
+
)
|
| 110 |
+
attention_weights.append(
|
| 111 |
+
(
|
| 112 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight",
|
| 113 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight",
|
| 114 |
+
)
|
| 115 |
+
)
|
| 116 |
+
attention_weights.append(
|
| 117 |
+
(
|
| 118 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight",
|
| 119 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight",
|
| 120 |
+
)
|
| 121 |
+
)
|
| 122 |
+
attention_weights.append(
|
| 123 |
+
(
|
| 124 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias",
|
| 125 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias",
|
| 126 |
+
)
|
| 127 |
+
)
|
| 128 |
+
attention_weights.append(
|
| 129 |
+
(
|
| 130 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean",
|
| 131 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean",
|
| 132 |
+
)
|
| 133 |
+
)
|
| 134 |
+
attention_weights.append(
|
| 135 |
+
(
|
| 136 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var",
|
| 137 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var",
|
| 138 |
+
)
|
| 139 |
+
)
|
| 140 |
+
attention_weights.append(
|
| 141 |
+
(
|
| 142 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked",
|
| 143 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked",
|
| 144 |
+
)
|
| 145 |
+
)
|
| 146 |
+
attention_weights.append(
|
| 147 |
+
(
|
| 148 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight",
|
| 149 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight",
|
| 150 |
+
)
|
| 151 |
+
)
|
| 152 |
+
attention_weights.append(
|
| 153 |
+
(
|
| 154 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight",
|
| 155 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight",
|
| 156 |
+
)
|
| 157 |
+
)
|
| 158 |
+
attention_weights.append(
|
| 159 |
+
(
|
| 160 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias",
|
| 161 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias",
|
| 162 |
+
)
|
| 163 |
+
)
|
| 164 |
+
attention_weights.append(
|
| 165 |
+
(
|
| 166 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean",
|
| 167 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean",
|
| 168 |
+
)
|
| 169 |
+
)
|
| 170 |
+
attention_weights.append(
|
| 171 |
+
(
|
| 172 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var",
|
| 173 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var",
|
| 174 |
+
)
|
| 175 |
+
)
|
| 176 |
+
attention_weights.append(
|
| 177 |
+
(
|
| 178 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked",
|
| 179 |
+
f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked",
|
| 180 |
+
)
|
| 181 |
+
)
|
| 182 |
+
attention_weights.append(
|
| 183 |
+
(
|
| 184 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight",
|
| 185 |
+
f"stage{idx}.blocks.{cnt}.attn.proj_q.weight",
|
| 186 |
+
)
|
| 187 |
+
)
|
| 188 |
+
attention_weights.append(
|
| 189 |
+
(
|
| 190 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias",
|
| 191 |
+
f"stage{idx}.blocks.{cnt}.attn.proj_q.bias",
|
| 192 |
+
)
|
| 193 |
+
)
|
| 194 |
+
attention_weights.append(
|
| 195 |
+
(
|
| 196 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight",
|
| 197 |
+
f"stage{idx}.blocks.{cnt}.attn.proj_k.weight",
|
| 198 |
+
)
|
| 199 |
+
)
|
| 200 |
+
attention_weights.append(
|
| 201 |
+
(
|
| 202 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias",
|
| 203 |
+
f"stage{idx}.blocks.{cnt}.attn.proj_k.bias",
|
| 204 |
+
)
|
| 205 |
+
)
|
| 206 |
+
attention_weights.append(
|
| 207 |
+
(
|
| 208 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight",
|
| 209 |
+
f"stage{idx}.blocks.{cnt}.attn.proj_v.weight",
|
| 210 |
+
)
|
| 211 |
+
)
|
| 212 |
+
attention_weights.append(
|
| 213 |
+
(
|
| 214 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias",
|
| 215 |
+
f"stage{idx}.blocks.{cnt}.attn.proj_v.bias",
|
| 216 |
+
)
|
| 217 |
+
)
|
| 218 |
+
attention_weights.append(
|
| 219 |
+
(
|
| 220 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight",
|
| 221 |
+
f"stage{idx}.blocks.{cnt}.attn.proj.weight",
|
| 222 |
+
)
|
| 223 |
+
)
|
| 224 |
+
attention_weights.append(
|
| 225 |
+
(
|
| 226 |
+
f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias",
|
| 227 |
+
f"stage{idx}.blocks.{cnt}.attn.proj.bias",
|
| 228 |
+
)
|
| 229 |
+
)
|
| 230 |
+
attention_weights.append(
|
| 231 |
+
(f"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight", f"stage{idx}.blocks.{cnt}.mlp.fc1.weight")
|
| 232 |
+
)
|
| 233 |
+
attention_weights.append(
|
| 234 |
+
(f"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias", f"stage{idx}.blocks.{cnt}.mlp.fc1.bias")
|
| 235 |
+
)
|
| 236 |
+
attention_weights.append(
|
| 237 |
+
(f"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight", f"stage{idx}.blocks.{cnt}.mlp.fc2.weight")
|
| 238 |
+
)
|
| 239 |
+
attention_weights.append(
|
| 240 |
+
(f"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias", f"stage{idx}.blocks.{cnt}.mlp.fc2.bias")
|
| 241 |
+
)
|
| 242 |
+
attention_weights.append(
|
| 243 |
+
(f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight", f"stage{idx}.blocks.{cnt}.norm1.weight")
|
| 244 |
+
)
|
| 245 |
+
attention_weights.append(
|
| 246 |
+
(f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias", f"stage{idx}.blocks.{cnt}.norm1.bias")
|
| 247 |
+
)
|
| 248 |
+
attention_weights.append(
|
| 249 |
+
(f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight", f"stage{idx}.blocks.{cnt}.norm2.weight")
|
| 250 |
+
)
|
| 251 |
+
attention_weights.append(
|
| 252 |
+
(f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias", f"stage{idx}.blocks.{cnt}.norm2.bias")
|
| 253 |
+
)
|
| 254 |
+
return attention_weights
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def cls_token(idx):
|
| 258 |
+
"""
|
| 259 |
+
Function helps in renaming cls_token weights
|
| 260 |
+
"""
|
| 261 |
+
token = []
|
| 262 |
+
token.append((f"cvt.encoder.stages.{idx}.cls_token", "stage2.cls_token"))
|
| 263 |
+
return token
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def final():
|
| 267 |
+
"""
|
| 268 |
+
Function helps in renaming final classification layer
|
| 269 |
+
"""
|
| 270 |
+
head = []
|
| 271 |
+
head.append(("layernorm.weight", "norm.weight"))
|
| 272 |
+
head.append(("layernorm.bias", "norm.bias"))
|
| 273 |
+
head.append(("classifier.weight", "head.weight"))
|
| 274 |
+
head.append(("classifier.bias", "head.bias"))
|
| 275 |
+
return head
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def convert_cvt_checkpoint(cvt_model, image_size, cvt_file_name, pytorch_dump_folder):
|
| 279 |
+
"""
|
| 280 |
+
Fucntion to convert the microsoft cvt checkpoint to huggingface checkpoint
|
| 281 |
+
"""
|
| 282 |
+
img_labels_file = "imagenet-1k-id2label.json"
|
| 283 |
+
num_labels = 1000
|
| 284 |
+
|
| 285 |
+
repo_id = "huggingface/label-files"
|
| 286 |
+
num_labels = num_labels
|
| 287 |
+
id2label = json.loads(Path(hf_hub_download(repo_id, img_labels_file, repo_type="dataset")).read_text())
|
| 288 |
+
id2label = {int(k): v for k, v in id2label.items()}
|
| 289 |
+
|
| 290 |
+
id2label = id2label
|
| 291 |
+
label2id = {v: k for k, v in id2label.items()}
|
| 292 |
+
|
| 293 |
+
config = config = CvtConfig(num_labels=num_labels, id2label=id2label, label2id=label2id)
|
| 294 |
+
|
| 295 |
+
# For depth size 13 (13 = 1+2+10)
|
| 296 |
+
if cvt_model.rsplit("/", 1)[-1][4:6] == "13":
|
| 297 |
+
config.depth = [1, 2, 10]
|
| 298 |
+
|
| 299 |
+
# For depth size 21 (21 = 1+4+16)
|
| 300 |
+
elif cvt_model.rsplit("/", 1)[-1][4:6] == "21":
|
| 301 |
+
config.depth = [1, 4, 16]
|
| 302 |
+
|
| 303 |
+
# For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20)
|
| 304 |
+
else:
|
| 305 |
+
config.depth = [2, 2, 20]
|
| 306 |
+
config.num_heads = [3, 12, 16]
|
| 307 |
+
config.embed_dim = [192, 768, 1024]
|
| 308 |
+
|
| 309 |
+
model = CvtForImageClassification(config)
|
| 310 |
+
image_processor = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k")
|
| 311 |
+
image_processor.size["shortest_edge"] = image_size
|
| 312 |
+
original_weights = torch.load(cvt_file_name, map_location=torch.device("cpu"))
|
| 313 |
+
|
| 314 |
+
huggingface_weights = OrderedDict()
|
| 315 |
+
list_of_state_dict = []
|
| 316 |
+
|
| 317 |
+
for idx in range(len(config.depth)):
|
| 318 |
+
if config.cls_token[idx]:
|
| 319 |
+
list_of_state_dict = list_of_state_dict + cls_token(idx)
|
| 320 |
+
list_of_state_dict = list_of_state_dict + embeddings(idx)
|
| 321 |
+
for cnt in range(config.depth[idx]):
|
| 322 |
+
list_of_state_dict = list_of_state_dict + attention(idx, cnt)
|
| 323 |
+
|
| 324 |
+
list_of_state_dict = list_of_state_dict + final()
|
| 325 |
+
for gg in list_of_state_dict:
|
| 326 |
+
print(gg)
|
| 327 |
+
for i in range(len(list_of_state_dict)):
|
| 328 |
+
huggingface_weights[list_of_state_dict[i][0]] = original_weights[list_of_state_dict[i][1]]
|
| 329 |
+
|
| 330 |
+
model.load_state_dict(huggingface_weights)
|
| 331 |
+
model.save_pretrained(pytorch_dump_folder)
|
| 332 |
+
image_processor.save_pretrained(pytorch_dump_folder)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
# Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al
|
| 336 |
+
|
| 337 |
+
if __name__ == "__main__":
|
| 338 |
+
parser = argparse.ArgumentParser()
|
| 339 |
+
parser.add_argument(
|
| 340 |
+
"--cvt_model",
|
| 341 |
+
default="cvt-w24",
|
| 342 |
+
type=str,
|
| 343 |
+
help="Name of the cvt model you'd like to convert.",
|
| 344 |
+
)
|
| 345 |
+
parser.add_argument(
|
| 346 |
+
"--image_size",
|
| 347 |
+
default=384,
|
| 348 |
+
type=int,
|
| 349 |
+
help="Input Image Size",
|
| 350 |
+
)
|
| 351 |
+
parser.add_argument(
|
| 352 |
+
"--cvt_file_name",
|
| 353 |
+
default=r"cvtmodels\CvT-w24-384x384-IN-22k.pth",
|
| 354 |
+
type=str,
|
| 355 |
+
help="Input Image Size",
|
| 356 |
+
)
|
| 357 |
+
parser.add_argument(
|
| 358 |
+
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
args = parser.parse_args()
|
| 362 |
+
convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/cvt/modeling_cvt.py
ADDED
|
@@ -0,0 +1,725 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch CvT model."""
|
| 16 |
+
|
| 17 |
+
import collections.abc
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 25 |
+
|
| 26 |
+
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
|
| 27 |
+
from ...modeling_outputs import ImageClassifierOutputWithNoAttention, ModelOutput
|
| 28 |
+
from ...modeling_utils import PreTrainedModel, find_pruneable_heads_and_indices, prune_linear_layer
|
| 29 |
+
from ...utils import logging
|
| 30 |
+
from .configuration_cvt import CvtConfig
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
# General docstring
|
| 36 |
+
_CONFIG_FOR_DOC = "CvtConfig"
|
| 37 |
+
|
| 38 |
+
# Base docstring
|
| 39 |
+
_CHECKPOINT_FOR_DOC = "microsoft/cvt-13"
|
| 40 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 384, 14, 14]
|
| 41 |
+
|
| 42 |
+
# Image classification docstring
|
| 43 |
+
_IMAGE_CLASS_CHECKPOINT = "microsoft/cvt-13"
|
| 44 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class BaseModelOutputWithCLSToken(ModelOutput):
|
| 49 |
+
"""
|
| 50 |
+
Base class for model's outputs, with potential hidden states and attentions.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 54 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 55 |
+
cls_token_value (`torch.FloatTensor` of shape `(batch_size, 1, hidden_size)`):
|
| 56 |
+
Classification token at the output of the last layer of the model.
|
| 57 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 58 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 59 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 60 |
+
plus the initial embedding outputs.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
last_hidden_state: torch.FloatTensor = None
|
| 64 |
+
cls_token_value: torch.FloatTensor = None
|
| 65 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# Copied from transformers.models.beit.modeling_beit.drop_path
|
| 69 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 70 |
+
"""
|
| 71 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 72 |
+
|
| 73 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 74 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 75 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 76 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 77 |
+
argument.
|
| 78 |
+
"""
|
| 79 |
+
if drop_prob == 0.0 or not training:
|
| 80 |
+
return input
|
| 81 |
+
keep_prob = 1 - drop_prob
|
| 82 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 83 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 84 |
+
random_tensor.floor_() # binarize
|
| 85 |
+
output = input.div(keep_prob) * random_tensor
|
| 86 |
+
return output
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Copied from transformers.models.beit.modeling_beit.BeitDropPath
|
| 90 |
+
class CvtDropPath(nn.Module):
|
| 91 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 92 |
+
|
| 93 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 94 |
+
super().__init__()
|
| 95 |
+
self.drop_prob = drop_prob
|
| 96 |
+
|
| 97 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 98 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 99 |
+
|
| 100 |
+
def extra_repr(self) -> str:
|
| 101 |
+
return "p={}".format(self.drop_prob)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class CvtEmbeddings(nn.Module):
|
| 105 |
+
"""
|
| 106 |
+
Construct the CvT embeddings.
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
def __init__(self, patch_size, num_channels, embed_dim, stride, padding, dropout_rate):
|
| 110 |
+
super().__init__()
|
| 111 |
+
self.convolution_embeddings = CvtConvEmbeddings(
|
| 112 |
+
patch_size=patch_size, num_channels=num_channels, embed_dim=embed_dim, stride=stride, padding=padding
|
| 113 |
+
)
|
| 114 |
+
self.dropout = nn.Dropout(dropout_rate)
|
| 115 |
+
|
| 116 |
+
def forward(self, pixel_values):
|
| 117 |
+
hidden_state = self.convolution_embeddings(pixel_values)
|
| 118 |
+
hidden_state = self.dropout(hidden_state)
|
| 119 |
+
return hidden_state
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class CvtConvEmbeddings(nn.Module):
|
| 123 |
+
"""
|
| 124 |
+
Image to Conv Embedding.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
def __init__(self, patch_size, num_channels, embed_dim, stride, padding):
|
| 128 |
+
super().__init__()
|
| 129 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 130 |
+
self.patch_size = patch_size
|
| 131 |
+
self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=stride, padding=padding)
|
| 132 |
+
self.normalization = nn.LayerNorm(embed_dim)
|
| 133 |
+
|
| 134 |
+
def forward(self, pixel_values):
|
| 135 |
+
pixel_values = self.projection(pixel_values)
|
| 136 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 137 |
+
hidden_size = height * width
|
| 138 |
+
# rearrange "b c h w -> b (h w) c"
|
| 139 |
+
pixel_values = pixel_values.view(batch_size, num_channels, hidden_size).permute(0, 2, 1)
|
| 140 |
+
if self.normalization:
|
| 141 |
+
pixel_values = self.normalization(pixel_values)
|
| 142 |
+
# rearrange "b (h w) c" -> b c h w"
|
| 143 |
+
pixel_values = pixel_values.permute(0, 2, 1).view(batch_size, num_channels, height, width)
|
| 144 |
+
return pixel_values
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class CvtSelfAttentionConvProjection(nn.Module):
|
| 148 |
+
def __init__(self, embed_dim, kernel_size, padding, stride):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.convolution = nn.Conv2d(
|
| 151 |
+
embed_dim,
|
| 152 |
+
embed_dim,
|
| 153 |
+
kernel_size=kernel_size,
|
| 154 |
+
padding=padding,
|
| 155 |
+
stride=stride,
|
| 156 |
+
bias=False,
|
| 157 |
+
groups=embed_dim,
|
| 158 |
+
)
|
| 159 |
+
self.normalization = nn.BatchNorm2d(embed_dim)
|
| 160 |
+
|
| 161 |
+
def forward(self, hidden_state):
|
| 162 |
+
hidden_state = self.convolution(hidden_state)
|
| 163 |
+
hidden_state = self.normalization(hidden_state)
|
| 164 |
+
return hidden_state
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class CvtSelfAttentionLinearProjection(nn.Module):
|
| 168 |
+
def forward(self, hidden_state):
|
| 169 |
+
batch_size, num_channels, height, width = hidden_state.shape
|
| 170 |
+
hidden_size = height * width
|
| 171 |
+
# rearrange " b c h w -> b (h w) c"
|
| 172 |
+
hidden_state = hidden_state.view(batch_size, num_channels, hidden_size).permute(0, 2, 1)
|
| 173 |
+
return hidden_state
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class CvtSelfAttentionProjection(nn.Module):
|
| 177 |
+
def __init__(self, embed_dim, kernel_size, padding, stride, projection_method="dw_bn"):
|
| 178 |
+
super().__init__()
|
| 179 |
+
if projection_method == "dw_bn":
|
| 180 |
+
self.convolution_projection = CvtSelfAttentionConvProjection(embed_dim, kernel_size, padding, stride)
|
| 181 |
+
self.linear_projection = CvtSelfAttentionLinearProjection()
|
| 182 |
+
|
| 183 |
+
def forward(self, hidden_state):
|
| 184 |
+
hidden_state = self.convolution_projection(hidden_state)
|
| 185 |
+
hidden_state = self.linear_projection(hidden_state)
|
| 186 |
+
return hidden_state
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class CvtSelfAttention(nn.Module):
|
| 190 |
+
def __init__(
|
| 191 |
+
self,
|
| 192 |
+
num_heads,
|
| 193 |
+
embed_dim,
|
| 194 |
+
kernel_size,
|
| 195 |
+
padding_q,
|
| 196 |
+
padding_kv,
|
| 197 |
+
stride_q,
|
| 198 |
+
stride_kv,
|
| 199 |
+
qkv_projection_method,
|
| 200 |
+
qkv_bias,
|
| 201 |
+
attention_drop_rate,
|
| 202 |
+
with_cls_token=True,
|
| 203 |
+
**kwargs,
|
| 204 |
+
):
|
| 205 |
+
super().__init__()
|
| 206 |
+
self.scale = embed_dim**-0.5
|
| 207 |
+
self.with_cls_token = with_cls_token
|
| 208 |
+
self.embed_dim = embed_dim
|
| 209 |
+
self.num_heads = num_heads
|
| 210 |
+
|
| 211 |
+
self.convolution_projection_query = CvtSelfAttentionProjection(
|
| 212 |
+
embed_dim,
|
| 213 |
+
kernel_size,
|
| 214 |
+
padding_q,
|
| 215 |
+
stride_q,
|
| 216 |
+
projection_method="linear" if qkv_projection_method == "avg" else qkv_projection_method,
|
| 217 |
+
)
|
| 218 |
+
self.convolution_projection_key = CvtSelfAttentionProjection(
|
| 219 |
+
embed_dim, kernel_size, padding_kv, stride_kv, projection_method=qkv_projection_method
|
| 220 |
+
)
|
| 221 |
+
self.convolution_projection_value = CvtSelfAttentionProjection(
|
| 222 |
+
embed_dim, kernel_size, padding_kv, stride_kv, projection_method=qkv_projection_method
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
self.projection_query = nn.Linear(embed_dim, embed_dim, bias=qkv_bias)
|
| 226 |
+
self.projection_key = nn.Linear(embed_dim, embed_dim, bias=qkv_bias)
|
| 227 |
+
self.projection_value = nn.Linear(embed_dim, embed_dim, bias=qkv_bias)
|
| 228 |
+
|
| 229 |
+
self.dropout = nn.Dropout(attention_drop_rate)
|
| 230 |
+
|
| 231 |
+
def rearrange_for_multi_head_attention(self, hidden_state):
|
| 232 |
+
batch_size, hidden_size, _ = hidden_state.shape
|
| 233 |
+
head_dim = self.embed_dim // self.num_heads
|
| 234 |
+
# rearrange 'b t (h d) -> b h t d'
|
| 235 |
+
return hidden_state.view(batch_size, hidden_size, self.num_heads, head_dim).permute(0, 2, 1, 3)
|
| 236 |
+
|
| 237 |
+
def forward(self, hidden_state, height, width):
|
| 238 |
+
if self.with_cls_token:
|
| 239 |
+
cls_token, hidden_state = torch.split(hidden_state, [1, height * width], 1)
|
| 240 |
+
batch_size, hidden_size, num_channels = hidden_state.shape
|
| 241 |
+
# rearrange "b (h w) c -> b c h w"
|
| 242 |
+
hidden_state = hidden_state.permute(0, 2, 1).view(batch_size, num_channels, height, width)
|
| 243 |
+
|
| 244 |
+
key = self.convolution_projection_key(hidden_state)
|
| 245 |
+
query = self.convolution_projection_query(hidden_state)
|
| 246 |
+
value = self.convolution_projection_value(hidden_state)
|
| 247 |
+
|
| 248 |
+
if self.with_cls_token:
|
| 249 |
+
query = torch.cat((cls_token, query), dim=1)
|
| 250 |
+
key = torch.cat((cls_token, key), dim=1)
|
| 251 |
+
value = torch.cat((cls_token, value), dim=1)
|
| 252 |
+
|
| 253 |
+
head_dim = self.embed_dim // self.num_heads
|
| 254 |
+
|
| 255 |
+
query = self.rearrange_for_multi_head_attention(self.projection_query(query))
|
| 256 |
+
key = self.rearrange_for_multi_head_attention(self.projection_key(key))
|
| 257 |
+
value = self.rearrange_for_multi_head_attention(self.projection_value(value))
|
| 258 |
+
|
| 259 |
+
attention_score = torch.einsum("bhlk,bhtk->bhlt", [query, key]) * self.scale
|
| 260 |
+
attention_probs = torch.nn.functional.softmax(attention_score, dim=-1)
|
| 261 |
+
attention_probs = self.dropout(attention_probs)
|
| 262 |
+
|
| 263 |
+
context = torch.einsum("bhlt,bhtv->bhlv", [attention_probs, value])
|
| 264 |
+
# rearrange"b h t d -> b t (h d)"
|
| 265 |
+
_, _, hidden_size, _ = context.shape
|
| 266 |
+
context = context.permute(0, 2, 1, 3).contiguous().view(batch_size, hidden_size, self.num_heads * head_dim)
|
| 267 |
+
return context
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class CvtSelfOutput(nn.Module):
|
| 271 |
+
"""
|
| 272 |
+
The residual connection is defined in CvtLayer instead of here (as is the case with other models), due to the
|
| 273 |
+
layernorm applied before each block.
|
| 274 |
+
"""
|
| 275 |
+
|
| 276 |
+
def __init__(self, embed_dim, drop_rate):
|
| 277 |
+
super().__init__()
|
| 278 |
+
self.dense = nn.Linear(embed_dim, embed_dim)
|
| 279 |
+
self.dropout = nn.Dropout(drop_rate)
|
| 280 |
+
|
| 281 |
+
def forward(self, hidden_state, input_tensor):
|
| 282 |
+
hidden_state = self.dense(hidden_state)
|
| 283 |
+
hidden_state = self.dropout(hidden_state)
|
| 284 |
+
return hidden_state
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class CvtAttention(nn.Module):
|
| 288 |
+
def __init__(
|
| 289 |
+
self,
|
| 290 |
+
num_heads,
|
| 291 |
+
embed_dim,
|
| 292 |
+
kernel_size,
|
| 293 |
+
padding_q,
|
| 294 |
+
padding_kv,
|
| 295 |
+
stride_q,
|
| 296 |
+
stride_kv,
|
| 297 |
+
qkv_projection_method,
|
| 298 |
+
qkv_bias,
|
| 299 |
+
attention_drop_rate,
|
| 300 |
+
drop_rate,
|
| 301 |
+
with_cls_token=True,
|
| 302 |
+
):
|
| 303 |
+
super().__init__()
|
| 304 |
+
self.attention = CvtSelfAttention(
|
| 305 |
+
num_heads,
|
| 306 |
+
embed_dim,
|
| 307 |
+
kernel_size,
|
| 308 |
+
padding_q,
|
| 309 |
+
padding_kv,
|
| 310 |
+
stride_q,
|
| 311 |
+
stride_kv,
|
| 312 |
+
qkv_projection_method,
|
| 313 |
+
qkv_bias,
|
| 314 |
+
attention_drop_rate,
|
| 315 |
+
with_cls_token,
|
| 316 |
+
)
|
| 317 |
+
self.output = CvtSelfOutput(embed_dim, drop_rate)
|
| 318 |
+
self.pruned_heads = set()
|
| 319 |
+
|
| 320 |
+
def prune_heads(self, heads):
|
| 321 |
+
if len(heads) == 0:
|
| 322 |
+
return
|
| 323 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 324 |
+
heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# Prune linear layers
|
| 328 |
+
self.attention.query = prune_linear_layer(self.attention.query, index)
|
| 329 |
+
self.attention.key = prune_linear_layer(self.attention.key, index)
|
| 330 |
+
self.attention.value = prune_linear_layer(self.attention.value, index)
|
| 331 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 332 |
+
|
| 333 |
+
# Update hyper params and store pruned heads
|
| 334 |
+
self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
|
| 335 |
+
self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
|
| 336 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 337 |
+
|
| 338 |
+
def forward(self, hidden_state, height, width):
|
| 339 |
+
self_output = self.attention(hidden_state, height, width)
|
| 340 |
+
attention_output = self.output(self_output, hidden_state)
|
| 341 |
+
return attention_output
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class CvtIntermediate(nn.Module):
|
| 345 |
+
def __init__(self, embed_dim, mlp_ratio):
|
| 346 |
+
super().__init__()
|
| 347 |
+
self.dense = nn.Linear(embed_dim, int(embed_dim * mlp_ratio))
|
| 348 |
+
self.activation = nn.GELU()
|
| 349 |
+
|
| 350 |
+
def forward(self, hidden_state):
|
| 351 |
+
hidden_state = self.dense(hidden_state)
|
| 352 |
+
hidden_state = self.activation(hidden_state)
|
| 353 |
+
return hidden_state
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class CvtOutput(nn.Module):
|
| 357 |
+
def __init__(self, embed_dim, mlp_ratio, drop_rate):
|
| 358 |
+
super().__init__()
|
| 359 |
+
self.dense = nn.Linear(int(embed_dim * mlp_ratio), embed_dim)
|
| 360 |
+
self.dropout = nn.Dropout(drop_rate)
|
| 361 |
+
|
| 362 |
+
def forward(self, hidden_state, input_tensor):
|
| 363 |
+
hidden_state = self.dense(hidden_state)
|
| 364 |
+
hidden_state = self.dropout(hidden_state)
|
| 365 |
+
hidden_state = hidden_state + input_tensor
|
| 366 |
+
return hidden_state
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class CvtLayer(nn.Module):
|
| 370 |
+
"""
|
| 371 |
+
CvtLayer composed by attention layers, normalization and multi-layer perceptrons (mlps).
|
| 372 |
+
"""
|
| 373 |
+
|
| 374 |
+
def __init__(
|
| 375 |
+
self,
|
| 376 |
+
num_heads,
|
| 377 |
+
embed_dim,
|
| 378 |
+
kernel_size,
|
| 379 |
+
padding_q,
|
| 380 |
+
padding_kv,
|
| 381 |
+
stride_q,
|
| 382 |
+
stride_kv,
|
| 383 |
+
qkv_projection_method,
|
| 384 |
+
qkv_bias,
|
| 385 |
+
attention_drop_rate,
|
| 386 |
+
drop_rate,
|
| 387 |
+
mlp_ratio,
|
| 388 |
+
drop_path_rate,
|
| 389 |
+
with_cls_token=True,
|
| 390 |
+
):
|
| 391 |
+
super().__init__()
|
| 392 |
+
self.attention = CvtAttention(
|
| 393 |
+
num_heads,
|
| 394 |
+
embed_dim,
|
| 395 |
+
kernel_size,
|
| 396 |
+
padding_q,
|
| 397 |
+
padding_kv,
|
| 398 |
+
stride_q,
|
| 399 |
+
stride_kv,
|
| 400 |
+
qkv_projection_method,
|
| 401 |
+
qkv_bias,
|
| 402 |
+
attention_drop_rate,
|
| 403 |
+
drop_rate,
|
| 404 |
+
with_cls_token,
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
self.intermediate = CvtIntermediate(embed_dim, mlp_ratio)
|
| 408 |
+
self.output = CvtOutput(embed_dim, mlp_ratio, drop_rate)
|
| 409 |
+
self.drop_path = CvtDropPath(drop_prob=drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
|
| 410 |
+
self.layernorm_before = nn.LayerNorm(embed_dim)
|
| 411 |
+
self.layernorm_after = nn.LayerNorm(embed_dim)
|
| 412 |
+
|
| 413 |
+
def forward(self, hidden_state, height, width):
|
| 414 |
+
self_attention_output = self.attention(
|
| 415 |
+
self.layernorm_before(hidden_state), # in Cvt, layernorm is applied before self-attention
|
| 416 |
+
height,
|
| 417 |
+
width,
|
| 418 |
+
)
|
| 419 |
+
attention_output = self_attention_output
|
| 420 |
+
attention_output = self.drop_path(attention_output)
|
| 421 |
+
|
| 422 |
+
# first residual connection
|
| 423 |
+
hidden_state = attention_output + hidden_state
|
| 424 |
+
|
| 425 |
+
# in Cvt, layernorm is also applied after self-attention
|
| 426 |
+
layer_output = self.layernorm_after(hidden_state)
|
| 427 |
+
layer_output = self.intermediate(layer_output)
|
| 428 |
+
|
| 429 |
+
# second residual connection is done here
|
| 430 |
+
layer_output = self.output(layer_output, hidden_state)
|
| 431 |
+
layer_output = self.drop_path(layer_output)
|
| 432 |
+
return layer_output
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
class CvtStage(nn.Module):
|
| 436 |
+
def __init__(self, config, stage):
|
| 437 |
+
super().__init__()
|
| 438 |
+
self.config = config
|
| 439 |
+
self.stage = stage
|
| 440 |
+
if self.config.cls_token[self.stage]:
|
| 441 |
+
self.cls_token = nn.Parameter(torch.randn(1, 1, self.config.embed_dim[-1]))
|
| 442 |
+
|
| 443 |
+
self.embedding = CvtEmbeddings(
|
| 444 |
+
patch_size=config.patch_sizes[self.stage],
|
| 445 |
+
stride=config.patch_stride[self.stage],
|
| 446 |
+
num_channels=config.num_channels if self.stage == 0 else config.embed_dim[self.stage - 1],
|
| 447 |
+
embed_dim=config.embed_dim[self.stage],
|
| 448 |
+
padding=config.patch_padding[self.stage],
|
| 449 |
+
dropout_rate=config.drop_rate[self.stage],
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
drop_path_rates = [x.item() for x in torch.linspace(0, config.drop_path_rate[self.stage], config.depth[stage])]
|
| 453 |
+
|
| 454 |
+
self.layers = nn.Sequential(
|
| 455 |
+
*[
|
| 456 |
+
CvtLayer(
|
| 457 |
+
num_heads=config.num_heads[self.stage],
|
| 458 |
+
embed_dim=config.embed_dim[self.stage],
|
| 459 |
+
kernel_size=config.kernel_qkv[self.stage],
|
| 460 |
+
padding_q=config.padding_q[self.stage],
|
| 461 |
+
padding_kv=config.padding_kv[self.stage],
|
| 462 |
+
stride_kv=config.stride_kv[self.stage],
|
| 463 |
+
stride_q=config.stride_q[self.stage],
|
| 464 |
+
qkv_projection_method=config.qkv_projection_method[self.stage],
|
| 465 |
+
qkv_bias=config.qkv_bias[self.stage],
|
| 466 |
+
attention_drop_rate=config.attention_drop_rate[self.stage],
|
| 467 |
+
drop_rate=config.drop_rate[self.stage],
|
| 468 |
+
drop_path_rate=drop_path_rates[self.stage],
|
| 469 |
+
mlp_ratio=config.mlp_ratio[self.stage],
|
| 470 |
+
with_cls_token=config.cls_token[self.stage],
|
| 471 |
+
)
|
| 472 |
+
for _ in range(config.depth[self.stage])
|
| 473 |
+
]
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
def forward(self, hidden_state):
|
| 477 |
+
cls_token = None
|
| 478 |
+
hidden_state = self.embedding(hidden_state)
|
| 479 |
+
batch_size, num_channels, height, width = hidden_state.shape
|
| 480 |
+
# rearrange b c h w -> b (h w) c"
|
| 481 |
+
hidden_state = hidden_state.view(batch_size, num_channels, height * width).permute(0, 2, 1)
|
| 482 |
+
if self.config.cls_token[self.stage]:
|
| 483 |
+
cls_token = self.cls_token.expand(batch_size, -1, -1)
|
| 484 |
+
hidden_state = torch.cat((cls_token, hidden_state), dim=1)
|
| 485 |
+
|
| 486 |
+
for layer in self.layers:
|
| 487 |
+
layer_outputs = layer(hidden_state, height, width)
|
| 488 |
+
hidden_state = layer_outputs
|
| 489 |
+
|
| 490 |
+
if self.config.cls_token[self.stage]:
|
| 491 |
+
cls_token, hidden_state = torch.split(hidden_state, [1, height * width], 1)
|
| 492 |
+
hidden_state = hidden_state.permute(0, 2, 1).view(batch_size, num_channels, height, width)
|
| 493 |
+
return hidden_state, cls_token
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
class CvtEncoder(nn.Module):
|
| 497 |
+
def __init__(self, config):
|
| 498 |
+
super().__init__()
|
| 499 |
+
self.config = config
|
| 500 |
+
self.stages = nn.ModuleList([])
|
| 501 |
+
for stage_idx in range(len(config.depth)):
|
| 502 |
+
self.stages.append(CvtStage(config, stage_idx))
|
| 503 |
+
|
| 504 |
+
def forward(self, pixel_values, output_hidden_states=False, return_dict=True):
|
| 505 |
+
all_hidden_states = () if output_hidden_states else None
|
| 506 |
+
hidden_state = pixel_values
|
| 507 |
+
|
| 508 |
+
cls_token = None
|
| 509 |
+
for _, (stage_module) in enumerate(self.stages):
|
| 510 |
+
hidden_state, cls_token = stage_module(hidden_state)
|
| 511 |
+
if output_hidden_states:
|
| 512 |
+
all_hidden_states = all_hidden_states + (hidden_state,)
|
| 513 |
+
|
| 514 |
+
if not return_dict:
|
| 515 |
+
return tuple(v for v in [hidden_state, cls_token, all_hidden_states] if v is not None)
|
| 516 |
+
|
| 517 |
+
return BaseModelOutputWithCLSToken(
|
| 518 |
+
last_hidden_state=hidden_state,
|
| 519 |
+
cls_token_value=cls_token,
|
| 520 |
+
hidden_states=all_hidden_states,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
class CvtPreTrainedModel(PreTrainedModel):
|
| 525 |
+
"""
|
| 526 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 527 |
+
models.
|
| 528 |
+
"""
|
| 529 |
+
|
| 530 |
+
config_class = CvtConfig
|
| 531 |
+
base_model_prefix = "cvt"
|
| 532 |
+
main_input_name = "pixel_values"
|
| 533 |
+
_no_split_modules = ["CvtLayer"]
|
| 534 |
+
|
| 535 |
+
def _init_weights(self, module):
|
| 536 |
+
"""Initialize the weights"""
|
| 537 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 538 |
+
module.weight.data = nn.init.trunc_normal_(module.weight.data, mean=0.0, std=self.config.initializer_range)
|
| 539 |
+
if module.bias is not None:
|
| 540 |
+
module.bias.data.zero_()
|
| 541 |
+
elif isinstance(module, nn.LayerNorm):
|
| 542 |
+
module.bias.data.zero_()
|
| 543 |
+
module.weight.data.fill_(1.0)
|
| 544 |
+
elif isinstance(module, CvtStage):
|
| 545 |
+
if self.config.cls_token[module.stage]:
|
| 546 |
+
module.cls_token.data = nn.init.trunc_normal_(
|
| 547 |
+
module.cls_token.data, mean=0.0, std=self.config.initializer_range
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
CVT_START_DOCSTRING = r"""
|
| 552 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 553 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 554 |
+
behavior.
|
| 555 |
+
|
| 556 |
+
Parameters:
|
| 557 |
+
config ([`CvtConfig`]): Model configuration class with all the parameters of the model.
|
| 558 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 559 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 560 |
+
"""
|
| 561 |
+
|
| 562 |
+
CVT_INPUTS_DOCSTRING = r"""
|
| 563 |
+
Args:
|
| 564 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 565 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`CvtImageProcessor.__call__`]
|
| 566 |
+
for details.
|
| 567 |
+
output_hidden_states (`bool`, *optional*):
|
| 568 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 569 |
+
more detail.
|
| 570 |
+
return_dict (`bool`, *optional*):
|
| 571 |
+
Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
|
| 572 |
+
"""
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
@add_start_docstrings(
|
| 576 |
+
"The bare Cvt Model transformer outputting raw hidden-states without any specific head on top.",
|
| 577 |
+
CVT_START_DOCSTRING,
|
| 578 |
+
)
|
| 579 |
+
class CvtModel(CvtPreTrainedModel):
|
| 580 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 581 |
+
super().__init__(config)
|
| 582 |
+
self.config = config
|
| 583 |
+
self.encoder = CvtEncoder(config)
|
| 584 |
+
self.post_init()
|
| 585 |
+
|
| 586 |
+
def _prune_heads(self, heads_to_prune):
|
| 587 |
+
"""
|
| 588 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 589 |
+
class PreTrainedModel
|
| 590 |
+
"""
|
| 591 |
+
for layer, heads in heads_to_prune.items():
|
| 592 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 593 |
+
|
| 594 |
+
@add_start_docstrings_to_model_forward(CVT_INPUTS_DOCSTRING)
|
| 595 |
+
@add_code_sample_docstrings(
|
| 596 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 597 |
+
output_type=BaseModelOutputWithCLSToken,
|
| 598 |
+
config_class=_CONFIG_FOR_DOC,
|
| 599 |
+
modality="vision",
|
| 600 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 601 |
+
)
|
| 602 |
+
def forward(
|
| 603 |
+
self,
|
| 604 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 605 |
+
output_hidden_states: Optional[bool] = None,
|
| 606 |
+
return_dict: Optional[bool] = None,
|
| 607 |
+
) -> Union[Tuple, BaseModelOutputWithCLSToken]:
|
| 608 |
+
output_hidden_states = (
|
| 609 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 610 |
+
)
|
| 611 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 612 |
+
|
| 613 |
+
if pixel_values is None:
|
| 614 |
+
raise ValueError("You have to specify pixel_values")
|
| 615 |
+
|
| 616 |
+
encoder_outputs = self.encoder(
|
| 617 |
+
pixel_values,
|
| 618 |
+
output_hidden_states=output_hidden_states,
|
| 619 |
+
return_dict=return_dict,
|
| 620 |
+
)
|
| 621 |
+
sequence_output = encoder_outputs[0]
|
| 622 |
+
|
| 623 |
+
if not return_dict:
|
| 624 |
+
return (sequence_output,) + encoder_outputs[1:]
|
| 625 |
+
|
| 626 |
+
return BaseModelOutputWithCLSToken(
|
| 627 |
+
last_hidden_state=sequence_output,
|
| 628 |
+
cls_token_value=encoder_outputs.cls_token_value,
|
| 629 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 630 |
+
)
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
@add_start_docstrings(
|
| 634 |
+
"""
|
| 635 |
+
Cvt Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
|
| 636 |
+
the [CLS] token) e.g. for ImageNet.
|
| 637 |
+
""",
|
| 638 |
+
CVT_START_DOCSTRING,
|
| 639 |
+
)
|
| 640 |
+
class CvtForImageClassification(CvtPreTrainedModel):
|
| 641 |
+
def __init__(self, config):
|
| 642 |
+
super().__init__(config)
|
| 643 |
+
|
| 644 |
+
self.num_labels = config.num_labels
|
| 645 |
+
self.cvt = CvtModel(config, add_pooling_layer=False)
|
| 646 |
+
self.layernorm = nn.LayerNorm(config.embed_dim[-1])
|
| 647 |
+
# Classifier head
|
| 648 |
+
self.classifier = (
|
| 649 |
+
nn.Linear(config.embed_dim[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
# Initialize weights and apply final processing
|
| 653 |
+
self.post_init()
|
| 654 |
+
|
| 655 |
+
@add_start_docstrings_to_model_forward(CVT_INPUTS_DOCSTRING)
|
| 656 |
+
@add_code_sample_docstrings(
|
| 657 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
| 658 |
+
output_type=ImageClassifierOutputWithNoAttention,
|
| 659 |
+
config_class=_CONFIG_FOR_DOC,
|
| 660 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
| 661 |
+
)
|
| 662 |
+
def forward(
|
| 663 |
+
self,
|
| 664 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 665 |
+
labels: Optional[torch.Tensor] = None,
|
| 666 |
+
output_hidden_states: Optional[bool] = None,
|
| 667 |
+
return_dict: Optional[bool] = None,
|
| 668 |
+
) -> Union[Tuple, ImageClassifierOutputWithNoAttention]:
|
| 669 |
+
r"""
|
| 670 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 671 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 672 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 673 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 674 |
+
"""
|
| 675 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 676 |
+
outputs = self.cvt(
|
| 677 |
+
pixel_values,
|
| 678 |
+
output_hidden_states=output_hidden_states,
|
| 679 |
+
return_dict=return_dict,
|
| 680 |
+
)
|
| 681 |
+
|
| 682 |
+
sequence_output = outputs[0]
|
| 683 |
+
cls_token = outputs[1]
|
| 684 |
+
if self.config.cls_token[-1]:
|
| 685 |
+
sequence_output = self.layernorm(cls_token)
|
| 686 |
+
else:
|
| 687 |
+
batch_size, num_channels, height, width = sequence_output.shape
|
| 688 |
+
# rearrange "b c h w -> b (h w) c"
|
| 689 |
+
sequence_output = sequence_output.view(batch_size, num_channels, height * width).permute(0, 2, 1)
|
| 690 |
+
sequence_output = self.layernorm(sequence_output)
|
| 691 |
+
|
| 692 |
+
sequence_output_mean = sequence_output.mean(dim=1)
|
| 693 |
+
logits = self.classifier(sequence_output_mean)
|
| 694 |
+
|
| 695 |
+
loss = None
|
| 696 |
+
if labels is not None:
|
| 697 |
+
if self.config.problem_type is None:
|
| 698 |
+
if self.config.num_labels == 1:
|
| 699 |
+
self.config.problem_type = "regression"
|
| 700 |
+
elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 701 |
+
self.config.problem_type = "single_label_classification"
|
| 702 |
+
else:
|
| 703 |
+
self.config.problem_type = "multi_label_classification"
|
| 704 |
+
|
| 705 |
+
if self.config.problem_type == "regression":
|
| 706 |
+
loss_fct = MSELoss()
|
| 707 |
+
if self.config.num_labels == 1:
|
| 708 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 709 |
+
else:
|
| 710 |
+
loss = loss_fct(logits, labels)
|
| 711 |
+
elif self.config.problem_type == "single_label_classification":
|
| 712 |
+
loss_fct = CrossEntropyLoss()
|
| 713 |
+
loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
|
| 714 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 715 |
+
loss_fct = BCEWithLogitsLoss()
|
| 716 |
+
loss = loss_fct(logits, labels)
|
| 717 |
+
|
| 718 |
+
if not return_dict:
|
| 719 |
+
output = (logits,) + outputs[2:]
|
| 720 |
+
return ((loss,) + output) if loss is not None else output
|
| 721 |
+
|
| 722 |
+
return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
__all__ = ["CvtForImageClassification", "CvtModel", "CvtPreTrainedModel"]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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 |
+
"""TF 2.0 Cvt model."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import collections.abc
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from typing import Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import tensorflow as tf
|
| 24 |
+
|
| 25 |
+
from ...modeling_tf_outputs import TFImageClassifierOutputWithNoAttention
|
| 26 |
+
from ...modeling_tf_utils import (
|
| 27 |
+
TFModelInputType,
|
| 28 |
+
TFPreTrainedModel,
|
| 29 |
+
TFSequenceClassificationLoss,
|
| 30 |
+
get_initializer,
|
| 31 |
+
keras,
|
| 32 |
+
keras_serializable,
|
| 33 |
+
unpack_inputs,
|
| 34 |
+
)
|
| 35 |
+
from ...tf_utils import shape_list, stable_softmax
|
| 36 |
+
from ...utils import (
|
| 37 |
+
ModelOutput,
|
| 38 |
+
add_start_docstrings,
|
| 39 |
+
add_start_docstrings_to_model_forward,
|
| 40 |
+
logging,
|
| 41 |
+
replace_return_docstrings,
|
| 42 |
+
)
|
| 43 |
+
from .configuration_cvt import CvtConfig
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
# General docstring
|
| 49 |
+
_CONFIG_FOR_DOC = "CvtConfig"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dataclass
|
| 53 |
+
class TFBaseModelOutputWithCLSToken(ModelOutput):
|
| 54 |
+
"""
|
| 55 |
+
Base class for model's outputs.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 59 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 60 |
+
cls_token_value (`tf.Tensor` of shape `(batch_size, 1, hidden_size)`):
|
| 61 |
+
Classification token at the output of the last layer of the model.
|
| 62 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 63 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 64 |
+
`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus
|
| 65 |
+
the initial embedding outputs.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
last_hidden_state: tf.Tensor = None
|
| 69 |
+
cls_token_value: tf.Tensor = None
|
| 70 |
+
hidden_states: Tuple[tf.Tensor, ...] | None = None
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class TFCvtDropPath(keras.layers.Layer):
|
| 74 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 75 |
+
References:
|
| 76 |
+
(1) github.com:rwightman/pytorch-image-models
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
def __init__(self, drop_prob: float, **kwargs):
|
| 80 |
+
super().__init__(**kwargs)
|
| 81 |
+
self.drop_prob = drop_prob
|
| 82 |
+
|
| 83 |
+
def call(self, x: tf.Tensor, training=None):
|
| 84 |
+
if self.drop_prob == 0.0 or not training:
|
| 85 |
+
return x
|
| 86 |
+
keep_prob = 1 - self.drop_prob
|
| 87 |
+
shape = (tf.shape(x)[0],) + (1,) * (len(tf.shape(x)) - 1)
|
| 88 |
+
random_tensor = keep_prob + tf.random.uniform(shape, 0, 1, dtype=self.compute_dtype)
|
| 89 |
+
random_tensor = tf.floor(random_tensor)
|
| 90 |
+
return (x / keep_prob) * random_tensor
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class TFCvtEmbeddings(keras.layers.Layer):
|
| 94 |
+
"""Construct the Convolutional Token Embeddings."""
|
| 95 |
+
|
| 96 |
+
def __init__(
|
| 97 |
+
self,
|
| 98 |
+
config: CvtConfig,
|
| 99 |
+
patch_size: int,
|
| 100 |
+
num_channels: int,
|
| 101 |
+
embed_dim: int,
|
| 102 |
+
stride: int,
|
| 103 |
+
padding: int,
|
| 104 |
+
dropout_rate: float,
|
| 105 |
+
**kwargs,
|
| 106 |
+
):
|
| 107 |
+
super().__init__(**kwargs)
|
| 108 |
+
self.convolution_embeddings = TFCvtConvEmbeddings(
|
| 109 |
+
config,
|
| 110 |
+
patch_size=patch_size,
|
| 111 |
+
num_channels=num_channels,
|
| 112 |
+
embed_dim=embed_dim,
|
| 113 |
+
stride=stride,
|
| 114 |
+
padding=padding,
|
| 115 |
+
name="convolution_embeddings",
|
| 116 |
+
)
|
| 117 |
+
self.dropout = keras.layers.Dropout(dropout_rate)
|
| 118 |
+
|
| 119 |
+
def call(self, pixel_values: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 120 |
+
hidden_state = self.convolution_embeddings(pixel_values)
|
| 121 |
+
hidden_state = self.dropout(hidden_state, training=training)
|
| 122 |
+
return hidden_state
|
| 123 |
+
|
| 124 |
+
def build(self, input_shape=None):
|
| 125 |
+
if self.built:
|
| 126 |
+
return
|
| 127 |
+
self.built = True
|
| 128 |
+
if getattr(self, "convolution_embeddings", None) is not None:
|
| 129 |
+
with tf.name_scope(self.convolution_embeddings.name):
|
| 130 |
+
self.convolution_embeddings.build(None)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class TFCvtConvEmbeddings(keras.layers.Layer):
|
| 134 |
+
"""Image to Convolution Embeddings. This convolutional operation aims to model local spatial contexts."""
|
| 135 |
+
|
| 136 |
+
def __init__(
|
| 137 |
+
self,
|
| 138 |
+
config: CvtConfig,
|
| 139 |
+
patch_size: int,
|
| 140 |
+
num_channels: int,
|
| 141 |
+
embed_dim: int,
|
| 142 |
+
stride: int,
|
| 143 |
+
padding: int,
|
| 144 |
+
**kwargs,
|
| 145 |
+
):
|
| 146 |
+
super().__init__(**kwargs)
|
| 147 |
+
self.padding = keras.layers.ZeroPadding2D(padding=padding)
|
| 148 |
+
self.patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 149 |
+
self.projection = keras.layers.Conv2D(
|
| 150 |
+
filters=embed_dim,
|
| 151 |
+
kernel_size=patch_size,
|
| 152 |
+
strides=stride,
|
| 153 |
+
padding="valid",
|
| 154 |
+
data_format="channels_last",
|
| 155 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 156 |
+
name="projection",
|
| 157 |
+
)
|
| 158 |
+
# Using the same default epsilon as PyTorch
|
| 159 |
+
self.normalization = keras.layers.LayerNormalization(epsilon=1e-5, name="normalization")
|
| 160 |
+
self.num_channels = num_channels
|
| 161 |
+
self.embed_dim = embed_dim
|
| 162 |
+
|
| 163 |
+
def call(self, pixel_values: tf.Tensor) -> tf.Tensor:
|
| 164 |
+
if isinstance(pixel_values, dict):
|
| 165 |
+
pixel_values = pixel_values["pixel_values"]
|
| 166 |
+
|
| 167 |
+
pixel_values = self.projection(self.padding(pixel_values))
|
| 168 |
+
|
| 169 |
+
# "batch_size, height, width, num_channels -> batch_size, (height*width), num_channels"
|
| 170 |
+
batch_size, height, width, num_channels = shape_list(pixel_values)
|
| 171 |
+
hidden_size = height * width
|
| 172 |
+
pixel_values = tf.reshape(pixel_values, shape=(batch_size, hidden_size, num_channels))
|
| 173 |
+
pixel_values = self.normalization(pixel_values)
|
| 174 |
+
|
| 175 |
+
# "batch_size, (height*width), num_channels -> batch_size, height, width, num_channels"
|
| 176 |
+
pixel_values = tf.reshape(pixel_values, shape=(batch_size, height, width, num_channels))
|
| 177 |
+
return pixel_values
|
| 178 |
+
|
| 179 |
+
def build(self, input_shape=None):
|
| 180 |
+
if self.built:
|
| 181 |
+
return
|
| 182 |
+
self.built = True
|
| 183 |
+
if getattr(self, "projection", None) is not None:
|
| 184 |
+
with tf.name_scope(self.projection.name):
|
| 185 |
+
self.projection.build([None, None, None, self.num_channels])
|
| 186 |
+
if getattr(self, "normalization", None) is not None:
|
| 187 |
+
with tf.name_scope(self.normalization.name):
|
| 188 |
+
self.normalization.build([None, None, self.embed_dim])
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class TFCvtSelfAttentionConvProjection(keras.layers.Layer):
|
| 192 |
+
"""Convolutional projection layer."""
|
| 193 |
+
|
| 194 |
+
def __init__(self, config: CvtConfig, embed_dim: int, kernel_size: int, stride: int, padding: int, **kwargs):
|
| 195 |
+
super().__init__(**kwargs)
|
| 196 |
+
self.padding = keras.layers.ZeroPadding2D(padding=padding)
|
| 197 |
+
self.convolution = keras.layers.Conv2D(
|
| 198 |
+
filters=embed_dim,
|
| 199 |
+
kernel_size=kernel_size,
|
| 200 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 201 |
+
padding="valid",
|
| 202 |
+
strides=stride,
|
| 203 |
+
use_bias=False,
|
| 204 |
+
name="convolution",
|
| 205 |
+
groups=embed_dim,
|
| 206 |
+
)
|
| 207 |
+
# Using the same default epsilon as PyTorch, TF uses (1 - pytorch momentum)
|
| 208 |
+
self.normalization = keras.layers.BatchNormalization(epsilon=1e-5, momentum=0.9, name="normalization")
|
| 209 |
+
self.embed_dim = embed_dim
|
| 210 |
+
|
| 211 |
+
def call(self, hidden_state: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 212 |
+
hidden_state = self.convolution(self.padding(hidden_state))
|
| 213 |
+
hidden_state = self.normalization(hidden_state, training=training)
|
| 214 |
+
return hidden_state
|
| 215 |
+
|
| 216 |
+
def build(self, input_shape=None):
|
| 217 |
+
if self.built:
|
| 218 |
+
return
|
| 219 |
+
self.built = True
|
| 220 |
+
if getattr(self, "convolution", None) is not None:
|
| 221 |
+
with tf.name_scope(self.convolution.name):
|
| 222 |
+
self.convolution.build([None, None, None, self.embed_dim])
|
| 223 |
+
if getattr(self, "normalization", None) is not None:
|
| 224 |
+
with tf.name_scope(self.normalization.name):
|
| 225 |
+
self.normalization.build([None, None, None, self.embed_dim])
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class TFCvtSelfAttentionLinearProjection(keras.layers.Layer):
|
| 229 |
+
"""Linear projection layer used to flatten tokens into 1D."""
|
| 230 |
+
|
| 231 |
+
def call(self, hidden_state: tf.Tensor) -> tf.Tensor:
|
| 232 |
+
# "batch_size, height, width, num_channels -> batch_size, (height*width), num_channels"
|
| 233 |
+
batch_size, height, width, num_channels = shape_list(hidden_state)
|
| 234 |
+
hidden_size = height * width
|
| 235 |
+
hidden_state = tf.reshape(hidden_state, shape=(batch_size, hidden_size, num_channels))
|
| 236 |
+
return hidden_state
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class TFCvtSelfAttentionProjection(keras.layers.Layer):
|
| 240 |
+
"""Convolutional Projection for Attention."""
|
| 241 |
+
|
| 242 |
+
def __init__(
|
| 243 |
+
self,
|
| 244 |
+
config: CvtConfig,
|
| 245 |
+
embed_dim: int,
|
| 246 |
+
kernel_size: int,
|
| 247 |
+
stride: int,
|
| 248 |
+
padding: int,
|
| 249 |
+
projection_method: str = "dw_bn",
|
| 250 |
+
**kwargs,
|
| 251 |
+
):
|
| 252 |
+
super().__init__(**kwargs)
|
| 253 |
+
if projection_method == "dw_bn":
|
| 254 |
+
self.convolution_projection = TFCvtSelfAttentionConvProjection(
|
| 255 |
+
config, embed_dim, kernel_size, stride, padding, name="convolution_projection"
|
| 256 |
+
)
|
| 257 |
+
self.linear_projection = TFCvtSelfAttentionLinearProjection()
|
| 258 |
+
|
| 259 |
+
def call(self, hidden_state: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 260 |
+
hidden_state = self.convolution_projection(hidden_state, training=training)
|
| 261 |
+
hidden_state = self.linear_projection(hidden_state)
|
| 262 |
+
return hidden_state
|
| 263 |
+
|
| 264 |
+
def build(self, input_shape=None):
|
| 265 |
+
if self.built:
|
| 266 |
+
return
|
| 267 |
+
self.built = True
|
| 268 |
+
if getattr(self, "convolution_projection", None) is not None:
|
| 269 |
+
with tf.name_scope(self.convolution_projection.name):
|
| 270 |
+
self.convolution_projection.build(None)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class TFCvtSelfAttention(keras.layers.Layer):
|
| 274 |
+
"""
|
| 275 |
+
Self-attention layer. A depth-wise separable convolution operation (Convolutional Projection), is applied for
|
| 276 |
+
query, key, and value embeddings.
|
| 277 |
+
"""
|
| 278 |
+
|
| 279 |
+
def __init__(
|
| 280 |
+
self,
|
| 281 |
+
config: CvtConfig,
|
| 282 |
+
num_heads: int,
|
| 283 |
+
embed_dim: int,
|
| 284 |
+
kernel_size: int,
|
| 285 |
+
stride_q: int,
|
| 286 |
+
stride_kv: int,
|
| 287 |
+
padding_q: int,
|
| 288 |
+
padding_kv: int,
|
| 289 |
+
qkv_projection_method: str,
|
| 290 |
+
qkv_bias: bool,
|
| 291 |
+
attention_drop_rate: float,
|
| 292 |
+
with_cls_token: bool = True,
|
| 293 |
+
**kwargs,
|
| 294 |
+
):
|
| 295 |
+
super().__init__(**kwargs)
|
| 296 |
+
self.scale = embed_dim**-0.5
|
| 297 |
+
self.with_cls_token = with_cls_token
|
| 298 |
+
self.embed_dim = embed_dim
|
| 299 |
+
self.num_heads = num_heads
|
| 300 |
+
|
| 301 |
+
self.convolution_projection_query = TFCvtSelfAttentionProjection(
|
| 302 |
+
config,
|
| 303 |
+
embed_dim,
|
| 304 |
+
kernel_size,
|
| 305 |
+
stride_q,
|
| 306 |
+
padding_q,
|
| 307 |
+
projection_method="linear" if qkv_projection_method == "avg" else qkv_projection_method,
|
| 308 |
+
name="convolution_projection_query",
|
| 309 |
+
)
|
| 310 |
+
self.convolution_projection_key = TFCvtSelfAttentionProjection(
|
| 311 |
+
config,
|
| 312 |
+
embed_dim,
|
| 313 |
+
kernel_size,
|
| 314 |
+
stride_kv,
|
| 315 |
+
padding_kv,
|
| 316 |
+
projection_method=qkv_projection_method,
|
| 317 |
+
name="convolution_projection_key",
|
| 318 |
+
)
|
| 319 |
+
self.convolution_projection_value = TFCvtSelfAttentionProjection(
|
| 320 |
+
config,
|
| 321 |
+
embed_dim,
|
| 322 |
+
kernel_size,
|
| 323 |
+
stride_kv,
|
| 324 |
+
padding_kv,
|
| 325 |
+
projection_method=qkv_projection_method,
|
| 326 |
+
name="convolution_projection_value",
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
self.projection_query = keras.layers.Dense(
|
| 330 |
+
units=embed_dim,
|
| 331 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 332 |
+
use_bias=qkv_bias,
|
| 333 |
+
bias_initializer="zeros",
|
| 334 |
+
name="projection_query",
|
| 335 |
+
)
|
| 336 |
+
self.projection_key = keras.layers.Dense(
|
| 337 |
+
units=embed_dim,
|
| 338 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 339 |
+
use_bias=qkv_bias,
|
| 340 |
+
bias_initializer="zeros",
|
| 341 |
+
name="projection_key",
|
| 342 |
+
)
|
| 343 |
+
self.projection_value = keras.layers.Dense(
|
| 344 |
+
units=embed_dim,
|
| 345 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 346 |
+
use_bias=qkv_bias,
|
| 347 |
+
bias_initializer="zeros",
|
| 348 |
+
name="projection_value",
|
| 349 |
+
)
|
| 350 |
+
self.dropout = keras.layers.Dropout(attention_drop_rate)
|
| 351 |
+
|
| 352 |
+
def rearrange_for_multi_head_attention(self, hidden_state: tf.Tensor) -> tf.Tensor:
|
| 353 |
+
batch_size, hidden_size, _ = shape_list(hidden_state)
|
| 354 |
+
head_dim = self.embed_dim // self.num_heads
|
| 355 |
+
hidden_state = tf.reshape(hidden_state, shape=(batch_size, hidden_size, self.num_heads, head_dim))
|
| 356 |
+
hidden_state = tf.transpose(hidden_state, perm=(0, 2, 1, 3))
|
| 357 |
+
return hidden_state
|
| 358 |
+
|
| 359 |
+
def call(self, hidden_state: tf.Tensor, height: int, width: int, training: bool = False) -> tf.Tensor:
|
| 360 |
+
if self.with_cls_token:
|
| 361 |
+
cls_token, hidden_state = tf.split(hidden_state, [1, height * width], 1)
|
| 362 |
+
|
| 363 |
+
# "batch_size, (height*width), num_channels -> batch_size, height, width, num_channels"
|
| 364 |
+
batch_size, hidden_size, num_channels = shape_list(hidden_state)
|
| 365 |
+
hidden_state = tf.reshape(hidden_state, shape=(batch_size, height, width, num_channels))
|
| 366 |
+
|
| 367 |
+
key = self.convolution_projection_key(hidden_state, training=training)
|
| 368 |
+
query = self.convolution_projection_query(hidden_state, training=training)
|
| 369 |
+
value = self.convolution_projection_value(hidden_state, training=training)
|
| 370 |
+
|
| 371 |
+
if self.with_cls_token:
|
| 372 |
+
query = tf.concat((cls_token, query), axis=1)
|
| 373 |
+
key = tf.concat((cls_token, key), axis=1)
|
| 374 |
+
value = tf.concat((cls_token, value), axis=1)
|
| 375 |
+
|
| 376 |
+
head_dim = self.embed_dim // self.num_heads
|
| 377 |
+
|
| 378 |
+
query = self.rearrange_for_multi_head_attention(self.projection_query(query))
|
| 379 |
+
key = self.rearrange_for_multi_head_attention(self.projection_key(key))
|
| 380 |
+
value = self.rearrange_for_multi_head_attention(self.projection_value(value))
|
| 381 |
+
|
| 382 |
+
attention_score = tf.matmul(query, key, transpose_b=True) * self.scale
|
| 383 |
+
attention_probs = stable_softmax(logits=attention_score, axis=-1)
|
| 384 |
+
attention_probs = self.dropout(attention_probs, training=training)
|
| 385 |
+
|
| 386 |
+
context = tf.matmul(attention_probs, value)
|
| 387 |
+
# "batch_size, num_heads, hidden_size, head_dim -> batch_size, hidden_size, (num_heads*head_dim)"
|
| 388 |
+
_, _, hidden_size, _ = shape_list(context)
|
| 389 |
+
context = tf.transpose(context, perm=(0, 2, 1, 3))
|
| 390 |
+
context = tf.reshape(context, (batch_size, hidden_size, self.num_heads * head_dim))
|
| 391 |
+
return context
|
| 392 |
+
|
| 393 |
+
def build(self, input_shape=None):
|
| 394 |
+
if self.built:
|
| 395 |
+
return
|
| 396 |
+
self.built = True
|
| 397 |
+
if getattr(self, "convolution_projection_query", None) is not None:
|
| 398 |
+
with tf.name_scope(self.convolution_projection_query.name):
|
| 399 |
+
self.convolution_projection_query.build(None)
|
| 400 |
+
if getattr(self, "convolution_projection_key", None) is not None:
|
| 401 |
+
with tf.name_scope(self.convolution_projection_key.name):
|
| 402 |
+
self.convolution_projection_key.build(None)
|
| 403 |
+
if getattr(self, "convolution_projection_value", None) is not None:
|
| 404 |
+
with tf.name_scope(self.convolution_projection_value.name):
|
| 405 |
+
self.convolution_projection_value.build(None)
|
| 406 |
+
if getattr(self, "projection_query", None) is not None:
|
| 407 |
+
with tf.name_scope(self.projection_query.name):
|
| 408 |
+
self.projection_query.build([None, None, self.embed_dim])
|
| 409 |
+
if getattr(self, "projection_key", None) is not None:
|
| 410 |
+
with tf.name_scope(self.projection_key.name):
|
| 411 |
+
self.projection_key.build([None, None, self.embed_dim])
|
| 412 |
+
if getattr(self, "projection_value", None) is not None:
|
| 413 |
+
with tf.name_scope(self.projection_value.name):
|
| 414 |
+
self.projection_value.build([None, None, self.embed_dim])
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class TFCvtSelfOutput(keras.layers.Layer):
|
| 418 |
+
"""Output of the Attention layer ."""
|
| 419 |
+
|
| 420 |
+
def __init__(self, config: CvtConfig, embed_dim: int, drop_rate: float, **kwargs):
|
| 421 |
+
super().__init__(**kwargs)
|
| 422 |
+
self.dense = keras.layers.Dense(
|
| 423 |
+
units=embed_dim, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 424 |
+
)
|
| 425 |
+
self.dropout = keras.layers.Dropout(drop_rate)
|
| 426 |
+
self.embed_dim = embed_dim
|
| 427 |
+
|
| 428 |
+
def call(self, hidden_state: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 429 |
+
hidden_state = self.dense(inputs=hidden_state)
|
| 430 |
+
hidden_state = self.dropout(inputs=hidden_state, training=training)
|
| 431 |
+
return hidden_state
|
| 432 |
+
|
| 433 |
+
def build(self, input_shape=None):
|
| 434 |
+
if self.built:
|
| 435 |
+
return
|
| 436 |
+
self.built = True
|
| 437 |
+
if getattr(self, "dense", None) is not None:
|
| 438 |
+
with tf.name_scope(self.dense.name):
|
| 439 |
+
self.dense.build([None, None, self.embed_dim])
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
class TFCvtAttention(keras.layers.Layer):
|
| 443 |
+
"""Attention layer. First chunk of the convolutional transformer block."""
|
| 444 |
+
|
| 445 |
+
def __init__(
|
| 446 |
+
self,
|
| 447 |
+
config: CvtConfig,
|
| 448 |
+
num_heads: int,
|
| 449 |
+
embed_dim: int,
|
| 450 |
+
kernel_size: int,
|
| 451 |
+
stride_q: int,
|
| 452 |
+
stride_kv: int,
|
| 453 |
+
padding_q: int,
|
| 454 |
+
padding_kv: int,
|
| 455 |
+
qkv_projection_method: str,
|
| 456 |
+
qkv_bias: bool,
|
| 457 |
+
attention_drop_rate: float,
|
| 458 |
+
drop_rate: float,
|
| 459 |
+
with_cls_token: bool = True,
|
| 460 |
+
**kwargs,
|
| 461 |
+
):
|
| 462 |
+
super().__init__(**kwargs)
|
| 463 |
+
self.attention = TFCvtSelfAttention(
|
| 464 |
+
config,
|
| 465 |
+
num_heads,
|
| 466 |
+
embed_dim,
|
| 467 |
+
kernel_size,
|
| 468 |
+
stride_q,
|
| 469 |
+
stride_kv,
|
| 470 |
+
padding_q,
|
| 471 |
+
padding_kv,
|
| 472 |
+
qkv_projection_method,
|
| 473 |
+
qkv_bias,
|
| 474 |
+
attention_drop_rate,
|
| 475 |
+
with_cls_token,
|
| 476 |
+
name="attention",
|
| 477 |
+
)
|
| 478 |
+
self.dense_output = TFCvtSelfOutput(config, embed_dim, drop_rate, name="output")
|
| 479 |
+
|
| 480 |
+
def prune_heads(self, heads):
|
| 481 |
+
raise NotImplementedError
|
| 482 |
+
|
| 483 |
+
def call(self, hidden_state: tf.Tensor, height: int, width: int, training: bool = False):
|
| 484 |
+
self_output = self.attention(hidden_state, height, width, training=training)
|
| 485 |
+
attention_output = self.dense_output(self_output, training=training)
|
| 486 |
+
return attention_output
|
| 487 |
+
|
| 488 |
+
def build(self, input_shape=None):
|
| 489 |
+
if self.built:
|
| 490 |
+
return
|
| 491 |
+
self.built = True
|
| 492 |
+
if getattr(self, "attention", None) is not None:
|
| 493 |
+
with tf.name_scope(self.attention.name):
|
| 494 |
+
self.attention.build(None)
|
| 495 |
+
if getattr(self, "dense_output", None) is not None:
|
| 496 |
+
with tf.name_scope(self.dense_output.name):
|
| 497 |
+
self.dense_output.build(None)
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
class TFCvtIntermediate(keras.layers.Layer):
|
| 501 |
+
"""Intermediate dense layer. Second chunk of the convolutional transformer block."""
|
| 502 |
+
|
| 503 |
+
def __init__(self, config: CvtConfig, embed_dim: int, mlp_ratio: int, **kwargs):
|
| 504 |
+
super().__init__(**kwargs)
|
| 505 |
+
self.dense = keras.layers.Dense(
|
| 506 |
+
units=int(embed_dim * mlp_ratio),
|
| 507 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 508 |
+
activation="gelu",
|
| 509 |
+
name="dense",
|
| 510 |
+
)
|
| 511 |
+
self.embed_dim = embed_dim
|
| 512 |
+
|
| 513 |
+
def call(self, hidden_state: tf.Tensor) -> tf.Tensor:
|
| 514 |
+
hidden_state = self.dense(hidden_state)
|
| 515 |
+
return hidden_state
|
| 516 |
+
|
| 517 |
+
def build(self, input_shape=None):
|
| 518 |
+
if self.built:
|
| 519 |
+
return
|
| 520 |
+
self.built = True
|
| 521 |
+
if getattr(self, "dense", None) is not None:
|
| 522 |
+
with tf.name_scope(self.dense.name):
|
| 523 |
+
self.dense.build([None, None, self.embed_dim])
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
class TFCvtOutput(keras.layers.Layer):
|
| 527 |
+
"""
|
| 528 |
+
Output of the Convolutional Transformer Block (last chunk). It consists of a MLP and a residual connection.
|
| 529 |
+
"""
|
| 530 |
+
|
| 531 |
+
def __init__(self, config: CvtConfig, embed_dim: int, mlp_ratio: int, drop_rate: int, **kwargs):
|
| 532 |
+
super().__init__(**kwargs)
|
| 533 |
+
self.dense = keras.layers.Dense(
|
| 534 |
+
units=embed_dim, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 535 |
+
)
|
| 536 |
+
self.dropout = keras.layers.Dropout(drop_rate)
|
| 537 |
+
self.embed_dim = embed_dim
|
| 538 |
+
self.mlp_ratio = mlp_ratio
|
| 539 |
+
|
| 540 |
+
def call(self, hidden_state: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 541 |
+
hidden_state = self.dense(inputs=hidden_state)
|
| 542 |
+
hidden_state = self.dropout(inputs=hidden_state, training=training)
|
| 543 |
+
hidden_state = hidden_state + input_tensor
|
| 544 |
+
return hidden_state
|
| 545 |
+
|
| 546 |
+
def build(self, input_shape=None):
|
| 547 |
+
if self.built:
|
| 548 |
+
return
|
| 549 |
+
self.built = True
|
| 550 |
+
if getattr(self, "dense", None) is not None:
|
| 551 |
+
with tf.name_scope(self.dense.name):
|
| 552 |
+
self.dense.build([None, None, int(self.embed_dim * self.mlp_ratio)])
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
class TFCvtLayer(keras.layers.Layer):
|
| 556 |
+
"""
|
| 557 |
+
Convolutional Transformer Block composed by attention layers, normalization and multi-layer perceptrons (mlps). It
|
| 558 |
+
consists of 3 chunks : an attention layer, an intermediate dense layer and an output layer. This corresponds to the
|
| 559 |
+
`Block` class in the original implementation.
|
| 560 |
+
"""
|
| 561 |
+
|
| 562 |
+
def __init__(
|
| 563 |
+
self,
|
| 564 |
+
config: CvtConfig,
|
| 565 |
+
num_heads: int,
|
| 566 |
+
embed_dim: int,
|
| 567 |
+
kernel_size: int,
|
| 568 |
+
stride_q: int,
|
| 569 |
+
stride_kv: int,
|
| 570 |
+
padding_q: int,
|
| 571 |
+
padding_kv: int,
|
| 572 |
+
qkv_projection_method: str,
|
| 573 |
+
qkv_bias: bool,
|
| 574 |
+
attention_drop_rate: float,
|
| 575 |
+
drop_rate: float,
|
| 576 |
+
mlp_ratio: float,
|
| 577 |
+
drop_path_rate: float,
|
| 578 |
+
with_cls_token: bool = True,
|
| 579 |
+
**kwargs,
|
| 580 |
+
):
|
| 581 |
+
super().__init__(**kwargs)
|
| 582 |
+
self.attention = TFCvtAttention(
|
| 583 |
+
config,
|
| 584 |
+
num_heads,
|
| 585 |
+
embed_dim,
|
| 586 |
+
kernel_size,
|
| 587 |
+
stride_q,
|
| 588 |
+
stride_kv,
|
| 589 |
+
padding_q,
|
| 590 |
+
padding_kv,
|
| 591 |
+
qkv_projection_method,
|
| 592 |
+
qkv_bias,
|
| 593 |
+
attention_drop_rate,
|
| 594 |
+
drop_rate,
|
| 595 |
+
with_cls_token,
|
| 596 |
+
name="attention",
|
| 597 |
+
)
|
| 598 |
+
self.intermediate = TFCvtIntermediate(config, embed_dim, mlp_ratio, name="intermediate")
|
| 599 |
+
self.dense_output = TFCvtOutput(config, embed_dim, mlp_ratio, drop_rate, name="output")
|
| 600 |
+
# Using `layers.Activation` instead of `tf.identity` to better control `training` behaviour.
|
| 601 |
+
self.drop_path = (
|
| 602 |
+
TFCvtDropPath(drop_path_rate, name="drop_path")
|
| 603 |
+
if drop_path_rate > 0.0
|
| 604 |
+
else keras.layers.Activation("linear", name="drop_path")
|
| 605 |
+
)
|
| 606 |
+
# Using the same default epsilon as PyTorch
|
| 607 |
+
self.layernorm_before = keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_before")
|
| 608 |
+
self.layernorm_after = keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_after")
|
| 609 |
+
self.embed_dim = embed_dim
|
| 610 |
+
|
| 611 |
+
def call(self, hidden_state: tf.Tensor, height: int, width: int, training: bool = False) -> tf.Tensor:
|
| 612 |
+
# in Cvt, layernorm is applied before self-attention
|
| 613 |
+
attention_output = self.attention(self.layernorm_before(hidden_state), height, width, training=training)
|
| 614 |
+
attention_output = self.drop_path(attention_output, training=training)
|
| 615 |
+
|
| 616 |
+
# first residual connection
|
| 617 |
+
hidden_state = attention_output + hidden_state
|
| 618 |
+
|
| 619 |
+
# in Cvt, layernorm is also applied after self-attention
|
| 620 |
+
layer_output = self.layernorm_after(hidden_state)
|
| 621 |
+
layer_output = self.intermediate(layer_output)
|
| 622 |
+
|
| 623 |
+
# second residual connection is done here
|
| 624 |
+
layer_output = self.dense_output(layer_output, hidden_state)
|
| 625 |
+
layer_output = self.drop_path(layer_output, training=training)
|
| 626 |
+
return layer_output
|
| 627 |
+
|
| 628 |
+
def build(self, input_shape=None):
|
| 629 |
+
if self.built:
|
| 630 |
+
return
|
| 631 |
+
self.built = True
|
| 632 |
+
if getattr(self, "attention", None) is not None:
|
| 633 |
+
with tf.name_scope(self.attention.name):
|
| 634 |
+
self.attention.build(None)
|
| 635 |
+
if getattr(self, "intermediate", None) is not None:
|
| 636 |
+
with tf.name_scope(self.intermediate.name):
|
| 637 |
+
self.intermediate.build(None)
|
| 638 |
+
if getattr(self, "dense_output", None) is not None:
|
| 639 |
+
with tf.name_scope(self.dense_output.name):
|
| 640 |
+
self.dense_output.build(None)
|
| 641 |
+
if getattr(self, "drop_path", None) is not None:
|
| 642 |
+
with tf.name_scope(self.drop_path.name):
|
| 643 |
+
self.drop_path.build(None)
|
| 644 |
+
if getattr(self, "layernorm_before", None) is not None:
|
| 645 |
+
with tf.name_scope(self.layernorm_before.name):
|
| 646 |
+
self.layernorm_before.build([None, None, self.embed_dim])
|
| 647 |
+
if getattr(self, "layernorm_after", None) is not None:
|
| 648 |
+
with tf.name_scope(self.layernorm_after.name):
|
| 649 |
+
self.layernorm_after.build([None, None, self.embed_dim])
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
class TFCvtStage(keras.layers.Layer):
|
| 653 |
+
"""
|
| 654 |
+
Cvt stage (encoder block). Each stage has 2 parts :
|
| 655 |
+
- (1) A Convolutional Token Embedding layer
|
| 656 |
+
- (2) A Convolutional Transformer Block (layer).
|
| 657 |
+
The classification token is added only in the last stage.
|
| 658 |
+
|
| 659 |
+
Args:
|
| 660 |
+
config ([`CvtConfig`]): Model configuration class.
|
| 661 |
+
stage (`int`): Stage number.
|
| 662 |
+
"""
|
| 663 |
+
|
| 664 |
+
def __init__(self, config: CvtConfig, stage: int, **kwargs):
|
| 665 |
+
super().__init__(**kwargs)
|
| 666 |
+
self.config = config
|
| 667 |
+
self.stage = stage
|
| 668 |
+
if self.config.cls_token[self.stage]:
|
| 669 |
+
self.cls_token = self.add_weight(
|
| 670 |
+
shape=(1, 1, self.config.embed_dim[-1]),
|
| 671 |
+
initializer=get_initializer(self.config.initializer_range),
|
| 672 |
+
trainable=True,
|
| 673 |
+
name="cvt.encoder.stages.2.cls_token",
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
self.embedding = TFCvtEmbeddings(
|
| 677 |
+
self.config,
|
| 678 |
+
patch_size=config.patch_sizes[self.stage],
|
| 679 |
+
num_channels=config.num_channels if self.stage == 0 else config.embed_dim[self.stage - 1],
|
| 680 |
+
stride=config.patch_stride[self.stage],
|
| 681 |
+
embed_dim=config.embed_dim[self.stage],
|
| 682 |
+
padding=config.patch_padding[self.stage],
|
| 683 |
+
dropout_rate=config.drop_rate[self.stage],
|
| 684 |
+
name="embedding",
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
drop_path_rates = tf.linspace(0.0, config.drop_path_rate[self.stage], config.depth[stage])
|
| 688 |
+
drop_path_rates = [x.numpy().item() for x in drop_path_rates]
|
| 689 |
+
self.layers = [
|
| 690 |
+
TFCvtLayer(
|
| 691 |
+
config,
|
| 692 |
+
num_heads=config.num_heads[self.stage],
|
| 693 |
+
embed_dim=config.embed_dim[self.stage],
|
| 694 |
+
kernel_size=config.kernel_qkv[self.stage],
|
| 695 |
+
stride_q=config.stride_q[self.stage],
|
| 696 |
+
stride_kv=config.stride_kv[self.stage],
|
| 697 |
+
padding_q=config.padding_q[self.stage],
|
| 698 |
+
padding_kv=config.padding_kv[self.stage],
|
| 699 |
+
qkv_projection_method=config.qkv_projection_method[self.stage],
|
| 700 |
+
qkv_bias=config.qkv_bias[self.stage],
|
| 701 |
+
attention_drop_rate=config.attention_drop_rate[self.stage],
|
| 702 |
+
drop_rate=config.drop_rate[self.stage],
|
| 703 |
+
mlp_ratio=config.mlp_ratio[self.stage],
|
| 704 |
+
drop_path_rate=drop_path_rates[self.stage],
|
| 705 |
+
with_cls_token=config.cls_token[self.stage],
|
| 706 |
+
name=f"layers.{j}",
|
| 707 |
+
)
|
| 708 |
+
for j in range(config.depth[self.stage])
|
| 709 |
+
]
|
| 710 |
+
|
| 711 |
+
def call(self, hidden_state: tf.Tensor, training: bool = False):
|
| 712 |
+
cls_token = None
|
| 713 |
+
hidden_state = self.embedding(hidden_state, training)
|
| 714 |
+
|
| 715 |
+
# "batch_size, height, width, num_channels -> batch_size, (height*width), num_channels"
|
| 716 |
+
batch_size, height, width, num_channels = shape_list(hidden_state)
|
| 717 |
+
hidden_size = height * width
|
| 718 |
+
hidden_state = tf.reshape(hidden_state, shape=(batch_size, hidden_size, num_channels))
|
| 719 |
+
|
| 720 |
+
if self.config.cls_token[self.stage]:
|
| 721 |
+
cls_token = tf.repeat(self.cls_token, repeats=batch_size, axis=0)
|
| 722 |
+
hidden_state = tf.concat((cls_token, hidden_state), axis=1)
|
| 723 |
+
|
| 724 |
+
for layer in self.layers:
|
| 725 |
+
layer_outputs = layer(hidden_state, height, width, training=training)
|
| 726 |
+
hidden_state = layer_outputs
|
| 727 |
+
|
| 728 |
+
if self.config.cls_token[self.stage]:
|
| 729 |
+
cls_token, hidden_state = tf.split(hidden_state, [1, height * width], 1)
|
| 730 |
+
|
| 731 |
+
# "batch_size, (height*width), num_channels -> batch_size, height, width, num_channels"
|
| 732 |
+
hidden_state = tf.reshape(hidden_state, shape=(batch_size, height, width, num_channels))
|
| 733 |
+
return hidden_state, cls_token
|
| 734 |
+
|
| 735 |
+
def build(self, input_shape=None):
|
| 736 |
+
if self.built:
|
| 737 |
+
return
|
| 738 |
+
self.built = True
|
| 739 |
+
if getattr(self, "embedding", None) is not None:
|
| 740 |
+
with tf.name_scope(self.embedding.name):
|
| 741 |
+
self.embedding.build(None)
|
| 742 |
+
if getattr(self, "layers", None) is not None:
|
| 743 |
+
for layer in self.layers:
|
| 744 |
+
with tf.name_scope(layer.name):
|
| 745 |
+
layer.build(None)
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
class TFCvtEncoder(keras.layers.Layer):
|
| 749 |
+
"""
|
| 750 |
+
Convolutional Vision Transformer encoder. CVT has 3 stages of encoder blocks with their respective number of layers
|
| 751 |
+
(depth) being 1, 2 and 10.
|
| 752 |
+
|
| 753 |
+
Args:
|
| 754 |
+
config ([`CvtConfig`]): Model configuration class.
|
| 755 |
+
"""
|
| 756 |
+
|
| 757 |
+
config_class = CvtConfig
|
| 758 |
+
|
| 759 |
+
def __init__(self, config: CvtConfig, **kwargs):
|
| 760 |
+
super().__init__(**kwargs)
|
| 761 |
+
self.config = config
|
| 762 |
+
self.stages = [
|
| 763 |
+
TFCvtStage(config, stage_idx, name=f"stages.{stage_idx}") for stage_idx in range(len(config.depth))
|
| 764 |
+
]
|
| 765 |
+
|
| 766 |
+
def call(
|
| 767 |
+
self,
|
| 768 |
+
pixel_values: TFModelInputType,
|
| 769 |
+
output_hidden_states: Optional[bool] = False,
|
| 770 |
+
return_dict: Optional[bool] = True,
|
| 771 |
+
training: Optional[bool] = False,
|
| 772 |
+
) -> Union[TFBaseModelOutputWithCLSToken, Tuple[tf.Tensor]]:
|
| 773 |
+
all_hidden_states = () if output_hidden_states else None
|
| 774 |
+
hidden_state = pixel_values
|
| 775 |
+
# When running on CPU, `keras.layers.Conv2D` doesn't support (batch_size, num_channels, height, width)
|
| 776 |
+
# as input format. So change the input format to (batch_size, height, width, num_channels).
|
| 777 |
+
hidden_state = tf.transpose(hidden_state, perm=(0, 2, 3, 1))
|
| 778 |
+
|
| 779 |
+
cls_token = None
|
| 780 |
+
for _, (stage_module) in enumerate(self.stages):
|
| 781 |
+
hidden_state, cls_token = stage_module(hidden_state, training=training)
|
| 782 |
+
if output_hidden_states:
|
| 783 |
+
all_hidden_states = all_hidden_states + (hidden_state,)
|
| 784 |
+
|
| 785 |
+
# Change back to (batch_size, num_channels, height, width) format to have uniformity in the modules
|
| 786 |
+
hidden_state = tf.transpose(hidden_state, perm=(0, 3, 1, 2))
|
| 787 |
+
if output_hidden_states:
|
| 788 |
+
all_hidden_states = tuple([tf.transpose(hs, perm=(0, 3, 1, 2)) for hs in all_hidden_states])
|
| 789 |
+
|
| 790 |
+
if not return_dict:
|
| 791 |
+
return tuple(v for v in [hidden_state, cls_token, all_hidden_states] if v is not None)
|
| 792 |
+
|
| 793 |
+
return TFBaseModelOutputWithCLSToken(
|
| 794 |
+
last_hidden_state=hidden_state,
|
| 795 |
+
cls_token_value=cls_token,
|
| 796 |
+
hidden_states=all_hidden_states,
|
| 797 |
+
)
|
| 798 |
+
|
| 799 |
+
def build(self, input_shape=None):
|
| 800 |
+
if self.built:
|
| 801 |
+
return
|
| 802 |
+
self.built = True
|
| 803 |
+
if getattr(self, "stages", None) is not None:
|
| 804 |
+
for layer in self.stages:
|
| 805 |
+
with tf.name_scope(layer.name):
|
| 806 |
+
layer.build(None)
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
@keras_serializable
|
| 810 |
+
class TFCvtMainLayer(keras.layers.Layer):
|
| 811 |
+
"""Construct the Cvt model."""
|
| 812 |
+
|
| 813 |
+
config_class = CvtConfig
|
| 814 |
+
|
| 815 |
+
def __init__(self, config: CvtConfig, **kwargs):
|
| 816 |
+
super().__init__(**kwargs)
|
| 817 |
+
self.config = config
|
| 818 |
+
self.encoder = TFCvtEncoder(config, name="encoder")
|
| 819 |
+
|
| 820 |
+
@unpack_inputs
|
| 821 |
+
def call(
|
| 822 |
+
self,
|
| 823 |
+
pixel_values: TFModelInputType | None = None,
|
| 824 |
+
output_hidden_states: Optional[bool] = None,
|
| 825 |
+
return_dict: Optional[bool] = None,
|
| 826 |
+
training: Optional[bool] = False,
|
| 827 |
+
) -> Union[TFBaseModelOutputWithCLSToken, Tuple[tf.Tensor]]:
|
| 828 |
+
if pixel_values is None:
|
| 829 |
+
raise ValueError("You have to specify pixel_values")
|
| 830 |
+
|
| 831 |
+
encoder_outputs = self.encoder(
|
| 832 |
+
pixel_values,
|
| 833 |
+
output_hidden_states=output_hidden_states,
|
| 834 |
+
return_dict=return_dict,
|
| 835 |
+
training=training,
|
| 836 |
+
)
|
| 837 |
+
|
| 838 |
+
sequence_output = encoder_outputs[0]
|
| 839 |
+
|
| 840 |
+
if not return_dict:
|
| 841 |
+
return (sequence_output,) + encoder_outputs[1:]
|
| 842 |
+
|
| 843 |
+
return TFBaseModelOutputWithCLSToken(
|
| 844 |
+
last_hidden_state=sequence_output,
|
| 845 |
+
cls_token_value=encoder_outputs.cls_token_value,
|
| 846 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
def build(self, input_shape=None):
|
| 850 |
+
if self.built:
|
| 851 |
+
return
|
| 852 |
+
self.built = True
|
| 853 |
+
if getattr(self, "encoder", None) is not None:
|
| 854 |
+
with tf.name_scope(self.encoder.name):
|
| 855 |
+
self.encoder.build(None)
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
class TFCvtPreTrainedModel(TFPreTrainedModel):
|
| 859 |
+
"""
|
| 860 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 861 |
+
models.
|
| 862 |
+
"""
|
| 863 |
+
|
| 864 |
+
config_class = CvtConfig
|
| 865 |
+
base_model_prefix = "cvt"
|
| 866 |
+
main_input_name = "pixel_values"
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
TFCVT_START_DOCSTRING = r"""
|
| 870 |
+
|
| 871 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 872 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 873 |
+
etc.)
|
| 874 |
+
|
| 875 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 876 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 877 |
+
behavior.
|
| 878 |
+
|
| 879 |
+
<Tip>
|
| 880 |
+
|
| 881 |
+
TF 2.0 models accepts two formats as inputs:
|
| 882 |
+
|
| 883 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 884 |
+
- having all inputs as a list, tuple or dict in the first positional arguments.
|
| 885 |
+
|
| 886 |
+
This second option is useful when using [`keras.Model.fit`] method which currently requires having all the
|
| 887 |
+
tensors in the first argument of the model call function: `model(inputs)`.
|
| 888 |
+
|
| 889 |
+
</Tip>
|
| 890 |
+
|
| 891 |
+
Args:
|
| 892 |
+
config ([`CvtConfig`]): Model configuration class with all the parameters of the model.
|
| 893 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 894 |
+
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 895 |
+
"""
|
| 896 |
+
|
| 897 |
+
TFCVT_INPUTS_DOCSTRING = r"""
|
| 898 |
+
Args:
|
| 899 |
+
pixel_values (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `(batch_size, num_channels, height, width)`):
|
| 900 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`CvtImageProcessor.__call__`]
|
| 901 |
+
for details.
|
| 902 |
+
|
| 903 |
+
output_hidden_states (`bool`, *optional*):
|
| 904 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 905 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 906 |
+
used instead.
|
| 907 |
+
return_dict (`bool`, *optional*):
|
| 908 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 909 |
+
eager mode, in graph mode the value will always be set to True.
|
| 910 |
+
training (`bool`, *optional*, defaults to `False``):
|
| 911 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 912 |
+
behaviors between training and evaluation).
|
| 913 |
+
"""
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
@add_start_docstrings(
|
| 917 |
+
"The bare Cvt Model transformer outputting raw hidden-states without any specific head on top.",
|
| 918 |
+
TFCVT_START_DOCSTRING,
|
| 919 |
+
)
|
| 920 |
+
class TFCvtModel(TFCvtPreTrainedModel):
|
| 921 |
+
def __init__(self, config: CvtConfig, *inputs, **kwargs):
|
| 922 |
+
super().__init__(config, *inputs, **kwargs)
|
| 923 |
+
|
| 924 |
+
self.cvt = TFCvtMainLayer(config, name="cvt")
|
| 925 |
+
|
| 926 |
+
@unpack_inputs
|
| 927 |
+
@add_start_docstrings_to_model_forward(TFCVT_INPUTS_DOCSTRING)
|
| 928 |
+
@replace_return_docstrings(output_type=TFBaseModelOutputWithCLSToken, config_class=_CONFIG_FOR_DOC)
|
| 929 |
+
def call(
|
| 930 |
+
self,
|
| 931 |
+
pixel_values: tf.Tensor | None = None,
|
| 932 |
+
output_hidden_states: Optional[bool] = None,
|
| 933 |
+
return_dict: Optional[bool] = None,
|
| 934 |
+
training: Optional[bool] = False,
|
| 935 |
+
) -> Union[TFBaseModelOutputWithCLSToken, Tuple[tf.Tensor]]:
|
| 936 |
+
r"""
|
| 937 |
+
Returns:
|
| 938 |
+
|
| 939 |
+
Examples:
|
| 940 |
+
|
| 941 |
+
```python
|
| 942 |
+
>>> from transformers import AutoImageProcessor, TFCvtModel
|
| 943 |
+
>>> from PIL import Image
|
| 944 |
+
>>> import requests
|
| 945 |
+
|
| 946 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 947 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 948 |
+
|
| 949 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/cvt-13")
|
| 950 |
+
>>> model = TFCvtModel.from_pretrained("microsoft/cvt-13")
|
| 951 |
+
|
| 952 |
+
>>> inputs = image_processor(images=image, return_tensors="tf")
|
| 953 |
+
>>> outputs = model(**inputs)
|
| 954 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 955 |
+
```"""
|
| 956 |
+
|
| 957 |
+
if pixel_values is None:
|
| 958 |
+
raise ValueError("You have to specify pixel_values")
|
| 959 |
+
|
| 960 |
+
outputs = self.cvt(
|
| 961 |
+
pixel_values=pixel_values,
|
| 962 |
+
output_hidden_states=output_hidden_states,
|
| 963 |
+
return_dict=return_dict,
|
| 964 |
+
training=training,
|
| 965 |
+
)
|
| 966 |
+
|
| 967 |
+
if not return_dict:
|
| 968 |
+
return (outputs[0],) + outputs[1:]
|
| 969 |
+
|
| 970 |
+
return TFBaseModelOutputWithCLSToken(
|
| 971 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 972 |
+
cls_token_value=outputs.cls_token_value,
|
| 973 |
+
hidden_states=outputs.hidden_states,
|
| 974 |
+
)
|
| 975 |
+
|
| 976 |
+
def build(self, input_shape=None):
|
| 977 |
+
if self.built:
|
| 978 |
+
return
|
| 979 |
+
self.built = True
|
| 980 |
+
if getattr(self, "cvt", None) is not None:
|
| 981 |
+
with tf.name_scope(self.cvt.name):
|
| 982 |
+
self.cvt.build(None)
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
@add_start_docstrings(
|
| 986 |
+
"""
|
| 987 |
+
Cvt Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
|
| 988 |
+
the [CLS] token) e.g. for ImageNet.
|
| 989 |
+
""",
|
| 990 |
+
TFCVT_START_DOCSTRING,
|
| 991 |
+
)
|
| 992 |
+
class TFCvtForImageClassification(TFCvtPreTrainedModel, TFSequenceClassificationLoss):
|
| 993 |
+
def __init__(self, config: CvtConfig, *inputs, **kwargs):
|
| 994 |
+
super().__init__(config, *inputs, **kwargs)
|
| 995 |
+
|
| 996 |
+
self.num_labels = config.num_labels
|
| 997 |
+
self.cvt = TFCvtMainLayer(config, name="cvt")
|
| 998 |
+
# Using same default epsilon as in the original implementation.
|
| 999 |
+
self.layernorm = keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm")
|
| 1000 |
+
|
| 1001 |
+
# Classifier head
|
| 1002 |
+
self.classifier = keras.layers.Dense(
|
| 1003 |
+
units=config.num_labels,
|
| 1004 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 1005 |
+
use_bias=True,
|
| 1006 |
+
bias_initializer="zeros",
|
| 1007 |
+
name="classifier",
|
| 1008 |
+
)
|
| 1009 |
+
self.config = config
|
| 1010 |
+
|
| 1011 |
+
@unpack_inputs
|
| 1012 |
+
@add_start_docstrings_to_model_forward(TFCVT_INPUTS_DOCSTRING)
|
| 1013 |
+
@replace_return_docstrings(output_type=TFImageClassifierOutputWithNoAttention, config_class=_CONFIG_FOR_DOC)
|
| 1014 |
+
def call(
|
| 1015 |
+
self,
|
| 1016 |
+
pixel_values: tf.Tensor | None = None,
|
| 1017 |
+
labels: tf.Tensor | None = None,
|
| 1018 |
+
output_hidden_states: Optional[bool] = None,
|
| 1019 |
+
return_dict: Optional[bool] = None,
|
| 1020 |
+
training: Optional[bool] = False,
|
| 1021 |
+
) -> Union[TFImageClassifierOutputWithNoAttention, Tuple[tf.Tensor]]:
|
| 1022 |
+
r"""
|
| 1023 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
|
| 1024 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 1025 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1026 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1027 |
+
|
| 1028 |
+
Returns:
|
| 1029 |
+
|
| 1030 |
+
Examples:
|
| 1031 |
+
|
| 1032 |
+
```python
|
| 1033 |
+
>>> from transformers import AutoImageProcessor, TFCvtForImageClassification
|
| 1034 |
+
>>> import tensorflow as tf
|
| 1035 |
+
>>> from PIL import Image
|
| 1036 |
+
>>> import requests
|
| 1037 |
+
|
| 1038 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1039 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1040 |
+
|
| 1041 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/cvt-13")
|
| 1042 |
+
>>> model = TFCvtForImageClassification.from_pretrained("microsoft/cvt-13")
|
| 1043 |
+
|
| 1044 |
+
>>> inputs = image_processor(images=image, return_tensors="tf")
|
| 1045 |
+
>>> outputs = model(**inputs)
|
| 1046 |
+
>>> logits = outputs.logits
|
| 1047 |
+
>>> # model predicts one of the 1000 ImageNet classes
|
| 1048 |
+
>>> predicted_class_idx = tf.math.argmax(logits, axis=-1)[0]
|
| 1049 |
+
>>> print("Predicted class:", model.config.id2label[int(predicted_class_idx)])
|
| 1050 |
+
```"""
|
| 1051 |
+
|
| 1052 |
+
outputs = self.cvt(
|
| 1053 |
+
pixel_values,
|
| 1054 |
+
output_hidden_states=output_hidden_states,
|
| 1055 |
+
return_dict=return_dict,
|
| 1056 |
+
training=training,
|
| 1057 |
+
)
|
| 1058 |
+
|
| 1059 |
+
sequence_output = outputs[0]
|
| 1060 |
+
cls_token = outputs[1]
|
| 1061 |
+
if self.config.cls_token[-1]:
|
| 1062 |
+
sequence_output = self.layernorm(cls_token)
|
| 1063 |
+
else:
|
| 1064 |
+
# rearrange "batch_size, num_channels, height, width -> batch_size, (height*width), num_channels"
|
| 1065 |
+
batch_size, num_channels, height, width = shape_list(sequence_output)
|
| 1066 |
+
sequence_output = tf.reshape(sequence_output, shape=(batch_size, num_channels, height * width))
|
| 1067 |
+
sequence_output = tf.transpose(sequence_output, perm=(0, 2, 1))
|
| 1068 |
+
sequence_output = self.layernorm(sequence_output)
|
| 1069 |
+
|
| 1070 |
+
sequence_output_mean = tf.reduce_mean(sequence_output, axis=1)
|
| 1071 |
+
logits = self.classifier(sequence_output_mean)
|
| 1072 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
|
| 1073 |
+
|
| 1074 |
+
if not return_dict:
|
| 1075 |
+
output = (logits,) + outputs[2:]
|
| 1076 |
+
return ((loss,) + output) if loss is not None else output
|
| 1077 |
+
|
| 1078 |
+
return TFImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
| 1079 |
+
|
| 1080 |
+
def build(self, input_shape=None):
|
| 1081 |
+
if self.built:
|
| 1082 |
+
return
|
| 1083 |
+
self.built = True
|
| 1084 |
+
if getattr(self, "cvt", None) is not None:
|
| 1085 |
+
with tf.name_scope(self.cvt.name):
|
| 1086 |
+
self.cvt.build(None)
|
| 1087 |
+
if getattr(self, "layernorm", None) is not None:
|
| 1088 |
+
with tf.name_scope(self.layernorm.name):
|
| 1089 |
+
self.layernorm.build([None, None, self.config.embed_dim[-1]])
|
| 1090 |
+
if getattr(self, "classifier", None) is not None:
|
| 1091 |
+
if hasattr(self.classifier, "name"):
|
| 1092 |
+
with tf.name_scope(self.classifier.name):
|
| 1093 |
+
self.classifier.build([None, None, self.config.embed_dim[-1]])
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
__all__ = ["TFCvtForImageClassification", "TFCvtModel", "TFCvtPreTrainedModel"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dab_detr/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ...utils import _LazyModule
|
| 18 |
+
from ...utils.import_utils import define_import_structure
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from .configuration_dab_detr import *
|
| 23 |
+
from .modeling_dab_detr 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__)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dab_detr/configuration_dab_detr.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""DAB-DETR model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
from ...utils.backbone_utils import verify_backbone_config_arguments
|
| 20 |
+
from ..auto import CONFIG_MAPPING
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class DabDetrConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`DabDetrModel`]. It is used to instantiate
|
| 29 |
+
a DAB-DETR 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 DAB-DETR
|
| 31 |
+
[IDEA-Research/dab_detr-base](https://huggingface.co/IDEA-Research/dab_detr-base) 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 |
+
use_timm_backbone (`bool`, *optional*, defaults to `True`):
|
| 38 |
+
Whether or not to use the `timm` library for the backbone. If set to `False`, will use the [`AutoBackbone`]
|
| 39 |
+
API.
|
| 40 |
+
backbone_config (`PretrainedConfig` or `dict`, *optional*):
|
| 41 |
+
The configuration of the backbone model. Only used in case `use_timm_backbone` is set to `False` in which
|
| 42 |
+
case it will default to `ResNetConfig()`.
|
| 43 |
+
backbone (`str`, *optional*, defaults to `"resnet50"`):
|
| 44 |
+
Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
|
| 45 |
+
will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
|
| 46 |
+
is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
|
| 47 |
+
use_pretrained_backbone (`bool`, *optional*, defaults to `True`):
|
| 48 |
+
Whether to use pretrained weights for the backbone.
|
| 49 |
+
backbone_kwargs (`dict`, *optional*):
|
| 50 |
+
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
|
| 51 |
+
e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
|
| 52 |
+
num_queries (`int`, *optional*, defaults to 300):
|
| 53 |
+
Number of object queries, i.e. detection slots. This is the maximal number of objects
|
| 54 |
+
[`DabDetrModel`] can detect in a single image. For COCO, we recommend 100 queries.
|
| 55 |
+
encoder_layers (`int`, *optional*, defaults to 6):
|
| 56 |
+
Number of encoder layers.
|
| 57 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 2048):
|
| 58 |
+
Dimension of the "intermediate" (often named feed-forward) layer in encoder.
|
| 59 |
+
encoder_attention_heads (`int`, *optional*, defaults to 8):
|
| 60 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 61 |
+
decoder_layers (`int`, *optional*, defaults to 6):
|
| 62 |
+
Number of decoder layers.
|
| 63 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 2048):
|
| 64 |
+
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
|
| 65 |
+
decoder_attention_heads (`int`, *optional*, defaults to 8):
|
| 66 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 67 |
+
is_encoder_decoder (`bool`, *optional*, defaults to `True`):
|
| 68 |
+
Indicates whether the transformer model architecture is an encoder-decoder or not.
|
| 69 |
+
activation_function (`str` or `function`, *optional*, defaults to `"prelu"`):
|
| 70 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 71 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 72 |
+
hidden_size (`int`, *optional*, defaults to 256):
|
| 73 |
+
This parameter is a general dimension parameter, defining dimensions for components such as the encoder layer and projection parameters in the decoder layer, among others.
|
| 74 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 75 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 76 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 77 |
+
The dropout ratio for the attention probabilities.
|
| 78 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 79 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 80 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 81 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 82 |
+
init_xavier_std (`float`, *optional*, defaults to 1.0):
|
| 83 |
+
The scaling factor used for the Xavier initialization gain in the HM Attention map module.
|
| 84 |
+
auxiliary_loss (`bool`, *optional*, defaults to `False`):
|
| 85 |
+
Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
|
| 86 |
+
dilation (`bool`, *optional*, defaults to `False`):
|
| 87 |
+
Whether to replace stride with dilation in the last convolutional block (DC5). Only supported when `use_timm_backbone` = `True`.
|
| 88 |
+
class_cost (`float`, *optional*, defaults to 2):
|
| 89 |
+
Relative weight of the classification error in the Hungarian matching cost.
|
| 90 |
+
bbox_cost (`float`, *optional*, defaults to 5):
|
| 91 |
+
Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost.
|
| 92 |
+
giou_cost (`float`, *optional*, defaults to 2):
|
| 93 |
+
Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost.
|
| 94 |
+
cls_loss_coefficient (`float`, *optional*, defaults to 2):
|
| 95 |
+
Relative weight of the classification loss in the object detection loss function.
|
| 96 |
+
bbox_loss_coefficient (`float`, *optional*, defaults to 5):
|
| 97 |
+
Relative weight of the L1 bounding box loss in the object detection loss.
|
| 98 |
+
giou_loss_coefficient (`float`, *optional*, defaults to 2):
|
| 99 |
+
Relative weight of the generalized IoU loss in the object detection loss.
|
| 100 |
+
focal_alpha (`float`, *optional*, defaults to 0.25):
|
| 101 |
+
Alpha parameter in the focal loss.
|
| 102 |
+
temperature_height (`int`, *optional*, defaults to 20):
|
| 103 |
+
Temperature parameter to tune the flatness of positional attention (HEIGHT)
|
| 104 |
+
temperature_width (`int`, *optional*, defaults to 20):
|
| 105 |
+
Temperature parameter to tune the flatness of positional attention (WIDTH)
|
| 106 |
+
query_dim (`int`, *optional*, defaults to 4):
|
| 107 |
+
Query dimension parameter represents the size of the output vector.
|
| 108 |
+
random_refpoints_xy (`bool`, *optional*, defaults to `False`):
|
| 109 |
+
Whether to fix the x and y coordinates of the anchor boxes with random initialization.
|
| 110 |
+
keep_query_pos (`bool`, *optional*, defaults to `False`):
|
| 111 |
+
Whether to concatenate the projected positional embedding from the object query into the original query (key) in every decoder layer.
|
| 112 |
+
num_patterns (`int`, *optional*, defaults to 0):
|
| 113 |
+
Number of pattern embeddings.
|
| 114 |
+
normalize_before (`bool`, *optional*, defaults to `False`):
|
| 115 |
+
Whether we use a normalization layer in the Encoder or not.
|
| 116 |
+
sine_position_embedding_scale (`float`, *optional*, defaults to 'None'):
|
| 117 |
+
Scaling factor applied to the normalized positional encodings.
|
| 118 |
+
initializer_bias_prior_prob (`float`, *optional*):
|
| 119 |
+
The prior probability used by the bias initializer to initialize biases for `enc_score_head` and `class_embed`.
|
| 120 |
+
If `None`, `prior_prob` computed as `prior_prob = 1 / (num_labels + 1)` while initializing model weights.
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
Examples:
|
| 124 |
+
|
| 125 |
+
```python
|
| 126 |
+
>>> from transformers import DabDetrConfig, DabDetrModel
|
| 127 |
+
|
| 128 |
+
>>> # Initializing a DAB-DETR IDEA-Research/dab_detr-base style configuration
|
| 129 |
+
>>> configuration = DabDetrConfig()
|
| 130 |
+
|
| 131 |
+
>>> # Initializing a model (with random weights) from the IDEA-Research/dab_detr-base style configuration
|
| 132 |
+
>>> model = DabDetrModel(configuration)
|
| 133 |
+
|
| 134 |
+
>>> # Accessing the model configuration
|
| 135 |
+
>>> configuration = model.config
|
| 136 |
+
```"""
|
| 137 |
+
|
| 138 |
+
model_type = "dab-detr"
|
| 139 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 140 |
+
attribute_map = {
|
| 141 |
+
"num_attention_heads": "encoder_attention_heads",
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
def __init__(
|
| 145 |
+
self,
|
| 146 |
+
use_timm_backbone=True,
|
| 147 |
+
backbone_config=None,
|
| 148 |
+
backbone="resnet50",
|
| 149 |
+
use_pretrained_backbone=True,
|
| 150 |
+
backbone_kwargs=None,
|
| 151 |
+
num_queries=300,
|
| 152 |
+
encoder_layers=6,
|
| 153 |
+
encoder_ffn_dim=2048,
|
| 154 |
+
encoder_attention_heads=8,
|
| 155 |
+
decoder_layers=6,
|
| 156 |
+
decoder_ffn_dim=2048,
|
| 157 |
+
decoder_attention_heads=8,
|
| 158 |
+
is_encoder_decoder=True,
|
| 159 |
+
activation_function="prelu",
|
| 160 |
+
hidden_size=256,
|
| 161 |
+
dropout=0.1,
|
| 162 |
+
attention_dropout=0.0,
|
| 163 |
+
activation_dropout=0.0,
|
| 164 |
+
init_std=0.02,
|
| 165 |
+
init_xavier_std=1.0,
|
| 166 |
+
auxiliary_loss=False,
|
| 167 |
+
dilation=False,
|
| 168 |
+
class_cost=2,
|
| 169 |
+
bbox_cost=5,
|
| 170 |
+
giou_cost=2,
|
| 171 |
+
cls_loss_coefficient=2,
|
| 172 |
+
bbox_loss_coefficient=5,
|
| 173 |
+
giou_loss_coefficient=2,
|
| 174 |
+
focal_alpha=0.25,
|
| 175 |
+
temperature_height=20,
|
| 176 |
+
temperature_width=20,
|
| 177 |
+
query_dim=4,
|
| 178 |
+
random_refpoints_xy=False,
|
| 179 |
+
keep_query_pos=False,
|
| 180 |
+
num_patterns=0,
|
| 181 |
+
normalize_before=False,
|
| 182 |
+
sine_position_embedding_scale=None,
|
| 183 |
+
initializer_bias_prior_prob=None,
|
| 184 |
+
**kwargs,
|
| 185 |
+
):
|
| 186 |
+
if query_dim != 4:
|
| 187 |
+
raise ValueError("The query dimensions has to be 4.")
|
| 188 |
+
|
| 189 |
+
# We default to values which were previously hard-coded in the model. This enables configurability of the config
|
| 190 |
+
# while keeping the default behavior the same.
|
| 191 |
+
if use_timm_backbone and backbone_kwargs is None:
|
| 192 |
+
backbone_kwargs = {}
|
| 193 |
+
if dilation:
|
| 194 |
+
backbone_kwargs["output_stride"] = 16
|
| 195 |
+
backbone_kwargs["out_indices"] = [1, 2, 3, 4]
|
| 196 |
+
backbone_kwargs["in_chans"] = 3 # num_channels
|
| 197 |
+
# Backwards compatibility
|
| 198 |
+
elif not use_timm_backbone and backbone in (None, "resnet50"):
|
| 199 |
+
if backbone_config is None:
|
| 200 |
+
logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.")
|
| 201 |
+
backbone_config = CONFIG_MAPPING["resnet"](out_features=["stage4"])
|
| 202 |
+
elif isinstance(backbone_config, dict):
|
| 203 |
+
backbone_model_type = backbone_config.get("model_type")
|
| 204 |
+
config_class = CONFIG_MAPPING[backbone_model_type]
|
| 205 |
+
backbone_config = config_class.from_dict(backbone_config)
|
| 206 |
+
backbone = None
|
| 207 |
+
# set timm attributes to None
|
| 208 |
+
dilation = None
|
| 209 |
+
|
| 210 |
+
verify_backbone_config_arguments(
|
| 211 |
+
use_timm_backbone=use_timm_backbone,
|
| 212 |
+
use_pretrained_backbone=use_pretrained_backbone,
|
| 213 |
+
backbone=backbone,
|
| 214 |
+
backbone_config=backbone_config,
|
| 215 |
+
backbone_kwargs=backbone_kwargs,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
self.use_timm_backbone = use_timm_backbone
|
| 219 |
+
self.backbone_config = backbone_config
|
| 220 |
+
self.num_queries = num_queries
|
| 221 |
+
self.hidden_size = hidden_size
|
| 222 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 223 |
+
self.encoder_layers = encoder_layers
|
| 224 |
+
self.encoder_attention_heads = encoder_attention_heads
|
| 225 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 226 |
+
self.decoder_layers = decoder_layers
|
| 227 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 228 |
+
self.dropout = dropout
|
| 229 |
+
self.attention_dropout = attention_dropout
|
| 230 |
+
self.activation_dropout = activation_dropout
|
| 231 |
+
self.activation_function = activation_function
|
| 232 |
+
self.init_std = init_std
|
| 233 |
+
self.init_xavier_std = init_xavier_std
|
| 234 |
+
self.num_hidden_layers = encoder_layers
|
| 235 |
+
self.auxiliary_loss = auxiliary_loss
|
| 236 |
+
self.backbone = backbone
|
| 237 |
+
self.use_pretrained_backbone = use_pretrained_backbone
|
| 238 |
+
self.backbone_kwargs = backbone_kwargs
|
| 239 |
+
# Hungarian matcher
|
| 240 |
+
self.class_cost = class_cost
|
| 241 |
+
self.bbox_cost = bbox_cost
|
| 242 |
+
self.giou_cost = giou_cost
|
| 243 |
+
# Loss coefficients
|
| 244 |
+
self.cls_loss_coefficient = cls_loss_coefficient
|
| 245 |
+
self.bbox_loss_coefficient = bbox_loss_coefficient
|
| 246 |
+
self.giou_loss_coefficient = giou_loss_coefficient
|
| 247 |
+
self.focal_alpha = focal_alpha
|
| 248 |
+
self.query_dim = query_dim
|
| 249 |
+
self.random_refpoints_xy = random_refpoints_xy
|
| 250 |
+
self.keep_query_pos = keep_query_pos
|
| 251 |
+
self.num_patterns = num_patterns
|
| 252 |
+
self.normalize_before = normalize_before
|
| 253 |
+
self.temperature_width = temperature_width
|
| 254 |
+
self.temperature_height = temperature_height
|
| 255 |
+
self.sine_position_embedding_scale = sine_position_embedding_scale
|
| 256 |
+
self.initializer_bias_prior_prob = initializer_bias_prior_prob
|
| 257 |
+
super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
__all__ = ["DabDetrConfig"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert DAB-DETR checkpoints."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import gc
|
| 19 |
+
import json
|
| 20 |
+
import re
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from huggingface_hub import hf_hub_download
|
| 25 |
+
|
| 26 |
+
from transformers import ConditionalDetrImageProcessor, DabDetrConfig, DabDetrForObjectDetection
|
| 27 |
+
from transformers.utils import logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logging.set_verbosity_info()
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
ORIGINAL_TO_CONVERTED_KEY_MAPPING = {
|
| 34 |
+
# convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads
|
| 35 |
+
# for dab-DETR, also convert reference point head and query scale MLP
|
| 36 |
+
r"input_proj\.(bias|weight)": r"input_projection.\1",
|
| 37 |
+
r"refpoint_embed\.weight": r"query_refpoint_embeddings.weight",
|
| 38 |
+
r"class_embed\.(bias|weight)": r"class_embed.\1",
|
| 39 |
+
# negative lookbehind because of the overlap
|
| 40 |
+
r"(?<!transformer\.decoder\.)bbox_embed\.layers\.(\d+)\.(bias|weight)": r"bbox_predictor.layers.\1.\2",
|
| 41 |
+
r"transformer\.encoder\.query_scale\.layers\.(\d+)\.(bias|weight)": r"encoder.query_scale.layers.\1.\2",
|
| 42 |
+
r"transformer\.decoder\.bbox_embed\.layers\.(\d+)\.(bias|weight)": r"decoder.bbox_embed.layers.\1.\2",
|
| 43 |
+
r"transformer\.decoder\.norm\.(bias|weight)": r"decoder.layernorm.\1",
|
| 44 |
+
r"transformer\.decoder\.ref_point_head\.layers\.(\d+)\.(bias|weight)": r"decoder.ref_point_head.layers.\1.\2",
|
| 45 |
+
r"transformer\.decoder\.ref_anchor_head\.layers\.(\d+)\.(bias|weight)": r"decoder.ref_anchor_head.layers.\1.\2",
|
| 46 |
+
r"transformer\.decoder\.query_scale\.layers\.(\d+)\.(bias|weight)": r"decoder.query_scale.layers.\1.\2",
|
| 47 |
+
r"transformer\.decoder\.layers\.0\.ca_qpos_proj\.(bias|weight)": r"decoder.layers.0.cross_attn.cross_attn_query_pos_proj.\1",
|
| 48 |
+
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms + activation function
|
| 49 |
+
# output projection
|
| 50 |
+
r"transformer\.encoder\.layers\.(\d+)\.self_attn\.out_proj\.(bias|weight)": r"encoder.layers.\1.self_attn.out_proj.\2",
|
| 51 |
+
# FFN layers
|
| 52 |
+
r"transformer\.encoder\.layers\.(\d+)\.linear(\d)\.(bias|weight)": r"encoder.layers.\1.fc\2.\3",
|
| 53 |
+
# normalization layers
|
| 54 |
+
# nm1
|
| 55 |
+
r"transformer\.encoder\.layers\.(\d+)\.norm1\.(bias|weight)": r"encoder.layers.\1.self_attn_layer_norm.\2",
|
| 56 |
+
# nm2
|
| 57 |
+
r"transformer\.encoder\.layers\.(\d+)\.norm2\.(bias|weight)": r"encoder.layers.\1.final_layer_norm.\2",
|
| 58 |
+
# activation function weight
|
| 59 |
+
r"transformer\.encoder\.layers\.(\d+)\.activation\.weight": r"encoder.layers.\1.activation_fn.weight",
|
| 60 |
+
#########################################################################################################################################
|
| 61 |
+
# decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms + activiation function weight
|
| 62 |
+
r"transformer\.decoder\.layers\.(\d+)\.self_attn\.out_proj\.(bias|weight)": r"decoder.layers.\1.self_attn.self_attn.output_proj.\2",
|
| 63 |
+
r"transformer\.decoder\.layers\.(\d+)\.cross_attn\.out_proj\.(bias|weight)": r"decoder.layers.\1.cross_attn.cross_attn.output_proj.\2",
|
| 64 |
+
# FFNs
|
| 65 |
+
r"transformer\.decoder\.layers\.(\d+)\.linear(\d)\.(bias|weight)": r"decoder.layers.\1.mlp.fc\2.\3",
|
| 66 |
+
# nm1
|
| 67 |
+
r"transformer\.decoder\.layers\.(\d+)\.norm1\.(bias|weight)": r"decoder.layers.\1.self_attn.self_attn_layer_norm.\2",
|
| 68 |
+
# nm2
|
| 69 |
+
r"transformer\.decoder\.layers\.(\d+)\.norm2\.(bias|weight)": r"decoder.layers.\1.cross_attn.cross_attn_layer_norm.\2",
|
| 70 |
+
# nm3
|
| 71 |
+
r"transformer\.decoder\.layers\.(\d+)\.norm3\.(bias|weight)": r"decoder.layers.\1.mlp.final_layer_norm.\2",
|
| 72 |
+
# activation function weight
|
| 73 |
+
r"transformer\.decoder\.layers\.(\d+)\.activation\.weight": r"decoder.layers.\1.mlp.activation_fn.weight",
|
| 74 |
+
# q, k, v projections and biases in self-attention in decoder
|
| 75 |
+
r"transformer\.decoder\.layers\.(\d+)\.sa_qcontent_proj\.(bias|weight)": r"decoder.layers.\1.self_attn.self_attn_query_content_proj.\2",
|
| 76 |
+
r"transformer\.decoder\.layers\.(\d+)\.sa_kcontent_proj\.(bias|weight)": r"decoder.layers.\1.self_attn.self_attn_key_content_proj.\2",
|
| 77 |
+
r"transformer\.decoder\.layers\.(\d+)\.sa_qpos_proj\.(bias|weight)": r"decoder.layers.\1.self_attn.self_attn_query_pos_proj.\2",
|
| 78 |
+
r"transformer\.decoder\.layers\.(\d+)\.sa_kpos_proj\.(bias|weight)": r"decoder.layers.\1.self_attn.self_attn_key_pos_proj.\2",
|
| 79 |
+
r"transformer\.decoder\.layers\.(\d+)\.sa_v_proj\.(bias|weight)": r"decoder.layers.\1.self_attn.self_attn_value_proj.\2",
|
| 80 |
+
# q, k, v projections in cross-attention in decoder
|
| 81 |
+
r"transformer\.decoder\.layers\.(\d+)\.ca_qcontent_proj\.(bias|weight)": r"decoder.layers.\1.cross_attn.cross_attn_query_content_proj.\2",
|
| 82 |
+
r"transformer\.decoder\.layers\.(\d+)\.ca_kcontent_proj\.(bias|weight)": r"decoder.layers.\1.cross_attn.cross_attn_key_content_proj.\2",
|
| 83 |
+
r"transformer\.decoder\.layers\.(\d+)\.ca_kpos_proj\.(bias|weight)": r"decoder.layers.\1.cross_attn.cross_attn_key_pos_proj.\2",
|
| 84 |
+
r"transformer\.decoder\.layers\.(\d+)\.ca_v_proj\.(bias|weight)": r"decoder.layers.\1.cross_attn.cross_attn_value_proj.\2",
|
| 85 |
+
r"transformer\.decoder\.layers\.(\d+)\.ca_qpos_sine_proj\.(bias|weight)": r"decoder.layers.\1.cross_attn.cross_attn_query_pos_sine_proj.\2",
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Copied from transformers.models.mllama.convert_mllama_weights_to_hf.convert_old_keys_to_new_keys
|
| 90 |
+
def convert_old_keys_to_new_keys(state_dict_keys: dict = None):
|
| 91 |
+
"""
|
| 92 |
+
This function should be applied only once, on the concatenated keys to efficiently rename using
|
| 93 |
+
the key mappings.
|
| 94 |
+
"""
|
| 95 |
+
output_dict = {}
|
| 96 |
+
if state_dict_keys is not None:
|
| 97 |
+
old_text = "\n".join(state_dict_keys)
|
| 98 |
+
new_text = old_text
|
| 99 |
+
for pattern, replacement in ORIGINAL_TO_CONVERTED_KEY_MAPPING.items():
|
| 100 |
+
if replacement is None:
|
| 101 |
+
new_text = re.sub(pattern, "", new_text) # an empty line
|
| 102 |
+
continue
|
| 103 |
+
new_text = re.sub(pattern, replacement, new_text)
|
| 104 |
+
output_dict = dict(zip(old_text.split("\n"), new_text.split("\n")))
|
| 105 |
+
return output_dict
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def write_image_processor(model_name, pytorch_dump_folder_path, push_to_hub):
|
| 109 |
+
logger.info("Converting image processor...")
|
| 110 |
+
format = "coco_detection"
|
| 111 |
+
image_processor = ConditionalDetrImageProcessor(format=format)
|
| 112 |
+
Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
|
| 113 |
+
image_processor.save_pretrained(pytorch_dump_folder_path)
|
| 114 |
+
|
| 115 |
+
if push_to_hub:
|
| 116 |
+
image_processor.push_to_hub(repo_id=model_name, commit_message="Add new image processor")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@torch.no_grad()
|
| 120 |
+
def write_model(model_name, pretrained_model_weights_path, pytorch_dump_folder_path, push_to_hub):
|
| 121 |
+
# load modified config. Why? After loading the default config, the backbone kwargs are already set.
|
| 122 |
+
if "dc5" in model_name:
|
| 123 |
+
config = DabDetrConfig(dilation=True)
|
| 124 |
+
else:
|
| 125 |
+
# load default config
|
| 126 |
+
config = DabDetrConfig()
|
| 127 |
+
# set other attributes
|
| 128 |
+
if "dab-detr-resnet-50-dc5" == model_name:
|
| 129 |
+
config.temperature_height = 10
|
| 130 |
+
config.temperature_width = 10
|
| 131 |
+
if "fixxy" in model_name:
|
| 132 |
+
config.random_refpoints_xy = True
|
| 133 |
+
if "pat3" in model_name:
|
| 134 |
+
config.num_patterns = 3
|
| 135 |
+
# only when the number of patterns (num_patterns parameter in config) are more than 0 like r50-pat3 or r50dc5-pat3
|
| 136 |
+
ORIGINAL_TO_CONVERTED_KEY_MAPPING.update({r"transformer.patterns.weight": r"patterns.weight"})
|
| 137 |
+
|
| 138 |
+
config.num_labels = 91
|
| 139 |
+
repo_id = "huggingface/label-files"
|
| 140 |
+
filename = "coco-detection-id2label.json"
|
| 141 |
+
id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
|
| 142 |
+
id2label = {int(k): v for k, v in id2label.items()}
|
| 143 |
+
config.id2label = id2label
|
| 144 |
+
config.label2id = {v: k for k, v in id2label.items()}
|
| 145 |
+
# load original model from local path
|
| 146 |
+
loaded = torch.load(pretrained_model_weights_path, map_location=torch.device("cpu"))["model"]
|
| 147 |
+
# Renaming the original model state dictionary to HF compatibile
|
| 148 |
+
all_keys = list(loaded.keys())
|
| 149 |
+
new_keys = convert_old_keys_to_new_keys(all_keys)
|
| 150 |
+
state_dict = {}
|
| 151 |
+
for key in all_keys:
|
| 152 |
+
if "backbone.0.body" in key:
|
| 153 |
+
new_key = key.replace("backbone.0.body", "backbone.conv_encoder.model._backbone")
|
| 154 |
+
state_dict[new_key] = loaded[key]
|
| 155 |
+
# Q, K, V encoder values mapping
|
| 156 |
+
elif re.search("self_attn.in_proj_(weight|bias)", key):
|
| 157 |
+
# Dynamically find the layer number
|
| 158 |
+
pattern = r"layers\.(\d+)\.self_attn\.in_proj_(weight|bias)"
|
| 159 |
+
match = re.search(pattern, key)
|
| 160 |
+
if match:
|
| 161 |
+
layer_num = match.group(1)
|
| 162 |
+
else:
|
| 163 |
+
raise ValueError(f"Pattern not found in key: {key}")
|
| 164 |
+
|
| 165 |
+
in_proj_value = loaded.pop(key)
|
| 166 |
+
if "weight" in key:
|
| 167 |
+
state_dict[f"encoder.layers.{layer_num}.self_attn.q_proj.weight"] = in_proj_value[:256, :]
|
| 168 |
+
state_dict[f"encoder.layers.{layer_num}.self_attn.k_proj.weight"] = in_proj_value[256:512, :]
|
| 169 |
+
state_dict[f"encoder.layers.{layer_num}.self_attn.v_proj.weight"] = in_proj_value[-256:, :]
|
| 170 |
+
elif "bias" in key:
|
| 171 |
+
state_dict[f"encoder.layers.{layer_num}.self_attn.q_proj.bias"] = in_proj_value[:256]
|
| 172 |
+
state_dict[f"encoder.layers.{layer_num}.self_attn.k_proj.bias"] = in_proj_value[256:512]
|
| 173 |
+
state_dict[f"encoder.layers.{layer_num}.self_attn.v_proj.bias"] = in_proj_value[-256:]
|
| 174 |
+
else:
|
| 175 |
+
new_key = new_keys[key]
|
| 176 |
+
state_dict[new_key] = loaded[key]
|
| 177 |
+
|
| 178 |
+
del loaded
|
| 179 |
+
gc.collect()
|
| 180 |
+
# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
|
| 181 |
+
prefix = "model."
|
| 182 |
+
for key in state_dict.copy().keys():
|
| 183 |
+
if not key.startswith("class_embed") and not key.startswith("bbox_predictor"):
|
| 184 |
+
val = state_dict.pop(key)
|
| 185 |
+
state_dict[prefix + key] = val
|
| 186 |
+
# finally, create HuggingFace model and load state dict
|
| 187 |
+
model = DabDetrForObjectDetection(config)
|
| 188 |
+
model.load_state_dict(state_dict)
|
| 189 |
+
model.eval()
|
| 190 |
+
logger.info(f"Saving PyTorch model to {pytorch_dump_folder_path}...")
|
| 191 |
+
Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
|
| 192 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 193 |
+
|
| 194 |
+
if push_to_hub:
|
| 195 |
+
model.push_to_hub(repo_id=model_name, commit_message="Add new model")
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def convert_dab_detr_checkpoint(model_name, pretrained_model_weights_path, pytorch_dump_folder_path, push_to_hub):
|
| 199 |
+
logger.info("Converting image processor...")
|
| 200 |
+
write_image_processor(model_name, pytorch_dump_folder_path, push_to_hub)
|
| 201 |
+
|
| 202 |
+
logger.info(f"Converting model {model_name}...")
|
| 203 |
+
write_model(model_name, pretrained_model_weights_path, pytorch_dump_folder_path, push_to_hub)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
if __name__ == "__main__":
|
| 207 |
+
parser = argparse.ArgumentParser()
|
| 208 |
+
|
| 209 |
+
parser.add_argument(
|
| 210 |
+
"--model_name",
|
| 211 |
+
default="dab-detr-resnet-50",
|
| 212 |
+
type=str,
|
| 213 |
+
help="Name of the DAB_DETR model you'd like to convert.",
|
| 214 |
+
)
|
| 215 |
+
parser.add_argument(
|
| 216 |
+
"--pretrained_model_weights_path",
|
| 217 |
+
default="modelzoo/R50/checkpoint.pth",
|
| 218 |
+
type=str,
|
| 219 |
+
help="The path of the original model weights like: modelzoo/checkpoint.pth",
|
| 220 |
+
)
|
| 221 |
+
parser.add_argument(
|
| 222 |
+
"--pytorch_dump_folder_path", default="DAB_DETR", type=str, help="Path to the folder to output PyTorch model."
|
| 223 |
+
)
|
| 224 |
+
parser.add_argument(
|
| 225 |
+
"--push_to_hub",
|
| 226 |
+
default=True,
|
| 227 |
+
type=bool,
|
| 228 |
+
help="Whether to upload the converted weights and image processor config to the HuggingFace model profile. Default is set to false.",
|
| 229 |
+
)
|
| 230 |
+
args = parser.parse_args()
|
| 231 |
+
convert_dab_detr_checkpoint(
|
| 232 |
+
args.model_name, args.pretrained_model_weights_path, args.pytorch_dump_folder_path, args.push_to_hub
|
| 233 |
+
)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dab_detr/modeling_dab_detr.py
ADDED
|
@@ -0,0 +1,1716 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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# coding=utf-8
|
| 2 |
+
# Copyright 2024 IDEA Research and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch DAB-DETR model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Dict, List, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from torch import Tensor, nn
|
| 23 |
+
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...modeling_attn_mask_utils import _prepare_4d_attention_mask
|
| 26 |
+
from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithCrossAttentions, Seq2SeqModelOutput
|
| 27 |
+
from ...modeling_utils import PreTrainedModel
|
| 28 |
+
from ...utils import (
|
| 29 |
+
ModelOutput,
|
| 30 |
+
add_start_docstrings,
|
| 31 |
+
add_start_docstrings_to_model_forward,
|
| 32 |
+
logging,
|
| 33 |
+
replace_return_docstrings,
|
| 34 |
+
)
|
| 35 |
+
from ...utils.backbone_utils import load_backbone
|
| 36 |
+
from .configuration_dab_detr import DabDetrConfig
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
_CONFIG_FOR_DOC = "DabDetrConfig"
|
| 42 |
+
_CHECKPOINT_FOR_DOC = "IDEA-Research/dab_detr-base"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass
|
| 46 |
+
# Copied from transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrDecoderOutput with ConditionalDetr->DabDetr,Conditional DETR->DAB-DETR,2 (anchor points)->4 (anchor points)
|
| 47 |
+
class DabDetrDecoderOutput(BaseModelOutputWithCrossAttentions):
|
| 48 |
+
"""
|
| 49 |
+
Base class for outputs of the Conditional DETR decoder. This class adds one attribute to
|
| 50 |
+
BaseModelOutputWithCrossAttentions, namely an optional stack of intermediate decoder activations, i.e. the output
|
| 51 |
+
of each decoder layer, each of them gone through a layernorm. This is useful when training the model with auxiliary
|
| 52 |
+
decoding losses.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 56 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 57 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 58 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 59 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 60 |
+
plus the initial embedding outputs.
|
| 61 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 62 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 63 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 64 |
+
the self-attention heads.
|
| 65 |
+
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
|
| 66 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 67 |
+
sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
|
| 68 |
+
used to compute the weighted average in the cross-attention heads.
|
| 69 |
+
intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
|
| 70 |
+
Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
|
| 71 |
+
layernorm.
|
| 72 |
+
reference_points (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))`):
|
| 73 |
+
Reference points (reference points of each layer of the decoder).
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
intermediate_hidden_states: Optional[torch.FloatTensor] = None
|
| 77 |
+
reference_points: Optional[Tuple[torch.FloatTensor]] = None
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass
|
| 81 |
+
# Copied from transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrModelOutput with ConditionalDetr->DabDetr,Conditional DETR->DAB-DETR,2 (anchor points)->4 (anchor points)
|
| 82 |
+
class DabDetrModelOutput(Seq2SeqModelOutput):
|
| 83 |
+
"""
|
| 84 |
+
Base class for outputs of the Conditional DETR encoder-decoder model. This class adds one attribute to
|
| 85 |
+
Seq2SeqModelOutput, namely an optional stack of intermediate decoder activations, i.e. the output of each decoder
|
| 86 |
+
layer, each of them gone through a layernorm. This is useful when training the model with auxiliary decoding
|
| 87 |
+
losses.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 91 |
+
Sequence of hidden-states at the output of the last layer of the decoder of the model.
|
| 92 |
+
decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 93 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 94 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of each
|
| 95 |
+
layer plus the initial embedding outputs.
|
| 96 |
+
decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 97 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 98 |
+
sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to compute the
|
| 99 |
+
weighted average in the self-attention heads.
|
| 100 |
+
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 101 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 102 |
+
sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
|
| 103 |
+
used to compute the weighted average in the cross-attention heads.
|
| 104 |
+
encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 105 |
+
Sequence of hidden-states at the output of the last layer of the encoder of the model.
|
| 106 |
+
encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 107 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 108 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each
|
| 109 |
+
layer plus the initial embedding outputs.
|
| 110 |
+
encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 111 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 112 |
+
sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the
|
| 113 |
+
weighted average in the self-attention heads.
|
| 114 |
+
intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, sequence_length, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
|
| 115 |
+
Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
|
| 116 |
+
layernorm.
|
| 117 |
+
reference_points (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))`):
|
| 118 |
+
Reference points (reference points of each layer of the decoder).
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
intermediate_hidden_states: Optional[torch.FloatTensor] = None
|
| 122 |
+
reference_points: Optional[Tuple[torch.FloatTensor]] = None
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@dataclass
|
| 126 |
+
# Copied from transformers.models.detr.modeling_detr.DetrObjectDetectionOutput with Detr->DabDetr
|
| 127 |
+
class DabDetrObjectDetectionOutput(ModelOutput):
|
| 128 |
+
"""
|
| 129 |
+
Output type of [`DabDetrForObjectDetection`].
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
|
| 133 |
+
Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
|
| 134 |
+
bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
|
| 135 |
+
scale-invariant IoU loss.
|
| 136 |
+
loss_dict (`Dict`, *optional*):
|
| 137 |
+
A dictionary containing the individual losses. Useful for logging.
|
| 138 |
+
logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
|
| 139 |
+
Classification logits (including no-object) for all queries.
|
| 140 |
+
pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
|
| 141 |
+
Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
|
| 142 |
+
values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
|
| 143 |
+
possible padding). You can use [`~DabDetrImageProcessor.post_process_object_detection`] to retrieve the
|
| 144 |
+
unnormalized bounding boxes.
|
| 145 |
+
auxiliary_outputs (`list[Dict]`, *optional*):
|
| 146 |
+
Optional, only returned when auxilary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
|
| 147 |
+
and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
|
| 148 |
+
`pred_boxes`) for each decoder layer.
|
| 149 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 150 |
+
Sequence of hidden-states at the output of the last layer of the decoder of the model.
|
| 151 |
+
decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 152 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 153 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of each
|
| 154 |
+
layer plus the initial embedding outputs.
|
| 155 |
+
decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 156 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 157 |
+
sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to compute the
|
| 158 |
+
weighted average in the self-attention heads.
|
| 159 |
+
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 160 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 161 |
+
sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
|
| 162 |
+
used to compute the weighted average in the cross-attention heads.
|
| 163 |
+
encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 164 |
+
Sequence of hidden-states at the output of the last layer of the encoder of the model.
|
| 165 |
+
encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 166 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 167 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each
|
| 168 |
+
layer plus the initial embedding outputs.
|
| 169 |
+
encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 170 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 171 |
+
sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the
|
| 172 |
+
weighted average in the self-attention heads.
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
loss: Optional[torch.FloatTensor] = None
|
| 176 |
+
loss_dict: Optional[Dict] = None
|
| 177 |
+
logits: torch.FloatTensor = None
|
| 178 |
+
pred_boxes: torch.FloatTensor = None
|
| 179 |
+
auxiliary_outputs: Optional[List[Dict]] = None
|
| 180 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 181 |
+
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 182 |
+
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 183 |
+
cross_attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 184 |
+
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
|
| 185 |
+
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 186 |
+
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# Copied from transformers.models.detr.modeling_detr.DetrFrozenBatchNorm2d with Detr->DabDetr
|
| 190 |
+
class DabDetrFrozenBatchNorm2d(nn.Module):
|
| 191 |
+
"""
|
| 192 |
+
BatchNorm2d where the batch statistics and the affine parameters are fixed.
|
| 193 |
+
|
| 194 |
+
Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
|
| 195 |
+
torchvision.models.resnet[18,34,50,101] produce nans.
|
| 196 |
+
"""
|
| 197 |
+
|
| 198 |
+
def __init__(self, n):
|
| 199 |
+
super().__init__()
|
| 200 |
+
self.register_buffer("weight", torch.ones(n))
|
| 201 |
+
self.register_buffer("bias", torch.zeros(n))
|
| 202 |
+
self.register_buffer("running_mean", torch.zeros(n))
|
| 203 |
+
self.register_buffer("running_var", torch.ones(n))
|
| 204 |
+
|
| 205 |
+
def _load_from_state_dict(
|
| 206 |
+
self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
|
| 207 |
+
):
|
| 208 |
+
num_batches_tracked_key = prefix + "num_batches_tracked"
|
| 209 |
+
if num_batches_tracked_key in state_dict:
|
| 210 |
+
del state_dict[num_batches_tracked_key]
|
| 211 |
+
|
| 212 |
+
super()._load_from_state_dict(
|
| 213 |
+
state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
def forward(self, x):
|
| 217 |
+
# move reshapes to the beginning
|
| 218 |
+
# to make it user-friendly
|
| 219 |
+
weight = self.weight.reshape(1, -1, 1, 1)
|
| 220 |
+
bias = self.bias.reshape(1, -1, 1, 1)
|
| 221 |
+
running_var = self.running_var.reshape(1, -1, 1, 1)
|
| 222 |
+
running_mean = self.running_mean.reshape(1, -1, 1, 1)
|
| 223 |
+
epsilon = 1e-5
|
| 224 |
+
scale = weight * (running_var + epsilon).rsqrt()
|
| 225 |
+
bias = bias - running_mean * scale
|
| 226 |
+
return x * scale + bias
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
# Copied from transformers.models.detr.modeling_detr.replace_batch_norm with Detr->DabDetr
|
| 230 |
+
def replace_batch_norm(model):
|
| 231 |
+
r"""
|
| 232 |
+
Recursively replace all `torch.nn.BatchNorm2d` with `DabDetrFrozenBatchNorm2d`.
|
| 233 |
+
|
| 234 |
+
Args:
|
| 235 |
+
model (torch.nn.Module):
|
| 236 |
+
input model
|
| 237 |
+
"""
|
| 238 |
+
for name, module in model.named_children():
|
| 239 |
+
if isinstance(module, nn.BatchNorm2d):
|
| 240 |
+
new_module = DabDetrFrozenBatchNorm2d(module.num_features)
|
| 241 |
+
|
| 242 |
+
if not module.weight.device == torch.device("meta"):
|
| 243 |
+
new_module.weight.data.copy_(module.weight)
|
| 244 |
+
new_module.bias.data.copy_(module.bias)
|
| 245 |
+
new_module.running_mean.data.copy_(module.running_mean)
|
| 246 |
+
new_module.running_var.data.copy_(module.running_var)
|
| 247 |
+
|
| 248 |
+
model._modules[name] = new_module
|
| 249 |
+
|
| 250 |
+
if len(list(module.children())) > 0:
|
| 251 |
+
replace_batch_norm(module)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
# Modified from transformers.models.detr.modeling_detr.DetrConvEncoder with Detr->DabDetr
|
| 255 |
+
class DabDetrConvEncoder(nn.Module):
|
| 256 |
+
"""
|
| 257 |
+
Convolutional backbone, using either the AutoBackbone API or one from the timm library.
|
| 258 |
+
|
| 259 |
+
nn.BatchNorm2d layers are replaced by DabDetrFrozenBatchNorm2d as defined above.
|
| 260 |
+
|
| 261 |
+
"""
|
| 262 |
+
|
| 263 |
+
def __init__(self, config: DabDetrConfig):
|
| 264 |
+
super().__init__()
|
| 265 |
+
|
| 266 |
+
self.config = config
|
| 267 |
+
backbone = load_backbone(config)
|
| 268 |
+
|
| 269 |
+
# replace batch norm by frozen batch norm
|
| 270 |
+
with torch.no_grad():
|
| 271 |
+
replace_batch_norm(backbone)
|
| 272 |
+
self.model = backbone
|
| 273 |
+
self.intermediate_channel_sizes = self.model.channels
|
| 274 |
+
|
| 275 |
+
def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):
|
| 276 |
+
# send pixel_values through the model to get list of feature maps
|
| 277 |
+
features = self.model(pixel_values).feature_maps
|
| 278 |
+
|
| 279 |
+
out = []
|
| 280 |
+
for feature_map in features:
|
| 281 |
+
# downsample pixel_mask to match shape of corresponding feature_map
|
| 282 |
+
mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]
|
| 283 |
+
out.append((feature_map, mask))
|
| 284 |
+
return out
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
# Copied from transformers.models.detr.modeling_detr.DetrConvModel with Detr->DabDetr
|
| 288 |
+
class DabDetrConvModel(nn.Module):
|
| 289 |
+
"""
|
| 290 |
+
This module adds 2D position embeddings to all intermediate feature maps of the convolutional encoder.
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
def __init__(self, conv_encoder, position_embedding):
|
| 294 |
+
super().__init__()
|
| 295 |
+
self.conv_encoder = conv_encoder
|
| 296 |
+
self.position_embedding = position_embedding
|
| 297 |
+
|
| 298 |
+
def forward(self, pixel_values, pixel_mask):
|
| 299 |
+
# send pixel_values and pixel_mask through backbone to get list of (feature_map, pixel_mask) tuples
|
| 300 |
+
out = self.conv_encoder(pixel_values, pixel_mask)
|
| 301 |
+
pos = []
|
| 302 |
+
for feature_map, mask in out:
|
| 303 |
+
# position encoding
|
| 304 |
+
pos.append(self.position_embedding(feature_map, mask).to(feature_map.dtype))
|
| 305 |
+
|
| 306 |
+
return out, pos
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
# Modified from transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrSinePositionEmbedding with ConditionalDetr->DabDetr
|
| 310 |
+
class DabDetrSinePositionEmbedding(nn.Module):
|
| 311 |
+
"""
|
| 312 |
+
This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
|
| 313 |
+
need paper, generalized to work on images.
|
| 314 |
+
"""
|
| 315 |
+
|
| 316 |
+
def __init__(self, config: DabDetrConfig):
|
| 317 |
+
super().__init__()
|
| 318 |
+
self.config = config
|
| 319 |
+
self.embedding_dim = config.hidden_size / 2
|
| 320 |
+
self.temperature_height = config.temperature_height
|
| 321 |
+
self.temperature_width = config.temperature_width
|
| 322 |
+
scale = config.sine_position_embedding_scale
|
| 323 |
+
if scale is None:
|
| 324 |
+
scale = 2 * math.pi
|
| 325 |
+
self.scale = scale
|
| 326 |
+
|
| 327 |
+
def forward(self, pixel_values, pixel_mask):
|
| 328 |
+
if pixel_mask is None:
|
| 329 |
+
raise ValueError("No pixel mask provided")
|
| 330 |
+
y_embed = pixel_mask.cumsum(1, dtype=torch.float32)
|
| 331 |
+
x_embed = pixel_mask.cumsum(2, dtype=torch.float32)
|
| 332 |
+
y_embed = y_embed / (y_embed[:, -1:, :] + 1e-6) * self.scale
|
| 333 |
+
x_embed = x_embed / (x_embed[:, :, -1:] + 1e-6) * self.scale
|
| 334 |
+
|
| 335 |
+
# We use float32 to ensure reproducibility of the original implementation
|
| 336 |
+
dim_tx = torch.arange(self.embedding_dim, dtype=torch.float32, device=pixel_values.device)
|
| 337 |
+
# Modifying dim_tx in place to avoid extra memory allocation -> dim_tx = self.temperature_width ** (2 * (dim_tx // 2) / self.embedding_dim)
|
| 338 |
+
dim_tx //= 2
|
| 339 |
+
dim_tx.mul_(2 / self.embedding_dim)
|
| 340 |
+
dim_tx.copy_(self.temperature_width**dim_tx)
|
| 341 |
+
pos_x = x_embed[:, :, :, None] / dim_tx
|
| 342 |
+
|
| 343 |
+
# We use float32 to ensure reproducibility of the original implementation
|
| 344 |
+
dim_ty = torch.arange(self.embedding_dim, dtype=torch.float32, device=pixel_values.device)
|
| 345 |
+
# Modifying dim_ty in place to avoid extra memory allocation -> dim_ty = self.temperature_height ** (2 * (dim_ty // 2) / self.embedding_dim)
|
| 346 |
+
dim_ty //= 2
|
| 347 |
+
dim_ty.mul_(2 / self.embedding_dim)
|
| 348 |
+
dim_ty.copy_(self.temperature_height**dim_ty)
|
| 349 |
+
pos_y = y_embed[:, :, :, None] / dim_ty
|
| 350 |
+
|
| 351 |
+
pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
|
| 352 |
+
pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
|
| 353 |
+
pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
|
| 354 |
+
return pos
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
# function to generate sine positional embedding for 4d coordinates
|
| 358 |
+
def gen_sine_position_embeddings(pos_tensor, hidden_size=256):
|
| 359 |
+
"""
|
| 360 |
+
This function computes position embeddings using sine and cosine functions from the input positional tensor,
|
| 361 |
+
which has a shape of (batch_size, num_queries, 4).
|
| 362 |
+
The last dimension of `pos_tensor` represents the following coordinates:
|
| 363 |
+
- 0: x-coord
|
| 364 |
+
- 1: y-coord
|
| 365 |
+
- 2: width
|
| 366 |
+
- 3: height
|
| 367 |
+
|
| 368 |
+
The output shape is (batch_size, num_queries, 512), where final dim (hidden_size*2 = 512) is the total embedding dimension
|
| 369 |
+
achieved by concatenating the sine and cosine values for each coordinate.
|
| 370 |
+
"""
|
| 371 |
+
scale = 2 * math.pi
|
| 372 |
+
dim = hidden_size // 2
|
| 373 |
+
dim_t = torch.arange(dim, dtype=torch.float32, device=pos_tensor.device)
|
| 374 |
+
dim_t = 10000 ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / dim)
|
| 375 |
+
x_embed = pos_tensor[:, :, 0] * scale
|
| 376 |
+
y_embed = pos_tensor[:, :, 1] * scale
|
| 377 |
+
pos_x = x_embed[:, :, None] / dim_t
|
| 378 |
+
pos_y = y_embed[:, :, None] / dim_t
|
| 379 |
+
pos_x = torch.stack((pos_x[:, :, 0::2].sin(), pos_x[:, :, 1::2].cos()), dim=3).flatten(2)
|
| 380 |
+
pos_y = torch.stack((pos_y[:, :, 0::2].sin(), pos_y[:, :, 1::2].cos()), dim=3).flatten(2)
|
| 381 |
+
if pos_tensor.size(-1) == 4:
|
| 382 |
+
w_embed = pos_tensor[:, :, 2] * scale
|
| 383 |
+
pos_w = w_embed[:, :, None] / dim_t
|
| 384 |
+
pos_w = torch.stack((pos_w[:, :, 0::2].sin(), pos_w[:, :, 1::2].cos()), dim=3).flatten(2)
|
| 385 |
+
|
| 386 |
+
h_embed = pos_tensor[:, :, 3] * scale
|
| 387 |
+
pos_h = h_embed[:, :, None] / dim_t
|
| 388 |
+
pos_h = torch.stack((pos_h[:, :, 0::2].sin(), pos_h[:, :, 1::2].cos()), dim=3).flatten(2)
|
| 389 |
+
|
| 390 |
+
pos = torch.cat((pos_y, pos_x, pos_w, pos_h), dim=2)
|
| 391 |
+
else:
|
| 392 |
+
raise ValueError("Unknown pos_tensor shape(-1):{}".format(pos_tensor.size(-1)))
|
| 393 |
+
return pos
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def inverse_sigmoid(x, eps=1e-5):
|
| 397 |
+
x = x.clamp(min=0, max=1)
|
| 398 |
+
x1 = x.clamp(min=eps)
|
| 399 |
+
x2 = (1 - x).clamp(min=eps)
|
| 400 |
+
return torch.log(x1 / x2)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
# Modified from transformers.models.detr.modeling_detr.DetrAttention
|
| 404 |
+
class DetrAttention(nn.Module):
|
| 405 |
+
"""
|
| 406 |
+
Multi-headed attention from 'Attention Is All You Need' paper.
|
| 407 |
+
|
| 408 |
+
Here, we add position embeddings to the queries and keys (as explained in the DETR paper).
|
| 409 |
+
"""
|
| 410 |
+
|
| 411 |
+
def __init__(
|
| 412 |
+
self,
|
| 413 |
+
config: DabDetrConfig,
|
| 414 |
+
bias: bool = True,
|
| 415 |
+
):
|
| 416 |
+
super().__init__()
|
| 417 |
+
self.config = config
|
| 418 |
+
self.hidden_size = config.hidden_size
|
| 419 |
+
self.num_heads = config.encoder_attention_heads
|
| 420 |
+
self.attention_dropout = config.attention_dropout
|
| 421 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 422 |
+
if self.head_dim * self.num_heads != self.hidden_size:
|
| 423 |
+
raise ValueError(
|
| 424 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
|
| 425 |
+
f" {self.num_heads})."
|
| 426 |
+
)
|
| 427 |
+
self.scaling = self.head_dim**-0.5
|
| 428 |
+
self.k_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=bias)
|
| 429 |
+
self.v_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=bias)
|
| 430 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=bias)
|
| 431 |
+
self.out_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=bias)
|
| 432 |
+
|
| 433 |
+
def forward(
|
| 434 |
+
self,
|
| 435 |
+
hidden_states: torch.Tensor,
|
| 436 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 437 |
+
object_queries: Optional[torch.Tensor] = None,
|
| 438 |
+
key_value_states: Optional[torch.Tensor] = None,
|
| 439 |
+
output_attentions: bool = False,
|
| 440 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 441 |
+
"""Input shape: Batch x Time x Channel"""
|
| 442 |
+
batch_size, q_len, embed_dim = hidden_states.size()
|
| 443 |
+
# add position embeddings to the hidden states before projecting to queries and keys
|
| 444 |
+
if object_queries is not None:
|
| 445 |
+
hidden_states_original = hidden_states
|
| 446 |
+
hidden_states = hidden_states + object_queries
|
| 447 |
+
|
| 448 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 449 |
+
key_states = self.k_proj(hidden_states)
|
| 450 |
+
value_states = self.v_proj(hidden_states_original)
|
| 451 |
+
|
| 452 |
+
query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 453 |
+
key_states = key_states.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
|
| 454 |
+
value_states = value_states.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
|
| 455 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3))
|
| 456 |
+
|
| 457 |
+
if attention_mask is not None:
|
| 458 |
+
attn_weights = attn_weights + attention_mask
|
| 459 |
+
|
| 460 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 461 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
| 462 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 463 |
+
|
| 464 |
+
if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
|
| 465 |
+
raise ValueError(
|
| 466 |
+
f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
|
| 467 |
+
f" {attn_output.size()}"
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 471 |
+
|
| 472 |
+
attn_output = attn_output.reshape(batch_size, q_len, embed_dim)
|
| 473 |
+
attn_output = self.out_proj(attn_output)
|
| 474 |
+
|
| 475 |
+
if not output_attentions:
|
| 476 |
+
attn_weights = None
|
| 477 |
+
|
| 478 |
+
return attn_output, attn_weights
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
# Modified from transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrAttention with ConditionalDetr->DABDETR,Conditional DETR->DabDetr
|
| 482 |
+
class DabDetrAttention(nn.Module):
|
| 483 |
+
"""
|
| 484 |
+
Cross-Attention used in DAB-DETR 'DAB-DETR for Fast Training Convergence' paper.
|
| 485 |
+
|
| 486 |
+
The key q_proj, k_proj, v_proj are defined outside the attention. This attention allows the dim of q, k to be
|
| 487 |
+
different to v.
|
| 488 |
+
"""
|
| 489 |
+
|
| 490 |
+
def __init__(self, config: DabDetrConfig, bias: bool = True, is_cross: bool = False):
|
| 491 |
+
super().__init__()
|
| 492 |
+
self.config = config
|
| 493 |
+
self.embed_dim = config.hidden_size * 2 if is_cross else config.hidden_size
|
| 494 |
+
self.output_dim = config.hidden_size
|
| 495 |
+
self.attention_heads = config.decoder_attention_heads
|
| 496 |
+
self.attention_dropout = config.attention_dropout
|
| 497 |
+
self.attention_head_dim = self.embed_dim // self.attention_heads
|
| 498 |
+
if self.attention_head_dim * self.attention_heads != self.embed_dim:
|
| 499 |
+
raise ValueError(
|
| 500 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `attention_heads`:"
|
| 501 |
+
f" {self.attention_heads})."
|
| 502 |
+
)
|
| 503 |
+
# head dimension of values
|
| 504 |
+
self.values_head_dim = self.output_dim // self.attention_heads
|
| 505 |
+
if self.values_head_dim * self.attention_heads != self.output_dim:
|
| 506 |
+
raise ValueError(
|
| 507 |
+
f"output_dim must be divisible by attention_heads (got `output_dim`: {self.output_dim} and `attention_heads`: {self.attention_heads})."
|
| 508 |
+
)
|
| 509 |
+
self.scaling = self.attention_head_dim**-0.5
|
| 510 |
+
self.output_proj = nn.Linear(self.output_dim, self.output_dim, bias=bias)
|
| 511 |
+
|
| 512 |
+
def forward(
|
| 513 |
+
self,
|
| 514 |
+
hidden_states: torch.Tensor,
|
| 515 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 516 |
+
key_states: Optional[torch.Tensor] = None,
|
| 517 |
+
value_states: Optional[torch.Tensor] = None,
|
| 518 |
+
output_attentions: Optional[bool] = None,
|
| 519 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 520 |
+
"""Input shape: Batch x Time x Channel"""
|
| 521 |
+
|
| 522 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 523 |
+
|
| 524 |
+
# scaling query and refactor key-, value states
|
| 525 |
+
query_states = hidden_states * self.scaling
|
| 526 |
+
query_states = query_states.view(batch_size, -1, self.attention_heads, self.attention_head_dim).transpose(1, 2)
|
| 527 |
+
key_states = key_states.view(batch_size, -1, self.attention_heads, self.attention_head_dim).transpose(1, 2)
|
| 528 |
+
value_states = value_states.view(batch_size, -1, self.attention_heads, self.values_head_dim).transpose(1, 2)
|
| 529 |
+
|
| 530 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3))
|
| 531 |
+
|
| 532 |
+
if attention_mask is not None:
|
| 533 |
+
attn_weights = attn_weights + attention_mask
|
| 534 |
+
|
| 535 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 536 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
| 537 |
+
attn_output = torch.matmul(attn_probs, value_states)
|
| 538 |
+
|
| 539 |
+
if attn_output.size() != (batch_size, self.attention_heads, q_len, self.values_head_dim):
|
| 540 |
+
raise ValueError(
|
| 541 |
+
f"`attn_output` should be of size {(batch_size, self.attention_heads, q_len, self.values_head_dim)}, but is"
|
| 542 |
+
f" {attn_output.size()}"
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 546 |
+
|
| 547 |
+
attn_output = attn_output.reshape(batch_size, q_len, self.output_dim)
|
| 548 |
+
attn_output = self.output_proj(attn_output)
|
| 549 |
+
|
| 550 |
+
if not output_attentions:
|
| 551 |
+
attn_weights = None
|
| 552 |
+
|
| 553 |
+
return attn_output, attn_weights
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
class DabDetrDecoderLayerSelfAttention(nn.Module):
|
| 557 |
+
def __init__(self, config: DabDetrConfig):
|
| 558 |
+
super().__init__()
|
| 559 |
+
self.dropout = config.dropout
|
| 560 |
+
self.self_attn_query_content_proj = nn.Linear(config.hidden_size, config.hidden_size)
|
| 561 |
+
self.self_attn_query_pos_proj = nn.Linear(config.hidden_size, config.hidden_size)
|
| 562 |
+
self.self_attn_key_content_proj = nn.Linear(config.hidden_size, config.hidden_size)
|
| 563 |
+
self.self_attn_key_pos_proj = nn.Linear(config.hidden_size, config.hidden_size)
|
| 564 |
+
self.self_attn_value_proj = nn.Linear(config.hidden_size, config.hidden_size)
|
| 565 |
+
self.self_attn = DabDetrAttention(config)
|
| 566 |
+
self.self_attn_layer_norm = nn.LayerNorm(config.hidden_size)
|
| 567 |
+
|
| 568 |
+
def forward(
|
| 569 |
+
self,
|
| 570 |
+
hidden_states: torch.Tensor,
|
| 571 |
+
query_position_embeddings: Optional[torch.Tensor] = None,
|
| 572 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 573 |
+
output_attentions: Optional[bool] = None,
|
| 574 |
+
):
|
| 575 |
+
residual = hidden_states
|
| 576 |
+
query_content = self.self_attn_query_content_proj(hidden_states)
|
| 577 |
+
query_pos = self.self_attn_query_pos_proj(query_position_embeddings)
|
| 578 |
+
key_content = self.self_attn_key_content_proj(hidden_states)
|
| 579 |
+
key_pos = self.self_attn_key_pos_proj(query_position_embeddings)
|
| 580 |
+
value = self.self_attn_value_proj(hidden_states)
|
| 581 |
+
|
| 582 |
+
query = query_content + query_pos
|
| 583 |
+
key = key_content + key_pos
|
| 584 |
+
|
| 585 |
+
hidden_states, attn_weights = self.self_attn(
|
| 586 |
+
hidden_states=query,
|
| 587 |
+
attention_mask=attention_mask,
|
| 588 |
+
key_states=key,
|
| 589 |
+
value_states=value,
|
| 590 |
+
output_attentions=True,
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 594 |
+
hidden_states = residual + hidden_states
|
| 595 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 596 |
+
|
| 597 |
+
return hidden_states, attn_weights
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
class DabDetrDecoderLayerCrossAttention(nn.Module):
|
| 601 |
+
def __init__(self, config: DabDetrConfig, is_first: bool = False):
|
| 602 |
+
super().__init__()
|
| 603 |
+
hidden_size = config.hidden_size
|
| 604 |
+
self.cross_attn_query_content_proj = nn.Linear(hidden_size, hidden_size)
|
| 605 |
+
self.cross_attn_query_pos_proj = nn.Linear(hidden_size, hidden_size)
|
| 606 |
+
self.cross_attn_key_content_proj = nn.Linear(hidden_size, hidden_size)
|
| 607 |
+
self.cross_attn_key_pos_proj = nn.Linear(hidden_size, hidden_size)
|
| 608 |
+
self.cross_attn_value_proj = nn.Linear(hidden_size, hidden_size)
|
| 609 |
+
self.cross_attn_query_pos_sine_proj = nn.Linear(hidden_size, hidden_size)
|
| 610 |
+
self.decoder_attention_heads = config.decoder_attention_heads
|
| 611 |
+
self.cross_attn_layer_norm = nn.LayerNorm(hidden_size)
|
| 612 |
+
self.cross_attn = DabDetrAttention(config, is_cross=True)
|
| 613 |
+
|
| 614 |
+
self.keep_query_pos = config.keep_query_pos
|
| 615 |
+
|
| 616 |
+
if not self.keep_query_pos and not is_first:
|
| 617 |
+
self.cross_attn_query_pos_proj = None
|
| 618 |
+
|
| 619 |
+
self.is_first = is_first
|
| 620 |
+
self.dropout = config.dropout
|
| 621 |
+
|
| 622 |
+
def forward(
|
| 623 |
+
self,
|
| 624 |
+
hidden_states: torch.Tensor,
|
| 625 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 626 |
+
query_position_embeddings: Optional[torch.Tensor] = None,
|
| 627 |
+
object_queries: Optional[torch.Tensor] = None,
|
| 628 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 629 |
+
query_sine_embed: Optional[torch.Tensor] = None,
|
| 630 |
+
output_attentions: Optional[bool] = None,
|
| 631 |
+
):
|
| 632 |
+
query_content = self.cross_attn_query_content_proj(hidden_states)
|
| 633 |
+
key_content = self.cross_attn_key_content_proj(encoder_hidden_states)
|
| 634 |
+
value = self.cross_attn_value_proj(encoder_hidden_states)
|
| 635 |
+
|
| 636 |
+
batch_size, num_queries, n_model = query_content.shape
|
| 637 |
+
_, height_width, _ = key_content.shape
|
| 638 |
+
|
| 639 |
+
key_pos = self.cross_attn_key_pos_proj(object_queries)
|
| 640 |
+
|
| 641 |
+
# For the first decoder layer, we add the positional embedding predicted from
|
| 642 |
+
# the object query (the positional embedding) into the original query (key) in DETR.
|
| 643 |
+
if self.is_first or self.keep_query_pos:
|
| 644 |
+
query_pos = self.cross_attn_query_pos_proj(query_position_embeddings)
|
| 645 |
+
query = query_content + query_pos
|
| 646 |
+
key = key_content + key_pos
|
| 647 |
+
else:
|
| 648 |
+
query = query_content
|
| 649 |
+
key = key_content
|
| 650 |
+
|
| 651 |
+
query = query.view(
|
| 652 |
+
batch_size, num_queries, self.decoder_attention_heads, n_model // self.decoder_attention_heads
|
| 653 |
+
)
|
| 654 |
+
query_sine_embed = self.cross_attn_query_pos_sine_proj(query_sine_embed)
|
| 655 |
+
query_sine_embed = query_sine_embed.view(
|
| 656 |
+
batch_size, num_queries, self.decoder_attention_heads, n_model // self.decoder_attention_heads
|
| 657 |
+
)
|
| 658 |
+
query = torch.cat([query, query_sine_embed], dim=3).view(batch_size, num_queries, n_model * 2)
|
| 659 |
+
key = key.view(batch_size, height_width, self.decoder_attention_heads, n_model // self.decoder_attention_heads)
|
| 660 |
+
key_pos = key_pos.view(
|
| 661 |
+
batch_size, height_width, self.decoder_attention_heads, n_model // self.decoder_attention_heads
|
| 662 |
+
)
|
| 663 |
+
key = torch.cat([key, key_pos], dim=3).view(batch_size, height_width, n_model * 2)
|
| 664 |
+
|
| 665 |
+
# Cross-Attention Block
|
| 666 |
+
cross_attn_weights = None
|
| 667 |
+
if encoder_hidden_states is not None:
|
| 668 |
+
residual = hidden_states
|
| 669 |
+
|
| 670 |
+
hidden_states, cross_attn_weights = self.cross_attn(
|
| 671 |
+
hidden_states=query,
|
| 672 |
+
attention_mask=encoder_attention_mask,
|
| 673 |
+
key_states=key,
|
| 674 |
+
value_states=value,
|
| 675 |
+
output_attentions=output_attentions,
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 679 |
+
hidden_states = residual + hidden_states
|
| 680 |
+
hidden_states = self.cross_attn_layer_norm(hidden_states)
|
| 681 |
+
|
| 682 |
+
return hidden_states, cross_attn_weights
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
class DabDetrDecoderLayerFFN(nn.Module):
|
| 686 |
+
def __init__(self, config: DabDetrConfig):
|
| 687 |
+
super().__init__()
|
| 688 |
+
hidden_size = config.hidden_size
|
| 689 |
+
self.final_layer_norm = nn.LayerNorm(hidden_size)
|
| 690 |
+
self.fc1 = nn.Linear(hidden_size, config.decoder_ffn_dim)
|
| 691 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, hidden_size)
|
| 692 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 693 |
+
self.dropout = config.dropout
|
| 694 |
+
self.activation_dropout = config.activation_dropout
|
| 695 |
+
self.keep_query_pos = config.keep_query_pos
|
| 696 |
+
|
| 697 |
+
def forward(self, hidden_states: torch.Tensor):
|
| 698 |
+
residual = hidden_states
|
| 699 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 700 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 701 |
+
hidden_states = self.fc2(hidden_states)
|
| 702 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 703 |
+
hidden_states = residual + hidden_states
|
| 704 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 705 |
+
|
| 706 |
+
return hidden_states
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
# Modified from transformers.models.detr.modeling_detr.DetrEncoderLayer with DetrEncoderLayer->DabDetrEncoderLayer,DetrConfig->DabDetrConfig
|
| 710 |
+
class DabDetrEncoderLayer(nn.Module):
|
| 711 |
+
def __init__(self, config: DabDetrConfig):
|
| 712 |
+
super().__init__()
|
| 713 |
+
self.hidden_size = config.hidden_size
|
| 714 |
+
self.self_attn = DetrAttention(config)
|
| 715 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size)
|
| 716 |
+
self.dropout = config.dropout
|
| 717 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 718 |
+
self.fc1 = nn.Linear(self.hidden_size, config.encoder_ffn_dim)
|
| 719 |
+
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.hidden_size)
|
| 720 |
+
self.final_layer_norm = nn.LayerNorm(self.hidden_size)
|
| 721 |
+
|
| 722 |
+
def forward(
|
| 723 |
+
self,
|
| 724 |
+
hidden_states: torch.Tensor,
|
| 725 |
+
attention_mask: torch.Tensor,
|
| 726 |
+
object_queries: torch.Tensor,
|
| 727 |
+
output_attentions: Optional[bool] = None,
|
| 728 |
+
):
|
| 729 |
+
"""
|
| 730 |
+
Args:
|
| 731 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
|
| 732 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 733 |
+
`(batch, source_len)` where padding elements are indicated by very large negative
|
| 734 |
+
values.
|
| 735 |
+
object_queries (`torch.FloatTensor`, *optional*):
|
| 736 |
+
Object queries (also called content embeddings), to be added to the hidden states.
|
| 737 |
+
output_attentions (`bool`, *optional*):
|
| 738 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 739 |
+
returned tensors for more detail.
|
| 740 |
+
"""
|
| 741 |
+
residual = hidden_states
|
| 742 |
+
hidden_states, attn_weights = self.self_attn(
|
| 743 |
+
hidden_states=hidden_states,
|
| 744 |
+
attention_mask=attention_mask,
|
| 745 |
+
object_queries=object_queries,
|
| 746 |
+
output_attentions=output_attentions,
|
| 747 |
+
)
|
| 748 |
+
|
| 749 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 750 |
+
hidden_states = residual + hidden_states
|
| 751 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 752 |
+
|
| 753 |
+
residual = hidden_states
|
| 754 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 755 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 756 |
+
|
| 757 |
+
hidden_states = self.fc2(hidden_states)
|
| 758 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 759 |
+
|
| 760 |
+
hidden_states = residual + hidden_states
|
| 761 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 762 |
+
|
| 763 |
+
outputs = (hidden_states,)
|
| 764 |
+
|
| 765 |
+
if output_attentions:
|
| 766 |
+
outputs += (attn_weights,)
|
| 767 |
+
|
| 768 |
+
return outputs
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
# Modified from transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrDecoderLayer with ConditionalDetr->DabDetr
|
| 772 |
+
class DabDetrDecoderLayer(nn.Module):
|
| 773 |
+
def __init__(self, config: DabDetrConfig, is_first: bool = False):
|
| 774 |
+
super().__init__()
|
| 775 |
+
self.self_attn = DabDetrDecoderLayerSelfAttention(config)
|
| 776 |
+
self.cross_attn = DabDetrDecoderLayerCrossAttention(config, is_first)
|
| 777 |
+
self.mlp = DabDetrDecoderLayerFFN(config)
|
| 778 |
+
|
| 779 |
+
def forward(
|
| 780 |
+
self,
|
| 781 |
+
hidden_states: torch.Tensor,
|
| 782 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 783 |
+
object_queries: Optional[torch.Tensor] = None,
|
| 784 |
+
query_position_embeddings: Optional[torch.Tensor] = None,
|
| 785 |
+
query_sine_embed: Optional[torch.Tensor] = None,
|
| 786 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 787 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 788 |
+
output_attentions: Optional[bool] = None,
|
| 789 |
+
):
|
| 790 |
+
"""
|
| 791 |
+
Args:
|
| 792 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
|
| 793 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 794 |
+
`(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
|
| 795 |
+
values.
|
| 796 |
+
object_queries (`torch.FloatTensor`, *optional*):
|
| 797 |
+
object_queries that are added to the queries and keys
|
| 798 |
+
in the cross-attention layer.
|
| 799 |
+
query_position_embeddings (`torch.FloatTensor`, *optional*):
|
| 800 |
+
object_queries that are added to the queries and keys
|
| 801 |
+
in the self-attention layer.
|
| 802 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 803 |
+
cross attention input to the layer of shape `(seq_len, batch, embed_dim)`
|
| 804 |
+
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
|
| 805 |
+
`(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
|
| 806 |
+
values.
|
| 807 |
+
output_attentions (`bool`, *optional*):
|
| 808 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 809 |
+
returned tensors for more detail.
|
| 810 |
+
|
| 811 |
+
"""
|
| 812 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 813 |
+
hidden_states=hidden_states,
|
| 814 |
+
query_position_embeddings=query_position_embeddings,
|
| 815 |
+
attention_mask=attention_mask,
|
| 816 |
+
output_attentions=output_attentions,
|
| 817 |
+
)
|
| 818 |
+
|
| 819 |
+
hidden_states, cross_attn_weights = self.cross_attn(
|
| 820 |
+
hidden_states=hidden_states,
|
| 821 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 822 |
+
query_position_embeddings=query_position_embeddings,
|
| 823 |
+
object_queries=object_queries,
|
| 824 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 825 |
+
query_sine_embed=query_sine_embed,
|
| 826 |
+
output_attentions=output_attentions,
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
hidden_states = self.mlp(hidden_states=hidden_states)
|
| 830 |
+
|
| 831 |
+
outputs = (hidden_states,)
|
| 832 |
+
|
| 833 |
+
if output_attentions:
|
| 834 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 835 |
+
|
| 836 |
+
return outputs
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
# Modified from transformers.models.detr.modeling_detr.DetrMLPPredictionHead with DetrMLPPredictionHead->DabDetrMLP
|
| 840 |
+
class DabDetrMLP(nn.Module):
|
| 841 |
+
"""
|
| 842 |
+
Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
|
| 843 |
+
height and width of a bounding box w.r.t. an image.
|
| 844 |
+
|
| 845 |
+
Copied from https://github.com/facebookresearch/detr/blob/master/models/detr.py
|
| 846 |
+
|
| 847 |
+
"""
|
| 848 |
+
|
| 849 |
+
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
|
| 850 |
+
super().__init__()
|
| 851 |
+
self.num_layers = num_layers
|
| 852 |
+
h = [hidden_dim] * (num_layers - 1)
|
| 853 |
+
self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
|
| 854 |
+
|
| 855 |
+
def forward(self, input_tensor):
|
| 856 |
+
for i, layer in enumerate(self.layers):
|
| 857 |
+
input_tensor = nn.functional.relu(layer(input_tensor)) if i < self.num_layers - 1 else layer(input_tensor)
|
| 858 |
+
return input_tensor
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
# Modified from transformers.models.detr.modeling_detr.DetrPreTrainedModel with Detr->DabDetr
|
| 862 |
+
class DabDetrPreTrainedModel(PreTrainedModel):
|
| 863 |
+
config_class = DabDetrConfig
|
| 864 |
+
base_model_prefix = "model"
|
| 865 |
+
main_input_name = "pixel_values"
|
| 866 |
+
_no_split_modules = [r"DabDetrConvEncoder", r"DabDetrEncoderLayer", r"DabDetrDecoderLayer"]
|
| 867 |
+
|
| 868 |
+
def _init_weights(self, module):
|
| 869 |
+
std = self.config.init_std
|
| 870 |
+
xavier_std = self.config.init_xavier_std
|
| 871 |
+
|
| 872 |
+
if isinstance(module, DabDetrMHAttentionMap):
|
| 873 |
+
nn.init.zeros_(module.k_linear.bias)
|
| 874 |
+
nn.init.zeros_(module.q_linear.bias)
|
| 875 |
+
nn.init.xavier_uniform_(module.k_linear.weight, gain=xavier_std)
|
| 876 |
+
nn.init.xavier_uniform_(module.q_linear.weight, gain=xavier_std)
|
| 877 |
+
if isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
|
| 878 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 879 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 880 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 881 |
+
if module.bias is not None:
|
| 882 |
+
module.bias.data.zero_()
|
| 883 |
+
elif isinstance(module, nn.Embedding):
|
| 884 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 885 |
+
if module.padding_idx is not None:
|
| 886 |
+
module.weight.data[module.padding_idx].zero_()
|
| 887 |
+
elif isinstance(module, DabDetrForObjectDetection):
|
| 888 |
+
nn.init.constant_(module.bbox_predictor.layers[-1].weight.data, 0)
|
| 889 |
+
nn.init.constant_(module.bbox_predictor.layers[-1].bias.data, 0)
|
| 890 |
+
|
| 891 |
+
# init prior_prob setting for focal loss
|
| 892 |
+
prior_prob = self.config.initializer_bias_prior_prob or 1 / (self.config.num_labels + 1)
|
| 893 |
+
bias_value = -math.log((1 - prior_prob) / prior_prob)
|
| 894 |
+
module.class_embed.bias.data.fill_(bias_value)
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
DAB_DETR_START_DOCSTRING = r"""
|
| 898 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 899 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 900 |
+
etc.)
|
| 901 |
+
|
| 902 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 903 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 904 |
+
and behavior.
|
| 905 |
+
|
| 906 |
+
Parameters:
|
| 907 |
+
config ([`DabDetrConfig`]):
|
| 908 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 909 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 910 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 911 |
+
"""
|
| 912 |
+
|
| 913 |
+
DAB_DETR_INPUTS_DOCSTRING = r"""
|
| 914 |
+
Args:
|
| 915 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 916 |
+
Pixel values. Padding will be ignored by default should you provide it.
|
| 917 |
+
|
| 918 |
+
Pixel values can be obtained using [`AutoImageProcessor`]. See [`DetrImageProcessor.__call__`]
|
| 919 |
+
for details.
|
| 920 |
+
|
| 921 |
+
pixel_mask (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
|
| 922 |
+
Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:
|
| 923 |
+
|
| 924 |
+
- 1 for pixels that are real (i.e. **not masked**),
|
| 925 |
+
- 0 for pixels that are padding (i.e. **masked**).
|
| 926 |
+
|
| 927 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 928 |
+
|
| 929 |
+
decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
|
| 930 |
+
Not used by default. Can be used to mask object queries.
|
| 931 |
+
encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
|
| 932 |
+
Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
|
| 933 |
+
`last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
|
| 934 |
+
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
|
| 935 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 936 |
+
Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
|
| 937 |
+
can choose to directly pass a flattened representation of an image.
|
| 938 |
+
decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
|
| 939 |
+
Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
|
| 940 |
+
embedded representation.
|
| 941 |
+
output_attentions (`bool`, *optional*):
|
| 942 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 943 |
+
tensors for more detail.
|
| 944 |
+
output_hidden_states (`bool`, *optional*):
|
| 945 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 946 |
+
more detail.
|
| 947 |
+
return_dict (`bool`, *optional*):
|
| 948 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 949 |
+
"""
|
| 950 |
+
|
| 951 |
+
|
| 952 |
+
# Modified from transformers.models.detr.modeling_detr.DetrEncoder with Detr->DabDetr,DETR->ConditionalDETR
|
| 953 |
+
class DabDetrEncoder(DabDetrPreTrainedModel):
|
| 954 |
+
"""
|
| 955 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 956 |
+
[`DabDetrEncoderLayer`].
|
| 957 |
+
|
| 958 |
+
The encoder updates the flattened feature map through multiple self-attention layers.
|
| 959 |
+
|
| 960 |
+
Small tweak for DAB-DETR:
|
| 961 |
+
|
| 962 |
+
- object_queries are added to the forward pass.
|
| 963 |
+
|
| 964 |
+
Args:
|
| 965 |
+
config: DabDetrConfig
|
| 966 |
+
"""
|
| 967 |
+
|
| 968 |
+
def __init__(self, config: DabDetrConfig):
|
| 969 |
+
super().__init__(config)
|
| 970 |
+
|
| 971 |
+
self.dropout = config.dropout
|
| 972 |
+
self.query_scale = DabDetrMLP(config.hidden_size, config.hidden_size, config.hidden_size, 2)
|
| 973 |
+
self.layers = nn.ModuleList([DabDetrEncoderLayer(config) for _ in range(config.encoder_layers)])
|
| 974 |
+
self.norm = nn.LayerNorm(config.hidden_size) if config.normalize_before else None
|
| 975 |
+
self.gradient_checkpointing = False
|
| 976 |
+
|
| 977 |
+
# Initialize weights and apply final processing
|
| 978 |
+
self.post_init()
|
| 979 |
+
|
| 980 |
+
def forward(
|
| 981 |
+
self,
|
| 982 |
+
inputs_embeds,
|
| 983 |
+
attention_mask,
|
| 984 |
+
object_queries,
|
| 985 |
+
output_attentions: Optional[bool] = None,
|
| 986 |
+
output_hidden_states: Optional[bool] = None,
|
| 987 |
+
return_dict: Optional[bool] = None,
|
| 988 |
+
):
|
| 989 |
+
r"""
|
| 990 |
+
Args:
|
| 991 |
+
inputs_embeds (`torch.FloatTensor` of shape `(sequence_length, batch_size, hidden_size)`):
|
| 992 |
+
Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
|
| 993 |
+
|
| 994 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 995 |
+
Mask to avoid performing attention on padding pixel features. Mask values selected in `[0, 1]`:
|
| 996 |
+
|
| 997 |
+
- 1 for pixel features that are real (i.e. **not masked**),
|
| 998 |
+
- 0 for pixel features that are padding (i.e. **masked**).
|
| 999 |
+
|
| 1000 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1001 |
+
|
| 1002 |
+
object_queries (`torch.FloatTensor` of shape `(sequence_length, batch_size, hidden_size)`):
|
| 1003 |
+
Object queries that are added to the queries in each self-attention layer.
|
| 1004 |
+
|
| 1005 |
+
output_attentions (`bool`, *optional*):
|
| 1006 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 1007 |
+
returned tensors for more detail.
|
| 1008 |
+
output_hidden_states (`bool`, *optional*):
|
| 1009 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 1010 |
+
for more detail.
|
| 1011 |
+
return_dict (`bool`, *optional*):
|
| 1012 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 1013 |
+
"""
|
| 1014 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1015 |
+
output_hidden_states = (
|
| 1016 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1017 |
+
)
|
| 1018 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1019 |
+
|
| 1020 |
+
hidden_states = inputs_embeds
|
| 1021 |
+
|
| 1022 |
+
# expand attention_mask
|
| 1023 |
+
if attention_mask is not None:
|
| 1024 |
+
# [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
|
| 1025 |
+
attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
|
| 1026 |
+
|
| 1027 |
+
encoder_states = () if output_hidden_states else None
|
| 1028 |
+
all_attentions = () if output_attentions else None
|
| 1029 |
+
|
| 1030 |
+
for encoder_layer in self.layers:
|
| 1031 |
+
if output_hidden_states:
|
| 1032 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 1033 |
+
# pos scaler
|
| 1034 |
+
pos_scales = self.query_scale(hidden_states)
|
| 1035 |
+
# we add object_queries * pos_scaler as extra input to the encoder_layer
|
| 1036 |
+
scaled_object_queries = object_queries * pos_scales
|
| 1037 |
+
|
| 1038 |
+
if self.gradient_checkpointing and self.training:
|
| 1039 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 1040 |
+
encoder_layer.__call__,
|
| 1041 |
+
hidden_states,
|
| 1042 |
+
attention_mask,
|
| 1043 |
+
scaled_object_queries,
|
| 1044 |
+
output_attentions,
|
| 1045 |
+
)
|
| 1046 |
+
else:
|
| 1047 |
+
layer_outputs = encoder_layer(
|
| 1048 |
+
hidden_states,
|
| 1049 |
+
attention_mask=attention_mask,
|
| 1050 |
+
object_queries=scaled_object_queries,
|
| 1051 |
+
output_attentions=output_attentions,
|
| 1052 |
+
)
|
| 1053 |
+
|
| 1054 |
+
hidden_states = layer_outputs[0]
|
| 1055 |
+
|
| 1056 |
+
if output_attentions:
|
| 1057 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 1058 |
+
|
| 1059 |
+
if self.norm:
|
| 1060 |
+
hidden_states = self.norm(hidden_states)
|
| 1061 |
+
|
| 1062 |
+
if output_hidden_states:
|
| 1063 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 1064 |
+
|
| 1065 |
+
if not return_dict:
|
| 1066 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 1067 |
+
return BaseModelOutput(
|
| 1068 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 1069 |
+
)
|
| 1070 |
+
|
| 1071 |
+
|
| 1072 |
+
# Modified from transformers.models.conditional_detr.modeling_conditional_detr.ConditionalDetrDecoder with ConditionalDetr->DabDetr,Conditional DETR->DAB-DETR
|
| 1073 |
+
class DabDetrDecoder(DabDetrPreTrainedModel):
|
| 1074 |
+
"""
|
| 1075 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`DabDetrDecoderLayer`].
|
| 1076 |
+
|
| 1077 |
+
The decoder updates the query embeddings through multiple self-attention and cross-attention layers.
|
| 1078 |
+
|
| 1079 |
+
Some small tweaks for DAB-DETR:
|
| 1080 |
+
|
| 1081 |
+
- object_queries and query_position_embeddings are added to the forward pass.
|
| 1082 |
+
- if self.config.auxiliary_loss is set to True, also returns a stack of activations from all decoding layers.
|
| 1083 |
+
|
| 1084 |
+
Args:
|
| 1085 |
+
config: DabDetrConfig
|
| 1086 |
+
"""
|
| 1087 |
+
|
| 1088 |
+
def __init__(self, config: DabDetrConfig):
|
| 1089 |
+
super().__init__(config)
|
| 1090 |
+
self.config = config
|
| 1091 |
+
self.dropout = config.dropout
|
| 1092 |
+
self.num_layers = config.decoder_layers
|
| 1093 |
+
self.gradient_checkpointing = False
|
| 1094 |
+
|
| 1095 |
+
self.layers = nn.ModuleList(
|
| 1096 |
+
[DabDetrDecoderLayer(config, is_first=(layer_id == 0)) for layer_id in range(config.decoder_layers)]
|
| 1097 |
+
)
|
| 1098 |
+
# in DAB-DETR, the decoder uses layernorm after the last decoder layer output
|
| 1099 |
+
self.hidden_size = config.hidden_size
|
| 1100 |
+
self.layernorm = nn.LayerNorm(self.hidden_size)
|
| 1101 |
+
|
| 1102 |
+
# Default cond-elewise
|
| 1103 |
+
self.query_scale = DabDetrMLP(self.hidden_size, self.hidden_size, self.hidden_size, 2)
|
| 1104 |
+
|
| 1105 |
+
self.ref_point_head = DabDetrMLP(
|
| 1106 |
+
config.query_dim // 2 * self.hidden_size, self.hidden_size, self.hidden_size, 2
|
| 1107 |
+
)
|
| 1108 |
+
|
| 1109 |
+
self.bbox_embed = None
|
| 1110 |
+
|
| 1111 |
+
# Default decoder_modulate_hw_attn is True
|
| 1112 |
+
self.ref_anchor_head = DabDetrMLP(self.hidden_size, self.hidden_size, 2, 2)
|
| 1113 |
+
|
| 1114 |
+
# Initialize weights and apply final processing
|
| 1115 |
+
self.post_init()
|
| 1116 |
+
|
| 1117 |
+
def forward(
|
| 1118 |
+
self,
|
| 1119 |
+
inputs_embeds,
|
| 1120 |
+
encoder_hidden_states,
|
| 1121 |
+
memory_key_padding_mask,
|
| 1122 |
+
object_queries,
|
| 1123 |
+
query_position_embeddings,
|
| 1124 |
+
output_attentions: Optional[bool] = None,
|
| 1125 |
+
output_hidden_states: Optional[bool] = None,
|
| 1126 |
+
return_dict: Optional[bool] = None,
|
| 1127 |
+
):
|
| 1128 |
+
r"""
|
| 1129 |
+
Args:
|
| 1130 |
+
inputs_embeds (`torch.FloatTensor` of shape `(sequence_length, batch_size, hidden_size)`):
|
| 1131 |
+
The query embeddings that are passed into the decoder.
|
| 1132 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(encoder_sequence_length, batch_size, hidden_size)`, *optional*):
|
| 1133 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 1134 |
+
of the decoder.
|
| 1135 |
+
memory_key_padding_mask (`torch.Tensor.bool` of shape `(batch_size, sequence_length)`):
|
| 1136 |
+
The memory_key_padding_mask indicates which positions in the memory (encoder outputs) should be ignored during the attention computation,
|
| 1137 |
+
ensuring padding tokens do not influence the attention mechanism.
|
| 1138 |
+
object_queries (`torch.FloatTensor` of shape `(sequence_length, batch_size, hidden_size)`, *optional*):
|
| 1139 |
+
Position embeddings that are added to the queries and keys in each cross-attention layer.
|
| 1140 |
+
query_position_embeddings (`torch.FloatTensor` of shape `(num_queries, batch_size, number_of_anchor_points)`):
|
| 1141 |
+
Position embeddings that are added to the queries and keys in each self-attention layer.
|
| 1142 |
+
output_attentions (`bool`, *optional*):
|
| 1143 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 1144 |
+
returned tensors for more detail.
|
| 1145 |
+
output_hidden_states (`bool`, *optional*):
|
| 1146 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 1147 |
+
for more detail.
|
| 1148 |
+
return_dict (`bool`, *optional*):
|
| 1149 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 1150 |
+
"""
|
| 1151 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1152 |
+
output_hidden_states = (
|
| 1153 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1154 |
+
)
|
| 1155 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1156 |
+
|
| 1157 |
+
if inputs_embeds is not None:
|
| 1158 |
+
hidden_states = inputs_embeds
|
| 1159 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1160 |
+
|
| 1161 |
+
# decoder layers
|
| 1162 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1163 |
+
all_self_attns = () if output_attentions else None
|
| 1164 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 1165 |
+
|
| 1166 |
+
intermediate = []
|
| 1167 |
+
reference_points = query_position_embeddings.sigmoid()
|
| 1168 |
+
ref_points = [reference_points]
|
| 1169 |
+
|
| 1170 |
+
# expand encoder attention mask
|
| 1171 |
+
if encoder_hidden_states is not None and memory_key_padding_mask is not None:
|
| 1172 |
+
# [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
|
| 1173 |
+
memory_key_padding_mask = _prepare_4d_attention_mask(
|
| 1174 |
+
memory_key_padding_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
|
| 1175 |
+
)
|
| 1176 |
+
|
| 1177 |
+
for layer_id, decoder_layer in enumerate(self.layers):
|
| 1178 |
+
if output_hidden_states:
|
| 1179 |
+
all_hidden_states += (hidden_states,)
|
| 1180 |
+
|
| 1181 |
+
obj_center = reference_points[..., : self.config.query_dim]
|
| 1182 |
+
query_sine_embed = gen_sine_position_embeddings(obj_center, self.hidden_size)
|
| 1183 |
+
query_pos = self.ref_point_head(query_sine_embed)
|
| 1184 |
+
|
| 1185 |
+
# For the first decoder layer, we do not apply transformation over p_s
|
| 1186 |
+
pos_transformation = 1 if layer_id == 0 else self.query_scale(hidden_states)
|
| 1187 |
+
|
| 1188 |
+
# apply transformation
|
| 1189 |
+
query_sine_embed = query_sine_embed[..., : self.hidden_size] * pos_transformation
|
| 1190 |
+
|
| 1191 |
+
# modulated Height Width attentions
|
| 1192 |
+
reference_anchor_size = self.ref_anchor_head(hidden_states).sigmoid() # nq, bs, 2
|
| 1193 |
+
query_sine_embed[..., self.hidden_size // 2 :] *= (
|
| 1194 |
+
reference_anchor_size[..., 0] / obj_center[..., 2]
|
| 1195 |
+
).unsqueeze(-1)
|
| 1196 |
+
query_sine_embed[..., : self.hidden_size // 2] *= (
|
| 1197 |
+
reference_anchor_size[..., 1] / obj_center[..., 3]
|
| 1198 |
+
).unsqueeze(-1)
|
| 1199 |
+
|
| 1200 |
+
if self.gradient_checkpointing and self.training:
|
| 1201 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 1202 |
+
decoder_layer.__call__,
|
| 1203 |
+
hidden_states,
|
| 1204 |
+
None,
|
| 1205 |
+
object_queries,
|
| 1206 |
+
query_pos,
|
| 1207 |
+
query_sine_embed,
|
| 1208 |
+
encoder_hidden_states,
|
| 1209 |
+
memory_key_padding_mask,
|
| 1210 |
+
output_attentions,
|
| 1211 |
+
)
|
| 1212 |
+
else:
|
| 1213 |
+
layer_outputs = decoder_layer(
|
| 1214 |
+
hidden_states,
|
| 1215 |
+
attention_mask=None,
|
| 1216 |
+
object_queries=object_queries,
|
| 1217 |
+
query_position_embeddings=query_pos,
|
| 1218 |
+
query_sine_embed=query_sine_embed,
|
| 1219 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1220 |
+
encoder_attention_mask=memory_key_padding_mask,
|
| 1221 |
+
output_attentions=output_attentions,
|
| 1222 |
+
)
|
| 1223 |
+
|
| 1224 |
+
# iter update
|
| 1225 |
+
hidden_states = layer_outputs[0]
|
| 1226 |
+
|
| 1227 |
+
if self.bbox_embed is not None:
|
| 1228 |
+
new_reference_points = self.bbox_embed(hidden_states)
|
| 1229 |
+
|
| 1230 |
+
new_reference_points[..., : self.config.query_dim] += inverse_sigmoid(reference_points)
|
| 1231 |
+
new_reference_points = new_reference_points[..., : self.config.query_dim].sigmoid()
|
| 1232 |
+
if layer_id != self.num_layers - 1:
|
| 1233 |
+
ref_points.append(new_reference_points)
|
| 1234 |
+
reference_points = new_reference_points.detach()
|
| 1235 |
+
|
| 1236 |
+
intermediate.append(self.layernorm(hidden_states))
|
| 1237 |
+
|
| 1238 |
+
if output_attentions:
|
| 1239 |
+
all_self_attns += (layer_outputs[1],)
|
| 1240 |
+
|
| 1241 |
+
if encoder_hidden_states is not None:
|
| 1242 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 1243 |
+
|
| 1244 |
+
# Layer normalization on hidden states
|
| 1245 |
+
hidden_states = self.layernorm(hidden_states)
|
| 1246 |
+
|
| 1247 |
+
if output_hidden_states:
|
| 1248 |
+
all_hidden_states += (hidden_states,)
|
| 1249 |
+
|
| 1250 |
+
output_intermediate_hidden_states = torch.stack(intermediate)
|
| 1251 |
+
output_reference_points = torch.stack(ref_points)
|
| 1252 |
+
|
| 1253 |
+
if not return_dict:
|
| 1254 |
+
return tuple(
|
| 1255 |
+
v
|
| 1256 |
+
for v in [
|
| 1257 |
+
hidden_states,
|
| 1258 |
+
all_hidden_states,
|
| 1259 |
+
all_self_attns,
|
| 1260 |
+
all_cross_attentions,
|
| 1261 |
+
output_intermediate_hidden_states,
|
| 1262 |
+
output_reference_points,
|
| 1263 |
+
]
|
| 1264 |
+
if v is not None
|
| 1265 |
+
)
|
| 1266 |
+
return DabDetrDecoderOutput(
|
| 1267 |
+
last_hidden_state=hidden_states,
|
| 1268 |
+
hidden_states=all_hidden_states,
|
| 1269 |
+
attentions=all_self_attns,
|
| 1270 |
+
cross_attentions=all_cross_attentions,
|
| 1271 |
+
intermediate_hidden_states=output_intermediate_hidden_states,
|
| 1272 |
+
reference_points=output_reference_points,
|
| 1273 |
+
)
|
| 1274 |
+
|
| 1275 |
+
|
| 1276 |
+
@add_start_docstrings(
|
| 1277 |
+
"""
|
| 1278 |
+
The bare DAB-DETR Model (consisting of a backbone and encoder-decoder Transformer) outputting raw
|
| 1279 |
+
hidden-states, intermediate hidden states, reference points, output coordinates without any specific head on top.
|
| 1280 |
+
""",
|
| 1281 |
+
DAB_DETR_START_DOCSTRING,
|
| 1282 |
+
)
|
| 1283 |
+
class DabDetrModel(DabDetrPreTrainedModel):
|
| 1284 |
+
def __init__(self, config: DabDetrConfig):
|
| 1285 |
+
super().__init__(config)
|
| 1286 |
+
|
| 1287 |
+
self.auxiliary_loss = config.auxiliary_loss
|
| 1288 |
+
|
| 1289 |
+
# Create backbone + positional encoding
|
| 1290 |
+
self.backbone = DabDetrConvEncoder(config)
|
| 1291 |
+
object_queries = DabDetrSinePositionEmbedding(config)
|
| 1292 |
+
|
| 1293 |
+
self.query_refpoint_embeddings = nn.Embedding(config.num_queries, config.query_dim)
|
| 1294 |
+
self.random_refpoints_xy = config.random_refpoints_xy
|
| 1295 |
+
if self.random_refpoints_xy:
|
| 1296 |
+
self.query_refpoint_embeddings.weight.data[:, :2].uniform_(0, 1)
|
| 1297 |
+
self.query_refpoint_embeddings.weight.data[:, :2] = inverse_sigmoid(
|
| 1298 |
+
self.query_refpoint_embeddings.weight.data[:, :2]
|
| 1299 |
+
)
|
| 1300 |
+
self.query_refpoint_embeddings.weight.data[:, :2].requires_grad = False
|
| 1301 |
+
|
| 1302 |
+
# Create projection layer
|
| 1303 |
+
self.input_projection = nn.Conv2d(
|
| 1304 |
+
self.backbone.intermediate_channel_sizes[-1], config.hidden_size, kernel_size=1
|
| 1305 |
+
)
|
| 1306 |
+
self.backbone = DabDetrConvModel(self.backbone, object_queries)
|
| 1307 |
+
|
| 1308 |
+
self.encoder = DabDetrEncoder(config)
|
| 1309 |
+
self.decoder = DabDetrDecoder(config)
|
| 1310 |
+
|
| 1311 |
+
# decoder related variables
|
| 1312 |
+
self.hidden_size = config.hidden_size
|
| 1313 |
+
self.num_queries = config.num_queries
|
| 1314 |
+
|
| 1315 |
+
self.num_patterns = config.num_patterns
|
| 1316 |
+
if not isinstance(self.num_patterns, int):
|
| 1317 |
+
logger.warning("num_patterns should be int but {}".format(type(self.num_patterns)))
|
| 1318 |
+
self.num_patterns = 0
|
| 1319 |
+
if self.num_patterns > 0:
|
| 1320 |
+
self.patterns = nn.Embedding(self.num_patterns, self.hidden_size)
|
| 1321 |
+
|
| 1322 |
+
self.aux_loss = config.auxiliary_loss
|
| 1323 |
+
|
| 1324 |
+
# Initialize weights and apply final processing
|
| 1325 |
+
self.post_init()
|
| 1326 |
+
|
| 1327 |
+
def get_encoder(self):
|
| 1328 |
+
return self.encoder
|
| 1329 |
+
|
| 1330 |
+
def get_decoder(self):
|
| 1331 |
+
return self.decoder
|
| 1332 |
+
|
| 1333 |
+
def freeze_backbone(self):
|
| 1334 |
+
for name, param in self.backbone.conv_encoder.model.named_parameters():
|
| 1335 |
+
param.requires_grad_(False)
|
| 1336 |
+
|
| 1337 |
+
def unfreeze_backbone(self):
|
| 1338 |
+
for name, param in self.backbone.conv_encoder.model.named_parameters():
|
| 1339 |
+
param.requires_grad_(True)
|
| 1340 |
+
|
| 1341 |
+
@add_start_docstrings_to_model_forward(DAB_DETR_INPUTS_DOCSTRING)
|
| 1342 |
+
@replace_return_docstrings(output_type=DabDetrModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 1343 |
+
def forward(
|
| 1344 |
+
self,
|
| 1345 |
+
pixel_values: torch.FloatTensor,
|
| 1346 |
+
pixel_mask: Optional[torch.LongTensor] = None,
|
| 1347 |
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
| 1348 |
+
encoder_outputs: Optional[torch.FloatTensor] = None,
|
| 1349 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1350 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1351 |
+
output_attentions: Optional[bool] = None,
|
| 1352 |
+
output_hidden_states: Optional[bool] = None,
|
| 1353 |
+
return_dict: Optional[bool] = None,
|
| 1354 |
+
) -> Union[Tuple[torch.FloatTensor], DabDetrModelOutput]:
|
| 1355 |
+
r"""
|
| 1356 |
+
Returns:
|
| 1357 |
+
|
| 1358 |
+
Examples:
|
| 1359 |
+
|
| 1360 |
+
```python
|
| 1361 |
+
>>> from transformers import AutoImageProcessor, AutoModel
|
| 1362 |
+
>>> from PIL import Image
|
| 1363 |
+
>>> import requests
|
| 1364 |
+
|
| 1365 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1366 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1367 |
+
|
| 1368 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("IDEA-Research/dab_detr-base")
|
| 1369 |
+
>>> model = AutoModel.from_pretrained("IDEA-Research/dab_detr-base")
|
| 1370 |
+
|
| 1371 |
+
>>> # prepare image for the model
|
| 1372 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 1373 |
+
|
| 1374 |
+
>>> # forward pass
|
| 1375 |
+
>>> outputs = model(**inputs)
|
| 1376 |
+
|
| 1377 |
+
>>> # the last hidden states are the final query embeddings of the Transformer decoder
|
| 1378 |
+
>>> # these are of shape (batch_size, num_queries, hidden_size)
|
| 1379 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 1380 |
+
>>> list(last_hidden_states.shape)
|
| 1381 |
+
[1, 300, 256]
|
| 1382 |
+
```"""
|
| 1383 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1384 |
+
output_hidden_states = (
|
| 1385 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1386 |
+
)
|
| 1387 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1388 |
+
|
| 1389 |
+
batch_size, _, height, width = pixel_values.shape
|
| 1390 |
+
device = pixel_values.device
|
| 1391 |
+
|
| 1392 |
+
if pixel_mask is None:
|
| 1393 |
+
pixel_mask = torch.ones(((batch_size, height, width)), device=device)
|
| 1394 |
+
|
| 1395 |
+
# First, sent pixel_values + pixel_mask through Backbone to obtain the features
|
| 1396 |
+
# pixel_values should be of shape (batch_size, num_channels, height, width)
|
| 1397 |
+
# pixel_mask should be of shape (batch_size, height, width)
|
| 1398 |
+
features, object_queries_list = self.backbone(pixel_values, pixel_mask)
|
| 1399 |
+
|
| 1400 |
+
# get final feature map and downsampled mask
|
| 1401 |
+
feature_map, mask = features[-1]
|
| 1402 |
+
|
| 1403 |
+
if mask is None:
|
| 1404 |
+
raise ValueError("Backbone does not return downsampled pixel mask")
|
| 1405 |
+
|
| 1406 |
+
flattened_mask = mask.flatten(1)
|
| 1407 |
+
|
| 1408 |
+
# Second, apply 1x1 convolution to reduce the channel dimension to hidden_size (256 by default)
|
| 1409 |
+
projected_feature_map = self.input_projection(feature_map)
|
| 1410 |
+
|
| 1411 |
+
# Third, flatten the feature map + object_queries of shape NxCxHxW to HWxNxC, and permute it to NxHWxC
|
| 1412 |
+
# In other words, turn their shape into ( sequence_length, batch_size, hidden_size)
|
| 1413 |
+
flattened_features = projected_feature_map.flatten(2).permute(0, 2, 1)
|
| 1414 |
+
object_queries = object_queries_list[-1].flatten(2).permute(0, 2, 1)
|
| 1415 |
+
reference_position_embeddings = self.query_refpoint_embeddings.weight.unsqueeze(0).repeat(batch_size, 1, 1)
|
| 1416 |
+
|
| 1417 |
+
# Fourth, sent flattened_features + flattened_mask + object_queries through encoder
|
| 1418 |
+
# flattened_features is a Tensor of shape (heigth*width, batch_size, hidden_size)
|
| 1419 |
+
# flattened_mask is a Tensor of shape (batch_size, heigth*width)
|
| 1420 |
+
if encoder_outputs is None:
|
| 1421 |
+
encoder_outputs = self.encoder(
|
| 1422 |
+
inputs_embeds=flattened_features,
|
| 1423 |
+
attention_mask=flattened_mask,
|
| 1424 |
+
object_queries=object_queries,
|
| 1425 |
+
output_attentions=output_attentions,
|
| 1426 |
+
output_hidden_states=output_hidden_states,
|
| 1427 |
+
return_dict=return_dict,
|
| 1428 |
+
)
|
| 1429 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
|
| 1430 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 1431 |
+
encoder_outputs = BaseModelOutput(
|
| 1432 |
+
last_hidden_state=encoder_outputs[0],
|
| 1433 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1434 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1435 |
+
)
|
| 1436 |
+
|
| 1437 |
+
# Fifth, sent query embeddings + object_queries through the decoder (which is conditioned on the encoder output)
|
| 1438 |
+
num_queries = reference_position_embeddings.shape[1]
|
| 1439 |
+
if self.num_patterns == 0:
|
| 1440 |
+
queries = torch.zeros(batch_size, num_queries, self.hidden_size, device=device)
|
| 1441 |
+
else:
|
| 1442 |
+
queries = (
|
| 1443 |
+
self.patterns.weight[:, None, None, :]
|
| 1444 |
+
.repeat(1, self.num_queries, batch_size, 1)
|
| 1445 |
+
.flatten(0, 1)
|
| 1446 |
+
.permute(1, 0, 2)
|
| 1447 |
+
) # bs, n_q*n_pat, hidden_size
|
| 1448 |
+
reference_position_embeddings = reference_position_embeddings.repeat(
|
| 1449 |
+
1, self.num_patterns, 1
|
| 1450 |
+
) # bs, n_q*n_pat, hidden_size
|
| 1451 |
+
|
| 1452 |
+
# decoder outputs consists of (dec_features, dec_hidden, dec_attn)
|
| 1453 |
+
decoder_outputs = self.decoder(
|
| 1454 |
+
inputs_embeds=queries,
|
| 1455 |
+
query_position_embeddings=reference_position_embeddings,
|
| 1456 |
+
object_queries=object_queries,
|
| 1457 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1458 |
+
memory_key_padding_mask=flattened_mask,
|
| 1459 |
+
output_attentions=output_attentions,
|
| 1460 |
+
output_hidden_states=output_hidden_states,
|
| 1461 |
+
return_dict=return_dict,
|
| 1462 |
+
)
|
| 1463 |
+
|
| 1464 |
+
if not return_dict:
|
| 1465 |
+
# last_hidden_state
|
| 1466 |
+
output = (decoder_outputs[0],)
|
| 1467 |
+
reference_points = decoder_outputs[-1]
|
| 1468 |
+
intermediate_hidden_states = decoder_outputs[-2]
|
| 1469 |
+
|
| 1470 |
+
# it has to follow the order of DABDETRModelOutput that is based on ModelOutput
|
| 1471 |
+
# If we only use one of the variables then the indexing will change.
|
| 1472 |
+
# E.g: if we return everything then 'decoder_attentions' is decoder_outputs[2], if we only use output_attentions then its decoder_outputs[1]
|
| 1473 |
+
if output_hidden_states and output_attentions:
|
| 1474 |
+
output += (
|
| 1475 |
+
decoder_outputs[1],
|
| 1476 |
+
decoder_outputs[2],
|
| 1477 |
+
decoder_outputs[3],
|
| 1478 |
+
encoder_outputs[0],
|
| 1479 |
+
encoder_outputs[1],
|
| 1480 |
+
encoder_outputs[2],
|
| 1481 |
+
)
|
| 1482 |
+
elif output_hidden_states:
|
| 1483 |
+
# decoder_hidden_states, encoder_last_hidden_state, encoder_hidden_states
|
| 1484 |
+
output += (
|
| 1485 |
+
decoder_outputs[1],
|
| 1486 |
+
encoder_outputs[0],
|
| 1487 |
+
encoder_outputs[1],
|
| 1488 |
+
)
|
| 1489 |
+
elif output_attentions:
|
| 1490 |
+
# decoder_self_attention, decoder_cross_attention, encoder_attentions
|
| 1491 |
+
output += (
|
| 1492 |
+
decoder_outputs[1],
|
| 1493 |
+
decoder_outputs[2],
|
| 1494 |
+
encoder_outputs[1],
|
| 1495 |
+
)
|
| 1496 |
+
|
| 1497 |
+
output += (intermediate_hidden_states, reference_points)
|
| 1498 |
+
|
| 1499 |
+
return output
|
| 1500 |
+
|
| 1501 |
+
reference_points = decoder_outputs.reference_points
|
| 1502 |
+
intermediate_hidden_states = decoder_outputs.intermediate_hidden_states
|
| 1503 |
+
|
| 1504 |
+
return DabDetrModelOutput(
|
| 1505 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1506 |
+
decoder_hidden_states=decoder_outputs.hidden_states if output_hidden_states else None,
|
| 1507 |
+
decoder_attentions=decoder_outputs.attentions if output_attentions else None,
|
| 1508 |
+
cross_attentions=decoder_outputs.cross_attentions if output_attentions else None,
|
| 1509 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state if output_hidden_states else None,
|
| 1510 |
+
encoder_hidden_states=encoder_outputs.hidden_states if output_hidden_states else None,
|
| 1511 |
+
encoder_attentions=encoder_outputs.attentions if output_attentions else None,
|
| 1512 |
+
intermediate_hidden_states=intermediate_hidden_states,
|
| 1513 |
+
reference_points=reference_points,
|
| 1514 |
+
)
|
| 1515 |
+
|
| 1516 |
+
|
| 1517 |
+
# Copied from transformers.models.detr.modeling_detr.DetrMHAttentionMap with Detr->DabDetr
|
| 1518 |
+
class DabDetrMHAttentionMap(nn.Module):
|
| 1519 |
+
"""This is a 2D attention module, which only returns the attention softmax (no multiplication by value)"""
|
| 1520 |
+
|
| 1521 |
+
def __init__(self, query_dim, hidden_dim, num_heads, dropout=0.0, bias=True, std=None):
|
| 1522 |
+
super().__init__()
|
| 1523 |
+
self.num_heads = num_heads
|
| 1524 |
+
self.hidden_dim = hidden_dim
|
| 1525 |
+
self.dropout = nn.Dropout(dropout)
|
| 1526 |
+
|
| 1527 |
+
self.q_linear = nn.Linear(query_dim, hidden_dim, bias=bias)
|
| 1528 |
+
self.k_linear = nn.Linear(query_dim, hidden_dim, bias=bias)
|
| 1529 |
+
|
| 1530 |
+
self.normalize_fact = float(hidden_dim / self.num_heads) ** -0.5
|
| 1531 |
+
|
| 1532 |
+
def forward(self, q, k, mask: Optional[Tensor] = None):
|
| 1533 |
+
q = self.q_linear(q)
|
| 1534 |
+
k = nn.functional.conv2d(k, self.k_linear.weight.unsqueeze(-1).unsqueeze(-1), self.k_linear.bias)
|
| 1535 |
+
queries_per_head = q.view(q.shape[0], q.shape[1], self.num_heads, self.hidden_dim // self.num_heads)
|
| 1536 |
+
keys_per_head = k.view(k.shape[0], self.num_heads, self.hidden_dim // self.num_heads, k.shape[-2], k.shape[-1])
|
| 1537 |
+
weights = torch.einsum("bqnc,bnchw->bqnhw", queries_per_head * self.normalize_fact, keys_per_head)
|
| 1538 |
+
|
| 1539 |
+
if mask is not None:
|
| 1540 |
+
weights = weights.masked_fill(mask.unsqueeze(1).unsqueeze(1), torch.finfo(weights.dtype).min)
|
| 1541 |
+
weights = nn.functional.softmax(weights.flatten(2), dim=-1).view(weights.size())
|
| 1542 |
+
weights = self.dropout(weights)
|
| 1543 |
+
return weights
|
| 1544 |
+
|
| 1545 |
+
|
| 1546 |
+
@add_start_docstrings(
|
| 1547 |
+
"""
|
| 1548 |
+
DAB_DETR Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on
|
| 1549 |
+
top, for tasks such as COCO detection.
|
| 1550 |
+
""",
|
| 1551 |
+
DAB_DETR_START_DOCSTRING,
|
| 1552 |
+
)
|
| 1553 |
+
class DabDetrForObjectDetection(DabDetrPreTrainedModel):
|
| 1554 |
+
# When using clones, all layers > 0 will be clones, but layer 0 *is* required
|
| 1555 |
+
_tied_weights_keys = [
|
| 1556 |
+
r"bbox_predictor\.layers\.\d+\.(weight|bias)",
|
| 1557 |
+
r"model\.decoder\.bbox_embed\.layers\.\d+\.(weight|bias)",
|
| 1558 |
+
]
|
| 1559 |
+
|
| 1560 |
+
def __init__(self, config: DabDetrConfig):
|
| 1561 |
+
super().__init__(config)
|
| 1562 |
+
|
| 1563 |
+
self.config = config
|
| 1564 |
+
self.auxiliary_loss = config.auxiliary_loss
|
| 1565 |
+
self.query_dim = config.query_dim
|
| 1566 |
+
# DAB-DETR encoder-decoder model
|
| 1567 |
+
self.model = DabDetrModel(config)
|
| 1568 |
+
|
| 1569 |
+
_bbox_embed = DabDetrMLP(config.hidden_size, config.hidden_size, 4, 3)
|
| 1570 |
+
# Object detection heads
|
| 1571 |
+
self.class_embed = nn.Linear(config.hidden_size, config.num_labels)
|
| 1572 |
+
|
| 1573 |
+
# Default bbox_embed_diff_each_layer is False
|
| 1574 |
+
self.bbox_predictor = _bbox_embed
|
| 1575 |
+
|
| 1576 |
+
# Default iter_update is True
|
| 1577 |
+
self.model.decoder.bbox_embed = self.bbox_predictor
|
| 1578 |
+
|
| 1579 |
+
# Initialize weights and apply final processing
|
| 1580 |
+
self.post_init()
|
| 1581 |
+
|
| 1582 |
+
# taken from https://github.com/Atten4Vis/conditionalDETR/blob/master/models/dab_detr.py
|
| 1583 |
+
@torch.jit.unused
|
| 1584 |
+
def _set_aux_loss(self, outputs_class, outputs_coord):
|
| 1585 |
+
# this is a workaround to make torchscript happy, as torchscript
|
| 1586 |
+
# doesn't support dictionary with non-homogeneous values, such
|
| 1587 |
+
# as a dict having both a Tensor and a list.
|
| 1588 |
+
return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
|
| 1589 |
+
|
| 1590 |
+
@add_start_docstrings_to_model_forward(DAB_DETR_INPUTS_DOCSTRING)
|
| 1591 |
+
@replace_return_docstrings(output_type=DabDetrObjectDetectionOutput, config_class=_CONFIG_FOR_DOC)
|
| 1592 |
+
def forward(
|
| 1593 |
+
self,
|
| 1594 |
+
pixel_values: torch.FloatTensor,
|
| 1595 |
+
pixel_mask: Optional[torch.LongTensor] = None,
|
| 1596 |
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
| 1597 |
+
encoder_outputs: Optional[torch.FloatTensor] = None,
|
| 1598 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1599 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1600 |
+
labels: Optional[List[dict]] = None,
|
| 1601 |
+
output_attentions: Optional[bool] = None,
|
| 1602 |
+
output_hidden_states: Optional[bool] = None,
|
| 1603 |
+
return_dict: Optional[bool] = None,
|
| 1604 |
+
) -> Union[Tuple[torch.FloatTensor], DabDetrObjectDetectionOutput]:
|
| 1605 |
+
r"""
|
| 1606 |
+
labels (`List[Dict]` of len `(batch_size,)`, *optional*):
|
| 1607 |
+
Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
|
| 1608 |
+
following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
|
| 1609 |
+
respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
|
| 1610 |
+
in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
|
| 1611 |
+
|
| 1612 |
+
Returns:
|
| 1613 |
+
|
| 1614 |
+
Examples:
|
| 1615 |
+
|
| 1616 |
+
```python
|
| 1617 |
+
>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
|
| 1618 |
+
>>> from PIL import Image
|
| 1619 |
+
>>> import requests
|
| 1620 |
+
|
| 1621 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1622 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1623 |
+
|
| 1624 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("IDEA-Research/dab-detr-resnet-50")
|
| 1625 |
+
>>> model = AutoModelForObjectDetection.from_pretrained("IDEA-Research/dab-detr-resnet-50")
|
| 1626 |
+
|
| 1627 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 1628 |
+
|
| 1629 |
+
>>> with torch.no_grad():
|
| 1630 |
+
>>> outputs = model(**inputs)
|
| 1631 |
+
|
| 1632 |
+
>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
|
| 1633 |
+
>>> target_sizes = torch.tensor([(image.height, image.width)])
|
| 1634 |
+
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[0]
|
| 1635 |
+
>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
|
| 1636 |
+
... box = [round(i, 2) for i in box.tolist()]
|
| 1637 |
+
... print(
|
| 1638 |
+
... f"Detected {model.config.id2label[label.item()]} with confidence "
|
| 1639 |
+
... f"{round(score.item(), 3)} at location {box}"
|
| 1640 |
+
... )
|
| 1641 |
+
Detected remote with confidence 0.833 at location [38.31, 72.1, 177.63, 118.45]
|
| 1642 |
+
Detected cat with confidence 0.831 at location [9.2, 51.38, 321.13, 469.0]
|
| 1643 |
+
Detected cat with confidence 0.804 at location [340.3, 16.85, 642.93, 370.95]
|
| 1644 |
+
Detected remote with confidence 0.683 at location [334.48, 73.49, 366.37, 190.01]
|
| 1645 |
+
Detected couch with confidence 0.535 at location [0.52, 1.19, 640.35, 475.1]
|
| 1646 |
+
```"""
|
| 1647 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1648 |
+
output_hidden_states = (
|
| 1649 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1650 |
+
)
|
| 1651 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1652 |
+
|
| 1653 |
+
# First, sent images through DAB_DETR base model to obtain encoder + decoder outputs
|
| 1654 |
+
model_outputs = self.model(
|
| 1655 |
+
pixel_values,
|
| 1656 |
+
pixel_mask=pixel_mask,
|
| 1657 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1658 |
+
encoder_outputs=encoder_outputs,
|
| 1659 |
+
inputs_embeds=inputs_embeds,
|
| 1660 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1661 |
+
output_attentions=output_attentions,
|
| 1662 |
+
output_hidden_states=output_hidden_states,
|
| 1663 |
+
return_dict=return_dict,
|
| 1664 |
+
)
|
| 1665 |
+
|
| 1666 |
+
reference_points = model_outputs.reference_points if return_dict else model_outputs[-1]
|
| 1667 |
+
intermediate_hidden_states = model_outputs.intermediate_hidden_states if return_dict else model_outputs[-2]
|
| 1668 |
+
|
| 1669 |
+
# class logits + predicted bounding boxes
|
| 1670 |
+
logits = self.class_embed(intermediate_hidden_states[-1])
|
| 1671 |
+
|
| 1672 |
+
reference_before_sigmoid = inverse_sigmoid(reference_points)
|
| 1673 |
+
bbox_with_refinement = self.bbox_predictor(intermediate_hidden_states)
|
| 1674 |
+
bbox_with_refinement[..., : self.query_dim] += reference_before_sigmoid
|
| 1675 |
+
outputs_coord = bbox_with_refinement.sigmoid()
|
| 1676 |
+
|
| 1677 |
+
pred_boxes = outputs_coord[-1]
|
| 1678 |
+
|
| 1679 |
+
loss, loss_dict, auxiliary_outputs = None, None, None
|
| 1680 |
+
if labels is not None:
|
| 1681 |
+
outputs_class = None
|
| 1682 |
+
if self.config.auxiliary_loss:
|
| 1683 |
+
outputs_class = self.class_embed(intermediate_hidden_states)
|
| 1684 |
+
loss, loss_dict, auxiliary_outputs = self.loss_function(
|
| 1685 |
+
logits, labels, self.device, pred_boxes, self.config, outputs_class, outputs_coord
|
| 1686 |
+
)
|
| 1687 |
+
|
| 1688 |
+
if not return_dict:
|
| 1689 |
+
if auxiliary_outputs is not None:
|
| 1690 |
+
output = (logits, pred_boxes) + auxiliary_outputs + model_outputs
|
| 1691 |
+
else:
|
| 1692 |
+
output = (logits, pred_boxes) + model_outputs
|
| 1693 |
+
# Since DabDetrObjectDetectionOutput doesn't have reference points + intermedieate_hidden_states we cut down.
|
| 1694 |
+
return ((loss, loss_dict) + output) if loss is not None else output[:-2]
|
| 1695 |
+
|
| 1696 |
+
return DabDetrObjectDetectionOutput(
|
| 1697 |
+
loss=loss,
|
| 1698 |
+
loss_dict=loss_dict,
|
| 1699 |
+
logits=logits,
|
| 1700 |
+
pred_boxes=pred_boxes,
|
| 1701 |
+
auxiliary_outputs=auxiliary_outputs,
|
| 1702 |
+
last_hidden_state=model_outputs.last_hidden_state,
|
| 1703 |
+
decoder_hidden_states=model_outputs.decoder_hidden_states if output_hidden_states else None,
|
| 1704 |
+
decoder_attentions=model_outputs.decoder_attentions if output_attentions else None,
|
| 1705 |
+
cross_attentions=model_outputs.cross_attentions if output_attentions else None,
|
| 1706 |
+
encoder_last_hidden_state=model_outputs.encoder_last_hidden_state if output_hidden_states else None,
|
| 1707 |
+
encoder_hidden_states=model_outputs.encoder_hidden_states if output_hidden_states else None,
|
| 1708 |
+
encoder_attentions=model_outputs.encoder_attentions if output_attentions else None,
|
| 1709 |
+
)
|
| 1710 |
+
|
| 1711 |
+
|
| 1712 |
+
__all__ = [
|
| 1713 |
+
"DabDetrForObjectDetection",
|
| 1714 |
+
"DabDetrModel",
|
| 1715 |
+
"DabDetrPreTrainedModel",
|
| 1716 |
+
]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dac/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_dac import *
|
| 22 |
+
from .feature_extraction_dac import *
|
| 23 |
+
from .modeling_dac 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__)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dac/configuration_dac.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 Descript 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 |
+
"""Dac model configuration"""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ...configuration_utils import PretrainedConfig
|
| 22 |
+
from ...utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class DacConfig(PretrainedConfig):
|
| 29 |
+
r"""
|
| 30 |
+
This is the configuration class to store the configuration of an [`DacModel`]. It is used to instantiate a
|
| 31 |
+
Dac model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 32 |
+
with the defaults will yield a similar configuration to that of the
|
| 33 |
+
[descript/dac_16khz](https://huggingface.co/descript/dac_16khz) 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 |
+
encoder_hidden_size (`int`, *optional*, defaults to 64):
|
| 40 |
+
Intermediate representation dimension for the encoder.
|
| 41 |
+
downsampling_ratios (`List[int]`, *optional*, defaults to `[2, 4, 8, 8]`):
|
| 42 |
+
Ratios for downsampling in the encoder. These are used in reverse order for upsampling in the decoder.
|
| 43 |
+
decoder_hidden_size (`int`, *optional*, defaults to 1536):
|
| 44 |
+
Intermediate representation dimension for the decoder.
|
| 45 |
+
n_codebooks (`int`, *optional*, defaults to 9):
|
| 46 |
+
Number of codebooks in the VQVAE.
|
| 47 |
+
codebook_size (`int`, *optional*, defaults to 1024):
|
| 48 |
+
Number of discrete codes in each codebook.
|
| 49 |
+
codebook_dim (`int`, *optional*, defaults to 8):
|
| 50 |
+
Dimension of the codebook vectors. If not defined, uses `encoder_hidden_size`.
|
| 51 |
+
quantizer_dropout (`bool`, *optional*, defaults to 0):
|
| 52 |
+
Whether to apply dropout to the quantizer.
|
| 53 |
+
commitment_loss_weight (float, *optional*, defaults to 0.25):
|
| 54 |
+
Weight of the commitment loss term in the VQVAE loss function.
|
| 55 |
+
codebook_loss_weight (float, *optional*, defaults to 1.0):
|
| 56 |
+
Weight of the codebook loss term in the VQVAE loss function.
|
| 57 |
+
sampling_rate (`int`, *optional*, defaults to 16000):
|
| 58 |
+
The sampling rate at which the audio waveform should be digitalized expressed in hertz (Hz).
|
| 59 |
+
Example:
|
| 60 |
+
|
| 61 |
+
```python
|
| 62 |
+
>>> from transformers import DacModel, DacConfig
|
| 63 |
+
|
| 64 |
+
>>> # Initializing a "descript/dac_16khz" style configuration
|
| 65 |
+
>>> configuration = DacConfig()
|
| 66 |
+
|
| 67 |
+
>>> # Initializing a model (with random weights) from the "descript/dac_16khz" style configuration
|
| 68 |
+
>>> model = DacModel(configuration)
|
| 69 |
+
|
| 70 |
+
>>> # Accessing the model configuration
|
| 71 |
+
>>> configuration = model.config
|
| 72 |
+
```"""
|
| 73 |
+
|
| 74 |
+
model_type = "dac"
|
| 75 |
+
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
encoder_hidden_size=64,
|
| 79 |
+
downsampling_ratios=[2, 4, 8, 8],
|
| 80 |
+
decoder_hidden_size=1536,
|
| 81 |
+
n_codebooks=9,
|
| 82 |
+
codebook_size=1024,
|
| 83 |
+
codebook_dim=8,
|
| 84 |
+
quantizer_dropout=0,
|
| 85 |
+
commitment_loss_weight=0.25,
|
| 86 |
+
codebook_loss_weight=1.0,
|
| 87 |
+
sampling_rate=16000,
|
| 88 |
+
**kwargs,
|
| 89 |
+
):
|
| 90 |
+
self.encoder_hidden_size = encoder_hidden_size
|
| 91 |
+
self.downsampling_ratios = downsampling_ratios
|
| 92 |
+
self.decoder_hidden_size = decoder_hidden_size
|
| 93 |
+
self.upsampling_ratios = downsampling_ratios[::-1]
|
| 94 |
+
self.n_codebooks = n_codebooks
|
| 95 |
+
self.codebook_size = codebook_size
|
| 96 |
+
self.codebook_dim = codebook_dim
|
| 97 |
+
self.quantizer_dropout = quantizer_dropout
|
| 98 |
+
self.sampling_rate = sampling_rate
|
| 99 |
+
|
| 100 |
+
self.hidden_size = encoder_hidden_size * (2 ** len(downsampling_ratios))
|
| 101 |
+
|
| 102 |
+
self.hop_length = int(np.prod(downsampling_ratios))
|
| 103 |
+
self.commitment_loss_weight = commitment_loss_weight
|
| 104 |
+
self.codebook_loss_weight = codebook_loss_weight
|
| 105 |
+
|
| 106 |
+
super().__init__(**kwargs)
|
| 107 |
+
|
| 108 |
+
@property
|
| 109 |
+
def frame_rate(self) -> int:
|
| 110 |
+
hop_length = np.prod(self.upsampling_ratios)
|
| 111 |
+
return math.ceil(self.sampling_rate / hop_length)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
__all__ = ["DacConfig"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dac/convert_dac_checkpoint.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 Descript 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 |
+
import argparse
|
| 16 |
+
import fnmatch
|
| 17 |
+
import re
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from transformers import (
|
| 22 |
+
DacConfig,
|
| 23 |
+
DacFeatureExtractor,
|
| 24 |
+
DacModel,
|
| 25 |
+
logging,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# checkpoints downloaded using:
|
| 30 |
+
# pip install descript-audio-codec
|
| 31 |
+
# python3 -m dac download # downloads the default 44kHz variant
|
| 32 |
+
# python3 -m dac download --model_type 44khz # downloads the 44kHz variant
|
| 33 |
+
# python3 -m dac download --model_type 24khz # downloads the 24kHz variant
|
| 34 |
+
# python3 -m dac download --model_type 16khz # downloads the 16kHz variant
|
| 35 |
+
# More informations: https://github.com/descriptinc/descript-audio-codec/tree/main
|
| 36 |
+
|
| 37 |
+
logging.set_verbosity_info()
|
| 38 |
+
logger = logging.get_logger("transformers.models.dac")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def match_pattern(string, pattern):
|
| 42 |
+
# Split the pattern into parts
|
| 43 |
+
pattern_parts = pattern.split(".")
|
| 44 |
+
string_parts = string.split(".")
|
| 45 |
+
|
| 46 |
+
pattern_block_count = string_block_count = 0
|
| 47 |
+
|
| 48 |
+
for part in pattern_parts:
|
| 49 |
+
if part.startswith("block"):
|
| 50 |
+
pattern_block_count += 1
|
| 51 |
+
|
| 52 |
+
for part in string_parts:
|
| 53 |
+
if part.startswith("block"):
|
| 54 |
+
string_block_count += 1
|
| 55 |
+
|
| 56 |
+
return fnmatch.fnmatch(string, pattern) and string_block_count == pattern_block_count
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
TOP_LEVEL_KEYS = []
|
| 60 |
+
IGNORE_KEYS = []
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
MAPPING_ENCODER = {
|
| 64 |
+
"encoder.block.0": ["encoder.conv1"],
|
| 65 |
+
"encoder.block.5": ["encoder.snake1"],
|
| 66 |
+
"encoder.block.6": ["encoder.conv2"],
|
| 67 |
+
"encoder.block.*.block.*.block.0".replace("*", r"\d+"): ["encoder.block", "res_unit", "snake1"],
|
| 68 |
+
"encoder.block.*.block.*.block.1".replace("*", r"\d+"): ["encoder.block", "res_unit", "conv1"],
|
| 69 |
+
"encoder.block.*.block.*.block.2".replace("*", r"\d+"): ["encoder.block", "res_unit", "snake2"],
|
| 70 |
+
"encoder.block.*.block.*.block.3".replace("*", r"\d+"): ["encoder.block", "res_unit", "conv2"],
|
| 71 |
+
"encoder.block.*.block.3".replace("*", r"\d+"): ["encoder.block", "snake1"],
|
| 72 |
+
"encoder.block.*.block.4".replace("*", r"\d+"): ["encoder.block", "conv1"],
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
MAPPING_QUANTIZER = {
|
| 76 |
+
"quantizer.quantizers.*": ["quantizer.quantizers.*"],
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
MAPPING_DECODER = {
|
| 80 |
+
"decoder.model.0": ["decoder.conv1"],
|
| 81 |
+
"decoder.model.5": ["decoder.snake1"],
|
| 82 |
+
"decoder.model.6": ["decoder.conv2"],
|
| 83 |
+
"decoder.model.*.block.0".replace("*", r"\d+"): ["decoder.block", "snake1"],
|
| 84 |
+
"decoder.model.*.block.1".replace("*", r"\d+"): ["decoder.block", "conv_t1"],
|
| 85 |
+
"decoder.model.*.block.*.block.0".replace("*", r"\d+"): ["decoder.block", "res_unit", "snake1"],
|
| 86 |
+
"decoder.model.*.block.*.block.1".replace("*", r"\d+"): ["decoder.block", "res_unit", "conv1"],
|
| 87 |
+
"decoder.model.*.block.*.block.2".replace("*", r"\d+"): ["decoder.block", "res_unit", "snake2"],
|
| 88 |
+
"decoder.model.*.block.*.block.3".replace("*", r"\d+"): ["decoder.block", "res_unit", "conv2"],
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
MAPPING = {
|
| 93 |
+
**MAPPING_ENCODER,
|
| 94 |
+
**MAPPING_QUANTIZER,
|
| 95 |
+
**MAPPING_DECODER,
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def set_recursively(hf_pointer, key, value, full_name, weight_type):
|
| 100 |
+
for attribute in key.split("."):
|
| 101 |
+
hf_pointer = getattr(hf_pointer, attribute)
|
| 102 |
+
|
| 103 |
+
if weight_type is not None:
|
| 104 |
+
hf_shape = getattr(hf_pointer, weight_type).shape
|
| 105 |
+
else:
|
| 106 |
+
hf_shape = hf_pointer.shape
|
| 107 |
+
|
| 108 |
+
if hf_shape != value.shape:
|
| 109 |
+
raise ValueError(
|
| 110 |
+
f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
|
| 111 |
+
f" {value.shape} for {full_name}"
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
if weight_type == "weight":
|
| 115 |
+
hf_pointer.weight.data = value
|
| 116 |
+
elif weight_type == "weight_g":
|
| 117 |
+
hf_pointer.weight_g.data = value
|
| 118 |
+
elif weight_type == "weight_v":
|
| 119 |
+
hf_pointer.weight_v.data = value
|
| 120 |
+
elif weight_type == "bias":
|
| 121 |
+
hf_pointer.bias.data = value
|
| 122 |
+
elif weight_type == "alpha":
|
| 123 |
+
hf_pointer.alpha.data = value
|
| 124 |
+
logger.info(f"{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def should_ignore(name, ignore_keys):
|
| 128 |
+
for key in ignore_keys:
|
| 129 |
+
if key.endswith(".*"):
|
| 130 |
+
if name.startswith(key[:-1]):
|
| 131 |
+
return True
|
| 132 |
+
elif ".*." in key:
|
| 133 |
+
prefix, suffix = key.split(".*.")
|
| 134 |
+
if prefix in name and suffix in name:
|
| 135 |
+
return True
|
| 136 |
+
elif key in name:
|
| 137 |
+
return True
|
| 138 |
+
return False
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def recursively_load_weights(orig_dict, hf_model, model_name):
|
| 142 |
+
unused_weights = []
|
| 143 |
+
|
| 144 |
+
if model_name not in ["dac_16khz", "dac_24khz", "dac_44khz"]:
|
| 145 |
+
raise ValueError(f"Unsupported model: {model_name}")
|
| 146 |
+
|
| 147 |
+
for name, value in orig_dict.items():
|
| 148 |
+
is_used = False
|
| 149 |
+
for key, mapped_key in MAPPING.items():
|
| 150 |
+
regex = re.compile(key)
|
| 151 |
+
if regex.search(name):
|
| 152 |
+
if len(mapped_key) == 1:
|
| 153 |
+
if mapped_key[0][0] == "q":
|
| 154 |
+
mapped_key = ".".join(name.split(".")[:-1])
|
| 155 |
+
else:
|
| 156 |
+
mapped_key = mapped_key[0]
|
| 157 |
+
elif len(mapped_key) == 3:
|
| 158 |
+
integers = re.findall(r"\b\d+\b", name)
|
| 159 |
+
if mapped_key[0][0] == "d":
|
| 160 |
+
mapped_key = "{}.{}.{}{}.{}".format(
|
| 161 |
+
mapped_key[0],
|
| 162 |
+
str(int(integers[0]) - 1),
|
| 163 |
+
mapped_key[1],
|
| 164 |
+
str(int(integers[1]) - 1),
|
| 165 |
+
mapped_key[2],
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
mapped_key = "{}.{}.{}{}.{}".format(
|
| 169 |
+
mapped_key[0],
|
| 170 |
+
str(int(integers[0]) - 1),
|
| 171 |
+
mapped_key[1],
|
| 172 |
+
str(int(integers[1]) + 1),
|
| 173 |
+
mapped_key[2],
|
| 174 |
+
)
|
| 175 |
+
elif len(mapped_key) == 2:
|
| 176 |
+
integers = re.findall(r"\b\d+\b", name)
|
| 177 |
+
mapped_key = "{}.{}.{}".format(mapped_key[0], str(int(integers[0]) - 1), mapped_key[1])
|
| 178 |
+
|
| 179 |
+
is_used = True
|
| 180 |
+
if "weight_g" in name:
|
| 181 |
+
weight_type = "weight_g"
|
| 182 |
+
elif "weight_v" in name:
|
| 183 |
+
weight_type = "weight_v"
|
| 184 |
+
elif "bias" in name:
|
| 185 |
+
weight_type = "bias"
|
| 186 |
+
elif "alpha" in name:
|
| 187 |
+
weight_type = "alpha"
|
| 188 |
+
elif "weight" in name:
|
| 189 |
+
weight_type = "weight"
|
| 190 |
+
set_recursively(hf_model, mapped_key, value, name, weight_type)
|
| 191 |
+
|
| 192 |
+
if not is_used:
|
| 193 |
+
unused_weights.append(name)
|
| 194 |
+
|
| 195 |
+
print(list(set(unused_weights)))
|
| 196 |
+
|
| 197 |
+
logger.warning(f"Unused weights: {unused_weights}")
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@torch.no_grad()
|
| 201 |
+
def convert_checkpoint(
|
| 202 |
+
model_name,
|
| 203 |
+
checkpoint_path,
|
| 204 |
+
pytorch_dump_folder_path,
|
| 205 |
+
sample_rate=16000,
|
| 206 |
+
repo_id=None,
|
| 207 |
+
):
|
| 208 |
+
model_dict = torch.load(checkpoint_path, "cpu")
|
| 209 |
+
|
| 210 |
+
config = DacConfig()
|
| 211 |
+
|
| 212 |
+
metadata = model_dict["metadata"]["kwargs"]
|
| 213 |
+
config.encoder_hidden_size = metadata["encoder_dim"]
|
| 214 |
+
config.downsampling_ratios = metadata["encoder_rates"]
|
| 215 |
+
config.codebook_size = metadata["codebook_size"]
|
| 216 |
+
config.n_codebooks = metadata["n_codebooks"]
|
| 217 |
+
config.codebook_dim = metadata["codebook_dim"]
|
| 218 |
+
config.decoder_hidden_size = metadata["decoder_dim"]
|
| 219 |
+
config.upsampling_ratios = metadata["decoder_rates"]
|
| 220 |
+
config.quantizer_dropout = float(metadata["quantizer_dropout"])
|
| 221 |
+
config.sampling_rate = sample_rate
|
| 222 |
+
|
| 223 |
+
model = DacModel(config)
|
| 224 |
+
feature_extractor = DacFeatureExtractor()
|
| 225 |
+
feature_extractor.sampling_rate = sample_rate
|
| 226 |
+
|
| 227 |
+
original_checkpoint = model_dict["state_dict"]
|
| 228 |
+
|
| 229 |
+
model.apply_weight_norm()
|
| 230 |
+
recursively_load_weights(original_checkpoint, model, model_name)
|
| 231 |
+
model.remove_weight_norm()
|
| 232 |
+
|
| 233 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 234 |
+
|
| 235 |
+
if repo_id:
|
| 236 |
+
print("Pushing to the hub...")
|
| 237 |
+
feature_extractor.push_to_hub(repo_id)
|
| 238 |
+
model.push_to_hub(repo_id)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
if __name__ == "__main__":
|
| 242 |
+
parser = argparse.ArgumentParser()
|
| 243 |
+
parser.add_argument(
|
| 244 |
+
"--model",
|
| 245 |
+
default="dac_44khz",
|
| 246 |
+
type=str,
|
| 247 |
+
help="The model to convert. Should be one of 'dac_16khz', 'dac_24khz', 'dac_44khz'.",
|
| 248 |
+
)
|
| 249 |
+
parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint")
|
| 250 |
+
parser.add_argument(
|
| 251 |
+
"--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model."
|
| 252 |
+
)
|
| 253 |
+
parser.add_argument(
|
| 254 |
+
"--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub."
|
| 255 |
+
)
|
| 256 |
+
parser.add_argument("--sample_rate", default=None, type=str, help="Sample rate used by DacFeatureExtractor")
|
| 257 |
+
args = parser.parse_args()
|
| 258 |
+
|
| 259 |
+
convert_checkpoint(
|
| 260 |
+
args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.sample_rate, args.push_to_hub
|
| 261 |
+
)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dac/feature_extraction_dac.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 Descript 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 |
+
"""Feature extractor class for DAC"""
|
| 16 |
+
|
| 17 |
+
from typing import List, Optional, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
|
| 22 |
+
from ...feature_extraction_utils import BatchFeature
|
| 23 |
+
from ...utils import PaddingStrategy, TensorType, logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class DacFeatureExtractor(SequenceFeatureExtractor):
|
| 30 |
+
r"""
|
| 31 |
+
Constructs an Dac feature extractor.
|
| 32 |
+
|
| 33 |
+
This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
|
| 34 |
+
most of the main methods. Users should refer to this superclass for more information regarding those methods.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
feature_size (`int`, *optional*, defaults to 1):
|
| 38 |
+
The feature dimension of the extracted features. Use 1 for mono, 2 for stereo.
|
| 39 |
+
sampling_rate (`int`, *optional*, defaults to 16000):
|
| 40 |
+
The sampling rate at which the audio waveform should be digitalized, expressed in hertz (Hz).
|
| 41 |
+
padding_value (`float`, *optional*, defaults to 0.0):
|
| 42 |
+
The value that is used for padding.
|
| 43 |
+
hop_length (`int`, *optional*, defaults to 512):
|
| 44 |
+
Overlap length between successive windows.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
model_input_names = ["input_values", "n_quantizers"]
|
| 48 |
+
|
| 49 |
+
def __init__(
|
| 50 |
+
self,
|
| 51 |
+
feature_size: int = 1,
|
| 52 |
+
sampling_rate: int = 16000,
|
| 53 |
+
padding_value: float = 0.0,
|
| 54 |
+
hop_length: int = 512,
|
| 55 |
+
**kwargs,
|
| 56 |
+
):
|
| 57 |
+
super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
|
| 58 |
+
self.hop_length = hop_length
|
| 59 |
+
|
| 60 |
+
def __call__(
|
| 61 |
+
self,
|
| 62 |
+
raw_audio: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],
|
| 63 |
+
padding: Optional[Union[bool, str, PaddingStrategy]] = None,
|
| 64 |
+
truncation: Optional[bool] = False,
|
| 65 |
+
max_length: Optional[int] = None,
|
| 66 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 67 |
+
sampling_rate: Optional[int] = None,
|
| 68 |
+
) -> BatchFeature:
|
| 69 |
+
"""
|
| 70 |
+
Main method to featurize and prepare for the model one or several sequence(s).
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
raw_audio (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`):
|
| 74 |
+
The sequence or batch of sequences to be processed. Each sequence can be a numpy array, a list of float
|
| 75 |
+
values, a list of numpy arrays or a list of list of float values. The numpy array must be of shape
|
| 76 |
+
`(num_samples,)` for mono audio (`feature_size = 1`), or `(2, num_samples)` for stereo audio
|
| 77 |
+
(`feature_size = 2`).
|
| 78 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
|
| 79 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
| 80 |
+
index) among:
|
| 81 |
+
|
| 82 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 83 |
+
sequence if provided).
|
| 84 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 85 |
+
acceptable input length for the model if that argument is not provided.
|
| 86 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 87 |
+
lengths).
|
| 88 |
+
truncation (`bool`, *optional*, defaults to `False`):
|
| 89 |
+
Activates truncation to cut input sequences longer than `max_length` to `max_length`.
|
| 90 |
+
max_length (`int`, *optional*):
|
| 91 |
+
Maximum length of the returned list and optionally padding length (see above).
|
| 92 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*, default to 'pt'):
|
| 93 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 94 |
+
|
| 95 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 96 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 97 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 98 |
+
sampling_rate (`int`, *optional*):
|
| 99 |
+
The sampling rate at which the `audio` input was sampled. It is strongly recommended to pass
|
| 100 |
+
`sampling_rate` at the forward call to prevent silent errors.
|
| 101 |
+
"""
|
| 102 |
+
if sampling_rate is not None:
|
| 103 |
+
if sampling_rate != self.sampling_rate:
|
| 104 |
+
raise ValueError(
|
| 105 |
+
f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
|
| 106 |
+
f" {self.sampling_rate}. Please make sure that the provided audio input was sampled with"
|
| 107 |
+
f" {self.sampling_rate} and not {sampling_rate}."
|
| 108 |
+
)
|
| 109 |
+
else:
|
| 110 |
+
logger.warning(
|
| 111 |
+
f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
|
| 112 |
+
"Failing to do so can result in silent errors that might be hard to debug."
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
if padding and truncation:
|
| 116 |
+
raise ValueError("Both padding and truncation were set. Make sure you only set one.")
|
| 117 |
+
elif padding is None:
|
| 118 |
+
# by default let's pad the inputs
|
| 119 |
+
padding = True
|
| 120 |
+
|
| 121 |
+
is_batched = bool(
|
| 122 |
+
isinstance(raw_audio, (list, tuple)) and (isinstance(raw_audio[0], (np.ndarray, tuple, list)))
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
if is_batched:
|
| 126 |
+
raw_audio = [np.asarray(audio, dtype=np.float32).T for audio in raw_audio]
|
| 127 |
+
elif not is_batched and not isinstance(raw_audio, np.ndarray):
|
| 128 |
+
raw_audio = np.asarray(raw_audio, dtype=np.float32)
|
| 129 |
+
elif isinstance(raw_audio, np.ndarray) and raw_audio.dtype is np.dtype(np.float64):
|
| 130 |
+
raw_audio = raw_audio.astype(np.float32)
|
| 131 |
+
|
| 132 |
+
# always return batch
|
| 133 |
+
if not is_batched:
|
| 134 |
+
raw_audio = [np.asarray(raw_audio).T]
|
| 135 |
+
|
| 136 |
+
# verify inputs are valid
|
| 137 |
+
for idx, example in enumerate(raw_audio):
|
| 138 |
+
if example.ndim > 2:
|
| 139 |
+
raise ValueError(f"Expected input shape (channels, length) but got shape {example.shape}")
|
| 140 |
+
if self.feature_size == 1 and example.ndim != 1:
|
| 141 |
+
raise ValueError(f"Expected mono audio but example has {example.shape[-1]} channels")
|
| 142 |
+
if self.feature_size == 2:
|
| 143 |
+
raise ValueError("Stereo audio isn't supported for now")
|
| 144 |
+
|
| 145 |
+
input_values = BatchFeature({"input_values": raw_audio})
|
| 146 |
+
|
| 147 |
+
# normal padding on batch
|
| 148 |
+
padded_inputs = self.pad(
|
| 149 |
+
input_values,
|
| 150 |
+
max_length=max_length,
|
| 151 |
+
truncation=truncation,
|
| 152 |
+
padding=padding,
|
| 153 |
+
return_attention_mask=False,
|
| 154 |
+
pad_to_multiple_of=self.hop_length,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
if padding:
|
| 158 |
+
padded_inputs.input_values = padded_inputs.input_values[:, np.newaxis, :]
|
| 159 |
+
|
| 160 |
+
input_values = []
|
| 161 |
+
for example in padded_inputs.pop("input_values"):
|
| 162 |
+
if self.feature_size == 1:
|
| 163 |
+
example = example[..., None]
|
| 164 |
+
input_values.append(example.T)
|
| 165 |
+
|
| 166 |
+
padded_inputs["input_values"] = input_values
|
| 167 |
+
if return_tensors is not None:
|
| 168 |
+
padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
|
| 169 |
+
|
| 170 |
+
return padded_inputs
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
__all__ = ["DacFeatureExtractor"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/dac/modeling_dac.py
ADDED
|
@@ -0,0 +1,724 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"""Transformers DAC model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn as nn
|
| 24 |
+
import torch.nn.functional as F
|
| 25 |
+
|
| 26 |
+
from ...modeling_utils import PreTrainedModel
|
| 27 |
+
from ...utils import (
|
| 28 |
+
ModelOutput,
|
| 29 |
+
add_start_docstrings,
|
| 30 |
+
add_start_docstrings_to_model_forward,
|
| 31 |
+
replace_return_docstrings,
|
| 32 |
+
)
|
| 33 |
+
from .configuration_dac import DacConfig
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# General docstring
|
| 37 |
+
_CONFIG_FOR_DOC = "DacConfig"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass
|
| 41 |
+
class DacOutput(ModelOutput):
|
| 42 |
+
"""
|
| 43 |
+
Args:
|
| 44 |
+
loss (`torch.Tensor`):
|
| 45 |
+
Loss from the encoder model, comprising the weighted combination of the commitment and codebook losses.
|
| 46 |
+
audio_values (`torch.Tensor` of shape `(batch_size, input_length)`):
|
| 47 |
+
Reconstructed audio data.
|
| 48 |
+
quantized_representation (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
|
| 49 |
+
Quantized continuous representation of input.
|
| 50 |
+
audio_codes (`torch.LongTensor` of shape `(batch_size, num_codebooks, time_steps)`):
|
| 51 |
+
Codebook indices for each codebook (quantized discrete representation of input).
|
| 52 |
+
projected_latents (`torch.Tensor` of shape `(batch_size, num_codebooks * dimension, time_steps)`):
|
| 53 |
+
Projected latents (continuous representation of input before quantization).
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
loss: torch.FloatTensor = None
|
| 57 |
+
audio_values: torch.FloatTensor = None
|
| 58 |
+
quantized_representation: torch.FloatTensor = None
|
| 59 |
+
audio_codes: torch.LongTensor = None
|
| 60 |
+
projected_latents: torch.FloatTensor = None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@dataclass
|
| 64 |
+
class DacEncoderOutput(ModelOutput):
|
| 65 |
+
"""
|
| 66 |
+
Args:
|
| 67 |
+
loss (`torch.Tensor`):
|
| 68 |
+
Loss from the encoder model, comprising the weighted combination of the commitment and codebook losses.
|
| 69 |
+
quantized_representation (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`, *optional*):
|
| 70 |
+
Quantized continuous representation of input.
|
| 71 |
+
audio_codes (`torch.Tensor` of shape `(batch_size, num_codebooks, time_steps)`, *optional*):
|
| 72 |
+
Codebook indices for each codebook (quantized discrete representation of input).
|
| 73 |
+
projected_latents (`torch.Tensor` of shape `(batch_size, num_codebooks * dimension, time_steps)`, *optional*):
|
| 74 |
+
Projected latents (continuous representation of input before quantization).
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
loss: torch.FloatTensor = None
|
| 78 |
+
quantized_representation: torch.FloatTensor = None
|
| 79 |
+
audio_codes: torch.FloatTensor = None
|
| 80 |
+
projected_latents: torch.FloatTensor = None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@dataclass
|
| 84 |
+
# Copied from transformers.models.encodec.modeling_encodec.EncodecDecoderOutput with Encodec->Dac, segment_length->input_length
|
| 85 |
+
class DacDecoderOutput(ModelOutput):
|
| 86 |
+
"""
|
| 87 |
+
Args:
|
| 88 |
+
audio_values (`torch.FloatTensor` of shape `(batch_size, input_length)`, *optional*):
|
| 89 |
+
Decoded audio values, obtained using the decoder part of Dac.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
audio_values: torch.FloatTensor = None
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class Snake1d(nn.Module):
|
| 96 |
+
"""
|
| 97 |
+
A 1-dimensional Snake activation function module.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def __init__(self, hidden_dim):
|
| 101 |
+
super().__init__()
|
| 102 |
+
self.alpha = nn.Parameter(torch.ones(1, hidden_dim, 1))
|
| 103 |
+
|
| 104 |
+
def forward(self, hidden_states):
|
| 105 |
+
shape = hidden_states.shape
|
| 106 |
+
hidden_states = hidden_states.reshape(shape[0], shape[1], -1)
|
| 107 |
+
hidden_states = hidden_states + (self.alpha + 1e-9).reciprocal() * torch.sin(self.alpha * hidden_states).pow(2)
|
| 108 |
+
hidden_states = hidden_states.reshape(shape)
|
| 109 |
+
return hidden_states
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class DacVectorQuantize(nn.Module):
|
| 113 |
+
"""
|
| 114 |
+
Implementation of VQ similar to Karpathy's repo (https://github.com/karpathy/deep-vector-quantization)
|
| 115 |
+
|
| 116 |
+
Additionally uses following tricks from improved VQGAN
|
| 117 |
+
(https://arxiv.org/pdf/2110.04627.pdf):
|
| 118 |
+
1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space
|
| 119 |
+
for improved codebook usage
|
| 120 |
+
2. l2-normalized codes: Converts euclidean distance to cosine similarity which
|
| 121 |
+
improves training stability
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
def __init__(self, config: DacConfig):
|
| 125 |
+
super().__init__()
|
| 126 |
+
|
| 127 |
+
self.in_proj = nn.Conv1d(config.hidden_size, config.codebook_dim, kernel_size=1)
|
| 128 |
+
self.out_proj = nn.Conv1d(config.codebook_dim, config.hidden_size, kernel_size=1)
|
| 129 |
+
self.codebook = nn.Embedding(config.codebook_size, config.codebook_dim)
|
| 130 |
+
|
| 131 |
+
def forward(self, hidden_state):
|
| 132 |
+
"""
|
| 133 |
+
Quantizes the input tensor using a fixed codebook and returns the corresponding codebook vectors.
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
hidden_state (`torch.FloatTensor` of shape `(batch_size, dimension, time_steps)`):
|
| 137 |
+
Input tensor.
|
| 138 |
+
|
| 139 |
+
Returns:
|
| 140 |
+
quantized_representation (`torch.Tensor`of shape `(batch_size, dimension, time_steps)`):
|
| 141 |
+
Quantized continuous representation of input.
|
| 142 |
+
commitment_loss (`torch.FloatTensor`of shape `(1)`):
|
| 143 |
+
Commitment loss to train encoder to predict vectors closer to codebook entries.
|
| 144 |
+
codebook_loss (`torch.FloatTensor`of shape `(1)`):
|
| 145 |
+
Codebook loss to update the codebook.
|
| 146 |
+
audio_codes (`torch.LongTensor` of shape `(batch_size, time_steps)`):
|
| 147 |
+
Codebook indices for each codebook, quantized discrete representation of input.
|
| 148 |
+
projected_latents (torch.FloatTensor of shape `(batch_size, num_codebooks * dimension, time_steps)`):
|
| 149 |
+
Projected latents (continuous representation of input before quantization).
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
projected_latents = self.in_proj(hidden_state)
|
| 153 |
+
quantized_representation, audio_codes = self.decode_latents(projected_latents)
|
| 154 |
+
|
| 155 |
+
commitment_loss = F.mse_loss(projected_latents, quantized_representation.detach(), reduction="mean")
|
| 156 |
+
codebook_loss = F.mse_loss(quantized_representation, projected_latents.detach(), reduction="mean")
|
| 157 |
+
# noop in forward pass, straight-through gradient estimator in backward pass
|
| 158 |
+
quantized_representation = projected_latents + (quantized_representation - projected_latents).detach()
|
| 159 |
+
quantized_representation = self.out_proj(quantized_representation)
|
| 160 |
+
|
| 161 |
+
return quantized_representation, commitment_loss, codebook_loss, audio_codes, projected_latents
|
| 162 |
+
|
| 163 |
+
def decode_latents(self, hidden_states):
|
| 164 |
+
batch_size, hidden_dim, sequence_length = hidden_states.shape
|
| 165 |
+
encodings = hidden_states.permute(0, 2, 1).reshape(batch_size * sequence_length, hidden_dim)
|
| 166 |
+
codebook = self.codebook.weight # codebook: (N x D)
|
| 167 |
+
|
| 168 |
+
# L2 normalize encodings and codebook (ViT-VQGAN)
|
| 169 |
+
encodings = F.normalize(encodings)
|
| 170 |
+
codebook = F.normalize(codebook)
|
| 171 |
+
|
| 172 |
+
# Compute euclidean distance with codebook
|
| 173 |
+
l2_norm = encodings.pow(2).sum(1, keepdim=True)
|
| 174 |
+
dist = -(l2_norm - 2 * encodings @ codebook.t()) + codebook.pow(2).sum(1, keepdim=True).t()
|
| 175 |
+
|
| 176 |
+
indices = dist.max(1)[1]
|
| 177 |
+
indices = indices.reshape(hidden_states.size(0), -1)
|
| 178 |
+
quantized_representation = self.codebook(indices).transpose(1, 2)
|
| 179 |
+
return quantized_representation, indices
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class DacResidualUnit(nn.Module):
|
| 183 |
+
"""
|
| 184 |
+
A residual unit composed of Snake1d and weight-normalized Conv1d layers with dilations.
|
| 185 |
+
"""
|
| 186 |
+
|
| 187 |
+
def __init__(self, dimension: int = 16, dilation: int = 1):
|
| 188 |
+
super().__init__()
|
| 189 |
+
pad = ((7 - 1) * dilation) // 2
|
| 190 |
+
|
| 191 |
+
self.snake1 = Snake1d(dimension)
|
| 192 |
+
self.conv1 = nn.Conv1d(dimension, dimension, kernel_size=7, dilation=dilation, padding=pad)
|
| 193 |
+
self.snake2 = Snake1d(dimension)
|
| 194 |
+
self.conv2 = nn.Conv1d(dimension, dimension, kernel_size=1)
|
| 195 |
+
|
| 196 |
+
def forward(self, hidden_state):
|
| 197 |
+
"""
|
| 198 |
+
Forward pass through the residual unit.
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
hidden_state (`torch.Tensor` of shape `(batch_size, channels, time_steps)`):
|
| 202 |
+
Input tensor .
|
| 203 |
+
|
| 204 |
+
Returns:
|
| 205 |
+
output_tensor (`torch.Tensor` of shape `(batch_size, channels, time_steps)`):
|
| 206 |
+
Input tensor after passing through the residual unit.
|
| 207 |
+
"""
|
| 208 |
+
output_tensor = hidden_state
|
| 209 |
+
output_tensor = self.conv1(self.snake1(output_tensor))
|
| 210 |
+
output_tensor = self.conv2(self.snake2(output_tensor))
|
| 211 |
+
|
| 212 |
+
padding = (hidden_state.shape[-1] - output_tensor.shape[-1]) // 2
|
| 213 |
+
if padding > 0:
|
| 214 |
+
hidden_state = hidden_state[..., padding:-padding]
|
| 215 |
+
output_tensor = hidden_state + output_tensor
|
| 216 |
+
return output_tensor
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class DacEncoderBlock(nn.Module):
|
| 220 |
+
"""Encoder block used in DAC encoder."""
|
| 221 |
+
|
| 222 |
+
def __init__(self, config: DacConfig, stride: int = 1, stride_index: int = 1):
|
| 223 |
+
super().__init__()
|
| 224 |
+
|
| 225 |
+
dimension = config.encoder_hidden_size * 2**stride_index
|
| 226 |
+
self.res_unit1 = DacResidualUnit(dimension // 2, dilation=1)
|
| 227 |
+
self.res_unit2 = DacResidualUnit(dimension // 2, dilation=3)
|
| 228 |
+
self.res_unit3 = DacResidualUnit(dimension // 2, dilation=9)
|
| 229 |
+
self.snake1 = Snake1d(dimension // 2)
|
| 230 |
+
self.conv1 = nn.Conv1d(
|
| 231 |
+
dimension // 2, dimension, kernel_size=2 * stride, stride=stride, padding=math.ceil(stride / 2)
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
def forward(self, hidden_state):
|
| 235 |
+
hidden_state = self.res_unit1(hidden_state)
|
| 236 |
+
hidden_state = self.res_unit2(hidden_state)
|
| 237 |
+
hidden_state = self.snake1(self.res_unit3(hidden_state))
|
| 238 |
+
hidden_state = self.conv1(hidden_state)
|
| 239 |
+
|
| 240 |
+
return hidden_state
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class DacDecoderBlock(nn.Module):
|
| 244 |
+
"""Decoder block used in DAC decoder."""
|
| 245 |
+
|
| 246 |
+
def __init__(self, config: DacConfig, stride: int = 1, stride_index: int = 1):
|
| 247 |
+
super().__init__()
|
| 248 |
+
|
| 249 |
+
input_dim = config.decoder_hidden_size // 2**stride_index
|
| 250 |
+
output_dim = config.decoder_hidden_size // 2 ** (stride_index + 1)
|
| 251 |
+
self.snake1 = Snake1d(input_dim)
|
| 252 |
+
self.conv_t1 = nn.ConvTranspose1d(
|
| 253 |
+
input_dim,
|
| 254 |
+
output_dim,
|
| 255 |
+
kernel_size=2 * stride,
|
| 256 |
+
stride=stride,
|
| 257 |
+
padding=math.ceil(stride / 2),
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
self.res_unit1 = DacResidualUnit(output_dim, dilation=1)
|
| 261 |
+
self.res_unit2 = DacResidualUnit(output_dim, dilation=3)
|
| 262 |
+
self.res_unit3 = DacResidualUnit(output_dim, dilation=9)
|
| 263 |
+
|
| 264 |
+
def forward(self, hidden_state):
|
| 265 |
+
hidden_state = self.snake1(hidden_state)
|
| 266 |
+
hidden_state = self.conv_t1(hidden_state)
|
| 267 |
+
hidden_state = self.res_unit1(hidden_state)
|
| 268 |
+
hidden_state = self.res_unit2(hidden_state)
|
| 269 |
+
hidden_state = self.res_unit3(hidden_state)
|
| 270 |
+
|
| 271 |
+
return hidden_state
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
class DacResidualVectorQuantize(nn.Module):
|
| 275 |
+
"""
|
| 276 |
+
ResidualVectorQuantize block - Introduced in SoundStream: An end2end neural audio codec (https://arxiv.org/abs/2107.03312)
|
| 277 |
+
"""
|
| 278 |
+
|
| 279 |
+
def __init__(self, config: DacConfig):
|
| 280 |
+
super().__init__()
|
| 281 |
+
|
| 282 |
+
n_codebooks = config.n_codebooks
|
| 283 |
+
quantizer_dropout = config.quantizer_dropout
|
| 284 |
+
|
| 285 |
+
self.n_codebooks = n_codebooks
|
| 286 |
+
|
| 287 |
+
self.quantizers = nn.ModuleList([DacVectorQuantize(config) for i in range(config.n_codebooks)])
|
| 288 |
+
self.quantizer_dropout = quantizer_dropout
|
| 289 |
+
|
| 290 |
+
def forward(self, hidden_state, n_quantizers: int = None):
|
| 291 |
+
"""
|
| 292 |
+
Quantizes the input tensor using a fixed set of codebooks and returns corresponding codebook vectors.
|
| 293 |
+
Args:
|
| 294 |
+
hidden_state (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
|
| 295 |
+
Input tensor to be quantized.
|
| 296 |
+
n_quantizers (`int`, *optional*):
|
| 297 |
+
Number of quantizers to use. If specified and `self.quantizer_dropout` is True,
|
| 298 |
+
this argument is ignored during training, and a random number of quantizers is used.
|
| 299 |
+
|
| 300 |
+
Returns:
|
| 301 |
+
quantized_representation (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
|
| 302 |
+
Quantized continuous representation of input.
|
| 303 |
+
audio_codes (`torch.Tensor` of shape `(batch_size, num_codebooks, time_steps)`):
|
| 304 |
+
Codebook indices for each codebook (quantized discrete representation of input).
|
| 305 |
+
projected_latents (`torch.Tensor` of shape `(batch_size, num_codebooks * dimension, time_steps)`):
|
| 306 |
+
Projected latents (continuous representation of input before quantization).
|
| 307 |
+
commitment_loss (`torch.Tensor` of shape `(1)`):
|
| 308 |
+
Commitment loss to train the encoder to predict vectors closer to codebook entries.
|
| 309 |
+
codebook_loss (`torch.Tensor` of shape `(1)`):
|
| 310 |
+
Codebook loss to update the codebook.
|
| 311 |
+
"""
|
| 312 |
+
|
| 313 |
+
quantized_representation = 0
|
| 314 |
+
residual = hidden_state
|
| 315 |
+
commitment_loss = 0
|
| 316 |
+
codebook_loss = 0
|
| 317 |
+
|
| 318 |
+
audio_codes = []
|
| 319 |
+
projected_latents = []
|
| 320 |
+
|
| 321 |
+
n_quantizers = n_quantizers if n_quantizers is not None else self.n_codebooks
|
| 322 |
+
if self.training:
|
| 323 |
+
n_quantizers = torch.ones((hidden_state.shape[0],)) * self.n_codebooks + 1
|
| 324 |
+
dropout = torch.randint(1, self.n_codebooks + 1, (hidden_state.shape[0],))
|
| 325 |
+
n_dropout = int(hidden_state.shape[0] * self.quantizer_dropout)
|
| 326 |
+
n_quantizers[:n_dropout] = dropout[:n_dropout]
|
| 327 |
+
n_quantizers = n_quantizers.to(hidden_state.device)
|
| 328 |
+
|
| 329 |
+
for i, quantizer in enumerate(self.quantizers):
|
| 330 |
+
if self.training is False and i >= n_quantizers:
|
| 331 |
+
break
|
| 332 |
+
|
| 333 |
+
quantized_representation_i, commitment_loss_i, codebook_loss_i, indices_i, projected_latents_i = quantizer(
|
| 334 |
+
residual
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
# Create mask to apply quantizer dropout
|
| 338 |
+
mask = torch.full((hidden_state.shape[0],), fill_value=i, device=hidden_state.device) < n_quantizers
|
| 339 |
+
quantized_representation = quantized_representation + quantized_representation_i * mask[:, None, None]
|
| 340 |
+
residual = residual - quantized_representation_i
|
| 341 |
+
|
| 342 |
+
# Sum losses
|
| 343 |
+
commitment_loss += commitment_loss_i * mask
|
| 344 |
+
codebook_loss += codebook_loss_i * mask
|
| 345 |
+
|
| 346 |
+
audio_codes.append(indices_i)
|
| 347 |
+
projected_latents.append(projected_latents_i)
|
| 348 |
+
|
| 349 |
+
audio_codes = torch.stack(audio_codes, dim=1)
|
| 350 |
+
projected_latents = torch.cat(projected_latents, dim=1)
|
| 351 |
+
|
| 352 |
+
return quantized_representation, audio_codes, projected_latents, commitment_loss, codebook_loss
|
| 353 |
+
|
| 354 |
+
def from_codes(self, audio_codes: torch.Tensor):
|
| 355 |
+
"""
|
| 356 |
+
Reconstructs the continuous representation from quantized codes.
|
| 357 |
+
|
| 358 |
+
Args:
|
| 359 |
+
audio_codes (`torch.Tensor` of shape `(batch_size, num_codebooks, time_steps)`):
|
| 360 |
+
Quantized discrete representation of input.
|
| 361 |
+
|
| 362 |
+
Returns:
|
| 363 |
+
quantized_representation (`torch.Tensor`):
|
| 364 |
+
Quantized continuous representation of input.
|
| 365 |
+
projected_latents (`torch.Tensor`):
|
| 366 |
+
List of projected latents (continuous representations of input before quantization)
|
| 367 |
+
for each codebook.
|
| 368 |
+
audio_codes (`torch.Tensor`):
|
| 369 |
+
Codebook indices for each codebook.
|
| 370 |
+
"""
|
| 371 |
+
quantized_representation = 0.0
|
| 372 |
+
projected_latents = []
|
| 373 |
+
n_codebooks = audio_codes.shape[1]
|
| 374 |
+
for i in range(n_codebooks):
|
| 375 |
+
projected_latents_i = self.quantizers[i].codebook(audio_codes[:, i, :]).transpose(1, 2)
|
| 376 |
+
projected_latents.append(projected_latents_i)
|
| 377 |
+
quantized_representation += self.quantizers[i].out_proj(projected_latents_i)
|
| 378 |
+
return quantized_representation, torch.cat(projected_latents, dim=1), audio_codes
|
| 379 |
+
|
| 380 |
+
def from_latents(self, latents: torch.Tensor):
|
| 381 |
+
"""Reconstructs the quantized representation from unquantized latents.
|
| 382 |
+
|
| 383 |
+
Args:
|
| 384 |
+
latents (`torch.Tensor` of shape `(batch_size, total_latent_dimension, time_steps)`):
|
| 385 |
+
Continuous representation of input after projection.
|
| 386 |
+
|
| 387 |
+
Returns:
|
| 388 |
+
quantized_representation (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
|
| 389 |
+
Quantized representation of the full-projected space.
|
| 390 |
+
quantized_latents (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`):
|
| 391 |
+
Quantized representation of the latent space (continuous representation before quantization).
|
| 392 |
+
"""
|
| 393 |
+
quantized_representation = 0
|
| 394 |
+
quantized_latents = []
|
| 395 |
+
codes = []
|
| 396 |
+
codebook_dims_tensor = torch.tensor([0] + [q.codebook_dim for q in self.quantizers])
|
| 397 |
+
dims = torch.cumsum(codebook_dims_tensor, dim=0)
|
| 398 |
+
|
| 399 |
+
n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[0]
|
| 400 |
+
for i in range(n_codebooks):
|
| 401 |
+
hidden_dim_j, hidden_dim_k = dims[i], dims[i + 1]
|
| 402 |
+
quantized_latents_i, codes_i = self.quantizers[i].decode_latents(latents[:, hidden_dim_j:hidden_dim_k, :])
|
| 403 |
+
quantized_latents.append(quantized_latents_i)
|
| 404 |
+
codes.append(codes_i)
|
| 405 |
+
|
| 406 |
+
quantized_representation_i = self.quantizers[i].out_proj(quantized_latents_i)
|
| 407 |
+
quantized_representation = quantized_representation + quantized_representation_i
|
| 408 |
+
|
| 409 |
+
return quantized_representation, torch.cat(quantized_latents, dim=1)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
class DacDecoder(nn.Module):
|
| 413 |
+
"""DAC Decoder"""
|
| 414 |
+
|
| 415 |
+
def __init__(self, config: DacConfig):
|
| 416 |
+
super().__init__()
|
| 417 |
+
|
| 418 |
+
input_channel = config.hidden_size
|
| 419 |
+
channels = config.decoder_hidden_size
|
| 420 |
+
strides = config.upsampling_ratios
|
| 421 |
+
|
| 422 |
+
# Add first conv layer
|
| 423 |
+
self.conv1 = nn.Conv1d(input_channel, channels, kernel_size=7, padding=3)
|
| 424 |
+
|
| 425 |
+
# Add upsampling + MRF blocks
|
| 426 |
+
block = []
|
| 427 |
+
for stride_index, stride in enumerate(strides):
|
| 428 |
+
block += [DacDecoderBlock(config, stride, stride_index)]
|
| 429 |
+
|
| 430 |
+
self.block = nn.ModuleList(block)
|
| 431 |
+
output_dim = config.decoder_hidden_size // 2 ** (stride_index + 1)
|
| 432 |
+
self.snake1 = Snake1d(output_dim)
|
| 433 |
+
self.conv2 = nn.Conv1d(output_dim, 1, kernel_size=7, padding=3)
|
| 434 |
+
self.tanh = nn.Tanh()
|
| 435 |
+
|
| 436 |
+
def forward(self, hidden_state):
|
| 437 |
+
hidden_state = self.conv1(hidden_state)
|
| 438 |
+
|
| 439 |
+
for layer in self.block:
|
| 440 |
+
hidden_state = layer(hidden_state)
|
| 441 |
+
|
| 442 |
+
hidden_state = self.snake1(hidden_state)
|
| 443 |
+
hidden_state = self.conv2(hidden_state)
|
| 444 |
+
hidden_state = self.tanh(hidden_state)
|
| 445 |
+
|
| 446 |
+
return hidden_state
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
class DacEncoder(nn.Module):
|
| 450 |
+
"""DAC Encoder"""
|
| 451 |
+
|
| 452 |
+
def __init__(self, config: DacConfig):
|
| 453 |
+
super().__init__()
|
| 454 |
+
|
| 455 |
+
strides = config.downsampling_ratios
|
| 456 |
+
# Create first convolution
|
| 457 |
+
self.conv1 = nn.Conv1d(1, config.encoder_hidden_size, kernel_size=7, padding=3)
|
| 458 |
+
|
| 459 |
+
self.block = []
|
| 460 |
+
# Create EncoderBlocks that double channels as they downsample by `stride`
|
| 461 |
+
for stride_index, stride in enumerate(strides):
|
| 462 |
+
stride_index = stride_index + 1
|
| 463 |
+
self.block += [DacEncoderBlock(config, stride=stride, stride_index=stride_index)]
|
| 464 |
+
|
| 465 |
+
self.block = nn.ModuleList(self.block)
|
| 466 |
+
d_model = config.encoder_hidden_size * 2**stride_index
|
| 467 |
+
self.snake1 = Snake1d(d_model)
|
| 468 |
+
self.conv2 = nn.Conv1d(d_model, config.hidden_size, kernel_size=3, padding=1)
|
| 469 |
+
|
| 470 |
+
def forward(self, hidden_state):
|
| 471 |
+
hidden_state = self.conv1(hidden_state)
|
| 472 |
+
|
| 473 |
+
for module in self.block:
|
| 474 |
+
hidden_state = module(hidden_state)
|
| 475 |
+
|
| 476 |
+
hidden_state = self.snake1(hidden_state)
|
| 477 |
+
hidden_state = self.conv2(hidden_state)
|
| 478 |
+
|
| 479 |
+
return hidden_state
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
class DacPreTrainedModel(PreTrainedModel):
|
| 483 |
+
"""
|
| 484 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
|
| 485 |
+
"""
|
| 486 |
+
|
| 487 |
+
config_class = DacConfig
|
| 488 |
+
base_model_prefix = "dac"
|
| 489 |
+
main_input_name = "input_values"
|
| 490 |
+
|
| 491 |
+
def _init_weights(self, module):
|
| 492 |
+
if isinstance(module, nn.Conv1d):
|
| 493 |
+
nn.init.trunc_normal_(module.weight, std=0.02)
|
| 494 |
+
nn.init.constant_(module.bias, 0)
|
| 495 |
+
|
| 496 |
+
def apply_weight_norm(self):
|
| 497 |
+
weight_norm = nn.utils.weight_norm
|
| 498 |
+
if hasattr(nn.utils.parametrizations, "weight_norm"):
|
| 499 |
+
weight_norm = nn.utils.parametrizations.weight_norm
|
| 500 |
+
|
| 501 |
+
for layer in self.quantizer.quantizers:
|
| 502 |
+
weight_norm(layer.in_proj)
|
| 503 |
+
weight_norm(layer.out_proj)
|
| 504 |
+
|
| 505 |
+
weight_norm(self.encoder.conv1)
|
| 506 |
+
weight_norm(self.encoder.conv2)
|
| 507 |
+
|
| 508 |
+
for layer in self.encoder.block:
|
| 509 |
+
weight_norm(layer.conv1)
|
| 510 |
+
weight_norm(layer.res_unit1.conv1)
|
| 511 |
+
weight_norm(layer.res_unit1.conv2)
|
| 512 |
+
weight_norm(layer.res_unit2.conv1)
|
| 513 |
+
weight_norm(layer.res_unit2.conv2)
|
| 514 |
+
weight_norm(layer.res_unit3.conv1)
|
| 515 |
+
weight_norm(layer.res_unit3.conv2)
|
| 516 |
+
|
| 517 |
+
weight_norm(self.decoder.conv1)
|
| 518 |
+
weight_norm(self.decoder.conv2)
|
| 519 |
+
|
| 520 |
+
for layer in self.decoder.block:
|
| 521 |
+
weight_norm(layer.conv_t1)
|
| 522 |
+
weight_norm(layer.res_unit1.conv1)
|
| 523 |
+
weight_norm(layer.res_unit1.conv2)
|
| 524 |
+
weight_norm(layer.res_unit2.conv1)
|
| 525 |
+
weight_norm(layer.res_unit2.conv2)
|
| 526 |
+
weight_norm(layer.res_unit3.conv1)
|
| 527 |
+
weight_norm(layer.res_unit3.conv2)
|
| 528 |
+
|
| 529 |
+
def remove_weight_norm(self):
|
| 530 |
+
for layer in self.quantizer.quantizers:
|
| 531 |
+
nn.utils.remove_weight_norm(layer.in_proj)
|
| 532 |
+
nn.utils.remove_weight_norm(layer.out_proj)
|
| 533 |
+
|
| 534 |
+
nn.utils.remove_weight_norm(self.encoder.conv1)
|
| 535 |
+
nn.utils.remove_weight_norm(self.encoder.conv2)
|
| 536 |
+
|
| 537 |
+
for layer in self.encoder.block:
|
| 538 |
+
nn.utils.remove_weight_norm(layer.conv1)
|
| 539 |
+
nn.utils.remove_weight_norm(layer.res_unit1.conv1)
|
| 540 |
+
nn.utils.remove_weight_norm(layer.res_unit1.conv2)
|
| 541 |
+
nn.utils.remove_weight_norm(layer.res_unit2.conv1)
|
| 542 |
+
nn.utils.remove_weight_norm(layer.res_unit2.conv2)
|
| 543 |
+
nn.utils.remove_weight_norm(layer.res_unit3.conv1)
|
| 544 |
+
nn.utils.remove_weight_norm(layer.res_unit3.conv2)
|
| 545 |
+
|
| 546 |
+
nn.utils.remove_weight_norm(self.decoder.conv1)
|
| 547 |
+
nn.utils.remove_weight_norm(self.decoder.conv2)
|
| 548 |
+
|
| 549 |
+
for layer in self.decoder.block:
|
| 550 |
+
nn.utils.remove_weight_norm(layer.conv_t1)
|
| 551 |
+
nn.utils.remove_weight_norm(layer.res_unit1.conv1)
|
| 552 |
+
nn.utils.remove_weight_norm(layer.res_unit1.conv2)
|
| 553 |
+
nn.utils.remove_weight_norm(layer.res_unit2.conv1)
|
| 554 |
+
nn.utils.remove_weight_norm(layer.res_unit2.conv2)
|
| 555 |
+
nn.utils.remove_weight_norm(layer.res_unit3.conv1)
|
| 556 |
+
nn.utils.remove_weight_norm(layer.res_unit3.conv2)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
DAC_START_DOCSTRING = r"""
|
| 560 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 561 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 562 |
+
etc.)
|
| 563 |
+
|
| 564 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 565 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 566 |
+
and behavior.
|
| 567 |
+
|
| 568 |
+
Parameters:
|
| 569 |
+
config ([`DacConfig`]):
|
| 570 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 571 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 572 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 573 |
+
"""
|
| 574 |
+
|
| 575 |
+
DAC_INPUTS_DOCSTRING = r"""
|
| 576 |
+
Args:
|
| 577 |
+
input_values (`torch.Tensor` of shape `(batch_size, 1, time_steps)`).
|
| 578 |
+
Audio data to encode,
|
| 579 |
+
n_quantizers (`int`, *optional*):
|
| 580 |
+
Number of quantizers to use. If `None`, all quantizers are used. Default is `None`.
|
| 581 |
+
return_dict (`bool`, *optional*):
|
| 582 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 583 |
+
"""
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
@add_start_docstrings(
|
| 587 |
+
"The DAC (Descript Audio Codec) model.",
|
| 588 |
+
DAC_START_DOCSTRING,
|
| 589 |
+
)
|
| 590 |
+
class DacModel(DacPreTrainedModel):
|
| 591 |
+
def __init__(self, config: DacConfig):
|
| 592 |
+
super().__init__(config)
|
| 593 |
+
self.config = config
|
| 594 |
+
|
| 595 |
+
self.encoder = DacEncoder(config)
|
| 596 |
+
self.decoder = DacDecoder(config)
|
| 597 |
+
|
| 598 |
+
self.quantizer = DacResidualVectorQuantize(config)
|
| 599 |
+
|
| 600 |
+
self.bits_per_codebook = int(math.log2(self.config.codebook_size))
|
| 601 |
+
if 2**self.bits_per_codebook != self.config.codebook_size:
|
| 602 |
+
raise ValueError("The codebook_size must be a power of 2.")
|
| 603 |
+
|
| 604 |
+
# Initialize weights and apply final processing
|
| 605 |
+
self.post_init()
|
| 606 |
+
|
| 607 |
+
@replace_return_docstrings(output_type=DacEncoderOutput, config_class=_CONFIG_FOR_DOC)
|
| 608 |
+
def encode(
|
| 609 |
+
self,
|
| 610 |
+
input_values: torch.Tensor,
|
| 611 |
+
n_quantizers: int = None,
|
| 612 |
+
return_dict: Optional[bool] = None,
|
| 613 |
+
):
|
| 614 |
+
"""
|
| 615 |
+
Encode given audio data and return quantized latent codes
|
| 616 |
+
|
| 617 |
+
Args:
|
| 618 |
+
input_values (`torch.Tensor of shape `(batch_size, 1, time_steps)`):
|
| 619 |
+
Input audio data to encode,
|
| 620 |
+
n_quantizers (int, *optional*):
|
| 621 |
+
Number of quantizers to use. If None, all quantizers are used. Default is None.
|
| 622 |
+
return_dict (`bool`, *optional*):
|
| 623 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 624 |
+
Returns:
|
| 625 |
+
|
| 626 |
+
"""
|
| 627 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 628 |
+
|
| 629 |
+
quantized_representation = self.encoder(input_values)
|
| 630 |
+
quantized_representation, audio_codes, projected_latents, commitment_loss, codebook_loss = self.quantizer(
|
| 631 |
+
quantized_representation, n_quantizers
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
loss = self.config.commitment_loss_weight * commitment_loss + self.config.codebook_loss_weight * codebook_loss
|
| 635 |
+
|
| 636 |
+
if not return_dict:
|
| 637 |
+
return (loss, quantized_representation, audio_codes, projected_latents)
|
| 638 |
+
|
| 639 |
+
return DacEncoderOutput(loss, quantized_representation, audio_codes, projected_latents)
|
| 640 |
+
|
| 641 |
+
@replace_return_docstrings(output_type=DacDecoderOutput, config_class=_CONFIG_FOR_DOC)
|
| 642 |
+
def decode(
|
| 643 |
+
self,
|
| 644 |
+
quantized_representation: Optional[torch.Tensor] = None,
|
| 645 |
+
audio_codes: Optional[torch.Tensor] = None,
|
| 646 |
+
return_dict: Optional[bool] = None,
|
| 647 |
+
):
|
| 648 |
+
"""Decode given latent codes and return audio data
|
| 649 |
+
|
| 650 |
+
Args:
|
| 651 |
+
quantized_representation (torch.Tensor of shape `(batch_size, dimension, time_steps)`, *optional*):
|
| 652 |
+
Quantized continuous representation of input.
|
| 653 |
+
audio_codes (`torch.Tensor` of shape `(batch_size, num_codebooks, time_steps)`, *optional*):
|
| 654 |
+
The codebook indices for each codebook, representing the quantized discrete
|
| 655 |
+
representation of the input. This parameter should be provided if you want
|
| 656 |
+
to decode directly from the audio codes (it will overwrite quantized_representation).
|
| 657 |
+
return_dict (`bool`, *optional*):
|
| 658 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 659 |
+
|
| 660 |
+
Returns:
|
| 661 |
+
|
| 662 |
+
"""
|
| 663 |
+
|
| 664 |
+
if quantized_representation is None and audio_codes is None:
|
| 665 |
+
raise ValueError("Either `quantized_representation` or `audio_codes` must be provided.")
|
| 666 |
+
|
| 667 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 668 |
+
|
| 669 |
+
if audio_codes is not None:
|
| 670 |
+
quantized_representation = self.quantizer.from_codes(audio_codes)[0]
|
| 671 |
+
|
| 672 |
+
audio_values = self.decoder(quantized_representation).squeeze(1)
|
| 673 |
+
|
| 674 |
+
if not return_dict:
|
| 675 |
+
return (audio_values,)
|
| 676 |
+
|
| 677 |
+
return DacDecoderOutput(audio_values)
|
| 678 |
+
|
| 679 |
+
@add_start_docstrings_to_model_forward(DAC_INPUTS_DOCSTRING)
|
| 680 |
+
@replace_return_docstrings(output_type=DacOutput, config_class=_CONFIG_FOR_DOC)
|
| 681 |
+
def forward(
|
| 682 |
+
self,
|
| 683 |
+
input_values: torch.Tensor,
|
| 684 |
+
n_quantizers: int = None,
|
| 685 |
+
return_dict: Optional[bool] = None,
|
| 686 |
+
):
|
| 687 |
+
"""
|
| 688 |
+
Returns:
|
| 689 |
+
Examples:
|
| 690 |
+
|
| 691 |
+
```python
|
| 692 |
+
>>> from datasets import load_dataset, Audio
|
| 693 |
+
>>> from transformers import DacModel, AutoProcessor
|
| 694 |
+
>>> librispeech_dummy = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 695 |
+
|
| 696 |
+
>>> model = DacModel.from_pretrained("descript/dac_16khz")
|
| 697 |
+
>>> processor = AutoProcessor.from_pretrained("descript/dac_16khz")
|
| 698 |
+
>>> librispeech_dummy = librispeech_dummy.cast_column("audio", Audio(sampling_rate=processor.sampling_rate))
|
| 699 |
+
>>> audio_sample = librispeech_dummy[-1]["audio"]["array"]
|
| 700 |
+
>>> inputs = processor(raw_audio=audio_sample, sampling_rate=processor.sampling_rate, return_tensors="pt")
|
| 701 |
+
|
| 702 |
+
>>> encoder_outputs = model.encode(inputs["input_values"])
|
| 703 |
+
>>> # Get the intermediate audio codes
|
| 704 |
+
>>> audio_codes = encoder_outputs.audio_codes
|
| 705 |
+
>>> # Reconstruct the audio from its quantized representation
|
| 706 |
+
>>> audio_values = model.decode(encoder_outputs.quantized_representation)
|
| 707 |
+
>>> # or the equivalent with a forward pass
|
| 708 |
+
>>> audio_values = model(inputs["input_values"]).audio_values
|
| 709 |
+
```"""
|
| 710 |
+
|
| 711 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 712 |
+
length = input_values.shape[-1]
|
| 713 |
+
loss, quantized_representation, audio_codes, projected_latents = self.encode(
|
| 714 |
+
input_values, n_quantizers, return_dict=False
|
| 715 |
+
)
|
| 716 |
+
audio_values = self.decode(quantized_representation, return_dict=False)[0][..., :length]
|
| 717 |
+
|
| 718 |
+
if not return_dict:
|
| 719 |
+
return (loss, audio_values, quantized_representation, audio_codes, projected_latents)
|
| 720 |
+
|
| 721 |
+
return DacOutput(loss, audio_values, quantized_representation, audio_codes, projected_latents)
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
__all__ = ["DacModel", "DacPreTrainedModel"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/data2vec/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_data2vec_audio import *
|
| 22 |
+
from .configuration_data2vec_text import *
|
| 23 |
+
from .configuration_data2vec_vision import *
|
| 24 |
+
from .modeling_data2vec_audio import *
|
| 25 |
+
from .modeling_data2vec_text import *
|
| 26 |
+
from .modeling_data2vec_vision import *
|
| 27 |
+
from .modeling_tf_data2vec_vision import *
|
| 28 |
+
else:
|
| 29 |
+
import sys
|
| 30 |
+
|
| 31 |
+
_file = globals()["__file__"]
|
| 32 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/data2vec/configuration_data2vec_audio.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
"""Data2VecText configuration"""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PretrainedConfig
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Data2VecAudioConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`Data2VecAudioModel`]. It is used to instantiate
|
| 29 |
+
an Data2VecAudio 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 Data2VecAudio
|
| 31 |
+
[facebook/data2vec-audio-base-960h](https://huggingface.co/facebook/data2vec-audio-base-960h) 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 32):
|
| 39 |
+
Vocabulary size of the Data2VecAudio model. Defines the number of different tokens that can be represented
|
| 40 |
+
by the `inputs_ids` passed when calling [`Data2VecAudioModel`] or [`TFData2VecAudioModel`]. Vocabulary size
|
| 41 |
+
of the model. Defines the different tokens that can be represented by the *inputs_ids* passed to the
|
| 42 |
+
forward method of [`Data2VecAudioModel`].
|
| 43 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 44 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 45 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 46 |
+
Number of hidden layers in the Transformer encoder.
|
| 47 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 48 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 49 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 50 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 51 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 52 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 53 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 54 |
+
hidden_dropout (`float`, *optional*, defaults to 0.1):
|
| 55 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 56 |
+
activation_dropout (`float`, *optional*, defaults to 0.1):
|
| 57 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 58 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 59 |
+
The dropout ratio for the attention probabilities.
|
| 60 |
+
final_dropout (`float`, *optional*, defaults to 0.1):
|
| 61 |
+
The dropout probability for the final projection layer of [`Data2VecAudioForCTC`].
|
| 62 |
+
layerdrop (`float`, *optional*, defaults to 0.1):
|
| 63 |
+
The LayerDrop probability. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more
|
| 64 |
+
details.
|
| 65 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 66 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 67 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 68 |
+
The epsilon used by the layer normalization layers.
|
| 69 |
+
feat_proj_dropout (`float`, *optional*, defaults to 0.0):
|
| 70 |
+
The dropout probability for output of the feature encoder.
|
| 71 |
+
feat_extract_activation (`str, `optional`, defaults to `"gelu"`):
|
| 72 |
+
The non-linear activation function (function or string) in the 1D convolutional layers of the feature
|
| 73 |
+
extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 74 |
+
conv_dim (`Tuple[int]` or `List[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
|
| 75 |
+
A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
|
| 76 |
+
feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
|
| 77 |
+
conv_stride (`Tuple[int]` or `List[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
|
| 78 |
+
A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
|
| 79 |
+
of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
|
| 80 |
+
conv_kernel (`Tuple[int]` or `List[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
|
| 81 |
+
A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
|
| 82 |
+
length of *conv_kernel* defines the number of convolutional layers and has to match the length of
|
| 83 |
+
*conv_dim*.
|
| 84 |
+
conv_bias (`bool`, *optional*, defaults to `False`):
|
| 85 |
+
Whether the 1D convolutional layers have a bias.
|
| 86 |
+
num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
|
| 87 |
+
Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
|
| 88 |
+
embeddings layer.
|
| 89 |
+
num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
|
| 90 |
+
Number of groups of 1D convolutional positional embeddings layer.
|
| 91 |
+
mask_time_prob (`float`, *optional*, defaults to 0.05):
|
| 92 |
+
Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
|
| 93 |
+
procecure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
|
| 94 |
+
reasoning from the propability of each feature vector to be chosen as the start of the vector span to be
|
| 95 |
+
masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
|
| 96 |
+
mask_time_length (`int`, *optional*, defaults to 10):
|
| 97 |
+
Length of vector span along the time axis.
|
| 98 |
+
mask_time_min_masks (`int`, *optional*, defaults to 2),:
|
| 99 |
+
The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
|
| 100 |
+
irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
|
| 101 |
+
mask_time_min_masks''
|
| 102 |
+
mask_feature_prob (`float`, *optional*, defaults to 0.0):
|
| 103 |
+
Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
|
| 104 |
+
masking procecure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
|
| 105 |
+
the axis. If reasoning from the propability of each feature vector to be chosen as the start of the vector
|
| 106 |
+
span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
|
| 107 |
+
may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
|
| 108 |
+
True`.
|
| 109 |
+
mask_feature_length (`int`, *optional*, defaults to 10):
|
| 110 |
+
Length of vector span along the feature axis.
|
| 111 |
+
mask_feature_min_masks (`int`, *optional*, defaults to 0),:
|
| 112 |
+
The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
|
| 113 |
+
step, irrespectively of `mask_feature_prob`. Only relevant if
|
| 114 |
+
''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
|
| 115 |
+
ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`):
|
| 116 |
+
Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
|
| 117 |
+
instance of [`Data2VecAudioForCTC`].
|
| 118 |
+
ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
|
| 119 |
+
Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
|
| 120 |
+
occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
|
| 121 |
+
of [`Data2VecAudioForCTC`].
|
| 122 |
+
use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
|
| 123 |
+
Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
|
| 124 |
+
instance of [`Data2VecAudioForSequenceClassification`].
|
| 125 |
+
classifier_proj_size (`int`, *optional*, defaults to 256):
|
| 126 |
+
Dimensionality of the projection before token mean-pooling for classification.
|
| 127 |
+
tdnn_dim (`Tuple[int]` or `List[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
|
| 128 |
+
A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
|
| 129 |
+
module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
|
| 130 |
+
tdnn_kernel (`Tuple[int]` or `List[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
|
| 131 |
+
A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
|
| 132 |
+
*XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
|
| 133 |
+
tdnn_dilation (`Tuple[int]` or `List[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
|
| 134 |
+
A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
|
| 135 |
+
*XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
|
| 136 |
+
xvector_output_dim (`int`, *optional*, defaults to 512):
|
| 137 |
+
Dimensionality of the *XVector* embedding vectors.
|
| 138 |
+
add_adapter (`bool`, *optional*, defaults to `False`):
|
| 139 |
+
Whether a convolutional network should be stacked on top of the Data2VecAudio Encoder. Can be very useful
|
| 140 |
+
for warm-starting Data2VecAudio for SpeechEncoderDecoder models.
|
| 141 |
+
adapter_kernel_size (`int`, *optional*, defaults to 3):
|
| 142 |
+
Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
|
| 143 |
+
adapter_stride (`int`, *optional*, defaults to 2):
|
| 144 |
+
Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
|
| 145 |
+
num_adapter_layers (`int`, *optional*, defaults to 3):
|
| 146 |
+
Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
|
| 147 |
+
True`.
|
| 148 |
+
output_hidden_size (`int`, *optional*):
|
| 149 |
+
Dimensionality of the encoder output layer. If not defined, this defaults to *hidden-size*. Only relevant
|
| 150 |
+
if `add_adapter is True`.
|
| 151 |
+
|
| 152 |
+
Example:
|
| 153 |
+
|
| 154 |
+
```python
|
| 155 |
+
>>> from transformers import Data2VecAudioConfig, Data2VecAudioModel
|
| 156 |
+
|
| 157 |
+
>>> # Initializing a Data2VecAudio facebook/data2vec-audio-base-960h style configuration
|
| 158 |
+
>>> configuration = Data2VecAudioConfig()
|
| 159 |
+
|
| 160 |
+
>>> # Initializing a model (with random weights) from the facebook/data2vec-audio-base-960h style configuration
|
| 161 |
+
>>> model = Data2VecAudioModel(configuration)
|
| 162 |
+
|
| 163 |
+
>>> # Accessing the model configuration
|
| 164 |
+
>>> configuration = model.config
|
| 165 |
+
```"""
|
| 166 |
+
|
| 167 |
+
model_type = "data2vec-audio"
|
| 168 |
+
|
| 169 |
+
def __init__(
|
| 170 |
+
self,
|
| 171 |
+
vocab_size=32,
|
| 172 |
+
hidden_size=768,
|
| 173 |
+
num_hidden_layers=12,
|
| 174 |
+
num_attention_heads=12,
|
| 175 |
+
intermediate_size=3072,
|
| 176 |
+
hidden_act="gelu",
|
| 177 |
+
hidden_dropout=0.1,
|
| 178 |
+
activation_dropout=0.1,
|
| 179 |
+
attention_dropout=0.1,
|
| 180 |
+
feat_proj_dropout=0.0,
|
| 181 |
+
final_dropout=0.1,
|
| 182 |
+
layerdrop=0.1,
|
| 183 |
+
initializer_range=0.02,
|
| 184 |
+
layer_norm_eps=1e-5,
|
| 185 |
+
feat_extract_activation="gelu",
|
| 186 |
+
conv_dim=(512, 512, 512, 512, 512, 512, 512),
|
| 187 |
+
conv_stride=(5, 2, 2, 2, 2, 2, 2),
|
| 188 |
+
conv_kernel=(10, 3, 3, 3, 3, 2, 2),
|
| 189 |
+
conv_bias=False,
|
| 190 |
+
num_conv_pos_embedding_groups=16,
|
| 191 |
+
conv_pos_kernel_size=19,
|
| 192 |
+
num_conv_pos_embeddings=5,
|
| 193 |
+
mask_time_prob=0.05,
|
| 194 |
+
mask_time_length=10,
|
| 195 |
+
mask_time_min_masks=2,
|
| 196 |
+
mask_feature_prob=0.0,
|
| 197 |
+
mask_feature_length=10,
|
| 198 |
+
mask_feature_min_masks=0,
|
| 199 |
+
ctc_loss_reduction="sum",
|
| 200 |
+
ctc_zero_infinity=False,
|
| 201 |
+
use_weighted_layer_sum=False,
|
| 202 |
+
classifier_proj_size=256,
|
| 203 |
+
tdnn_dim=(512, 512, 512, 512, 1500),
|
| 204 |
+
tdnn_kernel=(5, 3, 3, 1, 1),
|
| 205 |
+
tdnn_dilation=(1, 2, 3, 1, 1),
|
| 206 |
+
xvector_output_dim=512,
|
| 207 |
+
pad_token_id=0,
|
| 208 |
+
bos_token_id=1,
|
| 209 |
+
eos_token_id=2,
|
| 210 |
+
add_adapter=False,
|
| 211 |
+
adapter_kernel_size=3,
|
| 212 |
+
adapter_stride=2,
|
| 213 |
+
num_adapter_layers=3,
|
| 214 |
+
output_hidden_size=None,
|
| 215 |
+
**kwargs,
|
| 216 |
+
):
|
| 217 |
+
super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
|
| 218 |
+
self.hidden_size = hidden_size
|
| 219 |
+
self.feat_extract_activation = feat_extract_activation
|
| 220 |
+
self.conv_dim = list(conv_dim)
|
| 221 |
+
self.conv_stride = list(conv_stride)
|
| 222 |
+
self.conv_kernel = list(conv_kernel)
|
| 223 |
+
self.conv_bias = conv_bias
|
| 224 |
+
self.num_conv_pos_embeddings = num_conv_pos_embeddings
|
| 225 |
+
self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
|
| 226 |
+
self.conv_pos_kernel_size = conv_pos_kernel_size
|
| 227 |
+
self.num_feat_extract_layers = len(self.conv_dim)
|
| 228 |
+
self.num_hidden_layers = num_hidden_layers
|
| 229 |
+
self.intermediate_size = intermediate_size
|
| 230 |
+
self.hidden_act = hidden_act
|
| 231 |
+
self.num_attention_heads = num_attention_heads
|
| 232 |
+
self.hidden_dropout = hidden_dropout
|
| 233 |
+
self.attention_dropout = attention_dropout
|
| 234 |
+
self.activation_dropout = activation_dropout
|
| 235 |
+
self.feat_proj_dropout = feat_proj_dropout
|
| 236 |
+
self.final_dropout = final_dropout
|
| 237 |
+
self.layerdrop = layerdrop
|
| 238 |
+
self.layer_norm_eps = layer_norm_eps
|
| 239 |
+
self.initializer_range = initializer_range
|
| 240 |
+
self.vocab_size = vocab_size
|
| 241 |
+
self.use_weighted_layer_sum = use_weighted_layer_sum
|
| 242 |
+
|
| 243 |
+
if (
|
| 244 |
+
(len(self.conv_stride) != self.num_feat_extract_layers)
|
| 245 |
+
or (len(self.conv_kernel) != self.num_feat_extract_layers)
|
| 246 |
+
or (len(self.conv_dim) != self.num_feat_extract_layers)
|
| 247 |
+
):
|
| 248 |
+
raise ValueError(
|
| 249 |
+
"Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
|
| 250 |
+
" `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
|
| 251 |
+
f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
|
| 252 |
+
f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
|
| 256 |
+
self.mask_time_prob = mask_time_prob
|
| 257 |
+
self.mask_time_length = mask_time_length
|
| 258 |
+
self.mask_time_min_masks = mask_time_min_masks
|
| 259 |
+
self.mask_feature_prob = mask_feature_prob
|
| 260 |
+
self.mask_feature_length = mask_feature_length
|
| 261 |
+
self.mask_feature_min_masks = mask_feature_min_masks
|
| 262 |
+
|
| 263 |
+
# ctc loss
|
| 264 |
+
self.ctc_loss_reduction = ctc_loss_reduction
|
| 265 |
+
self.ctc_zero_infinity = ctc_zero_infinity
|
| 266 |
+
|
| 267 |
+
# adapter
|
| 268 |
+
self.add_adapter = add_adapter
|
| 269 |
+
self.adapter_kernel_size = adapter_kernel_size
|
| 270 |
+
self.adapter_stride = adapter_stride
|
| 271 |
+
self.num_adapter_layers = num_adapter_layers
|
| 272 |
+
self.output_hidden_size = output_hidden_size or hidden_size
|
| 273 |
+
|
| 274 |
+
# SequenceClassification-specific parameter. Feel free to ignore for other classes.
|
| 275 |
+
self.classifier_proj_size = classifier_proj_size
|
| 276 |
+
|
| 277 |
+
# XVector-specific parameters. Feel free to ignore for other classes.
|
| 278 |
+
self.tdnn_dim = list(tdnn_dim)
|
| 279 |
+
self.tdnn_kernel = list(tdnn_kernel)
|
| 280 |
+
self.tdnn_dilation = list(tdnn_dilation)
|
| 281 |
+
self.xvector_output_dim = xvector_output_dim
|
| 282 |
+
|
| 283 |
+
@property
|
| 284 |
+
def inputs_to_logits_ratio(self):
|
| 285 |
+
return math.prod(self.conv_stride)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
__all__ = ["Data2VecAudioConfig"]
|
tasks/tasksmith-441eeab80047/tests/source/src/transformers/models/data2vec/configuration_data2vec_text.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Data2VecText configuration"""
|
| 16 |
+
|
| 17 |
+
from collections import OrderedDict
|
| 18 |
+
from typing import Mapping
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PretrainedConfig
|
| 21 |
+
from ...onnx import OnnxConfig
|
| 22 |
+
from ...utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Data2VecTextConfig(PretrainedConfig):
|
| 29 |
+
r"""
|
| 30 |
+
This is the configuration class to store the configuration of a [`Data2VecTextModel`] and [`Data2VecTextModel`]. It
|
| 31 |
+
is used to instantiate a Data2VecText model according to the specified arguments, defining the model architecture.
|
| 32 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the Data2VecText
|
| 33 |
+
[facebook/data2vec-text-base](https://huggingface.co/facebook/data2vec-text-base) 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 |
+
|
| 39 |
+
Args:
|
| 40 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 41 |
+
Vocabulary size of the DATA2VEC model. Defines the number of different tokens that can be represented by
|
| 42 |
+
the `inputs_ids` passed when calling [`Data2VecModel`].
|
| 43 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 44 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 45 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 46 |
+
Number of hidden layers in the Transformer encoder.
|
| 47 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 48 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 49 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 50 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 51 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
| 52 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 53 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 54 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 55 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 56 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 57 |
+
The dropout ratio for the attention probabilities.
|
| 58 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 59 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 60 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 61 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 62 |
+
The vocabulary size of the `token_type_ids` passed when calling [`Data2VecModel`].
|
| 63 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 64 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 65 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 66 |
+
The epsilon used by the layer normalization layers.
|
| 67 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 68 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 69 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 70 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 71 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 72 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 73 |
+
is_decoder (`bool`, *optional*, defaults to `False`):
|
| 74 |
+
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
|
| 75 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 76 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 77 |
+
relevant if `config.is_decoder=True`.
|
| 78 |
+
classifier_dropout (`float`, *optional*):
|
| 79 |
+
The dropout ratio for the classification head.
|
| 80 |
+
|
| 81 |
+
Examples:
|
| 82 |
+
|
| 83 |
+
```python
|
| 84 |
+
>>> from transformers import Data2VecTextConfig, Data2VecTextModel
|
| 85 |
+
|
| 86 |
+
>>> # Initializing a Data2VecText facebook/data2vec-text-base style configuration
|
| 87 |
+
>>> configuration = Data2VecTextConfig()
|
| 88 |
+
|
| 89 |
+
>>> # Initializing a model (with random weights) from the facebook/data2vec-text-base style configuration
|
| 90 |
+
>>> model = Data2VecTextModel(configuration)
|
| 91 |
+
|
| 92 |
+
>>> # Accessing the model configuration
|
| 93 |
+
>>> configuration = model.config
|
| 94 |
+
```"""
|
| 95 |
+
|
| 96 |
+
model_type = "data2vec-text"
|
| 97 |
+
|
| 98 |
+
def __init__(
|
| 99 |
+
self,
|
| 100 |
+
vocab_size=30522,
|
| 101 |
+
hidden_size=768,
|
| 102 |
+
num_hidden_layers=12,
|
| 103 |
+
num_attention_heads=12,
|
| 104 |
+
intermediate_size=3072,
|
| 105 |
+
hidden_act="gelu",
|
| 106 |
+
hidden_dropout_prob=0.1,
|
| 107 |
+
attention_probs_dropout_prob=0.1,
|
| 108 |
+
max_position_embeddings=512,
|
| 109 |
+
type_vocab_size=2,
|
| 110 |
+
initializer_range=0.02,
|
| 111 |
+
layer_norm_eps=1e-12,
|
| 112 |
+
pad_token_id=1,
|
| 113 |
+
bos_token_id=0,
|
| 114 |
+
eos_token_id=2,
|
| 115 |
+
position_embedding_type="absolute",
|
| 116 |
+
use_cache=True,
|
| 117 |
+
classifier_dropout=None,
|
| 118 |
+
**kwargs,
|
| 119 |
+
):
|
| 120 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 121 |
+
|
| 122 |
+
self.vocab_size = vocab_size
|
| 123 |
+
self.hidden_size = hidden_size
|
| 124 |
+
self.num_hidden_layers = num_hidden_layers
|
| 125 |
+
self.num_attention_heads = num_attention_heads
|
| 126 |
+
self.hidden_act = hidden_act
|
| 127 |
+
self.intermediate_size = intermediate_size
|
| 128 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 129 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 130 |
+
self.max_position_embeddings = max_position_embeddings
|
| 131 |
+
self.type_vocab_size = type_vocab_size
|
| 132 |
+
self.initializer_range = initializer_range
|
| 133 |
+
self.layer_norm_eps = layer_norm_eps
|
| 134 |
+
self.position_embedding_type = position_embedding_type
|
| 135 |
+
self.use_cache = use_cache
|
| 136 |
+
self.classifier_dropout = classifier_dropout
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class Data2VecTextOnnxConfig(OnnxConfig):
|
| 140 |
+
@property
|
| 141 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 142 |
+
if self.task == "multiple-choice":
|
| 143 |
+
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
|
| 144 |
+
else:
|
| 145 |
+
dynamic_axis = {0: "batch", 1: "sequence"}
|
| 146 |
+
return OrderedDict(
|
| 147 |
+
[
|
| 148 |
+
("input_ids", dynamic_axis),
|
| 149 |
+
("attention_mask", dynamic_axis),
|
| 150 |
+
]
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
__all__ = ["Data2VecTextConfig", "Data2VecTextOnnxConfig"]
|