Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/dpt/__init__.py +76 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/dpt/configuration_dpt.py +258 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/dpt/convert_dpt_beit_to_hf.py +306 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__init__.py +107 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/configuration_fnet.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/convert_fnet_original_flax_checkpoint_to_pytorch.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/modeling_fnet.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet_fast.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py +157 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/modeling_fnet.py +1185 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/tokenization_fnet.py +351 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/tokenization_fnet_fast.py +204 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/configuration_kosmos2.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/modeling_kosmos2.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/processing_kosmos2.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/configuration_kosmos2.py +299 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.py +77 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/modeling_kosmos2.py +2056 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/processing_kosmos2.py +666 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/qdqbert/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/qdqbert/__pycache__/configuration_qdqbert.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/qdqbert/__pycache__/modeling_qdqbert.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__init__.py +96 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/convert_hifigan.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/convert_speecht5_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/feature_extraction_speecht5.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/number_normalizer.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/processing_speecht5.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/convert_speecht5_original_pytorch_checkpoint_to_pytorch.py +401 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/feature_extraction_speecht5.py +393 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/number_normalizer.py +192 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/processing_speecht5.py +183 -0
- evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/tokenization_speecht5.py +235 -0
- falcon/lib/python3.10/site-packages/torch/__pycache__/_tensor_docs.cpython-310.pyc +3 -0
- falcon/lib/python3.10/site-packages/torch/__pycache__/_torch_docs.cpython-310.pyc +3 -0
- falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/__init__.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/bounds.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/codecache.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/comm_analysis.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/comms.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/config.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/coordinate_descent_tuner.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-310.pyc +0 -0
- falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/cudagraph_utils.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -1266,3 +1266,5 @@ falcon/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/mod
|
|
| 1266 |
falcon/lib/python3.10/site-packages/transformers/__pycache__/training_args.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1267 |
falcon/lib/python3.10/site-packages/transformers/__pycache__/modeling_outputs.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1268 |
evalkit_tf437/lib/python3.10/site-packages/transformers/generation/__pycache__/tf_utils.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 1266 |
falcon/lib/python3.10/site-packages/transformers/__pycache__/training_args.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1267 |
falcon/lib/python3.10/site-packages/transformers/__pycache__/modeling_outputs.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1268 |
evalkit_tf437/lib/python3.10/site-packages/transformers/generation/__pycache__/tf_utils.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1269 |
+
falcon/lib/python3.10/site-packages/torch/__pycache__/_torch_docs.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1270 |
+
falcon/lib/python3.10/site-packages/torch/__pycache__/_tensor_docs.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/dpt/__init__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available
|
| 17 |
+
from ...utils import OptionalDependencyNotAvailable
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_import_structure = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]}
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
if not is_vision_available():
|
| 24 |
+
raise OptionalDependencyNotAvailable()
|
| 25 |
+
except OptionalDependencyNotAvailable:
|
| 26 |
+
pass
|
| 27 |
+
else:
|
| 28 |
+
_import_structure["feature_extraction_dpt"] = ["DPTFeatureExtractor"]
|
| 29 |
+
_import_structure["image_processing_dpt"] = ["DPTImageProcessor"]
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
if not is_torch_available():
|
| 33 |
+
raise OptionalDependencyNotAvailable()
|
| 34 |
+
except OptionalDependencyNotAvailable:
|
| 35 |
+
pass
|
| 36 |
+
else:
|
| 37 |
+
_import_structure["modeling_dpt"] = [
|
| 38 |
+
"DPT_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 39 |
+
"DPTForDepthEstimation",
|
| 40 |
+
"DPTForSemanticSegmentation",
|
| 41 |
+
"DPTModel",
|
| 42 |
+
"DPTPreTrainedModel",
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if TYPE_CHECKING:
|
| 47 |
+
from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig
|
| 48 |
+
|
| 49 |
+
try:
|
| 50 |
+
if not is_vision_available():
|
| 51 |
+
raise OptionalDependencyNotAvailable()
|
| 52 |
+
except OptionalDependencyNotAvailable:
|
| 53 |
+
pass
|
| 54 |
+
else:
|
| 55 |
+
from .feature_extraction_dpt import DPTFeatureExtractor
|
| 56 |
+
from .image_processing_dpt import DPTImageProcessor
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
if not is_torch_available():
|
| 60 |
+
raise OptionalDependencyNotAvailable()
|
| 61 |
+
except OptionalDependencyNotAvailable:
|
| 62 |
+
pass
|
| 63 |
+
else:
|
| 64 |
+
from .modeling_dpt import (
|
| 65 |
+
DPT_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 66 |
+
DPTForDepthEstimation,
|
| 67 |
+
DPTForSemanticSegmentation,
|
| 68 |
+
DPTModel,
|
| 69 |
+
DPTPreTrainedModel,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
else:
|
| 74 |
+
import sys
|
| 75 |
+
|
| 76 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/dpt/configuration_dpt.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
""" DPT model configuration"""
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PretrainedConfig
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
from ..auto.configuration_auto import CONFIG_MAPPING
|
| 22 |
+
from ..bit import BitConfig
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
DPT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 28 |
+
"Intel/dpt-large": "https://huggingface.co/Intel/dpt-large/resolve/main/config.json",
|
| 29 |
+
# See all DPT models at https://huggingface.co/models?filter=dpt
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class DPTConfig(PretrainedConfig):
|
| 34 |
+
r"""
|
| 35 |
+
This is the configuration class to store the configuration of a [`DPTModel`]. It is used to instantiate an DPT
|
| 36 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 37 |
+
defaults will yield a similar configuration to that of the DPT
|
| 38 |
+
[Intel/dpt-large](https://huggingface.co/Intel/dpt-large) architecture.
|
| 39 |
+
|
| 40 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 41 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 46 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 47 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 48 |
+
Number of hidden layers in the Transformer encoder.
|
| 49 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 50 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 51 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 52 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 53 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 54 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 55 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 56 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 57 |
+
The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
|
| 58 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 59 |
+
The dropout ratio for the attention probabilities.
|
| 60 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 61 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 62 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 63 |
+
The epsilon used by the layer normalization layers.
|
| 64 |
+
image_size (`int`, *optional*, defaults to 384):
|
| 65 |
+
The size (resolution) of each image.
|
| 66 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 67 |
+
The size (resolution) of each patch.
|
| 68 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 69 |
+
The number of input channels.
|
| 70 |
+
is_hybrid (`bool`, *optional*, defaults to `False`):
|
| 71 |
+
Whether to use a hybrid backbone. Useful in the context of loading DPT-Hybrid models.
|
| 72 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
Whether to add a bias to the queries, keys and values.
|
| 74 |
+
backbone_out_indices (`List[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
|
| 75 |
+
Indices of the intermediate hidden states to use from backbone.
|
| 76 |
+
readout_type (`str`, *optional*, defaults to `"project"`):
|
| 77 |
+
The readout type to use when processing the readout token (CLS token) of the intermediate hidden states of
|
| 78 |
+
the ViT backbone. Can be one of [`"ignore"`, `"add"`, `"project"`].
|
| 79 |
+
|
| 80 |
+
- "ignore" simply ignores the CLS token.
|
| 81 |
+
- "add" passes the information from the CLS token to all other tokens by adding the representations.
|
| 82 |
+
- "project" passes information to the other tokens by concatenating the readout to all other tokens before
|
| 83 |
+
projecting the
|
| 84 |
+
representation to the original feature dimension D using a linear layer followed by a GELU non-linearity.
|
| 85 |
+
reassemble_factors (`List[int]`, *optional*, defaults to `[4, 2, 1, 0.5]`):
|
| 86 |
+
The up/downsampling factors of the reassemble layers.
|
| 87 |
+
neck_hidden_sizes (`List[str]`, *optional*, defaults to `[96, 192, 384, 768]`):
|
| 88 |
+
The hidden sizes to project to for the feature maps of the backbone.
|
| 89 |
+
fusion_hidden_size (`int`, *optional*, defaults to 256):
|
| 90 |
+
The number of channels before fusion.
|
| 91 |
+
head_in_index (`int`, *optional*, defaults to -1):
|
| 92 |
+
The index of the features to use in the heads.
|
| 93 |
+
use_batch_norm_in_fusion_residual (`bool`, *optional*, defaults to `False`):
|
| 94 |
+
Whether to use batch normalization in the pre-activate residual units of the fusion blocks.
|
| 95 |
+
use_bias_in_fusion_residual (`bool`, *optional*, defaults to `True`):
|
| 96 |
+
Whether to use bias in the pre-activate residual units of the fusion blocks.
|
| 97 |
+
add_projection (`bool`, *optional*, defaults to `False`):
|
| 98 |
+
Whether to add a projection layer before the depth estimation head.
|
| 99 |
+
use_auxiliary_head (`bool`, *optional*, defaults to `True`):
|
| 100 |
+
Whether to use an auxiliary head during training.
|
| 101 |
+
auxiliary_loss_weight (`float`, *optional*, defaults to 0.4):
|
| 102 |
+
Weight of the cross-entropy loss of the auxiliary head.
|
| 103 |
+
semantic_loss_ignore_index (`int`, *optional*, defaults to 255):
|
| 104 |
+
The index that is ignored by the loss function of the semantic segmentation model.
|
| 105 |
+
semantic_classifier_dropout (`float`, *optional*, defaults to 0.1):
|
| 106 |
+
The dropout ratio for the semantic classification head.
|
| 107 |
+
backbone_featmap_shape (`List[int]`, *optional*, defaults to `[1, 1024, 24, 24]`):
|
| 108 |
+
Used only for the `hybrid` embedding type. The shape of the feature maps of the backbone.
|
| 109 |
+
neck_ignore_stages (`List[int]`, *optional*, defaults to `[0, 1]`):
|
| 110 |
+
Used only for the `hybrid` embedding type. The stages of the readout layers to ignore.
|
| 111 |
+
backbone_config (`Union[Dict[str, Any], PretrainedConfig]`, *optional*):
|
| 112 |
+
The configuration of the backbone model. Only used in case `is_hybrid` is `True` or in case you want to
|
| 113 |
+
leverage the [`AutoBackbone`] API.
|
| 114 |
+
|
| 115 |
+
Example:
|
| 116 |
+
|
| 117 |
+
```python
|
| 118 |
+
>>> from transformers import DPTModel, DPTConfig
|
| 119 |
+
|
| 120 |
+
>>> # Initializing a DPT dpt-large style configuration
|
| 121 |
+
>>> configuration = DPTConfig()
|
| 122 |
+
|
| 123 |
+
>>> # Initializing a model from the dpt-large style configuration
|
| 124 |
+
>>> model = DPTModel(configuration)
|
| 125 |
+
|
| 126 |
+
>>> # Accessing the model configuration
|
| 127 |
+
>>> configuration = model.config
|
| 128 |
+
```"""
|
| 129 |
+
|
| 130 |
+
model_type = "dpt"
|
| 131 |
+
|
| 132 |
+
def __init__(
|
| 133 |
+
self,
|
| 134 |
+
hidden_size=768,
|
| 135 |
+
num_hidden_layers=12,
|
| 136 |
+
num_attention_heads=12,
|
| 137 |
+
intermediate_size=3072,
|
| 138 |
+
hidden_act="gelu",
|
| 139 |
+
hidden_dropout_prob=0.0,
|
| 140 |
+
attention_probs_dropout_prob=0.0,
|
| 141 |
+
initializer_range=0.02,
|
| 142 |
+
layer_norm_eps=1e-12,
|
| 143 |
+
image_size=384,
|
| 144 |
+
patch_size=16,
|
| 145 |
+
num_channels=3,
|
| 146 |
+
is_hybrid=False,
|
| 147 |
+
qkv_bias=True,
|
| 148 |
+
backbone_out_indices=[2, 5, 8, 11],
|
| 149 |
+
readout_type="project",
|
| 150 |
+
reassemble_factors=[4, 2, 1, 0.5],
|
| 151 |
+
neck_hidden_sizes=[96, 192, 384, 768],
|
| 152 |
+
fusion_hidden_size=256,
|
| 153 |
+
head_in_index=-1,
|
| 154 |
+
use_batch_norm_in_fusion_residual=False,
|
| 155 |
+
use_bias_in_fusion_residual=None,
|
| 156 |
+
add_projection=False,
|
| 157 |
+
use_auxiliary_head=True,
|
| 158 |
+
auxiliary_loss_weight=0.4,
|
| 159 |
+
semantic_loss_ignore_index=255,
|
| 160 |
+
semantic_classifier_dropout=0.1,
|
| 161 |
+
backbone_featmap_shape=[1, 1024, 24, 24],
|
| 162 |
+
neck_ignore_stages=[0, 1],
|
| 163 |
+
backbone_config=None,
|
| 164 |
+
**kwargs,
|
| 165 |
+
):
|
| 166 |
+
super().__init__(**kwargs)
|
| 167 |
+
|
| 168 |
+
self.hidden_size = hidden_size
|
| 169 |
+
self.is_hybrid = is_hybrid
|
| 170 |
+
|
| 171 |
+
use_autobackbone = False
|
| 172 |
+
if self.is_hybrid:
|
| 173 |
+
if backbone_config is None:
|
| 174 |
+
logger.info("Initializing the config with a `BiT` backbone.")
|
| 175 |
+
backbone_config = {
|
| 176 |
+
"global_padding": "same",
|
| 177 |
+
"layer_type": "bottleneck",
|
| 178 |
+
"depths": [3, 4, 9],
|
| 179 |
+
"out_features": ["stage1", "stage2", "stage3"],
|
| 180 |
+
"embedding_dynamic_padding": True,
|
| 181 |
+
}
|
| 182 |
+
self.backbone_config = BitConfig(**backbone_config)
|
| 183 |
+
elif isinstance(backbone_config, dict):
|
| 184 |
+
logger.info("Initializing the config with a `BiT` backbone.")
|
| 185 |
+
self.backbone_config = BitConfig(**backbone_config)
|
| 186 |
+
elif isinstance(backbone_config, PretrainedConfig):
|
| 187 |
+
self.backbone_config = backbone_config
|
| 188 |
+
else:
|
| 189 |
+
raise ValueError(
|
| 190 |
+
f"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}."
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
self.backbone_featmap_shape = backbone_featmap_shape
|
| 194 |
+
self.neck_ignore_stages = neck_ignore_stages
|
| 195 |
+
|
| 196 |
+
if readout_type != "project":
|
| 197 |
+
raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode.")
|
| 198 |
+
|
| 199 |
+
elif backbone_config is not None:
|
| 200 |
+
use_autobackbone = True
|
| 201 |
+
|
| 202 |
+
if 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 |
+
|
| 207 |
+
self.backbone_config = backbone_config
|
| 208 |
+
self.backbone_featmap_shape = None
|
| 209 |
+
self.neck_ignore_stages = []
|
| 210 |
+
|
| 211 |
+
else:
|
| 212 |
+
self.backbone_config = backbone_config
|
| 213 |
+
self.backbone_featmap_shape = None
|
| 214 |
+
self.neck_ignore_stages = []
|
| 215 |
+
|
| 216 |
+
self.num_hidden_layers = None if use_autobackbone else num_hidden_layers
|
| 217 |
+
self.num_attention_heads = None if use_autobackbone else num_attention_heads
|
| 218 |
+
self.intermediate_size = None if use_autobackbone else intermediate_size
|
| 219 |
+
self.hidden_dropout_prob = None if use_autobackbone else hidden_dropout_prob
|
| 220 |
+
self.attention_probs_dropout_prob = None if use_autobackbone else attention_probs_dropout_prob
|
| 221 |
+
self.layer_norm_eps = None if use_autobackbone else layer_norm_eps
|
| 222 |
+
self.image_size = None if use_autobackbone else image_size
|
| 223 |
+
self.patch_size = None if use_autobackbone else patch_size
|
| 224 |
+
self.num_channels = None if use_autobackbone else num_channels
|
| 225 |
+
self.qkv_bias = None if use_autobackbone else qkv_bias
|
| 226 |
+
self.backbone_out_indices = None if use_autobackbone else backbone_out_indices
|
| 227 |
+
|
| 228 |
+
if readout_type not in ["ignore", "add", "project"]:
|
| 229 |
+
raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']")
|
| 230 |
+
self.hidden_act = hidden_act
|
| 231 |
+
self.initializer_range = initializer_range
|
| 232 |
+
self.readout_type = readout_type
|
| 233 |
+
self.reassemble_factors = reassemble_factors
|
| 234 |
+
self.neck_hidden_sizes = neck_hidden_sizes
|
| 235 |
+
self.fusion_hidden_size = fusion_hidden_size
|
| 236 |
+
self.head_in_index = head_in_index
|
| 237 |
+
self.use_batch_norm_in_fusion_residual = use_batch_norm_in_fusion_residual
|
| 238 |
+
self.use_bias_in_fusion_residual = use_bias_in_fusion_residual
|
| 239 |
+
self.add_projection = add_projection
|
| 240 |
+
|
| 241 |
+
# auxiliary head attributes (semantic segmentation)
|
| 242 |
+
self.use_auxiliary_head = use_auxiliary_head
|
| 243 |
+
self.auxiliary_loss_weight = auxiliary_loss_weight
|
| 244 |
+
self.semantic_loss_ignore_index = semantic_loss_ignore_index
|
| 245 |
+
self.semantic_classifier_dropout = semantic_classifier_dropout
|
| 246 |
+
|
| 247 |
+
def to_dict(self):
|
| 248 |
+
"""
|
| 249 |
+
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`]. Returns:
|
| 250 |
+
`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
|
| 251 |
+
"""
|
| 252 |
+
output = copy.deepcopy(self.__dict__)
|
| 253 |
+
|
| 254 |
+
if output["backbone_config"] is not None:
|
| 255 |
+
output["backbone_config"] = self.backbone_config.to_dict()
|
| 256 |
+
|
| 257 |
+
output["model_type"] = self.__class__.model_type
|
| 258 |
+
return output
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/dpt/convert_dpt_beit_to_hf.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 DPT 3.1 checkpoints from the MiDaS repository. URL: https://github.com/isl-org/MiDaS"""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import requests
|
| 22 |
+
import torch
|
| 23 |
+
from PIL import Image
|
| 24 |
+
|
| 25 |
+
from transformers import BeitConfig, DPTConfig, DPTForDepthEstimation, DPTImageProcessor
|
| 26 |
+
from transformers.utils import logging
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logging.set_verbosity_info()
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_dpt_config(model_name):
|
| 34 |
+
hidden_size = 768
|
| 35 |
+
num_hidden_layers = 12
|
| 36 |
+
num_attention_heads = 12
|
| 37 |
+
intermediate_size = 3072
|
| 38 |
+
out_features = ["stage3", "stage6", "stage9", "stage12"] # beit-base-384 uses [2, 5, 8, 11]
|
| 39 |
+
|
| 40 |
+
if "large" in model_name:
|
| 41 |
+
hidden_size = 1024
|
| 42 |
+
num_hidden_layers = 24
|
| 43 |
+
num_attention_heads = 16
|
| 44 |
+
intermediate_size = 4096
|
| 45 |
+
out_features = ["stage6", "stage12", "stage18", "stage24"] # beit-large-512 uses [5, 11, 17, 23]
|
| 46 |
+
|
| 47 |
+
if "512" in model_name:
|
| 48 |
+
image_size = 512
|
| 49 |
+
elif "384" in model_name:
|
| 50 |
+
image_size = 384
|
| 51 |
+
else:
|
| 52 |
+
raise ValueError("Model not supported")
|
| 53 |
+
|
| 54 |
+
backbone_config = BeitConfig(
|
| 55 |
+
image_size=image_size,
|
| 56 |
+
num_hidden_layers=num_hidden_layers,
|
| 57 |
+
hidden_size=hidden_size,
|
| 58 |
+
intermediate_size=intermediate_size,
|
| 59 |
+
num_attention_heads=num_attention_heads,
|
| 60 |
+
use_relative_position_bias=True,
|
| 61 |
+
reshape_hidden_states=False,
|
| 62 |
+
out_features=out_features,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
neck_hidden_sizes = [256, 512, 1024, 1024] if "large" in model_name else [96, 192, 384, 768]
|
| 66 |
+
config = DPTConfig(backbone_config=backbone_config, neck_hidden_sizes=neck_hidden_sizes)
|
| 67 |
+
|
| 68 |
+
return config, image_size
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# here we list all keys to be renamed (original name on the left, our name on the right)
|
| 72 |
+
def create_rename_keys(config):
|
| 73 |
+
rename_keys = []
|
| 74 |
+
|
| 75 |
+
# fmt: off
|
| 76 |
+
# stem
|
| 77 |
+
rename_keys.append(("pretrained.model.cls_token", "backbone.embeddings.cls_token"))
|
| 78 |
+
rename_keys.append(("pretrained.model.patch_embed.proj.weight", "backbone.embeddings.patch_embeddings.projection.weight"))
|
| 79 |
+
rename_keys.append(("pretrained.model.patch_embed.proj.bias", "backbone.embeddings.patch_embeddings.projection.bias"))
|
| 80 |
+
|
| 81 |
+
# Transfomer encoder
|
| 82 |
+
for i in range(config.backbone_config.num_hidden_layers):
|
| 83 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.gamma_1", f"backbone.encoder.layer.{i}.lambda_1"))
|
| 84 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.gamma_2", f"backbone.encoder.layer.{i}.lambda_2"))
|
| 85 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.norm1.weight", f"backbone.encoder.layer.{i}.layernorm_before.weight"))
|
| 86 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.norm1.bias", f"backbone.encoder.layer.{i}.layernorm_before.bias"))
|
| 87 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.norm2.weight", f"backbone.encoder.layer.{i}.layernorm_after.weight"))
|
| 88 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.norm2.bias", f"backbone.encoder.layer.{i}.layernorm_after.bias"))
|
| 89 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.mlp.fc1.weight", f"backbone.encoder.layer.{i}.intermediate.dense.weight"))
|
| 90 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.mlp.fc1.bias", f"backbone.encoder.layer.{i}.intermediate.dense.bias"))
|
| 91 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.mlp.fc2.weight", f"backbone.encoder.layer.{i}.output.dense.weight"))
|
| 92 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.mlp.fc2.bias", f"backbone.encoder.layer.{i}.output.dense.bias"))
|
| 93 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.attn.proj.weight", f"backbone.encoder.layer.{i}.attention.output.dense.weight"))
|
| 94 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.attn.proj.bias", f"backbone.encoder.layer.{i}.attention.output.dense.bias"))
|
| 95 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.attn.relative_position_bias_table", f"backbone.encoder.layer.{i}.attention.attention.relative_position_bias.relative_position_bias_table"))
|
| 96 |
+
rename_keys.append((f"pretrained.model.blocks.{i}.attn.relative_position_index", f"backbone.encoder.layer.{i}.attention.attention.relative_position_bias.relative_position_index"))
|
| 97 |
+
|
| 98 |
+
# activation postprocessing (readout projections + resize blocks)
|
| 99 |
+
for i in range(4):
|
| 100 |
+
rename_keys.append((f"pretrained.act_postprocess{i+1}.0.project.0.weight", f"neck.reassemble_stage.readout_projects.{i}.0.weight"))
|
| 101 |
+
rename_keys.append((f"pretrained.act_postprocess{i+1}.0.project.0.bias", f"neck.reassemble_stage.readout_projects.{i}.0.bias"))
|
| 102 |
+
|
| 103 |
+
rename_keys.append((f"pretrained.act_postprocess{i+1}.3.weight", f"neck.reassemble_stage.layers.{i}.projection.weight"))
|
| 104 |
+
rename_keys.append((f"pretrained.act_postprocess{i+1}.3.bias", f"neck.reassemble_stage.layers.{i}.projection.bias"))
|
| 105 |
+
|
| 106 |
+
if i != 2:
|
| 107 |
+
rename_keys.append((f"pretrained.act_postprocess{i+1}.4.weight", f"neck.reassemble_stage.layers.{i}.resize.weight"))
|
| 108 |
+
rename_keys.append((f"pretrained.act_postprocess{i+1}.4.bias", f"neck.reassemble_stage.layers.{i}.resize.bias"))
|
| 109 |
+
|
| 110 |
+
# refinenet (tricky here)
|
| 111 |
+
mapping = {1:3, 2:2, 3:1, 4:0}
|
| 112 |
+
|
| 113 |
+
for i in range(1, 5):
|
| 114 |
+
j = mapping[i]
|
| 115 |
+
rename_keys.append((f"scratch.refinenet{i}.out_conv.weight", f"neck.fusion_stage.layers.{j}.projection.weight"))
|
| 116 |
+
rename_keys.append((f"scratch.refinenet{i}.out_conv.bias", f"neck.fusion_stage.layers.{j}.projection.bias"))
|
| 117 |
+
rename_keys.append((f"scratch.refinenet{i}.resConfUnit1.conv1.weight", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution1.weight"))
|
| 118 |
+
rename_keys.append((f"scratch.refinenet{i}.resConfUnit1.conv1.bias", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution1.bias"))
|
| 119 |
+
rename_keys.append((f"scratch.refinenet{i}.resConfUnit1.conv2.weight", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution2.weight"))
|
| 120 |
+
rename_keys.append((f"scratch.refinenet{i}.resConfUnit1.conv2.bias", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution2.bias"))
|
| 121 |
+
rename_keys.append((f"scratch.refinenet{i}.resConfUnit2.conv1.weight", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution1.weight"))
|
| 122 |
+
rename_keys.append((f"scratch.refinenet{i}.resConfUnit2.conv1.bias", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution1.bias"))
|
| 123 |
+
rename_keys.append((f"scratch.refinenet{i}.resConfUnit2.conv2.weight", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution2.weight"))
|
| 124 |
+
rename_keys.append((f"scratch.refinenet{i}.resConfUnit2.conv2.bias", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution2.bias"))
|
| 125 |
+
|
| 126 |
+
# scratch convolutions
|
| 127 |
+
for i in range(4):
|
| 128 |
+
rename_keys.append((f"scratch.layer{i+1}_rn.weight", f"neck.convs.{i}.weight"))
|
| 129 |
+
|
| 130 |
+
# head
|
| 131 |
+
for i in range(0, 5, 2):
|
| 132 |
+
rename_keys.append((f"scratch.output_conv.{i}.weight", f"head.head.{i}.weight"))
|
| 133 |
+
rename_keys.append((f"scratch.output_conv.{i}.bias", f"head.head.{i}.bias"))
|
| 134 |
+
|
| 135 |
+
return rename_keys
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def remove_ignore_keys_(state_dict):
|
| 139 |
+
ignore_keys = ["pretrained.model.head.weight", "pretrained.model.head.bias"]
|
| 140 |
+
for k in ignore_keys:
|
| 141 |
+
state_dict.pop(k, None)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# we split up the matrix of each encoder layer into queries, keys and values
|
| 145 |
+
def read_in_q_k_v(state_dict, config):
|
| 146 |
+
hidden_size = config.backbone_config.hidden_size
|
| 147 |
+
for i in range(config.backbone_config.num_hidden_layers):
|
| 148 |
+
# read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
|
| 149 |
+
in_proj_weight = state_dict.pop(f"pretrained.model.blocks.{i}.attn.qkv.weight")
|
| 150 |
+
q_bias = state_dict.pop(f"pretrained.model.blocks.{i}.attn.q_bias")
|
| 151 |
+
v_bias = state_dict.pop(f"pretrained.model.blocks.{i}.attn.v_bias")
|
| 152 |
+
# next, add query, keys and values (in that order) to the state dict
|
| 153 |
+
state_dict[f"backbone.encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[:hidden_size, :]
|
| 154 |
+
state_dict[f"backbone.encoder.layer.{i}.attention.attention.query.bias"] = q_bias
|
| 155 |
+
state_dict[f"backbone.encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
|
| 156 |
+
hidden_size : hidden_size * 2, :
|
| 157 |
+
]
|
| 158 |
+
state_dict[f"backbone.encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[-hidden_size:, :]
|
| 159 |
+
state_dict[f"backbone.encoder.layer.{i}.attention.attention.value.bias"] = v_bias
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def rename_key(dct, old, new):
|
| 163 |
+
val = dct.pop(old)
|
| 164 |
+
dct[new] = val
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# We will verify our results on an image of cute cats
|
| 168 |
+
def prepare_img():
|
| 169 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 170 |
+
im = Image.open(requests.get(url, stream=True).raw)
|
| 171 |
+
return im
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@torch.no_grad()
|
| 175 |
+
def convert_dpt_checkpoint(model_name, pytorch_dump_folder_path, push_to_hub):
|
| 176 |
+
"""
|
| 177 |
+
Copy/paste/tweak model's weights to our DPT structure.
|
| 178 |
+
"""
|
| 179 |
+
|
| 180 |
+
name_to_url = {
|
| 181 |
+
"dpt-beit-large-512": "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_large_512.pt",
|
| 182 |
+
"dpt-beit-large-384": "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_large_384.pt",
|
| 183 |
+
"dpt-beit-base-384": "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_base_384.pt",
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
# define DPT configuration based on URL
|
| 187 |
+
checkpoint_url = name_to_url[model_name]
|
| 188 |
+
config, image_size = get_dpt_config(model_name)
|
| 189 |
+
# load original state_dict from URL
|
| 190 |
+
state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")
|
| 191 |
+
# remove certain keys
|
| 192 |
+
remove_ignore_keys_(state_dict)
|
| 193 |
+
# rename keys
|
| 194 |
+
rename_keys = create_rename_keys(config)
|
| 195 |
+
for src, dest in rename_keys:
|
| 196 |
+
rename_key(state_dict, src, dest)
|
| 197 |
+
# read in qkv matrices
|
| 198 |
+
read_in_q_k_v(state_dict, config)
|
| 199 |
+
|
| 200 |
+
# load HuggingFace model
|
| 201 |
+
model = DPTForDepthEstimation(config)
|
| 202 |
+
missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
|
| 203 |
+
print("Missing keys:", missing_keys)
|
| 204 |
+
print("Unexpected keys:", unexpected_keys)
|
| 205 |
+
assert missing_keys == []
|
| 206 |
+
# assert unexpected_keys == ["pretrained.model.fc_norm.weight", "pretrained.model.fc_norm.bias"]
|
| 207 |
+
model.eval()
|
| 208 |
+
|
| 209 |
+
# Check outputs on an image
|
| 210 |
+
# We set `keep_aspect_ratio=False` as our current BEiT does not support arbitrary window sizes
|
| 211 |
+
processor = DPTImageProcessor(
|
| 212 |
+
size={"height": image_size, "width": image_size}, keep_aspect_ratio=False, ensure_multiple_of=32
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
image = prepare_img()
|
| 216 |
+
pixel_values = processor(image, return_tensors="pt").pixel_values
|
| 217 |
+
|
| 218 |
+
print("First values of pixel values:", pixel_values[0, 0, :3, :3])
|
| 219 |
+
print("Mean of pixel values:", pixel_values.mean().item())
|
| 220 |
+
print("Shape of pixel values:", pixel_values.shape)
|
| 221 |
+
|
| 222 |
+
import requests
|
| 223 |
+
from PIL import Image
|
| 224 |
+
from torchvision import transforms
|
| 225 |
+
|
| 226 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 227 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
| 228 |
+
|
| 229 |
+
transforms = transforms.Compose(
|
| 230 |
+
[
|
| 231 |
+
transforms.Resize((image_size, image_size)),
|
| 232 |
+
transforms.ToTensor(),
|
| 233 |
+
]
|
| 234 |
+
)
|
| 235 |
+
pixel_values = transforms(image).unsqueeze(0)
|
| 236 |
+
|
| 237 |
+
# forward pass
|
| 238 |
+
with torch.no_grad():
|
| 239 |
+
outputs = model(pixel_values)
|
| 240 |
+
|
| 241 |
+
predicted_depth = outputs.predicted_depth
|
| 242 |
+
|
| 243 |
+
print("Shape of predicted depth:", predicted_depth.shape)
|
| 244 |
+
print("First values of predicted depth:", predicted_depth[0, :3, :3])
|
| 245 |
+
|
| 246 |
+
# assert logits
|
| 247 |
+
# TODO there's still a small difference with the original logits
|
| 248 |
+
if model_name == "dpt-beit-large-512":
|
| 249 |
+
# OK, checked
|
| 250 |
+
expected_shape = torch.Size([1, 512, 512])
|
| 251 |
+
expected_slice = torch.tensor(
|
| 252 |
+
[[2804.6260, 2792.5708, 2812.9263], [2772.0288, 2780.1118, 2796.2529], [2748.1094, 2766.6558, 2766.9834]]
|
| 253 |
+
)
|
| 254 |
+
elif model_name == "dpt-beit-large-384":
|
| 255 |
+
# OK, checked
|
| 256 |
+
expected_shape = torch.Size([1, 384, 384])
|
| 257 |
+
expected_slice = torch.tensor(
|
| 258 |
+
[[1783.2273, 1780.5729, 1792.6453], [1759.9817, 1765.5359, 1778.5002], [1739.1633, 1754.7903, 1757.1990]],
|
| 259 |
+
)
|
| 260 |
+
elif model_name == "dpt-beit-base-384":
|
| 261 |
+
# OK, checked
|
| 262 |
+
expected_shape = torch.Size([1, 384, 384])
|
| 263 |
+
expected_slice = torch.tensor(
|
| 264 |
+
[[2898.4482, 2891.3750, 2904.8079], [2858.6685, 2877.2615, 2894.4507], [2842.1235, 2854.1023, 2861.6328]],
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
assert predicted_depth.shape == torch.Size(expected_shape)
|
| 268 |
+
assert torch.allclose(predicted_depth[0, :3, :3], expected_slice)
|
| 269 |
+
print("Looks ok!")
|
| 270 |
+
|
| 271 |
+
if pytorch_dump_folder_path is not None:
|
| 272 |
+
Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
|
| 273 |
+
print(f"Saving model and processor to {pytorch_dump_folder_path}")
|
| 274 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 275 |
+
processor.save_pretrained(pytorch_dump_folder_path)
|
| 276 |
+
|
| 277 |
+
if push_to_hub:
|
| 278 |
+
print("Pushing model and processor to hub...")
|
| 279 |
+
model.push_to_hub(repo_id=f"nielsr/{model_name}")
|
| 280 |
+
processor.push_to_hub(repo_id=f"nielsr/{model_name}")
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
if __name__ == "__main__":
|
| 284 |
+
parser = argparse.ArgumentParser()
|
| 285 |
+
# Required parameters
|
| 286 |
+
parser.add_argument(
|
| 287 |
+
"--model_name",
|
| 288 |
+
default="dpt-beit-large-512",
|
| 289 |
+
type=str,
|
| 290 |
+
choices=["dpt-beit-large-512", "dpt-beit-large-384", "dpt-beit-base-384"],
|
| 291 |
+
help="Name of the model you'd like to convert.",
|
| 292 |
+
)
|
| 293 |
+
parser.add_argument(
|
| 294 |
+
"--pytorch_dump_folder_path",
|
| 295 |
+
default=None,
|
| 296 |
+
type=str,
|
| 297 |
+
help="Path to the output PyTorch model directory.",
|
| 298 |
+
)
|
| 299 |
+
parser.add_argument(
|
| 300 |
+
"--push_to_hub",
|
| 301 |
+
action="store_true",
|
| 302 |
+
help="Whether to push the model to the hub after conversion.",
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
args = parser.parse_args()
|
| 306 |
+
convert_dpt_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__init__.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import (
|
| 17 |
+
OptionalDependencyNotAvailable,
|
| 18 |
+
_LazyModule,
|
| 19 |
+
is_sentencepiece_available,
|
| 20 |
+
is_tokenizers_available,
|
| 21 |
+
is_torch_available,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
_import_structure = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]}
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
if not is_sentencepiece_available():
|
| 29 |
+
raise OptionalDependencyNotAvailable()
|
| 30 |
+
except OptionalDependencyNotAvailable:
|
| 31 |
+
pass
|
| 32 |
+
else:
|
| 33 |
+
_import_structure["tokenization_fnet"] = ["FNetTokenizer"]
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
if not is_tokenizers_available():
|
| 37 |
+
raise OptionalDependencyNotAvailable()
|
| 38 |
+
except OptionalDependencyNotAvailable:
|
| 39 |
+
pass
|
| 40 |
+
else:
|
| 41 |
+
_import_structure["tokenization_fnet_fast"] = ["FNetTokenizerFast"]
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
if not is_torch_available():
|
| 45 |
+
raise OptionalDependencyNotAvailable()
|
| 46 |
+
except OptionalDependencyNotAvailable:
|
| 47 |
+
pass
|
| 48 |
+
else:
|
| 49 |
+
_import_structure["modeling_fnet"] = [
|
| 50 |
+
"FNET_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 51 |
+
"FNetForMaskedLM",
|
| 52 |
+
"FNetForMultipleChoice",
|
| 53 |
+
"FNetForNextSentencePrediction",
|
| 54 |
+
"FNetForPreTraining",
|
| 55 |
+
"FNetForQuestionAnswering",
|
| 56 |
+
"FNetForSequenceClassification",
|
| 57 |
+
"FNetForTokenClassification",
|
| 58 |
+
"FNetLayer",
|
| 59 |
+
"FNetModel",
|
| 60 |
+
"FNetPreTrainedModel",
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
if TYPE_CHECKING:
|
| 65 |
+
from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
if not is_sentencepiece_available():
|
| 69 |
+
raise OptionalDependencyNotAvailable()
|
| 70 |
+
except OptionalDependencyNotAvailable:
|
| 71 |
+
pass
|
| 72 |
+
else:
|
| 73 |
+
from .tokenization_fnet import FNetTokenizer
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
if not is_tokenizers_available():
|
| 77 |
+
raise OptionalDependencyNotAvailable()
|
| 78 |
+
except OptionalDependencyNotAvailable:
|
| 79 |
+
pass
|
| 80 |
+
else:
|
| 81 |
+
from .tokenization_fnet_fast import FNetTokenizerFast
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
if not is_torch_available():
|
| 85 |
+
raise OptionalDependencyNotAvailable()
|
| 86 |
+
except OptionalDependencyNotAvailable:
|
| 87 |
+
pass
|
| 88 |
+
else:
|
| 89 |
+
from .modeling_fnet import (
|
| 90 |
+
FNET_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 91 |
+
FNetForMaskedLM,
|
| 92 |
+
FNetForMultipleChoice,
|
| 93 |
+
FNetForNextSentencePrediction,
|
| 94 |
+
FNetForPreTraining,
|
| 95 |
+
FNetForQuestionAnswering,
|
| 96 |
+
FNetForSequenceClassification,
|
| 97 |
+
FNetForTokenClassification,
|
| 98 |
+
FNetLayer,
|
| 99 |
+
FNetModel,
|
| 100 |
+
FNetPreTrainedModel,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
else:
|
| 105 |
+
import sys
|
| 106 |
+
|
| 107 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.55 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/configuration_fnet.cpython-310.pyc
ADDED
|
Binary file (5.09 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/convert_fnet_original_flax_checkpoint_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (3.85 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/modeling_fnet.cpython-310.pyc
ADDED
|
Binary file (35.9 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet.cpython-310.pyc
ADDED
|
Binary file (12.9 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet_fast.cpython-310.pyc
ADDED
|
Binary file (7.51 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert FNet checkpoint."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from flax.training.checkpoints import restore_checkpoint
|
| 22 |
+
|
| 23 |
+
from transformers import FNetConfig, FNetForPreTraining
|
| 24 |
+
from transformers.utils import logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logging.set_verbosity_info()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def convert_flax_checkpoint_to_pytorch(flax_checkpoint_path, fnet_config_file, save_path):
|
| 31 |
+
# Initialise PyTorch model
|
| 32 |
+
config = FNetConfig.from_json_file(fnet_config_file)
|
| 33 |
+
print(f"Building PyTorch model from configuration: {config}")
|
| 34 |
+
fnet_pretraining_model = FNetForPreTraining(config)
|
| 35 |
+
|
| 36 |
+
checkpoint_dict = restore_checkpoint(flax_checkpoint_path, None)
|
| 37 |
+
pretrained_model_params = checkpoint_dict["target"]
|
| 38 |
+
|
| 39 |
+
# Embeddings
|
| 40 |
+
# Position IDs
|
| 41 |
+
state_dict = fnet_pretraining_model.state_dict()
|
| 42 |
+
|
| 43 |
+
position_ids = state_dict["fnet.embeddings.position_ids"]
|
| 44 |
+
new_state_dict = {"fnet.embeddings.position_ids": position_ids}
|
| 45 |
+
# Embedding Layers
|
| 46 |
+
new_state_dict["fnet.embeddings.word_embeddings.weight"] = torch.tensor(
|
| 47 |
+
pretrained_model_params["encoder"]["embedder"]["word"]["embedding"]
|
| 48 |
+
)
|
| 49 |
+
new_state_dict["fnet.embeddings.position_embeddings.weight"] = torch.tensor(
|
| 50 |
+
pretrained_model_params["encoder"]["embedder"]["position"]["embedding"][0]
|
| 51 |
+
)
|
| 52 |
+
new_state_dict["fnet.embeddings.token_type_embeddings.weight"] = torch.tensor(
|
| 53 |
+
pretrained_model_params["encoder"]["embedder"]["type"]["embedding"]
|
| 54 |
+
)
|
| 55 |
+
new_state_dict["fnet.embeddings.projection.weight"] = torch.tensor(
|
| 56 |
+
pretrained_model_params["encoder"]["embedder"]["hidden_mapping_in"]["kernel"]
|
| 57 |
+
).T
|
| 58 |
+
new_state_dict["fnet.embeddings.projection.bias"] = torch.tensor(
|
| 59 |
+
pretrained_model_params["encoder"]["embedder"]["hidden_mapping_in"]["bias"]
|
| 60 |
+
)
|
| 61 |
+
new_state_dict["fnet.embeddings.LayerNorm.weight"] = torch.tensor(
|
| 62 |
+
pretrained_model_params["encoder"]["embedder"]["layer_norm"]["scale"]
|
| 63 |
+
)
|
| 64 |
+
new_state_dict["fnet.embeddings.LayerNorm.bias"] = torch.tensor(
|
| 65 |
+
pretrained_model_params["encoder"]["embedder"]["layer_norm"]["bias"]
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
# Encoder Layers
|
| 69 |
+
for layer in range(config.num_hidden_layers):
|
| 70 |
+
new_state_dict[f"fnet.encoder.layer.{layer}.fourier.output.LayerNorm.weight"] = torch.tensor(
|
| 71 |
+
pretrained_model_params["encoder"][f"encoder_{layer}"]["mixing_layer_norm"]["scale"]
|
| 72 |
+
)
|
| 73 |
+
new_state_dict[f"fnet.encoder.layer.{layer}.fourier.output.LayerNorm.bias"] = torch.tensor(
|
| 74 |
+
pretrained_model_params["encoder"][f"encoder_{layer}"]["mixing_layer_norm"]["bias"]
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
new_state_dict[f"fnet.encoder.layer.{layer}.intermediate.dense.weight"] = torch.tensor(
|
| 78 |
+
pretrained_model_params["encoder"][f"feed_forward_{layer}"]["intermediate"]["kernel"]
|
| 79 |
+
).T
|
| 80 |
+
new_state_dict[f"fnet.encoder.layer.{layer}.intermediate.dense.bias"] = torch.tensor(
|
| 81 |
+
pretrained_model_params["encoder"][f"feed_forward_{layer}"]["intermediate"]["bias"]
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
new_state_dict[f"fnet.encoder.layer.{layer}.output.dense.weight"] = torch.tensor(
|
| 85 |
+
pretrained_model_params["encoder"][f"feed_forward_{layer}"]["output"]["kernel"]
|
| 86 |
+
).T
|
| 87 |
+
new_state_dict[f"fnet.encoder.layer.{layer}.output.dense.bias"] = torch.tensor(
|
| 88 |
+
pretrained_model_params["encoder"][f"feed_forward_{layer}"]["output"]["bias"]
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
new_state_dict[f"fnet.encoder.layer.{layer}.output.LayerNorm.weight"] = torch.tensor(
|
| 92 |
+
pretrained_model_params["encoder"][f"encoder_{layer}"]["output_layer_norm"]["scale"]
|
| 93 |
+
)
|
| 94 |
+
new_state_dict[f"fnet.encoder.layer.{layer}.output.LayerNorm.bias"] = torch.tensor(
|
| 95 |
+
pretrained_model_params["encoder"][f"encoder_{layer}"]["output_layer_norm"]["bias"]
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
# Pooler Layers
|
| 99 |
+
new_state_dict["fnet.pooler.dense.weight"] = torch.tensor(pretrained_model_params["encoder"]["pooler"]["kernel"]).T
|
| 100 |
+
new_state_dict["fnet.pooler.dense.bias"] = torch.tensor(pretrained_model_params["encoder"]["pooler"]["bias"])
|
| 101 |
+
|
| 102 |
+
# Masked LM Layers
|
| 103 |
+
new_state_dict["cls.predictions.transform.dense.weight"] = torch.tensor(
|
| 104 |
+
pretrained_model_params["predictions_dense"]["kernel"]
|
| 105 |
+
).T
|
| 106 |
+
new_state_dict["cls.predictions.transform.dense.bias"] = torch.tensor(
|
| 107 |
+
pretrained_model_params["predictions_dense"]["bias"]
|
| 108 |
+
)
|
| 109 |
+
new_state_dict["cls.predictions.transform.LayerNorm.weight"] = torch.tensor(
|
| 110 |
+
pretrained_model_params["predictions_layer_norm"]["scale"]
|
| 111 |
+
)
|
| 112 |
+
new_state_dict["cls.predictions.transform.LayerNorm.bias"] = torch.tensor(
|
| 113 |
+
pretrained_model_params["predictions_layer_norm"]["bias"]
|
| 114 |
+
)
|
| 115 |
+
new_state_dict["cls.predictions.decoder.weight"] = torch.tensor(
|
| 116 |
+
pretrained_model_params["encoder"]["embedder"]["word"]["embedding"]
|
| 117 |
+
)
|
| 118 |
+
new_state_dict["cls.predictions.decoder.bias"] = torch.tensor(
|
| 119 |
+
pretrained_model_params["predictions_output"]["output_bias"]
|
| 120 |
+
)
|
| 121 |
+
new_state_dict["cls.predictions.bias"] = torch.tensor(pretrained_model_params["predictions_output"]["output_bias"])
|
| 122 |
+
|
| 123 |
+
# Seq Relationship Layers
|
| 124 |
+
new_state_dict["cls.seq_relationship.weight"] = torch.tensor(
|
| 125 |
+
pretrained_model_params["classification"]["output_kernel"]
|
| 126 |
+
)
|
| 127 |
+
new_state_dict["cls.seq_relationship.bias"] = torch.tensor(
|
| 128 |
+
pretrained_model_params["classification"]["output_bias"]
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Load State Dict
|
| 132 |
+
fnet_pretraining_model.load_state_dict(new_state_dict)
|
| 133 |
+
|
| 134 |
+
# Save PreTrained
|
| 135 |
+
print(f"Saving pretrained model to {save_path}")
|
| 136 |
+
fnet_pretraining_model.save_pretrained(save_path)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
if __name__ == "__main__":
|
| 140 |
+
parser = argparse.ArgumentParser()
|
| 141 |
+
# Required parameters
|
| 142 |
+
parser.add_argument(
|
| 143 |
+
"--flax_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
|
| 144 |
+
)
|
| 145 |
+
parser.add_argument(
|
| 146 |
+
"--fnet_config_file",
|
| 147 |
+
default=None,
|
| 148 |
+
type=str,
|
| 149 |
+
required=True,
|
| 150 |
+
help=(
|
| 151 |
+
"The config json file corresponding to the pre-trained FNet model. \n"
|
| 152 |
+
"This specifies the model architecture."
|
| 153 |
+
),
|
| 154 |
+
)
|
| 155 |
+
parser.add_argument("--save_path", default=None, type=str, required=True, help="Path to the output model.")
|
| 156 |
+
args = parser.parse_args()
|
| 157 |
+
convert_flax_checkpoint_to_pytorch(args.flax_checkpoint_path, args.fnet_config_file, args.save_path)
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/modeling_fnet.py
ADDED
|
@@ -0,0 +1,1185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 Google 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 FNet model."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from functools import partial
|
| 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 ...utils import is_scipy_available
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_scipy_available():
|
| 31 |
+
from scipy import linalg
|
| 32 |
+
|
| 33 |
+
from ...activations import ACT2FN
|
| 34 |
+
from ...modeling_outputs import (
|
| 35 |
+
BaseModelOutput,
|
| 36 |
+
BaseModelOutputWithPooling,
|
| 37 |
+
MaskedLMOutput,
|
| 38 |
+
ModelOutput,
|
| 39 |
+
MultipleChoiceModelOutput,
|
| 40 |
+
NextSentencePredictorOutput,
|
| 41 |
+
QuestionAnsweringModelOutput,
|
| 42 |
+
SequenceClassifierOutput,
|
| 43 |
+
TokenClassifierOutput,
|
| 44 |
+
)
|
| 45 |
+
from ...modeling_utils import PreTrainedModel
|
| 46 |
+
from ...pytorch_utils import apply_chunking_to_forward
|
| 47 |
+
from ...utils import (
|
| 48 |
+
add_code_sample_docstrings,
|
| 49 |
+
add_start_docstrings,
|
| 50 |
+
add_start_docstrings_to_model_forward,
|
| 51 |
+
logging,
|
| 52 |
+
replace_return_docstrings,
|
| 53 |
+
)
|
| 54 |
+
from .configuration_fnet import FNetConfig
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
logger = logging.get_logger(__name__)
|
| 58 |
+
|
| 59 |
+
_CHECKPOINT_FOR_DOC = "google/fnet-base"
|
| 60 |
+
_CONFIG_FOR_DOC = "FNetConfig"
|
| 61 |
+
|
| 62 |
+
FNET_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 63 |
+
"google/fnet-base",
|
| 64 |
+
"google/fnet-large",
|
| 65 |
+
# See all FNet models at https://huggingface.co/models?filter=fnet
|
| 66 |
+
]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# Adapted from https://github.com/google-research/google-research/blob/master/f_net/fourier.py
|
| 70 |
+
def _two_dim_matmul(x, matrix_dim_one, matrix_dim_two):
|
| 71 |
+
"""Applies 2D matrix multiplication to 3D input arrays."""
|
| 72 |
+
seq_length = x.shape[1]
|
| 73 |
+
matrix_dim_one = matrix_dim_one[:seq_length, :seq_length]
|
| 74 |
+
x = x.type(torch.complex64)
|
| 75 |
+
return torch.einsum("bij,jk,ni->bnk", x, matrix_dim_two, matrix_dim_one)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# # Adapted from https://github.com/google-research/google-research/blob/master/f_net/fourier.py
|
| 79 |
+
def two_dim_matmul(x, matrix_dim_one, matrix_dim_two):
|
| 80 |
+
return _two_dim_matmul(x, matrix_dim_one, matrix_dim_two)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# Adapted from https://github.com/google-research/google-research/blob/master/f_net/fourier.py
|
| 84 |
+
def fftn(x):
|
| 85 |
+
"""
|
| 86 |
+
Applies n-dimensional Fast Fourier Transform (FFT) to input array.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
x: Input n-dimensional array.
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
n-dimensional Fourier transform of input n-dimensional array.
|
| 93 |
+
"""
|
| 94 |
+
out = x
|
| 95 |
+
for axis in reversed(range(x.ndim)[1:]): # We don't need to apply FFT to last axis
|
| 96 |
+
out = torch.fft.fft(out, axis=axis)
|
| 97 |
+
return out
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class FNetEmbeddings(nn.Module):
|
| 101 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 102 |
+
|
| 103 |
+
def __init__(self, config):
|
| 104 |
+
super().__init__()
|
| 105 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 106 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 107 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 108 |
+
|
| 109 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 110 |
+
# any TensorFlow checkpoint file
|
| 111 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 112 |
+
# NOTE: This is the project layer and will be needed. The original code allows for different embedding and different model dimensions.
|
| 113 |
+
self.projection = nn.Linear(config.hidden_size, config.hidden_size)
|
| 114 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 115 |
+
|
| 116 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 117 |
+
self.register_buffer(
|
| 118 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
self.register_buffer(
|
| 122 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
|
| 126 |
+
if input_ids is not None:
|
| 127 |
+
input_shape = input_ids.size()
|
| 128 |
+
else:
|
| 129 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 130 |
+
|
| 131 |
+
seq_length = input_shape[1]
|
| 132 |
+
|
| 133 |
+
if position_ids is None:
|
| 134 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 135 |
+
|
| 136 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 137 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 138 |
+
# issue #5664
|
| 139 |
+
if token_type_ids is None:
|
| 140 |
+
if hasattr(self, "token_type_ids"):
|
| 141 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 142 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 143 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 144 |
+
else:
|
| 145 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 146 |
+
|
| 147 |
+
if inputs_embeds is None:
|
| 148 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 149 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 150 |
+
|
| 151 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 152 |
+
|
| 153 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 154 |
+
embeddings += position_embeddings
|
| 155 |
+
embeddings = self.LayerNorm(embeddings)
|
| 156 |
+
embeddings = self.projection(embeddings)
|
| 157 |
+
embeddings = self.dropout(embeddings)
|
| 158 |
+
return embeddings
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class FNetBasicFourierTransform(nn.Module):
|
| 162 |
+
def __init__(self, config):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self._init_fourier_transform(config)
|
| 165 |
+
|
| 166 |
+
def _init_fourier_transform(self, config):
|
| 167 |
+
if not config.use_tpu_fourier_optimizations:
|
| 168 |
+
self.fourier_transform = partial(torch.fft.fftn, dim=(1, 2))
|
| 169 |
+
elif config.max_position_embeddings <= 4096:
|
| 170 |
+
if is_scipy_available():
|
| 171 |
+
self.register_buffer(
|
| 172 |
+
"dft_mat_hidden", torch.tensor(linalg.dft(config.hidden_size), dtype=torch.complex64)
|
| 173 |
+
)
|
| 174 |
+
self.register_buffer(
|
| 175 |
+
"dft_mat_seq", torch.tensor(linalg.dft(config.tpu_short_seq_length), dtype=torch.complex64)
|
| 176 |
+
)
|
| 177 |
+
self.fourier_transform = partial(
|
| 178 |
+
two_dim_matmul, matrix_dim_one=self.dft_mat_seq, matrix_dim_two=self.dft_mat_hidden
|
| 179 |
+
)
|
| 180 |
+
else:
|
| 181 |
+
logging.warning(
|
| 182 |
+
"SciPy is needed for DFT matrix calculation and is not found. Using TPU optimized fast fourier"
|
| 183 |
+
" transform instead."
|
| 184 |
+
)
|
| 185 |
+
self.fourier_transform = fftn
|
| 186 |
+
else:
|
| 187 |
+
self.fourier_transform = fftn
|
| 188 |
+
|
| 189 |
+
def forward(self, hidden_states):
|
| 190 |
+
# NOTE: We do not use torch.vmap as it is not integrated into PyTorch stable versions.
|
| 191 |
+
# Interested users can modify the code to use vmap from the nightly versions, getting the vmap from here:
|
| 192 |
+
# https://pytorch.org/docs/master/generated/torch.vmap.html. Note that fourier transform methods will need
|
| 193 |
+
# change accordingly.
|
| 194 |
+
|
| 195 |
+
outputs = self.fourier_transform(hidden_states).real
|
| 196 |
+
return (outputs,)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class FNetBasicOutput(nn.Module):
|
| 200 |
+
def __init__(self, config):
|
| 201 |
+
super().__init__()
|
| 202 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 203 |
+
|
| 204 |
+
def forward(self, hidden_states, input_tensor):
|
| 205 |
+
hidden_states = self.LayerNorm(input_tensor + hidden_states)
|
| 206 |
+
return hidden_states
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class FNetFourierTransform(nn.Module):
|
| 210 |
+
def __init__(self, config):
|
| 211 |
+
super().__init__()
|
| 212 |
+
self.self = FNetBasicFourierTransform(config)
|
| 213 |
+
self.output = FNetBasicOutput(config)
|
| 214 |
+
|
| 215 |
+
def forward(self, hidden_states):
|
| 216 |
+
self_outputs = self.self(hidden_states)
|
| 217 |
+
fourier_output = self.output(self_outputs[0], hidden_states)
|
| 218 |
+
outputs = (fourier_output,)
|
| 219 |
+
return outputs
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->FNet
|
| 223 |
+
class FNetIntermediate(nn.Module):
|
| 224 |
+
def __init__(self, config):
|
| 225 |
+
super().__init__()
|
| 226 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 227 |
+
if isinstance(config.hidden_act, str):
|
| 228 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 229 |
+
else:
|
| 230 |
+
self.intermediate_act_fn = config.hidden_act
|
| 231 |
+
|
| 232 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 233 |
+
hidden_states = self.dense(hidden_states)
|
| 234 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 235 |
+
return hidden_states
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->FNet
|
| 239 |
+
class FNetOutput(nn.Module):
|
| 240 |
+
def __init__(self, config):
|
| 241 |
+
super().__init__()
|
| 242 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 243 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 244 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 245 |
+
|
| 246 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 247 |
+
hidden_states = self.dense(hidden_states)
|
| 248 |
+
hidden_states = self.dropout(hidden_states)
|
| 249 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 250 |
+
return hidden_states
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class FNetLayer(nn.Module):
|
| 254 |
+
def __init__(self, config):
|
| 255 |
+
super().__init__()
|
| 256 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 257 |
+
self.seq_len_dim = 1 # The dimension which has the sequence length
|
| 258 |
+
self.fourier = FNetFourierTransform(config)
|
| 259 |
+
self.intermediate = FNetIntermediate(config)
|
| 260 |
+
self.output = FNetOutput(config)
|
| 261 |
+
|
| 262 |
+
def forward(self, hidden_states):
|
| 263 |
+
self_fourier_outputs = self.fourier(hidden_states)
|
| 264 |
+
fourier_output = self_fourier_outputs[0]
|
| 265 |
+
|
| 266 |
+
layer_output = apply_chunking_to_forward(
|
| 267 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, fourier_output
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
outputs = (layer_output,)
|
| 271 |
+
|
| 272 |
+
return outputs
|
| 273 |
+
|
| 274 |
+
def feed_forward_chunk(self, fourier_output):
|
| 275 |
+
intermediate_output = self.intermediate(fourier_output)
|
| 276 |
+
layer_output = self.output(intermediate_output, fourier_output)
|
| 277 |
+
return layer_output
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class FNetEncoder(nn.Module):
|
| 281 |
+
def __init__(self, config):
|
| 282 |
+
super().__init__()
|
| 283 |
+
self.config = config
|
| 284 |
+
self.layer = nn.ModuleList([FNetLayer(config) for _ in range(config.num_hidden_layers)])
|
| 285 |
+
self.gradient_checkpointing = False
|
| 286 |
+
|
| 287 |
+
def forward(self, hidden_states, output_hidden_states=False, return_dict=True):
|
| 288 |
+
all_hidden_states = () if output_hidden_states else None
|
| 289 |
+
|
| 290 |
+
for i, layer_module in enumerate(self.layer):
|
| 291 |
+
if output_hidden_states:
|
| 292 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 293 |
+
|
| 294 |
+
if self.gradient_checkpointing and self.training:
|
| 295 |
+
layer_outputs = self._gradient_checkpointing_func(layer_module.__call__, hidden_states)
|
| 296 |
+
else:
|
| 297 |
+
layer_outputs = layer_module(hidden_states)
|
| 298 |
+
|
| 299 |
+
hidden_states = layer_outputs[0]
|
| 300 |
+
|
| 301 |
+
if output_hidden_states:
|
| 302 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 303 |
+
|
| 304 |
+
if not return_dict:
|
| 305 |
+
return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
|
| 306 |
+
|
| 307 |
+
return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->FNet
|
| 311 |
+
class FNetPooler(nn.Module):
|
| 312 |
+
def __init__(self, config):
|
| 313 |
+
super().__init__()
|
| 314 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 315 |
+
self.activation = nn.Tanh()
|
| 316 |
+
|
| 317 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 318 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 319 |
+
# to the first token.
|
| 320 |
+
first_token_tensor = hidden_states[:, 0]
|
| 321 |
+
pooled_output = self.dense(first_token_tensor)
|
| 322 |
+
pooled_output = self.activation(pooled_output)
|
| 323 |
+
return pooled_output
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->FNet
|
| 327 |
+
class FNetPredictionHeadTransform(nn.Module):
|
| 328 |
+
def __init__(self, config):
|
| 329 |
+
super().__init__()
|
| 330 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 331 |
+
if isinstance(config.hidden_act, str):
|
| 332 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 333 |
+
else:
|
| 334 |
+
self.transform_act_fn = config.hidden_act
|
| 335 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 336 |
+
|
| 337 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 338 |
+
hidden_states = self.dense(hidden_states)
|
| 339 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 340 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 341 |
+
return hidden_states
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class FNetLMPredictionHead(nn.Module):
|
| 345 |
+
def __init__(self, config):
|
| 346 |
+
super().__init__()
|
| 347 |
+
self.transform = FNetPredictionHeadTransform(config)
|
| 348 |
+
|
| 349 |
+
# The output weights are the same as the input embeddings, but there is
|
| 350 |
+
# an output-only bias for each token.
|
| 351 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
|
| 352 |
+
|
| 353 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 354 |
+
self.decoder.bias = self.bias
|
| 355 |
+
|
| 356 |
+
def forward(self, hidden_states):
|
| 357 |
+
hidden_states = self.transform(hidden_states)
|
| 358 |
+
hidden_states = self.decoder(hidden_states)
|
| 359 |
+
return hidden_states
|
| 360 |
+
|
| 361 |
+
def _tie_weights(self):
|
| 362 |
+
# To tie those two weights if they get disconnected (on TPU or when the bias is resized)
|
| 363 |
+
self.bias = self.decoder.bias
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
class FNetOnlyMLMHead(nn.Module):
|
| 367 |
+
def __init__(self, config):
|
| 368 |
+
super().__init__()
|
| 369 |
+
self.predictions = FNetLMPredictionHead(config)
|
| 370 |
+
|
| 371 |
+
def forward(self, sequence_output):
|
| 372 |
+
prediction_scores = self.predictions(sequence_output)
|
| 373 |
+
return prediction_scores
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
# Copied from transformers.models.bert.modeling_bert.BertOnlyNSPHead with Bert->FNet
|
| 377 |
+
class FNetOnlyNSPHead(nn.Module):
|
| 378 |
+
def __init__(self, config):
|
| 379 |
+
super().__init__()
|
| 380 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
| 381 |
+
|
| 382 |
+
def forward(self, pooled_output):
|
| 383 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
| 384 |
+
return seq_relationship_score
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
# Copied from transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert->FNet
|
| 388 |
+
class FNetPreTrainingHeads(nn.Module):
|
| 389 |
+
def __init__(self, config):
|
| 390 |
+
super().__init__()
|
| 391 |
+
self.predictions = FNetLMPredictionHead(config)
|
| 392 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
| 393 |
+
|
| 394 |
+
def forward(self, sequence_output, pooled_output):
|
| 395 |
+
prediction_scores = self.predictions(sequence_output)
|
| 396 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
| 397 |
+
return prediction_scores, seq_relationship_score
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
class FNetPreTrainedModel(PreTrainedModel):
|
| 401 |
+
"""
|
| 402 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 403 |
+
models.
|
| 404 |
+
"""
|
| 405 |
+
|
| 406 |
+
config_class = FNetConfig
|
| 407 |
+
base_model_prefix = "fnet"
|
| 408 |
+
supports_gradient_checkpointing = True
|
| 409 |
+
|
| 410 |
+
def _init_weights(self, module):
|
| 411 |
+
"""Initialize the weights"""
|
| 412 |
+
if isinstance(module, nn.Linear):
|
| 413 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 414 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 415 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 416 |
+
# NOTE: Original code uses same initialization as weights for biases as well.
|
| 417 |
+
if module.bias is not None:
|
| 418 |
+
module.bias.data.zero_()
|
| 419 |
+
elif isinstance(module, nn.Embedding):
|
| 420 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 421 |
+
if module.padding_idx is not None:
|
| 422 |
+
module.weight.data[module.padding_idx].zero_()
|
| 423 |
+
elif isinstance(module, nn.LayerNorm):
|
| 424 |
+
module.bias.data.zero_()
|
| 425 |
+
module.weight.data.fill_(1.0)
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
@dataclass
|
| 429 |
+
class FNetForPreTrainingOutput(ModelOutput):
|
| 430 |
+
"""
|
| 431 |
+
Output type of [`FNetForPreTraining`].
|
| 432 |
+
|
| 433 |
+
Args:
|
| 434 |
+
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
| 435 |
+
Total loss as the sum of the masked language modeling loss and the next sequence prediction
|
| 436 |
+
(classification) loss.
|
| 437 |
+
prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 438 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 439 |
+
seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
|
| 440 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
| 441 |
+
before SoftMax).
|
| 442 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 443 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 444 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 445 |
+
plus the initial embedding outputs.
|
| 446 |
+
"""
|
| 447 |
+
|
| 448 |
+
loss: Optional[torch.FloatTensor] = None
|
| 449 |
+
prediction_logits: torch.FloatTensor = None
|
| 450 |
+
seq_relationship_logits: torch.FloatTensor = None
|
| 451 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
FNET_START_DOCSTRING = r"""
|
| 455 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
|
| 456 |
+
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 457 |
+
behavior.
|
| 458 |
+
|
| 459 |
+
Parameters:
|
| 460 |
+
config ([`FNetConfig`]): Model configuration class with all the parameters of the model.
|
| 461 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 462 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 463 |
+
"""
|
| 464 |
+
|
| 465 |
+
FNET_INPUTS_DOCSTRING = r"""
|
| 466 |
+
Args:
|
| 467 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
| 468 |
+
Indices of input sequence tokens in the vocabulary.
|
| 469 |
+
|
| 470 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 471 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 472 |
+
|
| 473 |
+
[What are input IDs?](../glossary#input-ids)
|
| 474 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 475 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 476 |
+
1]`:
|
| 477 |
+
|
| 478 |
+
- 0 corresponds to a *sentence A* token,
|
| 479 |
+
- 1 corresponds to a *sentence B* token.
|
| 480 |
+
|
| 481 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 482 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 483 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 484 |
+
config.max_position_embeddings - 1]`.
|
| 485 |
+
|
| 486 |
+
[What are position IDs?](../glossary#position-ids)
|
| 487 |
+
|
| 488 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 489 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 490 |
+
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
|
| 491 |
+
model's internal embedding lookup matrix.
|
| 492 |
+
output_hidden_states (`bool`, *optional*):
|
| 493 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 494 |
+
more detail.
|
| 495 |
+
return_dict (`bool`, *optional*):
|
| 496 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 497 |
+
"""
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
@add_start_docstrings(
|
| 501 |
+
"The bare FNet Model transformer outputting raw hidden-states without any specific head on top.",
|
| 502 |
+
FNET_START_DOCSTRING,
|
| 503 |
+
)
|
| 504 |
+
class FNetModel(FNetPreTrainedModel):
|
| 505 |
+
"""
|
| 506 |
+
|
| 507 |
+
The model can behave as an encoder, following the architecture described in [FNet: Mixing Tokens with Fourier
|
| 508 |
+
Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
|
| 509 |
+
|
| 510 |
+
"""
|
| 511 |
+
|
| 512 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 513 |
+
super().__init__(config)
|
| 514 |
+
self.config = config
|
| 515 |
+
|
| 516 |
+
self.embeddings = FNetEmbeddings(config)
|
| 517 |
+
self.encoder = FNetEncoder(config)
|
| 518 |
+
|
| 519 |
+
self.pooler = FNetPooler(config) if add_pooling_layer else None
|
| 520 |
+
|
| 521 |
+
# Initialize weights and apply final processing
|
| 522 |
+
self.post_init()
|
| 523 |
+
|
| 524 |
+
def get_input_embeddings(self):
|
| 525 |
+
return self.embeddings.word_embeddings
|
| 526 |
+
|
| 527 |
+
def set_input_embeddings(self, value):
|
| 528 |
+
self.embeddings.word_embeddings = value
|
| 529 |
+
|
| 530 |
+
@add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 531 |
+
@add_code_sample_docstrings(
|
| 532 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 533 |
+
output_type=BaseModelOutput,
|
| 534 |
+
config_class=_CONFIG_FOR_DOC,
|
| 535 |
+
)
|
| 536 |
+
def forward(
|
| 537 |
+
self,
|
| 538 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 539 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 540 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 541 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 542 |
+
output_hidden_states: Optional[bool] = None,
|
| 543 |
+
return_dict: Optional[bool] = None,
|
| 544 |
+
) -> Union[tuple, BaseModelOutput]:
|
| 545 |
+
output_hidden_states = (
|
| 546 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 547 |
+
)
|
| 548 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 549 |
+
|
| 550 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 551 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 552 |
+
elif input_ids is not None:
|
| 553 |
+
input_shape = input_ids.size()
|
| 554 |
+
batch_size, seq_length = input_shape
|
| 555 |
+
elif inputs_embeds is not None:
|
| 556 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 557 |
+
batch_size, seq_length = input_shape
|
| 558 |
+
else:
|
| 559 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 560 |
+
|
| 561 |
+
if (
|
| 562 |
+
self.config.use_tpu_fourier_optimizations
|
| 563 |
+
and seq_length <= 4096
|
| 564 |
+
and self.config.tpu_short_seq_length != seq_length
|
| 565 |
+
):
|
| 566 |
+
raise ValueError(
|
| 567 |
+
"The `tpu_short_seq_length` in FNetConfig should be set equal to the sequence length being passed to"
|
| 568 |
+
" the model when using TPU optimizations."
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 572 |
+
|
| 573 |
+
if token_type_ids is None:
|
| 574 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 575 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 576 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 577 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 578 |
+
else:
|
| 579 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 580 |
+
|
| 581 |
+
embedding_output = self.embeddings(
|
| 582 |
+
input_ids=input_ids,
|
| 583 |
+
position_ids=position_ids,
|
| 584 |
+
token_type_ids=token_type_ids,
|
| 585 |
+
inputs_embeds=inputs_embeds,
|
| 586 |
+
)
|
| 587 |
+
encoder_outputs = self.encoder(
|
| 588 |
+
embedding_output,
|
| 589 |
+
output_hidden_states=output_hidden_states,
|
| 590 |
+
return_dict=return_dict,
|
| 591 |
+
)
|
| 592 |
+
sequence_output = encoder_outputs[0]
|
| 593 |
+
|
| 594 |
+
pooler_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 595 |
+
|
| 596 |
+
if not return_dict:
|
| 597 |
+
return (sequence_output, pooler_output) + encoder_outputs[1:]
|
| 598 |
+
|
| 599 |
+
return BaseModelOutputWithPooling(
|
| 600 |
+
last_hidden_state=sequence_output,
|
| 601 |
+
pooler_output=pooler_output,
|
| 602 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
@add_start_docstrings(
|
| 607 |
+
"""
|
| 608 |
+
FNet Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
|
| 609 |
+
sentence prediction (classification)` head.
|
| 610 |
+
""",
|
| 611 |
+
FNET_START_DOCSTRING,
|
| 612 |
+
)
|
| 613 |
+
class FNetForPreTraining(FNetPreTrainedModel):
|
| 614 |
+
_tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
|
| 615 |
+
|
| 616 |
+
def __init__(self, config):
|
| 617 |
+
super().__init__(config)
|
| 618 |
+
|
| 619 |
+
self.fnet = FNetModel(config)
|
| 620 |
+
self.cls = FNetPreTrainingHeads(config)
|
| 621 |
+
|
| 622 |
+
# Initialize weights and apply final processing
|
| 623 |
+
self.post_init()
|
| 624 |
+
|
| 625 |
+
def get_output_embeddings(self):
|
| 626 |
+
return self.cls.predictions.decoder
|
| 627 |
+
|
| 628 |
+
def set_output_embeddings(self, new_embeddings):
|
| 629 |
+
self.cls.predictions.decoder = new_embeddings
|
| 630 |
+
|
| 631 |
+
@add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 632 |
+
@replace_return_docstrings(output_type=FNetForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
|
| 633 |
+
def forward(
|
| 634 |
+
self,
|
| 635 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 636 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 637 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 638 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 639 |
+
labels: Optional[torch.Tensor] = None,
|
| 640 |
+
next_sentence_label: Optional[torch.Tensor] = None,
|
| 641 |
+
output_hidden_states: Optional[bool] = None,
|
| 642 |
+
return_dict: Optional[bool] = None,
|
| 643 |
+
) -> Union[Tuple, FNetForPreTrainingOutput]:
|
| 644 |
+
r"""
|
| 645 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 646 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 647 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 648 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 649 |
+
next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 650 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
|
| 651 |
+
(see `input_ids` docstring) Indices should be in `[0, 1]`:
|
| 652 |
+
|
| 653 |
+
- 0 indicates sequence B is a continuation of sequence A,
|
| 654 |
+
- 1 indicates sequence B is a random sequence.
|
| 655 |
+
kwargs (`Dict[str, any]`, optional, defaults to *{}*):
|
| 656 |
+
Used to hide legacy arguments that have been deprecated.
|
| 657 |
+
|
| 658 |
+
Returns:
|
| 659 |
+
|
| 660 |
+
Example:
|
| 661 |
+
|
| 662 |
+
```python
|
| 663 |
+
>>> from transformers import AutoTokenizer, FNetForPreTraining
|
| 664 |
+
>>> import torch
|
| 665 |
+
|
| 666 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/fnet-base")
|
| 667 |
+
>>> model = FNetForPreTraining.from_pretrained("google/fnet-base")
|
| 668 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 669 |
+
>>> outputs = model(**inputs)
|
| 670 |
+
>>> prediction_logits = outputs.prediction_logits
|
| 671 |
+
>>> seq_relationship_logits = outputs.seq_relationship_logits
|
| 672 |
+
```"""
|
| 673 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 674 |
+
|
| 675 |
+
outputs = self.fnet(
|
| 676 |
+
input_ids,
|
| 677 |
+
token_type_ids=token_type_ids,
|
| 678 |
+
position_ids=position_ids,
|
| 679 |
+
inputs_embeds=inputs_embeds,
|
| 680 |
+
output_hidden_states=output_hidden_states,
|
| 681 |
+
return_dict=return_dict,
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
sequence_output, pooled_output = outputs[:2]
|
| 685 |
+
prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
|
| 686 |
+
|
| 687 |
+
total_loss = None
|
| 688 |
+
if labels is not None and next_sentence_label is not None:
|
| 689 |
+
loss_fct = CrossEntropyLoss()
|
| 690 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 691 |
+
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
|
| 692 |
+
total_loss = masked_lm_loss + next_sentence_loss
|
| 693 |
+
|
| 694 |
+
if not return_dict:
|
| 695 |
+
output = (prediction_scores, seq_relationship_score) + outputs[2:]
|
| 696 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 697 |
+
|
| 698 |
+
return FNetForPreTrainingOutput(
|
| 699 |
+
loss=total_loss,
|
| 700 |
+
prediction_logits=prediction_scores,
|
| 701 |
+
seq_relationship_logits=seq_relationship_score,
|
| 702 |
+
hidden_states=outputs.hidden_states,
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
@add_start_docstrings("""FNet Model with a `language modeling` head on top.""", FNET_START_DOCSTRING)
|
| 707 |
+
class FNetForMaskedLM(FNetPreTrainedModel):
|
| 708 |
+
_tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
|
| 709 |
+
|
| 710 |
+
def __init__(self, config):
|
| 711 |
+
super().__init__(config)
|
| 712 |
+
|
| 713 |
+
self.fnet = FNetModel(config)
|
| 714 |
+
self.cls = FNetOnlyMLMHead(config)
|
| 715 |
+
|
| 716 |
+
# Initialize weights and apply final processing
|
| 717 |
+
self.post_init()
|
| 718 |
+
|
| 719 |
+
def get_output_embeddings(self):
|
| 720 |
+
return self.cls.predictions.decoder
|
| 721 |
+
|
| 722 |
+
def set_output_embeddings(self, new_embeddings):
|
| 723 |
+
self.cls.predictions.decoder = new_embeddings
|
| 724 |
+
|
| 725 |
+
@add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 726 |
+
@add_code_sample_docstrings(
|
| 727 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 728 |
+
output_type=MaskedLMOutput,
|
| 729 |
+
config_class=_CONFIG_FOR_DOC,
|
| 730 |
+
)
|
| 731 |
+
def forward(
|
| 732 |
+
self,
|
| 733 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 734 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 735 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 736 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 737 |
+
labels: Optional[torch.Tensor] = None,
|
| 738 |
+
output_hidden_states: Optional[bool] = None,
|
| 739 |
+
return_dict: Optional[bool] = None,
|
| 740 |
+
) -> Union[Tuple, MaskedLMOutput]:
|
| 741 |
+
r"""
|
| 742 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 743 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 744 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 745 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 746 |
+
"""
|
| 747 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 748 |
+
|
| 749 |
+
outputs = self.fnet(
|
| 750 |
+
input_ids,
|
| 751 |
+
token_type_ids=token_type_ids,
|
| 752 |
+
position_ids=position_ids,
|
| 753 |
+
inputs_embeds=inputs_embeds,
|
| 754 |
+
output_hidden_states=output_hidden_states,
|
| 755 |
+
return_dict=return_dict,
|
| 756 |
+
)
|
| 757 |
+
|
| 758 |
+
sequence_output = outputs[0]
|
| 759 |
+
prediction_scores = self.cls(sequence_output)
|
| 760 |
+
|
| 761 |
+
masked_lm_loss = None
|
| 762 |
+
if labels is not None:
|
| 763 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
| 764 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 765 |
+
|
| 766 |
+
if not return_dict:
|
| 767 |
+
output = (prediction_scores,) + outputs[2:]
|
| 768 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 769 |
+
|
| 770 |
+
return MaskedLMOutput(loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states)
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
@add_start_docstrings(
|
| 774 |
+
"""FNet Model with a `next sentence prediction (classification)` head on top.""",
|
| 775 |
+
FNET_START_DOCSTRING,
|
| 776 |
+
)
|
| 777 |
+
class FNetForNextSentencePrediction(FNetPreTrainedModel):
|
| 778 |
+
def __init__(self, config):
|
| 779 |
+
super().__init__(config)
|
| 780 |
+
|
| 781 |
+
self.fnet = FNetModel(config)
|
| 782 |
+
self.cls = FNetOnlyNSPHead(config)
|
| 783 |
+
|
| 784 |
+
# Initialize weights and apply final processing
|
| 785 |
+
self.post_init()
|
| 786 |
+
|
| 787 |
+
@add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 788 |
+
@replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
|
| 789 |
+
def forward(
|
| 790 |
+
self,
|
| 791 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 792 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 793 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 794 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 795 |
+
labels: Optional[torch.Tensor] = None,
|
| 796 |
+
output_hidden_states: Optional[bool] = None,
|
| 797 |
+
return_dict: Optional[bool] = None,
|
| 798 |
+
**kwargs,
|
| 799 |
+
) -> Union[Tuple, NextSentencePredictorOutput]:
|
| 800 |
+
r"""
|
| 801 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 802 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
|
| 803 |
+
(see `input_ids` docstring). Indices should be in `[0, 1]`:
|
| 804 |
+
|
| 805 |
+
- 0 indicates sequence B is a continuation of sequence A,
|
| 806 |
+
- 1 indicates sequence B is a random sequence.
|
| 807 |
+
|
| 808 |
+
Returns:
|
| 809 |
+
|
| 810 |
+
Example:
|
| 811 |
+
|
| 812 |
+
```python
|
| 813 |
+
>>> from transformers import AutoTokenizer, FNetForNextSentencePrediction
|
| 814 |
+
>>> import torch
|
| 815 |
+
|
| 816 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/fnet-base")
|
| 817 |
+
>>> model = FNetForNextSentencePrediction.from_pretrained("google/fnet-base")
|
| 818 |
+
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
|
| 819 |
+
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
|
| 820 |
+
>>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
|
| 821 |
+
>>> outputs = model(**encoding, labels=torch.LongTensor([1]))
|
| 822 |
+
>>> logits = outputs.logits
|
| 823 |
+
>>> assert logits[0, 0] < logits[0, 1] # next sentence was random
|
| 824 |
+
```"""
|
| 825 |
+
|
| 826 |
+
if "next_sentence_label" in kwargs:
|
| 827 |
+
warnings.warn(
|
| 828 |
+
"The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
|
| 829 |
+
" `labels` instead.",
|
| 830 |
+
FutureWarning,
|
| 831 |
+
)
|
| 832 |
+
labels = kwargs.pop("next_sentence_label")
|
| 833 |
+
|
| 834 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 835 |
+
|
| 836 |
+
outputs = self.fnet(
|
| 837 |
+
input_ids,
|
| 838 |
+
token_type_ids=token_type_ids,
|
| 839 |
+
position_ids=position_ids,
|
| 840 |
+
inputs_embeds=inputs_embeds,
|
| 841 |
+
output_hidden_states=output_hidden_states,
|
| 842 |
+
return_dict=return_dict,
|
| 843 |
+
)
|
| 844 |
+
|
| 845 |
+
pooled_output = outputs[1]
|
| 846 |
+
|
| 847 |
+
seq_relationship_scores = self.cls(pooled_output)
|
| 848 |
+
|
| 849 |
+
next_sentence_loss = None
|
| 850 |
+
if labels is not None:
|
| 851 |
+
loss_fct = CrossEntropyLoss()
|
| 852 |
+
next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
|
| 853 |
+
|
| 854 |
+
if not return_dict:
|
| 855 |
+
output = (seq_relationship_scores,) + outputs[2:]
|
| 856 |
+
return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
|
| 857 |
+
|
| 858 |
+
return NextSentencePredictorOutput(
|
| 859 |
+
loss=next_sentence_loss,
|
| 860 |
+
logits=seq_relationship_scores,
|
| 861 |
+
hidden_states=outputs.hidden_states,
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
@add_start_docstrings(
|
| 866 |
+
"""
|
| 867 |
+
FNet Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
| 868 |
+
output) e.g. for GLUE tasks.
|
| 869 |
+
""",
|
| 870 |
+
FNET_START_DOCSTRING,
|
| 871 |
+
)
|
| 872 |
+
class FNetForSequenceClassification(FNetPreTrainedModel):
|
| 873 |
+
def __init__(self, config):
|
| 874 |
+
super().__init__(config)
|
| 875 |
+
self.num_labels = config.num_labels
|
| 876 |
+
self.fnet = FNetModel(config)
|
| 877 |
+
|
| 878 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 879 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 880 |
+
|
| 881 |
+
# Initialize weights and apply final processing
|
| 882 |
+
self.post_init()
|
| 883 |
+
|
| 884 |
+
@add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 885 |
+
@add_code_sample_docstrings(
|
| 886 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 887 |
+
output_type=SequenceClassifierOutput,
|
| 888 |
+
config_class=_CONFIG_FOR_DOC,
|
| 889 |
+
)
|
| 890 |
+
def forward(
|
| 891 |
+
self,
|
| 892 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 893 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 894 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 895 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 896 |
+
labels: Optional[torch.Tensor] = None,
|
| 897 |
+
output_hidden_states: Optional[bool] = None,
|
| 898 |
+
return_dict: Optional[bool] = None,
|
| 899 |
+
) -> Union[Tuple, SequenceClassifierOutput]:
|
| 900 |
+
r"""
|
| 901 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 902 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 903 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 904 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 905 |
+
"""
|
| 906 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 907 |
+
|
| 908 |
+
outputs = self.fnet(
|
| 909 |
+
input_ids,
|
| 910 |
+
token_type_ids=token_type_ids,
|
| 911 |
+
position_ids=position_ids,
|
| 912 |
+
inputs_embeds=inputs_embeds,
|
| 913 |
+
output_hidden_states=output_hidden_states,
|
| 914 |
+
return_dict=return_dict,
|
| 915 |
+
)
|
| 916 |
+
|
| 917 |
+
pooled_output = outputs[1]
|
| 918 |
+
pooled_output = self.dropout(pooled_output)
|
| 919 |
+
logits = self.classifier(pooled_output)
|
| 920 |
+
|
| 921 |
+
loss = None
|
| 922 |
+
if labels is not None:
|
| 923 |
+
if self.config.problem_type is None:
|
| 924 |
+
if self.num_labels == 1:
|
| 925 |
+
self.config.problem_type = "regression"
|
| 926 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 927 |
+
self.config.problem_type = "single_label_classification"
|
| 928 |
+
else:
|
| 929 |
+
self.config.problem_type = "multi_label_classification"
|
| 930 |
+
|
| 931 |
+
if self.config.problem_type == "regression":
|
| 932 |
+
loss_fct = MSELoss()
|
| 933 |
+
if self.num_labels == 1:
|
| 934 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 935 |
+
else:
|
| 936 |
+
loss = loss_fct(logits, labels)
|
| 937 |
+
elif self.config.problem_type == "single_label_classification":
|
| 938 |
+
loss_fct = CrossEntropyLoss()
|
| 939 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 940 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 941 |
+
loss_fct = BCEWithLogitsLoss()
|
| 942 |
+
loss = loss_fct(logits, labels)
|
| 943 |
+
if not return_dict:
|
| 944 |
+
output = (logits,) + outputs[2:]
|
| 945 |
+
return ((loss,) + output) if loss is not None else output
|
| 946 |
+
|
| 947 |
+
return SequenceClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
@add_start_docstrings(
|
| 951 |
+
"""
|
| 952 |
+
FNet Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 953 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 954 |
+
""",
|
| 955 |
+
FNET_START_DOCSTRING,
|
| 956 |
+
)
|
| 957 |
+
class FNetForMultipleChoice(FNetPreTrainedModel):
|
| 958 |
+
def __init__(self, config):
|
| 959 |
+
super().__init__(config)
|
| 960 |
+
|
| 961 |
+
self.fnet = FNetModel(config)
|
| 962 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 963 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 964 |
+
|
| 965 |
+
# Initialize weights and apply final processing
|
| 966 |
+
self.post_init()
|
| 967 |
+
|
| 968 |
+
@add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
|
| 969 |
+
@add_code_sample_docstrings(
|
| 970 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 971 |
+
output_type=MultipleChoiceModelOutput,
|
| 972 |
+
config_class=_CONFIG_FOR_DOC,
|
| 973 |
+
)
|
| 974 |
+
def forward(
|
| 975 |
+
self,
|
| 976 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 977 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 978 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 979 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 980 |
+
labels: Optional[torch.Tensor] = None,
|
| 981 |
+
output_hidden_states: Optional[bool] = None,
|
| 982 |
+
return_dict: Optional[bool] = None,
|
| 983 |
+
) -> Union[Tuple, MultipleChoiceModelOutput]:
|
| 984 |
+
r"""
|
| 985 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 986 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
| 987 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
| 988 |
+
`input_ids` above)
|
| 989 |
+
"""
|
| 990 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 991 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
| 992 |
+
|
| 993 |
+
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
| 994 |
+
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
| 995 |
+
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
| 996 |
+
inputs_embeds = (
|
| 997 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
| 998 |
+
if inputs_embeds is not None
|
| 999 |
+
else None
|
| 1000 |
+
)
|
| 1001 |
+
|
| 1002 |
+
outputs = self.fnet(
|
| 1003 |
+
input_ids,
|
| 1004 |
+
token_type_ids=token_type_ids,
|
| 1005 |
+
position_ids=position_ids,
|
| 1006 |
+
inputs_embeds=inputs_embeds,
|
| 1007 |
+
output_hidden_states=output_hidden_states,
|
| 1008 |
+
return_dict=return_dict,
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
pooled_output = outputs[1]
|
| 1012 |
+
|
| 1013 |
+
pooled_output = self.dropout(pooled_output)
|
| 1014 |
+
logits = self.classifier(pooled_output)
|
| 1015 |
+
reshaped_logits = logits.view(-1, num_choices)
|
| 1016 |
+
|
| 1017 |
+
loss = None
|
| 1018 |
+
if labels is not None:
|
| 1019 |
+
loss_fct = CrossEntropyLoss()
|
| 1020 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 1021 |
+
|
| 1022 |
+
if not return_dict:
|
| 1023 |
+
output = (reshaped_logits,) + outputs[2:]
|
| 1024 |
+
return ((loss,) + output) if loss is not None else output
|
| 1025 |
+
|
| 1026 |
+
return MultipleChoiceModelOutput(loss=loss, logits=reshaped_logits, hidden_states=outputs.hidden_states)
|
| 1027 |
+
|
| 1028 |
+
|
| 1029 |
+
@add_start_docstrings(
|
| 1030 |
+
"""
|
| 1031 |
+
FNet Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1032 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1033 |
+
""",
|
| 1034 |
+
FNET_START_DOCSTRING,
|
| 1035 |
+
)
|
| 1036 |
+
class FNetForTokenClassification(FNetPreTrainedModel):
|
| 1037 |
+
def __init__(self, config):
|
| 1038 |
+
super().__init__(config)
|
| 1039 |
+
self.num_labels = config.num_labels
|
| 1040 |
+
|
| 1041 |
+
self.fnet = FNetModel(config)
|
| 1042 |
+
|
| 1043 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 1044 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1045 |
+
|
| 1046 |
+
# Initialize weights and apply final processing
|
| 1047 |
+
self.post_init()
|
| 1048 |
+
|
| 1049 |
+
@add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1050 |
+
@add_code_sample_docstrings(
|
| 1051 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1052 |
+
output_type=TokenClassifierOutput,
|
| 1053 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1054 |
+
)
|
| 1055 |
+
def forward(
|
| 1056 |
+
self,
|
| 1057 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1058 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1059 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1060 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1061 |
+
labels: Optional[torch.Tensor] = None,
|
| 1062 |
+
output_hidden_states: Optional[bool] = None,
|
| 1063 |
+
return_dict: Optional[bool] = None,
|
| 1064 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
| 1065 |
+
r"""
|
| 1066 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1067 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1068 |
+
"""
|
| 1069 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1070 |
+
|
| 1071 |
+
outputs = self.fnet(
|
| 1072 |
+
input_ids,
|
| 1073 |
+
token_type_ids=token_type_ids,
|
| 1074 |
+
position_ids=position_ids,
|
| 1075 |
+
inputs_embeds=inputs_embeds,
|
| 1076 |
+
output_hidden_states=output_hidden_states,
|
| 1077 |
+
return_dict=return_dict,
|
| 1078 |
+
)
|
| 1079 |
+
|
| 1080 |
+
sequence_output = outputs[0]
|
| 1081 |
+
|
| 1082 |
+
sequence_output = self.dropout(sequence_output)
|
| 1083 |
+
logits = self.classifier(sequence_output)
|
| 1084 |
+
|
| 1085 |
+
loss = None
|
| 1086 |
+
if labels is not None:
|
| 1087 |
+
loss_fct = CrossEntropyLoss()
|
| 1088 |
+
# Only keep active parts of the loss
|
| 1089 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1090 |
+
|
| 1091 |
+
if not return_dict:
|
| 1092 |
+
output = (logits,) + outputs[2:]
|
| 1093 |
+
return ((loss,) + output) if loss is not None else output
|
| 1094 |
+
|
| 1095 |
+
return TokenClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
| 1096 |
+
|
| 1097 |
+
|
| 1098 |
+
@add_start_docstrings(
|
| 1099 |
+
"""
|
| 1100 |
+
FNet Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1101 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1102 |
+
""",
|
| 1103 |
+
FNET_START_DOCSTRING,
|
| 1104 |
+
)
|
| 1105 |
+
class FNetForQuestionAnswering(FNetPreTrainedModel):
|
| 1106 |
+
def __init__(self, config):
|
| 1107 |
+
super().__init__(config)
|
| 1108 |
+
|
| 1109 |
+
self.num_labels = config.num_labels
|
| 1110 |
+
|
| 1111 |
+
self.fnet = FNetModel(config)
|
| 1112 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1113 |
+
|
| 1114 |
+
# Initialize weights and apply final processing
|
| 1115 |
+
self.post_init()
|
| 1116 |
+
|
| 1117 |
+
@add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1118 |
+
@add_code_sample_docstrings(
|
| 1119 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1120 |
+
output_type=QuestionAnsweringModelOutput,
|
| 1121 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1122 |
+
)
|
| 1123 |
+
def forward(
|
| 1124 |
+
self,
|
| 1125 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1126 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1127 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1128 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1129 |
+
start_positions: Optional[torch.Tensor] = None,
|
| 1130 |
+
end_positions: Optional[torch.Tensor] = None,
|
| 1131 |
+
output_hidden_states: Optional[bool] = None,
|
| 1132 |
+
return_dict: Optional[bool] = None,
|
| 1133 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
| 1134 |
+
r"""
|
| 1135 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1136 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1137 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1138 |
+
are not taken into account for computing the loss.
|
| 1139 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1140 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1141 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1142 |
+
are not taken into account for computing the loss.
|
| 1143 |
+
"""
|
| 1144 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1145 |
+
|
| 1146 |
+
outputs = self.fnet(
|
| 1147 |
+
input_ids,
|
| 1148 |
+
token_type_ids=token_type_ids,
|
| 1149 |
+
position_ids=position_ids,
|
| 1150 |
+
inputs_embeds=inputs_embeds,
|
| 1151 |
+
output_hidden_states=output_hidden_states,
|
| 1152 |
+
return_dict=return_dict,
|
| 1153 |
+
)
|
| 1154 |
+
|
| 1155 |
+
sequence_output = outputs[0]
|
| 1156 |
+
|
| 1157 |
+
logits = self.qa_outputs(sequence_output)
|
| 1158 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1159 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1160 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1161 |
+
|
| 1162 |
+
total_loss = None
|
| 1163 |
+
if start_positions is not None and end_positions is not None:
|
| 1164 |
+
# If we are on multi-GPU, split add a dimension
|
| 1165 |
+
if len(start_positions.size()) > 1:
|
| 1166 |
+
start_positions = start_positions.squeeze(-1)
|
| 1167 |
+
if len(end_positions.size()) > 1:
|
| 1168 |
+
end_positions = end_positions.squeeze(-1)
|
| 1169 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1170 |
+
ignored_index = start_logits.size(1)
|
| 1171 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1172 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1173 |
+
|
| 1174 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1175 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1176 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1177 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1178 |
+
|
| 1179 |
+
if not return_dict:
|
| 1180 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1181 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1182 |
+
|
| 1183 |
+
return QuestionAnsweringModelOutput(
|
| 1184 |
+
loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states
|
| 1185 |
+
)
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/tokenization_fnet.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 Google Research, Google AI, Google Brain and the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Tokenization classes for FNet model."""
|
| 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 logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
|
| 30 |
+
|
| 31 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
| 32 |
+
"vocab_file": {
|
| 33 |
+
"google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/spiece.model",
|
| 34 |
+
"google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/spiece.model",
|
| 35 |
+
},
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
| 39 |
+
"google/fnet-base": 512,
|
| 40 |
+
"google/fnet-large": 512,
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
SPIECE_UNDERLINE = "▁"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class FNetTokenizer(PreTrainedTokenizer):
|
| 47 |
+
"""
|
| 48 |
+
Construct an FNet tokenizer. Adapted from [`AlbertTokenizer`]. Based on
|
| 49 |
+
[SentencePiece](https://github.com/google/sentencepiece). This tokenizer inherits from [`PreTrainedTokenizer`]
|
| 50 |
+
which contains most of the main methods. Users should refer to this superclass for more information regarding those
|
| 51 |
+
methods.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
vocab_file (`str`):
|
| 55 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 56 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 57 |
+
do_lower_case (`bool`, *optional*, defaults to `False`):
|
| 58 |
+
Whether or not to lowercase the input when tokenizing.
|
| 59 |
+
remove_space (`bool`, *optional*, defaults to `True`):
|
| 60 |
+
Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
|
| 61 |
+
keep_accents (`bool`, *optional*, defaults to `True`):
|
| 62 |
+
Whether or not to keep accents when tokenizing.
|
| 63 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 64 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 65 |
+
token instead.
|
| 66 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 67 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 68 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 69 |
+
token of a sequence built with special tokens.
|
| 70 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 71 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 72 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 73 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 74 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 75 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 76 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 77 |
+
modeling. This is the token which the model will try to predict.
|
| 78 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 79 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 80 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 81 |
+
to set:
|
| 82 |
+
|
| 83 |
+
- `enable_sampling`: Enable subword regularization.
|
| 84 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 85 |
+
|
| 86 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 87 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 88 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 89 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 90 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 91 |
+
BPE-dropout.
|
| 92 |
+
|
| 93 |
+
Attributes:
|
| 94 |
+
sp_model (`SentencePieceProcessor`):
|
| 95 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 99 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
| 100 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
| 101 |
+
model_input_names = ["input_ids", "token_type_ids"]
|
| 102 |
+
|
| 103 |
+
def __init__(
|
| 104 |
+
self,
|
| 105 |
+
vocab_file,
|
| 106 |
+
do_lower_case=False,
|
| 107 |
+
remove_space=True,
|
| 108 |
+
keep_accents=True,
|
| 109 |
+
unk_token="<unk>",
|
| 110 |
+
sep_token="[SEP]",
|
| 111 |
+
pad_token="<pad>",
|
| 112 |
+
cls_token="[CLS]",
|
| 113 |
+
mask_token="[MASK]",
|
| 114 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
| 115 |
+
**kwargs,
|
| 116 |
+
) -> None:
|
| 117 |
+
# Mask token behave like a normal word, i.e. include the space before it and
|
| 118 |
+
# is included in the raw text, there should be a match in a non-normalized sentence.
|
| 119 |
+
mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
|
| 120 |
+
cls_token = AddedToken(cls_token, special=True) if isinstance(cls_token, str) else cls_token
|
| 121 |
+
sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
|
| 122 |
+
mask_token = AddedToken(mask_token, special=True) if isinstance(mask_token, str) else mask_token
|
| 123 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 124 |
+
|
| 125 |
+
self.do_lower_case = do_lower_case
|
| 126 |
+
self.remove_space = remove_space
|
| 127 |
+
self.keep_accents = keep_accents
|
| 128 |
+
self.vocab_file = vocab_file
|
| 129 |
+
|
| 130 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 131 |
+
self.sp_model.Load(vocab_file)
|
| 132 |
+
|
| 133 |
+
super().__init__(
|
| 134 |
+
do_lower_case=do_lower_case,
|
| 135 |
+
remove_space=remove_space,
|
| 136 |
+
keep_accents=keep_accents,
|
| 137 |
+
unk_token=unk_token,
|
| 138 |
+
sep_token=sep_token,
|
| 139 |
+
pad_token=pad_token,
|
| 140 |
+
cls_token=cls_token,
|
| 141 |
+
mask_token=mask_token,
|
| 142 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 143 |
+
**kwargs,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
@property
|
| 147 |
+
def vocab_size(self):
|
| 148 |
+
return len(self.sp_model)
|
| 149 |
+
|
| 150 |
+
def get_vocab(self):
|
| 151 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 152 |
+
vocab.update(self.added_tokens_encoder)
|
| 153 |
+
return vocab
|
| 154 |
+
|
| 155 |
+
def __getstate__(self):
|
| 156 |
+
state = self.__dict__.copy()
|
| 157 |
+
state["sp_model"] = None
|
| 158 |
+
return state
|
| 159 |
+
|
| 160 |
+
def __setstate__(self, d):
|
| 161 |
+
self.__dict__ = d
|
| 162 |
+
|
| 163 |
+
# for backward compatibility
|
| 164 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 165 |
+
self.sp_model_kwargs = {}
|
| 166 |
+
|
| 167 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 168 |
+
self.sp_model.Load(self.vocab_file)
|
| 169 |
+
|
| 170 |
+
def preprocess_text(self, inputs):
|
| 171 |
+
if self.remove_space:
|
| 172 |
+
outputs = " ".join(inputs.strip().split())
|
| 173 |
+
else:
|
| 174 |
+
outputs = inputs
|
| 175 |
+
outputs = outputs.replace("``", '"').replace("''", '"')
|
| 176 |
+
|
| 177 |
+
if not self.keep_accents:
|
| 178 |
+
outputs = unicodedata.normalize("NFKD", outputs)
|
| 179 |
+
outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
|
| 180 |
+
if self.do_lower_case:
|
| 181 |
+
outputs = outputs.lower()
|
| 182 |
+
|
| 183 |
+
return outputs
|
| 184 |
+
|
| 185 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 186 |
+
"""Tokenize a string."""
|
| 187 |
+
text = self.preprocess_text(text)
|
| 188 |
+
pieces = self.sp_model.encode(text, out_type=str)
|
| 189 |
+
new_pieces = []
|
| 190 |
+
for piece in pieces:
|
| 191 |
+
if len(piece) > 1 and piece[-1] == str(",") and piece[-2].isdigit():
|
| 192 |
+
cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
|
| 193 |
+
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
|
| 194 |
+
if len(cur_pieces[0]) == 1:
|
| 195 |
+
cur_pieces = cur_pieces[1:]
|
| 196 |
+
else:
|
| 197 |
+
cur_pieces[0] = cur_pieces[0][1:]
|
| 198 |
+
cur_pieces.append(piece[-1])
|
| 199 |
+
new_pieces.extend(cur_pieces)
|
| 200 |
+
else:
|
| 201 |
+
new_pieces.append(piece)
|
| 202 |
+
|
| 203 |
+
return new_pieces
|
| 204 |
+
|
| 205 |
+
def _convert_token_to_id(self, token):
|
| 206 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 207 |
+
return self.sp_model.PieceToId(token)
|
| 208 |
+
|
| 209 |
+
def _convert_id_to_token(self, index):
|
| 210 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 211 |
+
return self.sp_model.IdToPiece(index)
|
| 212 |
+
|
| 213 |
+
# Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.convert_tokens_to_string
|
| 214 |
+
def convert_tokens_to_string(self, tokens):
|
| 215 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 216 |
+
current_sub_tokens = []
|
| 217 |
+
out_string = ""
|
| 218 |
+
prev_is_special = False
|
| 219 |
+
for token in tokens:
|
| 220 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
| 221 |
+
if token in self.all_special_tokens:
|
| 222 |
+
if not prev_is_special:
|
| 223 |
+
out_string += " "
|
| 224 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
| 225 |
+
prev_is_special = True
|
| 226 |
+
current_sub_tokens = []
|
| 227 |
+
else:
|
| 228 |
+
current_sub_tokens.append(token)
|
| 229 |
+
prev_is_special = False
|
| 230 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
| 231 |
+
return out_string.strip()
|
| 232 |
+
|
| 233 |
+
def _decode(
|
| 234 |
+
self,
|
| 235 |
+
token_ids: List[int],
|
| 236 |
+
skip_special_tokens: bool = False,
|
| 237 |
+
clean_up_tokenization_spaces: bool = None,
|
| 238 |
+
spaces_between_special_tokens: bool = False,
|
| 239 |
+
**kwargs,
|
| 240 |
+
) -> str:
|
| 241 |
+
text = super()._decode(
|
| 242 |
+
token_ids=token_ids,
|
| 243 |
+
skip_special_tokens=skip_special_tokens,
|
| 244 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 245 |
+
spaces_between_special_tokens=spaces_between_special_tokens,
|
| 246 |
+
**kwargs,
|
| 247 |
+
)
|
| 248 |
+
# Mimic the behavior of the Rust tokenizer:
|
| 249 |
+
# No space after <unk>
|
| 250 |
+
if not spaces_between_special_tokens:
|
| 251 |
+
text = text.replace("<unk> ", "<unk>")
|
| 252 |
+
return text
|
| 253 |
+
|
| 254 |
+
def build_inputs_with_special_tokens(
|
| 255 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 256 |
+
) -> List[int]:
|
| 257 |
+
"""
|
| 258 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 259 |
+
adding special tokens. An FNet sequence has the following format:
|
| 260 |
+
|
| 261 |
+
- single sequence: `[CLS] X [SEP]`
|
| 262 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 263 |
+
|
| 264 |
+
Args:
|
| 265 |
+
token_ids_0 (`List[int]`):
|
| 266 |
+
List of IDs to which the special tokens will be added.
|
| 267 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 268 |
+
Optional second list of IDs for sequence pairs.
|
| 269 |
+
|
| 270 |
+
Returns:
|
| 271 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 272 |
+
"""
|
| 273 |
+
sep = [self.sep_token_id]
|
| 274 |
+
cls = [self.cls_token_id]
|
| 275 |
+
if token_ids_1 is None:
|
| 276 |
+
return cls + token_ids_0 + sep
|
| 277 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 278 |
+
|
| 279 |
+
def get_special_tokens_mask(
|
| 280 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 281 |
+
) -> List[int]:
|
| 282 |
+
"""
|
| 283 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 284 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 285 |
+
|
| 286 |
+
Args:
|
| 287 |
+
token_ids_0 (`List[int]`):
|
| 288 |
+
List of IDs.
|
| 289 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 290 |
+
Optional second list of IDs for sequence pairs.
|
| 291 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 292 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 293 |
+
|
| 294 |
+
Returns:
|
| 295 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
if already_has_special_tokens:
|
| 299 |
+
return super().get_special_tokens_mask(
|
| 300 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
if token_ids_1 is not None:
|
| 304 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 305 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 306 |
+
|
| 307 |
+
def create_token_type_ids_from_sequences(
|
| 308 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 309 |
+
) -> List[int]:
|
| 310 |
+
"""
|
| 311 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. An FNet sequence
|
| 312 |
+
pair mask has the following format: :
|
| 313 |
+
|
| 314 |
+
```
|
| 315 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence |
|
| 316 |
+
```
|
| 317 |
+
|
| 318 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 319 |
+
|
| 320 |
+
Args:
|
| 321 |
+
token_ids_0 (`List[int]`):
|
| 322 |
+
List of IDs.
|
| 323 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 324 |
+
Optional second list of IDs for sequence pairs.
|
| 325 |
+
|
| 326 |
+
Returns:
|
| 327 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 328 |
+
"""
|
| 329 |
+
sep = [self.sep_token_id]
|
| 330 |
+
cls = [self.cls_token_id]
|
| 331 |
+
|
| 332 |
+
if token_ids_1 is None:
|
| 333 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 334 |
+
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
| 335 |
+
|
| 336 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 337 |
+
if not os.path.isdir(save_directory):
|
| 338 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 339 |
+
return
|
| 340 |
+
out_vocab_file = os.path.join(
|
| 341 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 345 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 346 |
+
elif not os.path.isfile(self.vocab_file):
|
| 347 |
+
with open(out_vocab_file, "wb") as fi:
|
| 348 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 349 |
+
fi.write(content_spiece_model)
|
| 350 |
+
|
| 351 |
+
return (out_vocab_file,)
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/fnet/tokenization_fnet_fast.py
ADDED
|
@@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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 Google AI, Google Brain and the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Tokenization classes for FNet model."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
from shutil import copyfile
|
| 20 |
+
from typing import List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
from ...tokenization_utils import AddedToken
|
| 23 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 24 |
+
from ...utils import is_sentencepiece_available, logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if is_sentencepiece_available():
|
| 28 |
+
from .tokenization_fnet import FNetTokenizer
|
| 29 |
+
else:
|
| 30 |
+
FNetTokenizer = None
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
|
| 34 |
+
|
| 35 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
| 36 |
+
"vocab_file": {
|
| 37 |
+
"google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/spiece.model",
|
| 38 |
+
"google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/spiece.model",
|
| 39 |
+
},
|
| 40 |
+
"tokenizer_file": {
|
| 41 |
+
"google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json",
|
| 42 |
+
"google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json",
|
| 43 |
+
},
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
| 47 |
+
"google/fnet-base": 512,
|
| 48 |
+
"google/fnet-large": 512,
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
SPIECE_UNDERLINE = "▁"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class FNetTokenizerFast(PreTrainedTokenizerFast):
|
| 55 |
+
"""
|
| 56 |
+
Construct a "fast" FNetTokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
|
| 57 |
+
[`AlbertTokenizerFast`]. Based on
|
| 58 |
+
[Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This
|
| 59 |
+
tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to
|
| 60 |
+
this superclass for more information regarding those methods
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
vocab_file (`str`):
|
| 64 |
+
[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 `False`):
|
| 67 |
+
Whether or not to lowercase the input when tokenizing.
|
| 68 |
+
remove_space (`bool`, *optional*, defaults to `True`):
|
| 69 |
+
Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
|
| 70 |
+
keep_accents (`bool`, *optional*, defaults to `True`):
|
| 71 |
+
Whether or not to keep accents when tokenizing.
|
| 72 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 73 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 74 |
+
token instead.
|
| 75 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 76 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 77 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 78 |
+
token of a sequence built with special tokens.
|
| 79 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 80 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 81 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 82 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 83 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 84 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 85 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 86 |
+
modeling. This is the token which the model will try to predict.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 90 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
| 91 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
| 92 |
+
model_input_names = ["input_ids", "token_type_ids"]
|
| 93 |
+
slow_tokenizer_class = FNetTokenizer
|
| 94 |
+
|
| 95 |
+
def __init__(
|
| 96 |
+
self,
|
| 97 |
+
vocab_file=None,
|
| 98 |
+
tokenizer_file=None,
|
| 99 |
+
do_lower_case=False,
|
| 100 |
+
remove_space=True,
|
| 101 |
+
keep_accents=True,
|
| 102 |
+
unk_token="<unk>",
|
| 103 |
+
sep_token="[SEP]",
|
| 104 |
+
pad_token="<pad>",
|
| 105 |
+
cls_token="[CLS]",
|
| 106 |
+
mask_token="[MASK]",
|
| 107 |
+
**kwargs,
|
| 108 |
+
):
|
| 109 |
+
# Mask token behave like a normal word, i.e. include the space before it and
|
| 110 |
+
# is included in the raw text, there should be a match in a non-normalized sentence.
|
| 111 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 112 |
+
cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
|
| 113 |
+
sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
|
| 114 |
+
|
| 115 |
+
super().__init__(
|
| 116 |
+
vocab_file,
|
| 117 |
+
tokenizer_file=tokenizer_file,
|
| 118 |
+
do_lower_case=do_lower_case,
|
| 119 |
+
remove_space=remove_space,
|
| 120 |
+
keep_accents=keep_accents,
|
| 121 |
+
unk_token=unk_token,
|
| 122 |
+
sep_token=sep_token,
|
| 123 |
+
pad_token=pad_token,
|
| 124 |
+
cls_token=cls_token,
|
| 125 |
+
mask_token=mask_token,
|
| 126 |
+
**kwargs,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
self.do_lower_case = do_lower_case
|
| 130 |
+
self.remove_space = remove_space
|
| 131 |
+
self.keep_accents = keep_accents
|
| 132 |
+
self.vocab_file = vocab_file
|
| 133 |
+
|
| 134 |
+
@property
|
| 135 |
+
def can_save_slow_tokenizer(self) -> bool:
|
| 136 |
+
return os.path.isfile(self.vocab_file) if self.vocab_file else False
|
| 137 |
+
|
| 138 |
+
def build_inputs_with_special_tokens(
|
| 139 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 140 |
+
) -> List[int]:
|
| 141 |
+
"""
|
| 142 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 143 |
+
adding special tokens. An FNet sequence has the following format:
|
| 144 |
+
|
| 145 |
+
- single sequence: `[CLS] X [SEP]`
|
| 146 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
token_ids_0 (`List[int]`):
|
| 150 |
+
List of IDs to which the special tokens will be added
|
| 151 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 152 |
+
Optional second list of IDs for sequence pairs.
|
| 153 |
+
|
| 154 |
+
Returns:
|
| 155 |
+
`List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 156 |
+
"""
|
| 157 |
+
sep = [self.sep_token_id]
|
| 158 |
+
cls = [self.cls_token_id]
|
| 159 |
+
if token_ids_1 is None:
|
| 160 |
+
return cls + token_ids_0 + sep
|
| 161 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 162 |
+
|
| 163 |
+
def create_token_type_ids_from_sequences(
|
| 164 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 165 |
+
) -> List[int]:
|
| 166 |
+
"""
|
| 167 |
+
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An FNet
|
| 168 |
+
sequence pair mask has the following format:
|
| 169 |
+
|
| 170 |
+
```
|
| 171 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 172 |
+
| first sequence | second sequence |
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
if token_ids_1 is None, only returns the first portion of the mask (0s).
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
token_ids_0 (`List[int]`):
|
| 179 |
+
List of ids.
|
| 180 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 181 |
+
Optional second list of IDs for sequence pairs.
|
| 182 |
+
|
| 183 |
+
Returns:
|
| 184 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 185 |
+
"""
|
| 186 |
+
sep = [self.sep_token_id]
|
| 187 |
+
cls = [self.cls_token_id]
|
| 188 |
+
|
| 189 |
+
if token_ids_1 is None:
|
| 190 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 191 |
+
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
| 192 |
+
|
| 193 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 194 |
+
if not os.path.isdir(save_directory):
|
| 195 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 196 |
+
return
|
| 197 |
+
out_vocab_file = os.path.join(
|
| 198 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
| 202 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 203 |
+
|
| 204 |
+
return (out_vocab_file,)
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/configuration_kosmos2.cpython-310.pyc
ADDED
|
Binary file (11.4 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (2.32 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/modeling_kosmos2.cpython-310.pyc
ADDED
|
Binary file (64.4 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/processing_kosmos2.cpython-310.pyc
ADDED
|
Binary file (21 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/configuration_kosmos2.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 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 |
+
""" KOSMOS-2 model configuration"""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from typing import Union
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PretrainedConfig
|
| 21 |
+
from ...utils import logging
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
KOSMOS2_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 27 |
+
"microsoft/kosmos-2-patch14-224": (
|
| 28 |
+
"https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/config.json"
|
| 29 |
+
),
|
| 30 |
+
# See all KOSMOS-2 models at https://huggingface.co/models?filter=kosmos-2
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Kosmos2TextConfig(PretrainedConfig):
|
| 35 |
+
r"""
|
| 36 |
+
This is the configuration class to store the configuration of a [`Kosmos2TextModel`]. It is used to instantiate a
|
| 37 |
+
KOSMOS-2 text decoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 38 |
+
configuration with the defaults will yield a similar configuration to that of the text decoder of the KOSMOS-2
|
| 39 |
+
[microsoft/kosmos-2-patch14-224](https://huggingface.co/microsoft/kosmos-2-patch14-224) architecture.
|
| 40 |
+
|
| 41 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 42 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
vocab_size (`int`, *optional*, defaults to 65037):
|
| 46 |
+
Vocabulary size of the Kosmos2 model. Defines the number of different tokens that can be represented by the
|
| 47 |
+
`inputs_ids` passed when calling [`Kosmos2Model`].
|
| 48 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
| 49 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 50 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 51 |
+
embed_dim (`int`, *optional*, defaults to 2048):
|
| 52 |
+
Dimensionality of the layers and the pooler layer.
|
| 53 |
+
layers (`int`, *optional*, defaults to 24):
|
| 54 |
+
Number of hidden layers in the Transformer encoder.
|
| 55 |
+
ffn_dim (`int`, *optional*, defaults to 8192):
|
| 56 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 57 |
+
attention_heads (`int`, *optional*, defaults to 32):
|
| 58 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 59 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 60 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 61 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 62 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 63 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 64 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 65 |
+
The dropout ratio for the attention probabilities.
|
| 66 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 67 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 68 |
+
layerdrop (`float`, *optional*, defaults to 0.0):
|
| 69 |
+
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 70 |
+
for more details.
|
| 71 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
| 72 |
+
The epsilon used by the layer normalization layers.
|
| 73 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 74 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 75 |
+
scale_embedding (`bool`, *optional*, defaults to `True`):
|
| 76 |
+
Scale embeddings by diving by sqrt(embed_dim).
|
| 77 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 78 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
| 79 |
+
```"""
|
| 80 |
+
|
| 81 |
+
model_type = "kosmos_2_text_model"
|
| 82 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 83 |
+
attribute_map = {
|
| 84 |
+
"num_attention_heads": "attention_heads",
|
| 85 |
+
"hidden_size": "embed_dim",
|
| 86 |
+
"num_hidden_layers": "layers",
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
vocab_size=65037,
|
| 92 |
+
max_position_embeddings=2048,
|
| 93 |
+
embed_dim=2048,
|
| 94 |
+
layers=24,
|
| 95 |
+
ffn_dim=8192,
|
| 96 |
+
attention_heads=32,
|
| 97 |
+
activation_function="gelu",
|
| 98 |
+
dropout=0.1,
|
| 99 |
+
attention_dropout=0.1,
|
| 100 |
+
activation_dropout=0.0,
|
| 101 |
+
layerdrop=0.0,
|
| 102 |
+
layer_norm_eps=1e-5,
|
| 103 |
+
init_std=0.02,
|
| 104 |
+
scale_embedding=True,
|
| 105 |
+
use_cache=True,
|
| 106 |
+
pad_token_id=1,
|
| 107 |
+
bos_token_id=0,
|
| 108 |
+
eos_token_id=2,
|
| 109 |
+
**kwargs,
|
| 110 |
+
):
|
| 111 |
+
super().__init__(
|
| 112 |
+
pad_token_id=pad_token_id,
|
| 113 |
+
bos_token_id=bos_token_id,
|
| 114 |
+
eos_token_id=eos_token_id,
|
| 115 |
+
**kwargs,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
self.vocab_size = vocab_size
|
| 119 |
+
self.max_position_embeddings = max_position_embeddings
|
| 120 |
+
self.embed_dim = embed_dim
|
| 121 |
+
self.layers = layers
|
| 122 |
+
self.ffn_dim = ffn_dim
|
| 123 |
+
self.attention_heads = attention_heads
|
| 124 |
+
self.activation_function = activation_function
|
| 125 |
+
self.dropout = dropout
|
| 126 |
+
self.attention_dropout = attention_dropout
|
| 127 |
+
self.activation_dropout = activation_dropout
|
| 128 |
+
self.layerdrop = layerdrop
|
| 129 |
+
self.layer_norm_eps = layer_norm_eps
|
| 130 |
+
self.init_std = init_std
|
| 131 |
+
self.scale_embedding = scale_embedding
|
| 132 |
+
self.use_cache = use_cache
|
| 133 |
+
|
| 134 |
+
@classmethod
|
| 135 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 136 |
+
cls._set_token_in_kwargs(kwargs)
|
| 137 |
+
|
| 138 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 139 |
+
|
| 140 |
+
# get the text config dict if we are loading from Kosmos2Config
|
| 141 |
+
if config_dict.get("model_type") == "kosmos-2":
|
| 142 |
+
config_dict = config_dict["text_config"]
|
| 143 |
+
|
| 144 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 145 |
+
logger.warning(
|
| 146 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 147 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class Kosmos2VisionConfig(PretrainedConfig):
|
| 154 |
+
r"""
|
| 155 |
+
This is the configuration class to store the configuration of a [`Kosmos2VisionModel`]. It is used to instantiate a
|
| 156 |
+
KOSMOS-2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 157 |
+
configuration with the defaults will yield a similar configuration to that of the vision encoder of the KOSMOS-2
|
| 158 |
+
[microsoft/kosmos-2-patch14-224](https://huggingface.co/microsoft/kosmos-2-patch14-224) architecture.
|
| 159 |
+
|
| 160 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 161 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
| 165 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 166 |
+
intermediate_size (`int`, *optional*, defaults to 4096):
|
| 167 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 168 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
| 169 |
+
Number of hidden layers in the Transformer encoder.
|
| 170 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 171 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 172 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 173 |
+
The number of input channels.
|
| 174 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 175 |
+
The size (resolution) of each image.
|
| 176 |
+
patch_size (`int`, *optional*, defaults to 14):
|
| 177 |
+
The size (resolution) of each patch.
|
| 178 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
| 179 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 180 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
|
| 181 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
| 182 |
+
The epsilon used by the layer normalization layers.
|
| 183 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 184 |
+
The dropout ratio for the attention probabilities.
|
| 185 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 186 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 187 |
+
initializer_factor (`float`, *optional*, defaults to 1):
|
| 188 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
| 189 |
+
testing).
|
| 190 |
+
```"""
|
| 191 |
+
|
| 192 |
+
model_type = "kosmos_2_vision_model"
|
| 193 |
+
|
| 194 |
+
def __init__(
|
| 195 |
+
self,
|
| 196 |
+
hidden_size=1024,
|
| 197 |
+
intermediate_size=4096,
|
| 198 |
+
num_hidden_layers=24,
|
| 199 |
+
num_attention_heads=16,
|
| 200 |
+
num_channels=3,
|
| 201 |
+
image_size=224,
|
| 202 |
+
patch_size=14,
|
| 203 |
+
hidden_act="quick_gelu",
|
| 204 |
+
layer_norm_eps=1e-5,
|
| 205 |
+
attention_dropout=0.0,
|
| 206 |
+
initializer_range=0.02,
|
| 207 |
+
initializer_factor=1.0,
|
| 208 |
+
**kwargs,
|
| 209 |
+
):
|
| 210 |
+
super().__init__(**kwargs)
|
| 211 |
+
|
| 212 |
+
self.hidden_size = hidden_size
|
| 213 |
+
self.intermediate_size = intermediate_size
|
| 214 |
+
self.num_hidden_layers = num_hidden_layers
|
| 215 |
+
self.num_attention_heads = num_attention_heads
|
| 216 |
+
self.num_channels = num_channels
|
| 217 |
+
self.patch_size = patch_size
|
| 218 |
+
self.image_size = image_size
|
| 219 |
+
self.initializer_range = initializer_range
|
| 220 |
+
self.initializer_factor = initializer_factor
|
| 221 |
+
self.attention_dropout = attention_dropout
|
| 222 |
+
self.layer_norm_eps = layer_norm_eps
|
| 223 |
+
self.hidden_act = hidden_act
|
| 224 |
+
|
| 225 |
+
@classmethod
|
| 226 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 227 |
+
cls._set_token_in_kwargs(kwargs)
|
| 228 |
+
|
| 229 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 230 |
+
|
| 231 |
+
# get the vision config dict if we are loading from Kosmos2Config
|
| 232 |
+
if config_dict.get("model_type") == "kosmos-2":
|
| 233 |
+
config_dict = config_dict["vision_config"]
|
| 234 |
+
|
| 235 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 236 |
+
logger.warning(
|
| 237 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 238 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
class Kosmos2Config(PretrainedConfig):
|
| 245 |
+
r"""
|
| 246 |
+
This is the configuration class to store the configuration of a [`Kosmos2Model`]. It is used to instantiate a
|
| 247 |
+
KOSMOS-2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 248 |
+
with the defaults will yield a similar configuration to that of the KOSMOS-2
|
| 249 |
+
[microsoft/kosmos-2-patch14-224](https://huggingface.co/microsoft/kosmos-2-patch14-224) architecture.
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
text_config (`dict`, *optional*):
|
| 253 |
+
Dictionary of configuration options used to initialize [`Kosmos2TextConfig`].
|
| 254 |
+
vision_config (`dict`, *optional*):
|
| 255 |
+
Dictionary of configuration options used to initialize [`Kosmos2VisionConfig`].
|
| 256 |
+
latent_query_num (`int`, *optional*, defaults to 64):
|
| 257 |
+
The number of latent query tokens that represent the image features used in the text decoder component.
|
| 258 |
+
kwargs (*optional*):
|
| 259 |
+
Dictionary of keyword arguments.
|
| 260 |
+
|
| 261 |
+
Example:
|
| 262 |
+
|
| 263 |
+
```python
|
| 264 |
+
>>> from transformers import Kosmos2Config, Kosmos2Model
|
| 265 |
+
|
| 266 |
+
>>> # Initializing a Kosmos-2 kosmos-2-patch14-224 style configuration
|
| 267 |
+
>>> configuration = Kosmos2Config()
|
| 268 |
+
|
| 269 |
+
>>> # Initializing a model (with random weights) from the kosmos-2-patch14-224 style configuration
|
| 270 |
+
>>> model = Kosmos2Model(configuration)
|
| 271 |
+
|
| 272 |
+
>>> # Accessing the model configuration
|
| 273 |
+
>>> configuration = model.config
|
| 274 |
+
```"""
|
| 275 |
+
|
| 276 |
+
model_type = "kosmos-2"
|
| 277 |
+
is_composition = True
|
| 278 |
+
|
| 279 |
+
def __init__(
|
| 280 |
+
self,
|
| 281 |
+
text_config=None,
|
| 282 |
+
vision_config=None,
|
| 283 |
+
latent_query_num=64,
|
| 284 |
+
**kwargs,
|
| 285 |
+
):
|
| 286 |
+
super().__init__(**kwargs)
|
| 287 |
+
|
| 288 |
+
if text_config is None:
|
| 289 |
+
text_config = {}
|
| 290 |
+
logger.info("`text_config` is `None`. Initializing the `Kosmos2TextConfig` with default values.")
|
| 291 |
+
|
| 292 |
+
if vision_config is None:
|
| 293 |
+
vision_config = {}
|
| 294 |
+
logger.info("`vision_config` is `None`. Initializing the `Kosmos2VisionConfig` with default values.")
|
| 295 |
+
|
| 296 |
+
self.text_config = Kosmos2TextConfig(**text_config)
|
| 297 |
+
self.vision_config = Kosmos2VisionConfig(**vision_config)
|
| 298 |
+
|
| 299 |
+
self.latent_query_num = latent_query_num
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
|
| 3 |
+
from fairseq.checkpoint_utils import load_checkpoint_to_cpu
|
| 4 |
+
|
| 5 |
+
from transformers import Kosmos2Config, Kosmos2ForConditionalGeneration
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
KEYS_TO_MODIFY_MAPPING = {
|
| 9 |
+
"gpt_model.decoder.output_projection": "text_model.lm_head",
|
| 10 |
+
"gpt_model.decoder": "text_model.model",
|
| 11 |
+
"img_connector": "image_to_text_projection",
|
| 12 |
+
"img_model.visual.class_embedding": "vision_model.model.embeddings.class_embedding",
|
| 13 |
+
"img_model.visual.positional_embedding": "vision_model.model.embeddings.position_embedding.weight",
|
| 14 |
+
"img_model.visual.conv1": "vision_model.model.embeddings.patch_embedding",
|
| 15 |
+
"img_model.visual": "vision_model.model",
|
| 16 |
+
"ln_pre": "pre_layrnorm",
|
| 17 |
+
"ln_post": "post_layernorm",
|
| 18 |
+
"transformer.resblocks": "encoder.layers",
|
| 19 |
+
"ts_attn": "self_attn",
|
| 20 |
+
"ln_1": "layer_norm1",
|
| 21 |
+
"ln_2": "layer_norm2",
|
| 22 |
+
"c_fc": "fc1",
|
| 23 |
+
"c_proj": "fc2",
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
KEYS_TO_IGNORE = [
|
| 28 |
+
# this buffer in the original code is only used to send weights to the desired device
|
| 29 |
+
"gpt_model.decoder.embed_positions._float_tensor",
|
| 30 |
+
# this weight is never used in the forward in the original KOSMOS-2)
|
| 31 |
+
"gpt_model.decoder.self_attn_sope.scale",
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def rename_key(key):
|
| 36 |
+
for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
|
| 37 |
+
if key_to_modify in key:
|
| 38 |
+
key = key.replace(key_to_modify, new_key)
|
| 39 |
+
|
| 40 |
+
return key
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def convert_kosmos2_checkpoint_to_pytorch(checkpoint_path, pytorch_dump_folder_path):
|
| 44 |
+
state = load_checkpoint_to_cpu(checkpoint_path)
|
| 45 |
+
state_dict = state["model"]
|
| 46 |
+
state_dict_keys = list(state_dict.keys())
|
| 47 |
+
|
| 48 |
+
config = Kosmos2Config()
|
| 49 |
+
# This is necessary to match the results given by the original demo
|
| 50 |
+
config.text_config.no_repeat_ngram_size = 3
|
| 51 |
+
model = Kosmos2ForConditionalGeneration(config)
|
| 52 |
+
|
| 53 |
+
# convert (by renaming keys)
|
| 54 |
+
converted_state_dict = {}
|
| 55 |
+
for key in state_dict_keys:
|
| 56 |
+
if key in KEYS_TO_IGNORE:
|
| 57 |
+
continue
|
| 58 |
+
renamed_key = rename_key(key)
|
| 59 |
+
converted_state_dict[renamed_key] = state_dict[key]
|
| 60 |
+
|
| 61 |
+
# check weight loading
|
| 62 |
+
model.load_state_dict(converted_state_dict, strict=True)
|
| 63 |
+
# save the result
|
| 64 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
parser = argparse.ArgumentParser()
|
| 69 |
+
# Required parameters
|
| 70 |
+
parser.add_argument(
|
| 71 |
+
"--kosmos2_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump."
|
| 72 |
+
)
|
| 73 |
+
parser.add_argument(
|
| 74 |
+
"--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
|
| 75 |
+
)
|
| 76 |
+
args = parser.parse_args()
|
| 77 |
+
convert_kosmos2_checkpoint_to_pytorch(args.kosmos2_checkpoint_path, args.pytorch_dump_folder_path)
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/modeling_kosmos2.py
ADDED
|
@@ -0,0 +1,2056 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 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 KOSMOS-2 model."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import Any, List, Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.utils.checkpoint
|
| 24 |
+
from torch import nn
|
| 25 |
+
from torch.nn import CrossEntropyLoss
|
| 26 |
+
|
| 27 |
+
from ...activations import ACT2FN
|
| 28 |
+
from ...modeling_outputs import (
|
| 29 |
+
BaseModelOutput,
|
| 30 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 31 |
+
BaseModelOutputWithPooling,
|
| 32 |
+
CausalLMOutputWithCrossAttentions,
|
| 33 |
+
)
|
| 34 |
+
from ...modeling_utils import PreTrainedModel
|
| 35 |
+
from ...utils import (
|
| 36 |
+
ModelOutput,
|
| 37 |
+
add_start_docstrings,
|
| 38 |
+
add_start_docstrings_to_model_forward,
|
| 39 |
+
logging,
|
| 40 |
+
replace_return_docstrings,
|
| 41 |
+
)
|
| 42 |
+
from .configuration_kosmos2 import Kosmos2Config, Kosmos2TextConfig, Kosmos2VisionConfig
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
logger = logging.get_logger(__name__)
|
| 46 |
+
|
| 47 |
+
_CONFIG_FOR_DOC = Kosmos2Config
|
| 48 |
+
|
| 49 |
+
KOSMOS2_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 50 |
+
"microsoft/kosmos-2-patch14-224",
|
| 51 |
+
# See all KOSMOS-2 models at https://huggingface.co/models?filter=kosmos-2
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
| 56 |
+
"""
|
| 57 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
| 58 |
+
"""
|
| 59 |
+
bsz, src_len = mask.size()
|
| 60 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
| 61 |
+
|
| 62 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
| 63 |
+
|
| 64 |
+
inverted_mask = 1.0 - expanded_mask
|
| 65 |
+
|
| 66 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _make_causal_mask(
|
| 70 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
| 71 |
+
):
|
| 72 |
+
"""
|
| 73 |
+
Make causal mask used for bi-directional self-attention.
|
| 74 |
+
"""
|
| 75 |
+
bsz, tgt_len = input_ids_shape
|
| 76 |
+
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
| 77 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
| 78 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
| 79 |
+
mask = mask.to(dtype)
|
| 80 |
+
|
| 81 |
+
if past_key_values_length > 0:
|
| 82 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
| 83 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
|
| 87 |
+
def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
|
| 88 |
+
"""
|
| 89 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
|
| 90 |
+
are ignored. This is modified from fairseq's `utils.make_positions`.
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
x: torch.Tensor x:
|
| 94 |
+
|
| 95 |
+
Returns: torch.Tensor
|
| 96 |
+
"""
|
| 97 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
| 98 |
+
mask = input_ids.ne(padding_idx).int()
|
| 99 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
| 100 |
+
return incremental_indices.long() + padding_idx
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
KOSMOS2_START_DOCSTRING = r"""
|
| 104 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 105 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 106 |
+
etc.)
|
| 107 |
+
|
| 108 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 109 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 110 |
+
and behavior.
|
| 111 |
+
|
| 112 |
+
Parameters:
|
| 113 |
+
config ([`Kosmos2Config`]): Model configuration class with all the parameters of the model.
|
| 114 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 115 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
KOSMOS2_VISION_INPUTS_DOCSTRING = r"""
|
| 119 |
+
Args:
|
| 120 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 121 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 122 |
+
[`CLIPImageProcessor.__call__`] for details.
|
| 123 |
+
output_attentions (`bool`, *optional*):
|
| 124 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 125 |
+
tensors for more detail.
|
| 126 |
+
output_hidden_states (`bool`, *optional*):
|
| 127 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 128 |
+
more detail.
|
| 129 |
+
return_dict (`bool`, *optional*):
|
| 130 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
KOSMOS2_TEXT_INPUTS_DOCSTRING = r"""
|
| 134 |
+
Args:
|
| 135 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 136 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 137 |
+
it.
|
| 138 |
+
|
| 139 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 140 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 141 |
+
|
| 142 |
+
[What are input IDs?](../glossary#input-ids)
|
| 143 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 144 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 145 |
+
|
| 146 |
+
- 1 for tokens that are **not masked**,
|
| 147 |
+
- 0 for tokens that are **masked**.
|
| 148 |
+
|
| 149 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 150 |
+
image_embeds: (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
|
| 151 |
+
Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
|
| 152 |
+
image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 153 |
+
Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
|
| 154 |
+
1]`:
|
| 155 |
+
|
| 156 |
+
- 1 for places where to put the image features,
|
| 157 |
+
- 0 for places that are not for image features (i.e. for text tokens).
|
| 158 |
+
|
| 159 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 160 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 161 |
+
the model is configured as a decoder.
|
| 162 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 163 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 164 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 165 |
+
|
| 166 |
+
- 1 for tokens that are **not masked**,
|
| 167 |
+
- 0 for tokens that are **masked**.
|
| 168 |
+
|
| 169 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 170 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 171 |
+
|
| 172 |
+
- 1 indicates the head is **not masked**,
|
| 173 |
+
- 0 indicates the head is **masked**.
|
| 174 |
+
|
| 175 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 176 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 177 |
+
|
| 178 |
+
- 1 indicates the head is **not masked**,
|
| 179 |
+
- 0 indicates the head is **masked**.
|
| 180 |
+
|
| 181 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
| 182 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 183 |
+
|
| 184 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 185 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 186 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 187 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 188 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 189 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 190 |
+
model's internal embedding lookup matrix.
|
| 191 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 192 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 193 |
+
config.max_position_embeddings - 1]`.
|
| 194 |
+
|
| 195 |
+
[What are position IDs?](../glossary#position-ids)
|
| 196 |
+
use_cache (`bool`, *optional*):
|
| 197 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 198 |
+
`past_key_values`).
|
| 199 |
+
output_attentions (`bool`, *optional*):
|
| 200 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 201 |
+
tensors for more detail.
|
| 202 |
+
output_hidden_states (`bool`, *optional*):
|
| 203 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 204 |
+
more detail.
|
| 205 |
+
return_dict (`bool`, *optional*):
|
| 206 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
KOSMOS2_INPUTS_DOCSTRING = r"""
|
| 210 |
+
Args:
|
| 211 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 212 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 213 |
+
[`CLIPImageProcessor.__call__`] for details.
|
| 214 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 215 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 216 |
+
it.
|
| 217 |
+
|
| 218 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 219 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 220 |
+
|
| 221 |
+
[What are input IDs?](../glossary#input-ids)
|
| 222 |
+
image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 223 |
+
Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
|
| 224 |
+
1]`:
|
| 225 |
+
|
| 226 |
+
- 1 for places where to put the image features,
|
| 227 |
+
- 0 for places that are not for image features (i.e. for text tokens).
|
| 228 |
+
|
| 229 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 230 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 231 |
+
|
| 232 |
+
- 1 for tokens that are **not masked**,
|
| 233 |
+
- 0 for tokens that are **masked**.
|
| 234 |
+
|
| 235 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 236 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 237 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 238 |
+
|
| 239 |
+
- 1 indicates the head is **not masked**,
|
| 240 |
+
- 0 indicates the head is **masked**.
|
| 241 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
| 242 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 243 |
+
|
| 244 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 245 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 246 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 247 |
+
image_embeds: (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
|
| 248 |
+
Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
|
| 249 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 250 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 251 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 252 |
+
model's internal embedding lookup matrix.
|
| 253 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 254 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 255 |
+
config.max_position_embeddings - 1]`.
|
| 256 |
+
|
| 257 |
+
[What are position IDs?](../glossary#position-ids)
|
| 258 |
+
use_cache (`bool`, *optional*):
|
| 259 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 260 |
+
`past_key_values`).
|
| 261 |
+
output_attentions (`bool`, *optional*):
|
| 262 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 263 |
+
tensors for more detail.
|
| 264 |
+
output_hidden_states (`bool`, *optional*):
|
| 265 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 266 |
+
more detail.
|
| 267 |
+
return_dict (`bool`, *optional*):
|
| 268 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
@dataclass
|
| 273 |
+
class Kosmos2ModelOutput(ModelOutput):
|
| 274 |
+
"""
|
| 275 |
+
Base class for text model's outputs that also contains a pooling of the last hidden states.
|
| 276 |
+
|
| 277 |
+
Args:
|
| 278 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 279 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 280 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 281 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 282 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 283 |
+
|
| 284 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 285 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 286 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 287 |
+
sequence_length)`.
|
| 288 |
+
|
| 289 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 290 |
+
heads.
|
| 291 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
|
| 292 |
+
Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
|
| 293 |
+
projection_attentions (`tuple(torch.FloatTensor)`, *optional*):
|
| 294 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 295 |
+
sequence_length)`.
|
| 296 |
+
|
| 297 |
+
Attentions weights given by `Kosmos2ImageToTextProjection`, after the attention softmax, used to compute
|
| 298 |
+
the weighted average in the self-attention heads.
|
| 299 |
+
vision_model_output(`BaseModelOutputWithPooling`, *optional*):
|
| 300 |
+
The output of the [`Kosmos2VisionModel`].
|
| 301 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 302 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 303 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
|
| 304 |
+
`config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
|
| 305 |
+
encoder_sequence_length, embed_size_per_head)`.
|
| 306 |
+
|
| 307 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
|
| 308 |
+
`config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
|
| 309 |
+
input) to speed up sequential decoding.
|
| 310 |
+
"""
|
| 311 |
+
|
| 312 |
+
last_hidden_state: torch.FloatTensor = None
|
| 313 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
|
| 314 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 315 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 316 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 317 |
+
projection_attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 318 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
| 319 |
+
|
| 320 |
+
def to_tuple(self) -> Tuple[Any]:
|
| 321 |
+
return tuple(
|
| 322 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 323 |
+
for k in self.keys()
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
@dataclass
|
| 328 |
+
class Kosmos2ForConditionalGenerationModelOutput(ModelOutput):
|
| 329 |
+
"""
|
| 330 |
+
Model output class for `Kosmos2ForConditionalGeneration`.
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 334 |
+
Language modeling loss (for next-token prediction).
|
| 335 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 336 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 337 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 338 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 339 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 340 |
+
|
| 341 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 342 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 343 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 344 |
+
sequence_length)`.
|
| 345 |
+
|
| 346 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 347 |
+
heads.
|
| 348 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
|
| 349 |
+
Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
|
| 350 |
+
projection_attentions (`tuple(torch.FloatTensor)`, *optional*):
|
| 351 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 352 |
+
sequence_length)`.
|
| 353 |
+
|
| 354 |
+
Attentions weights given by `Kosmos2ImageToTextProjection`, after the attention softmax, used to compute
|
| 355 |
+
the weighted average in the self-attention heads.
|
| 356 |
+
vision_model_output(`BaseModelOutputWithPooling`, *optional*):
|
| 357 |
+
The output of the [`Kosmos2VisionModel`].
|
| 358 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 359 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 360 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
|
| 361 |
+
`config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
|
| 362 |
+
encoder_sequence_length, embed_size_per_head)`.
|
| 363 |
+
|
| 364 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
|
| 365 |
+
`config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
|
| 366 |
+
input) to speed up sequential decoding.
|
| 367 |
+
"""
|
| 368 |
+
|
| 369 |
+
loss: Optional[torch.FloatTensor] = None
|
| 370 |
+
logits: torch.FloatTensor = None
|
| 371 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
|
| 372 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 373 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 374 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 375 |
+
projection_attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 376 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
| 377 |
+
|
| 378 |
+
def to_tuple(self) -> Tuple[Any]:
|
| 379 |
+
return tuple(
|
| 380 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 381 |
+
for k in self.keys()
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->Kosmos2
|
| 386 |
+
class Kosmos2VisionEmbeddings(nn.Module):
|
| 387 |
+
def __init__(self, config: Kosmos2VisionConfig):
|
| 388 |
+
super().__init__()
|
| 389 |
+
self.config = config
|
| 390 |
+
self.embed_dim = config.hidden_size
|
| 391 |
+
self.image_size = config.image_size
|
| 392 |
+
self.patch_size = config.patch_size
|
| 393 |
+
|
| 394 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
| 395 |
+
|
| 396 |
+
self.patch_embedding = nn.Conv2d(
|
| 397 |
+
in_channels=config.num_channels,
|
| 398 |
+
out_channels=self.embed_dim,
|
| 399 |
+
kernel_size=self.patch_size,
|
| 400 |
+
stride=self.patch_size,
|
| 401 |
+
bias=False,
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 405 |
+
self.num_positions = self.num_patches + 1
|
| 406 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
| 407 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
|
| 408 |
+
|
| 409 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 410 |
+
batch_size = pixel_values.shape[0]
|
| 411 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 412 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
|
| 413 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
| 414 |
+
|
| 415 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
| 416 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 417 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
| 418 |
+
return embeddings
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPAttention with CLIP->Kosmos2Vision
|
| 422 |
+
class Kosmos2VisionAttention(nn.Module):
|
| 423 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 424 |
+
|
| 425 |
+
def __init__(self, config):
|
| 426 |
+
super().__init__()
|
| 427 |
+
self.config = config
|
| 428 |
+
self.embed_dim = config.hidden_size
|
| 429 |
+
self.num_heads = config.num_attention_heads
|
| 430 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 431 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 432 |
+
raise ValueError(
|
| 433 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 434 |
+
f" {self.num_heads})."
|
| 435 |
+
)
|
| 436 |
+
self.scale = self.head_dim**-0.5
|
| 437 |
+
self.dropout = config.attention_dropout
|
| 438 |
+
|
| 439 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 440 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 441 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 442 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 443 |
+
|
| 444 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 445 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 446 |
+
|
| 447 |
+
def forward(
|
| 448 |
+
self,
|
| 449 |
+
hidden_states: torch.Tensor,
|
| 450 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 451 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
| 452 |
+
output_attentions: Optional[bool] = False,
|
| 453 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 454 |
+
"""Input shape: Batch x Time x Channel"""
|
| 455 |
+
|
| 456 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
| 457 |
+
|
| 458 |
+
# get query proj
|
| 459 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
| 460 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 461 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 462 |
+
|
| 463 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 464 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 465 |
+
key_states = key_states.view(*proj_shape)
|
| 466 |
+
value_states = value_states.view(*proj_shape)
|
| 467 |
+
|
| 468 |
+
src_len = key_states.size(1)
|
| 469 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 470 |
+
|
| 471 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 472 |
+
raise ValueError(
|
| 473 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 474 |
+
f" {attn_weights.size()}"
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
# apply the causal_attention_mask first
|
| 478 |
+
if causal_attention_mask is not None:
|
| 479 |
+
if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 480 |
+
raise ValueError(
|
| 481 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
| 482 |
+
f" {causal_attention_mask.size()}"
|
| 483 |
+
)
|
| 484 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
|
| 485 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 486 |
+
|
| 487 |
+
if attention_mask is not None:
|
| 488 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 489 |
+
raise ValueError(
|
| 490 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 491 |
+
)
|
| 492 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 493 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 494 |
+
|
| 495 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 496 |
+
|
| 497 |
+
if output_attentions:
|
| 498 |
+
# this operation is a bit akward, but it's required to
|
| 499 |
+
# make sure that attn_weights keeps its gradient.
|
| 500 |
+
# In order to do so, attn_weights have to reshaped
|
| 501 |
+
# twice and have to be reused in the following
|
| 502 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 503 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 504 |
+
else:
|
| 505 |
+
attn_weights_reshaped = None
|
| 506 |
+
|
| 507 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 508 |
+
|
| 509 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 510 |
+
|
| 511 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 512 |
+
raise ValueError(
|
| 513 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 514 |
+
f" {attn_output.size()}"
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 518 |
+
attn_output = attn_output.transpose(1, 2)
|
| 519 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
| 520 |
+
|
| 521 |
+
attn_output = self.out_proj(attn_output)
|
| 522 |
+
|
| 523 |
+
return attn_output, attn_weights_reshaped
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Kosmos2Vision
|
| 527 |
+
class Kosmos2VisionMLP(nn.Module):
|
| 528 |
+
def __init__(self, config):
|
| 529 |
+
super().__init__()
|
| 530 |
+
self.config = config
|
| 531 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 532 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 533 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 534 |
+
|
| 535 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 536 |
+
hidden_states = self.fc1(hidden_states)
|
| 537 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 538 |
+
hidden_states = self.fc2(hidden_states)
|
| 539 |
+
return hidden_states
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Kosmos2Vision
|
| 543 |
+
class Kosmos2VisionEncoderLayer(nn.Module):
|
| 544 |
+
def __init__(self, config: Kosmos2VisionConfig):
|
| 545 |
+
super().__init__()
|
| 546 |
+
self.embed_dim = config.hidden_size
|
| 547 |
+
self.self_attn = Kosmos2VisionAttention(config)
|
| 548 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 549 |
+
self.mlp = Kosmos2VisionMLP(config)
|
| 550 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 551 |
+
|
| 552 |
+
def forward(
|
| 553 |
+
self,
|
| 554 |
+
hidden_states: torch.Tensor,
|
| 555 |
+
attention_mask: torch.Tensor,
|
| 556 |
+
causal_attention_mask: torch.Tensor,
|
| 557 |
+
output_attentions: Optional[bool] = False,
|
| 558 |
+
) -> Tuple[torch.FloatTensor]:
|
| 559 |
+
"""
|
| 560 |
+
Args:
|
| 561 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 562 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 563 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 564 |
+
`(config.encoder_attention_heads,)`.
|
| 565 |
+
output_attentions (`bool`, *optional*):
|
| 566 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 567 |
+
returned tensors for more detail.
|
| 568 |
+
"""
|
| 569 |
+
residual = hidden_states
|
| 570 |
+
|
| 571 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 572 |
+
hidden_states, attn_weights = self.self_attn(
|
| 573 |
+
hidden_states=hidden_states,
|
| 574 |
+
attention_mask=attention_mask,
|
| 575 |
+
causal_attention_mask=causal_attention_mask,
|
| 576 |
+
output_attentions=output_attentions,
|
| 577 |
+
)
|
| 578 |
+
hidden_states = residual + hidden_states
|
| 579 |
+
|
| 580 |
+
residual = hidden_states
|
| 581 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 582 |
+
hidden_states = self.mlp(hidden_states)
|
| 583 |
+
hidden_states = residual + hidden_states
|
| 584 |
+
|
| 585 |
+
outputs = (hidden_states,)
|
| 586 |
+
|
| 587 |
+
if output_attentions:
|
| 588 |
+
outputs += (attn_weights,)
|
| 589 |
+
|
| 590 |
+
return outputs
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Kosmos2Vision
|
| 594 |
+
class Kosmos2VisionEncoder(nn.Module):
|
| 595 |
+
"""
|
| 596 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 597 |
+
[`Kosmos2VisionEncoderLayer`].
|
| 598 |
+
|
| 599 |
+
Args:
|
| 600 |
+
config: Kosmos2VisionConfig
|
| 601 |
+
"""
|
| 602 |
+
|
| 603 |
+
def __init__(self, config: Kosmos2VisionConfig):
|
| 604 |
+
super().__init__()
|
| 605 |
+
self.config = config
|
| 606 |
+
self.layers = nn.ModuleList([Kosmos2VisionEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 607 |
+
self.gradient_checkpointing = False
|
| 608 |
+
|
| 609 |
+
def forward(
|
| 610 |
+
self,
|
| 611 |
+
inputs_embeds,
|
| 612 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 613 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
| 614 |
+
output_attentions: Optional[bool] = None,
|
| 615 |
+
output_hidden_states: Optional[bool] = None,
|
| 616 |
+
return_dict: Optional[bool] = None,
|
| 617 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 618 |
+
r"""
|
| 619 |
+
Args:
|
| 620 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 621 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 622 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 623 |
+
than the model's internal embedding lookup matrix.
|
| 624 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 625 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 626 |
+
|
| 627 |
+
- 1 for tokens that are **not masked**,
|
| 628 |
+
- 0 for tokens that are **masked**.
|
| 629 |
+
|
| 630 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 631 |
+
causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 632 |
+
Causal mask for the text model. Mask values selected in `[0, 1]`:
|
| 633 |
+
|
| 634 |
+
- 1 for tokens that are **not masked**,
|
| 635 |
+
- 0 for tokens that are **masked**.
|
| 636 |
+
|
| 637 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 638 |
+
output_attentions (`bool`, *optional*):
|
| 639 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 640 |
+
returned tensors for more detail.
|
| 641 |
+
output_hidden_states (`bool`, *optional*):
|
| 642 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 643 |
+
for more detail.
|
| 644 |
+
return_dict (`bool`, *optional*):
|
| 645 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 646 |
+
"""
|
| 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 |
+
|
| 653 |
+
encoder_states = () if output_hidden_states else None
|
| 654 |
+
all_attentions = () if output_attentions else None
|
| 655 |
+
|
| 656 |
+
hidden_states = inputs_embeds
|
| 657 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 658 |
+
if output_hidden_states:
|
| 659 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 660 |
+
if self.gradient_checkpointing and self.training:
|
| 661 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 662 |
+
encoder_layer.__call__,
|
| 663 |
+
hidden_states,
|
| 664 |
+
attention_mask,
|
| 665 |
+
causal_attention_mask,
|
| 666 |
+
output_attentions,
|
| 667 |
+
)
|
| 668 |
+
else:
|
| 669 |
+
layer_outputs = encoder_layer(
|
| 670 |
+
hidden_states,
|
| 671 |
+
attention_mask,
|
| 672 |
+
causal_attention_mask,
|
| 673 |
+
output_attentions=output_attentions,
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
hidden_states = layer_outputs[0]
|
| 677 |
+
|
| 678 |
+
if output_attentions:
|
| 679 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 680 |
+
|
| 681 |
+
if output_hidden_states:
|
| 682 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 683 |
+
|
| 684 |
+
if not return_dict:
|
| 685 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 686 |
+
return BaseModelOutput(
|
| 687 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 688 |
+
)
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
# Similar to `transformers.models.clip.modeling_clip.CLIPVisionTransformer` but without docstring for `forward`
|
| 692 |
+
class Kosmos2VisionTransformer(nn.Module):
|
| 693 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionTransformer.__init__ with CLIPVision->Kosmos2Vision,CLIP_VISION->KOSMOS2_VISION,CLIP->Kosmos2Vision
|
| 694 |
+
def __init__(self, config: Kosmos2VisionConfig):
|
| 695 |
+
super().__init__()
|
| 696 |
+
self.config = config
|
| 697 |
+
embed_dim = config.hidden_size
|
| 698 |
+
|
| 699 |
+
self.embeddings = Kosmos2VisionEmbeddings(config)
|
| 700 |
+
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 701 |
+
self.encoder = Kosmos2VisionEncoder(config)
|
| 702 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 703 |
+
|
| 704 |
+
def forward(
|
| 705 |
+
self,
|
| 706 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 707 |
+
output_attentions: Optional[bool] = None,
|
| 708 |
+
output_hidden_states: Optional[bool] = None,
|
| 709 |
+
return_dict: Optional[bool] = None,
|
| 710 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 711 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 712 |
+
output_hidden_states = (
|
| 713 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 714 |
+
)
|
| 715 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 716 |
+
|
| 717 |
+
if pixel_values is None:
|
| 718 |
+
raise ValueError("You have to specify pixel_values")
|
| 719 |
+
|
| 720 |
+
hidden_states = self.embeddings(pixel_values)
|
| 721 |
+
hidden_states = self.pre_layrnorm(hidden_states)
|
| 722 |
+
|
| 723 |
+
encoder_outputs = self.encoder(
|
| 724 |
+
inputs_embeds=hidden_states,
|
| 725 |
+
output_attentions=output_attentions,
|
| 726 |
+
output_hidden_states=output_hidden_states,
|
| 727 |
+
return_dict=return_dict,
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
last_hidden_state = encoder_outputs[0]
|
| 731 |
+
pooled_output = last_hidden_state[:, 0, :]
|
| 732 |
+
pooled_output = self.post_layernorm(pooled_output)
|
| 733 |
+
|
| 734 |
+
if not return_dict:
|
| 735 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 736 |
+
|
| 737 |
+
return BaseModelOutputWithPooling(
|
| 738 |
+
last_hidden_state=last_hidden_state,
|
| 739 |
+
pooler_output=pooled_output,
|
| 740 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 741 |
+
attentions=encoder_outputs.attentions,
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
# Similar to `transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding` but allowing to pass `position_ids`
|
| 746 |
+
class Kosmos2TextSinusoidalPositionalEmbedding(nn.Module):
|
| 747 |
+
"""This module produces sinusoidal positional embeddings of any length."""
|
| 748 |
+
|
| 749 |
+
# Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.__init__
|
| 750 |
+
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 751 |
+
super().__init__()
|
| 752 |
+
self.offset = 2
|
| 753 |
+
self.embedding_dim = embedding_dim
|
| 754 |
+
self.padding_idx = padding_idx
|
| 755 |
+
self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
|
| 756 |
+
|
| 757 |
+
# Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.make_weights
|
| 758 |
+
def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 759 |
+
emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
|
| 760 |
+
if hasattr(self, "weights"):
|
| 761 |
+
# in forward put the weights on the correct dtype and device of the param
|
| 762 |
+
emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
|
| 763 |
+
|
| 764 |
+
self.register_buffer("weights", emb_weights, persistent=False)
|
| 765 |
+
|
| 766 |
+
@staticmethod
|
| 767 |
+
# Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.get_embedding
|
| 768 |
+
def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 769 |
+
"""
|
| 770 |
+
Build sinusoidal embeddings.
|
| 771 |
+
|
| 772 |
+
This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
|
| 773 |
+
"Attention Is All You Need".
|
| 774 |
+
"""
|
| 775 |
+
half_dim = embedding_dim // 2
|
| 776 |
+
emb = math.log(10000) / (half_dim - 1)
|
| 777 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb)
|
| 778 |
+
emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0)
|
| 779 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
|
| 780 |
+
if embedding_dim % 2 == 1:
|
| 781 |
+
# zero pad
|
| 782 |
+
emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
|
| 783 |
+
if padding_idx is not None:
|
| 784 |
+
emb[padding_idx, :] = 0
|
| 785 |
+
|
| 786 |
+
return emb.to(torch.get_default_dtype())
|
| 787 |
+
|
| 788 |
+
@torch.no_grad()
|
| 789 |
+
def forward(
|
| 790 |
+
self,
|
| 791 |
+
input_ids: torch.Tensor = None,
|
| 792 |
+
inputs_embeds: torch.Tensor = None,
|
| 793 |
+
past_key_values_length: int = 0,
|
| 794 |
+
position_ids: torch.Tensor = None,
|
| 795 |
+
):
|
| 796 |
+
if input_ids is not None:
|
| 797 |
+
bsz, seq_len = input_ids.size()
|
| 798 |
+
if position_ids is None:
|
| 799 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
| 800 |
+
position_ids = create_position_ids_from_input_ids(
|
| 801 |
+
input_ids, self.padding_idx, past_key_values_length
|
| 802 |
+
).to(input_ids.device)
|
| 803 |
+
else:
|
| 804 |
+
bsz, seq_len = inputs_embeds.size()[:-1]
|
| 805 |
+
if position_ids is None:
|
| 806 |
+
position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, past_key_values_length)
|
| 807 |
+
|
| 808 |
+
# expand embeddings if needed
|
| 809 |
+
max_pos = self.padding_idx + 1 + seq_len + past_key_values_length
|
| 810 |
+
if max_pos > self.weights.size(0):
|
| 811 |
+
self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
|
| 812 |
+
|
| 813 |
+
return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach()
|
| 814 |
+
|
| 815 |
+
# Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.create_position_ids_from_inputs_embeds
|
| 816 |
+
def create_position_ids_from_inputs_embeds(self, inputs_embeds, past_key_values_length):
|
| 817 |
+
"""
|
| 818 |
+
We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
|
| 819 |
+
|
| 820 |
+
Args:
|
| 821 |
+
inputs_embeds: torch.Tensor
|
| 822 |
+
|
| 823 |
+
Returns: torch.Tensor
|
| 824 |
+
"""
|
| 825 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 826 |
+
sequence_length = input_shape[1]
|
| 827 |
+
|
| 828 |
+
position_ids = torch.arange(
|
| 829 |
+
self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
|
| 830 |
+
)
|
| 831 |
+
return position_ids.unsqueeze(0).expand(input_shape).contiguous() + past_key_values_length
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
class KosmosTextAttention(nn.Module):
|
| 835 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 836 |
+
|
| 837 |
+
# Similar to transformers.models.bart.modeling_bart.BartAttention.__init__ except an additional `inner_attn_ln`.
|
| 838 |
+
def __init__(
|
| 839 |
+
self,
|
| 840 |
+
config,
|
| 841 |
+
embed_dim: int,
|
| 842 |
+
num_heads: int,
|
| 843 |
+
dropout: float = 0.0,
|
| 844 |
+
is_decoder: bool = False,
|
| 845 |
+
add_inner_attn_layernorm: bool = False,
|
| 846 |
+
bias: bool = True,
|
| 847 |
+
):
|
| 848 |
+
super().__init__()
|
| 849 |
+
self.embed_dim = embed_dim
|
| 850 |
+
self.num_heads = num_heads
|
| 851 |
+
self.dropout = dropout
|
| 852 |
+
self.head_dim = embed_dim // num_heads
|
| 853 |
+
|
| 854 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 855 |
+
raise ValueError(
|
| 856 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 857 |
+
f" and `num_heads`: {num_heads})."
|
| 858 |
+
)
|
| 859 |
+
self.scaling = self.head_dim**-0.5
|
| 860 |
+
self.is_decoder = is_decoder
|
| 861 |
+
|
| 862 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 863 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 864 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 865 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 866 |
+
|
| 867 |
+
# End opy
|
| 868 |
+
self.inner_attn_ln = None
|
| 869 |
+
if add_inner_attn_layernorm:
|
| 870 |
+
self.inner_attn_ln = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 871 |
+
|
| 872 |
+
def _shape(self, projection: torch.Tensor) -> torch.Tensor:
|
| 873 |
+
new_projection_shape = projection.size()[:-1] + (self.num_heads, self.head_dim)
|
| 874 |
+
# move heads to 2nd position (B, T, H * D) -> (B, T, H, D) -> (B, H, T, D)
|
| 875 |
+
new_projection = projection.view(new_projection_shape).permute(0, 2, 1, 3)
|
| 876 |
+
return new_projection
|
| 877 |
+
|
| 878 |
+
def forward(
|
| 879 |
+
self,
|
| 880 |
+
hidden_states: torch.Tensor,
|
| 881 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 882 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 883 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 884 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 885 |
+
output_attentions: bool = False,
|
| 886 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 887 |
+
"""Input shape: Batch x Time x Channel"""
|
| 888 |
+
|
| 889 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 890 |
+
# for the decoder
|
| 891 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 892 |
+
batch_size, seq_length = hidden_states.shape[:2]
|
| 893 |
+
|
| 894 |
+
# use encoder_hidden_states if cross attention
|
| 895 |
+
current_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
|
| 896 |
+
# checking that the `sequence_length` of the `past_key_value` is the same as the he provided
|
| 897 |
+
# `encoder_hidden_states` to support prefix tuning
|
| 898 |
+
if is_cross_attention and past_key_value and past_key_value[0].shape[2] == current_states.shape[1]:
|
| 899 |
+
# reuse k,v, cross_attentions
|
| 900 |
+
key_states = past_key_value[0]
|
| 901 |
+
value_states = past_key_value[1]
|
| 902 |
+
else:
|
| 903 |
+
key_states = self._shape(self.k_proj(current_states))
|
| 904 |
+
value_states = self._shape(self.v_proj(current_states))
|
| 905 |
+
if past_key_value is not None and not is_cross_attention:
|
| 906 |
+
# reuse k, v, self_attention
|
| 907 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 908 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 909 |
+
|
| 910 |
+
query_states = self._shape(self.q_proj(hidden_states) * self.scaling)
|
| 911 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(-1, -2))
|
| 912 |
+
|
| 913 |
+
if self.is_decoder:
|
| 914 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 915 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 916 |
+
# key/value_states (first "if" case)
|
| 917 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 918 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 919 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 920 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 921 |
+
past_key_value = (key_states, value_states)
|
| 922 |
+
|
| 923 |
+
src_len = key_states.size(2)
|
| 924 |
+
|
| 925 |
+
if attention_mask is not None:
|
| 926 |
+
if attention_mask.size() != (batch_size, 1, seq_length, src_len):
|
| 927 |
+
raise ValueError(
|
| 928 |
+
f"Attention mask should be of size {(batch_size, 1, seq_length, src_len)}, but is {attention_mask.size()}"
|
| 929 |
+
)
|
| 930 |
+
attn_weights = attn_weights + attention_mask
|
| 931 |
+
|
| 932 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 933 |
+
|
| 934 |
+
# Mask heads if we want to
|
| 935 |
+
if layer_head_mask is not None:
|
| 936 |
+
attn_weights = attn_weights * layer_head_mask
|
| 937 |
+
|
| 938 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 939 |
+
|
| 940 |
+
# attn_output = torch.bmm(attn_probs, value_states) ?
|
| 941 |
+
context_states = torch.matmul(attn_weights, value_states)
|
| 942 |
+
# attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) ?
|
| 943 |
+
context_states = context_states.permute(0, 2, 1, 3).contiguous().view(batch_size, seq_length, -1)
|
| 944 |
+
|
| 945 |
+
if self.inner_attn_ln is not None:
|
| 946 |
+
context_states = self.inner_attn_ln(context_states)
|
| 947 |
+
|
| 948 |
+
attn_output = self.out_proj(context_states)
|
| 949 |
+
|
| 950 |
+
return attn_output, attn_weights, past_key_value
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
class Kosmos2TextFFN(nn.Module):
|
| 954 |
+
def __init__(self, config: Kosmos2TextConfig):
|
| 955 |
+
super().__init__()
|
| 956 |
+
|
| 957 |
+
self.dropout = config.dropout
|
| 958 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 959 |
+
self.activation_dropout = config.activation_dropout
|
| 960 |
+
|
| 961 |
+
self.fc1 = nn.Linear(config.embed_dim, config.ffn_dim)
|
| 962 |
+
self.fc2 = nn.Linear(config.ffn_dim, config.embed_dim)
|
| 963 |
+
|
| 964 |
+
self.ffn_layernorm = nn.LayerNorm(config.ffn_dim, eps=config.layer_norm_eps)
|
| 965 |
+
|
| 966 |
+
def forward(self, hidden_states):
|
| 967 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 968 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 969 |
+
hidden_states = self.ffn_layernorm(hidden_states)
|
| 970 |
+
hidden_states = self.fc2(hidden_states)
|
| 971 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 972 |
+
|
| 973 |
+
return hidden_states
|
| 974 |
+
|
| 975 |
+
|
| 976 |
+
class Kosmos2TextBlock(nn.Module):
|
| 977 |
+
def __init__(self, config: Kosmos2TextConfig):
|
| 978 |
+
super().__init__()
|
| 979 |
+
self.embed_dim = config.embed_dim
|
| 980 |
+
|
| 981 |
+
self.self_attn = KosmosTextAttention(
|
| 982 |
+
config,
|
| 983 |
+
embed_dim=self.embed_dim,
|
| 984 |
+
num_heads=config.attention_heads,
|
| 985 |
+
dropout=config.attention_dropout,
|
| 986 |
+
is_decoder=True,
|
| 987 |
+
add_inner_attn_layernorm=True,
|
| 988 |
+
)
|
| 989 |
+
self.dropout = config.dropout
|
| 990 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 991 |
+
|
| 992 |
+
if config.add_cross_attention:
|
| 993 |
+
self.encoder_attn = KosmosTextAttention(
|
| 994 |
+
config,
|
| 995 |
+
embed_dim=self.embed_dim,
|
| 996 |
+
num_heads=config.attention_heads,
|
| 997 |
+
dropout=config.attention_dropout,
|
| 998 |
+
is_decoder=True,
|
| 999 |
+
add_inner_attn_layernorm=False,
|
| 1000 |
+
)
|
| 1001 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 1002 |
+
|
| 1003 |
+
self.ffn = Kosmos2TextFFN(config)
|
| 1004 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 1005 |
+
|
| 1006 |
+
def forward(
|
| 1007 |
+
self,
|
| 1008 |
+
hidden_states: torch.Tensor,
|
| 1009 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1010 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1011 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1012 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 1013 |
+
cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
|
| 1014 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 1015 |
+
output_attentions: Optional[bool] = False,
|
| 1016 |
+
use_cache: Optional[bool] = True,
|
| 1017 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 1018 |
+
residual = hidden_states
|
| 1019 |
+
|
| 1020 |
+
# Self Attention
|
| 1021 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 1022 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 1023 |
+
|
| 1024 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 1025 |
+
|
| 1026 |
+
# add present self-attn cache to positions 1,2 of present_key_value tuple
|
| 1027 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 1028 |
+
hidden_states=hidden_states,
|
| 1029 |
+
past_key_value=self_attn_past_key_value,
|
| 1030 |
+
attention_mask=attention_mask,
|
| 1031 |
+
layer_head_mask=layer_head_mask,
|
| 1032 |
+
output_attentions=output_attentions,
|
| 1033 |
+
)
|
| 1034 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 1035 |
+
hidden_states = residual + hidden_states
|
| 1036 |
+
|
| 1037 |
+
# Cross-Attention Block
|
| 1038 |
+
cross_attn_present_key_value = None
|
| 1039 |
+
cross_attn_weights = None
|
| 1040 |
+
if encoder_hidden_states is not None:
|
| 1041 |
+
if not hasattr(self, "encoder_attn"):
|
| 1042 |
+
raise ValueError(
|
| 1043 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 1044 |
+
" by setting `config.add_cross_attention=True`"
|
| 1045 |
+
)
|
| 1046 |
+
|
| 1047 |
+
residual = hidden_states
|
| 1048 |
+
|
| 1049 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 1050 |
+
|
| 1051 |
+
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
|
| 1052 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 1053 |
+
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
|
| 1054 |
+
hidden_states=hidden_states,
|
| 1055 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1056 |
+
attention_mask=encoder_attention_mask,
|
| 1057 |
+
layer_head_mask=cross_attn_layer_head_mask,
|
| 1058 |
+
past_key_value=cross_attn_past_key_value,
|
| 1059 |
+
output_attentions=output_attentions,
|
| 1060 |
+
)
|
| 1061 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 1062 |
+
hidden_states = residual + hidden_states
|
| 1063 |
+
|
| 1064 |
+
# add cross-attn to positions 3,4 of present_key_value tuple
|
| 1065 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 1066 |
+
|
| 1067 |
+
# Fully Connected
|
| 1068 |
+
residual = hidden_states
|
| 1069 |
+
|
| 1070 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 1071 |
+
|
| 1072 |
+
# FFN
|
| 1073 |
+
hidden_states = self.ffn(hidden_states)
|
| 1074 |
+
hidden_states = residual + hidden_states
|
| 1075 |
+
|
| 1076 |
+
outputs = (hidden_states,)
|
| 1077 |
+
|
| 1078 |
+
if output_attentions:
|
| 1079 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 1080 |
+
|
| 1081 |
+
if use_cache:
|
| 1082 |
+
outputs += (present_key_value,)
|
| 1083 |
+
|
| 1084 |
+
return outputs
|
| 1085 |
+
|
| 1086 |
+
|
| 1087 |
+
class Kosmos2TextTransformer(nn.Module):
|
| 1088 |
+
"""
|
| 1089 |
+
Transformer decoder consisting of `config.layers` layers. Each layer is a [`Kosmos2TextBlock`].
|
| 1090 |
+
|
| 1091 |
+
Args:
|
| 1092 |
+
config: Kosmos2TextConfig
|
| 1093 |
+
"""
|
| 1094 |
+
|
| 1095 |
+
def __init__(self, config: Kosmos2TextConfig):
|
| 1096 |
+
super().__init__()
|
| 1097 |
+
self.config = config
|
| 1098 |
+
self.dropout = config.dropout
|
| 1099 |
+
self.layerdrop = config.layerdrop
|
| 1100 |
+
|
| 1101 |
+
self.embed_scale = math.sqrt(config.embed_dim) if config.scale_embedding else 1.0
|
| 1102 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.embed_dim, padding_idx=config.pad_token_id)
|
| 1103 |
+
|
| 1104 |
+
self.embed_positions = Kosmos2TextSinusoidalPositionalEmbedding(
|
| 1105 |
+
num_positions=config.max_position_embeddings,
|
| 1106 |
+
embedding_dim=config.embed_dim,
|
| 1107 |
+
padding_idx=config.pad_token_id,
|
| 1108 |
+
)
|
| 1109 |
+
|
| 1110 |
+
self.layers = nn.ModuleList([Kosmos2TextBlock(config) for _ in range(config.layers)])
|
| 1111 |
+
self.layer_norm = nn.LayerNorm(config.embed_dim, config.layer_norm_eps)
|
| 1112 |
+
|
| 1113 |
+
self.gradient_checkpointing = False
|
| 1114 |
+
|
| 1115 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
| 1116 |
+
# create causal mask
|
| 1117 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1118 |
+
combined_attention_mask = None
|
| 1119 |
+
if input_shape[-1] > 1:
|
| 1120 |
+
combined_attention_mask = _make_causal_mask(
|
| 1121 |
+
input_shape,
|
| 1122 |
+
inputs_embeds.dtype,
|
| 1123 |
+
device=inputs_embeds.device,
|
| 1124 |
+
past_key_values_length=past_key_values_length,
|
| 1125 |
+
)
|
| 1126 |
+
|
| 1127 |
+
if attention_mask is not None:
|
| 1128 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1129 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
| 1130 |
+
inputs_embeds.device
|
| 1131 |
+
)
|
| 1132 |
+
combined_attention_mask = (
|
| 1133 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
| 1134 |
+
)
|
| 1135 |
+
|
| 1136 |
+
return combined_attention_mask
|
| 1137 |
+
|
| 1138 |
+
def forward_embedding(
|
| 1139 |
+
self,
|
| 1140 |
+
input_ids,
|
| 1141 |
+
inputs_embeds: torch.Tensor = None,
|
| 1142 |
+
image_embeds: torch.Tensor = None,
|
| 1143 |
+
img_input_mask: torch.Tensor = None,
|
| 1144 |
+
past_key_values_length: int = 0,
|
| 1145 |
+
position_ids: torch.Tensor = None,
|
| 1146 |
+
):
|
| 1147 |
+
# The argument `inputs_embeds` should be the one without being multiplied by `self.embed_scale`.
|
| 1148 |
+
if inputs_embeds is None:
|
| 1149 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 1150 |
+
|
| 1151 |
+
if image_embeds is not None:
|
| 1152 |
+
inputs_embeds[img_input_mask.to(dtype=torch.bool)] = image_embeds.to(inputs_embeds.device).view(
|
| 1153 |
+
-1, image_embeds.size(-1)
|
| 1154 |
+
)
|
| 1155 |
+
|
| 1156 |
+
inputs_embeds = inputs_embeds * self.embed_scale
|
| 1157 |
+
|
| 1158 |
+
# embed positions
|
| 1159 |
+
positions = self.embed_positions(
|
| 1160 |
+
input_ids=input_ids,
|
| 1161 |
+
inputs_embeds=inputs_embeds,
|
| 1162 |
+
past_key_values_length=past_key_values_length,
|
| 1163 |
+
position_ids=position_ids,
|
| 1164 |
+
)
|
| 1165 |
+
positions = positions.to(inputs_embeds.device)
|
| 1166 |
+
|
| 1167 |
+
hidden_states = inputs_embeds + positions
|
| 1168 |
+
|
| 1169 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 1170 |
+
|
| 1171 |
+
return hidden_states
|
| 1172 |
+
|
| 1173 |
+
def forward(
|
| 1174 |
+
self,
|
| 1175 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1176 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1177 |
+
image_embeds: Optional[torch.Tensor] = None,
|
| 1178 |
+
image_embeds_position_mask: Optional[torch.Tensor] = None,
|
| 1179 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1180 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1181 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1182 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1183 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1184 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1185 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1186 |
+
use_cache: Optional[bool] = None,
|
| 1187 |
+
output_attentions: Optional[bool] = None,
|
| 1188 |
+
output_hidden_states: Optional[bool] = None,
|
| 1189 |
+
return_dict: Optional[bool] = None,
|
| 1190 |
+
) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
|
| 1191 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1192 |
+
output_hidden_states = (
|
| 1193 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1194 |
+
)
|
| 1195 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1196 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1197 |
+
|
| 1198 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1199 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 1200 |
+
elif input_ids is not None:
|
| 1201 |
+
input_shape = input_ids.shape
|
| 1202 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 1203 |
+
elif inputs_embeds is not None:
|
| 1204 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1205 |
+
else:
|
| 1206 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1207 |
+
|
| 1208 |
+
# past_key_values_length
|
| 1209 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 1210 |
+
|
| 1211 |
+
# We don't need img info. when `past_key_values_length` > 0
|
| 1212 |
+
if past_key_values_length > 0:
|
| 1213 |
+
image_embeds = None
|
| 1214 |
+
image_embeds_position_mask = None
|
| 1215 |
+
|
| 1216 |
+
hidden_states = self.forward_embedding(
|
| 1217 |
+
input_ids=input_ids,
|
| 1218 |
+
inputs_embeds=inputs_embeds,
|
| 1219 |
+
image_embeds=image_embeds,
|
| 1220 |
+
img_input_mask=image_embeds_position_mask,
|
| 1221 |
+
past_key_values_length=past_key_values_length,
|
| 1222 |
+
position_ids=position_ids,
|
| 1223 |
+
)
|
| 1224 |
+
|
| 1225 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
| 1226 |
+
attention_mask, input_shape, hidden_states, past_key_values_length
|
| 1227 |
+
)
|
| 1228 |
+
|
| 1229 |
+
# expand encoder attention mask
|
| 1230 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 1231 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1232 |
+
encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
|
| 1233 |
+
|
| 1234 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 1235 |
+
|
| 1236 |
+
if self.gradient_checkpointing and self.training:
|
| 1237 |
+
if use_cache:
|
| 1238 |
+
logger.warning_once(
|
| 1239 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 1240 |
+
)
|
| 1241 |
+
use_cache = False
|
| 1242 |
+
|
| 1243 |
+
# decoder layers
|
| 1244 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1245 |
+
all_self_attns = () if output_attentions else None
|
| 1246 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 1247 |
+
present_key_value_states = () if use_cache else None
|
| 1248 |
+
|
| 1249 |
+
# check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
|
| 1250 |
+
for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
|
| 1251 |
+
if attn_mask is not None:
|
| 1252 |
+
if attn_mask.size()[0] != (len(self.layers)):
|
| 1253 |
+
raise ValueError(
|
| 1254 |
+
f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
|
| 1255 |
+
f" {head_mask.size()[0]}."
|
| 1256 |
+
)
|
| 1257 |
+
|
| 1258 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 1259 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 1260 |
+
if output_hidden_states:
|
| 1261 |
+
all_hidden_states += (hidden_states,)
|
| 1262 |
+
if self.training:
|
| 1263 |
+
dropout_probability = torch.rand([])
|
| 1264 |
+
if dropout_probability < self.layerdrop:
|
| 1265 |
+
continue
|
| 1266 |
+
|
| 1267 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 1268 |
+
|
| 1269 |
+
if self.gradient_checkpointing and self.training:
|
| 1270 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 1271 |
+
decoder_layer.__call__,
|
| 1272 |
+
hidden_states,
|
| 1273 |
+
attention_mask,
|
| 1274 |
+
encoder_hidden_states,
|
| 1275 |
+
encoder_attention_mask,
|
| 1276 |
+
head_mask[idx] if head_mask is not None else None,
|
| 1277 |
+
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
|
| 1278 |
+
None,
|
| 1279 |
+
output_attentions,
|
| 1280 |
+
use_cache,
|
| 1281 |
+
)
|
| 1282 |
+
else:
|
| 1283 |
+
layer_outputs = decoder_layer(
|
| 1284 |
+
hidden_states,
|
| 1285 |
+
attention_mask=attention_mask,
|
| 1286 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1287 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1288 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 1289 |
+
cross_attn_layer_head_mask=(
|
| 1290 |
+
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
|
| 1291 |
+
),
|
| 1292 |
+
past_key_value=past_key_value,
|
| 1293 |
+
output_attentions=output_attentions,
|
| 1294 |
+
use_cache=use_cache,
|
| 1295 |
+
)
|
| 1296 |
+
hidden_states = layer_outputs[0]
|
| 1297 |
+
|
| 1298 |
+
if use_cache:
|
| 1299 |
+
present_key_value_states += (layer_outputs[3 if output_attentions else 1],)
|
| 1300 |
+
|
| 1301 |
+
if output_attentions:
|
| 1302 |
+
all_self_attns += (layer_outputs[1],)
|
| 1303 |
+
|
| 1304 |
+
if encoder_hidden_states is not None:
|
| 1305 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 1306 |
+
|
| 1307 |
+
# add final layer norm
|
| 1308 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 1309 |
+
|
| 1310 |
+
# add hidden states from the last decoder layer
|
| 1311 |
+
if output_hidden_states:
|
| 1312 |
+
all_hidden_states += (hidden_states,)
|
| 1313 |
+
|
| 1314 |
+
if not return_dict:
|
| 1315 |
+
return tuple(
|
| 1316 |
+
v
|
| 1317 |
+
for v in [
|
| 1318 |
+
hidden_states,
|
| 1319 |
+
present_key_value_states,
|
| 1320 |
+
all_hidden_states,
|
| 1321 |
+
all_self_attns,
|
| 1322 |
+
all_cross_attentions,
|
| 1323 |
+
]
|
| 1324 |
+
if v is not None
|
| 1325 |
+
)
|
| 1326 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 1327 |
+
last_hidden_state=hidden_states,
|
| 1328 |
+
past_key_values=present_key_value_states,
|
| 1329 |
+
hidden_states=all_hidden_states,
|
| 1330 |
+
attentions=all_self_attns,
|
| 1331 |
+
cross_attentions=all_cross_attentions,
|
| 1332 |
+
)
|
| 1333 |
+
|
| 1334 |
+
|
| 1335 |
+
class Kosmos2PreTrainedModel(PreTrainedModel):
|
| 1336 |
+
"""
|
| 1337 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 1338 |
+
models.
|
| 1339 |
+
"""
|
| 1340 |
+
|
| 1341 |
+
config_class = Kosmos2Config
|
| 1342 |
+
supports_gradient_checkpointing = True
|
| 1343 |
+
_no_split_modules = ["Kosmos2VisionEncoderLayer", "Kosmos2TextBlock"]
|
| 1344 |
+
|
| 1345 |
+
def _init_weights(self, module):
|
| 1346 |
+
"""Initialize the weights"""
|
| 1347 |
+
if isinstance(self, Kosmos2VisionModel):
|
| 1348 |
+
factor = self.config.initializer_factor
|
| 1349 |
+
elif isinstance(self, (Kosmos2Model, Kosmos2ForConditionalGeneration)):
|
| 1350 |
+
factor = self.config.vision_config.initializer_factor
|
| 1351 |
+
|
| 1352 |
+
if isinstance(self, (Kosmos2TextModel, Kosmos2TextForCausalLM)):
|
| 1353 |
+
std = self.config.init_std
|
| 1354 |
+
elif isinstance(self, (Kosmos2Model, Kosmos2ForConditionalGeneration)):
|
| 1355 |
+
std = self.config.text_config.init_std
|
| 1356 |
+
|
| 1357 |
+
if isinstance(module, Kosmos2VisionEmbeddings):
|
| 1358 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
| 1359 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
| 1360 |
+
nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
|
| 1361 |
+
elif isinstance(module, Kosmos2VisionAttention):
|
| 1362 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 1363 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
| 1364 |
+
nn.init.normal_(module.q_proj.weight, std=in_proj_std)
|
| 1365 |
+
nn.init.normal_(module.k_proj.weight, std=in_proj_std)
|
| 1366 |
+
nn.init.normal_(module.v_proj.weight, std=in_proj_std)
|
| 1367 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
| 1368 |
+
if module.q_proj.bias is not None:
|
| 1369 |
+
module.q_proj.bias.data.zero_()
|
| 1370 |
+
if module.k_proj.bias is not None:
|
| 1371 |
+
module.k_proj.bias.data.zero_()
|
| 1372 |
+
if module.v_proj.bias is not None:
|
| 1373 |
+
module.v_proj.bias.data.zero_()
|
| 1374 |
+
if module.out_proj.bias is not None:
|
| 1375 |
+
module.out_proj.bias.data.zero_()
|
| 1376 |
+
elif isinstance(module, Kosmos2VisionMLP):
|
| 1377 |
+
in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 1378 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
| 1379 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
| 1380 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
| 1381 |
+
if module.fc1.bias is not None:
|
| 1382 |
+
module.fc1.bias.data.zero_()
|
| 1383 |
+
if module.fc2.bias is not None:
|
| 1384 |
+
module.fc2.bias.data.zero_()
|
| 1385 |
+
elif isinstance(module, Kosmos2VisionEncoderLayer):
|
| 1386 |
+
module.layer_norm1.bias.data.zero_()
|
| 1387 |
+
module.layer_norm1.weight.data.fill_(1.0)
|
| 1388 |
+
module.layer_norm2.bias.data.zero_()
|
| 1389 |
+
module.layer_norm2.weight.data.fill_(1.0)
|
| 1390 |
+
elif isinstance(module, Kosmos2VisionTransformer):
|
| 1391 |
+
module.pre_layrnorm.bias.data.zero_()
|
| 1392 |
+
module.pre_layrnorm.weight.data.fill_(1.0)
|
| 1393 |
+
module.post_layernorm.bias.data.zero_()
|
| 1394 |
+
module.post_layernorm.weight.data.fill_(1.0)
|
| 1395 |
+
elif isinstance(module, KosmosTextAttention):
|
| 1396 |
+
nn.init.normal_(module.q_proj.weight, std=std)
|
| 1397 |
+
nn.init.normal_(module.k_proj.weight, std=std)
|
| 1398 |
+
nn.init.normal_(module.v_proj.weight, std=std)
|
| 1399 |
+
nn.init.normal_(module.out_proj.weight, std=std)
|
| 1400 |
+
if module.q_proj.bias is not None:
|
| 1401 |
+
module.q_proj.bias.data.zero_()
|
| 1402 |
+
if module.k_proj.bias is not None:
|
| 1403 |
+
module.k_proj.bias.data.zero_()
|
| 1404 |
+
if module.v_proj.bias is not None:
|
| 1405 |
+
module.v_proj.bias.data.zero_()
|
| 1406 |
+
if module.out_proj.bias is not None:
|
| 1407 |
+
module.out_proj.bias.data.zero_()
|
| 1408 |
+
elif isinstance(module, Kosmos2TextFFN):
|
| 1409 |
+
nn.init.normal_(module.fc1.weight, std=std)
|
| 1410 |
+
nn.init.normal_(module.fc2.weight, std=std)
|
| 1411 |
+
if module.fc1.bias is not None:
|
| 1412 |
+
module.fc1.bias.data.zero_()
|
| 1413 |
+
if module.fc2.bias is not None:
|
| 1414 |
+
module.fc2.bias.data.zero_()
|
| 1415 |
+
elif isinstance(module, Kosmos2TextForCausalLM):
|
| 1416 |
+
nn.init.normal_(module.lm_head.weight, std=std)
|
| 1417 |
+
if module.lm_head.bias is not None:
|
| 1418 |
+
module.lm_head.bias.data.zero_()
|
| 1419 |
+
elif isinstance(module, Kosmos2ImageToTextProjection):
|
| 1420 |
+
nn.init.normal_(module.dense.weight, std=std)
|
| 1421 |
+
if module.dense.bias is not None:
|
| 1422 |
+
module.dense.bias.data.zero_()
|
| 1423 |
+
elif isinstance(module, Kosmos2TextTransformer):
|
| 1424 |
+
module.embed_tokens.weight.data.normal_(mean=0.0, std=std)
|
| 1425 |
+
if module.embed_tokens.padding_idx is not None:
|
| 1426 |
+
module.embed_tokens.weight.data[module.embed_tokens.padding_idx].zero_()
|
| 1427 |
+
|
| 1428 |
+
|
| 1429 |
+
class Kosmos2VisionModel(Kosmos2PreTrainedModel):
|
| 1430 |
+
config_class = Kosmos2VisionConfig
|
| 1431 |
+
main_input_name = "pixel_values"
|
| 1432 |
+
|
| 1433 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionModel.__init__ with CLIP_VISION->KOSMOS2_VISION,CLIP->Kosmos2,self.vision_model->self.model
|
| 1434 |
+
def __init__(self, config: Kosmos2VisionConfig):
|
| 1435 |
+
super().__init__(config)
|
| 1436 |
+
self.model = Kosmos2VisionTransformer(config)
|
| 1437 |
+
# Initialize weights and apply final processing
|
| 1438 |
+
self.post_init()
|
| 1439 |
+
|
| 1440 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionModel.get_input_embeddings with CLIP_VISION->KOSMOS2_VISION,CLIP->Kosmos2,self.vision_model->self.model
|
| 1441 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1442 |
+
return self.model.embeddings.patch_embedding
|
| 1443 |
+
|
| 1444 |
+
@add_start_docstrings_to_model_forward(KOSMOS2_VISION_INPUTS_DOCSTRING)
|
| 1445 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=Kosmos2VisionConfig)
|
| 1446 |
+
def forward(
|
| 1447 |
+
self,
|
| 1448 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1449 |
+
output_attentions: Optional[bool] = None,
|
| 1450 |
+
output_hidden_states: Optional[bool] = None,
|
| 1451 |
+
return_dict: Optional[bool] = None,
|
| 1452 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 1453 |
+
r"""
|
| 1454 |
+
Returns:
|
| 1455 |
+
|
| 1456 |
+
"""
|
| 1457 |
+
return self.model(
|
| 1458 |
+
pixel_values=pixel_values,
|
| 1459 |
+
output_attentions=output_attentions,
|
| 1460 |
+
output_hidden_states=output_hidden_states,
|
| 1461 |
+
return_dict=return_dict,
|
| 1462 |
+
)
|
| 1463 |
+
|
| 1464 |
+
|
| 1465 |
+
class Kosmos2TextModel(Kosmos2PreTrainedModel):
|
| 1466 |
+
config_class = Kosmos2TextConfig
|
| 1467 |
+
|
| 1468 |
+
def __init__(self, config: Kosmos2TextConfig):
|
| 1469 |
+
super().__init__(config)
|
| 1470 |
+
self.model = Kosmos2TextTransformer(config)
|
| 1471 |
+
# Initialize weights and apply final processing
|
| 1472 |
+
self.post_init()
|
| 1473 |
+
|
| 1474 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1475 |
+
return self.model.embed_tokens
|
| 1476 |
+
|
| 1477 |
+
def set_input_embeddings(self, value):
|
| 1478 |
+
self.model.embed_tokens = value
|
| 1479 |
+
|
| 1480 |
+
@add_start_docstrings_to_model_forward(KOSMOS2_TEXT_INPUTS_DOCSTRING)
|
| 1481 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPastAndCrossAttentions, config_class=Kosmos2TextConfig)
|
| 1482 |
+
def forward(
|
| 1483 |
+
self,
|
| 1484 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1485 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1486 |
+
image_embeds: Optional[torch.Tensor] = None,
|
| 1487 |
+
image_embeds_position_mask: Optional[torch.Tensor] = None,
|
| 1488 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1489 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1490 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1491 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1492 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1493 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1494 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1495 |
+
use_cache: Optional[bool] = None,
|
| 1496 |
+
output_attentions: Optional[bool] = None,
|
| 1497 |
+
output_hidden_states: Optional[bool] = None,
|
| 1498 |
+
return_dict: Optional[bool] = None,
|
| 1499 |
+
) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
|
| 1500 |
+
r"""
|
| 1501 |
+
Returns:
|
| 1502 |
+
|
| 1503 |
+
"""
|
| 1504 |
+
return self.model(
|
| 1505 |
+
input_ids=input_ids,
|
| 1506 |
+
attention_mask=attention_mask,
|
| 1507 |
+
image_embeds=image_embeds,
|
| 1508 |
+
image_embeds_position_mask=image_embeds_position_mask,
|
| 1509 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1510 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1511 |
+
head_mask=head_mask,
|
| 1512 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1513 |
+
past_key_values=past_key_values,
|
| 1514 |
+
inputs_embeds=inputs_embeds,
|
| 1515 |
+
position_ids=position_ids,
|
| 1516 |
+
use_cache=use_cache,
|
| 1517 |
+
output_attentions=output_attentions,
|
| 1518 |
+
output_hidden_states=output_hidden_states,
|
| 1519 |
+
return_dict=return_dict,
|
| 1520 |
+
)
|
| 1521 |
+
|
| 1522 |
+
|
| 1523 |
+
@add_start_docstrings(
|
| 1524 |
+
"""
|
| 1525 |
+
The text model from KOSMOS-2 with a language modeling head on top (linear layer with weights tied to the input
|
| 1526 |
+
embeddings).
|
| 1527 |
+
""",
|
| 1528 |
+
KOSMOS2_START_DOCSTRING,
|
| 1529 |
+
)
|
| 1530 |
+
class Kosmos2TextForCausalLM(Kosmos2PreTrainedModel):
|
| 1531 |
+
config_class = Kosmos2TextConfig
|
| 1532 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 1533 |
+
|
| 1534 |
+
def __init__(self, config: Kosmos2TextConfig):
|
| 1535 |
+
super().__init__(config)
|
| 1536 |
+
|
| 1537 |
+
self.model = Kosmos2TextTransformer(config)
|
| 1538 |
+
self.lm_head = nn.Linear(in_features=config.embed_dim, out_features=config.vocab_size, bias=False)
|
| 1539 |
+
|
| 1540 |
+
# Initialize weights and apply final processing
|
| 1541 |
+
self.post_init()
|
| 1542 |
+
|
| 1543 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1544 |
+
return self.model.embed_tokens
|
| 1545 |
+
|
| 1546 |
+
def set_input_embeddings(self, value):
|
| 1547 |
+
self.model.embed_tokens = value
|
| 1548 |
+
|
| 1549 |
+
def get_output_embeddings(self) -> nn.Module:
|
| 1550 |
+
return self.lm_head
|
| 1551 |
+
|
| 1552 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1553 |
+
self.lm_head = new_embeddings
|
| 1554 |
+
|
| 1555 |
+
@add_start_docstrings_to_model_forward(KOSMOS2_TEXT_INPUTS_DOCSTRING)
|
| 1556 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=Kosmos2TextConfig)
|
| 1557 |
+
def forward(
|
| 1558 |
+
self,
|
| 1559 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1560 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1561 |
+
image_embeds: Optional[torch.Tensor] = None,
|
| 1562 |
+
image_embeds_position_mask: Optional[torch.Tensor] = None,
|
| 1563 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1564 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1565 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1566 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1567 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1568 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1569 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1570 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1571 |
+
use_cache: Optional[bool] = None,
|
| 1572 |
+
output_attentions: Optional[bool] = None,
|
| 1573 |
+
output_hidden_states: Optional[bool] = None,
|
| 1574 |
+
return_dict: Optional[bool] = None,
|
| 1575 |
+
) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
|
| 1576 |
+
r"""
|
| 1577 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1578 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
| 1579 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
| 1580 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1581 |
+
|
| 1582 |
+
Returns:
|
| 1583 |
+
|
| 1584 |
+
"""
|
| 1585 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1586 |
+
|
| 1587 |
+
if labels is not None:
|
| 1588 |
+
if use_cache:
|
| 1589 |
+
logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
|
| 1590 |
+
use_cache = False
|
| 1591 |
+
|
| 1592 |
+
outputs = self.model(
|
| 1593 |
+
input_ids=input_ids,
|
| 1594 |
+
attention_mask=attention_mask,
|
| 1595 |
+
image_embeds=image_embeds,
|
| 1596 |
+
image_embeds_position_mask=image_embeds_position_mask,
|
| 1597 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1598 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1599 |
+
head_mask=head_mask,
|
| 1600 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1601 |
+
past_key_values=past_key_values,
|
| 1602 |
+
inputs_embeds=inputs_embeds,
|
| 1603 |
+
position_ids=position_ids,
|
| 1604 |
+
use_cache=use_cache,
|
| 1605 |
+
output_attentions=output_attentions,
|
| 1606 |
+
output_hidden_states=output_hidden_states,
|
| 1607 |
+
return_dict=return_dict,
|
| 1608 |
+
)
|
| 1609 |
+
lm_logits = self.lm_head(outputs[0])
|
| 1610 |
+
|
| 1611 |
+
loss = None
|
| 1612 |
+
if labels is not None:
|
| 1613 |
+
# move labels to correct device to enable model parallelism
|
| 1614 |
+
labels = labels.to(lm_logits.device)
|
| 1615 |
+
# Shift so that tokens < n predict n
|
| 1616 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
| 1617 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 1618 |
+
batch_size, seq_length, vocab_size = shift_logits.shape
|
| 1619 |
+
# Flatten the tokens
|
| 1620 |
+
loss_fct = CrossEntropyLoss()
|
| 1621 |
+
loss = loss_fct(
|
| 1622 |
+
shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)
|
| 1623 |
+
)
|
| 1624 |
+
|
| 1625 |
+
if not return_dict:
|
| 1626 |
+
output = (lm_logits,) + outputs[1:]
|
| 1627 |
+
return (loss,) + output if loss is not None else output
|
| 1628 |
+
|
| 1629 |
+
return CausalLMOutputWithCrossAttentions(
|
| 1630 |
+
loss=loss,
|
| 1631 |
+
logits=lm_logits,
|
| 1632 |
+
past_key_values=outputs.past_key_values,
|
| 1633 |
+
hidden_states=outputs.hidden_states,
|
| 1634 |
+
attentions=outputs.attentions,
|
| 1635 |
+
cross_attentions=outputs.cross_attentions,
|
| 1636 |
+
)
|
| 1637 |
+
|
| 1638 |
+
def prepare_inputs_for_generation(
|
| 1639 |
+
self,
|
| 1640 |
+
input_ids,
|
| 1641 |
+
image_embeds=None,
|
| 1642 |
+
image_embeds_position_mask=None,
|
| 1643 |
+
past_key_values=None,
|
| 1644 |
+
attention_mask=None,
|
| 1645 |
+
use_cache=None,
|
| 1646 |
+
**model_kwargs,
|
| 1647 |
+
):
|
| 1648 |
+
input_shape = input_ids.shape
|
| 1649 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
| 1650 |
+
if attention_mask is None:
|
| 1651 |
+
attention_mask = input_ids.new_ones(input_shape)
|
| 1652 |
+
|
| 1653 |
+
position_ids = None
|
| 1654 |
+
|
| 1655 |
+
# cut input_ids if past_key_values is used
|
| 1656 |
+
if past_key_values is not None:
|
| 1657 |
+
position_ids = create_position_ids_from_input_ids(
|
| 1658 |
+
input_ids,
|
| 1659 |
+
padding_idx=self.config.pad_token_id,
|
| 1660 |
+
past_key_values_length=0,
|
| 1661 |
+
)[:, -1:]
|
| 1662 |
+
|
| 1663 |
+
input_ids = input_ids[:, -1:]
|
| 1664 |
+
# the image info. is already encoded into the past keys/values
|
| 1665 |
+
image_embeds = None
|
| 1666 |
+
image_embeds_position_mask = None
|
| 1667 |
+
elif image_embeds_position_mask is not None:
|
| 1668 |
+
# appending `False` to `image_embeds_position_mask` (because `input_ids` grows during generation)
|
| 1669 |
+
batch_size, seq_len = input_ids.size()
|
| 1670 |
+
mask_len = image_embeds_position_mask.size()[-1]
|
| 1671 |
+
image_embeds_position_mask = torch.cat(
|
| 1672 |
+
(
|
| 1673 |
+
image_embeds_position_mask,
|
| 1674 |
+
torch.zeros(size=(batch_size, seq_len - mask_len), dtype=torch.bool, device=input_ids.device),
|
| 1675 |
+
),
|
| 1676 |
+
dim=1,
|
| 1677 |
+
)
|
| 1678 |
+
|
| 1679 |
+
return {
|
| 1680 |
+
"input_ids": input_ids,
|
| 1681 |
+
"image_embeds": image_embeds,
|
| 1682 |
+
"image_embeds_position_mask": image_embeds_position_mask,
|
| 1683 |
+
"past_key_values": past_key_values,
|
| 1684 |
+
"attention_mask": attention_mask,
|
| 1685 |
+
"position_ids": position_ids,
|
| 1686 |
+
"use_cache": use_cache,
|
| 1687 |
+
}
|
| 1688 |
+
|
| 1689 |
+
@staticmethod
|
| 1690 |
+
# Copied from transformers.models.umt5.modeling_umt5.UMT5ForConditionalGeneration._reorder_cache
|
| 1691 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 1692 |
+
reordered_past = ()
|
| 1693 |
+
for layer_past in past_key_values:
|
| 1694 |
+
reordered_past += (
|
| 1695 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 1696 |
+
)
|
| 1697 |
+
return reordered_past
|
| 1698 |
+
|
| 1699 |
+
|
| 1700 |
+
class Kosmos2ImageToTextProjection(nn.Module):
|
| 1701 |
+
"""The layer that transforms the image model's output to part of the text model's input (namely, image features)"""
|
| 1702 |
+
|
| 1703 |
+
def __init__(self, config: Kosmos2Config):
|
| 1704 |
+
super().__init__()
|
| 1705 |
+
self.dense = nn.Linear(config.vision_config.hidden_size, config.text_config.embed_dim)
|
| 1706 |
+
self.latent_query = nn.Parameter(torch.randn(config.latent_query_num, config.text_config.embed_dim))
|
| 1707 |
+
|
| 1708 |
+
self.x_attn = KosmosTextAttention(
|
| 1709 |
+
config.text_config,
|
| 1710 |
+
config.text_config.embed_dim,
|
| 1711 |
+
config.text_config.attention_heads,
|
| 1712 |
+
dropout=config.text_config.attention_dropout,
|
| 1713 |
+
is_decoder=False,
|
| 1714 |
+
add_inner_attn_layernorm=False,
|
| 1715 |
+
)
|
| 1716 |
+
|
| 1717 |
+
def forward(self, features):
|
| 1718 |
+
hidden_states = self.dense(features)
|
| 1719 |
+
|
| 1720 |
+
# shape = [batch, latent_query_num, h_dim]
|
| 1721 |
+
latent_query = self.latent_query.unsqueeze(0).expand(hidden_states.size(0), -1, -1)
|
| 1722 |
+
key_value_states = torch.cat([hidden_states, latent_query], dim=1)
|
| 1723 |
+
|
| 1724 |
+
hidden_states, attn_weights, _ = self.x_attn(
|
| 1725 |
+
hidden_states=latent_query,
|
| 1726 |
+
encoder_hidden_states=key_value_states,
|
| 1727 |
+
past_key_value=None,
|
| 1728 |
+
attention_mask=None,
|
| 1729 |
+
output_attentions=None,
|
| 1730 |
+
)
|
| 1731 |
+
|
| 1732 |
+
return hidden_states, attn_weights
|
| 1733 |
+
|
| 1734 |
+
|
| 1735 |
+
@add_start_docstrings(
|
| 1736 |
+
"""
|
| 1737 |
+
KOSMOS-2 Model for generating text and image features. The model consists of a vision encoder and a language model.
|
| 1738 |
+
""",
|
| 1739 |
+
KOSMOS2_START_DOCSTRING,
|
| 1740 |
+
)
|
| 1741 |
+
class Kosmos2Model(Kosmos2PreTrainedModel):
|
| 1742 |
+
config_class = Kosmos2Config
|
| 1743 |
+
main_input_name = "pixel_values"
|
| 1744 |
+
|
| 1745 |
+
def __init__(self, config: Kosmos2Config):
|
| 1746 |
+
super().__init__(config)
|
| 1747 |
+
|
| 1748 |
+
self.text_model = Kosmos2TextModel(config.text_config)
|
| 1749 |
+
self.vision_model = Kosmos2VisionModel(config.vision_config)
|
| 1750 |
+
self.image_to_text_projection = Kosmos2ImageToTextProjection(config)
|
| 1751 |
+
|
| 1752 |
+
# Initialize weights and apply final processing
|
| 1753 |
+
self.post_init()
|
| 1754 |
+
|
| 1755 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1756 |
+
return self.text_model.model.embed_tokens
|
| 1757 |
+
|
| 1758 |
+
def set_input_embeddings(self, value):
|
| 1759 |
+
self.text_model.model.embed_tokens = value
|
| 1760 |
+
|
| 1761 |
+
@add_start_docstrings_to_model_forward(KOSMOS2_INPUTS_DOCSTRING)
|
| 1762 |
+
@replace_return_docstrings(output_type=Kosmos2ModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 1763 |
+
def forward(
|
| 1764 |
+
self,
|
| 1765 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 1766 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1767 |
+
image_embeds_position_mask: Optional[torch.Tensor] = None,
|
| 1768 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1769 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1770 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1771 |
+
image_embeds: Optional[torch.Tensor] = None,
|
| 1772 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1773 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1774 |
+
use_cache: Optional[bool] = None,
|
| 1775 |
+
output_attentions: Optional[bool] = None,
|
| 1776 |
+
output_hidden_states: Optional[bool] = None,
|
| 1777 |
+
return_dict: Optional[bool] = None,
|
| 1778 |
+
) -> Union[Tuple, Kosmos2ModelOutput]:
|
| 1779 |
+
r"""
|
| 1780 |
+
Returns:
|
| 1781 |
+
|
| 1782 |
+
Examples:
|
| 1783 |
+
|
| 1784 |
+
```python
|
| 1785 |
+
>>> from PIL import Image
|
| 1786 |
+
>>> import requests
|
| 1787 |
+
>>> from transformers import AutoProcessor, Kosmos2Model
|
| 1788 |
+
|
| 1789 |
+
>>> model = Kosmos2Model.from_pretrained("microsoft/kosmos-2-patch14-224")
|
| 1790 |
+
>>> processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224")
|
| 1791 |
+
|
| 1792 |
+
>>> url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
|
| 1793 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1794 |
+
|
| 1795 |
+
>>> text = (
|
| 1796 |
+
... "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863>"
|
| 1797 |
+
... "</object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911>"
|
| 1798 |
+
... "</object>"
|
| 1799 |
+
... )
|
| 1800 |
+
|
| 1801 |
+
>>> inputs = processor(text=text, images=image, return_tensors="pt", add_eos_token=True)
|
| 1802 |
+
|
| 1803 |
+
>>> last_hidden_state = model(
|
| 1804 |
+
... pixel_values=inputs["pixel_values"],
|
| 1805 |
+
... input_ids=inputs["input_ids"],
|
| 1806 |
+
... attention_mask=inputs["attention_mask"],
|
| 1807 |
+
... image_embeds_position_mask=inputs["image_embeds_position_mask"],
|
| 1808 |
+
... ).last_hidden_state
|
| 1809 |
+
>>> list(last_hidden_state.shape)
|
| 1810 |
+
[1, 91, 2048]
|
| 1811 |
+
```"""
|
| 1812 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1813 |
+
output_hidden_states = (
|
| 1814 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1815 |
+
)
|
| 1816 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1817 |
+
|
| 1818 |
+
vision_model_output = None
|
| 1819 |
+
projection_attentions = None
|
| 1820 |
+
if image_embeds is None:
|
| 1821 |
+
if pixel_values is None:
|
| 1822 |
+
raise ValueError("You have to specify either `pixel_values` or `image_embeds`.")
|
| 1823 |
+
|
| 1824 |
+
vision_model_output = self.vision_model(
|
| 1825 |
+
pixel_values=pixel_values,
|
| 1826 |
+
output_attentions=output_attentions,
|
| 1827 |
+
output_hidden_states=output_hidden_states,
|
| 1828 |
+
return_dict=return_dict,
|
| 1829 |
+
)
|
| 1830 |
+
# The whole `last_hidden_state` through `post_layernorm` instead of just `pooled_output`.
|
| 1831 |
+
image_embeds = self.vision_model.model.post_layernorm(vision_model_output[0])
|
| 1832 |
+
# normalized features
|
| 1833 |
+
image_embeds = nn.functional.normalize(image_embeds, dim=-1)
|
| 1834 |
+
image_embeds, projection_attentions = self.image_to_text_projection(image_embeds)
|
| 1835 |
+
|
| 1836 |
+
outputs = self.text_model(
|
| 1837 |
+
input_ids=input_ids,
|
| 1838 |
+
attention_mask=attention_mask,
|
| 1839 |
+
image_embeds=image_embeds,
|
| 1840 |
+
image_embeds_position_mask=image_embeds_position_mask,
|
| 1841 |
+
head_mask=head_mask,
|
| 1842 |
+
past_key_values=past_key_values,
|
| 1843 |
+
inputs_embeds=inputs_embeds,
|
| 1844 |
+
position_ids=position_ids,
|
| 1845 |
+
use_cache=use_cache,
|
| 1846 |
+
output_attentions=output_attentions,
|
| 1847 |
+
output_hidden_states=output_hidden_states,
|
| 1848 |
+
return_dict=return_dict,
|
| 1849 |
+
)
|
| 1850 |
+
|
| 1851 |
+
if not return_dict:
|
| 1852 |
+
outputs = outputs + (image_embeds, projection_attentions, vision_model_output)
|
| 1853 |
+
return tuple(output for output in outputs if output is not None)
|
| 1854 |
+
|
| 1855 |
+
return Kosmos2ModelOutput(
|
| 1856 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 1857 |
+
past_key_values=outputs.past_key_values,
|
| 1858 |
+
hidden_states=outputs.hidden_states,
|
| 1859 |
+
attentions=outputs.attentions,
|
| 1860 |
+
image_embeds=image_embeds,
|
| 1861 |
+
projection_attentions=projection_attentions,
|
| 1862 |
+
vision_model_output=vision_model_output,
|
| 1863 |
+
)
|
| 1864 |
+
|
| 1865 |
+
|
| 1866 |
+
@add_start_docstrings(
|
| 1867 |
+
"""
|
| 1868 |
+
KOSMOS-2 Model for generating text and bounding boxes given an image. The model consists of a vision encoder and a
|
| 1869 |
+
language model.
|
| 1870 |
+
""",
|
| 1871 |
+
KOSMOS2_START_DOCSTRING,
|
| 1872 |
+
)
|
| 1873 |
+
class Kosmos2ForConditionalGeneration(Kosmos2PreTrainedModel):
|
| 1874 |
+
config_class = Kosmos2Config
|
| 1875 |
+
main_input_name = "pixel_values"
|
| 1876 |
+
_tied_weights_keys = ["text_model.lm_head.weight"]
|
| 1877 |
+
|
| 1878 |
+
def __init__(self, config: Kosmos2Config):
|
| 1879 |
+
super().__init__(config)
|
| 1880 |
+
|
| 1881 |
+
self.text_model = Kosmos2TextForCausalLM(config.text_config)
|
| 1882 |
+
self.vision_model = Kosmos2VisionModel(config.vision_config)
|
| 1883 |
+
|
| 1884 |
+
self.image_to_text_projection = Kosmos2ImageToTextProjection(config)
|
| 1885 |
+
|
| 1886 |
+
# Initialize weights and apply final processing
|
| 1887 |
+
self.post_init()
|
| 1888 |
+
|
| 1889 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1890 |
+
return self.text_model.model.embed_tokens
|
| 1891 |
+
|
| 1892 |
+
def set_input_embeddings(self, value):
|
| 1893 |
+
self.text_model.model.embed_tokens = value
|
| 1894 |
+
|
| 1895 |
+
def get_output_embeddings(self) -> nn.Module:
|
| 1896 |
+
return self.text_model.get_output_embeddings()
|
| 1897 |
+
|
| 1898 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1899 |
+
self.text_model.set_output_embeddings(new_embeddings)
|
| 1900 |
+
|
| 1901 |
+
@add_start_docstrings_to_model_forward(KOSMOS2_INPUTS_DOCSTRING)
|
| 1902 |
+
@replace_return_docstrings(output_type=Kosmos2ForConditionalGenerationModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 1903 |
+
def forward(
|
| 1904 |
+
self,
|
| 1905 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 1906 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1907 |
+
image_embeds_position_mask: Optional[torch.Tensor] = None,
|
| 1908 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1909 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1910 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1911 |
+
image_embeds: Optional[torch.Tensor] = None,
|
| 1912 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1913 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1914 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1915 |
+
use_cache: Optional[bool] = None,
|
| 1916 |
+
output_attentions: Optional[bool] = None,
|
| 1917 |
+
output_hidden_states: Optional[bool] = None,
|
| 1918 |
+
return_dict: Optional[bool] = None,
|
| 1919 |
+
) -> Union[Tuple, Kosmos2ForConditionalGenerationModelOutput]:
|
| 1920 |
+
r"""
|
| 1921 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1922 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
| 1923 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
| 1924 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1925 |
+
|
| 1926 |
+
Returns:
|
| 1927 |
+
|
| 1928 |
+
Examples:
|
| 1929 |
+
|
| 1930 |
+
```python
|
| 1931 |
+
>>> from PIL import Image
|
| 1932 |
+
>>> import requests
|
| 1933 |
+
>>> from transformers import AutoProcessor, Kosmos2ForConditionalGeneration
|
| 1934 |
+
|
| 1935 |
+
>>> model = Kosmos2ForConditionalGeneration.from_pretrained("microsoft/kosmos-2-patch14-224")
|
| 1936 |
+
>>> processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224")
|
| 1937 |
+
|
| 1938 |
+
>>> url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
|
| 1939 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1940 |
+
|
| 1941 |
+
>>> prompt = "<grounding> An image of"
|
| 1942 |
+
|
| 1943 |
+
>>> inputs = processor(text=prompt, images=image, return_tensors="pt")
|
| 1944 |
+
|
| 1945 |
+
>>> generated_ids = model.generate(
|
| 1946 |
+
... pixel_values=inputs["pixel_values"],
|
| 1947 |
+
... input_ids=inputs["input_ids"],
|
| 1948 |
+
... attention_mask=inputs["attention_mask"],
|
| 1949 |
+
... image_embeds=None,
|
| 1950 |
+
... image_embeds_position_mask=inputs["image_embeds_position_mask"],
|
| 1951 |
+
... use_cache=True,
|
| 1952 |
+
... max_new_tokens=64,
|
| 1953 |
+
... )
|
| 1954 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 1955 |
+
>>> processed_text = processor.post_process_generation(generated_text, cleanup_and_extract=False)
|
| 1956 |
+
>>> processed_text
|
| 1957 |
+
'<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>.'
|
| 1958 |
+
|
| 1959 |
+
>>> caption, entities = processor.post_process_generation(generated_text)
|
| 1960 |
+
>>> caption
|
| 1961 |
+
'An image of a snowman warming himself by a fire.'
|
| 1962 |
+
|
| 1963 |
+
>>> entities
|
| 1964 |
+
[('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]
|
| 1965 |
+
```"""
|
| 1966 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1967 |
+
output_hidden_states = (
|
| 1968 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1969 |
+
)
|
| 1970 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1971 |
+
|
| 1972 |
+
vision_model_output = None
|
| 1973 |
+
projection_attentions = None
|
| 1974 |
+
if image_embeds is None:
|
| 1975 |
+
if pixel_values is None:
|
| 1976 |
+
raise ValueError("You have to specify either `pixel_values` or `image_embeds`.")
|
| 1977 |
+
|
| 1978 |
+
vision_model_output = self.vision_model(
|
| 1979 |
+
pixel_values=pixel_values,
|
| 1980 |
+
output_attentions=output_attentions,
|
| 1981 |
+
output_hidden_states=output_hidden_states,
|
| 1982 |
+
return_dict=return_dict,
|
| 1983 |
+
)
|
| 1984 |
+
# The whole `last_hidden_state` through `post_layernorm` instead of just `pooled_output`.
|
| 1985 |
+
image_embeds = self.vision_model.model.post_layernorm(vision_model_output[0])
|
| 1986 |
+
# normalized features
|
| 1987 |
+
image_embeds = nn.functional.normalize(image_embeds, dim=-1)
|
| 1988 |
+
image_embeds, projection_attentions = self.image_to_text_projection(image_embeds)
|
| 1989 |
+
|
| 1990 |
+
lm_outputs = self.text_model(
|
| 1991 |
+
input_ids=input_ids,
|
| 1992 |
+
attention_mask=attention_mask,
|
| 1993 |
+
image_embeds=image_embeds,
|
| 1994 |
+
image_embeds_position_mask=image_embeds_position_mask,
|
| 1995 |
+
head_mask=head_mask,
|
| 1996 |
+
past_key_values=past_key_values,
|
| 1997 |
+
inputs_embeds=inputs_embeds,
|
| 1998 |
+
position_ids=position_ids,
|
| 1999 |
+
labels=labels,
|
| 2000 |
+
use_cache=use_cache,
|
| 2001 |
+
output_attentions=output_attentions,
|
| 2002 |
+
output_hidden_states=output_hidden_states,
|
| 2003 |
+
return_dict=return_dict,
|
| 2004 |
+
)
|
| 2005 |
+
|
| 2006 |
+
if not return_dict:
|
| 2007 |
+
outputs = lm_outputs + (image_embeds, projection_attentions, vision_model_output)
|
| 2008 |
+
return tuple(output for output in outputs if output is not None)
|
| 2009 |
+
|
| 2010 |
+
return Kosmos2ForConditionalGenerationModelOutput(
|
| 2011 |
+
loss=lm_outputs.loss,
|
| 2012 |
+
logits=lm_outputs.logits,
|
| 2013 |
+
past_key_values=lm_outputs.past_key_values,
|
| 2014 |
+
hidden_states=lm_outputs.hidden_states,
|
| 2015 |
+
attentions=lm_outputs.attentions,
|
| 2016 |
+
image_embeds=image_embeds,
|
| 2017 |
+
projection_attentions=projection_attentions,
|
| 2018 |
+
vision_model_output=vision_model_output,
|
| 2019 |
+
)
|
| 2020 |
+
|
| 2021 |
+
def generate(
|
| 2022 |
+
self,
|
| 2023 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 2024 |
+
image_embeds_position_mask: Optional[torch.Tensor] = None,
|
| 2025 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 2026 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 2027 |
+
image_embeds: Optional[torch.Tensor] = None,
|
| 2028 |
+
**kwargs,
|
| 2029 |
+
):
|
| 2030 |
+
# in order to allow `inputs` argument (as in `GenerationMixin`)
|
| 2031 |
+
inputs = kwargs.pop("inputs", None)
|
| 2032 |
+
if pixel_values is not None and inputs is not None:
|
| 2033 |
+
raise ValueError(
|
| 2034 |
+
f"`inputs`: {inputs} were passed alongside `pixel_values` which is not allowed."
|
| 2035 |
+
f"Make sure to either pass `inputs` or pixel_values=..."
|
| 2036 |
+
)
|
| 2037 |
+
if pixel_values is None and inputs is not None:
|
| 2038 |
+
pixel_values = inputs
|
| 2039 |
+
|
| 2040 |
+
if image_embeds is None:
|
| 2041 |
+
vision_model_output = self.vision_model(pixel_values)
|
| 2042 |
+
# The whole `last_hidden_state` through `post_layernorm` instead of just `pooled_output`.
|
| 2043 |
+
image_embeds = self.vision_model.model.post_layernorm(vision_model_output[0])
|
| 2044 |
+
# normalized features
|
| 2045 |
+
image_embeds = nn.functional.normalize(image_embeds, dim=-1)
|
| 2046 |
+
image_embeds, projection_attentions = self.image_to_text_projection(image_embeds)
|
| 2047 |
+
|
| 2048 |
+
output = self.text_model.generate(
|
| 2049 |
+
input_ids=input_ids,
|
| 2050 |
+
attention_mask=attention_mask,
|
| 2051 |
+
image_embeds=image_embeds,
|
| 2052 |
+
image_embeds_position_mask=image_embeds_position_mask,
|
| 2053 |
+
**kwargs,
|
| 2054 |
+
)
|
| 2055 |
+
|
| 2056 |
+
return output
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/kosmos2/processing_kosmos2.py
ADDED
|
@@ -0,0 +1,666 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 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 |
+
"""Processor class for KOSMOS-2."""
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
import math
|
| 19 |
+
import re
|
| 20 |
+
from typing import List, Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
from ...image_processing_utils import BatchFeature
|
| 23 |
+
from ...image_utils import ImageInput, is_batched
|
| 24 |
+
from ...processing_utils import ProcessorMixin
|
| 25 |
+
from ...tokenization_utils import AddedToken
|
| 26 |
+
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, TextInput, TruncationStrategy
|
| 27 |
+
from ...utils import TensorType
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
BboxInput = Union[
|
| 31 |
+
List[Tuple[int, int]],
|
| 32 |
+
List[Tuple[float, float, float, float]],
|
| 33 |
+
List[List[Tuple[int, int]]],
|
| 34 |
+
List[List[Tuple[float, float, float]]],
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class Kosmos2Processor(ProcessorMixin):
|
| 39 |
+
r"""
|
| 40 |
+
Constructs an KOSMOS-2 processor which wraps a KOSMOS-2 image processor and a KOSMOS-2 tokenizer into a single
|
| 41 |
+
processor.
|
| 42 |
+
|
| 43 |
+
[`Kosmos2Processor`] offers all the functionalities of [`CLIPImageProcessor`] and some functionalities of
|
| 44 |
+
[`XLMRobertaTokenizerFast`]. See the docstring of [`~Kosmos2Processor.__call__`] and [`~Kosmos2Processor.decode`]
|
| 45 |
+
for more information.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
image_processor (`CLIPImageProcessor`):
|
| 49 |
+
An instance of [`CLIPImageProcessor`]. The image processor is a required input.
|
| 50 |
+
tokenizer (`XLMRobertaTokenizerFast`):
|
| 51 |
+
An instance of ['XLMRobertaTokenizerFast`]. The tokenizer is a required input.
|
| 52 |
+
num_patch_index_tokens (`int`, *optional*, defaults to 1024):
|
| 53 |
+
The number of tokens that represent patch indices.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
attributes = ["image_processor", "tokenizer"]
|
| 57 |
+
image_processor_class = "CLIPImageProcessor"
|
| 58 |
+
tokenizer_class = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")
|
| 59 |
+
|
| 60 |
+
def __init__(self, image_processor, tokenizer, num_patch_index_tokens=1024):
|
| 61 |
+
tokenizer.return_token_type_ids = False
|
| 62 |
+
|
| 63 |
+
self.eod_token = "</doc>"
|
| 64 |
+
|
| 65 |
+
self.boi_token = "<image>"
|
| 66 |
+
self.eoi_token = "</image>"
|
| 67 |
+
|
| 68 |
+
self.eoc_token = "</chunk>"
|
| 69 |
+
self.eol_token = "</line>"
|
| 70 |
+
|
| 71 |
+
self.bop_token = "<phrase>"
|
| 72 |
+
self.eop_token = "</phrase>"
|
| 73 |
+
|
| 74 |
+
self.boo_token = "<object>"
|
| 75 |
+
self.eoo_token = "</object>"
|
| 76 |
+
|
| 77 |
+
self.dom_token = "</delimiter_of_multi_objects/>"
|
| 78 |
+
|
| 79 |
+
self.grd_token = "<grounding>"
|
| 80 |
+
|
| 81 |
+
self.tag_tokens = [
|
| 82 |
+
self.eod_token,
|
| 83 |
+
self.boi_token,
|
| 84 |
+
self.eoi_token,
|
| 85 |
+
self.eoc_token,
|
| 86 |
+
self.eol_token,
|
| 87 |
+
self.bop_token,
|
| 88 |
+
self.eop_token,
|
| 89 |
+
self.boo_token,
|
| 90 |
+
self.eoo_token,
|
| 91 |
+
self.dom_token,
|
| 92 |
+
self.grd_token,
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
self.num_patch_index_tokens = num_patch_index_tokens
|
| 96 |
+
patch_index_tokens = [f"<patch_index_{str(x).zfill(4)}>" for x in range(self.num_patch_index_tokens)]
|
| 97 |
+
|
| 98 |
+
tokens_to_add = []
|
| 99 |
+
for token in self.tag_tokens + patch_index_tokens:
|
| 100 |
+
tokens_to_add.append(AddedToken(token, lstrip=True, rstrip=False, normalized=False))
|
| 101 |
+
tokenizer.add_tokens(tokens_to_add)
|
| 102 |
+
|
| 103 |
+
super().__init__(image_processor, tokenizer)
|
| 104 |
+
|
| 105 |
+
def __call__(
|
| 106 |
+
self,
|
| 107 |
+
images: ImageInput = None,
|
| 108 |
+
text: Union[TextInput, List[TextInput]] = None,
|
| 109 |
+
bboxes: BboxInput = None,
|
| 110 |
+
num_image_tokens: Optional[int] = 64,
|
| 111 |
+
first_image_token_id: Optional[int] = None,
|
| 112 |
+
add_special_tokens: bool = True,
|
| 113 |
+
add_eos_token: bool = False,
|
| 114 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 115 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
| 116 |
+
max_length: Optional[int] = None,
|
| 117 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 118 |
+
return_attention_mask: Optional[bool] = None,
|
| 119 |
+
return_length: bool = False,
|
| 120 |
+
verbose: bool = True,
|
| 121 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 122 |
+
**kwargs,
|
| 123 |
+
) -> BatchFeature:
|
| 124 |
+
"""
|
| 125 |
+
This method uses [`CLIPImageProcessor.__call__`] method to prepare image(s) for the model, and
|
| 126 |
+
[`XLMRobertaTokenizerFast.__call__`] to prepare text for the model.
|
| 127 |
+
|
| 128 |
+
Please refer to the docstring of the above two methods for more information.
|
| 129 |
+
|
| 130 |
+
The rest of this documentation shows the arguments specific to `Kosmos2Processor`.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
bboxes (`Union[List[Tuple[int]], List[Tuple[float]], List[List[Tuple[int]]], List[List[Tuple[float]]]]`, *optional*):
|
| 134 |
+
The bounding bboxes associated to `texts`.
|
| 135 |
+
num_image_tokens (`int`, defaults to 64):
|
| 136 |
+
The number of (consecutive) places that are used to mark the placeholders to store image information.
|
| 137 |
+
This should be the same as `latent_query_num` in the instance of `Kosmos2Config` you are using.
|
| 138 |
+
first_image_token_id (`int`, *optional*):
|
| 139 |
+
The token id that will be used for the first place of the subsequence that is reserved to store image
|
| 140 |
+
information. If unset, will default to `self.tokenizer.unk_token_id + 1`.
|
| 141 |
+
add_eos_token (`bool`, defaults to `False`):
|
| 142 |
+
Whether or not to include `EOS` token id in the encoding when `add_special_tokens=True`.
|
| 143 |
+
"""
|
| 144 |
+
if images is None and text is None:
|
| 145 |
+
raise ValueError("You have to specify either images or text.")
|
| 146 |
+
|
| 147 |
+
encoding = BatchFeature()
|
| 148 |
+
|
| 149 |
+
if images is not None:
|
| 150 |
+
image_encoding = self.image_processor(images, return_tensors=return_tensors)
|
| 151 |
+
encoding.update(image_encoding)
|
| 152 |
+
|
| 153 |
+
if text is not None:
|
| 154 |
+
text = self.preprocess_examples(text, images, bboxes, num_image_tokens=num_image_tokens)
|
| 155 |
+
|
| 156 |
+
if add_special_tokens and not add_eos_token:
|
| 157 |
+
if isinstance(text, str):
|
| 158 |
+
text = f"{self.tokenizer.bos_token}{text}"
|
| 159 |
+
elif isinstance(text, list):
|
| 160 |
+
text = [f"{self.tokenizer.bos_token}{s}" for s in text]
|
| 161 |
+
|
| 162 |
+
text_encoding = self.tokenizer(
|
| 163 |
+
text=text,
|
| 164 |
+
add_special_tokens=(add_special_tokens and add_eos_token),
|
| 165 |
+
padding=padding and images is None,
|
| 166 |
+
truncation=truncation,
|
| 167 |
+
max_length=max_length,
|
| 168 |
+
pad_to_multiple_of=pad_to_multiple_of if images is None else pad_to_multiple_of,
|
| 169 |
+
return_attention_mask=return_attention_mask,
|
| 170 |
+
verbose=verbose,
|
| 171 |
+
return_tensors=return_tensors if images is None else None,
|
| 172 |
+
**kwargs,
|
| 173 |
+
)
|
| 174 |
+
encoding.update(text_encoding)
|
| 175 |
+
|
| 176 |
+
if text is not None and images is not None:
|
| 177 |
+
# Use the id of the first token after <unk>
|
| 178 |
+
if first_image_token_id is None:
|
| 179 |
+
first_image_token_id = self.tokenizer.unk_token_id + 1
|
| 180 |
+
|
| 181 |
+
# To see if we need one more `0` (for `<s>`) at the beginning of `image_embeds_position_mask`.
|
| 182 |
+
with_bos = add_special_tokens
|
| 183 |
+
|
| 184 |
+
# The first (actual) `<image>` token is always at the 1st or 2nd place (after `<s>` if any). Here we look
|
| 185 |
+
# for the second `<image>` token (which indicate the first image token).
|
| 186 |
+
start_index = int(with_bos) + 1
|
| 187 |
+
|
| 188 |
+
# Add `image_embeds_position_mask`: the leading and trailing `0` are for `boi` and `eoi` tokens. The `1` indicates
|
| 189 |
+
# the places of image tokens.
|
| 190 |
+
image_token_ids = list(range(first_image_token_id, first_image_token_id + num_image_tokens))
|
| 191 |
+
base_image_embeds_position_mask = [0] + [1] * num_image_tokens + [0]
|
| 192 |
+
|
| 193 |
+
# loop over `encoding["input_ids"]`
|
| 194 |
+
input_ids = []
|
| 195 |
+
image_embeds_position_mask = []
|
| 196 |
+
all_input_ids = encoding["input_ids"]
|
| 197 |
+
# not batched -> (changed to) batch of size 1
|
| 198 |
+
if isinstance(text, str):
|
| 199 |
+
all_input_ids = [all_input_ids]
|
| 200 |
+
encoding["attention_mask"] = [encoding["attention_mask"]]
|
| 201 |
+
for text_ids in all_input_ids:
|
| 202 |
+
# change the ids for the fake `<image>` tokens in `input_ids`
|
| 203 |
+
text_ids = text_ids[:start_index] + image_token_ids + text_ids[start_index + num_image_tokens :]
|
| 204 |
+
input_ids.append(text_ids)
|
| 205 |
+
|
| 206 |
+
mask = copy.copy(base_image_embeds_position_mask)
|
| 207 |
+
if with_bos:
|
| 208 |
+
# for `<s>`
|
| 209 |
+
mask = [0] + mask
|
| 210 |
+
# trailing part (which are not related to the image)
|
| 211 |
+
mask += [0] * (len(text_ids) - len(mask))
|
| 212 |
+
image_embeds_position_mask.append(mask)
|
| 213 |
+
|
| 214 |
+
if isinstance(text, list):
|
| 215 |
+
sorted_length = sorted(
|
| 216 |
+
[(idx, len(x)) for idx, x in enumerate(text_encoding.input_ids)], key=lambda x: x[-1]
|
| 217 |
+
)
|
| 218 |
+
_, min_len_not_padded = sorted_length[0]
|
| 219 |
+
idx, _ = sorted_length[-1]
|
| 220 |
+
|
| 221 |
+
text_encoding = self.tokenizer(
|
| 222 |
+
text=[text[idx]],
|
| 223 |
+
add_special_tokens=(add_special_tokens and add_eos_token),
|
| 224 |
+
padding=padding,
|
| 225 |
+
truncation=truncation,
|
| 226 |
+
max_length=max_length,
|
| 227 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 228 |
+
verbose=verbose,
|
| 229 |
+
return_tensors=None,
|
| 230 |
+
**kwargs,
|
| 231 |
+
)
|
| 232 |
+
max_len_padded = len(text_encoding.input_ids[0])
|
| 233 |
+
|
| 234 |
+
if min_len_not_padded != max_len_padded:
|
| 235 |
+
if self.tokenizer.padding_side == "right":
|
| 236 |
+
input_ids = [x + [self.tokenizer.pad_token_id] * (max_len_padded - len(x)) for x in input_ids]
|
| 237 |
+
image_embeds_position_mask = [
|
| 238 |
+
x + [0] * (max_len_padded - len(x)) for x in image_embeds_position_mask
|
| 239 |
+
]
|
| 240 |
+
encoding["attention_mask"] = [
|
| 241 |
+
x + [0] * (max_len_padded - len(x)) for x in encoding["attention_mask"]
|
| 242 |
+
]
|
| 243 |
+
elif self.tokenizer.padding_side == "left":
|
| 244 |
+
input_ids = [[self.tokenizer.pad_token_id] * (max_len_padded - len(x)) + x for x in input_ids]
|
| 245 |
+
image_embeds_position_mask = [
|
| 246 |
+
[0] * (max_len_padded - len(x)) + x for x in image_embeds_position_mask
|
| 247 |
+
]
|
| 248 |
+
encoding["attention_mask"] = [
|
| 249 |
+
[0] * (max_len_padded - len(x)) + x for x in encoding["attention_mask"]
|
| 250 |
+
]
|
| 251 |
+
|
| 252 |
+
# un-batch if necessary
|
| 253 |
+
if isinstance(text, str) and return_tensors is None:
|
| 254 |
+
input_ids = input_ids[0]
|
| 255 |
+
encoding["attention_mask"] = encoding["attention_mask"][0]
|
| 256 |
+
image_embeds_position_mask = image_embeds_position_mask[0]
|
| 257 |
+
|
| 258 |
+
# update (with the target tensor type if specified)
|
| 259 |
+
encoding.update(
|
| 260 |
+
BatchEncoding(
|
| 261 |
+
data={
|
| 262 |
+
"input_ids": input_ids,
|
| 263 |
+
"attention_mask": encoding["attention_mask"],
|
| 264 |
+
"image_embeds_position_mask": image_embeds_position_mask,
|
| 265 |
+
},
|
| 266 |
+
tensor_type=return_tensors,
|
| 267 |
+
)
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
return encoding
|
| 271 |
+
|
| 272 |
+
def _check_bboxes_for_single_text(self, bboxes):
|
| 273 |
+
"""
|
| 274 |
+
Check `bboxes` for a single text example. It could be
|
| 275 |
+
- `None`: no bounding box associated to a text.
|
| 276 |
+
- A list with each element being the bounding boxes associated to one `<phrase> ... </phrase>` pair found
|
| 277 |
+
in a text. This could be:
|
| 278 |
+
- `None`: no bounding box associated to a `<phrase> ... </phrase>` pair.
|
| 279 |
+
- A tuple of 2 integers: A single bounding box specified by patch indices.
|
| 280 |
+
- A tuple of 4 float point number: A single bounding box specified by (normalized) coordinates.
|
| 281 |
+
- A list containing the above 2 tuple types: Multiple bounding boxes for a
|
| 282 |
+
`<phrase> ... </phrase>` pair.
|
| 283 |
+
"""
|
| 284 |
+
if bboxes is None:
|
| 285 |
+
return
|
| 286 |
+
elif not isinstance(bboxes, list):
|
| 287 |
+
raise ValueError("`bboxes` (for a single text example) should be `None` or a list.")
|
| 288 |
+
|
| 289 |
+
# `bbox` is the bounding boxes for a single <phrase> </phrase> pair
|
| 290 |
+
for bbox in bboxes:
|
| 291 |
+
if bbox is None:
|
| 292 |
+
continue
|
| 293 |
+
elif not isinstance(bbox, list):
|
| 294 |
+
bbox = [bbox]
|
| 295 |
+
for element in bbox:
|
| 296 |
+
if not isinstance(element, tuple) or not (
|
| 297 |
+
(len(element) == 2 and all(isinstance(x, int) for x in element))
|
| 298 |
+
or (len(element) == 4 and all(isinstance(x, float) for x in element))
|
| 299 |
+
):
|
| 300 |
+
raise ValueError(
|
| 301 |
+
"Each element in `bboxes` (for a single text example) should be either `None`, a tuple containing "
|
| 302 |
+
"2 integers or 4 float point numbers, or a list containing such tuples. Also "
|
| 303 |
+
"make sure the arguments `texts` and `bboxes` passed to `preprocess_text` are both in "
|
| 304 |
+
"batches or both for a single example."
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
def _preprocess_single_example(self, text, image, bboxes, img_info_tokens):
|
| 308 |
+
text = text.strip()
|
| 309 |
+
if image is not None:
|
| 310 |
+
# Add `<image> ... (fake) image tokens ... </image>`
|
| 311 |
+
text = f"{img_info_tokens} {text}"
|
| 312 |
+
|
| 313 |
+
# Add `<object> <patch_idx_xxxx> <patch_idx_yyy> </object>` after `<phrase> phrase text </phrase>`
|
| 314 |
+
text = self._insert_patch_index_tokens(text, bboxes)
|
| 315 |
+
return text
|
| 316 |
+
|
| 317 |
+
def preprocess_examples(
|
| 318 |
+
self,
|
| 319 |
+
texts: Union[TextInput, List[TextInput]],
|
| 320 |
+
images: ImageInput = None,
|
| 321 |
+
bboxes: BboxInput = None,
|
| 322 |
+
num_image_tokens: Optional[int] = 64,
|
| 323 |
+
) -> Union[str, List[str]]:
|
| 324 |
+
"""Add image and bounding box information to `texts` as image and patch index tokens.
|
| 325 |
+
|
| 326 |
+
Args:
|
| 327 |
+
texts (`Union[TextInput, List[TextInput]]`): The texts to be processed.
|
| 328 |
+
images (`ImageInput`, *optional*): The images associated to `texts`.
|
| 329 |
+
bboxes (`Union[List[Tuple[int]], List[Tuple[float]], List[List[Tuple[int]]], List[List[Tuple[float]]]]`, *optional*):
|
| 330 |
+
The bounding bboxes associated to `texts`.
|
| 331 |
+
num_image_tokens (`int`, *optional*, defaults to 64):
|
| 332 |
+
The number of image tokens (used as latent queries). This should corresponds to the `latent_query_num`
|
| 333 |
+
attribute in `Kosmos2Config`.
|
| 334 |
+
|
| 335 |
+
Returns:
|
| 336 |
+
`Union[TextInput, List[TextInput]]`: The processed texts with image and patch index tokens.
|
| 337 |
+
"""
|
| 338 |
+
# These are fake `<image>` tokens enclosed between (the actual) `<image>` token and `</image>`.
|
| 339 |
+
img_tokens = [self.boi_token] * num_image_tokens
|
| 340 |
+
img_info_tokens = " ".join([self.boi_token] + img_tokens + [self.eoi_token])
|
| 341 |
+
|
| 342 |
+
# make batch to simplify processing logic
|
| 343 |
+
batched = True
|
| 344 |
+
if isinstance(texts, str):
|
| 345 |
+
batched = False
|
| 346 |
+
texts = [texts]
|
| 347 |
+
|
| 348 |
+
if images is None:
|
| 349 |
+
images = [None] * len(texts)
|
| 350 |
+
elif not is_batched(images):
|
| 351 |
+
images = [images]
|
| 352 |
+
if len(texts) != len(images):
|
| 353 |
+
raise ValueError(
|
| 354 |
+
f"The number of examples in `texts` and `images` should be the same. Got {len(texts)} v.s. {len(images)} instead."
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
if not batched:
|
| 358 |
+
self._check_bboxes_for_single_text(bboxes)
|
| 359 |
+
bboxes = [bboxes]
|
| 360 |
+
elif bboxes is not None:
|
| 361 |
+
if not isinstance(bboxes, list):
|
| 362 |
+
raise ValueError("`bboxes` should be `None` or a list (as a batch) when `texts` is passed as a batch.")
|
| 363 |
+
for x in bboxes:
|
| 364 |
+
self._check_bboxes_for_single_text(x)
|
| 365 |
+
else:
|
| 366 |
+
bboxes = [None] * len(texts)
|
| 367 |
+
|
| 368 |
+
if len(bboxes) != len(texts):
|
| 369 |
+
raise ValueError(
|
| 370 |
+
f"The number of examples in `texts` and `bboxes` should be the same. Got {len(texts)} v.s. {len(bboxes)} instead."
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
result = [
|
| 374 |
+
self._preprocess_single_example(text, image, bbox, img_info_tokens)
|
| 375 |
+
for text, image, bbox in zip(texts, images, bboxes)
|
| 376 |
+
]
|
| 377 |
+
# un-batch if necessary
|
| 378 |
+
if not batched:
|
| 379 |
+
result = result[0]
|
| 380 |
+
|
| 381 |
+
return result
|
| 382 |
+
|
| 383 |
+
# Copied from transformers.models.blip.processing_blip.BlipProcessor.batch_decode with BertTokenizerFast->PreTrainedTokenizer
|
| 384 |
+
def batch_decode(self, *args, **kwargs):
|
| 385 |
+
"""
|
| 386 |
+
This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 387 |
+
refer to the docstring of this method for more information.
|
| 388 |
+
"""
|
| 389 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 390 |
+
|
| 391 |
+
# Copied from transformers.models.blip.processing_blip.BlipProcessor.decode with BertTokenizerFast->PreTrainedTokenizer
|
| 392 |
+
def decode(self, *args, **kwargs):
|
| 393 |
+
"""
|
| 394 |
+
This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
|
| 395 |
+
the docstring of this method for more information.
|
| 396 |
+
"""
|
| 397 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 398 |
+
|
| 399 |
+
def post_process_generation(self, text, cleanup_and_extract=True):
|
| 400 |
+
caption = text.split(self.eoi_token)[-1]
|
| 401 |
+
if cleanup_and_extract:
|
| 402 |
+
return clean_text_and_extract_entities_with_bboxes(caption)
|
| 403 |
+
return caption
|
| 404 |
+
|
| 405 |
+
@property
|
| 406 |
+
# Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
|
| 407 |
+
def model_input_names(self):
|
| 408 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 409 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 410 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
| 411 |
+
|
| 412 |
+
def _insert_patch_index_tokens(self, text: str, bboxes: Union[List[Tuple[int]], List[Tuple[float]]]) -> str:
|
| 413 |
+
if bboxes is None or len(bboxes) == 0:
|
| 414 |
+
return text
|
| 415 |
+
|
| 416 |
+
matched_phrases = list(re.finditer(r"<phrase>.+?</phrase>", string=text))
|
| 417 |
+
if len(matched_phrases) != len(bboxes):
|
| 418 |
+
raise ValueError(
|
| 419 |
+
f"The number of elements in `bboxes` should be the same as the number of `<phrase> ... </phrase>` pairs in `text`. Got {len(matched_phrases)} v.s. {len(bboxes)} instead."
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
# insert object's patch index tokens
|
| 423 |
+
# the found `<phrase> ... </phrase>` pairs.
|
| 424 |
+
curr_pos = 0
|
| 425 |
+
buffer = []
|
| 426 |
+
for matched, bbox in zip(matched_phrases, bboxes):
|
| 427 |
+
_, end = matched.span()
|
| 428 |
+
buffer.append(text[curr_pos:end])
|
| 429 |
+
curr_pos = end
|
| 430 |
+
# A phrase without bbox
|
| 431 |
+
if bbox is None:
|
| 432 |
+
continue
|
| 433 |
+
# A phrase with a single bbox
|
| 434 |
+
if isinstance(bbox, tuple):
|
| 435 |
+
bbox = [bbox]
|
| 436 |
+
patch_index_strings = []
|
| 437 |
+
# A phrase could have multiple bboxes
|
| 438 |
+
if not all(box is not None for box in bbox):
|
| 439 |
+
raise ValueError(
|
| 440 |
+
"The multiple bounding boxes for a single phrase should not contain any `None` value."
|
| 441 |
+
)
|
| 442 |
+
for box in bbox:
|
| 443 |
+
patch_index_1, patch_index_2 = self._convert_bbox_to_patch_index_tokens(box)
|
| 444 |
+
patch_index_strings.append(f"{patch_index_1} {patch_index_2}")
|
| 445 |
+
# `bbox` being an empty list
|
| 446 |
+
if len(patch_index_strings) == 0:
|
| 447 |
+
continue
|
| 448 |
+
position_str = " </delimiter_of_multi_objects/> ".join(patch_index_strings)
|
| 449 |
+
buffer.append(f"<object> {position_str} </object>")
|
| 450 |
+
# remaining
|
| 451 |
+
if curr_pos < len(text):
|
| 452 |
+
buffer.append(text[curr_pos:])
|
| 453 |
+
|
| 454 |
+
text = "".join(buffer)
|
| 455 |
+
return text
|
| 456 |
+
|
| 457 |
+
def _convert_bbox_to_patch_index_tokens(
|
| 458 |
+
self, bbox: Union[Tuple[int, int], Tuple[float, float, float, float]]
|
| 459 |
+
) -> Tuple[str, str]:
|
| 460 |
+
# already computed patch indices
|
| 461 |
+
if len(bbox) == 2:
|
| 462 |
+
idx_1, idx_2 = bbox
|
| 463 |
+
# bbox specified with (normalized) coordinates
|
| 464 |
+
else:
|
| 465 |
+
# use `self.tokenizer` to get `num_patches_per_side`
|
| 466 |
+
num_patches_per_side = int(math.sqrt(self.num_patch_index_tokens))
|
| 467 |
+
idx_1, idx_2 = coordinate_to_patch_index(bbox, num_patches_per_side)
|
| 468 |
+
|
| 469 |
+
token_1 = f"<patch_index_{str(idx_1).zfill(4)}>"
|
| 470 |
+
token_2 = f"<patch_index_{str(idx_2).zfill(4)}>"
|
| 471 |
+
|
| 472 |
+
return token_1, token_2
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def coordinate_to_patch_index(bbox: Tuple[float, float, float, float], num_patches_per_side: int) -> Tuple[int, int]:
|
| 476 |
+
"""Convert a bounding box to a pair of patch indices.
|
| 477 |
+
|
| 478 |
+
Args:
|
| 479 |
+
bbox (`Tuple[float, float, float, float]`):
|
| 480 |
+
The 4 coordinates of the bounding box, with the format being (x1, y1, x2, y2) specifying the upper-left and
|
| 481 |
+
lower-right corners of the box. It should have x2 > x1 and y2 > y1.
|
| 482 |
+
num_patches_per_side (`int`): the number of patches along each side.
|
| 483 |
+
|
| 484 |
+
Returns:
|
| 485 |
+
`Tuple[int, int]`: A pair of patch indices representing the upper-left patch and lower-right patch.
|
| 486 |
+
"""
|
| 487 |
+
(x1, y1, x2, y2) = bbox
|
| 488 |
+
|
| 489 |
+
if not (x2 > x1 and y2 > y1):
|
| 490 |
+
raise ValueError("The coordinates in `bbox` should be `(x1, y1, x2, y2)` with `x2 > x1` and `y2 > y1`.")
|
| 491 |
+
|
| 492 |
+
ul_x = math.floor(x1 * num_patches_per_side)
|
| 493 |
+
ul_y = math.floor(y1 * num_patches_per_side)
|
| 494 |
+
|
| 495 |
+
lr_x = math.ceil(x2 * num_patches_per_side - 1)
|
| 496 |
+
lr_y = math.ceil(y2 * num_patches_per_side - 1)
|
| 497 |
+
|
| 498 |
+
ul_idx = ul_y * num_patches_per_side + ul_x
|
| 499 |
+
lr_idx = lr_y * num_patches_per_side + lr_x
|
| 500 |
+
|
| 501 |
+
return ul_idx, lr_idx
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
# copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L35C1-L75C38
|
| 505 |
+
# (with format modifications)
|
| 506 |
+
def patch_index_to_coordinate(ul_idx: int, lr_idx: int, num_patches_per_side: int):
|
| 507 |
+
"""
|
| 508 |
+
Given a grid of length `num_patches_per_side` and the indices of the upper-left and lower-right corners of a
|
| 509 |
+
bounding box, returns the normalized coordinates of the bounding box, in the form (x1, y1, x2, y2).
|
| 510 |
+
|
| 511 |
+
Args:
|
| 512 |
+
ul_idx (`int`): the index of the grid cell that corresponds to the upper-left corner of the bounding box.
|
| 513 |
+
lr_idx (`int`): the index of the grid cell that corresponds to the lower-right corner of the bounding box.
|
| 514 |
+
num_patches_per_side (`int`): the number of patches along each side.
|
| 515 |
+
|
| 516 |
+
Returns:
|
| 517 |
+
`Tuple[float]`: the normalized coordinates of the bounding box, in the form (x1, y1, x2, y2).
|
| 518 |
+
"""
|
| 519 |
+
# Compute the size of each cell in the grid
|
| 520 |
+
cell_size = 1.0 / num_patches_per_side
|
| 521 |
+
|
| 522 |
+
# Compute the x and y indices of the upper-left and lower-right corners of the bounding box
|
| 523 |
+
ul_x = ul_idx % num_patches_per_side
|
| 524 |
+
ul_y = ul_idx // num_patches_per_side
|
| 525 |
+
|
| 526 |
+
lr_x = lr_idx % num_patches_per_side
|
| 527 |
+
lr_y = lr_idx // num_patches_per_side
|
| 528 |
+
|
| 529 |
+
# Compute the normalized coordinates of the bounding box
|
| 530 |
+
if ul_idx == lr_idx:
|
| 531 |
+
x1 = ul_x * cell_size
|
| 532 |
+
y1 = ul_y * cell_size
|
| 533 |
+
x2 = lr_x * cell_size + cell_size
|
| 534 |
+
y2 = lr_y * cell_size + cell_size
|
| 535 |
+
elif ul_x == lr_x or ul_y == lr_y:
|
| 536 |
+
x1 = ul_x * cell_size
|
| 537 |
+
y1 = ul_y * cell_size
|
| 538 |
+
x2 = lr_x * cell_size + cell_size
|
| 539 |
+
y2 = lr_y * cell_size + cell_size
|
| 540 |
+
else:
|
| 541 |
+
x1 = ul_x * cell_size + cell_size / 2
|
| 542 |
+
y1 = ul_y * cell_size + cell_size / 2
|
| 543 |
+
x2 = lr_x * cell_size + cell_size / 2
|
| 544 |
+
y2 = lr_y * cell_size + cell_size / 2
|
| 545 |
+
|
| 546 |
+
return x1, y1, x2, y2
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
# copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L4-L33
|
| 550 |
+
# (with format modifications)
|
| 551 |
+
def extract_entities_with_patch_indices(text):
|
| 552 |
+
"""Extract entities contained in `text`. The bounding bboxes is given in the form of patch indices.
|
| 553 |
+
|
| 554 |
+
This functioin is only intended to be used within `clean_text_and_extract_entities_with_bboxes` where further
|
| 555 |
+
processing happens, including converting to normalized coordinates and whitespace character cleaning up.
|
| 556 |
+
|
| 557 |
+
Examples:
|
| 558 |
+
|
| 559 |
+
```python
|
| 560 |
+
>>> text = "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>."
|
| 561 |
+
>>> entities = extract_entities_with_patch_indices(text)
|
| 562 |
+
>>> entities
|
| 563 |
+
[(' a snowman', (31, 41), [(44, 863)]), (' a fire', (130, 137), [(5, 911)])]
|
| 564 |
+
```"""
|
| 565 |
+
# The regular expression pattern for matching the required formats
|
| 566 |
+
pattern = r"(?:(<phrase>([^<]+)</phrase>))?<object>((?:<patch_index_\d+><patch_index_\d+></delimiter_of_multi_objects/>)*<patch_index_\d+><patch_index_\d+>)</object>"
|
| 567 |
+
|
| 568 |
+
# Find all matches in the given string
|
| 569 |
+
matches = re.finditer(pattern, text)
|
| 570 |
+
|
| 571 |
+
# Initialize an empty list to store the valid patch_index combinations
|
| 572 |
+
entities_with_patch_indices = []
|
| 573 |
+
|
| 574 |
+
for match in matches:
|
| 575 |
+
# span of a `phrase` that is between <phrase> and </phrase>
|
| 576 |
+
span = match.span(2)
|
| 577 |
+
phrase_tag, phrase, match_content = match.groups()
|
| 578 |
+
if not phrase_tag:
|
| 579 |
+
phrase = None
|
| 580 |
+
# We take the starting position of `<object>`
|
| 581 |
+
span = (match.span(0)[0], match.span(0)[0])
|
| 582 |
+
|
| 583 |
+
# Split the match_content by the delimiter to get individual patch_index pairs
|
| 584 |
+
patch_index_pairs = match_content.split("</delimiter_of_multi_objects/>")
|
| 585 |
+
|
| 586 |
+
entity_bboxes = []
|
| 587 |
+
for pair in patch_index_pairs:
|
| 588 |
+
# Extract the xxxx and yyyy values from the patch_index pair
|
| 589 |
+
x = re.search(r"<patch_index_(\d+)>", pair)
|
| 590 |
+
y = re.search(r"<patch_index_(\d+)>", pair[1:])
|
| 591 |
+
|
| 592 |
+
if x and y:
|
| 593 |
+
if phrase:
|
| 594 |
+
entity_bboxes.append((int(x.group(1)), int(y.group(1))))
|
| 595 |
+
else:
|
| 596 |
+
entity_bboxes.append((int(x.group(1)), int(y.group(1))))
|
| 597 |
+
|
| 598 |
+
if phrase:
|
| 599 |
+
entities_with_patch_indices.append((phrase, span, entity_bboxes))
|
| 600 |
+
else:
|
| 601 |
+
for bbox in entity_bboxes:
|
| 602 |
+
# fake entity name
|
| 603 |
+
entity = f"<patch_index_{bbox[0]}><patch_index_{bbox[1]}>"
|
| 604 |
+
entities_with_patch_indices.append((entity, span, [bbox]))
|
| 605 |
+
|
| 606 |
+
return entities_with_patch_indices
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def adjust_entity_positions(entity, text):
|
| 610 |
+
"""Adjust the positions of the entities in `text` to be relative to the text with special fields removed."""
|
| 611 |
+
entity_name, (start, end) = entity
|
| 612 |
+
# computed the length of strings with special fields (tag tokens, patch index tokens, etc.) removed
|
| 613 |
+
adjusted_start = len(re.sub("<.*?>", "", text[:start]))
|
| 614 |
+
adjusted_end = len(re.sub("<.*?>", "", text[:end]))
|
| 615 |
+
adjusted_entity = (entity_name, (adjusted_start, adjusted_end))
|
| 616 |
+
return adjusted_entity
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
def _cleanup_spaces(text, entities):
|
| 620 |
+
"""Remove the spaces around the text and the entities in it."""
|
| 621 |
+
new_text = text.strip()
|
| 622 |
+
leading_spaces = len(text) - len(text.lstrip())
|
| 623 |
+
|
| 624 |
+
new_entities = []
|
| 625 |
+
for entity_name, (start, end), bboxes in entities:
|
| 626 |
+
entity_name_leading_spaces = len(entity_name) - len(entity_name.lstrip())
|
| 627 |
+
entity_name_trailing_spaces = len(entity_name) - len(entity_name.rstrip())
|
| 628 |
+
|
| 629 |
+
start = start - leading_spaces + entity_name_leading_spaces
|
| 630 |
+
end = end - leading_spaces - entity_name_trailing_spaces
|
| 631 |
+
entity_name = entity_name.strip()
|
| 632 |
+
|
| 633 |
+
new_entities.append((entity_name, (start, end), bboxes))
|
| 634 |
+
|
| 635 |
+
return new_text, new_entities
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
# copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L77-L87
|
| 639 |
+
# (with format modifications)
|
| 640 |
+
def clean_text_and_extract_entities_with_bboxes(text, num_patches_per_side=32):
|
| 641 |
+
"""Remove the tag tokens from `text`, extract entities in it with some cleaning up of white characters.
|
| 642 |
+
|
| 643 |
+
Examples:
|
| 644 |
+
|
| 645 |
+
```python
|
| 646 |
+
>>> text = "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>."
|
| 647 |
+
>>> clean_text, entities = clean_text_and_extract_entities_with_bboxes(text)
|
| 648 |
+
>>> clean_text
|
| 649 |
+
'An image of a snowman warming himself by a fire.'
|
| 650 |
+
|
| 651 |
+
>>> entities
|
| 652 |
+
[('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]
|
| 653 |
+
```"""
|
| 654 |
+
# remove special fields (tag tokens, patch index tokens, etc.)
|
| 655 |
+
processed_text = re.sub("<.*?>", "", text)
|
| 656 |
+
|
| 657 |
+
entities_with_patch_indices = extract_entities_with_patch_indices(text)
|
| 658 |
+
entities = []
|
| 659 |
+
for item in entities_with_patch_indices:
|
| 660 |
+
entity, bboxes = item[0:2], item[2]
|
| 661 |
+
adjusted_entity = adjust_entity_positions(entity, text)
|
| 662 |
+
bboxes_in_coords = [patch_index_to_coordinate(bbox[0], bbox[1], num_patches_per_side) for bbox in bboxes]
|
| 663 |
+
|
| 664 |
+
entities.append(adjusted_entity + (bboxes_in_coords,))
|
| 665 |
+
|
| 666 |
+
return _cleanup_spaces(processed_text, entities)
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/qdqbert/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.2 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/qdqbert/__pycache__/configuration_qdqbert.cpython-310.pyc
ADDED
|
Binary file (5.08 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/qdqbert/__pycache__/modeling_qdqbert.cpython-310.pyc
ADDED
|
Binary file (48.7 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__init__.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import (
|
| 17 |
+
OptionalDependencyNotAvailable,
|
| 18 |
+
_LazyModule,
|
| 19 |
+
is_sentencepiece_available,
|
| 20 |
+
is_torch_available,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
_import_structure = {
|
| 25 |
+
"configuration_speecht5": [
|
| 26 |
+
"SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
| 27 |
+
"SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP",
|
| 28 |
+
"SpeechT5Config",
|
| 29 |
+
"SpeechT5HifiGanConfig",
|
| 30 |
+
],
|
| 31 |
+
"feature_extraction_speecht5": ["SpeechT5FeatureExtractor"],
|
| 32 |
+
"processing_speecht5": ["SpeechT5Processor"],
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
if not is_sentencepiece_available():
|
| 37 |
+
raise OptionalDependencyNotAvailable()
|
| 38 |
+
except OptionalDependencyNotAvailable:
|
| 39 |
+
pass
|
| 40 |
+
else:
|
| 41 |
+
_import_structure["tokenization_speecht5"] = ["SpeechT5Tokenizer"]
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
if not is_torch_available():
|
| 45 |
+
raise OptionalDependencyNotAvailable()
|
| 46 |
+
except OptionalDependencyNotAvailable:
|
| 47 |
+
pass
|
| 48 |
+
else:
|
| 49 |
+
_import_structure["modeling_speecht5"] = [
|
| 50 |
+
"SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 51 |
+
"SpeechT5ForSpeechToText",
|
| 52 |
+
"SpeechT5ForSpeechToSpeech",
|
| 53 |
+
"SpeechT5ForTextToSpeech",
|
| 54 |
+
"SpeechT5Model",
|
| 55 |
+
"SpeechT5PreTrainedModel",
|
| 56 |
+
"SpeechT5HifiGan",
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
if TYPE_CHECKING:
|
| 60 |
+
from .configuration_speecht5 import (
|
| 61 |
+
SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
| 62 |
+
SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP,
|
| 63 |
+
SpeechT5Config,
|
| 64 |
+
SpeechT5HifiGanConfig,
|
| 65 |
+
)
|
| 66 |
+
from .feature_extraction_speecht5 import SpeechT5FeatureExtractor
|
| 67 |
+
from .processing_speecht5 import SpeechT5Processor
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
if not is_sentencepiece_available():
|
| 71 |
+
raise OptionalDependencyNotAvailable()
|
| 72 |
+
except OptionalDependencyNotAvailable:
|
| 73 |
+
pass
|
| 74 |
+
else:
|
| 75 |
+
from .tokenization_speecht5 import SpeechT5Tokenizer
|
| 76 |
+
|
| 77 |
+
try:
|
| 78 |
+
if not is_torch_available():
|
| 79 |
+
raise OptionalDependencyNotAvailable()
|
| 80 |
+
except OptionalDependencyNotAvailable:
|
| 81 |
+
pass
|
| 82 |
+
else:
|
| 83 |
+
from .modeling_speecht5 import (
|
| 84 |
+
SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 85 |
+
SpeechT5ForSpeechToSpeech,
|
| 86 |
+
SpeechT5ForSpeechToText,
|
| 87 |
+
SpeechT5ForTextToSpeech,
|
| 88 |
+
SpeechT5HifiGan,
|
| 89 |
+
SpeechT5Model,
|
| 90 |
+
SpeechT5PreTrainedModel,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
else:
|
| 94 |
+
import sys
|
| 95 |
+
|
| 96 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.53 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/convert_hifigan.cpython-310.pyc
ADDED
|
Binary file (2.84 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/convert_speecht5_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (11.4 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/feature_extraction_speecht5.cpython-310.pyc
ADDED
|
Binary file (13.8 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/number_normalizer.cpython-310.pyc
ADDED
|
Binary file (4.4 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/processing_speecht5.cpython-310.pyc
ADDED
|
Binary file (5.57 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/convert_speecht5_original_pytorch_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert SpeechT5 checkpoint."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from transformers import (
|
| 22 |
+
SpeechT5Config,
|
| 23 |
+
SpeechT5FeatureExtractor,
|
| 24 |
+
SpeechT5ForSpeechToSpeech,
|
| 25 |
+
SpeechT5ForSpeechToText,
|
| 26 |
+
SpeechT5ForTextToSpeech,
|
| 27 |
+
SpeechT5Processor,
|
| 28 |
+
SpeechT5Tokenizer,
|
| 29 |
+
logging,
|
| 30 |
+
)
|
| 31 |
+
from transformers.tokenization_utils import AddedToken
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
logging.set_verbosity_info()
|
| 35 |
+
logger = logging.get_logger("transformers.models.speecht5")
|
| 36 |
+
|
| 37 |
+
MAPPING_SPEECH_ENCODER_PRENET = {
|
| 38 |
+
"speech_encoder_prenet.layer_norm": "speecht5.encoder.prenet.feature_projection.layer_norm",
|
| 39 |
+
"speech_encoder_prenet.post_extract_proj": "speecht5.encoder.prenet.feature_projection.projection",
|
| 40 |
+
"speech_encoder_prenet.pos_conv.0": "speecht5.encoder.prenet.pos_conv_embed.conv",
|
| 41 |
+
"speech_encoder_prenet.mask_emb": "speecht5.encoder.prenet.masked_spec_embed",
|
| 42 |
+
}
|
| 43 |
+
MAPPING_TEXT_ENCODER_PRENET = {
|
| 44 |
+
"text_encoder_prenet.encoder_prenet.0": "speecht5.encoder.prenet.embed_tokens",
|
| 45 |
+
"text_encoder_prenet.encoder_prenet.1.alpha": "speecht5.encoder.prenet.encode_positions.alpha",
|
| 46 |
+
}
|
| 47 |
+
MAPPING_SPEECH_DECODER_PRENET = {
|
| 48 |
+
"speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0": "speecht5.decoder.prenet.layers.0",
|
| 49 |
+
"speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0": "speecht5.decoder.prenet.layers.1",
|
| 50 |
+
"speech_decoder_prenet.decoder_prenet.0.1": "speecht5.decoder.prenet.final_layer",
|
| 51 |
+
"speech_decoder_prenet.decoder_prenet.1.alpha": "speecht5.decoder.prenet.encode_positions.alpha",
|
| 52 |
+
"speech_decoder_prenet.spkembs_layer.0": "speecht5.decoder.prenet.speaker_embeds_layer",
|
| 53 |
+
}
|
| 54 |
+
MAPPING_SPEECH_DECODER_POSTNET = {
|
| 55 |
+
"speech_decoder_postnet.feat_out": "speech_decoder_postnet.feat_out",
|
| 56 |
+
"speech_decoder_postnet.prob_out": "speech_decoder_postnet.prob_out",
|
| 57 |
+
"speech_decoder_postnet.postnet.postnet.0.0": "speech_decoder_postnet.layers.0.conv",
|
| 58 |
+
"speech_decoder_postnet.postnet.postnet.0.1": "speech_decoder_postnet.layers.0.batch_norm",
|
| 59 |
+
"speech_decoder_postnet.postnet.postnet.1.0": "speech_decoder_postnet.layers.1.conv",
|
| 60 |
+
"speech_decoder_postnet.postnet.postnet.1.1": "speech_decoder_postnet.layers.1.batch_norm",
|
| 61 |
+
"speech_decoder_postnet.postnet.postnet.2.0": "speech_decoder_postnet.layers.2.conv",
|
| 62 |
+
"speech_decoder_postnet.postnet.postnet.2.1": "speech_decoder_postnet.layers.2.batch_norm",
|
| 63 |
+
"speech_decoder_postnet.postnet.postnet.3.0": "speech_decoder_postnet.layers.3.conv",
|
| 64 |
+
"speech_decoder_postnet.postnet.postnet.3.1": "speech_decoder_postnet.layers.3.batch_norm",
|
| 65 |
+
"speech_decoder_postnet.postnet.postnet.4.0": "speech_decoder_postnet.layers.4.conv",
|
| 66 |
+
"speech_decoder_postnet.postnet.postnet.4.1": "speech_decoder_postnet.layers.4.batch_norm",
|
| 67 |
+
}
|
| 68 |
+
MAPPING_TEXT_DECODER_PRENET = {
|
| 69 |
+
"text_decoder_prenet.embed_tokens": "speecht5.decoder.prenet.embed_tokens",
|
| 70 |
+
}
|
| 71 |
+
MAPPING_TEXT_DECODER_POSTNET = {
|
| 72 |
+
"text_decoder_postnet.output_projection": "text_decoder_postnet.lm_head",
|
| 73 |
+
}
|
| 74 |
+
MAPPING_ENCODER = {
|
| 75 |
+
"encoder.layers.*.self_attn.k_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj",
|
| 76 |
+
"encoder.layers.*.self_attn.v_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj",
|
| 77 |
+
"encoder.layers.*.self_attn.q_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj",
|
| 78 |
+
"encoder.layers.*.self_attn.out_proj": "speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj",
|
| 79 |
+
"encoder.layers.*.self_attn_layer_norm": "speecht5.encoder.wrapped_encoder.layers.*.layer_norm",
|
| 80 |
+
"encoder.layers.*.fc1": "speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense",
|
| 81 |
+
"encoder.layers.*.fc2": "speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense",
|
| 82 |
+
"encoder.layers.*.final_layer_norm": "speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm",
|
| 83 |
+
"encoder.layer_norm": "speecht5.encoder.wrapped_encoder.layer_norm",
|
| 84 |
+
"encoder.pos_emb.pe_k": "speecht5.encoder.wrapped_encoder.embed_positions.pe_k",
|
| 85 |
+
}
|
| 86 |
+
MAPPING_DECODER = {
|
| 87 |
+
"decoder.layers.*.self_attn.k_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj",
|
| 88 |
+
"decoder.layers.*.self_attn.v_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj",
|
| 89 |
+
"decoder.layers.*.self_attn.q_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj",
|
| 90 |
+
"decoder.layers.*.self_attn.out_proj": "speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj",
|
| 91 |
+
"decoder.layers.*.self_attn_layer_norm": "speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm",
|
| 92 |
+
"decoder.layers.*.encoder_attn.k_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj",
|
| 93 |
+
"decoder.layers.*.encoder_attn.v_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj",
|
| 94 |
+
"decoder.layers.*.encoder_attn.q_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj",
|
| 95 |
+
"decoder.layers.*.encoder_attn.out_proj": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj",
|
| 96 |
+
"decoder.layers.*.encoder_attn_layer_norm": "speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm",
|
| 97 |
+
"decoder.layers.*.fc1": "speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense",
|
| 98 |
+
"decoder.layers.*.fc2": "speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense",
|
| 99 |
+
"decoder.layers.*.final_layer_norm": "speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm",
|
| 100 |
+
}
|
| 101 |
+
MAPPING_S2T = {
|
| 102 |
+
**MAPPING_SPEECH_ENCODER_PRENET,
|
| 103 |
+
**MAPPING_ENCODER,
|
| 104 |
+
**MAPPING_DECODER,
|
| 105 |
+
**MAPPING_TEXT_DECODER_PRENET,
|
| 106 |
+
**MAPPING_TEXT_DECODER_POSTNET,
|
| 107 |
+
}
|
| 108 |
+
MAPPING_T2S = {
|
| 109 |
+
**MAPPING_TEXT_ENCODER_PRENET,
|
| 110 |
+
**MAPPING_ENCODER,
|
| 111 |
+
**MAPPING_DECODER,
|
| 112 |
+
**MAPPING_SPEECH_DECODER_PRENET,
|
| 113 |
+
**MAPPING_SPEECH_DECODER_POSTNET,
|
| 114 |
+
}
|
| 115 |
+
MAPPING_S2S = {
|
| 116 |
+
**MAPPING_SPEECH_ENCODER_PRENET,
|
| 117 |
+
**MAPPING_ENCODER,
|
| 118 |
+
**MAPPING_DECODER,
|
| 119 |
+
**MAPPING_SPEECH_DECODER_PRENET,
|
| 120 |
+
**MAPPING_SPEECH_DECODER_POSTNET,
|
| 121 |
+
}
|
| 122 |
+
TOP_LEVEL_KEYS = []
|
| 123 |
+
IGNORE_KEYS = [
|
| 124 |
+
"encoder.version",
|
| 125 |
+
"encoder.layers.*.norm_k.weight",
|
| 126 |
+
"encoder.layers.*.norm_k.bias",
|
| 127 |
+
"decoder.version",
|
| 128 |
+
"decoder.layers.*.norm_k.weight",
|
| 129 |
+
"decoder.layers.*.norm_k.bias",
|
| 130 |
+
"decoder.pos_emb.pe_k",
|
| 131 |
+
"speech_encoder_prenet.embed_positions._float_tensor",
|
| 132 |
+
"text_decoder_prenet.embed_positions._float_tensor",
|
| 133 |
+
]
|
| 134 |
+
IGNORE_KEYS_S2T = IGNORE_KEYS + [
|
| 135 |
+
"encoder.proj",
|
| 136 |
+
"text_encoder_prenet.*",
|
| 137 |
+
"speech_decoder_prenet.*",
|
| 138 |
+
"speech_decoder_postnet.*",
|
| 139 |
+
]
|
| 140 |
+
IGNORE_KEYS_T2S = IGNORE_KEYS + [
|
| 141 |
+
"encoder.proj",
|
| 142 |
+
"speech_encoder_prenet.*",
|
| 143 |
+
"text_decoder_prenet.*",
|
| 144 |
+
"text_decoder_postnet.*",
|
| 145 |
+
]
|
| 146 |
+
IGNORE_KEYS_S2S = IGNORE_KEYS + [
|
| 147 |
+
"encoder.proj",
|
| 148 |
+
"text_encoder_prenet.*",
|
| 149 |
+
"text_decoder_prenet.*",
|
| 150 |
+
"text_decoder_postnet.*",
|
| 151 |
+
]
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def set_recursively(hf_pointer, key, value, full_name, weight_type):
|
| 155 |
+
for attribute in key.split("."):
|
| 156 |
+
hf_pointer = getattr(hf_pointer, attribute)
|
| 157 |
+
|
| 158 |
+
if weight_type is not None:
|
| 159 |
+
hf_shape = getattr(hf_pointer, weight_type).shape
|
| 160 |
+
else:
|
| 161 |
+
hf_shape = hf_pointer.shape
|
| 162 |
+
|
| 163 |
+
if hf_shape != value.shape:
|
| 164 |
+
raise ValueError(
|
| 165 |
+
f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
|
| 166 |
+
f" {value.shape} for {full_name}"
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
if weight_type == "weight":
|
| 170 |
+
hf_pointer.weight.data = value
|
| 171 |
+
elif weight_type == "weight_g":
|
| 172 |
+
hf_pointer.weight_g.data = value
|
| 173 |
+
elif weight_type == "weight_v":
|
| 174 |
+
hf_pointer.weight_v.data = value
|
| 175 |
+
elif weight_type == "bias":
|
| 176 |
+
hf_pointer.bias.data = value
|
| 177 |
+
elif weight_type == "running_mean":
|
| 178 |
+
hf_pointer.running_mean.data = value
|
| 179 |
+
elif weight_type == "running_var":
|
| 180 |
+
hf_pointer.running_var.data = value
|
| 181 |
+
elif weight_type == "num_batches_tracked":
|
| 182 |
+
hf_pointer.num_batches_tracked.data = value
|
| 183 |
+
else:
|
| 184 |
+
hf_pointer.data = value
|
| 185 |
+
|
| 186 |
+
logger.info(f"{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.")
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def should_ignore(name, ignore_keys):
|
| 190 |
+
for key in ignore_keys:
|
| 191 |
+
if key.endswith(".*"):
|
| 192 |
+
if name.startswith(key[:-1]):
|
| 193 |
+
return True
|
| 194 |
+
elif ".*." in key:
|
| 195 |
+
prefix, suffix = key.split(".*.")
|
| 196 |
+
if prefix in name and suffix in name:
|
| 197 |
+
return True
|
| 198 |
+
elif key in name:
|
| 199 |
+
return True
|
| 200 |
+
return False
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def recursively_load_weights(fairseq_dict, hf_model, task):
|
| 204 |
+
unused_weights = []
|
| 205 |
+
|
| 206 |
+
if task == "s2t":
|
| 207 |
+
feature_encoder = hf_model.speecht5.encoder.prenet.feature_encoder
|
| 208 |
+
MAPPING = MAPPING_S2T
|
| 209 |
+
IGNORE_KEYS = IGNORE_KEYS_S2T
|
| 210 |
+
elif task == "t2s":
|
| 211 |
+
feature_encoder = None
|
| 212 |
+
MAPPING = MAPPING_T2S
|
| 213 |
+
IGNORE_KEYS = IGNORE_KEYS_T2S
|
| 214 |
+
elif task == "s2s":
|
| 215 |
+
feature_encoder = hf_model.speecht5.encoder.prenet.feature_encoder
|
| 216 |
+
MAPPING = MAPPING_S2S
|
| 217 |
+
IGNORE_KEYS = IGNORE_KEYS_S2S
|
| 218 |
+
else:
|
| 219 |
+
raise ValueError(f"Unsupported task: {task}")
|
| 220 |
+
|
| 221 |
+
for name, value in fairseq_dict.items():
|
| 222 |
+
if should_ignore(name, IGNORE_KEYS):
|
| 223 |
+
logger.info(f"{name} was ignored")
|
| 224 |
+
continue
|
| 225 |
+
|
| 226 |
+
is_used = False
|
| 227 |
+
if "conv_layers" in name:
|
| 228 |
+
load_conv_layer(
|
| 229 |
+
name,
|
| 230 |
+
value,
|
| 231 |
+
feature_encoder,
|
| 232 |
+
unused_weights,
|
| 233 |
+
hf_model.config.feat_extract_norm == "group",
|
| 234 |
+
)
|
| 235 |
+
is_used = True
|
| 236 |
+
else:
|
| 237 |
+
for key, mapped_key in MAPPING.items():
|
| 238 |
+
# mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
|
| 239 |
+
|
| 240 |
+
if "*" in key:
|
| 241 |
+
prefix, suffix = key.split(".*.")
|
| 242 |
+
if prefix in name and suffix in name:
|
| 243 |
+
key = suffix
|
| 244 |
+
|
| 245 |
+
# if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]:
|
| 246 |
+
if key in name:
|
| 247 |
+
is_used = True
|
| 248 |
+
if "*" in mapped_key:
|
| 249 |
+
layer_index = name.split(key)[0].split(".")[-2]
|
| 250 |
+
mapped_key = mapped_key.replace("*", layer_index)
|
| 251 |
+
if "weight_g" in name:
|
| 252 |
+
weight_type = "weight_g"
|
| 253 |
+
elif "weight_v" in name:
|
| 254 |
+
weight_type = "weight_v"
|
| 255 |
+
elif "bias" in name:
|
| 256 |
+
weight_type = "bias"
|
| 257 |
+
elif "weight" in name:
|
| 258 |
+
weight_type = "weight"
|
| 259 |
+
elif "running_mean" in name:
|
| 260 |
+
weight_type = "running_mean"
|
| 261 |
+
elif "running_var" in name:
|
| 262 |
+
weight_type = "running_var"
|
| 263 |
+
elif "num_batches_tracked" in name:
|
| 264 |
+
weight_type = "num_batches_tracked"
|
| 265 |
+
else:
|
| 266 |
+
weight_type = None
|
| 267 |
+
set_recursively(hf_model, mapped_key, value, name, weight_type)
|
| 268 |
+
continue
|
| 269 |
+
if not is_used:
|
| 270 |
+
unused_weights.append(name)
|
| 271 |
+
|
| 272 |
+
logger.warning(f"Unused weights: {unused_weights}")
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def load_conv_layer(full_name, value, feature_extractor, unused_weights, use_group_norm):
|
| 276 |
+
name = full_name.split("conv_layers.")[-1]
|
| 277 |
+
items = name.split(".")
|
| 278 |
+
layer_id = int(items[0])
|
| 279 |
+
type_id = int(items[1])
|
| 280 |
+
|
| 281 |
+
if type_id == 0:
|
| 282 |
+
if "bias" in name:
|
| 283 |
+
if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
|
| 284 |
+
raise ValueError(
|
| 285 |
+
f"{full_name} has size {value.shape}, but"
|
| 286 |
+
f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."
|
| 287 |
+
)
|
| 288 |
+
feature_extractor.conv_layers[layer_id].conv.bias.data = value
|
| 289 |
+
logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.")
|
| 290 |
+
elif "weight" in name:
|
| 291 |
+
if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
|
| 292 |
+
raise ValueError(
|
| 293 |
+
f"{full_name} has size {value.shape}, but"
|
| 294 |
+
f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."
|
| 295 |
+
)
|
| 296 |
+
feature_extractor.conv_layers[layer_id].conv.weight.data = value
|
| 297 |
+
logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.")
|
| 298 |
+
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
|
| 299 |
+
if "bias" in name:
|
| 300 |
+
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
|
| 301 |
+
raise ValueError(
|
| 302 |
+
f"{full_name} has size {value.shape}, but"
|
| 303 |
+
f" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found."
|
| 304 |
+
)
|
| 305 |
+
feature_extractor.conv_layers[layer_id].layer_norm.bias.data = value
|
| 306 |
+
logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.")
|
| 307 |
+
elif "weight" in name:
|
| 308 |
+
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
|
| 309 |
+
raise ValueError(
|
| 310 |
+
f"{full_name} has size {value.shape}, but"
|
| 311 |
+
f" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found."
|
| 312 |
+
)
|
| 313 |
+
feature_extractor.conv_layers[layer_id].layer_norm.weight.data = value
|
| 314 |
+
logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.")
|
| 315 |
+
else:
|
| 316 |
+
unused_weights.append(full_name)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@torch.no_grad()
|
| 320 |
+
def convert_speecht5_checkpoint(
|
| 321 |
+
task,
|
| 322 |
+
checkpoint_path,
|
| 323 |
+
pytorch_dump_folder_path,
|
| 324 |
+
config_path=None,
|
| 325 |
+
vocab_path=None,
|
| 326 |
+
repo_id=None,
|
| 327 |
+
):
|
| 328 |
+
"""
|
| 329 |
+
Copy/paste/tweak model's weights to transformers design.
|
| 330 |
+
"""
|
| 331 |
+
if config_path is not None:
|
| 332 |
+
config = SpeechT5Config.from_pretrained(config_path)
|
| 333 |
+
else:
|
| 334 |
+
config = SpeechT5Config()
|
| 335 |
+
|
| 336 |
+
if task == "s2t":
|
| 337 |
+
config.max_length = config.max_text_positions
|
| 338 |
+
model = SpeechT5ForSpeechToText(config)
|
| 339 |
+
elif task == "t2s":
|
| 340 |
+
config.max_speech_positions = 1876
|
| 341 |
+
config.max_text_positions = 600
|
| 342 |
+
config.max_length = config.max_speech_positions
|
| 343 |
+
model = SpeechT5ForTextToSpeech(config)
|
| 344 |
+
elif task == "s2s":
|
| 345 |
+
config.max_speech_positions = 1876
|
| 346 |
+
config.max_length = config.max_speech_positions
|
| 347 |
+
model = SpeechT5ForSpeechToSpeech(config)
|
| 348 |
+
else:
|
| 349 |
+
raise ValueError(f"Unknown task name: {task}")
|
| 350 |
+
|
| 351 |
+
if vocab_path:
|
| 352 |
+
tokenizer = SpeechT5Tokenizer(vocab_path, model_max_length=config.max_text_positions)
|
| 353 |
+
|
| 354 |
+
# Mask token behaves like a normal word, i.e. include the space before it
|
| 355 |
+
mask_token = AddedToken("<mask>", lstrip=True, rstrip=False)
|
| 356 |
+
tokenizer.mask_token = mask_token
|
| 357 |
+
tokenizer.add_special_tokens({"mask_token": mask_token})
|
| 358 |
+
tokenizer.add_tokens(["<ctc_blank>"])
|
| 359 |
+
|
| 360 |
+
feature_extractor = SpeechT5FeatureExtractor()
|
| 361 |
+
processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor)
|
| 362 |
+
processor.save_pretrained(pytorch_dump_folder_path)
|
| 363 |
+
|
| 364 |
+
fairseq_checkpoint = torch.load(checkpoint_path)
|
| 365 |
+
recursively_load_weights(fairseq_checkpoint["model"], model, task)
|
| 366 |
+
|
| 367 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 368 |
+
|
| 369 |
+
if repo_id:
|
| 370 |
+
print("Pushing to the hub...")
|
| 371 |
+
processor.push_to_hub(repo_id)
|
| 372 |
+
model.push_to_hub(repo_id)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
if __name__ == "__main__":
|
| 376 |
+
parser = argparse.ArgumentParser()
|
| 377 |
+
parser.add_argument(
|
| 378 |
+
"--task",
|
| 379 |
+
default="s2t",
|
| 380 |
+
type=str,
|
| 381 |
+
help="Type of the SpeechT5 model you'd like to convert. Should be one of 's2t', 't2s', 's2s'.",
|
| 382 |
+
)
|
| 383 |
+
parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to fairseq checkpoint")
|
| 384 |
+
parser.add_argument("--vocab_path", default=None, type=str, help="Path to SentencePiece model")
|
| 385 |
+
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
|
| 386 |
+
parser.add_argument(
|
| 387 |
+
"--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model."
|
| 388 |
+
)
|
| 389 |
+
parser.add_argument(
|
| 390 |
+
"--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub."
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
args = parser.parse_args()
|
| 394 |
+
convert_speecht5_checkpoint(
|
| 395 |
+
args.task,
|
| 396 |
+
args.checkpoint_path,
|
| 397 |
+
args.pytorch_dump_folder_path,
|
| 398 |
+
args.config_path,
|
| 399 |
+
args.vocab_path,
|
| 400 |
+
args.push_to_hub,
|
| 401 |
+
)
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/feature_extraction_speecht5.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Feature extractor class for SpeechT5."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
from typing import Any, Dict, List, Optional, Union
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
|
| 23 |
+
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
|
| 24 |
+
from ...feature_extraction_utils import BatchFeature
|
| 25 |
+
from ...utils import PaddingStrategy, TensorType, logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class SpeechT5FeatureExtractor(SequenceFeatureExtractor):
|
| 32 |
+
r"""
|
| 33 |
+
Constructs a SpeechT5 feature extractor.
|
| 34 |
+
|
| 35 |
+
This class can pre-process a raw speech signal by (optionally) normalizing to zero-mean unit-variance, for use by
|
| 36 |
+
the SpeechT5 speech encoder prenet.
|
| 37 |
+
|
| 38 |
+
This class can also extract log-mel filter bank features from raw speech, for use by the SpeechT5 speech decoder
|
| 39 |
+
prenet.
|
| 40 |
+
|
| 41 |
+
This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
|
| 42 |
+
most of the main methods. Users should refer to this superclass for more information regarding those methods.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
feature_size (`int`, *optional*, defaults to 1):
|
| 46 |
+
The feature dimension of the extracted features.
|
| 47 |
+
sampling_rate (`int`, *optional*, defaults to 16000):
|
| 48 |
+
The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
|
| 49 |
+
padding_value (`float`, *optional*, defaults to 0.0):
|
| 50 |
+
The value that is used to fill the padding values.
|
| 51 |
+
do_normalize (`bool`, *optional*, defaults to `False`):
|
| 52 |
+
Whether or not to zero-mean unit-variance normalize the input. Normalizing can help to significantly
|
| 53 |
+
improve the performance for some models.
|
| 54 |
+
num_mel_bins (`int`, *optional*, defaults to 80):
|
| 55 |
+
The number of mel-frequency bins in the extracted spectrogram features.
|
| 56 |
+
hop_length (`int`, *optional*, defaults to 16):
|
| 57 |
+
Number of ms between windows. Otherwise referred to as "shift" in many papers.
|
| 58 |
+
win_length (`int`, *optional*, defaults to 64):
|
| 59 |
+
Number of ms per window.
|
| 60 |
+
win_function (`str`, *optional*, defaults to `"hann_window"`):
|
| 61 |
+
Name for the window function used for windowing, must be accessible via `torch.{win_function}`
|
| 62 |
+
frame_signal_scale (`float`, *optional*, defaults to 1.0):
|
| 63 |
+
Constant multiplied in creating the frames before applying DFT. This argument is deprecated.
|
| 64 |
+
fmin (`float`, *optional*, defaults to 80):
|
| 65 |
+
Minimum mel frequency in Hz.
|
| 66 |
+
fmax (`float`, *optional*, defaults to 7600):
|
| 67 |
+
Maximum mel frequency in Hz.
|
| 68 |
+
mel_floor (`float`, *optional*, defaults to 1e-10):
|
| 69 |
+
Minimum value of mel frequency banks.
|
| 70 |
+
reduction_factor (`int`, *optional*, defaults to 2):
|
| 71 |
+
Spectrogram length reduction factor. This argument is deprecated.
|
| 72 |
+
return_attention_mask (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
Whether or not [`~SpeechT5FeatureExtractor.__call__`] should return `attention_mask`.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
model_input_names = ["input_values", "attention_mask"]
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
feature_size: int = 1,
|
| 81 |
+
sampling_rate: int = 16000,
|
| 82 |
+
padding_value: float = 0.0,
|
| 83 |
+
do_normalize: bool = False,
|
| 84 |
+
num_mel_bins: int = 80,
|
| 85 |
+
hop_length: int = 16,
|
| 86 |
+
win_length: int = 64,
|
| 87 |
+
win_function: str = "hann_window",
|
| 88 |
+
frame_signal_scale: float = 1.0,
|
| 89 |
+
fmin: float = 80,
|
| 90 |
+
fmax: float = 7600,
|
| 91 |
+
mel_floor: float = 1e-10,
|
| 92 |
+
reduction_factor: int = 2,
|
| 93 |
+
return_attention_mask: bool = True,
|
| 94 |
+
**kwargs,
|
| 95 |
+
):
|
| 96 |
+
super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
|
| 97 |
+
self.do_normalize = do_normalize
|
| 98 |
+
self.return_attention_mask = return_attention_mask
|
| 99 |
+
|
| 100 |
+
self.num_mel_bins = num_mel_bins
|
| 101 |
+
self.hop_length = hop_length
|
| 102 |
+
self.win_length = win_length
|
| 103 |
+
self.win_function = win_function
|
| 104 |
+
self.frame_signal_scale = frame_signal_scale
|
| 105 |
+
self.fmin = fmin
|
| 106 |
+
self.fmax = fmax
|
| 107 |
+
self.mel_floor = mel_floor
|
| 108 |
+
self.reduction_factor = reduction_factor
|
| 109 |
+
|
| 110 |
+
self.sample_size = win_length * sampling_rate // 1000
|
| 111 |
+
self.sample_stride = hop_length * sampling_rate // 1000
|
| 112 |
+
self.n_fft = optimal_fft_length(self.sample_size)
|
| 113 |
+
self.n_freqs = (self.n_fft // 2) + 1
|
| 114 |
+
|
| 115 |
+
self.window = window_function(window_length=self.sample_size, name=self.win_function, periodic=True)
|
| 116 |
+
|
| 117 |
+
self.mel_filters = mel_filter_bank(
|
| 118 |
+
num_frequency_bins=self.n_freqs,
|
| 119 |
+
num_mel_filters=self.num_mel_bins,
|
| 120 |
+
min_frequency=self.fmin,
|
| 121 |
+
max_frequency=self.fmax,
|
| 122 |
+
sampling_rate=self.sampling_rate,
|
| 123 |
+
norm="slaney",
|
| 124 |
+
mel_scale="slaney",
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if frame_signal_scale != 1.0:
|
| 128 |
+
warnings.warn(
|
| 129 |
+
"The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers",
|
| 130 |
+
FutureWarning,
|
| 131 |
+
)
|
| 132 |
+
if reduction_factor != 2.0:
|
| 133 |
+
warnings.warn(
|
| 134 |
+
"The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers",
|
| 135 |
+
FutureWarning,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
@staticmethod
|
| 139 |
+
# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
|
| 140 |
+
def zero_mean_unit_var_norm(
|
| 141 |
+
input_values: List[np.ndarray], attention_mask: List[np.ndarray], padding_value: float = 0.0
|
| 142 |
+
) -> List[np.ndarray]:
|
| 143 |
+
"""
|
| 144 |
+
Every array in the list is normalized to have zero mean and unit variance
|
| 145 |
+
"""
|
| 146 |
+
if attention_mask is not None:
|
| 147 |
+
attention_mask = np.array(attention_mask, np.int32)
|
| 148 |
+
normed_input_values = []
|
| 149 |
+
|
| 150 |
+
for vector, length in zip(input_values, attention_mask.sum(-1)):
|
| 151 |
+
normed_slice = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7)
|
| 152 |
+
if length < normed_slice.shape[0]:
|
| 153 |
+
normed_slice[length:] = padding_value
|
| 154 |
+
|
| 155 |
+
normed_input_values.append(normed_slice)
|
| 156 |
+
else:
|
| 157 |
+
normed_input_values = [(x - x.mean()) / np.sqrt(x.var() + 1e-7) for x in input_values]
|
| 158 |
+
|
| 159 |
+
return normed_input_values
|
| 160 |
+
|
| 161 |
+
def _extract_mel_features(
|
| 162 |
+
self,
|
| 163 |
+
one_waveform: np.ndarray,
|
| 164 |
+
) -> np.ndarray:
|
| 165 |
+
"""
|
| 166 |
+
Extracts log-mel filterbank features for one waveform array (unbatched).
|
| 167 |
+
"""
|
| 168 |
+
log_mel_spec = spectrogram(
|
| 169 |
+
one_waveform,
|
| 170 |
+
window=self.window,
|
| 171 |
+
frame_length=self.sample_size,
|
| 172 |
+
hop_length=self.sample_stride,
|
| 173 |
+
fft_length=self.n_fft,
|
| 174 |
+
mel_filters=self.mel_filters,
|
| 175 |
+
mel_floor=self.mel_floor,
|
| 176 |
+
log_mel="log10",
|
| 177 |
+
)
|
| 178 |
+
return log_mel_spec.T
|
| 179 |
+
|
| 180 |
+
def __call__(
|
| 181 |
+
self,
|
| 182 |
+
audio: Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None,
|
| 183 |
+
audio_target: Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None,
|
| 184 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 185 |
+
max_length: Optional[int] = None,
|
| 186 |
+
truncation: bool = False,
|
| 187 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 188 |
+
return_attention_mask: Optional[bool] = None,
|
| 189 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 190 |
+
sampling_rate: Optional[int] = None,
|
| 191 |
+
**kwargs,
|
| 192 |
+
) -> BatchFeature:
|
| 193 |
+
"""
|
| 194 |
+
Main method to featurize and prepare for the model one or several sequence(s).
|
| 195 |
+
|
| 196 |
+
Pass in a value for `audio` to extract waveform features. Pass in a value for `audio_target` to extract log-mel
|
| 197 |
+
spectrogram features.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
audio (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`, *optional*):
|
| 201 |
+
The sequence or batch of sequences to be processed. Each sequence can be a numpy array, a list of float
|
| 202 |
+
values, a list of numpy arrays or a list of list of float values. This outputs waveform features. Must
|
| 203 |
+
be mono channel audio, not stereo, i.e. single float per timestep.
|
| 204 |
+
audio_target (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`, *optional*):
|
| 205 |
+
The sequence or batch of sequences to be processed as targets. Each sequence can be a numpy array, a
|
| 206 |
+
list of float values, a list of numpy arrays or a list of list of float values. This outputs log-mel
|
| 207 |
+
spectrogram features.
|
| 208 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
| 209 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
| 210 |
+
index) among:
|
| 211 |
+
|
| 212 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 213 |
+
sequence if provided).
|
| 214 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 215 |
+
acceptable input length for the model if that argument is not provided.
|
| 216 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 217 |
+
lengths).
|
| 218 |
+
max_length (`int`, *optional*):
|
| 219 |
+
Maximum length of the returned list and optionally padding length (see above).
|
| 220 |
+
truncation (`bool`):
|
| 221 |
+
Activates truncation to cut input sequences longer than *max_length* to *max_length*.
|
| 222 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 223 |
+
If set will pad the sequence to a multiple of the provided value.
|
| 224 |
+
|
| 225 |
+
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
|
| 226 |
+
`>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
|
| 227 |
+
return_attention_mask (`bool`, *optional*):
|
| 228 |
+
Whether to return the attention mask. If left to the default, will return the attention mask according
|
| 229 |
+
to the specific feature_extractor's default.
|
| 230 |
+
|
| 231 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 232 |
+
|
| 233 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 234 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 235 |
+
|
| 236 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 237 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 238 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 239 |
+
sampling_rate (`int`, *optional*):
|
| 240 |
+
The sampling rate at which the `audio` or `audio_target` input was sampled. It is strongly recommended
|
| 241 |
+
to pass `sampling_rate` at the forward call to prevent silent errors.
|
| 242 |
+
"""
|
| 243 |
+
if audio is None and audio_target is None:
|
| 244 |
+
raise ValueError("You must provide either `audio` or `audio_target` values.")
|
| 245 |
+
|
| 246 |
+
if sampling_rate is not None:
|
| 247 |
+
if sampling_rate != self.sampling_rate:
|
| 248 |
+
raise ValueError(
|
| 249 |
+
f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
|
| 250 |
+
f" {self.sampling_rate}. Please make sure that the provided audio input was sampled with"
|
| 251 |
+
f" {self.sampling_rate} and not {sampling_rate}."
|
| 252 |
+
)
|
| 253 |
+
else:
|
| 254 |
+
logger.warning(
|
| 255 |
+
"It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
|
| 256 |
+
"Failing to do so can result in silent errors that might be hard to debug."
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
if audio is not None:
|
| 260 |
+
inputs = self._process_audio(
|
| 261 |
+
audio,
|
| 262 |
+
False,
|
| 263 |
+
padding,
|
| 264 |
+
max_length,
|
| 265 |
+
truncation,
|
| 266 |
+
pad_to_multiple_of,
|
| 267 |
+
return_attention_mask,
|
| 268 |
+
return_tensors,
|
| 269 |
+
**kwargs,
|
| 270 |
+
)
|
| 271 |
+
else:
|
| 272 |
+
inputs = None
|
| 273 |
+
|
| 274 |
+
if audio_target is not None:
|
| 275 |
+
inputs_target = self._process_audio(
|
| 276 |
+
audio_target,
|
| 277 |
+
True,
|
| 278 |
+
padding,
|
| 279 |
+
max_length,
|
| 280 |
+
truncation,
|
| 281 |
+
pad_to_multiple_of,
|
| 282 |
+
return_attention_mask,
|
| 283 |
+
return_tensors,
|
| 284 |
+
**kwargs,
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
if inputs is None:
|
| 288 |
+
return inputs_target
|
| 289 |
+
else:
|
| 290 |
+
inputs["labels"] = inputs_target["input_values"]
|
| 291 |
+
decoder_attention_mask = inputs_target.get("attention_mask")
|
| 292 |
+
if decoder_attention_mask is not None:
|
| 293 |
+
inputs["decoder_attention_mask"] = decoder_attention_mask
|
| 294 |
+
|
| 295 |
+
return inputs
|
| 296 |
+
|
| 297 |
+
def _process_audio(
|
| 298 |
+
self,
|
| 299 |
+
speech: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],
|
| 300 |
+
is_target: bool = False,
|
| 301 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 302 |
+
max_length: Optional[int] = None,
|
| 303 |
+
truncation: bool = False,
|
| 304 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 305 |
+
return_attention_mask: Optional[bool] = None,
|
| 306 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 307 |
+
**kwargs,
|
| 308 |
+
) -> BatchFeature:
|
| 309 |
+
is_batched_numpy = isinstance(speech, np.ndarray) and len(speech.shape) > 1
|
| 310 |
+
if is_batched_numpy and len(speech.shape) > 2:
|
| 311 |
+
raise ValueError(f"Only mono-channel audio is supported for input to {self}")
|
| 312 |
+
is_batched = is_batched_numpy or (
|
| 313 |
+
isinstance(speech, (list, tuple)) and (isinstance(speech[0], (np.ndarray, tuple, list)))
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
if is_batched:
|
| 317 |
+
speech = [np.asarray(speech, dtype=np.float32) for speech in speech]
|
| 318 |
+
elif not is_batched and not isinstance(speech, np.ndarray):
|
| 319 |
+
speech = np.asarray(speech, dtype=np.float32)
|
| 320 |
+
elif isinstance(speech, np.ndarray) and speech.dtype is np.dtype(np.float64):
|
| 321 |
+
speech = speech.astype(np.float32)
|
| 322 |
+
|
| 323 |
+
# always return batch
|
| 324 |
+
if not is_batched:
|
| 325 |
+
speech = [speech]
|
| 326 |
+
|
| 327 |
+
# needed to make pad() work on spectrogram inputs
|
| 328 |
+
feature_size_hack = self.feature_size
|
| 329 |
+
|
| 330 |
+
# convert into correct format for padding
|
| 331 |
+
if is_target:
|
| 332 |
+
features = [self._extract_mel_features(waveform) for waveform in speech]
|
| 333 |
+
encoded_inputs = BatchFeature({"input_values": features})
|
| 334 |
+
self.feature_size = self.num_mel_bins
|
| 335 |
+
else:
|
| 336 |
+
encoded_inputs = BatchFeature({"input_values": speech})
|
| 337 |
+
|
| 338 |
+
padded_inputs = self.pad(
|
| 339 |
+
encoded_inputs,
|
| 340 |
+
padding=padding,
|
| 341 |
+
max_length=max_length,
|
| 342 |
+
truncation=truncation,
|
| 343 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 344 |
+
return_attention_mask=return_attention_mask,
|
| 345 |
+
**kwargs,
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
self.feature_size = feature_size_hack
|
| 349 |
+
|
| 350 |
+
# convert input values to correct format
|
| 351 |
+
input_values = padded_inputs["input_values"]
|
| 352 |
+
if not isinstance(input_values[0], np.ndarray):
|
| 353 |
+
padded_inputs["input_values"] = [np.asarray(array, dtype=np.float32) for array in input_values]
|
| 354 |
+
elif (
|
| 355 |
+
not isinstance(input_values, np.ndarray)
|
| 356 |
+
and isinstance(input_values[0], np.ndarray)
|
| 357 |
+
and input_values[0].dtype is np.dtype(np.float64)
|
| 358 |
+
):
|
| 359 |
+
padded_inputs["input_values"] = [array.astype(np.float32) for array in input_values]
|
| 360 |
+
elif isinstance(input_values, np.ndarray) and input_values.dtype is np.dtype(np.float64):
|
| 361 |
+
padded_inputs["input_values"] = input_values.astype(np.float32)
|
| 362 |
+
|
| 363 |
+
# convert attention_mask to correct format
|
| 364 |
+
attention_mask = padded_inputs.get("attention_mask")
|
| 365 |
+
if attention_mask is not None:
|
| 366 |
+
padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask]
|
| 367 |
+
|
| 368 |
+
# zero-mean and unit-variance normalization
|
| 369 |
+
if not is_target and self.do_normalize:
|
| 370 |
+
attention_mask = (
|
| 371 |
+
attention_mask
|
| 372 |
+
if self._get_padding_strategies(padding, max_length=max_length) is not PaddingStrategy.DO_NOT_PAD
|
| 373 |
+
else None
|
| 374 |
+
)
|
| 375 |
+
padded_inputs["input_values"] = self.zero_mean_unit_var_norm(
|
| 376 |
+
padded_inputs["input_values"], attention_mask=attention_mask, padding_value=self.padding_value
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
if return_tensors is not None:
|
| 380 |
+
padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
|
| 381 |
+
|
| 382 |
+
return padded_inputs
|
| 383 |
+
|
| 384 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 385 |
+
output = super().to_dict()
|
| 386 |
+
|
| 387 |
+
# Don't serialize these as they are derived from the other properties.
|
| 388 |
+
names = ["window", "mel_filters", "sample_size", "sample_stride", "n_fft", "n_freqs"]
|
| 389 |
+
for name in names:
|
| 390 |
+
if name in output:
|
| 391 |
+
del output[name]
|
| 392 |
+
|
| 393 |
+
return output
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/number_normalizer.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The Fairseq Authors, 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 |
+
"""Number Normalizer class for SpeechT5."""
|
| 16 |
+
|
| 17 |
+
import re
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class EnglishNumberNormalizer:
|
| 21 |
+
def __init__(self):
|
| 22 |
+
self.ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
|
| 23 |
+
self.teens = [
|
| 24 |
+
"",
|
| 25 |
+
"eleven",
|
| 26 |
+
"twelve",
|
| 27 |
+
"thirteen",
|
| 28 |
+
"fourteen",
|
| 29 |
+
"fifteen",
|
| 30 |
+
"sixteen",
|
| 31 |
+
"seventeen",
|
| 32 |
+
"eighteen",
|
| 33 |
+
"nineteen",
|
| 34 |
+
]
|
| 35 |
+
self.tens = ["", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
|
| 36 |
+
self.thousands = [
|
| 37 |
+
"",
|
| 38 |
+
"thousand",
|
| 39 |
+
"million",
|
| 40 |
+
"billion",
|
| 41 |
+
"trillion",
|
| 42 |
+
"quadrillion",
|
| 43 |
+
"quintillion",
|
| 44 |
+
"sextillion",
|
| 45 |
+
"septillion",
|
| 46 |
+
"octillion",
|
| 47 |
+
"nonillion",
|
| 48 |
+
"decillion",
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
# Define a dictionary to map currency symbols to their names
|
| 52 |
+
# Top most traded currencies according to
|
| 53 |
+
# https://en.wikipedia.org/wiki/Template:Most_traded_currencies
|
| 54 |
+
self.currency_symbols = {
|
| 55 |
+
"$": " dollars",
|
| 56 |
+
"€": " euros",
|
| 57 |
+
"£": " pounds",
|
| 58 |
+
"¢": " cents",
|
| 59 |
+
"¥": " japanese yen",
|
| 60 |
+
"﷼": " saudi riyal",
|
| 61 |
+
"₹": " indian rupees",
|
| 62 |
+
"₽": " russian rubles",
|
| 63 |
+
"฿": " thai baht",
|
| 64 |
+
"₺": " turkish liras",
|
| 65 |
+
"₴": " ukrainian hryvnia",
|
| 66 |
+
"₣": " swiss francs",
|
| 67 |
+
"₡": " costa rican colon",
|
| 68 |
+
"₱": " philippine peso",
|
| 69 |
+
"₪": " israeli shekels",
|
| 70 |
+
"₮": " mongolian tögrög",
|
| 71 |
+
"₩": " south korean won",
|
| 72 |
+
"₦": " nigerian naira",
|
| 73 |
+
"₫": " vietnamese Đồng",
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
def spell_number(self, num):
|
| 77 |
+
if num == 0:
|
| 78 |
+
return "zero"
|
| 79 |
+
|
| 80 |
+
parts = []
|
| 81 |
+
for i in range(0, len(self.thousands)):
|
| 82 |
+
if num % 1000 != 0:
|
| 83 |
+
part = ""
|
| 84 |
+
hundreds = num % 1000 // 100
|
| 85 |
+
tens_units = num % 100
|
| 86 |
+
|
| 87 |
+
if hundreds > 0:
|
| 88 |
+
part += self.ones[hundreds] + " hundred"
|
| 89 |
+
if tens_units > 0:
|
| 90 |
+
part += " and "
|
| 91 |
+
|
| 92 |
+
if tens_units > 10 and tens_units < 20:
|
| 93 |
+
part += self.teens[tens_units - 10]
|
| 94 |
+
else:
|
| 95 |
+
tens_digit = self.tens[tens_units // 10]
|
| 96 |
+
ones_digit = self.ones[tens_units % 10]
|
| 97 |
+
if tens_digit:
|
| 98 |
+
part += tens_digit
|
| 99 |
+
if ones_digit:
|
| 100 |
+
if tens_digit:
|
| 101 |
+
part += " "
|
| 102 |
+
part += ones_digit
|
| 103 |
+
|
| 104 |
+
parts.append(part)
|
| 105 |
+
|
| 106 |
+
num //= 1000
|
| 107 |
+
|
| 108 |
+
return " ".join(reversed(parts))
|
| 109 |
+
|
| 110 |
+
def convert(self, number):
|
| 111 |
+
"""
|
| 112 |
+
Converts an individual number passed in string form to spelt-out form
|
| 113 |
+
"""
|
| 114 |
+
if "." in number:
|
| 115 |
+
integer_part, decimal_part = number.split(".")
|
| 116 |
+
else:
|
| 117 |
+
integer_part, decimal_part = number, "00"
|
| 118 |
+
|
| 119 |
+
# Extract currency symbol if present
|
| 120 |
+
currency_symbol = ""
|
| 121 |
+
for symbol, name in self.currency_symbols.items():
|
| 122 |
+
if integer_part.startswith(symbol):
|
| 123 |
+
currency_symbol = name
|
| 124 |
+
integer_part = integer_part[len(symbol) :]
|
| 125 |
+
break
|
| 126 |
+
|
| 127 |
+
if integer_part.startswith("-"):
|
| 128 |
+
if integer_part[1:].startswith(symbol):
|
| 129 |
+
currency_symbol = name
|
| 130 |
+
integer_part = "-" + integer_part[len(symbol) + 1 :]
|
| 131 |
+
break
|
| 132 |
+
|
| 133 |
+
# Extract 'minus' prefix for negative numbers
|
| 134 |
+
minus_prefix = ""
|
| 135 |
+
if integer_part.startswith("-"):
|
| 136 |
+
minus_prefix = "minus "
|
| 137 |
+
integer_part = integer_part[1:]
|
| 138 |
+
elif integer_part.startswith("minus"):
|
| 139 |
+
minus_prefix = "minus "
|
| 140 |
+
integer_part = integer_part[len("minus") :]
|
| 141 |
+
|
| 142 |
+
percent_suffix = ""
|
| 143 |
+
if "%" in integer_part or "%" in decimal_part:
|
| 144 |
+
percent_suffix = " percent"
|
| 145 |
+
integer_part = integer_part.replace("%", "")
|
| 146 |
+
decimal_part = decimal_part.replace("%", "")
|
| 147 |
+
|
| 148 |
+
integer_part = integer_part.zfill(3 * ((len(integer_part) - 1) // 3 + 1))
|
| 149 |
+
|
| 150 |
+
parts = []
|
| 151 |
+
for i in range(0, len(integer_part), 3):
|
| 152 |
+
chunk = int(integer_part[i : i + 3])
|
| 153 |
+
if chunk > 0:
|
| 154 |
+
part = self.spell_number(chunk)
|
| 155 |
+
unit = self.thousands[len(integer_part[i:]) // 3 - 1]
|
| 156 |
+
if unit:
|
| 157 |
+
part += " " + unit
|
| 158 |
+
parts.append(part)
|
| 159 |
+
|
| 160 |
+
spelled_integer = " ".join(parts)
|
| 161 |
+
|
| 162 |
+
# Format the spelt-out number based on conditions, such as:
|
| 163 |
+
# If it has decimal parts, currency symbol, minus prefix, etc
|
| 164 |
+
if decimal_part == "00":
|
| 165 |
+
return (
|
| 166 |
+
f"{minus_prefix}{spelled_integer}{percent_suffix}{currency_symbol}"
|
| 167 |
+
if minus_prefix or currency_symbol
|
| 168 |
+
else f"{spelled_integer}{percent_suffix}"
|
| 169 |
+
)
|
| 170 |
+
else:
|
| 171 |
+
spelled_decimal = " ".join([self.spell_number(int(digit)) for digit in decimal_part])
|
| 172 |
+
return (
|
| 173 |
+
f"{minus_prefix}{spelled_integer} point {spelled_decimal}{percent_suffix}{currency_symbol}"
|
| 174 |
+
if minus_prefix or currency_symbol
|
| 175 |
+
else f"{minus_prefix}{spelled_integer} point {spelled_decimal}{percent_suffix}"
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
def __call__(self, text):
|
| 179 |
+
"""
|
| 180 |
+
Convert numbers / number-like quantities in a string to their spelt-out counterparts
|
| 181 |
+
"""
|
| 182 |
+
# Form part of the pattern for all currency symbols
|
| 183 |
+
pattern = r"(?<!\w)(-?\$?\€?\£?\¢?\¥?\₹?\₽?\฿?\₺?\₴?\₣?\₡?\₱?\₪?\₮?\₩?\₦?\₫?\﷼?\d+(?:\.\d{1,2})?%?)(?!\w)"
|
| 184 |
+
|
| 185 |
+
# Find and replace commas in numbers (15,000 -> 15000, etc)
|
| 186 |
+
text = re.sub(r"(\d+,\d+)", lambda match: match.group(1).replace(",", ""), text)
|
| 187 |
+
|
| 188 |
+
# Use regex to find and replace numbers in the text
|
| 189 |
+
converted_text = re.sub(pattern, lambda match: self.convert(match.group(1)), text)
|
| 190 |
+
converted_text = re.sub(" +", " ", converted_text)
|
| 191 |
+
|
| 192 |
+
return converted_text
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/processing_speecht5.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Speech processor class for SpeechT5."""
|
| 16 |
+
|
| 17 |
+
from ...processing_utils import ProcessorMixin
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class SpeechT5Processor(ProcessorMixin):
|
| 21 |
+
r"""
|
| 22 |
+
Constructs a SpeechT5 processor which wraps a feature extractor and a tokenizer into a single processor.
|
| 23 |
+
|
| 24 |
+
[`SpeechT5Processor`] offers all the functionalities of [`SpeechT5FeatureExtractor`] and [`SpeechT5Tokenizer`]. See
|
| 25 |
+
the docstring of [`~SpeechT5Processor.__call__`] and [`~SpeechT5Processor.decode`] for more information.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
feature_extractor (`SpeechT5FeatureExtractor`):
|
| 29 |
+
An instance of [`SpeechT5FeatureExtractor`]. The feature extractor is a required input.
|
| 30 |
+
tokenizer (`SpeechT5Tokenizer`):
|
| 31 |
+
An instance of [`SpeechT5Tokenizer`]. The tokenizer is a required input.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
feature_extractor_class = "SpeechT5FeatureExtractor"
|
| 35 |
+
tokenizer_class = "SpeechT5Tokenizer"
|
| 36 |
+
|
| 37 |
+
def __init__(self, feature_extractor, tokenizer):
|
| 38 |
+
super().__init__(feature_extractor, tokenizer)
|
| 39 |
+
|
| 40 |
+
def __call__(self, *args, **kwargs):
|
| 41 |
+
"""
|
| 42 |
+
Processes audio and text input, as well as audio and text targets.
|
| 43 |
+
|
| 44 |
+
You can process audio by using the argument `audio`, or process audio targets by using the argument
|
| 45 |
+
`audio_target`. This forwards the arguments to SpeechT5FeatureExtractor's
|
| 46 |
+
[`~SpeechT5FeatureExtractor.__call__`].
|
| 47 |
+
|
| 48 |
+
You can process text by using the argument `text`, or process text labels by using the argument `text_target`.
|
| 49 |
+
This forwards the arguments to SpeechT5Tokenizer's [`~SpeechT5Tokenizer.__call__`].
|
| 50 |
+
|
| 51 |
+
Valid input combinations are:
|
| 52 |
+
|
| 53 |
+
- `text` only
|
| 54 |
+
- `audio` only
|
| 55 |
+
- `text_target` only
|
| 56 |
+
- `audio_target` only
|
| 57 |
+
- `text` and `audio_target`
|
| 58 |
+
- `audio` and `audio_target`
|
| 59 |
+
- `text` and `text_target`
|
| 60 |
+
- `audio` and `text_target`
|
| 61 |
+
|
| 62 |
+
Please refer to the docstring of the above two methods for more information.
|
| 63 |
+
"""
|
| 64 |
+
audio = kwargs.pop("audio", None)
|
| 65 |
+
text = kwargs.pop("text", None)
|
| 66 |
+
text_target = kwargs.pop("text_target", None)
|
| 67 |
+
audio_target = kwargs.pop("audio_target", None)
|
| 68 |
+
sampling_rate = kwargs.pop("sampling_rate", None)
|
| 69 |
+
|
| 70 |
+
if audio is not None and text is not None:
|
| 71 |
+
raise ValueError(
|
| 72 |
+
"Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?"
|
| 73 |
+
)
|
| 74 |
+
if audio_target is not None and text_target is not None:
|
| 75 |
+
raise ValueError(
|
| 76 |
+
"Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?"
|
| 77 |
+
)
|
| 78 |
+
if audio is None and audio_target is None and text is None and text_target is None:
|
| 79 |
+
raise ValueError(
|
| 80 |
+
"You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process."
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
if audio is not None:
|
| 84 |
+
inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
|
| 85 |
+
elif text is not None:
|
| 86 |
+
inputs = self.tokenizer(text, **kwargs)
|
| 87 |
+
else:
|
| 88 |
+
inputs = None
|
| 89 |
+
|
| 90 |
+
if audio_target is not None:
|
| 91 |
+
targets = self.feature_extractor(audio_target=audio_target, *args, sampling_rate=sampling_rate, **kwargs)
|
| 92 |
+
labels = targets["input_values"]
|
| 93 |
+
elif text_target is not None:
|
| 94 |
+
targets = self.tokenizer(text_target, **kwargs)
|
| 95 |
+
labels = targets["input_ids"]
|
| 96 |
+
else:
|
| 97 |
+
targets = None
|
| 98 |
+
|
| 99 |
+
if inputs is None:
|
| 100 |
+
return targets
|
| 101 |
+
|
| 102 |
+
if targets is not None:
|
| 103 |
+
inputs["labels"] = labels
|
| 104 |
+
|
| 105 |
+
decoder_attention_mask = targets.get("attention_mask")
|
| 106 |
+
if decoder_attention_mask is not None:
|
| 107 |
+
inputs["decoder_attention_mask"] = decoder_attention_mask
|
| 108 |
+
|
| 109 |
+
return inputs
|
| 110 |
+
|
| 111 |
+
def pad(self, *args, **kwargs):
|
| 112 |
+
"""
|
| 113 |
+
Collates the audio and text inputs, as well as their targets, into a padded batch.
|
| 114 |
+
|
| 115 |
+
Audio inputs are padded by SpeechT5FeatureExtractor's [`~SpeechT5FeatureExtractor.pad`]. Text inputs are padded
|
| 116 |
+
by SpeechT5Tokenizer's [`~SpeechT5Tokenizer.pad`].
|
| 117 |
+
|
| 118 |
+
Valid input combinations are:
|
| 119 |
+
|
| 120 |
+
- `input_ids` only
|
| 121 |
+
- `input_values` only
|
| 122 |
+
- `labels` only, either log-mel spectrograms or text tokens
|
| 123 |
+
- `input_ids` and log-mel spectrogram `labels`
|
| 124 |
+
- `input_values` and text `labels`
|
| 125 |
+
|
| 126 |
+
Please refer to the docstring of the above two methods for more information.
|
| 127 |
+
"""
|
| 128 |
+
input_values = kwargs.pop("input_values", None)
|
| 129 |
+
input_ids = kwargs.pop("input_ids", None)
|
| 130 |
+
labels = kwargs.pop("labels", None)
|
| 131 |
+
|
| 132 |
+
if input_values is not None and input_ids is not None:
|
| 133 |
+
raise ValueError("Cannot process both `input_values` and `input_ids` inputs.")
|
| 134 |
+
if input_values is None and input_ids is None and labels is None:
|
| 135 |
+
raise ValueError(
|
| 136 |
+
"You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded."
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
if input_values is not None:
|
| 140 |
+
inputs = self.feature_extractor.pad(input_values, *args, **kwargs)
|
| 141 |
+
elif input_ids is not None:
|
| 142 |
+
inputs = self.tokenizer.pad(input_ids, **kwargs)
|
| 143 |
+
else:
|
| 144 |
+
inputs = None
|
| 145 |
+
|
| 146 |
+
if labels is not None:
|
| 147 |
+
if "input_ids" in labels or (isinstance(labels, list) and "input_ids" in labels[0]):
|
| 148 |
+
targets = self.tokenizer.pad(labels, **kwargs)
|
| 149 |
+
labels = targets["input_ids"]
|
| 150 |
+
else:
|
| 151 |
+
feature_size_hack = self.feature_extractor.feature_size
|
| 152 |
+
self.feature_extractor.feature_size = self.feature_extractor.num_mel_bins
|
| 153 |
+
targets = self.feature_extractor.pad(labels, *args, **kwargs)
|
| 154 |
+
self.feature_extractor.feature_size = feature_size_hack
|
| 155 |
+
labels = targets["input_values"]
|
| 156 |
+
else:
|
| 157 |
+
targets = None
|
| 158 |
+
|
| 159 |
+
if inputs is None:
|
| 160 |
+
return targets
|
| 161 |
+
|
| 162 |
+
if targets is not None:
|
| 163 |
+
inputs["labels"] = labels
|
| 164 |
+
|
| 165 |
+
decoder_attention_mask = targets.get("attention_mask")
|
| 166 |
+
if decoder_attention_mask is not None:
|
| 167 |
+
inputs["decoder_attention_mask"] = decoder_attention_mask
|
| 168 |
+
|
| 169 |
+
return inputs
|
| 170 |
+
|
| 171 |
+
def batch_decode(self, *args, **kwargs):
|
| 172 |
+
"""
|
| 173 |
+
This method forwards all its arguments to SpeechT5Tokenizer's [`~SpeechT5Tokenizer.batch_decode`]. Please refer
|
| 174 |
+
to the docstring of this method for more information.
|
| 175 |
+
"""
|
| 176 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 177 |
+
|
| 178 |
+
def decode(self, *args, **kwargs):
|
| 179 |
+
"""
|
| 180 |
+
This method forwards all its arguments to SpeechT5Tokenizer's [`~SpeechT5Tokenizer.decode`]. Please refer to
|
| 181 |
+
the docstring of this method for more information.
|
| 182 |
+
"""
|
| 183 |
+
return self.tokenizer.decode(*args, **kwargs)
|
evalkit_tf437/lib/python3.10/site-packages/transformers/models/speecht5/tokenization_speecht5.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization class for SpeechT5."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
from shutil import copyfile
|
| 20 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import sentencepiece as spm
|
| 23 |
+
|
| 24 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 25 |
+
from ...utils import logging
|
| 26 |
+
from .number_normalizer import EnglishNumberNormalizer
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spm_char.model"}
|
| 32 |
+
|
| 33 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
| 34 |
+
"vocab_file": {
|
| 35 |
+
"microsoft/speecht5_asr": "https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model",
|
| 36 |
+
"microsoft/speecht5_tts": "https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model",
|
| 37 |
+
"microsoft/speecht5_vc": "https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model",
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
| 42 |
+
"microsoft/speecht5_asr": 1024,
|
| 43 |
+
"microsoft/speecht5_tts": 1024,
|
| 44 |
+
"microsoft/speecht5_vc": 1024,
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class SpeechT5Tokenizer(PreTrainedTokenizer):
|
| 49 |
+
"""
|
| 50 |
+
Construct a SpeechT5 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
| 51 |
+
|
| 52 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 53 |
+
this superclass for more information regarding those methods.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
vocab_file (`str`):
|
| 57 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 58 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 59 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 60 |
+
The begin of sequence token.
|
| 61 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 62 |
+
The end of sequence token.
|
| 63 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 64 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 65 |
+
token instead.
|
| 66 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 67 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 68 |
+
normalize (`bool`, *optional*, defaults to `False`):
|
| 69 |
+
Whether to convert numeric quantities in the text to their spelt-out english counterparts.
|
| 70 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 71 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 72 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 73 |
+
to set:
|
| 74 |
+
|
| 75 |
+
- `enable_sampling`: Enable subword regularization.
|
| 76 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 77 |
+
|
| 78 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 79 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 80 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 81 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 82 |
+
|
| 83 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 84 |
+
BPE-dropout.
|
| 85 |
+
|
| 86 |
+
Attributes:
|
| 87 |
+
sp_model (`SentencePieceProcessor`):
|
| 88 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 92 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
| 93 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
| 94 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 95 |
+
|
| 96 |
+
def __init__(
|
| 97 |
+
self,
|
| 98 |
+
vocab_file,
|
| 99 |
+
bos_token="<s>",
|
| 100 |
+
eos_token="</s>",
|
| 101 |
+
unk_token="<unk>",
|
| 102 |
+
pad_token="<pad>",
|
| 103 |
+
normalize=False,
|
| 104 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
| 105 |
+
**kwargs,
|
| 106 |
+
) -> None:
|
| 107 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 108 |
+
self.vocab_file = vocab_file
|
| 109 |
+
self.normalize = normalize
|
| 110 |
+
self._normalizer = None
|
| 111 |
+
|
| 112 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 113 |
+
self.sp_model.Load(vocab_file)
|
| 114 |
+
|
| 115 |
+
super().__init__(
|
| 116 |
+
bos_token=bos_token,
|
| 117 |
+
eos_token=eos_token,
|
| 118 |
+
unk_token=unk_token,
|
| 119 |
+
pad_token=pad_token,
|
| 120 |
+
normalize=normalize,
|
| 121 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 122 |
+
**kwargs,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
|
| 126 |
+
normalize = kwargs.pop("normalize", self.normalize)
|
| 127 |
+
if is_split_into_words:
|
| 128 |
+
text = " " + text
|
| 129 |
+
if normalize:
|
| 130 |
+
text = self.normalizer(text)
|
| 131 |
+
return (text, kwargs)
|
| 132 |
+
|
| 133 |
+
@property
|
| 134 |
+
def vocab_size(self):
|
| 135 |
+
return self.sp_model.get_piece_size()
|
| 136 |
+
|
| 137 |
+
@property
|
| 138 |
+
def normalizer(self):
|
| 139 |
+
if self._normalizer is None:
|
| 140 |
+
self._normalizer = EnglishNumberNormalizer()
|
| 141 |
+
return self._normalizer
|
| 142 |
+
|
| 143 |
+
@normalizer.setter
|
| 144 |
+
def normalizer(self, value):
|
| 145 |
+
self._normalizer = value
|
| 146 |
+
|
| 147 |
+
def get_vocab(self):
|
| 148 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 149 |
+
vocab.update(self.added_tokens_encoder)
|
| 150 |
+
return vocab
|
| 151 |
+
|
| 152 |
+
def __getstate__(self):
|
| 153 |
+
state = self.__dict__.copy()
|
| 154 |
+
state["sp_model"] = None
|
| 155 |
+
return state
|
| 156 |
+
|
| 157 |
+
def __setstate__(self, d):
|
| 158 |
+
self.__dict__ = d
|
| 159 |
+
|
| 160 |
+
# for backward compatibility
|
| 161 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 162 |
+
self.sp_model_kwargs = {}
|
| 163 |
+
|
| 164 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 165 |
+
self.sp_model.Load(self.vocab_file)
|
| 166 |
+
|
| 167 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 168 |
+
"""Take as input a string and return a list of strings (tokens) for words/sub-words"""
|
| 169 |
+
return self.sp_model.encode(text, out_type=str)
|
| 170 |
+
|
| 171 |
+
def _convert_token_to_id(self, token):
|
| 172 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 173 |
+
return self.sp_model.piece_to_id(token)
|
| 174 |
+
|
| 175 |
+
def _convert_id_to_token(self, index):
|
| 176 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 177 |
+
token = self.sp_model.IdToPiece(index)
|
| 178 |
+
return token
|
| 179 |
+
|
| 180 |
+
# Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.convert_tokens_to_string
|
| 181 |
+
def convert_tokens_to_string(self, tokens):
|
| 182 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 183 |
+
current_sub_tokens = []
|
| 184 |
+
out_string = ""
|
| 185 |
+
prev_is_special = False
|
| 186 |
+
for token in tokens:
|
| 187 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
| 188 |
+
if token in self.all_special_tokens:
|
| 189 |
+
if not prev_is_special:
|
| 190 |
+
out_string += " "
|
| 191 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
| 192 |
+
prev_is_special = True
|
| 193 |
+
current_sub_tokens = []
|
| 194 |
+
else:
|
| 195 |
+
current_sub_tokens.append(token)
|
| 196 |
+
prev_is_special = False
|
| 197 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
| 198 |
+
return out_string.strip()
|
| 199 |
+
|
| 200 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> List[int]:
|
| 201 |
+
"""Build model inputs from a sequence by appending eos_token_id."""
|
| 202 |
+
if token_ids_1 is None:
|
| 203 |
+
return token_ids_0 + [self.eos_token_id]
|
| 204 |
+
# We don't expect to process pairs, but leave the pair logic for API consistency
|
| 205 |
+
return token_ids_0 + token_ids_1 + [self.eos_token_id]
|
| 206 |
+
|
| 207 |
+
def get_special_tokens_mask(
|
| 208 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 209 |
+
) -> List[int]:
|
| 210 |
+
if already_has_special_tokens:
|
| 211 |
+
return super().get_special_tokens_mask(
|
| 212 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
suffix_ones = [1]
|
| 216 |
+
if token_ids_1 is None:
|
| 217 |
+
return ([0] * len(token_ids_0)) + suffix_ones
|
| 218 |
+
return ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones
|
| 219 |
+
|
| 220 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 221 |
+
if not os.path.isdir(save_directory):
|
| 222 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 223 |
+
return
|
| 224 |
+
out_vocab_file = os.path.join(
|
| 225 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 229 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 230 |
+
elif not os.path.isfile(self.vocab_file):
|
| 231 |
+
with open(out_vocab_file, "wb") as fi:
|
| 232 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 233 |
+
fi.write(content_spiece_model)
|
| 234 |
+
|
| 235 |
+
return (out_vocab_file,)
|
falcon/lib/python3.10/site-packages/torch/__pycache__/_tensor_docs.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eeb0544059d9d4568592ab3d03c2613e397548ad0dd8b39a7eddb5859b6e361b
|
| 3 |
+
size 134196
|
falcon/lib/python3.10/site-packages/torch/__pycache__/_torch_docs.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8b33cce193043fa5a03cf5a650b0235deb450f565f5eb9a6ed817841c84ff4cc
|
| 3 |
+
size 404999
|
falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (3.74 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/bounds.cpython-310.pyc
ADDED
|
Binary file (4.54 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/codecache.cpython-310.pyc
ADDED
|
Binary file (76.9 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/comm_analysis.cpython-310.pyc
ADDED
|
Binary file (5.14 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/comms.cpython-310.pyc
ADDED
|
Binary file (9.97 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/config.cpython-310.pyc
ADDED
|
Binary file (10.5 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/coordinate_descent_tuner.cpython-310.pyc
ADDED
|
Binary file (7.24 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-310.pyc
ADDED
|
Binary file (60.8 kB). View file
|
|
|
falcon/lib/python3.10/site-packages/torch/_inductor/__pycache__/cudagraph_utils.cpython-310.pyc
ADDED
|
Binary file (3.6 kB). View file
|
|
|