Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/camembert/__init__.py +30 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/camembert/configuration_camembert.py +155 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/camembert/modeling_camembert.py +1576 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/camembert/modeling_tf_camembert.py +1800 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/camembert/tokenization_camembert.py +323 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/camembert/tokenization_camembert_fast.py +197 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/clap/__init__.py +29 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/clap/configuration_clap.py +382 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/clap/feature_extraction_clap.py +367 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/clap/modeling_clap.py +1929 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/clap/processing_clap.py +75 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/__init__.py +28 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/configuration_colpali.py +102 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/modeling_colpali.py +214 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/modular_colpali.py +344 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/processing_colpali.py +410 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/cpm/__init__.py +27 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/cpm/tokenization_cpm.py +350 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/cpm/tokenization_cpm_fast.py +237 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/__init__.py +49 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dinov3_vit/__init__.py +28 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dinov3_vit/configuration_dinov3_vit.py +166 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dinov3_vit/image_processing_dinov3_vit_fast.py +96 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dinov3_vit/modeling_dinov3_vit.py +538 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dinov3_vit/modular_dinov3_vit.py +428 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dpr/__init__.py +30 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dpr/configuration_dpr.py +131 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dpr/modeling_dpr.py +592 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dpr/modeling_tf_dpr.py +799 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dpr/tokenization_dpr.py +321 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dpr/tokenization_dpr_fast.py +321 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm4_moe/__init__.py +27 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm4_moe/configuration_glm4_moe.py +242 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm4_moe/modeling_glm4_moe.py +616 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm4_moe/modular_glm4_moe.py +329 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glpn/__init__.py +29 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glpn/configuration_glpn.py +135 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glpn/feature_extraction_glpn.py +38 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glpn/image_processing_glpn.py +276 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glpn/modeling_glpn.py +724 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_oss/__init__.py +27 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_oss/configuration_gpt_oss.py +126 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_oss/modeling_gpt_oss.py +725 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_oss/modular_gpt_oss.py +472 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/hgnet_v2/__init__.py +29 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/hgnet_v2/configuration_hgnet_v2.py +152 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/hgnet_v2/modeling_hgnet_v2.py +476 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/hgnet_v2/modular_hgnet_v2.py +599 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/hunyuan_v1_moe/__init__.py +14 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/hunyuan_v1_moe/configuration_hunyuan_v1_moe.py +204 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/camembert/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_camembert import *
|
| 22 |
+
from .modeling_camembert import *
|
| 23 |
+
from .modeling_tf_camembert import *
|
| 24 |
+
from .tokenization_camembert import *
|
| 25 |
+
from .tokenization_camembert_fast import *
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
_file = globals()["__file__"]
|
| 30 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/camembert/configuration_camembert.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""CamemBERT configuration"""
|
| 17 |
+
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
from collections.abc import Mapping
|
| 20 |
+
|
| 21 |
+
from ...configuration_utils import PretrainedConfig
|
| 22 |
+
from ...onnx import OnnxConfig
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class CamembertConfig(PretrainedConfig):
|
| 30 |
+
"""
|
| 31 |
+
This is the configuration class to store the configuration of a [`CamembertModel`] or a [`TFCamembertModel`]. It is
|
| 32 |
+
used to instantiate a Camembert model according to the specified arguments, defining the model architecture.
|
| 33 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the Camembert
|
| 34 |
+
[almanach/camembert-base](https://huggingface.co/almanach/camembert-base) architecture.
|
| 35 |
+
|
| 36 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 37 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 42 |
+
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
|
| 43 |
+
`inputs_ids` passed when calling [`CamembertModel`] or [`TFCamembertModel`].
|
| 44 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 45 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 46 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 47 |
+
Number of hidden layers in the Transformer encoder.
|
| 48 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 49 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 50 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 51 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 52 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
| 53 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 54 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 55 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 56 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 57 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 58 |
+
The dropout ratio for the attention probabilities.
|
| 59 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 60 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 61 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 62 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 63 |
+
The vocabulary size of the `token_type_ids` passed when calling [`CamembertModel`] or [`TFCamembertModel`].
|
| 64 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 65 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 66 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 67 |
+
The epsilon used by the layer normalization layers.
|
| 68 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 69 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 70 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 71 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
|
| 72 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 73 |
+
with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
|
| 74 |
+
is_decoder (`bool`, *optional*, defaults to `False`):
|
| 75 |
+
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
|
| 76 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 77 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 78 |
+
relevant if `config.is_decoder=True`.
|
| 79 |
+
classifier_dropout (`float`, *optional*):
|
| 80 |
+
The dropout ratio for the classification head.
|
| 81 |
+
|
| 82 |
+
Example:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
>>> from transformers import CamembertConfig, CamembertModel
|
| 86 |
+
|
| 87 |
+
>>> # Initializing a Camembert almanach/camembert-base style configuration
|
| 88 |
+
>>> configuration = CamembertConfig()
|
| 89 |
+
|
| 90 |
+
>>> # Initializing a model (with random weights) from the almanach/camembert-base style configuration
|
| 91 |
+
>>> model = CamembertModel(configuration)
|
| 92 |
+
|
| 93 |
+
>>> # Accessing the model configuration
|
| 94 |
+
>>> configuration = model.config
|
| 95 |
+
```"""
|
| 96 |
+
|
| 97 |
+
model_type = "camembert"
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
vocab_size=30522,
|
| 102 |
+
hidden_size=768,
|
| 103 |
+
num_hidden_layers=12,
|
| 104 |
+
num_attention_heads=12,
|
| 105 |
+
intermediate_size=3072,
|
| 106 |
+
hidden_act="gelu",
|
| 107 |
+
hidden_dropout_prob=0.1,
|
| 108 |
+
attention_probs_dropout_prob=0.1,
|
| 109 |
+
max_position_embeddings=512,
|
| 110 |
+
type_vocab_size=2,
|
| 111 |
+
initializer_range=0.02,
|
| 112 |
+
layer_norm_eps=1e-12,
|
| 113 |
+
pad_token_id=1,
|
| 114 |
+
bos_token_id=0,
|
| 115 |
+
eos_token_id=2,
|
| 116 |
+
position_embedding_type="absolute",
|
| 117 |
+
use_cache=True,
|
| 118 |
+
classifier_dropout=None,
|
| 119 |
+
**kwargs,
|
| 120 |
+
):
|
| 121 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 122 |
+
|
| 123 |
+
self.vocab_size = vocab_size
|
| 124 |
+
self.hidden_size = hidden_size
|
| 125 |
+
self.num_hidden_layers = num_hidden_layers
|
| 126 |
+
self.num_attention_heads = num_attention_heads
|
| 127 |
+
self.hidden_act = hidden_act
|
| 128 |
+
self.intermediate_size = intermediate_size
|
| 129 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 130 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 131 |
+
self.max_position_embeddings = max_position_embeddings
|
| 132 |
+
self.type_vocab_size = type_vocab_size
|
| 133 |
+
self.initializer_range = initializer_range
|
| 134 |
+
self.layer_norm_eps = layer_norm_eps
|
| 135 |
+
self.position_embedding_type = position_embedding_type
|
| 136 |
+
self.use_cache = use_cache
|
| 137 |
+
self.classifier_dropout = classifier_dropout
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class CamembertOnnxConfig(OnnxConfig):
|
| 141 |
+
@property
|
| 142 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 143 |
+
if self.task == "multiple-choice":
|
| 144 |
+
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
|
| 145 |
+
else:
|
| 146 |
+
dynamic_axis = {0: "batch", 1: "sequence"}
|
| 147 |
+
return OrderedDict(
|
| 148 |
+
[
|
| 149 |
+
("input_ids", dynamic_axis),
|
| 150 |
+
("attention_mask", dynamic_axis),
|
| 151 |
+
]
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
__all__ = ["CamembertConfig", "CamembertOnnxConfig"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/camembert/modeling_camembert.py
ADDED
|
@@ -0,0 +1,1576 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019 Inria, Facebook AI Research and the HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""PyTorch CamemBERT model."""
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
from typing import Optional, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 24 |
+
|
| 25 |
+
from ...activations import ACT2FN, gelu
|
| 26 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 27 |
+
from ...generation import GenerationMixin
|
| 28 |
+
from ...modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa, _prepare_4d_causal_attention_mask_for_sdpa
|
| 29 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 30 |
+
from ...modeling_outputs import (
|
| 31 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 32 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 33 |
+
CausalLMOutputWithCrossAttentions,
|
| 34 |
+
MaskedLMOutput,
|
| 35 |
+
MultipleChoiceModelOutput,
|
| 36 |
+
QuestionAnsweringModelOutput,
|
| 37 |
+
SequenceClassifierOutput,
|
| 38 |
+
TokenClassifierOutput,
|
| 39 |
+
)
|
| 40 |
+
from ...modeling_utils import PreTrainedModel
|
| 41 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 42 |
+
from ...utils import auto_docstring, logging
|
| 43 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 44 |
+
from .configuration_camembert import CamembertConfig
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->Camembert
|
| 51 |
+
class CamembertEmbeddings(nn.Module):
|
| 52 |
+
"""
|
| 53 |
+
Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
# Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__
|
| 57 |
+
def __init__(self, config):
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 60 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 61 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 62 |
+
|
| 63 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 64 |
+
# any TensorFlow checkpoint file
|
| 65 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 66 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 67 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 68 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 69 |
+
self.register_buffer(
|
| 70 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 71 |
+
)
|
| 72 |
+
self.register_buffer(
|
| 73 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# End copy
|
| 77 |
+
self.padding_idx = config.pad_token_id
|
| 78 |
+
self.position_embeddings = nn.Embedding(
|
| 79 |
+
config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
def forward(
|
| 83 |
+
self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
|
| 84 |
+
):
|
| 85 |
+
if position_ids is None:
|
| 86 |
+
if input_ids is not None:
|
| 87 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
| 88 |
+
position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
|
| 89 |
+
else:
|
| 90 |
+
position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
|
| 91 |
+
|
| 92 |
+
if input_ids is not None:
|
| 93 |
+
input_shape = input_ids.size()
|
| 94 |
+
else:
|
| 95 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 96 |
+
|
| 97 |
+
seq_length = input_shape[1]
|
| 98 |
+
|
| 99 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 100 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 101 |
+
# issue #5664
|
| 102 |
+
if token_type_ids is None:
|
| 103 |
+
if hasattr(self, "token_type_ids"):
|
| 104 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 105 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 106 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 107 |
+
else:
|
| 108 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 109 |
+
|
| 110 |
+
if inputs_embeds is None:
|
| 111 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 112 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 113 |
+
|
| 114 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 115 |
+
if self.position_embedding_type == "absolute":
|
| 116 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 117 |
+
embeddings += position_embeddings
|
| 118 |
+
embeddings = self.LayerNorm(embeddings)
|
| 119 |
+
embeddings = self.dropout(embeddings)
|
| 120 |
+
return embeddings
|
| 121 |
+
|
| 122 |
+
def create_position_ids_from_inputs_embeds(self, inputs_embeds):
|
| 123 |
+
"""
|
| 124 |
+
We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
inputs_embeds: torch.Tensor
|
| 128 |
+
|
| 129 |
+
Returns: torch.Tensor
|
| 130 |
+
"""
|
| 131 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 132 |
+
sequence_length = input_shape[1]
|
| 133 |
+
|
| 134 |
+
position_ids = torch.arange(
|
| 135 |
+
self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
|
| 136 |
+
)
|
| 137 |
+
return position_ids.unsqueeze(0).expand(input_shape)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfAttention with Roberta->Camembert
|
| 141 |
+
class CamembertSelfAttention(nn.Module):
|
| 142 |
+
def __init__(self, config, position_embedding_type=None, layer_idx=None):
|
| 143 |
+
super().__init__()
|
| 144 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 145 |
+
raise ValueError(
|
| 146 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 147 |
+
f"heads ({config.num_attention_heads})"
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
self.num_attention_heads = config.num_attention_heads
|
| 151 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 152 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 153 |
+
|
| 154 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 155 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 156 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 157 |
+
|
| 158 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 159 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
| 160 |
+
config, "position_embedding_type", "absolute"
|
| 161 |
+
)
|
| 162 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 163 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 164 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 165 |
+
|
| 166 |
+
self.is_decoder = config.is_decoder
|
| 167 |
+
self.layer_idx = layer_idx
|
| 168 |
+
|
| 169 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 170 |
+
def forward(
|
| 171 |
+
self,
|
| 172 |
+
hidden_states: torch.Tensor,
|
| 173 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 174 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 175 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 176 |
+
past_key_values: Optional[Cache] = None,
|
| 177 |
+
output_attentions: Optional[bool] = False,
|
| 178 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 179 |
+
) -> tuple[torch.Tensor]:
|
| 180 |
+
batch_size, seq_length, _ = hidden_states.shape
|
| 181 |
+
query_layer = self.query(hidden_states)
|
| 182 |
+
query_layer = query_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
|
| 183 |
+
1, 2
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
is_updated = False
|
| 187 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 188 |
+
if past_key_values is not None:
|
| 189 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 190 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 191 |
+
if is_cross_attention:
|
| 192 |
+
# after the first generated id, we can subsequently re-use all key/value_layer from cache
|
| 193 |
+
curr_past_key_value = past_key_values.cross_attention_cache
|
| 194 |
+
else:
|
| 195 |
+
curr_past_key_value = past_key_values.self_attention_cache
|
| 196 |
+
else:
|
| 197 |
+
curr_past_key_value = past_key_values
|
| 198 |
+
|
| 199 |
+
current_states = encoder_hidden_states if is_cross_attention else hidden_states
|
| 200 |
+
if is_cross_attention and past_key_values is not None and is_updated:
|
| 201 |
+
# reuse k,v, cross_attentions
|
| 202 |
+
key_layer = curr_past_key_value.layers[self.layer_idx].keys
|
| 203 |
+
value_layer = curr_past_key_value.layers[self.layer_idx].values
|
| 204 |
+
else:
|
| 205 |
+
key_layer = self.key(current_states)
|
| 206 |
+
key_layer = key_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
|
| 207 |
+
1, 2
|
| 208 |
+
)
|
| 209 |
+
value_layer = self.value(current_states)
|
| 210 |
+
value_layer = value_layer.view(
|
| 211 |
+
batch_size, -1, self.num_attention_heads, self.attention_head_size
|
| 212 |
+
).transpose(1, 2)
|
| 213 |
+
|
| 214 |
+
if past_key_values is not None:
|
| 215 |
+
# save all key/value_layer to cache to be re-used for fast auto-regressive generation
|
| 216 |
+
cache_position = cache_position if not is_cross_attention else None
|
| 217 |
+
key_layer, value_layer = curr_past_key_value.update(
|
| 218 |
+
key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
|
| 219 |
+
)
|
| 220 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 221 |
+
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
|
| 222 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 223 |
+
|
| 224 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 225 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 226 |
+
|
| 227 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 228 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
| 229 |
+
if past_key_values is not None:
|
| 230 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
| 231 |
+
-1, 1
|
| 232 |
+
)
|
| 233 |
+
else:
|
| 234 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 235 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 236 |
+
distance = position_ids_l - position_ids_r
|
| 237 |
+
|
| 238 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 239 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 240 |
+
|
| 241 |
+
if self.position_embedding_type == "relative_key":
|
| 242 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 243 |
+
attention_scores = attention_scores + relative_position_scores
|
| 244 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 245 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 246 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 247 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 248 |
+
|
| 249 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 250 |
+
if attention_mask is not None:
|
| 251 |
+
# Apply the attention mask is (precomputed for all layers in CamembertModel forward() function)
|
| 252 |
+
attention_scores = attention_scores + attention_mask
|
| 253 |
+
|
| 254 |
+
# Normalize the attention scores to probabilities.
|
| 255 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 256 |
+
|
| 257 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 258 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 259 |
+
attention_probs = self.dropout(attention_probs)
|
| 260 |
+
|
| 261 |
+
# Mask heads if we want to
|
| 262 |
+
if head_mask is not None:
|
| 263 |
+
attention_probs = attention_probs * head_mask
|
| 264 |
+
|
| 265 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 266 |
+
|
| 267 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 268 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 269 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 270 |
+
|
| 271 |
+
return context_layer, attention_probs
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaSdpaSelfAttention with Roberta->Camembert
|
| 275 |
+
class CamembertSdpaSelfAttention(CamembertSelfAttention):
|
| 276 |
+
def __init__(self, config, position_embedding_type=None, layer_idx=None):
|
| 277 |
+
super().__init__(config, position_embedding_type=position_embedding_type, layer_idx=layer_idx)
|
| 278 |
+
self.dropout_prob = config.attention_probs_dropout_prob
|
| 279 |
+
|
| 280 |
+
# Adapted from CamembertSelfAttention
|
| 281 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 282 |
+
def forward(
|
| 283 |
+
self,
|
| 284 |
+
hidden_states: torch.Tensor,
|
| 285 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 286 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 287 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 288 |
+
past_key_values: Optional[Cache] = None,
|
| 289 |
+
output_attentions: Optional[bool] = False,
|
| 290 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 291 |
+
) -> tuple[torch.Tensor]:
|
| 292 |
+
if self.position_embedding_type != "absolute" or output_attentions or head_mask is not None:
|
| 293 |
+
# TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once implemented.
|
| 294 |
+
logger.warning_once(
|
| 295 |
+
"CamembertSdpaSelfAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support "
|
| 296 |
+
"non-absolute `position_embedding_type` or `output_attentions=True` or `head_mask`. Falling back to "
|
| 297 |
+
"the manual attention implementation, but specifying the manual implementation will be required from "
|
| 298 |
+
"Transformers version v5.0.0 onwards. This warning can be removed using the argument "
|
| 299 |
+
'`attn_implementation="eager"` when loading the model.'
|
| 300 |
+
)
|
| 301 |
+
return super().forward(
|
| 302 |
+
hidden_states,
|
| 303 |
+
attention_mask,
|
| 304 |
+
head_mask,
|
| 305 |
+
encoder_hidden_states,
|
| 306 |
+
past_key_values,
|
| 307 |
+
output_attentions,
|
| 308 |
+
cache_position,
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
bsz, tgt_len, _ = hidden_states.size()
|
| 312 |
+
|
| 313 |
+
query_layer = (
|
| 314 |
+
self.query(hidden_states).view(bsz, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
is_updated = False
|
| 318 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 319 |
+
current_states = encoder_hidden_states if is_cross_attention else hidden_states
|
| 320 |
+
if past_key_values is not None:
|
| 321 |
+
if isinstance(past_key_values, EncoderDecoderCache):
|
| 322 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 323 |
+
if is_cross_attention:
|
| 324 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 325 |
+
curr_past_key_value = past_key_values.cross_attention_cache
|
| 326 |
+
else:
|
| 327 |
+
curr_past_key_value = past_key_values.self_attention_cache
|
| 328 |
+
else:
|
| 329 |
+
curr_past_key_value = past_key_values
|
| 330 |
+
|
| 331 |
+
current_states = encoder_hidden_states if is_cross_attention else hidden_states
|
| 332 |
+
if is_cross_attention and past_key_values is not None and is_updated:
|
| 333 |
+
# reuse k,v, cross_attentions
|
| 334 |
+
key_layer = curr_past_key_value.layers[self.layer_idx].keys
|
| 335 |
+
value_layer = curr_past_key_value.layers[self.layer_idx].values
|
| 336 |
+
else:
|
| 337 |
+
key_layer = (
|
| 338 |
+
self.key(current_states)
|
| 339 |
+
.view(bsz, -1, self.num_attention_heads, self.attention_head_size)
|
| 340 |
+
.transpose(1, 2)
|
| 341 |
+
)
|
| 342 |
+
value_layer = (
|
| 343 |
+
self.value(current_states)
|
| 344 |
+
.view(bsz, -1, self.num_attention_heads, self.attention_head_size)
|
| 345 |
+
.transpose(1, 2)
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
if past_key_values is not None:
|
| 349 |
+
# save all key/value_layer to cache to be re-used for fast auto-regressive generation
|
| 350 |
+
cache_position = cache_position if not is_cross_attention else None
|
| 351 |
+
key_layer, value_layer = curr_past_key_value.update(
|
| 352 |
+
key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
|
| 353 |
+
)
|
| 354 |
+
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
|
| 355 |
+
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
|
| 356 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 357 |
+
|
| 358 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
| 359 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
| 360 |
+
# The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create
|
| 361 |
+
# a causal mask in case tgt_len == 1.
|
| 362 |
+
is_causal = self.is_decoder and not is_cross_attention and attention_mask is None and tgt_len > 1
|
| 363 |
+
|
| 364 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 365 |
+
query_layer,
|
| 366 |
+
key_layer,
|
| 367 |
+
value_layer,
|
| 368 |
+
attn_mask=attention_mask,
|
| 369 |
+
dropout_p=self.dropout_prob if self.training else 0.0,
|
| 370 |
+
is_causal=is_causal,
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
attn_output = attn_output.transpose(1, 2)
|
| 374 |
+
attn_output = attn_output.reshape(bsz, tgt_len, self.all_head_size)
|
| 375 |
+
|
| 376 |
+
return attn_output, None
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput with Roberta->Camembert
|
| 380 |
+
class CamembertSelfOutput(nn.Module):
|
| 381 |
+
def __init__(self, config):
|
| 382 |
+
super().__init__()
|
| 383 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 384 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 385 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 386 |
+
|
| 387 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 388 |
+
hidden_states = self.dense(hidden_states)
|
| 389 |
+
hidden_states = self.dropout(hidden_states)
|
| 390 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 391 |
+
return hidden_states
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
CAMEMBERT_SELF_ATTENTION_CLASSES = {
|
| 395 |
+
"eager": CamembertSelfAttention,
|
| 396 |
+
"sdpa": CamembertSdpaSelfAttention,
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaAttention with Roberta->Camembert,ROBERTA->CAMEMBERT
|
| 401 |
+
class CamembertAttention(nn.Module):
|
| 402 |
+
def __init__(self, config, position_embedding_type=None, layer_idx=None):
|
| 403 |
+
super().__init__()
|
| 404 |
+
self.self = CAMEMBERT_SELF_ATTENTION_CLASSES[config._attn_implementation](
|
| 405 |
+
config,
|
| 406 |
+
position_embedding_type=position_embedding_type,
|
| 407 |
+
layer_idx=layer_idx,
|
| 408 |
+
)
|
| 409 |
+
self.output = CamembertSelfOutput(config)
|
| 410 |
+
self.pruned_heads = set()
|
| 411 |
+
|
| 412 |
+
def prune_heads(self, heads):
|
| 413 |
+
if len(heads) == 0:
|
| 414 |
+
return
|
| 415 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 416 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
# Prune linear layers
|
| 420 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 421 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 422 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 423 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 424 |
+
|
| 425 |
+
# Update hyper params and store pruned heads
|
| 426 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 427 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 428 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 429 |
+
|
| 430 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 431 |
+
def forward(
|
| 432 |
+
self,
|
| 433 |
+
hidden_states: torch.Tensor,
|
| 434 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 435 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 436 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 437 |
+
past_key_values: Optional[Cache] = None,
|
| 438 |
+
output_attentions: Optional[bool] = False,
|
| 439 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 440 |
+
) -> tuple[torch.Tensor]:
|
| 441 |
+
self_outputs = self.self(
|
| 442 |
+
hidden_states,
|
| 443 |
+
attention_mask=attention_mask,
|
| 444 |
+
head_mask=head_mask,
|
| 445 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 446 |
+
past_key_values=past_key_values,
|
| 447 |
+
output_attentions=output_attentions,
|
| 448 |
+
cache_position=cache_position,
|
| 449 |
+
)
|
| 450 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 451 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 452 |
+
return outputs
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Roberta->Camembert
|
| 456 |
+
class CamembertIntermediate(nn.Module):
|
| 457 |
+
def __init__(self, config):
|
| 458 |
+
super().__init__()
|
| 459 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 460 |
+
if isinstance(config.hidden_act, str):
|
| 461 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 462 |
+
else:
|
| 463 |
+
self.intermediate_act_fn = config.hidden_act
|
| 464 |
+
|
| 465 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 466 |
+
hidden_states = self.dense(hidden_states)
|
| 467 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 468 |
+
return hidden_states
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Roberta->Camembert
|
| 472 |
+
class CamembertOutput(nn.Module):
|
| 473 |
+
def __init__(self, config):
|
| 474 |
+
super().__init__()
|
| 475 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 476 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 477 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 478 |
+
|
| 479 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 480 |
+
hidden_states = self.dense(hidden_states)
|
| 481 |
+
hidden_states = self.dropout(hidden_states)
|
| 482 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 483 |
+
return hidden_states
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaLayer with Roberta->Camembert
|
| 487 |
+
class CamembertLayer(GradientCheckpointingLayer):
|
| 488 |
+
def __init__(self, config, layer_idx=None):
|
| 489 |
+
super().__init__()
|
| 490 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 491 |
+
self.seq_len_dim = 1
|
| 492 |
+
self.attention = CamembertAttention(config, layer_idx=layer_idx)
|
| 493 |
+
self.is_decoder = config.is_decoder
|
| 494 |
+
self.add_cross_attention = config.add_cross_attention
|
| 495 |
+
if self.add_cross_attention:
|
| 496 |
+
if not self.is_decoder:
|
| 497 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 498 |
+
self.crossattention = CamembertAttention(config, position_embedding_type="absolute", layer_idx=layer_idx)
|
| 499 |
+
self.intermediate = CamembertIntermediate(config)
|
| 500 |
+
self.output = CamembertOutput(config)
|
| 501 |
+
|
| 502 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 503 |
+
def forward(
|
| 504 |
+
self,
|
| 505 |
+
hidden_states: torch.Tensor,
|
| 506 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 507 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 508 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 509 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 510 |
+
past_key_values: Optional[Cache] = None,
|
| 511 |
+
output_attentions: Optional[bool] = False,
|
| 512 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 513 |
+
) -> tuple[torch.Tensor]:
|
| 514 |
+
self_attention_outputs = self.attention(
|
| 515 |
+
hidden_states,
|
| 516 |
+
attention_mask=attention_mask,
|
| 517 |
+
head_mask=head_mask,
|
| 518 |
+
output_attentions=output_attentions,
|
| 519 |
+
past_key_values=past_key_values,
|
| 520 |
+
cache_position=cache_position,
|
| 521 |
+
)
|
| 522 |
+
attention_output = self_attention_outputs[0]
|
| 523 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 524 |
+
|
| 525 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 526 |
+
if not hasattr(self, "crossattention"):
|
| 527 |
+
raise ValueError(
|
| 528 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 529 |
+
" by setting `config.add_cross_attention=True`"
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
cross_attention_outputs = self.crossattention(
|
| 533 |
+
attention_output,
|
| 534 |
+
attention_mask=encoder_attention_mask,
|
| 535 |
+
head_mask=head_mask,
|
| 536 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 537 |
+
past_key_values=past_key_values,
|
| 538 |
+
output_attentions=output_attentions,
|
| 539 |
+
cache_position=cache_position,
|
| 540 |
+
)
|
| 541 |
+
attention_output = cross_attention_outputs[0]
|
| 542 |
+
outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
|
| 543 |
+
|
| 544 |
+
layer_output = apply_chunking_to_forward(
|
| 545 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 546 |
+
)
|
| 547 |
+
outputs = (layer_output,) + outputs
|
| 548 |
+
|
| 549 |
+
return outputs
|
| 550 |
+
|
| 551 |
+
def feed_forward_chunk(self, attention_output):
|
| 552 |
+
intermediate_output = self.intermediate(attention_output)
|
| 553 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 554 |
+
return layer_output
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaEncoder with Roberta->Camembert
|
| 558 |
+
class CamembertEncoder(nn.Module):
|
| 559 |
+
def __init__(self, config, layer_idx=None):
|
| 560 |
+
super().__init__()
|
| 561 |
+
self.config = config
|
| 562 |
+
self.layer = nn.ModuleList([CamembertLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
|
| 563 |
+
self.gradient_checkpointing = False
|
| 564 |
+
|
| 565 |
+
def forward(
|
| 566 |
+
self,
|
| 567 |
+
hidden_states: torch.Tensor,
|
| 568 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 569 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 570 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 571 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 572 |
+
past_key_values: Optional[Cache] = None,
|
| 573 |
+
use_cache: Optional[bool] = None,
|
| 574 |
+
output_attentions: Optional[bool] = False,
|
| 575 |
+
output_hidden_states: Optional[bool] = False,
|
| 576 |
+
return_dict: Optional[bool] = True,
|
| 577 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 578 |
+
) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
| 579 |
+
all_hidden_states = () if output_hidden_states else None
|
| 580 |
+
all_self_attentions = () if output_attentions else None
|
| 581 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 582 |
+
|
| 583 |
+
if self.gradient_checkpointing and self.training:
|
| 584 |
+
if use_cache:
|
| 585 |
+
logger.warning_once(
|
| 586 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 587 |
+
)
|
| 588 |
+
use_cache = False
|
| 589 |
+
|
| 590 |
+
if use_cache and self.config.is_decoder and past_key_values is None:
|
| 591 |
+
past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 592 |
+
|
| 593 |
+
if use_cache and self.config.is_decoder and isinstance(past_key_values, tuple):
|
| 594 |
+
logger.warning_once(
|
| 595 |
+
"Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. "
|
| 596 |
+
"You should pass an instance of `EncoderDecoderCache` instead, e.g. "
|
| 597 |
+
"`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
|
| 598 |
+
)
|
| 599 |
+
past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
|
| 600 |
+
|
| 601 |
+
for i, layer_module in enumerate(self.layer):
|
| 602 |
+
if output_hidden_states:
|
| 603 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 604 |
+
|
| 605 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 606 |
+
|
| 607 |
+
layer_outputs = layer_module(
|
| 608 |
+
hidden_states,
|
| 609 |
+
attention_mask,
|
| 610 |
+
layer_head_mask,
|
| 611 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 612 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 613 |
+
past_key_values=past_key_values,
|
| 614 |
+
output_attentions=output_attentions,
|
| 615 |
+
cache_position=cache_position,
|
| 616 |
+
)
|
| 617 |
+
|
| 618 |
+
hidden_states = layer_outputs[0]
|
| 619 |
+
if output_attentions:
|
| 620 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 621 |
+
if self.config.add_cross_attention:
|
| 622 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 623 |
+
|
| 624 |
+
if output_hidden_states:
|
| 625 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 626 |
+
|
| 627 |
+
if not return_dict:
|
| 628 |
+
return tuple(
|
| 629 |
+
v
|
| 630 |
+
for v in [
|
| 631 |
+
hidden_states,
|
| 632 |
+
past_key_values,
|
| 633 |
+
all_hidden_states,
|
| 634 |
+
all_self_attentions,
|
| 635 |
+
all_cross_attentions,
|
| 636 |
+
]
|
| 637 |
+
if v is not None
|
| 638 |
+
)
|
| 639 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 640 |
+
last_hidden_state=hidden_states,
|
| 641 |
+
past_key_values=past_key_values,
|
| 642 |
+
hidden_states=all_hidden_states,
|
| 643 |
+
attentions=all_self_attentions,
|
| 644 |
+
cross_attentions=all_cross_attentions,
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler
|
| 649 |
+
class CamembertPooler(nn.Module):
|
| 650 |
+
def __init__(self, config):
|
| 651 |
+
super().__init__()
|
| 652 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 653 |
+
self.activation = nn.Tanh()
|
| 654 |
+
|
| 655 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 656 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 657 |
+
# to the first token.
|
| 658 |
+
first_token_tensor = hidden_states[:, 0]
|
| 659 |
+
pooled_output = self.dense(first_token_tensor)
|
| 660 |
+
pooled_output = self.activation(pooled_output)
|
| 661 |
+
return pooled_output
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
@auto_docstring
|
| 665 |
+
class CamembertPreTrainedModel(PreTrainedModel):
|
| 666 |
+
config: CamembertConfig
|
| 667 |
+
base_model_prefix = "roberta"
|
| 668 |
+
supports_gradient_checkpointing = True
|
| 669 |
+
_supports_sdpa = True
|
| 670 |
+
|
| 671 |
+
# Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights with BertLMPredictionHead->CamembertLMHead
|
| 672 |
+
def _init_weights(self, module):
|
| 673 |
+
"""Initialize the weights"""
|
| 674 |
+
if isinstance(module, nn.Linear):
|
| 675 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 676 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 677 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 678 |
+
if module.bias is not None:
|
| 679 |
+
module.bias.data.zero_()
|
| 680 |
+
elif isinstance(module, nn.Embedding):
|
| 681 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 682 |
+
if module.padding_idx is not None:
|
| 683 |
+
module.weight.data[module.padding_idx].zero_()
|
| 684 |
+
elif isinstance(module, nn.LayerNorm):
|
| 685 |
+
module.bias.data.zero_()
|
| 686 |
+
module.weight.data.fill_(1.0)
|
| 687 |
+
elif isinstance(module, CamembertLMHead):
|
| 688 |
+
module.bias.data.zero_()
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaClassificationHead with Roberta->Camembert
|
| 692 |
+
class CamembertClassificationHead(nn.Module):
|
| 693 |
+
"""Head for sentence-level classification tasks."""
|
| 694 |
+
|
| 695 |
+
def __init__(self, config):
|
| 696 |
+
super().__init__()
|
| 697 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 698 |
+
classifier_dropout = (
|
| 699 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 700 |
+
)
|
| 701 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 702 |
+
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
|
| 703 |
+
|
| 704 |
+
def forward(self, features, **kwargs):
|
| 705 |
+
x = features[:, 0, :] # take <s> token (equiv. to [CLS])
|
| 706 |
+
x = self.dropout(x)
|
| 707 |
+
x = self.dense(x)
|
| 708 |
+
x = torch.tanh(x)
|
| 709 |
+
x = self.dropout(x)
|
| 710 |
+
x = self.out_proj(x)
|
| 711 |
+
return x
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaLMHead with Roberta->Camembert
|
| 715 |
+
class CamembertLMHead(nn.Module):
|
| 716 |
+
"""Camembert Head for masked language modeling."""
|
| 717 |
+
|
| 718 |
+
def __init__(self, config):
|
| 719 |
+
super().__init__()
|
| 720 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 721 |
+
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 722 |
+
|
| 723 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
|
| 724 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 725 |
+
self.decoder.bias = self.bias
|
| 726 |
+
|
| 727 |
+
def forward(self, features, **kwargs):
|
| 728 |
+
x = self.dense(features)
|
| 729 |
+
x = gelu(x)
|
| 730 |
+
x = self.layer_norm(x)
|
| 731 |
+
|
| 732 |
+
# project back to size of vocabulary with bias
|
| 733 |
+
x = self.decoder(x)
|
| 734 |
+
|
| 735 |
+
return x
|
| 736 |
+
|
| 737 |
+
def _tie_weights(self):
|
| 738 |
+
# To tie those two weights if they get disconnected (on TPU or when the bias is resized)
|
| 739 |
+
# For accelerate compatibility and to not break backward compatibility
|
| 740 |
+
if self.decoder.bias.device.type == "meta":
|
| 741 |
+
self.decoder.bias = self.bias
|
| 742 |
+
else:
|
| 743 |
+
self.bias = self.decoder.bias
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
@auto_docstring
|
| 747 |
+
class CamembertModel(CamembertPreTrainedModel):
|
| 748 |
+
"""
|
| 749 |
+
|
| 750 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 751 |
+
cross-attention is added between the self-attention layers, following the architecture described in *Attention is
|
| 752 |
+
all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
|
| 753 |
+
Kaiser and Illia Polosukhin.
|
| 754 |
+
|
| 755 |
+
To behave as a decoder the model needs to be initialized with the `is_decoder` argument of the configuration set to
|
| 756 |
+
`True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
| 757 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
| 758 |
+
|
| 759 |
+
.. _*Attention is all you need*: https://huggingface.co/papers/1706.03762
|
| 760 |
+
|
| 761 |
+
"""
|
| 762 |
+
|
| 763 |
+
_no_split_modules = []
|
| 764 |
+
|
| 765 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaModel.__init__ with Roberta->Camembert
|
| 766 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 767 |
+
r"""
|
| 768 |
+
add_pooling_layer (bool, *optional*, defaults to `True`):
|
| 769 |
+
Whether to add a pooling layer
|
| 770 |
+
"""
|
| 771 |
+
super().__init__(config)
|
| 772 |
+
self.config = config
|
| 773 |
+
|
| 774 |
+
self.embeddings = CamembertEmbeddings(config)
|
| 775 |
+
self.encoder = CamembertEncoder(config)
|
| 776 |
+
|
| 777 |
+
self.pooler = CamembertPooler(config) if add_pooling_layer else None
|
| 778 |
+
|
| 779 |
+
self.attn_implementation = config._attn_implementation
|
| 780 |
+
self.position_embedding_type = config.position_embedding_type
|
| 781 |
+
|
| 782 |
+
# Initialize weights and apply final processing
|
| 783 |
+
self.post_init()
|
| 784 |
+
|
| 785 |
+
def get_input_embeddings(self):
|
| 786 |
+
return self.embeddings.word_embeddings
|
| 787 |
+
|
| 788 |
+
def set_input_embeddings(self, value):
|
| 789 |
+
self.embeddings.word_embeddings = value
|
| 790 |
+
|
| 791 |
+
def _prune_heads(self, heads_to_prune):
|
| 792 |
+
"""
|
| 793 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 794 |
+
class PreTrainedModel
|
| 795 |
+
"""
|
| 796 |
+
for layer, heads in heads_to_prune.items():
|
| 797 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 798 |
+
|
| 799 |
+
@auto_docstring
|
| 800 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaModel.forward
|
| 801 |
+
def forward(
|
| 802 |
+
self,
|
| 803 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 804 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 805 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 806 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 807 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 808 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 809 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 810 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 811 |
+
past_key_values: Optional[Cache] = None,
|
| 812 |
+
use_cache: Optional[bool] = None,
|
| 813 |
+
output_attentions: Optional[bool] = None,
|
| 814 |
+
output_hidden_states: Optional[bool] = None,
|
| 815 |
+
return_dict: Optional[bool] = None,
|
| 816 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 817 |
+
) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
| 818 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 819 |
+
output_hidden_states = (
|
| 820 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 821 |
+
)
|
| 822 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 823 |
+
|
| 824 |
+
if self.config.is_decoder:
|
| 825 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 826 |
+
else:
|
| 827 |
+
use_cache = False
|
| 828 |
+
|
| 829 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 830 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 831 |
+
elif input_ids is not None:
|
| 832 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 833 |
+
input_shape = input_ids.size()
|
| 834 |
+
elif inputs_embeds is not None:
|
| 835 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 836 |
+
else:
|
| 837 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 838 |
+
|
| 839 |
+
batch_size, seq_length = input_shape
|
| 840 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 841 |
+
|
| 842 |
+
past_key_values_length = 0
|
| 843 |
+
if past_key_values is not None:
|
| 844 |
+
past_key_values_length = (
|
| 845 |
+
past_key_values[0][0].shape[-2]
|
| 846 |
+
if not isinstance(past_key_values, Cache)
|
| 847 |
+
else past_key_values.get_seq_length()
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
if token_type_ids is None:
|
| 851 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 852 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 853 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 854 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 855 |
+
else:
|
| 856 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 857 |
+
|
| 858 |
+
embedding_output = self.embeddings(
|
| 859 |
+
input_ids=input_ids,
|
| 860 |
+
position_ids=position_ids,
|
| 861 |
+
token_type_ids=token_type_ids,
|
| 862 |
+
inputs_embeds=inputs_embeds,
|
| 863 |
+
past_key_values_length=past_key_values_length,
|
| 864 |
+
)
|
| 865 |
+
|
| 866 |
+
if attention_mask is None:
|
| 867 |
+
attention_mask = torch.ones((batch_size, seq_length + past_key_values_length), device=device)
|
| 868 |
+
|
| 869 |
+
use_sdpa_attention_masks = (
|
| 870 |
+
self.attn_implementation == "sdpa"
|
| 871 |
+
and self.position_embedding_type == "absolute"
|
| 872 |
+
and head_mask is None
|
| 873 |
+
and not output_attentions
|
| 874 |
+
)
|
| 875 |
+
|
| 876 |
+
# Expand the attention mask
|
| 877 |
+
if use_sdpa_attention_masks and attention_mask.dim() == 2:
|
| 878 |
+
# Expand the attention mask for SDPA.
|
| 879 |
+
# [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
|
| 880 |
+
if self.config.is_decoder:
|
| 881 |
+
extended_attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
| 882 |
+
attention_mask,
|
| 883 |
+
input_shape,
|
| 884 |
+
embedding_output,
|
| 885 |
+
past_key_values_length,
|
| 886 |
+
)
|
| 887 |
+
else:
|
| 888 |
+
extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
|
| 889 |
+
attention_mask, embedding_output.dtype, tgt_len=seq_length
|
| 890 |
+
)
|
| 891 |
+
else:
|
| 892 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 893 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 894 |
+
extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 895 |
+
|
| 896 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
| 897 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 898 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
| 899 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
| 900 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
| 901 |
+
if encoder_attention_mask is None:
|
| 902 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
| 903 |
+
|
| 904 |
+
if use_sdpa_attention_masks and encoder_attention_mask.dim() == 2:
|
| 905 |
+
# Expand the attention mask for SDPA.
|
| 906 |
+
# [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
|
| 907 |
+
encoder_extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
|
| 908 |
+
encoder_attention_mask, embedding_output.dtype, tgt_len=seq_length
|
| 909 |
+
)
|
| 910 |
+
else:
|
| 911 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
| 912 |
+
else:
|
| 913 |
+
encoder_extended_attention_mask = None
|
| 914 |
+
|
| 915 |
+
# Prepare head mask if needed
|
| 916 |
+
# 1.0 in head_mask indicate we keep the head
|
| 917 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 918 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 919 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 920 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 921 |
+
|
| 922 |
+
encoder_outputs = self.encoder(
|
| 923 |
+
embedding_output,
|
| 924 |
+
attention_mask=extended_attention_mask,
|
| 925 |
+
head_mask=head_mask,
|
| 926 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 927 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 928 |
+
past_key_values=past_key_values,
|
| 929 |
+
use_cache=use_cache,
|
| 930 |
+
output_attentions=output_attentions,
|
| 931 |
+
output_hidden_states=output_hidden_states,
|
| 932 |
+
return_dict=return_dict,
|
| 933 |
+
cache_position=cache_position,
|
| 934 |
+
)
|
| 935 |
+
sequence_output = encoder_outputs[0]
|
| 936 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 937 |
+
|
| 938 |
+
if not return_dict:
|
| 939 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 940 |
+
|
| 941 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
| 942 |
+
last_hidden_state=sequence_output,
|
| 943 |
+
pooler_output=pooled_output,
|
| 944 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 945 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 946 |
+
attentions=encoder_outputs.attentions,
|
| 947 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 948 |
+
)
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
@auto_docstring
|
| 952 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 953 |
+
class CamembertForMaskedLM(CamembertPreTrainedModel):
|
| 954 |
+
_tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
|
| 955 |
+
|
| 956 |
+
def __init__(self, config):
|
| 957 |
+
super().__init__(config)
|
| 958 |
+
|
| 959 |
+
if config.is_decoder:
|
| 960 |
+
logger.warning(
|
| 961 |
+
"If you want to use `CamembertForMaskedLM` make sure `config.is_decoder=False` for "
|
| 962 |
+
"bi-directional self-attention."
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
self.roberta = CamembertModel(config, add_pooling_layer=False)
|
| 966 |
+
self.lm_head = CamembertLMHead(config)
|
| 967 |
+
|
| 968 |
+
# Initialize weights and apply final processing
|
| 969 |
+
self.post_init()
|
| 970 |
+
|
| 971 |
+
def get_output_embeddings(self):
|
| 972 |
+
return self.lm_head.decoder
|
| 973 |
+
|
| 974 |
+
def set_output_embeddings(self, new_embeddings):
|
| 975 |
+
self.lm_head.decoder = new_embeddings
|
| 976 |
+
|
| 977 |
+
@auto_docstring
|
| 978 |
+
def forward(
|
| 979 |
+
self,
|
| 980 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 981 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 982 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 983 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 984 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 985 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 986 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 987 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 988 |
+
labels: Optional[torch.LongTensor] = None,
|
| 989 |
+
output_attentions: Optional[bool] = None,
|
| 990 |
+
output_hidden_states: Optional[bool] = None,
|
| 991 |
+
return_dict: Optional[bool] = None,
|
| 992 |
+
) -> Union[tuple[torch.Tensor], MaskedLMOutput]:
|
| 993 |
+
r"""
|
| 994 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 995 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
|
| 996 |
+
|
| 997 |
+
- 0 corresponds to a *sentence A* token,
|
| 998 |
+
- 1 corresponds to a *sentence B* token.
|
| 999 |
+
This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
|
| 1000 |
+
>= 2. All the value in this tensor should be always < type_vocab_size.
|
| 1001 |
+
|
| 1002 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 1003 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1004 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 1005 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 1006 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1007 |
+
"""
|
| 1008 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1009 |
+
|
| 1010 |
+
outputs = self.roberta(
|
| 1011 |
+
input_ids,
|
| 1012 |
+
attention_mask=attention_mask,
|
| 1013 |
+
token_type_ids=token_type_ids,
|
| 1014 |
+
position_ids=position_ids,
|
| 1015 |
+
head_mask=head_mask,
|
| 1016 |
+
inputs_embeds=inputs_embeds,
|
| 1017 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1018 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1019 |
+
output_attentions=output_attentions,
|
| 1020 |
+
output_hidden_states=output_hidden_states,
|
| 1021 |
+
return_dict=return_dict,
|
| 1022 |
+
)
|
| 1023 |
+
sequence_output = outputs[0]
|
| 1024 |
+
prediction_scores = self.lm_head(sequence_output)
|
| 1025 |
+
|
| 1026 |
+
masked_lm_loss = None
|
| 1027 |
+
if labels is not None:
|
| 1028 |
+
# move labels to correct device to enable model parallelism
|
| 1029 |
+
labels = labels.to(prediction_scores.device)
|
| 1030 |
+
loss_fct = CrossEntropyLoss()
|
| 1031 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1032 |
+
|
| 1033 |
+
if not return_dict:
|
| 1034 |
+
output = (prediction_scores,) + outputs[2:]
|
| 1035 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1036 |
+
|
| 1037 |
+
return MaskedLMOutput(
|
| 1038 |
+
loss=masked_lm_loss,
|
| 1039 |
+
logits=prediction_scores,
|
| 1040 |
+
hidden_states=outputs.hidden_states,
|
| 1041 |
+
attentions=outputs.attentions,
|
| 1042 |
+
)
|
| 1043 |
+
|
| 1044 |
+
|
| 1045 |
+
@auto_docstring(
|
| 1046 |
+
custom_intro="""
|
| 1047 |
+
CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the
|
| 1048 |
+
pooled output) e.g. for GLUE tasks.
|
| 1049 |
+
"""
|
| 1050 |
+
)
|
| 1051 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForSequenceClassification with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 1052 |
+
class CamembertForSequenceClassification(CamembertPreTrainedModel):
|
| 1053 |
+
def __init__(self, config):
|
| 1054 |
+
super().__init__(config)
|
| 1055 |
+
self.num_labels = config.num_labels
|
| 1056 |
+
self.config = config
|
| 1057 |
+
|
| 1058 |
+
self.roberta = CamembertModel(config, add_pooling_layer=False)
|
| 1059 |
+
self.classifier = CamembertClassificationHead(config)
|
| 1060 |
+
|
| 1061 |
+
# Initialize weights and apply final processing
|
| 1062 |
+
self.post_init()
|
| 1063 |
+
|
| 1064 |
+
@auto_docstring
|
| 1065 |
+
def forward(
|
| 1066 |
+
self,
|
| 1067 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1068 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1069 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1070 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1071 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1072 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1073 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1074 |
+
output_attentions: Optional[bool] = None,
|
| 1075 |
+
output_hidden_states: Optional[bool] = None,
|
| 1076 |
+
return_dict: Optional[bool] = None,
|
| 1077 |
+
) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
|
| 1078 |
+
r"""
|
| 1079 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1080 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
|
| 1081 |
+
|
| 1082 |
+
- 0 corresponds to a *sentence A* token,
|
| 1083 |
+
- 1 corresponds to a *sentence B* token.
|
| 1084 |
+
This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
|
| 1085 |
+
>= 2. All the value in this tensor should be always < type_vocab_size.
|
| 1086 |
+
|
| 1087 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 1088 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1089 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1090 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1091 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1092 |
+
"""
|
| 1093 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1094 |
+
|
| 1095 |
+
outputs = self.roberta(
|
| 1096 |
+
input_ids,
|
| 1097 |
+
attention_mask=attention_mask,
|
| 1098 |
+
token_type_ids=token_type_ids,
|
| 1099 |
+
position_ids=position_ids,
|
| 1100 |
+
head_mask=head_mask,
|
| 1101 |
+
inputs_embeds=inputs_embeds,
|
| 1102 |
+
output_attentions=output_attentions,
|
| 1103 |
+
output_hidden_states=output_hidden_states,
|
| 1104 |
+
return_dict=return_dict,
|
| 1105 |
+
)
|
| 1106 |
+
sequence_output = outputs[0]
|
| 1107 |
+
logits = self.classifier(sequence_output)
|
| 1108 |
+
|
| 1109 |
+
loss = None
|
| 1110 |
+
if labels is not None:
|
| 1111 |
+
# move labels to correct device to enable model parallelism
|
| 1112 |
+
labels = labels.to(logits.device)
|
| 1113 |
+
if self.config.problem_type is None:
|
| 1114 |
+
if self.num_labels == 1:
|
| 1115 |
+
self.config.problem_type = "regression"
|
| 1116 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1117 |
+
self.config.problem_type = "single_label_classification"
|
| 1118 |
+
else:
|
| 1119 |
+
self.config.problem_type = "multi_label_classification"
|
| 1120 |
+
|
| 1121 |
+
if self.config.problem_type == "regression":
|
| 1122 |
+
loss_fct = MSELoss()
|
| 1123 |
+
if self.num_labels == 1:
|
| 1124 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1125 |
+
else:
|
| 1126 |
+
loss = loss_fct(logits, labels)
|
| 1127 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1128 |
+
loss_fct = CrossEntropyLoss()
|
| 1129 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1130 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1131 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1132 |
+
loss = loss_fct(logits, labels)
|
| 1133 |
+
|
| 1134 |
+
if not return_dict:
|
| 1135 |
+
output = (logits,) + outputs[2:]
|
| 1136 |
+
return ((loss,) + output) if loss is not None else output
|
| 1137 |
+
|
| 1138 |
+
return SequenceClassifierOutput(
|
| 1139 |
+
loss=loss,
|
| 1140 |
+
logits=logits,
|
| 1141 |
+
hidden_states=outputs.hidden_states,
|
| 1142 |
+
attentions=outputs.attentions,
|
| 1143 |
+
)
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
@auto_docstring
|
| 1147 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForMultipleChoice with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 1148 |
+
class CamembertForMultipleChoice(CamembertPreTrainedModel):
|
| 1149 |
+
def __init__(self, config):
|
| 1150 |
+
super().__init__(config)
|
| 1151 |
+
|
| 1152 |
+
self.roberta = CamembertModel(config)
|
| 1153 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 1154 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 1155 |
+
|
| 1156 |
+
# Initialize weights and apply final processing
|
| 1157 |
+
self.post_init()
|
| 1158 |
+
|
| 1159 |
+
@auto_docstring
|
| 1160 |
+
def forward(
|
| 1161 |
+
self,
|
| 1162 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1163 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1164 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1165 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1166 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1167 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1168 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1169 |
+
output_attentions: Optional[bool] = None,
|
| 1170 |
+
output_hidden_states: Optional[bool] = None,
|
| 1171 |
+
return_dict: Optional[bool] = None,
|
| 1172 |
+
) -> Union[tuple[torch.Tensor], MultipleChoiceModelOutput]:
|
| 1173 |
+
r"""
|
| 1174 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
|
| 1175 |
+
Indices of input sequence tokens in the vocabulary.
|
| 1176 |
+
|
| 1177 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1178 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1179 |
+
|
| 1180 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1181 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
|
| 1182 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
|
| 1183 |
+
|
| 1184 |
+
- 0 corresponds to a *sentence A* token,
|
| 1185 |
+
- 1 corresponds to a *sentence B* token.
|
| 1186 |
+
This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
|
| 1187 |
+
>= 2. All the value in this tensor should be always < type_vocab_size.
|
| 1188 |
+
|
| 1189 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 1190 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1191 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
| 1192 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
| 1193 |
+
`input_ids` above)
|
| 1194 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
|
| 1195 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 1196 |
+
config.max_position_embeddings - 1]`.
|
| 1197 |
+
|
| 1198 |
+
[What are position IDs?](../glossary#position-ids)
|
| 1199 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
|
| 1200 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 1201 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 1202 |
+
model's internal embedding lookup matrix.
|
| 1203 |
+
"""
|
| 1204 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1205 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
| 1206 |
+
|
| 1207 |
+
flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
| 1208 |
+
flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
| 1209 |
+
flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
| 1210 |
+
flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 1211 |
+
flat_inputs_embeds = (
|
| 1212 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
| 1213 |
+
if inputs_embeds is not None
|
| 1214 |
+
else None
|
| 1215 |
+
)
|
| 1216 |
+
|
| 1217 |
+
outputs = self.roberta(
|
| 1218 |
+
flat_input_ids,
|
| 1219 |
+
position_ids=flat_position_ids,
|
| 1220 |
+
token_type_ids=flat_token_type_ids,
|
| 1221 |
+
attention_mask=flat_attention_mask,
|
| 1222 |
+
head_mask=head_mask,
|
| 1223 |
+
inputs_embeds=flat_inputs_embeds,
|
| 1224 |
+
output_attentions=output_attentions,
|
| 1225 |
+
output_hidden_states=output_hidden_states,
|
| 1226 |
+
return_dict=return_dict,
|
| 1227 |
+
)
|
| 1228 |
+
pooled_output = outputs[1]
|
| 1229 |
+
|
| 1230 |
+
pooled_output = self.dropout(pooled_output)
|
| 1231 |
+
logits = self.classifier(pooled_output)
|
| 1232 |
+
reshaped_logits = logits.view(-1, num_choices)
|
| 1233 |
+
|
| 1234 |
+
loss = None
|
| 1235 |
+
if labels is not None:
|
| 1236 |
+
# move labels to correct device to enable model parallelism
|
| 1237 |
+
labels = labels.to(reshaped_logits.device)
|
| 1238 |
+
loss_fct = CrossEntropyLoss()
|
| 1239 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 1240 |
+
|
| 1241 |
+
if not return_dict:
|
| 1242 |
+
output = (reshaped_logits,) + outputs[2:]
|
| 1243 |
+
return ((loss,) + output) if loss is not None else output
|
| 1244 |
+
|
| 1245 |
+
return MultipleChoiceModelOutput(
|
| 1246 |
+
loss=loss,
|
| 1247 |
+
logits=reshaped_logits,
|
| 1248 |
+
hidden_states=outputs.hidden_states,
|
| 1249 |
+
attentions=outputs.attentions,
|
| 1250 |
+
)
|
| 1251 |
+
|
| 1252 |
+
|
| 1253 |
+
@auto_docstring
|
| 1254 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForTokenClassification with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 1255 |
+
class CamembertForTokenClassification(CamembertPreTrainedModel):
|
| 1256 |
+
def __init__(self, config):
|
| 1257 |
+
super().__init__(config)
|
| 1258 |
+
self.num_labels = config.num_labels
|
| 1259 |
+
|
| 1260 |
+
self.roberta = CamembertModel(config, add_pooling_layer=False)
|
| 1261 |
+
classifier_dropout = (
|
| 1262 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1263 |
+
)
|
| 1264 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1265 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1266 |
+
|
| 1267 |
+
# Initialize weights and apply final processing
|
| 1268 |
+
self.post_init()
|
| 1269 |
+
|
| 1270 |
+
@auto_docstring
|
| 1271 |
+
def forward(
|
| 1272 |
+
self,
|
| 1273 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1274 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1275 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1276 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1277 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1278 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1279 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1280 |
+
output_attentions: Optional[bool] = None,
|
| 1281 |
+
output_hidden_states: Optional[bool] = None,
|
| 1282 |
+
return_dict: Optional[bool] = None,
|
| 1283 |
+
) -> Union[tuple[torch.Tensor], TokenClassifierOutput]:
|
| 1284 |
+
r"""
|
| 1285 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1286 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
|
| 1287 |
+
|
| 1288 |
+
- 0 corresponds to a *sentence A* token,
|
| 1289 |
+
- 1 corresponds to a *sentence B* token.
|
| 1290 |
+
This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
|
| 1291 |
+
>= 2. All the value in this tensor should be always < type_vocab_size.
|
| 1292 |
+
|
| 1293 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 1294 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1295 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1296 |
+
"""
|
| 1297 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1298 |
+
|
| 1299 |
+
outputs = self.roberta(
|
| 1300 |
+
input_ids,
|
| 1301 |
+
attention_mask=attention_mask,
|
| 1302 |
+
token_type_ids=token_type_ids,
|
| 1303 |
+
position_ids=position_ids,
|
| 1304 |
+
head_mask=head_mask,
|
| 1305 |
+
inputs_embeds=inputs_embeds,
|
| 1306 |
+
output_attentions=output_attentions,
|
| 1307 |
+
output_hidden_states=output_hidden_states,
|
| 1308 |
+
return_dict=return_dict,
|
| 1309 |
+
)
|
| 1310 |
+
|
| 1311 |
+
sequence_output = outputs[0]
|
| 1312 |
+
|
| 1313 |
+
sequence_output = self.dropout(sequence_output)
|
| 1314 |
+
logits = self.classifier(sequence_output)
|
| 1315 |
+
|
| 1316 |
+
loss = None
|
| 1317 |
+
if labels is not None:
|
| 1318 |
+
# move labels to correct device to enable model parallelism
|
| 1319 |
+
labels = labels.to(logits.device)
|
| 1320 |
+
loss_fct = CrossEntropyLoss()
|
| 1321 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1322 |
+
|
| 1323 |
+
if not return_dict:
|
| 1324 |
+
output = (logits,) + outputs[2:]
|
| 1325 |
+
return ((loss,) + output) if loss is not None else output
|
| 1326 |
+
|
| 1327 |
+
return TokenClassifierOutput(
|
| 1328 |
+
loss=loss,
|
| 1329 |
+
logits=logits,
|
| 1330 |
+
hidden_states=outputs.hidden_states,
|
| 1331 |
+
attentions=outputs.attentions,
|
| 1332 |
+
)
|
| 1333 |
+
|
| 1334 |
+
|
| 1335 |
+
@auto_docstring
|
| 1336 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForQuestionAnswering with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 1337 |
+
class CamembertForQuestionAnswering(CamembertPreTrainedModel):
|
| 1338 |
+
def __init__(self, config):
|
| 1339 |
+
super().__init__(config)
|
| 1340 |
+
self.num_labels = config.num_labels
|
| 1341 |
+
|
| 1342 |
+
self.roberta = CamembertModel(config, add_pooling_layer=False)
|
| 1343 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1344 |
+
|
| 1345 |
+
# Initialize weights and apply final processing
|
| 1346 |
+
self.post_init()
|
| 1347 |
+
|
| 1348 |
+
@auto_docstring
|
| 1349 |
+
def forward(
|
| 1350 |
+
self,
|
| 1351 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1352 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1353 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1354 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1355 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1356 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1357 |
+
start_positions: Optional[torch.LongTensor] = None,
|
| 1358 |
+
end_positions: Optional[torch.LongTensor] = None,
|
| 1359 |
+
output_attentions: Optional[bool] = None,
|
| 1360 |
+
output_hidden_states: Optional[bool] = None,
|
| 1361 |
+
return_dict: Optional[bool] = None,
|
| 1362 |
+
) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]:
|
| 1363 |
+
r"""
|
| 1364 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1365 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
|
| 1366 |
+
|
| 1367 |
+
- 0 corresponds to a *sentence A* token,
|
| 1368 |
+
- 1 corresponds to a *sentence B* token.
|
| 1369 |
+
This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
|
| 1370 |
+
>= 2. All the value in this tensor should be always < type_vocab_size.
|
| 1371 |
+
|
| 1372 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 1373 |
+
"""
|
| 1374 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1375 |
+
|
| 1376 |
+
outputs = self.roberta(
|
| 1377 |
+
input_ids,
|
| 1378 |
+
attention_mask=attention_mask,
|
| 1379 |
+
token_type_ids=token_type_ids,
|
| 1380 |
+
position_ids=position_ids,
|
| 1381 |
+
head_mask=head_mask,
|
| 1382 |
+
inputs_embeds=inputs_embeds,
|
| 1383 |
+
output_attentions=output_attentions,
|
| 1384 |
+
output_hidden_states=output_hidden_states,
|
| 1385 |
+
return_dict=return_dict,
|
| 1386 |
+
)
|
| 1387 |
+
|
| 1388 |
+
sequence_output = outputs[0]
|
| 1389 |
+
|
| 1390 |
+
logits = self.qa_outputs(sequence_output)
|
| 1391 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1392 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1393 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1394 |
+
|
| 1395 |
+
total_loss = None
|
| 1396 |
+
if start_positions is not None and end_positions is not None:
|
| 1397 |
+
# If we are on multi-GPU, split add a dimension
|
| 1398 |
+
if len(start_positions.size()) > 1:
|
| 1399 |
+
start_positions = start_positions.squeeze(-1)
|
| 1400 |
+
if len(end_positions.size()) > 1:
|
| 1401 |
+
end_positions = end_positions.squeeze(-1)
|
| 1402 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1403 |
+
ignored_index = start_logits.size(1)
|
| 1404 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1405 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1406 |
+
|
| 1407 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1408 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1409 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1410 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1411 |
+
|
| 1412 |
+
if not return_dict:
|
| 1413 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1414 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1415 |
+
|
| 1416 |
+
return QuestionAnsweringModelOutput(
|
| 1417 |
+
loss=total_loss,
|
| 1418 |
+
start_logits=start_logits,
|
| 1419 |
+
end_logits=end_logits,
|
| 1420 |
+
hidden_states=outputs.hidden_states,
|
| 1421 |
+
attentions=outputs.attentions,
|
| 1422 |
+
)
|
| 1423 |
+
|
| 1424 |
+
|
| 1425 |
+
@auto_docstring(
|
| 1426 |
+
custom_intro="""
|
| 1427 |
+
CamemBERT Model with a `language modeling` head on top for CLM fine-tuning.
|
| 1428 |
+
"""
|
| 1429 |
+
)
|
| 1430 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM with Roberta->Camembert, ROBERTA->CAMEMBERT, FacebookAI/roberta-base->almanach/camembert-base
|
| 1431 |
+
class CamembertForCausalLM(CamembertPreTrainedModel, GenerationMixin):
|
| 1432 |
+
_tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
|
| 1433 |
+
|
| 1434 |
+
def __init__(self, config):
|
| 1435 |
+
super().__init__(config)
|
| 1436 |
+
|
| 1437 |
+
if not config.is_decoder:
|
| 1438 |
+
logger.warning("If you want to use `CamembertLMHeadModel` as a standalone, add `is_decoder=True.`")
|
| 1439 |
+
|
| 1440 |
+
self.roberta = CamembertModel(config, add_pooling_layer=False)
|
| 1441 |
+
self.lm_head = CamembertLMHead(config)
|
| 1442 |
+
|
| 1443 |
+
# Initialize weights and apply final processing
|
| 1444 |
+
self.post_init()
|
| 1445 |
+
|
| 1446 |
+
def get_output_embeddings(self):
|
| 1447 |
+
return self.lm_head.decoder
|
| 1448 |
+
|
| 1449 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1450 |
+
self.lm_head.decoder = new_embeddings
|
| 1451 |
+
|
| 1452 |
+
@auto_docstring
|
| 1453 |
+
def forward(
|
| 1454 |
+
self,
|
| 1455 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1456 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1457 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1458 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1459 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1460 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1461 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 1462 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 1463 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1464 |
+
past_key_values: Optional[Cache] = None,
|
| 1465 |
+
use_cache: Optional[bool] = None,
|
| 1466 |
+
output_attentions: Optional[bool] = None,
|
| 1467 |
+
output_hidden_states: Optional[bool] = None,
|
| 1468 |
+
return_dict: Optional[bool] = None,
|
| 1469 |
+
**kwargs,
|
| 1470 |
+
) -> Union[tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
|
| 1471 |
+
r"""
|
| 1472 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1473 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
|
| 1474 |
+
|
| 1475 |
+
- 0 corresponds to a *sentence A* token,
|
| 1476 |
+
- 1 corresponds to a *sentence B* token.
|
| 1477 |
+
This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
|
| 1478 |
+
>= 2. All the value in this tensor should be always < type_vocab_size.
|
| 1479 |
+
|
| 1480 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 1481 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1482 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
| 1483 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
| 1484 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1485 |
+
|
| 1486 |
+
Example:
|
| 1487 |
+
|
| 1488 |
+
```python
|
| 1489 |
+
>>> from transformers import AutoTokenizer, CamembertForCausalLM, AutoConfig
|
| 1490 |
+
>>> import torch
|
| 1491 |
+
|
| 1492 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("almanach/camembert-base")
|
| 1493 |
+
>>> config = AutoConfig.from_pretrained("almanach/camembert-base")
|
| 1494 |
+
>>> config.is_decoder = True
|
| 1495 |
+
>>> model = CamembertForCausalLM.from_pretrained("almanach/camembert-base", config=config)
|
| 1496 |
+
|
| 1497 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 1498 |
+
>>> outputs = model(**inputs)
|
| 1499 |
+
|
| 1500 |
+
>>> prediction_logits = outputs.logits
|
| 1501 |
+
```"""
|
| 1502 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1503 |
+
if labels is not None:
|
| 1504 |
+
use_cache = False
|
| 1505 |
+
|
| 1506 |
+
outputs = self.roberta(
|
| 1507 |
+
input_ids,
|
| 1508 |
+
attention_mask=attention_mask,
|
| 1509 |
+
token_type_ids=token_type_ids,
|
| 1510 |
+
position_ids=position_ids,
|
| 1511 |
+
head_mask=head_mask,
|
| 1512 |
+
inputs_embeds=inputs_embeds,
|
| 1513 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1514 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1515 |
+
past_key_values=past_key_values,
|
| 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 |
+
sequence_output = outputs[0]
|
| 1523 |
+
prediction_scores = self.lm_head(sequence_output)
|
| 1524 |
+
|
| 1525 |
+
lm_loss = None
|
| 1526 |
+
if labels is not None:
|
| 1527 |
+
# move labels to correct device to enable model parallelism
|
| 1528 |
+
labels = labels.to(prediction_scores.device)
|
| 1529 |
+
lm_loss = self.loss_function(
|
| 1530 |
+
prediction_scores,
|
| 1531 |
+
labels,
|
| 1532 |
+
vocab_size=self.config.vocab_size,
|
| 1533 |
+
**kwargs,
|
| 1534 |
+
)
|
| 1535 |
+
|
| 1536 |
+
if not return_dict:
|
| 1537 |
+
output = (prediction_scores,) + outputs[2:]
|
| 1538 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
| 1539 |
+
|
| 1540 |
+
return CausalLMOutputWithCrossAttentions(
|
| 1541 |
+
loss=lm_loss,
|
| 1542 |
+
logits=prediction_scores,
|
| 1543 |
+
past_key_values=outputs.past_key_values,
|
| 1544 |
+
hidden_states=outputs.hidden_states,
|
| 1545 |
+
attentions=outputs.attentions,
|
| 1546 |
+
cross_attentions=outputs.cross_attentions,
|
| 1547 |
+
)
|
| 1548 |
+
|
| 1549 |
+
|
| 1550 |
+
# Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
|
| 1551 |
+
def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
|
| 1552 |
+
"""
|
| 1553 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
|
| 1554 |
+
are ignored. This is modified from fairseq's `utils.make_positions`.
|
| 1555 |
+
|
| 1556 |
+
Args:
|
| 1557 |
+
x: torch.Tensor x:
|
| 1558 |
+
|
| 1559 |
+
Returns: torch.Tensor
|
| 1560 |
+
"""
|
| 1561 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
| 1562 |
+
mask = input_ids.ne(padding_idx).int()
|
| 1563 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
| 1564 |
+
return incremental_indices.long() + padding_idx
|
| 1565 |
+
|
| 1566 |
+
|
| 1567 |
+
__all__ = [
|
| 1568 |
+
"CamembertForCausalLM",
|
| 1569 |
+
"CamembertForMaskedLM",
|
| 1570 |
+
"CamembertForMultipleChoice",
|
| 1571 |
+
"CamembertForQuestionAnswering",
|
| 1572 |
+
"CamembertForSequenceClassification",
|
| 1573 |
+
"CamembertForTokenClassification",
|
| 1574 |
+
"CamembertModel",
|
| 1575 |
+
"CamembertPreTrainedModel",
|
| 1576 |
+
]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/camembert/modeling_tf_camembert.py
ADDED
|
@@ -0,0 +1,1800 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""TF 2.0 CamemBERT model."""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import math
|
| 21 |
+
import warnings
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import tensorflow as tf
|
| 25 |
+
|
| 26 |
+
from ...activations_tf import get_tf_activation
|
| 27 |
+
from ...modeling_tf_outputs import (
|
| 28 |
+
TFBaseModelOutputWithPastAndCrossAttentions,
|
| 29 |
+
TFBaseModelOutputWithPoolingAndCrossAttentions,
|
| 30 |
+
TFCausalLMOutputWithCrossAttentions,
|
| 31 |
+
TFMaskedLMOutput,
|
| 32 |
+
TFMultipleChoiceModelOutput,
|
| 33 |
+
TFQuestionAnsweringModelOutput,
|
| 34 |
+
TFSequenceClassifierOutput,
|
| 35 |
+
TFTokenClassifierOutput,
|
| 36 |
+
)
|
| 37 |
+
from ...modeling_tf_utils import (
|
| 38 |
+
TFCausalLanguageModelingLoss,
|
| 39 |
+
TFMaskedLanguageModelingLoss,
|
| 40 |
+
TFModelInputType,
|
| 41 |
+
TFMultipleChoiceLoss,
|
| 42 |
+
TFPreTrainedModel,
|
| 43 |
+
TFQuestionAnsweringLoss,
|
| 44 |
+
TFSequenceClassificationLoss,
|
| 45 |
+
TFTokenClassificationLoss,
|
| 46 |
+
get_initializer,
|
| 47 |
+
keras,
|
| 48 |
+
keras_serializable,
|
| 49 |
+
unpack_inputs,
|
| 50 |
+
)
|
| 51 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
| 52 |
+
from ...utils import (
|
| 53 |
+
add_code_sample_docstrings,
|
| 54 |
+
add_start_docstrings,
|
| 55 |
+
add_start_docstrings_to_model_forward,
|
| 56 |
+
logging,
|
| 57 |
+
)
|
| 58 |
+
from .configuration_camembert import CamembertConfig
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
logger = logging.get_logger(__name__)
|
| 62 |
+
|
| 63 |
+
_CHECKPOINT_FOR_DOC = "almanach/camembert-base"
|
| 64 |
+
_CONFIG_FOR_DOC = "CamembertConfig"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
CAMEMBERT_START_DOCSTRING = r"""
|
| 68 |
+
|
| 69 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 70 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 71 |
+
etc.)
|
| 72 |
+
|
| 73 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 74 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 75 |
+
behavior.
|
| 76 |
+
|
| 77 |
+
<Tip>
|
| 78 |
+
|
| 79 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 80 |
+
|
| 81 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 82 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 83 |
+
|
| 84 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 85 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 86 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 87 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 88 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 89 |
+
positional argument:
|
| 90 |
+
|
| 91 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 92 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 93 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 94 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 95 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 96 |
+
|
| 97 |
+
Note that when creating models and layers with
|
| 98 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 99 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 100 |
+
|
| 101 |
+
</Tip>
|
| 102 |
+
|
| 103 |
+
Parameters:
|
| 104 |
+
config ([`CamembertConfig`]): Model configuration class with all the parameters of the
|
| 105 |
+
model. Initializing with a config file does not load the weights associated with the model, only the
|
| 106 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
CAMEMBERT_INPUTS_DOCSTRING = r"""
|
| 110 |
+
Args:
|
| 111 |
+
input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
|
| 112 |
+
Indices of input sequence tokens in the vocabulary.
|
| 113 |
+
|
| 114 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 115 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 116 |
+
|
| 117 |
+
[What are input IDs?](../glossary#input-ids)
|
| 118 |
+
attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 119 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 120 |
+
|
| 121 |
+
- 1 for tokens that are **not masked**,
|
| 122 |
+
- 0 for tokens that are **masked**.
|
| 123 |
+
|
| 124 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 125 |
+
token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 126 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 127 |
+
1]`:
|
| 128 |
+
|
| 129 |
+
- 0 corresponds to a *sentence A* token,
|
| 130 |
+
- 1 corresponds to a *sentence B* token.
|
| 131 |
+
|
| 132 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 133 |
+
position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 134 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 135 |
+
config.max_position_embeddings - 1]`.
|
| 136 |
+
|
| 137 |
+
[What are position IDs?](../glossary#position-ids)
|
| 138 |
+
head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 139 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 140 |
+
|
| 141 |
+
- 1 indicates the head is **not masked**,
|
| 142 |
+
- 0 indicates the head is **masked**.
|
| 143 |
+
|
| 144 |
+
inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
|
| 145 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 146 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 147 |
+
model's internal embedding lookup matrix.
|
| 148 |
+
output_attentions (`bool`, *optional*):
|
| 149 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 150 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 151 |
+
config will be used instead.
|
| 152 |
+
output_hidden_states (`bool`, *optional*):
|
| 153 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 154 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 155 |
+
used instead.
|
| 156 |
+
return_dict (`bool`, *optional*):
|
| 157 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 158 |
+
eager mode, in graph mode the value will always be set to True.
|
| 159 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 160 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 161 |
+
behaviors between training and evaluation).
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaEmbeddings
|
| 166 |
+
class TFCamembertEmbeddings(keras.layers.Layer):
|
| 167 |
+
"""
|
| 168 |
+
Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
def __init__(self, config, **kwargs):
|
| 172 |
+
super().__init__(**kwargs)
|
| 173 |
+
|
| 174 |
+
self.padding_idx = 1
|
| 175 |
+
self.config = config
|
| 176 |
+
self.hidden_size = config.hidden_size
|
| 177 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 178 |
+
self.initializer_range = config.initializer_range
|
| 179 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 180 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 181 |
+
|
| 182 |
+
def build(self, input_shape=None):
|
| 183 |
+
with tf.name_scope("word_embeddings"):
|
| 184 |
+
self.weight = self.add_weight(
|
| 185 |
+
name="weight",
|
| 186 |
+
shape=[self.config.vocab_size, self.hidden_size],
|
| 187 |
+
initializer=get_initializer(self.initializer_range),
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
with tf.name_scope("token_type_embeddings"):
|
| 191 |
+
self.token_type_embeddings = self.add_weight(
|
| 192 |
+
name="embeddings",
|
| 193 |
+
shape=[self.config.type_vocab_size, self.hidden_size],
|
| 194 |
+
initializer=get_initializer(self.initializer_range),
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
with tf.name_scope("position_embeddings"):
|
| 198 |
+
self.position_embeddings = self.add_weight(
|
| 199 |
+
name="embeddings",
|
| 200 |
+
shape=[self.max_position_embeddings, self.hidden_size],
|
| 201 |
+
initializer=get_initializer(self.initializer_range),
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
if self.built:
|
| 205 |
+
return
|
| 206 |
+
self.built = True
|
| 207 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 208 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 209 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 210 |
+
|
| 211 |
+
def create_position_ids_from_input_ids(self, input_ids, past_key_values_length=0):
|
| 212 |
+
"""
|
| 213 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
|
| 214 |
+
symbols are ignored. This is modified from fairseq's `utils.make_positions`.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
input_ids: tf.Tensor
|
| 218 |
+
Returns: tf.Tensor
|
| 219 |
+
"""
|
| 220 |
+
mask = tf.cast(tf.math.not_equal(input_ids, self.padding_idx), dtype=input_ids.dtype)
|
| 221 |
+
incremental_indices = (tf.math.cumsum(mask, axis=1) + past_key_values_length) * mask
|
| 222 |
+
|
| 223 |
+
return incremental_indices + self.padding_idx
|
| 224 |
+
|
| 225 |
+
def call(
|
| 226 |
+
self,
|
| 227 |
+
input_ids=None,
|
| 228 |
+
position_ids=None,
|
| 229 |
+
token_type_ids=None,
|
| 230 |
+
inputs_embeds=None,
|
| 231 |
+
past_key_values_length=0,
|
| 232 |
+
training=False,
|
| 233 |
+
):
|
| 234 |
+
"""
|
| 235 |
+
Applies embedding based on inputs tensor.
|
| 236 |
+
|
| 237 |
+
Returns:
|
| 238 |
+
final_embeddings (`tf.Tensor`): output embedding tensor.
|
| 239 |
+
"""
|
| 240 |
+
assert not (input_ids is None and inputs_embeds is None)
|
| 241 |
+
|
| 242 |
+
if input_ids is not None:
|
| 243 |
+
check_embeddings_within_bounds(input_ids, self.config.vocab_size)
|
| 244 |
+
inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
|
| 245 |
+
|
| 246 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 247 |
+
|
| 248 |
+
if token_type_ids is None:
|
| 249 |
+
token_type_ids = tf.fill(dims=input_shape, value=0)
|
| 250 |
+
|
| 251 |
+
if position_ids is None:
|
| 252 |
+
if input_ids is not None:
|
| 253 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
| 254 |
+
position_ids = self.create_position_ids_from_input_ids(
|
| 255 |
+
input_ids=input_ids, past_key_values_length=past_key_values_length
|
| 256 |
+
)
|
| 257 |
+
else:
|
| 258 |
+
position_ids = tf.expand_dims(
|
| 259 |
+
tf.range(start=self.padding_idx + 1, limit=input_shape[-1] + self.padding_idx + 1), axis=0
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
|
| 263 |
+
token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
|
| 264 |
+
final_embeddings = inputs_embeds + position_embeds + token_type_embeds
|
| 265 |
+
final_embeddings = self.LayerNorm(inputs=final_embeddings)
|
| 266 |
+
final_embeddings = self.dropout(inputs=final_embeddings, training=training)
|
| 267 |
+
|
| 268 |
+
return final_embeddings
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertPooler with Bert->Camembert
|
| 272 |
+
class TFCamembertPooler(keras.layers.Layer):
|
| 273 |
+
def __init__(self, config: CamembertConfig, **kwargs):
|
| 274 |
+
super().__init__(**kwargs)
|
| 275 |
+
|
| 276 |
+
self.dense = keras.layers.Dense(
|
| 277 |
+
units=config.hidden_size,
|
| 278 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 279 |
+
activation="tanh",
|
| 280 |
+
name="dense",
|
| 281 |
+
)
|
| 282 |
+
self.config = config
|
| 283 |
+
|
| 284 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 285 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 286 |
+
# to the first token.
|
| 287 |
+
first_token_tensor = hidden_states[:, 0]
|
| 288 |
+
pooled_output = self.dense(inputs=first_token_tensor)
|
| 289 |
+
|
| 290 |
+
return pooled_output
|
| 291 |
+
|
| 292 |
+
def build(self, input_shape=None):
|
| 293 |
+
if self.built:
|
| 294 |
+
return
|
| 295 |
+
self.built = True
|
| 296 |
+
if getattr(self, "dense", None) is not None:
|
| 297 |
+
with tf.name_scope(self.dense.name):
|
| 298 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertSelfAttention with Bert->Camembert
|
| 302 |
+
class TFCamembertSelfAttention(keras.layers.Layer):
|
| 303 |
+
def __init__(self, config: CamembertConfig, **kwargs):
|
| 304 |
+
super().__init__(**kwargs)
|
| 305 |
+
|
| 306 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
| 307 |
+
raise ValueError(
|
| 308 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number "
|
| 309 |
+
f"of attention heads ({config.num_attention_heads})"
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
self.num_attention_heads = config.num_attention_heads
|
| 313 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 314 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 315 |
+
self.sqrt_att_head_size = math.sqrt(self.attention_head_size)
|
| 316 |
+
|
| 317 |
+
self.query = keras.layers.Dense(
|
| 318 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
|
| 319 |
+
)
|
| 320 |
+
self.key = keras.layers.Dense(
|
| 321 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
|
| 322 |
+
)
|
| 323 |
+
self.value = keras.layers.Dense(
|
| 324 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
|
| 325 |
+
)
|
| 326 |
+
self.dropout = keras.layers.Dropout(rate=config.attention_probs_dropout_prob)
|
| 327 |
+
|
| 328 |
+
self.is_decoder = config.is_decoder
|
| 329 |
+
self.config = config
|
| 330 |
+
|
| 331 |
+
def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
|
| 332 |
+
# Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
|
| 333 |
+
tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))
|
| 334 |
+
|
| 335 |
+
# Transpose the tensor from [batch_size, seq_length, num_attention_heads, attention_head_size] to [batch_size, num_attention_heads, seq_length, attention_head_size]
|
| 336 |
+
return tf.transpose(tensor, perm=[0, 2, 1, 3])
|
| 337 |
+
|
| 338 |
+
def call(
|
| 339 |
+
self,
|
| 340 |
+
hidden_states: tf.Tensor,
|
| 341 |
+
attention_mask: tf.Tensor,
|
| 342 |
+
head_mask: tf.Tensor,
|
| 343 |
+
encoder_hidden_states: tf.Tensor,
|
| 344 |
+
encoder_attention_mask: tf.Tensor,
|
| 345 |
+
past_key_value: tuple[tf.Tensor],
|
| 346 |
+
output_attentions: bool,
|
| 347 |
+
training: bool = False,
|
| 348 |
+
) -> tuple[tf.Tensor]:
|
| 349 |
+
batch_size = shape_list(hidden_states)[0]
|
| 350 |
+
mixed_query_layer = self.query(inputs=hidden_states)
|
| 351 |
+
|
| 352 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 353 |
+
# and values come from an encoder; the attention mask needs to be
|
| 354 |
+
# such that the encoder's padding tokens are not attended to.
|
| 355 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 356 |
+
|
| 357 |
+
if is_cross_attention and past_key_value is not None:
|
| 358 |
+
# reuse k,v, cross_attentions
|
| 359 |
+
key_layer = past_key_value[0]
|
| 360 |
+
value_layer = past_key_value[1]
|
| 361 |
+
attention_mask = encoder_attention_mask
|
| 362 |
+
elif is_cross_attention:
|
| 363 |
+
key_layer = self.transpose_for_scores(self.key(inputs=encoder_hidden_states), batch_size)
|
| 364 |
+
value_layer = self.transpose_for_scores(self.value(inputs=encoder_hidden_states), batch_size)
|
| 365 |
+
attention_mask = encoder_attention_mask
|
| 366 |
+
elif past_key_value is not None:
|
| 367 |
+
key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
|
| 368 |
+
value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
|
| 369 |
+
key_layer = tf.concat([past_key_value[0], key_layer], axis=2)
|
| 370 |
+
value_layer = tf.concat([past_key_value[1], value_layer], axis=2)
|
| 371 |
+
else:
|
| 372 |
+
key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
|
| 373 |
+
value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
|
| 374 |
+
|
| 375 |
+
query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
|
| 376 |
+
|
| 377 |
+
if self.is_decoder:
|
| 378 |
+
# if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
|
| 379 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 380 |
+
# key/value_states (first "if" case)
|
| 381 |
+
# if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
|
| 382 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 383 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 384 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 385 |
+
past_key_value = (key_layer, value_layer)
|
| 386 |
+
|
| 387 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 388 |
+
# (batch size, num_heads, seq_len_q, seq_len_k)
|
| 389 |
+
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
|
| 390 |
+
dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
|
| 391 |
+
attention_scores = tf.divide(attention_scores, dk)
|
| 392 |
+
|
| 393 |
+
if attention_mask is not None:
|
| 394 |
+
# Apply the attention mask is (precomputed for all layers in TFCamembertModel call() function)
|
| 395 |
+
attention_scores = tf.add(attention_scores, attention_mask)
|
| 396 |
+
|
| 397 |
+
# Normalize the attention scores to probabilities.
|
| 398 |
+
attention_probs = stable_softmax(logits=attention_scores, axis=-1)
|
| 399 |
+
|
| 400 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 401 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 402 |
+
attention_probs = self.dropout(inputs=attention_probs, training=training)
|
| 403 |
+
|
| 404 |
+
# Mask heads if we want to
|
| 405 |
+
if head_mask is not None:
|
| 406 |
+
attention_probs = tf.multiply(attention_probs, head_mask)
|
| 407 |
+
|
| 408 |
+
attention_output = tf.matmul(attention_probs, value_layer)
|
| 409 |
+
attention_output = tf.transpose(attention_output, perm=[0, 2, 1, 3])
|
| 410 |
+
|
| 411 |
+
# (batch_size, seq_len_q, all_head_size)
|
| 412 |
+
attention_output = tf.reshape(tensor=attention_output, shape=(batch_size, -1, self.all_head_size))
|
| 413 |
+
outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
|
| 414 |
+
|
| 415 |
+
if self.is_decoder:
|
| 416 |
+
outputs = outputs + (past_key_value,)
|
| 417 |
+
return outputs
|
| 418 |
+
|
| 419 |
+
def build(self, input_shape=None):
|
| 420 |
+
if self.built:
|
| 421 |
+
return
|
| 422 |
+
self.built = True
|
| 423 |
+
if getattr(self, "query", None) is not None:
|
| 424 |
+
with tf.name_scope(self.query.name):
|
| 425 |
+
self.query.build([None, None, self.config.hidden_size])
|
| 426 |
+
if getattr(self, "key", None) is not None:
|
| 427 |
+
with tf.name_scope(self.key.name):
|
| 428 |
+
self.key.build([None, None, self.config.hidden_size])
|
| 429 |
+
if getattr(self, "value", None) is not None:
|
| 430 |
+
with tf.name_scope(self.value.name):
|
| 431 |
+
self.value.build([None, None, self.config.hidden_size])
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertSelfOutput with Bert->Camembert
|
| 435 |
+
class TFCamembertSelfOutput(keras.layers.Layer):
|
| 436 |
+
def __init__(self, config: CamembertConfig, **kwargs):
|
| 437 |
+
super().__init__(**kwargs)
|
| 438 |
+
|
| 439 |
+
self.dense = keras.layers.Dense(
|
| 440 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 441 |
+
)
|
| 442 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 443 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 444 |
+
self.config = config
|
| 445 |
+
|
| 446 |
+
def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 447 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 448 |
+
hidden_states = self.dropout(inputs=hidden_states, training=training)
|
| 449 |
+
hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
|
| 450 |
+
|
| 451 |
+
return hidden_states
|
| 452 |
+
|
| 453 |
+
def build(self, input_shape=None):
|
| 454 |
+
if self.built:
|
| 455 |
+
return
|
| 456 |
+
self.built = True
|
| 457 |
+
if getattr(self, "dense", None) is not None:
|
| 458 |
+
with tf.name_scope(self.dense.name):
|
| 459 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 460 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 461 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 462 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertAttention with Bert->Camembert
|
| 466 |
+
class TFCamembertAttention(keras.layers.Layer):
|
| 467 |
+
def __init__(self, config: CamembertConfig, **kwargs):
|
| 468 |
+
super().__init__(**kwargs)
|
| 469 |
+
|
| 470 |
+
self.self_attention = TFCamembertSelfAttention(config, name="self")
|
| 471 |
+
self.dense_output = TFCamembertSelfOutput(config, name="output")
|
| 472 |
+
|
| 473 |
+
def prune_heads(self, heads):
|
| 474 |
+
raise NotImplementedError
|
| 475 |
+
|
| 476 |
+
def call(
|
| 477 |
+
self,
|
| 478 |
+
input_tensor: tf.Tensor,
|
| 479 |
+
attention_mask: tf.Tensor,
|
| 480 |
+
head_mask: tf.Tensor,
|
| 481 |
+
encoder_hidden_states: tf.Tensor,
|
| 482 |
+
encoder_attention_mask: tf.Tensor,
|
| 483 |
+
past_key_value: tuple[tf.Tensor],
|
| 484 |
+
output_attentions: bool,
|
| 485 |
+
training: bool = False,
|
| 486 |
+
) -> tuple[tf.Tensor]:
|
| 487 |
+
self_outputs = self.self_attention(
|
| 488 |
+
hidden_states=input_tensor,
|
| 489 |
+
attention_mask=attention_mask,
|
| 490 |
+
head_mask=head_mask,
|
| 491 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 492 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 493 |
+
past_key_value=past_key_value,
|
| 494 |
+
output_attentions=output_attentions,
|
| 495 |
+
training=training,
|
| 496 |
+
)
|
| 497 |
+
attention_output = self.dense_output(
|
| 498 |
+
hidden_states=self_outputs[0], input_tensor=input_tensor, training=training
|
| 499 |
+
)
|
| 500 |
+
# add attentions (possibly with past_key_value) if we output them
|
| 501 |
+
outputs = (attention_output,) + self_outputs[1:]
|
| 502 |
+
|
| 503 |
+
return outputs
|
| 504 |
+
|
| 505 |
+
def build(self, input_shape=None):
|
| 506 |
+
if self.built:
|
| 507 |
+
return
|
| 508 |
+
self.built = True
|
| 509 |
+
if getattr(self, "self_attention", None) is not None:
|
| 510 |
+
with tf.name_scope(self.self_attention.name):
|
| 511 |
+
self.self_attention.build(None)
|
| 512 |
+
if getattr(self, "dense_output", None) is not None:
|
| 513 |
+
with tf.name_scope(self.dense_output.name):
|
| 514 |
+
self.dense_output.build(None)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertIntermediate with Bert->Camembert
|
| 518 |
+
class TFCamembertIntermediate(keras.layers.Layer):
|
| 519 |
+
def __init__(self, config: CamembertConfig, **kwargs):
|
| 520 |
+
super().__init__(**kwargs)
|
| 521 |
+
|
| 522 |
+
self.dense = keras.layers.Dense(
|
| 523 |
+
units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
if isinstance(config.hidden_act, str):
|
| 527 |
+
self.intermediate_act_fn = get_tf_activation(config.hidden_act)
|
| 528 |
+
else:
|
| 529 |
+
self.intermediate_act_fn = config.hidden_act
|
| 530 |
+
self.config = config
|
| 531 |
+
|
| 532 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 533 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 534 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 535 |
+
|
| 536 |
+
return hidden_states
|
| 537 |
+
|
| 538 |
+
def build(self, input_shape=None):
|
| 539 |
+
if self.built:
|
| 540 |
+
return
|
| 541 |
+
self.built = True
|
| 542 |
+
if getattr(self, "dense", None) is not None:
|
| 543 |
+
with tf.name_scope(self.dense.name):
|
| 544 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertOutput with Bert->Camembert
|
| 548 |
+
class TFCamembertOutput(keras.layers.Layer):
|
| 549 |
+
def __init__(self, config: CamembertConfig, **kwargs):
|
| 550 |
+
super().__init__(**kwargs)
|
| 551 |
+
|
| 552 |
+
self.dense = keras.layers.Dense(
|
| 553 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 554 |
+
)
|
| 555 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 556 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 557 |
+
self.config = config
|
| 558 |
+
|
| 559 |
+
def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 560 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 561 |
+
hidden_states = self.dropout(inputs=hidden_states, training=training)
|
| 562 |
+
hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
|
| 563 |
+
|
| 564 |
+
return hidden_states
|
| 565 |
+
|
| 566 |
+
def build(self, input_shape=None):
|
| 567 |
+
if self.built:
|
| 568 |
+
return
|
| 569 |
+
self.built = True
|
| 570 |
+
if getattr(self, "dense", None) is not None:
|
| 571 |
+
with tf.name_scope(self.dense.name):
|
| 572 |
+
self.dense.build([None, None, self.config.intermediate_size])
|
| 573 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 574 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 575 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertLayer with Bert->Camembert
|
| 579 |
+
class TFCamembertLayer(keras.layers.Layer):
|
| 580 |
+
def __init__(self, config: CamembertConfig, **kwargs):
|
| 581 |
+
super().__init__(**kwargs)
|
| 582 |
+
|
| 583 |
+
self.attention = TFCamembertAttention(config, name="attention")
|
| 584 |
+
self.is_decoder = config.is_decoder
|
| 585 |
+
self.add_cross_attention = config.add_cross_attention
|
| 586 |
+
if self.add_cross_attention:
|
| 587 |
+
if not self.is_decoder:
|
| 588 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 589 |
+
self.crossattention = TFCamembertAttention(config, name="crossattention")
|
| 590 |
+
self.intermediate = TFCamembertIntermediate(config, name="intermediate")
|
| 591 |
+
self.bert_output = TFCamembertOutput(config, name="output")
|
| 592 |
+
|
| 593 |
+
def call(
|
| 594 |
+
self,
|
| 595 |
+
hidden_states: tf.Tensor,
|
| 596 |
+
attention_mask: tf.Tensor,
|
| 597 |
+
head_mask: tf.Tensor,
|
| 598 |
+
encoder_hidden_states: tf.Tensor | None,
|
| 599 |
+
encoder_attention_mask: tf.Tensor | None,
|
| 600 |
+
past_key_value: tuple[tf.Tensor] | None,
|
| 601 |
+
output_attentions: bool,
|
| 602 |
+
training: bool = False,
|
| 603 |
+
) -> tuple[tf.Tensor]:
|
| 604 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 605 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 606 |
+
self_attention_outputs = self.attention(
|
| 607 |
+
input_tensor=hidden_states,
|
| 608 |
+
attention_mask=attention_mask,
|
| 609 |
+
head_mask=head_mask,
|
| 610 |
+
encoder_hidden_states=None,
|
| 611 |
+
encoder_attention_mask=None,
|
| 612 |
+
past_key_value=self_attn_past_key_value,
|
| 613 |
+
output_attentions=output_attentions,
|
| 614 |
+
training=training,
|
| 615 |
+
)
|
| 616 |
+
attention_output = self_attention_outputs[0]
|
| 617 |
+
|
| 618 |
+
# if decoder, the last output is tuple of self-attn cache
|
| 619 |
+
if self.is_decoder:
|
| 620 |
+
outputs = self_attention_outputs[1:-1]
|
| 621 |
+
present_key_value = self_attention_outputs[-1]
|
| 622 |
+
else:
|
| 623 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 624 |
+
|
| 625 |
+
cross_attn_present_key_value = None
|
| 626 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 627 |
+
if not hasattr(self, "crossattention"):
|
| 628 |
+
raise ValueError(
|
| 629 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 630 |
+
" by setting `config.add_cross_attention=True`"
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
| 634 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 635 |
+
cross_attention_outputs = self.crossattention(
|
| 636 |
+
input_tensor=attention_output,
|
| 637 |
+
attention_mask=attention_mask,
|
| 638 |
+
head_mask=head_mask,
|
| 639 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 640 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 641 |
+
past_key_value=cross_attn_past_key_value,
|
| 642 |
+
output_attentions=output_attentions,
|
| 643 |
+
training=training,
|
| 644 |
+
)
|
| 645 |
+
attention_output = cross_attention_outputs[0]
|
| 646 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 647 |
+
|
| 648 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
| 649 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
| 650 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 651 |
+
|
| 652 |
+
intermediate_output = self.intermediate(hidden_states=attention_output)
|
| 653 |
+
layer_output = self.bert_output(
|
| 654 |
+
hidden_states=intermediate_output, input_tensor=attention_output, training=training
|
| 655 |
+
)
|
| 656 |
+
outputs = (layer_output,) + outputs # add attentions if we output them
|
| 657 |
+
|
| 658 |
+
# if decoder, return the attn key/values as the last output
|
| 659 |
+
if self.is_decoder:
|
| 660 |
+
outputs = outputs + (present_key_value,)
|
| 661 |
+
|
| 662 |
+
return outputs
|
| 663 |
+
|
| 664 |
+
def build(self, input_shape=None):
|
| 665 |
+
if self.built:
|
| 666 |
+
return
|
| 667 |
+
self.built = True
|
| 668 |
+
if getattr(self, "attention", None) is not None:
|
| 669 |
+
with tf.name_scope(self.attention.name):
|
| 670 |
+
self.attention.build(None)
|
| 671 |
+
if getattr(self, "intermediate", None) is not None:
|
| 672 |
+
with tf.name_scope(self.intermediate.name):
|
| 673 |
+
self.intermediate.build(None)
|
| 674 |
+
if getattr(self, "bert_output", None) is not None:
|
| 675 |
+
with tf.name_scope(self.bert_output.name):
|
| 676 |
+
self.bert_output.build(None)
|
| 677 |
+
if getattr(self, "crossattention", None) is not None:
|
| 678 |
+
with tf.name_scope(self.crossattention.name):
|
| 679 |
+
self.crossattention.build(None)
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertEncoder with Bert->Camembert
|
| 683 |
+
class TFCamembertEncoder(keras.layers.Layer):
|
| 684 |
+
def __init__(self, config: CamembertConfig, **kwargs):
|
| 685 |
+
super().__init__(**kwargs)
|
| 686 |
+
self.config = config
|
| 687 |
+
self.layer = [TFCamembertLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
|
| 688 |
+
|
| 689 |
+
def call(
|
| 690 |
+
self,
|
| 691 |
+
hidden_states: tf.Tensor,
|
| 692 |
+
attention_mask: tf.Tensor,
|
| 693 |
+
head_mask: tf.Tensor,
|
| 694 |
+
encoder_hidden_states: tf.Tensor | None,
|
| 695 |
+
encoder_attention_mask: tf.Tensor | None,
|
| 696 |
+
past_key_values: tuple[tuple[tf.Tensor]] | None,
|
| 697 |
+
use_cache: bool | None,
|
| 698 |
+
output_attentions: bool,
|
| 699 |
+
output_hidden_states: bool,
|
| 700 |
+
return_dict: bool,
|
| 701 |
+
training: bool = False,
|
| 702 |
+
) -> TFBaseModelOutputWithPastAndCrossAttentions | tuple[tf.Tensor]:
|
| 703 |
+
all_hidden_states = () if output_hidden_states else None
|
| 704 |
+
all_attentions = () if output_attentions else None
|
| 705 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 706 |
+
|
| 707 |
+
next_decoder_cache = () if use_cache else None
|
| 708 |
+
for i, layer_module in enumerate(self.layer):
|
| 709 |
+
if output_hidden_states:
|
| 710 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 711 |
+
|
| 712 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 713 |
+
|
| 714 |
+
layer_outputs = layer_module(
|
| 715 |
+
hidden_states=hidden_states,
|
| 716 |
+
attention_mask=attention_mask,
|
| 717 |
+
head_mask=head_mask[i],
|
| 718 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 719 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 720 |
+
past_key_value=past_key_value,
|
| 721 |
+
output_attentions=output_attentions,
|
| 722 |
+
training=training,
|
| 723 |
+
)
|
| 724 |
+
hidden_states = layer_outputs[0]
|
| 725 |
+
|
| 726 |
+
if use_cache:
|
| 727 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 728 |
+
|
| 729 |
+
if output_attentions:
|
| 730 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 731 |
+
if self.config.add_cross_attention and encoder_hidden_states is not None:
|
| 732 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 733 |
+
|
| 734 |
+
# Add last layer
|
| 735 |
+
if output_hidden_states:
|
| 736 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 737 |
+
|
| 738 |
+
if not return_dict:
|
| 739 |
+
return tuple(
|
| 740 |
+
v for v in [hidden_states, all_hidden_states, all_attentions, all_cross_attentions] if v is not None
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
return TFBaseModelOutputWithPastAndCrossAttentions(
|
| 744 |
+
last_hidden_state=hidden_states,
|
| 745 |
+
past_key_values=next_decoder_cache,
|
| 746 |
+
hidden_states=all_hidden_states,
|
| 747 |
+
attentions=all_attentions,
|
| 748 |
+
cross_attentions=all_cross_attentions,
|
| 749 |
+
)
|
| 750 |
+
|
| 751 |
+
def build(self, input_shape=None):
|
| 752 |
+
if self.built:
|
| 753 |
+
return
|
| 754 |
+
self.built = True
|
| 755 |
+
if getattr(self, "layer", None) is not None:
|
| 756 |
+
for layer in self.layer:
|
| 757 |
+
with tf.name_scope(layer.name):
|
| 758 |
+
layer.build(None)
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
@keras_serializable
|
| 762 |
+
# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaMainLayer with Roberta->Camembert
|
| 763 |
+
class TFCamembertMainLayer(keras.layers.Layer):
|
| 764 |
+
config_class = CamembertConfig
|
| 765 |
+
|
| 766 |
+
def __init__(self, config, add_pooling_layer=True, **kwargs):
|
| 767 |
+
super().__init__(**kwargs)
|
| 768 |
+
|
| 769 |
+
self.config = config
|
| 770 |
+
self.is_decoder = config.is_decoder
|
| 771 |
+
|
| 772 |
+
self.num_hidden_layers = config.num_hidden_layers
|
| 773 |
+
self.initializer_range = config.initializer_range
|
| 774 |
+
self.output_attentions = config.output_attentions
|
| 775 |
+
self.output_hidden_states = config.output_hidden_states
|
| 776 |
+
self.return_dict = config.use_return_dict
|
| 777 |
+
self.encoder = TFCamembertEncoder(config, name="encoder")
|
| 778 |
+
self.pooler = TFCamembertPooler(config, name="pooler") if add_pooling_layer else None
|
| 779 |
+
# The embeddings must be the last declaration in order to follow the weights order
|
| 780 |
+
self.embeddings = TFCamembertEmbeddings(config, name="embeddings")
|
| 781 |
+
|
| 782 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer.get_input_embeddings
|
| 783 |
+
def get_input_embeddings(self) -> keras.layers.Layer:
|
| 784 |
+
return self.embeddings
|
| 785 |
+
|
| 786 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer.set_input_embeddings
|
| 787 |
+
def set_input_embeddings(self, value: tf.Variable):
|
| 788 |
+
self.embeddings.weight = value
|
| 789 |
+
self.embeddings.vocab_size = shape_list(value)[0]
|
| 790 |
+
|
| 791 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer._prune_heads
|
| 792 |
+
def _prune_heads(self, heads_to_prune):
|
| 793 |
+
"""
|
| 794 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 795 |
+
class PreTrainedModel
|
| 796 |
+
"""
|
| 797 |
+
raise NotImplementedError
|
| 798 |
+
|
| 799 |
+
@unpack_inputs
|
| 800 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer.call
|
| 801 |
+
def call(
|
| 802 |
+
self,
|
| 803 |
+
input_ids: TFModelInputType | None = None,
|
| 804 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 805 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 806 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 807 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 808 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 809 |
+
encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
|
| 810 |
+
encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 811 |
+
past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
|
| 812 |
+
use_cache: bool | None = None,
|
| 813 |
+
output_attentions: bool | None = None,
|
| 814 |
+
output_hidden_states: bool | None = None,
|
| 815 |
+
return_dict: bool | None = None,
|
| 816 |
+
training: bool = False,
|
| 817 |
+
) -> TFBaseModelOutputWithPoolingAndCrossAttentions | tuple[tf.Tensor]:
|
| 818 |
+
if not self.config.is_decoder:
|
| 819 |
+
use_cache = False
|
| 820 |
+
|
| 821 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 822 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 823 |
+
elif input_ids is not None:
|
| 824 |
+
input_shape = shape_list(input_ids)
|
| 825 |
+
elif inputs_embeds is not None:
|
| 826 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 827 |
+
else:
|
| 828 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 829 |
+
|
| 830 |
+
batch_size, seq_length = input_shape
|
| 831 |
+
|
| 832 |
+
if past_key_values is None:
|
| 833 |
+
past_key_values_length = 0
|
| 834 |
+
past_key_values = [None] * len(self.encoder.layer)
|
| 835 |
+
else:
|
| 836 |
+
past_key_values_length = shape_list(past_key_values[0][0])[-2]
|
| 837 |
+
|
| 838 |
+
if attention_mask is None:
|
| 839 |
+
attention_mask = tf.fill(dims=(batch_size, seq_length + past_key_values_length), value=1)
|
| 840 |
+
|
| 841 |
+
if token_type_ids is None:
|
| 842 |
+
token_type_ids = tf.fill(dims=input_shape, value=0)
|
| 843 |
+
|
| 844 |
+
embedding_output = self.embeddings(
|
| 845 |
+
input_ids=input_ids,
|
| 846 |
+
position_ids=position_ids,
|
| 847 |
+
token_type_ids=token_type_ids,
|
| 848 |
+
inputs_embeds=inputs_embeds,
|
| 849 |
+
past_key_values_length=past_key_values_length,
|
| 850 |
+
training=training,
|
| 851 |
+
)
|
| 852 |
+
|
| 853 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
| 854 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
| 855 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
| 856 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
| 857 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
| 858 |
+
attention_mask_shape = shape_list(attention_mask)
|
| 859 |
+
|
| 860 |
+
mask_seq_length = seq_length + past_key_values_length
|
| 861 |
+
# Copied from `modeling_tf_t5.py`
|
| 862 |
+
# Provided a padding mask of dimensions [batch_size, mask_seq_length]
|
| 863 |
+
# - if the model is a decoder, apply a causal mask in addition to the padding mask
|
| 864 |
+
# - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
|
| 865 |
+
if self.is_decoder:
|
| 866 |
+
seq_ids = tf.range(mask_seq_length)
|
| 867 |
+
causal_mask = tf.less_equal(
|
| 868 |
+
tf.tile(seq_ids[None, None, :], (batch_size, mask_seq_length, 1)),
|
| 869 |
+
seq_ids[None, :, None],
|
| 870 |
+
)
|
| 871 |
+
causal_mask = tf.cast(causal_mask, dtype=attention_mask.dtype)
|
| 872 |
+
extended_attention_mask = causal_mask * attention_mask[:, None, :]
|
| 873 |
+
attention_mask_shape = shape_list(extended_attention_mask)
|
| 874 |
+
extended_attention_mask = tf.reshape(
|
| 875 |
+
extended_attention_mask, (attention_mask_shape[0], 1, attention_mask_shape[1], attention_mask_shape[2])
|
| 876 |
+
)
|
| 877 |
+
if past_key_values[0] is not None:
|
| 878 |
+
# attention_mask needs to be sliced to the shape `[batch_size, 1, from_seq_length - cached_seq_length, to_seq_length]
|
| 879 |
+
extended_attention_mask = extended_attention_mask[:, :, -seq_length:, :]
|
| 880 |
+
else:
|
| 881 |
+
extended_attention_mask = tf.reshape(
|
| 882 |
+
attention_mask, (attention_mask_shape[0], 1, 1, attention_mask_shape[1])
|
| 883 |
+
)
|
| 884 |
+
|
| 885 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 886 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 887 |
+
# positions we want to attend and -10000.0 for masked positions.
|
| 888 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 889 |
+
# effectively the same as removing these entirely.
|
| 890 |
+
extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)
|
| 891 |
+
one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
|
| 892 |
+
ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
|
| 893 |
+
extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
|
| 894 |
+
|
| 895 |
+
# Copied from `modeling_tf_t5.py` with -1e9 -> -10000
|
| 896 |
+
if self.is_decoder and encoder_attention_mask is not None:
|
| 897 |
+
# If a 2D ou 3D attention mask is provided for the cross-attention
|
| 898 |
+
# we need to make broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
|
| 899 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 900 |
+
encoder_attention_mask = tf.cast(encoder_attention_mask, dtype=extended_attention_mask.dtype)
|
| 901 |
+
num_dims_encoder_attention_mask = len(shape_list(encoder_attention_mask))
|
| 902 |
+
if num_dims_encoder_attention_mask == 3:
|
| 903 |
+
encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :]
|
| 904 |
+
if num_dims_encoder_attention_mask == 2:
|
| 905 |
+
encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :]
|
| 906 |
+
|
| 907 |
+
# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
|
| 908 |
+
# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow/transformer/transformer_layers.py#L270
|
| 909 |
+
# encoder_extended_attention_mask = tf.math.equal(encoder_extended_attention_mask,
|
| 910 |
+
# tf.transpose(encoder_extended_attention_mask, perm=(-1, -2)))
|
| 911 |
+
|
| 912 |
+
encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * -10000.0
|
| 913 |
+
else:
|
| 914 |
+
encoder_extended_attention_mask = None
|
| 915 |
+
|
| 916 |
+
# Prepare head mask if needed
|
| 917 |
+
# 1.0 in head_mask indicate we keep the head
|
| 918 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 919 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 920 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 921 |
+
if head_mask is not None:
|
| 922 |
+
raise NotImplementedError
|
| 923 |
+
else:
|
| 924 |
+
head_mask = [None] * self.config.num_hidden_layers
|
| 925 |
+
|
| 926 |
+
encoder_outputs = self.encoder(
|
| 927 |
+
hidden_states=embedding_output,
|
| 928 |
+
attention_mask=extended_attention_mask,
|
| 929 |
+
head_mask=head_mask,
|
| 930 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 931 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 932 |
+
past_key_values=past_key_values,
|
| 933 |
+
use_cache=use_cache,
|
| 934 |
+
output_attentions=output_attentions,
|
| 935 |
+
output_hidden_states=output_hidden_states,
|
| 936 |
+
return_dict=return_dict,
|
| 937 |
+
training=training,
|
| 938 |
+
)
|
| 939 |
+
|
| 940 |
+
sequence_output = encoder_outputs[0]
|
| 941 |
+
pooled_output = self.pooler(hidden_states=sequence_output) if self.pooler is not None else None
|
| 942 |
+
|
| 943 |
+
if not return_dict:
|
| 944 |
+
return (
|
| 945 |
+
sequence_output,
|
| 946 |
+
pooled_output,
|
| 947 |
+
) + encoder_outputs[1:]
|
| 948 |
+
|
| 949 |
+
return TFBaseModelOutputWithPoolingAndCrossAttentions(
|
| 950 |
+
last_hidden_state=sequence_output,
|
| 951 |
+
pooler_output=pooled_output,
|
| 952 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 953 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 954 |
+
attentions=encoder_outputs.attentions,
|
| 955 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 956 |
+
)
|
| 957 |
+
|
| 958 |
+
def build(self, input_shape=None):
|
| 959 |
+
if self.built:
|
| 960 |
+
return
|
| 961 |
+
self.built = True
|
| 962 |
+
if getattr(self, "encoder", None) is not None:
|
| 963 |
+
with tf.name_scope(self.encoder.name):
|
| 964 |
+
self.encoder.build(None)
|
| 965 |
+
if getattr(self, "pooler", None) is not None:
|
| 966 |
+
with tf.name_scope(self.pooler.name):
|
| 967 |
+
self.pooler.build(None)
|
| 968 |
+
if getattr(self, "embeddings", None) is not None:
|
| 969 |
+
with tf.name_scope(self.embeddings.name):
|
| 970 |
+
self.embeddings.build(None)
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
class TFCamembertPreTrainedModel(TFPreTrainedModel):
|
| 974 |
+
"""
|
| 975 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 976 |
+
models.
|
| 977 |
+
"""
|
| 978 |
+
|
| 979 |
+
config_class = CamembertConfig
|
| 980 |
+
base_model_prefix = "roberta"
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
@add_start_docstrings(
|
| 984 |
+
"The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.",
|
| 985 |
+
CAMEMBERT_START_DOCSTRING,
|
| 986 |
+
)
|
| 987 |
+
# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaModel with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 988 |
+
class TFCamembertModel(TFCamembertPreTrainedModel):
|
| 989 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 990 |
+
super().__init__(config, *inputs, **kwargs)
|
| 991 |
+
self.roberta = TFCamembertMainLayer(config, name="roberta")
|
| 992 |
+
|
| 993 |
+
@unpack_inputs
|
| 994 |
+
@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 995 |
+
@add_code_sample_docstrings(
|
| 996 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 997 |
+
output_type=TFBaseModelOutputWithPoolingAndCrossAttentions,
|
| 998 |
+
config_class=_CONFIG_FOR_DOC,
|
| 999 |
+
)
|
| 1000 |
+
def call(
|
| 1001 |
+
self,
|
| 1002 |
+
input_ids: TFModelInputType | None = None,
|
| 1003 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1004 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1005 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1006 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1007 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1008 |
+
encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
|
| 1009 |
+
encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1010 |
+
past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
|
| 1011 |
+
use_cache: bool | None = None,
|
| 1012 |
+
output_attentions: bool | None = None,
|
| 1013 |
+
output_hidden_states: bool | None = None,
|
| 1014 |
+
return_dict: bool | None = None,
|
| 1015 |
+
training: bool | None = False,
|
| 1016 |
+
) -> tuple | TFBaseModelOutputWithPoolingAndCrossAttentions:
|
| 1017 |
+
r"""
|
| 1018 |
+
encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1019 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 1020 |
+
the model is configured as a decoder.
|
| 1021 |
+
encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1022 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 1023 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1024 |
+
|
| 1025 |
+
- 1 for tokens that are **not masked**,
|
| 1026 |
+
- 0 for tokens that are **masked**.
|
| 1027 |
+
|
| 1028 |
+
past_key_values (`tuple[tuple[tf.Tensor]]` of length `config.n_layers`)
|
| 1029 |
+
contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 1030 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 1031 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 1032 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1033 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 1034 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 1035 |
+
`past_key_values`). Set to `False` during training, `True` during generation
|
| 1036 |
+
"""
|
| 1037 |
+
outputs = self.roberta(
|
| 1038 |
+
input_ids=input_ids,
|
| 1039 |
+
attention_mask=attention_mask,
|
| 1040 |
+
token_type_ids=token_type_ids,
|
| 1041 |
+
position_ids=position_ids,
|
| 1042 |
+
head_mask=head_mask,
|
| 1043 |
+
inputs_embeds=inputs_embeds,
|
| 1044 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1045 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1046 |
+
past_key_values=past_key_values,
|
| 1047 |
+
use_cache=use_cache,
|
| 1048 |
+
output_attentions=output_attentions,
|
| 1049 |
+
output_hidden_states=output_hidden_states,
|
| 1050 |
+
return_dict=return_dict,
|
| 1051 |
+
training=training,
|
| 1052 |
+
)
|
| 1053 |
+
|
| 1054 |
+
return outputs
|
| 1055 |
+
|
| 1056 |
+
def build(self, input_shape=None):
|
| 1057 |
+
if self.built:
|
| 1058 |
+
return
|
| 1059 |
+
self.built = True
|
| 1060 |
+
if getattr(self, "roberta", None) is not None:
|
| 1061 |
+
with tf.name_scope(self.roberta.name):
|
| 1062 |
+
self.roberta.build(None)
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaLMHead with Roberta->Camembert
|
| 1066 |
+
class TFCamembertLMHead(keras.layers.Layer):
|
| 1067 |
+
"""Camembert Head for masked language modeling."""
|
| 1068 |
+
|
| 1069 |
+
def __init__(self, config, input_embeddings, **kwargs):
|
| 1070 |
+
super().__init__(**kwargs)
|
| 1071 |
+
|
| 1072 |
+
self.config = config
|
| 1073 |
+
self.hidden_size = config.hidden_size
|
| 1074 |
+
self.dense = keras.layers.Dense(
|
| 1075 |
+
config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 1076 |
+
)
|
| 1077 |
+
self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
|
| 1078 |
+
self.act = get_tf_activation("gelu")
|
| 1079 |
+
|
| 1080 |
+
# The output weights are the same as the input embeddings, but there is
|
| 1081 |
+
# an output-only bias for each token.
|
| 1082 |
+
self.decoder = input_embeddings
|
| 1083 |
+
|
| 1084 |
+
def build(self, input_shape=None):
|
| 1085 |
+
self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
|
| 1086 |
+
|
| 1087 |
+
if self.built:
|
| 1088 |
+
return
|
| 1089 |
+
self.built = True
|
| 1090 |
+
if getattr(self, "dense", None) is not None:
|
| 1091 |
+
with tf.name_scope(self.dense.name):
|
| 1092 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 1093 |
+
if getattr(self, "layer_norm", None) is not None:
|
| 1094 |
+
with tf.name_scope(self.layer_norm.name):
|
| 1095 |
+
self.layer_norm.build([None, None, self.config.hidden_size])
|
| 1096 |
+
|
| 1097 |
+
def get_output_embeddings(self):
|
| 1098 |
+
return self.decoder
|
| 1099 |
+
|
| 1100 |
+
def set_output_embeddings(self, value):
|
| 1101 |
+
self.decoder.weight = value
|
| 1102 |
+
self.decoder.vocab_size = shape_list(value)[0]
|
| 1103 |
+
|
| 1104 |
+
def get_bias(self):
|
| 1105 |
+
return {"bias": self.bias}
|
| 1106 |
+
|
| 1107 |
+
def set_bias(self, value):
|
| 1108 |
+
self.bias = value["bias"]
|
| 1109 |
+
self.config.vocab_size = shape_list(value["bias"])[0]
|
| 1110 |
+
|
| 1111 |
+
def call(self, hidden_states):
|
| 1112 |
+
hidden_states = self.dense(hidden_states)
|
| 1113 |
+
hidden_states = self.act(hidden_states)
|
| 1114 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 1115 |
+
|
| 1116 |
+
# project back to size of vocabulary with bias
|
| 1117 |
+
seq_length = shape_list(tensor=hidden_states)[1]
|
| 1118 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.hidden_size])
|
| 1119 |
+
hidden_states = tf.matmul(a=hidden_states, b=self.decoder.weight, transpose_b=True)
|
| 1120 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
|
| 1121 |
+
hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
|
| 1122 |
+
|
| 1123 |
+
return hidden_states
|
| 1124 |
+
|
| 1125 |
+
|
| 1126 |
+
@add_start_docstrings(
|
| 1127 |
+
"""CamemBERT Model with a `language modeling` head on top.""",
|
| 1128 |
+
CAMEMBERT_START_DOCSTRING,
|
| 1129 |
+
)
|
| 1130 |
+
# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForMaskedLM with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 1131 |
+
class TFCamembertForMaskedLM(TFCamembertPreTrainedModel, TFMaskedLanguageModelingLoss):
|
| 1132 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1133 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head.decoder.weight"]
|
| 1134 |
+
|
| 1135 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1136 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1137 |
+
|
| 1138 |
+
self.roberta = TFCamembertMainLayer(config, add_pooling_layer=False, name="roberta")
|
| 1139 |
+
self.lm_head = TFCamembertLMHead(config, self.roberta.embeddings, name="lm_head")
|
| 1140 |
+
|
| 1141 |
+
def get_lm_head(self):
|
| 1142 |
+
return self.lm_head
|
| 1143 |
+
|
| 1144 |
+
def get_prefix_bias_name(self):
|
| 1145 |
+
warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
|
| 1146 |
+
return self.name + "/" + self.lm_head.name
|
| 1147 |
+
|
| 1148 |
+
@unpack_inputs
|
| 1149 |
+
@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1150 |
+
@add_code_sample_docstrings(
|
| 1151 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1152 |
+
output_type=TFMaskedLMOutput,
|
| 1153 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1154 |
+
mask="<mask>",
|
| 1155 |
+
expected_output="' Paris'",
|
| 1156 |
+
expected_loss=0.1,
|
| 1157 |
+
)
|
| 1158 |
+
def call(
|
| 1159 |
+
self,
|
| 1160 |
+
input_ids: TFModelInputType | None = None,
|
| 1161 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1162 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1163 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1164 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1165 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1166 |
+
output_attentions: bool | None = None,
|
| 1167 |
+
output_hidden_states: bool | None = None,
|
| 1168 |
+
return_dict: bool | None = None,
|
| 1169 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1170 |
+
training: bool | None = False,
|
| 1171 |
+
) -> TFMaskedLMOutput | tuple[tf.Tensor]:
|
| 1172 |
+
r"""
|
| 1173 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1174 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 1175 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 1176 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1177 |
+
"""
|
| 1178 |
+
outputs = self.roberta(
|
| 1179 |
+
input_ids,
|
| 1180 |
+
attention_mask=attention_mask,
|
| 1181 |
+
token_type_ids=token_type_ids,
|
| 1182 |
+
position_ids=position_ids,
|
| 1183 |
+
head_mask=head_mask,
|
| 1184 |
+
inputs_embeds=inputs_embeds,
|
| 1185 |
+
output_attentions=output_attentions,
|
| 1186 |
+
output_hidden_states=output_hidden_states,
|
| 1187 |
+
return_dict=return_dict,
|
| 1188 |
+
training=training,
|
| 1189 |
+
)
|
| 1190 |
+
|
| 1191 |
+
sequence_output = outputs[0]
|
| 1192 |
+
prediction_scores = self.lm_head(sequence_output)
|
| 1193 |
+
|
| 1194 |
+
loss = None if labels is None else self.hf_compute_loss(labels, prediction_scores)
|
| 1195 |
+
|
| 1196 |
+
if not return_dict:
|
| 1197 |
+
output = (prediction_scores,) + outputs[2:]
|
| 1198 |
+
return ((loss,) + output) if loss is not None else output
|
| 1199 |
+
|
| 1200 |
+
return TFMaskedLMOutput(
|
| 1201 |
+
loss=loss,
|
| 1202 |
+
logits=prediction_scores,
|
| 1203 |
+
hidden_states=outputs.hidden_states,
|
| 1204 |
+
attentions=outputs.attentions,
|
| 1205 |
+
)
|
| 1206 |
+
|
| 1207 |
+
def build(self, input_shape=None):
|
| 1208 |
+
if self.built:
|
| 1209 |
+
return
|
| 1210 |
+
self.built = True
|
| 1211 |
+
if getattr(self, "roberta", None) is not None:
|
| 1212 |
+
with tf.name_scope(self.roberta.name):
|
| 1213 |
+
self.roberta.build(None)
|
| 1214 |
+
if getattr(self, "lm_head", None) is not None:
|
| 1215 |
+
with tf.name_scope(self.lm_head.name):
|
| 1216 |
+
self.lm_head.build(None)
|
| 1217 |
+
|
| 1218 |
+
|
| 1219 |
+
# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaClassificationHead
|
| 1220 |
+
class TFCamembertClassificationHead(keras.layers.Layer):
|
| 1221 |
+
"""Head for sentence-level classification tasks."""
|
| 1222 |
+
|
| 1223 |
+
def __init__(self, config, **kwargs):
|
| 1224 |
+
super().__init__(**kwargs)
|
| 1225 |
+
self.dense = keras.layers.Dense(
|
| 1226 |
+
config.hidden_size,
|
| 1227 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 1228 |
+
activation="tanh",
|
| 1229 |
+
name="dense",
|
| 1230 |
+
)
|
| 1231 |
+
classifier_dropout = (
|
| 1232 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1233 |
+
)
|
| 1234 |
+
self.dropout = keras.layers.Dropout(classifier_dropout)
|
| 1235 |
+
self.out_proj = keras.layers.Dense(
|
| 1236 |
+
config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="out_proj"
|
| 1237 |
+
)
|
| 1238 |
+
self.config = config
|
| 1239 |
+
|
| 1240 |
+
def call(self, features, training=False):
|
| 1241 |
+
x = features[:, 0, :] # take <s> token (equiv. to [CLS])
|
| 1242 |
+
x = self.dropout(x, training=training)
|
| 1243 |
+
x = self.dense(x)
|
| 1244 |
+
x = self.dropout(x, training=training)
|
| 1245 |
+
x = self.out_proj(x)
|
| 1246 |
+
return x
|
| 1247 |
+
|
| 1248 |
+
def build(self, input_shape=None):
|
| 1249 |
+
if self.built:
|
| 1250 |
+
return
|
| 1251 |
+
self.built = True
|
| 1252 |
+
if getattr(self, "dense", None) is not None:
|
| 1253 |
+
with tf.name_scope(self.dense.name):
|
| 1254 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 1255 |
+
if getattr(self, "out_proj", None) is not None:
|
| 1256 |
+
with tf.name_scope(self.out_proj.name):
|
| 1257 |
+
self.out_proj.build([None, None, self.config.hidden_size])
|
| 1258 |
+
|
| 1259 |
+
|
| 1260 |
+
@add_start_docstrings(
|
| 1261 |
+
"""
|
| 1262 |
+
CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the
|
| 1263 |
+
pooled output) e.g. for GLUE tasks.
|
| 1264 |
+
""",
|
| 1265 |
+
CAMEMBERT_START_DOCSTRING,
|
| 1266 |
+
)
|
| 1267 |
+
# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForSequenceClassification with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 1268 |
+
class TFCamembertForSequenceClassification(TFCamembertPreTrainedModel, TFSequenceClassificationLoss):
|
| 1269 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1270 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head"]
|
| 1271 |
+
|
| 1272 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1273 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1274 |
+
self.num_labels = config.num_labels
|
| 1275 |
+
|
| 1276 |
+
self.roberta = TFCamembertMainLayer(config, add_pooling_layer=False, name="roberta")
|
| 1277 |
+
self.classifier = TFCamembertClassificationHead(config, name="classifier")
|
| 1278 |
+
|
| 1279 |
+
@unpack_inputs
|
| 1280 |
+
@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1281 |
+
@add_code_sample_docstrings(
|
| 1282 |
+
checkpoint="cardiffnlp/twitter-roberta-base-emotion",
|
| 1283 |
+
output_type=TFSequenceClassifierOutput,
|
| 1284 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1285 |
+
expected_output="'optimism'",
|
| 1286 |
+
expected_loss=0.08,
|
| 1287 |
+
)
|
| 1288 |
+
def call(
|
| 1289 |
+
self,
|
| 1290 |
+
input_ids: TFModelInputType | None = None,
|
| 1291 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1292 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1293 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1294 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1295 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1296 |
+
output_attentions: bool | None = None,
|
| 1297 |
+
output_hidden_states: bool | None = None,
|
| 1298 |
+
return_dict: bool | None = None,
|
| 1299 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1300 |
+
training: bool | None = False,
|
| 1301 |
+
) -> TFSequenceClassifierOutput | tuple[tf.Tensor]:
|
| 1302 |
+
r"""
|
| 1303 |
+
labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1304 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1305 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1306 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1307 |
+
"""
|
| 1308 |
+
outputs = self.roberta(
|
| 1309 |
+
input_ids,
|
| 1310 |
+
attention_mask=attention_mask,
|
| 1311 |
+
token_type_ids=token_type_ids,
|
| 1312 |
+
position_ids=position_ids,
|
| 1313 |
+
head_mask=head_mask,
|
| 1314 |
+
inputs_embeds=inputs_embeds,
|
| 1315 |
+
output_attentions=output_attentions,
|
| 1316 |
+
output_hidden_states=output_hidden_states,
|
| 1317 |
+
return_dict=return_dict,
|
| 1318 |
+
training=training,
|
| 1319 |
+
)
|
| 1320 |
+
sequence_output = outputs[0]
|
| 1321 |
+
logits = self.classifier(sequence_output, training=training)
|
| 1322 |
+
|
| 1323 |
+
loss = None if labels is None else self.hf_compute_loss(labels, logits)
|
| 1324 |
+
|
| 1325 |
+
if not return_dict:
|
| 1326 |
+
output = (logits,) + outputs[2:]
|
| 1327 |
+
return ((loss,) + output) if loss is not None else output
|
| 1328 |
+
|
| 1329 |
+
return TFSequenceClassifierOutput(
|
| 1330 |
+
loss=loss,
|
| 1331 |
+
logits=logits,
|
| 1332 |
+
hidden_states=outputs.hidden_states,
|
| 1333 |
+
attentions=outputs.attentions,
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
def build(self, input_shape=None):
|
| 1337 |
+
if self.built:
|
| 1338 |
+
return
|
| 1339 |
+
self.built = True
|
| 1340 |
+
if getattr(self, "roberta", None) is not None:
|
| 1341 |
+
with tf.name_scope(self.roberta.name):
|
| 1342 |
+
self.roberta.build(None)
|
| 1343 |
+
if getattr(self, "classifier", None) is not None:
|
| 1344 |
+
with tf.name_scope(self.classifier.name):
|
| 1345 |
+
self.classifier.build(None)
|
| 1346 |
+
|
| 1347 |
+
|
| 1348 |
+
@add_start_docstrings(
|
| 1349 |
+
"""
|
| 1350 |
+
CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
|
| 1351 |
+
for Named-Entity-Recognition (NER) tasks.
|
| 1352 |
+
""",
|
| 1353 |
+
CAMEMBERT_START_DOCSTRING,
|
| 1354 |
+
)
|
| 1355 |
+
# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForTokenClassification with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 1356 |
+
class TFCamembertForTokenClassification(TFCamembertPreTrainedModel, TFTokenClassificationLoss):
|
| 1357 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1358 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head"]
|
| 1359 |
+
_keys_to_ignore_on_load_missing = [r"dropout"]
|
| 1360 |
+
|
| 1361 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1362 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1363 |
+
self.num_labels = config.num_labels
|
| 1364 |
+
|
| 1365 |
+
self.roberta = TFCamembertMainLayer(config, add_pooling_layer=False, name="roberta")
|
| 1366 |
+
classifier_dropout = (
|
| 1367 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1368 |
+
)
|
| 1369 |
+
self.dropout = keras.layers.Dropout(classifier_dropout)
|
| 1370 |
+
self.classifier = keras.layers.Dense(
|
| 1371 |
+
config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 1372 |
+
)
|
| 1373 |
+
self.config = config
|
| 1374 |
+
|
| 1375 |
+
@unpack_inputs
|
| 1376 |
+
@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1377 |
+
@add_code_sample_docstrings(
|
| 1378 |
+
checkpoint="ydshieh/roberta-large-ner-english",
|
| 1379 |
+
output_type=TFTokenClassifierOutput,
|
| 1380 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1381 |
+
expected_output="['O', 'ORG', 'ORG', 'O', 'O', 'O', 'O', 'O', 'LOC', 'O', 'LOC', 'LOC']",
|
| 1382 |
+
expected_loss=0.01,
|
| 1383 |
+
)
|
| 1384 |
+
def call(
|
| 1385 |
+
self,
|
| 1386 |
+
input_ids: TFModelInputType | None = None,
|
| 1387 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1388 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1389 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1390 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1391 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1392 |
+
output_attentions: bool | None = None,
|
| 1393 |
+
output_hidden_states: bool | None = None,
|
| 1394 |
+
return_dict: bool | None = None,
|
| 1395 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1396 |
+
training: bool | None = False,
|
| 1397 |
+
) -> TFTokenClassifierOutput | tuple[tf.Tensor]:
|
| 1398 |
+
r"""
|
| 1399 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1400 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1401 |
+
"""
|
| 1402 |
+
outputs = self.roberta(
|
| 1403 |
+
input_ids,
|
| 1404 |
+
attention_mask=attention_mask,
|
| 1405 |
+
token_type_ids=token_type_ids,
|
| 1406 |
+
position_ids=position_ids,
|
| 1407 |
+
head_mask=head_mask,
|
| 1408 |
+
inputs_embeds=inputs_embeds,
|
| 1409 |
+
output_attentions=output_attentions,
|
| 1410 |
+
output_hidden_states=output_hidden_states,
|
| 1411 |
+
return_dict=return_dict,
|
| 1412 |
+
training=training,
|
| 1413 |
+
)
|
| 1414 |
+
sequence_output = outputs[0]
|
| 1415 |
+
|
| 1416 |
+
sequence_output = self.dropout(sequence_output, training=training)
|
| 1417 |
+
logits = self.classifier(sequence_output)
|
| 1418 |
+
|
| 1419 |
+
loss = None if labels is None else self.hf_compute_loss(labels, logits)
|
| 1420 |
+
|
| 1421 |
+
if not return_dict:
|
| 1422 |
+
output = (logits,) + outputs[2:]
|
| 1423 |
+
return ((loss,) + output) if loss is not None else output
|
| 1424 |
+
|
| 1425 |
+
return TFTokenClassifierOutput(
|
| 1426 |
+
loss=loss,
|
| 1427 |
+
logits=logits,
|
| 1428 |
+
hidden_states=outputs.hidden_states,
|
| 1429 |
+
attentions=outputs.attentions,
|
| 1430 |
+
)
|
| 1431 |
+
|
| 1432 |
+
def build(self, input_shape=None):
|
| 1433 |
+
if self.built:
|
| 1434 |
+
return
|
| 1435 |
+
self.built = True
|
| 1436 |
+
if getattr(self, "roberta", None) is not None:
|
| 1437 |
+
with tf.name_scope(self.roberta.name):
|
| 1438 |
+
self.roberta.build(None)
|
| 1439 |
+
if getattr(self, "classifier", None) is not None:
|
| 1440 |
+
with tf.name_scope(self.classifier.name):
|
| 1441 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
| 1442 |
+
|
| 1443 |
+
|
| 1444 |
+
@add_start_docstrings(
|
| 1445 |
+
"""
|
| 1446 |
+
CamemBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 1447 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 1448 |
+
""",
|
| 1449 |
+
CAMEMBERT_START_DOCSTRING,
|
| 1450 |
+
)
|
| 1451 |
+
# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForMultipleChoice with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 1452 |
+
class TFCamembertForMultipleChoice(TFCamembertPreTrainedModel, TFMultipleChoiceLoss):
|
| 1453 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1454 |
+
_keys_to_ignore_on_load_unexpected = [r"lm_head"]
|
| 1455 |
+
_keys_to_ignore_on_load_missing = [r"dropout"]
|
| 1456 |
+
|
| 1457 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1458 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1459 |
+
|
| 1460 |
+
self.roberta = TFCamembertMainLayer(config, name="roberta")
|
| 1461 |
+
self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
|
| 1462 |
+
self.classifier = keras.layers.Dense(
|
| 1463 |
+
1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 1464 |
+
)
|
| 1465 |
+
self.config = config
|
| 1466 |
+
|
| 1467 |
+
@unpack_inputs
|
| 1468 |
+
@add_start_docstrings_to_model_forward(
|
| 1469 |
+
CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
|
| 1470 |
+
)
|
| 1471 |
+
@add_code_sample_docstrings(
|
| 1472 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1473 |
+
output_type=TFMultipleChoiceModelOutput,
|
| 1474 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1475 |
+
)
|
| 1476 |
+
def call(
|
| 1477 |
+
self,
|
| 1478 |
+
input_ids: TFModelInputType | None = None,
|
| 1479 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1480 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1481 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1482 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1483 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1484 |
+
output_attentions: bool | None = None,
|
| 1485 |
+
output_hidden_states: bool | None = None,
|
| 1486 |
+
return_dict: bool | None = None,
|
| 1487 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1488 |
+
training: bool | None = False,
|
| 1489 |
+
) -> TFMultipleChoiceModelOutput | tuple[tf.Tensor]:
|
| 1490 |
+
r"""
|
| 1491 |
+
labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1492 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
|
| 1493 |
+
where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
|
| 1494 |
+
"""
|
| 1495 |
+
|
| 1496 |
+
if input_ids is not None:
|
| 1497 |
+
num_choices = shape_list(input_ids)[1]
|
| 1498 |
+
seq_length = shape_list(input_ids)[2]
|
| 1499 |
+
else:
|
| 1500 |
+
num_choices = shape_list(inputs_embeds)[1]
|
| 1501 |
+
seq_length = shape_list(inputs_embeds)[2]
|
| 1502 |
+
|
| 1503 |
+
flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
|
| 1504 |
+
flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
|
| 1505 |
+
flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None
|
| 1506 |
+
flat_position_ids = tf.reshape(position_ids, (-1, seq_length)) if position_ids is not None else None
|
| 1507 |
+
outputs = self.roberta(
|
| 1508 |
+
flat_input_ids,
|
| 1509 |
+
flat_attention_mask,
|
| 1510 |
+
flat_token_type_ids,
|
| 1511 |
+
flat_position_ids,
|
| 1512 |
+
head_mask,
|
| 1513 |
+
inputs_embeds,
|
| 1514 |
+
output_attentions,
|
| 1515 |
+
output_hidden_states,
|
| 1516 |
+
return_dict=return_dict,
|
| 1517 |
+
training=training,
|
| 1518 |
+
)
|
| 1519 |
+
pooled_output = outputs[1]
|
| 1520 |
+
pooled_output = self.dropout(pooled_output, training=training)
|
| 1521 |
+
logits = self.classifier(pooled_output)
|
| 1522 |
+
reshaped_logits = tf.reshape(logits, (-1, num_choices))
|
| 1523 |
+
|
| 1524 |
+
loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
|
| 1525 |
+
|
| 1526 |
+
if not return_dict:
|
| 1527 |
+
output = (reshaped_logits,) + outputs[2:]
|
| 1528 |
+
return ((loss,) + output) if loss is not None else output
|
| 1529 |
+
|
| 1530 |
+
return TFMultipleChoiceModelOutput(
|
| 1531 |
+
loss=loss,
|
| 1532 |
+
logits=reshaped_logits,
|
| 1533 |
+
hidden_states=outputs.hidden_states,
|
| 1534 |
+
attentions=outputs.attentions,
|
| 1535 |
+
)
|
| 1536 |
+
|
| 1537 |
+
def build(self, input_shape=None):
|
| 1538 |
+
if self.built:
|
| 1539 |
+
return
|
| 1540 |
+
self.built = True
|
| 1541 |
+
if getattr(self, "roberta", None) is not None:
|
| 1542 |
+
with tf.name_scope(self.roberta.name):
|
| 1543 |
+
self.roberta.build(None)
|
| 1544 |
+
if getattr(self, "classifier", None) is not None:
|
| 1545 |
+
with tf.name_scope(self.classifier.name):
|
| 1546 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
| 1547 |
+
|
| 1548 |
+
|
| 1549 |
+
@add_start_docstrings(
|
| 1550 |
+
"""
|
| 1551 |
+
CamemBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1552 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1553 |
+
""",
|
| 1554 |
+
CAMEMBERT_START_DOCSTRING,
|
| 1555 |
+
)
|
| 1556 |
+
# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForQuestionAnswering with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 1557 |
+
class TFCamembertForQuestionAnswering(TFCamembertPreTrainedModel, TFQuestionAnsweringLoss):
|
| 1558 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1559 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head"]
|
| 1560 |
+
|
| 1561 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1562 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1563 |
+
self.num_labels = config.num_labels
|
| 1564 |
+
|
| 1565 |
+
self.roberta = TFCamembertMainLayer(config, add_pooling_layer=False, name="roberta")
|
| 1566 |
+
self.qa_outputs = keras.layers.Dense(
|
| 1567 |
+
config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
|
| 1568 |
+
)
|
| 1569 |
+
self.config = config
|
| 1570 |
+
|
| 1571 |
+
@unpack_inputs
|
| 1572 |
+
@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1573 |
+
@add_code_sample_docstrings(
|
| 1574 |
+
checkpoint="ydshieh/roberta-base-squad2",
|
| 1575 |
+
output_type=TFQuestionAnsweringModelOutput,
|
| 1576 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1577 |
+
expected_output="' puppet'",
|
| 1578 |
+
expected_loss=0.86,
|
| 1579 |
+
)
|
| 1580 |
+
def call(
|
| 1581 |
+
self,
|
| 1582 |
+
input_ids: TFModelInputType | None = None,
|
| 1583 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1584 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1585 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1586 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1587 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1588 |
+
output_attentions: bool | None = None,
|
| 1589 |
+
output_hidden_states: bool | None = None,
|
| 1590 |
+
return_dict: bool | None = None,
|
| 1591 |
+
start_positions: np.ndarray | tf.Tensor | None = None,
|
| 1592 |
+
end_positions: np.ndarray | tf.Tensor | None = None,
|
| 1593 |
+
training: bool | None = False,
|
| 1594 |
+
) -> TFQuestionAnsweringModelOutput | tuple[tf.Tensor]:
|
| 1595 |
+
r"""
|
| 1596 |
+
start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1597 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1598 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1599 |
+
are not taken into account for computing the loss.
|
| 1600 |
+
end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1601 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1602 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1603 |
+
are not taken into account for computing the loss.
|
| 1604 |
+
"""
|
| 1605 |
+
outputs = self.roberta(
|
| 1606 |
+
input_ids,
|
| 1607 |
+
attention_mask=attention_mask,
|
| 1608 |
+
token_type_ids=token_type_ids,
|
| 1609 |
+
position_ids=position_ids,
|
| 1610 |
+
head_mask=head_mask,
|
| 1611 |
+
inputs_embeds=inputs_embeds,
|
| 1612 |
+
output_attentions=output_attentions,
|
| 1613 |
+
output_hidden_states=output_hidden_states,
|
| 1614 |
+
return_dict=return_dict,
|
| 1615 |
+
training=training,
|
| 1616 |
+
)
|
| 1617 |
+
sequence_output = outputs[0]
|
| 1618 |
+
|
| 1619 |
+
logits = self.qa_outputs(sequence_output)
|
| 1620 |
+
start_logits, end_logits = tf.split(logits, 2, axis=-1)
|
| 1621 |
+
start_logits = tf.squeeze(start_logits, axis=-1)
|
| 1622 |
+
end_logits = tf.squeeze(end_logits, axis=-1)
|
| 1623 |
+
|
| 1624 |
+
loss = None
|
| 1625 |
+
if start_positions is not None and end_positions is not None:
|
| 1626 |
+
labels = {"start_position": start_positions}
|
| 1627 |
+
labels["end_position"] = end_positions
|
| 1628 |
+
loss = self.hf_compute_loss(labels, (start_logits, end_logits))
|
| 1629 |
+
|
| 1630 |
+
if not return_dict:
|
| 1631 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1632 |
+
return ((loss,) + output) if loss is not None else output
|
| 1633 |
+
|
| 1634 |
+
return TFQuestionAnsweringModelOutput(
|
| 1635 |
+
loss=loss,
|
| 1636 |
+
start_logits=start_logits,
|
| 1637 |
+
end_logits=end_logits,
|
| 1638 |
+
hidden_states=outputs.hidden_states,
|
| 1639 |
+
attentions=outputs.attentions,
|
| 1640 |
+
)
|
| 1641 |
+
|
| 1642 |
+
def build(self, input_shape=None):
|
| 1643 |
+
if self.built:
|
| 1644 |
+
return
|
| 1645 |
+
self.built = True
|
| 1646 |
+
if getattr(self, "roberta", None) is not None:
|
| 1647 |
+
with tf.name_scope(self.roberta.name):
|
| 1648 |
+
self.roberta.build(None)
|
| 1649 |
+
if getattr(self, "qa_outputs", None) is not None:
|
| 1650 |
+
with tf.name_scope(self.qa_outputs.name):
|
| 1651 |
+
self.qa_outputs.build([None, None, self.config.hidden_size])
|
| 1652 |
+
|
| 1653 |
+
|
| 1654 |
+
@add_start_docstrings(
|
| 1655 |
+
"""CamemBERT Model with a `language modeling` head on top for CLM fine-tuning.""", CAMEMBERT_START_DOCSTRING
|
| 1656 |
+
)
|
| 1657 |
+
# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForCausalLM with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 1658 |
+
class TFCamembertForCausalLM(TFCamembertPreTrainedModel, TFCausalLanguageModelingLoss):
|
| 1659 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1660 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head.decoder.weight"]
|
| 1661 |
+
|
| 1662 |
+
def __init__(self, config: CamembertConfig, *inputs, **kwargs):
|
| 1663 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1664 |
+
|
| 1665 |
+
if not config.is_decoder:
|
| 1666 |
+
logger.warning("If you want to use `TFCamembertLMHeadModel` as a standalone, add `is_decoder=True.`")
|
| 1667 |
+
|
| 1668 |
+
self.roberta = TFCamembertMainLayer(config, add_pooling_layer=False, name="roberta")
|
| 1669 |
+
self.lm_head = TFCamembertLMHead(config, input_embeddings=self.roberta.embeddings, name="lm_head")
|
| 1670 |
+
|
| 1671 |
+
def get_lm_head(self):
|
| 1672 |
+
return self.lm_head
|
| 1673 |
+
|
| 1674 |
+
def get_prefix_bias_name(self):
|
| 1675 |
+
warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
|
| 1676 |
+
return self.name + "/" + self.lm_head.name
|
| 1677 |
+
|
| 1678 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertLMHeadModel.prepare_inputs_for_generation
|
| 1679 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
|
| 1680 |
+
input_shape = input_ids.shape
|
| 1681 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
| 1682 |
+
if attention_mask is None:
|
| 1683 |
+
attention_mask = tf.ones(input_shape)
|
| 1684 |
+
|
| 1685 |
+
# cut decoder_input_ids if past is used
|
| 1686 |
+
if past_key_values is not None:
|
| 1687 |
+
input_ids = input_ids[:, -1:]
|
| 1688 |
+
|
| 1689 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
|
| 1690 |
+
|
| 1691 |
+
@unpack_inputs
|
| 1692 |
+
@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1693 |
+
@add_code_sample_docstrings(
|
| 1694 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1695 |
+
output_type=TFCausalLMOutputWithCrossAttentions,
|
| 1696 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1697 |
+
)
|
| 1698 |
+
def call(
|
| 1699 |
+
self,
|
| 1700 |
+
input_ids: TFModelInputType | None = None,
|
| 1701 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1702 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1703 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1704 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1705 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1706 |
+
encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
|
| 1707 |
+
encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1708 |
+
past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
|
| 1709 |
+
use_cache: bool | None = None,
|
| 1710 |
+
output_attentions: bool | None = None,
|
| 1711 |
+
output_hidden_states: bool | None = None,
|
| 1712 |
+
return_dict: bool | None = None,
|
| 1713 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1714 |
+
training: bool | None = False,
|
| 1715 |
+
) -> TFCausalLMOutputWithCrossAttentions | tuple[tf.Tensor]:
|
| 1716 |
+
r"""
|
| 1717 |
+
encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1718 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 1719 |
+
the model is configured as a decoder.
|
| 1720 |
+
encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1721 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 1722 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1723 |
+
|
| 1724 |
+
- 1 for tokens that are **not masked**,
|
| 1725 |
+
- 0 for tokens that are **masked**.
|
| 1726 |
+
|
| 1727 |
+
past_key_values (`tuple[tuple[tf.Tensor]]` of length `config.n_layers`)
|
| 1728 |
+
contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 1729 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 1730 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 1731 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1732 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 1733 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 1734 |
+
`past_key_values`). Set to `False` during training, `True` during generation
|
| 1735 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1736 |
+
Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
|
| 1737 |
+
config.vocab_size - 1]`.
|
| 1738 |
+
"""
|
| 1739 |
+
outputs = self.roberta(
|
| 1740 |
+
input_ids=input_ids,
|
| 1741 |
+
attention_mask=attention_mask,
|
| 1742 |
+
token_type_ids=token_type_ids,
|
| 1743 |
+
position_ids=position_ids,
|
| 1744 |
+
head_mask=head_mask,
|
| 1745 |
+
inputs_embeds=inputs_embeds,
|
| 1746 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1747 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1748 |
+
past_key_values=past_key_values,
|
| 1749 |
+
use_cache=use_cache,
|
| 1750 |
+
output_attentions=output_attentions,
|
| 1751 |
+
output_hidden_states=output_hidden_states,
|
| 1752 |
+
return_dict=return_dict,
|
| 1753 |
+
training=training,
|
| 1754 |
+
)
|
| 1755 |
+
|
| 1756 |
+
sequence_output = outputs[0]
|
| 1757 |
+
logits = self.lm_head(hidden_states=sequence_output, training=training)
|
| 1758 |
+
loss = None
|
| 1759 |
+
|
| 1760 |
+
if labels is not None:
|
| 1761 |
+
# shift labels to the left and cut last logit token
|
| 1762 |
+
shifted_logits = logits[:, :-1]
|
| 1763 |
+
labels = labels[:, 1:]
|
| 1764 |
+
loss = self.hf_compute_loss(labels=labels, logits=shifted_logits)
|
| 1765 |
+
|
| 1766 |
+
if not return_dict:
|
| 1767 |
+
output = (logits,) + outputs[2:]
|
| 1768 |
+
return ((loss,) + output) if loss is not None else output
|
| 1769 |
+
|
| 1770 |
+
return TFCausalLMOutputWithCrossAttentions(
|
| 1771 |
+
loss=loss,
|
| 1772 |
+
logits=logits,
|
| 1773 |
+
past_key_values=outputs.past_key_values,
|
| 1774 |
+
hidden_states=outputs.hidden_states,
|
| 1775 |
+
attentions=outputs.attentions,
|
| 1776 |
+
cross_attentions=outputs.cross_attentions,
|
| 1777 |
+
)
|
| 1778 |
+
|
| 1779 |
+
def build(self, input_shape=None):
|
| 1780 |
+
if self.built:
|
| 1781 |
+
return
|
| 1782 |
+
self.built = True
|
| 1783 |
+
if getattr(self, "roberta", None) is not None:
|
| 1784 |
+
with tf.name_scope(self.roberta.name):
|
| 1785 |
+
self.roberta.build(None)
|
| 1786 |
+
if getattr(self, "lm_head", None) is not None:
|
| 1787 |
+
with tf.name_scope(self.lm_head.name):
|
| 1788 |
+
self.lm_head.build(None)
|
| 1789 |
+
|
| 1790 |
+
|
| 1791 |
+
__all__ = [
|
| 1792 |
+
"TFCamembertForCausalLM",
|
| 1793 |
+
"TFCamembertForMaskedLM",
|
| 1794 |
+
"TFCamembertForMultipleChoice",
|
| 1795 |
+
"TFCamembertForQuestionAnswering",
|
| 1796 |
+
"TFCamembertForSequenceClassification",
|
| 1797 |
+
"TFCamembertForTokenClassification",
|
| 1798 |
+
"TFCamembertModel",
|
| 1799 |
+
"TFCamembertPreTrainedModel",
|
| 1800 |
+
]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/camembert/tokenization_camembert.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 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 Camembert model."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from shutil import copyfile
|
| 19 |
+
from typing import Any, Optional
|
| 20 |
+
|
| 21 |
+
import sentencepiece as spm
|
| 22 |
+
|
| 23 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 24 |
+
from ...utils import logging
|
| 25 |
+
from ...utils.import_utils import requires
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model"}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
SPIECE_UNDERLINE = "▁"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@requires(backends=("sentencepiece",))
|
| 37 |
+
class CamembertTokenizer(PreTrainedTokenizer):
|
| 38 |
+
"""
|
| 39 |
+
Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Construct a CamemBERT tokenizer. Based on
|
| 40 |
+
[SentencePiece](https://github.com/google/sentencepiece).
|
| 41 |
+
|
| 42 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 43 |
+
this superclass for more information regarding those methods.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
vocab_file (`str`):
|
| 47 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 48 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 49 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 50 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 51 |
+
|
| 52 |
+
<Tip>
|
| 53 |
+
|
| 54 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 55 |
+
sequence. The token used is the `cls_token`.
|
| 56 |
+
|
| 57 |
+
</Tip>
|
| 58 |
+
|
| 59 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 60 |
+
The end of sequence token.
|
| 61 |
+
|
| 62 |
+
<Tip>
|
| 63 |
+
|
| 64 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 65 |
+
The token used is the `sep_token`.
|
| 66 |
+
|
| 67 |
+
</Tip>
|
| 68 |
+
|
| 69 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
| 70 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 71 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 72 |
+
token of a sequence built with special tokens.
|
| 73 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
| 74 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 75 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 76 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 77 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 78 |
+
token instead.
|
| 79 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 80 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 81 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 82 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 83 |
+
modeling. This is the token which the model will try to predict.
|
| 84 |
+
additional_special_tokens (`list[str]`, *optional*, defaults to `['<s>NOTUSED', '</s>NOTUSED', '<unk>NOTUSED']`):
|
| 85 |
+
Additional special tokens used by the tokenizer.
|
| 86 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 87 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 88 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 89 |
+
to set:
|
| 90 |
+
|
| 91 |
+
- `enable_sampling`: Enable subword regularization.
|
| 92 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 93 |
+
|
| 94 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 95 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 96 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 97 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 98 |
+
|
| 99 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 100 |
+
BPE-dropout.
|
| 101 |
+
|
| 102 |
+
Attributes:
|
| 103 |
+
sp_model (`SentencePieceProcessor`):
|
| 104 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 108 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 109 |
+
|
| 110 |
+
def __init__(
|
| 111 |
+
self,
|
| 112 |
+
vocab_file,
|
| 113 |
+
bos_token="<s>",
|
| 114 |
+
eos_token="</s>",
|
| 115 |
+
sep_token="</s>",
|
| 116 |
+
cls_token="<s>",
|
| 117 |
+
unk_token="<unk>",
|
| 118 |
+
pad_token="<pad>",
|
| 119 |
+
mask_token="<mask>",
|
| 120 |
+
additional_special_tokens=["<s>NOTUSED", "</s>NOTUSED", "<unk>NOTUSED"],
|
| 121 |
+
sp_model_kwargs: Optional[dict[str, Any]] = None,
|
| 122 |
+
**kwargs,
|
| 123 |
+
) -> None:
|
| 124 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 125 |
+
mask_token = (
|
| 126 |
+
AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False, special=True)
|
| 127 |
+
if isinstance(mask_token, str)
|
| 128 |
+
else mask_token
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 132 |
+
|
| 133 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 134 |
+
self.sp_model.Load(str(vocab_file))
|
| 135 |
+
self.vocab_file = vocab_file
|
| 136 |
+
|
| 137 |
+
# HACK: These tokens were added by the author for an obscure reason as they were already part of the
|
| 138 |
+
# sentencepiece vocabulary (this is the case for <s> and </s> and <unk>).
|
| 139 |
+
# In this case it is recommended to properly set the tokens by hand.
|
| 140 |
+
self._added_tokens_decoder = {
|
| 141 |
+
0: AddedToken("<s>NOTUSED", special=True),
|
| 142 |
+
1: AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token,
|
| 143 |
+
2: AddedToken("</s>NOTUSED", special=True),
|
| 144 |
+
3: AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token,
|
| 145 |
+
4: AddedToken("<unk>NOTUSED", special=True),
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
self.fairseq_offset = 4 # 3 tokens are newly added, but the offset starts from 4
|
| 149 |
+
|
| 150 |
+
# legacy: camemebert is a particular case were we have to make sure `"<unk>NOTUSED"` is here
|
| 151 |
+
if "added_tokens_decoder" in kwargs:
|
| 152 |
+
# this is the only class that requires this unfortunately.....
|
| 153 |
+
# the reason is that the fast version has a whole.
|
| 154 |
+
kwargs["added_tokens_decoder"].update(self._added_tokens_decoder)
|
| 155 |
+
|
| 156 |
+
super().__init__(
|
| 157 |
+
bos_token=bos_token,
|
| 158 |
+
eos_token=eos_token,
|
| 159 |
+
unk_token=unk_token,
|
| 160 |
+
sep_token=sep_token,
|
| 161 |
+
cls_token=cls_token,
|
| 162 |
+
pad_token=pad_token,
|
| 163 |
+
mask_token=mask_token,
|
| 164 |
+
additional_special_tokens=additional_special_tokens,
|
| 165 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 166 |
+
**kwargs,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def vocab_size(self):
|
| 171 |
+
# The length of the vocabulary without added tokens is len(self.sp_model) but the added tokens are added at the beginning.
|
| 172 |
+
return len(self.sp_model)
|
| 173 |
+
|
| 174 |
+
def get_vocab(self):
|
| 175 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.fairseq_offset)}
|
| 176 |
+
vocab.update(self.added_tokens_encoder)
|
| 177 |
+
return vocab
|
| 178 |
+
|
| 179 |
+
def _tokenize(self, text: str) -> list[str]:
|
| 180 |
+
return self.sp_model.encode(text, out_type=str)
|
| 181 |
+
|
| 182 |
+
def _convert_token_to_id(self, token):
|
| 183 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 184 |
+
# specific to camembert, both 3 and 4 point to the unk token.
|
| 185 |
+
if self.sp_model.PieceToId(token) == 0:
|
| 186 |
+
# Convert sentence piece unk token to fairseq unk token index
|
| 187 |
+
return self.unk_token_id
|
| 188 |
+
return self.fairseq_offset + self.sp_model.PieceToId(token)
|
| 189 |
+
|
| 190 |
+
def _convert_id_to_token(self, index):
|
| 191 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 192 |
+
return self.sp_model.IdToPiece(index - self.fairseq_offset)
|
| 193 |
+
|
| 194 |
+
def convert_tokens_to_string(self, tokens):
|
| 195 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 196 |
+
# TODO decode outputs do not match between fast and slow
|
| 197 |
+
current_sub_tokens = []
|
| 198 |
+
out_string = ""
|
| 199 |
+
prev_is_special = False
|
| 200 |
+
for token in tokens:
|
| 201 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
| 202 |
+
if token in self.all_special_tokens:
|
| 203 |
+
if not prev_is_special:
|
| 204 |
+
out_string += " "
|
| 205 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
| 206 |
+
prev_is_special = True
|
| 207 |
+
current_sub_tokens = []
|
| 208 |
+
else:
|
| 209 |
+
current_sub_tokens.append(token)
|
| 210 |
+
prev_is_special = False
|
| 211 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
| 212 |
+
return out_string.strip()
|
| 213 |
+
|
| 214 |
+
def __getstate__(self):
|
| 215 |
+
state = self.__dict__.copy()
|
| 216 |
+
state["sp_model"] = None
|
| 217 |
+
return state
|
| 218 |
+
|
| 219 |
+
def __setstate__(self, d):
|
| 220 |
+
self.__dict__ = d
|
| 221 |
+
|
| 222 |
+
# for backward compatibility
|
| 223 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 224 |
+
self.sp_model_kwargs = {}
|
| 225 |
+
|
| 226 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 227 |
+
self.sp_model.Load(self.vocab_file)
|
| 228 |
+
|
| 229 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 230 |
+
if not os.path.isdir(save_directory):
|
| 231 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 232 |
+
return
|
| 233 |
+
out_vocab_file = os.path.join(
|
| 234 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 238 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 239 |
+
elif not os.path.isfile(self.vocab_file):
|
| 240 |
+
with open(out_vocab_file, "wb") as fi:
|
| 241 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 242 |
+
fi.write(content_spiece_model)
|
| 243 |
+
|
| 244 |
+
return (out_vocab_file,)
|
| 245 |
+
|
| 246 |
+
def build_inputs_with_special_tokens(
|
| 247 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 248 |
+
) -> list[int]:
|
| 249 |
+
"""
|
| 250 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 251 |
+
adding special tokens. An CamemBERT sequence has the following format:
|
| 252 |
+
|
| 253 |
+
- single sequence: `<s> X </s>`
|
| 254 |
+
- pair of sequences: `<s> A </s></s> B </s>`
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
token_ids_0 (`list[int]`):
|
| 258 |
+
List of IDs to which the special tokens will be added.
|
| 259 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 260 |
+
Optional second list of IDs for sequence pairs.
|
| 261 |
+
|
| 262 |
+
Returns:
|
| 263 |
+
`list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 264 |
+
"""
|
| 265 |
+
|
| 266 |
+
if token_ids_1 is None:
|
| 267 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 268 |
+
cls = [self.cls_token_id]
|
| 269 |
+
sep = [self.sep_token_id]
|
| 270 |
+
return cls + token_ids_0 + sep + sep + token_ids_1 + sep
|
| 271 |
+
|
| 272 |
+
def get_special_tokens_mask(
|
| 273 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
|
| 274 |
+
) -> list[int]:
|
| 275 |
+
"""
|
| 276 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 277 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 278 |
+
|
| 279 |
+
Args:
|
| 280 |
+
token_ids_0 (`list[int]`):
|
| 281 |
+
List of IDs.
|
| 282 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 283 |
+
Optional second list of IDs for sequence pairs.
|
| 284 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 285 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 286 |
+
|
| 287 |
+
Returns:
|
| 288 |
+
`list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 289 |
+
"""
|
| 290 |
+
if already_has_special_tokens:
|
| 291 |
+
return super().get_special_tokens_mask(
|
| 292 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
if token_ids_1 is None:
|
| 296 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 297 |
+
return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
|
| 298 |
+
|
| 299 |
+
def create_token_type_ids_from_sequences(
|
| 300 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 301 |
+
) -> list[int]:
|
| 302 |
+
"""
|
| 303 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. CamemBERT, like
|
| 304 |
+
RoBERTa, does not make use of token type ids, therefore a list of zeros is returned.
|
| 305 |
+
|
| 306 |
+
Args:
|
| 307 |
+
token_ids_0 (`list[int]`):
|
| 308 |
+
List of IDs.
|
| 309 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 310 |
+
Optional second list of IDs for sequence pairs.
|
| 311 |
+
|
| 312 |
+
Returns:
|
| 313 |
+
`list[int]`: List of zeros.
|
| 314 |
+
"""
|
| 315 |
+
sep = [self.sep_token_id]
|
| 316 |
+
cls = [self.cls_token_id]
|
| 317 |
+
|
| 318 |
+
if token_ids_1 is None:
|
| 319 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 320 |
+
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
__all__ = ["CamembertTokenizer"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/camembert/tokenization_camembert_fast.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License
|
| 15 |
+
"""Fast tokenization classes for Camembert model."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from shutil import copyfile
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
from ...tokenization_utils import AddedToken
|
| 22 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 23 |
+
from ...utils import is_sentencepiece_available, logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if is_sentencepiece_available():
|
| 27 |
+
from .tokenization_camembert import CamembertTokenizer
|
| 28 |
+
else:
|
| 29 |
+
CamembertTokenizer = None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
SPIECE_UNDERLINE = "▁"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class CamembertTokenizerFast(PreTrainedTokenizerFast):
|
| 41 |
+
"""
|
| 42 |
+
Construct a "fast" CamemBERT tokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
|
| 43 |
+
[`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
|
| 44 |
+
[BPE](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=BPE#models).
|
| 45 |
+
|
| 46 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
| 47 |
+
refer to this superclass for more information regarding those methods.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
vocab_file (`str`):
|
| 51 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 52 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 53 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 54 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 55 |
+
|
| 56 |
+
<Tip>
|
| 57 |
+
|
| 58 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 59 |
+
sequence. The token used is the `cls_token`.
|
| 60 |
+
|
| 61 |
+
</Tip>
|
| 62 |
+
|
| 63 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 64 |
+
The end of sequence token.
|
| 65 |
+
|
| 66 |
+
<Tip>
|
| 67 |
+
|
| 68 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 69 |
+
The token used is the `sep_token`.
|
| 70 |
+
|
| 71 |
+
</Tip>
|
| 72 |
+
|
| 73 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
| 74 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 75 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 76 |
+
token of a sequence built with special tokens.
|
| 77 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
| 78 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 79 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 80 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 81 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 82 |
+
token instead.
|
| 83 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 84 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 85 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 86 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 87 |
+
modeling. This is the token which the model will try to predict.
|
| 88 |
+
additional_special_tokens (`list[str]`, *optional*, defaults to `["<s>NOTUSED", "</s>NOTUSED"]`):
|
| 89 |
+
Additional special tokens used by the tokenizer.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 93 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 94 |
+
slow_tokenizer_class = CamembertTokenizer
|
| 95 |
+
|
| 96 |
+
def __init__(
|
| 97 |
+
self,
|
| 98 |
+
vocab_file=None,
|
| 99 |
+
tokenizer_file=None,
|
| 100 |
+
bos_token="<s>",
|
| 101 |
+
eos_token="</s>",
|
| 102 |
+
sep_token="</s>",
|
| 103 |
+
cls_token="<s>",
|
| 104 |
+
unk_token="<unk>",
|
| 105 |
+
pad_token="<pad>",
|
| 106 |
+
mask_token="<mask>",
|
| 107 |
+
additional_special_tokens=["<s>NOTUSED", "</s>NOTUSED", "<unk>NOTUSED"],
|
| 108 |
+
**kwargs,
|
| 109 |
+
):
|
| 110 |
+
# Mask token behave like a normal word, i.e. include the space before it. Will have normalized = False
|
| 111 |
+
mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
|
| 112 |
+
super().__init__(
|
| 113 |
+
vocab_file,
|
| 114 |
+
tokenizer_file=tokenizer_file,
|
| 115 |
+
bos_token=bos_token,
|
| 116 |
+
eos_token=eos_token,
|
| 117 |
+
sep_token=sep_token,
|
| 118 |
+
cls_token=cls_token,
|
| 119 |
+
unk_token=unk_token,
|
| 120 |
+
pad_token=pad_token,
|
| 121 |
+
mask_token=mask_token,
|
| 122 |
+
additional_special_tokens=additional_special_tokens,
|
| 123 |
+
**kwargs,
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
self.vocab_file = vocab_file
|
| 127 |
+
|
| 128 |
+
def build_inputs_with_special_tokens(
|
| 129 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 130 |
+
) -> list[int]:
|
| 131 |
+
"""
|
| 132 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 133 |
+
adding special tokens. An CamemBERT sequence has the following format:
|
| 134 |
+
|
| 135 |
+
- single sequence: `<s> X </s>`
|
| 136 |
+
- pair of sequences: `<s> A </s></s> B </s>`
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
token_ids_0 (`list[int]`):
|
| 140 |
+
List of IDs to which the special tokens will be added.
|
| 141 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 142 |
+
Optional second list of IDs for sequence pairs.
|
| 143 |
+
|
| 144 |
+
Returns:
|
| 145 |
+
`list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
if token_ids_1 is None:
|
| 149 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 150 |
+
cls = [self.cls_token_id]
|
| 151 |
+
sep = [self.sep_token_id]
|
| 152 |
+
return cls + token_ids_0 + sep + sep + token_ids_1 + sep
|
| 153 |
+
|
| 154 |
+
def create_token_type_ids_from_sequences(
|
| 155 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 156 |
+
) -> list[int]:
|
| 157 |
+
"""
|
| 158 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. CamemBERT, like
|
| 159 |
+
RoBERTa, does not make use of token type ids, therefore a list of zeros is returned.
|
| 160 |
+
|
| 161 |
+
Args:
|
| 162 |
+
token_ids_0 (`list[int]`):
|
| 163 |
+
List of IDs.
|
| 164 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 165 |
+
Optional second list of IDs for sequence pairs.
|
| 166 |
+
|
| 167 |
+
Returns:
|
| 168 |
+
`list[int]`: List of zeros.
|
| 169 |
+
"""
|
| 170 |
+
sep = [self.sep_token_id]
|
| 171 |
+
cls = [self.cls_token_id]
|
| 172 |
+
|
| 173 |
+
if token_ids_1 is None:
|
| 174 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 175 |
+
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
|
| 176 |
+
|
| 177 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 178 |
+
if not self.can_save_slow_tokenizer:
|
| 179 |
+
raise ValueError(
|
| 180 |
+
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
|
| 181 |
+
"tokenizer."
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
if not os.path.isdir(save_directory):
|
| 185 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 186 |
+
return
|
| 187 |
+
out_vocab_file = os.path.join(
|
| 188 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
| 192 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 193 |
+
|
| 194 |
+
return (out_vocab_file,)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
__all__ = ["CamembertTokenizerFast"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/clap/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_clap import *
|
| 22 |
+
from .feature_extraction_clap import *
|
| 23 |
+
from .modeling_clap import *
|
| 24 |
+
from .processing_clap import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/clap/configuration_clap.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"""CLAP model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ClapTextConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`ClapTextModel`]. It is used to instantiate a CLAP
|
| 27 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 28 |
+
defaults will yield a similar configuration to that of the CLAP
|
| 29 |
+
[calp-hsat-fused](https://huggingface.co/laion/clap-hsat-fused) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 37 |
+
Vocabulary size of the CLAP model. Defines the number of different tokens that can be represented by the
|
| 38 |
+
`inputs_ids` passed when calling [`ClapTextModel`].
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 40 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 41 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 42 |
+
Number of hidden layers in the Transformer encoder.
|
| 43 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 44 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 45 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 46 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 47 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"relu"`):
|
| 48 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"relu"`,
|
| 49 |
+
`"relu"`, `"silu"` and `"relu_new"` are supported.
|
| 50 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 51 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 52 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 53 |
+
The dropout ratio for the attention probabilities.
|
| 54 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 55 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 56 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 57 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 58 |
+
The vocabulary size of the `token_type_ids` passed when calling [`ClapTextModel`].
|
| 59 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 60 |
+
The epsilon used by the layer normalization layers.
|
| 61 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 62 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 63 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 64 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
|
| 65 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 66 |
+
with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
|
| 67 |
+
is_decoder (`bool`, *optional*, defaults to `False`):
|
| 68 |
+
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
|
| 69 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 70 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 71 |
+
relevant if `config.is_decoder=True`.
|
| 72 |
+
projection_hidden_act (`str`, *optional*, defaults to `"relu"`):
|
| 73 |
+
The non-linear activation function (function or string) in the projection layer. If string, `"gelu"`,
|
| 74 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 75 |
+
projection_dim (`int`, *optional*, defaults to 512)
|
| 76 |
+
Dimension of the projection head of the `ClapTextModelWithProjection`.
|
| 77 |
+
|
| 78 |
+
Examples:
|
| 79 |
+
|
| 80 |
+
```python
|
| 81 |
+
>>> from transformers import ClapTextConfig, ClapTextModel
|
| 82 |
+
|
| 83 |
+
>>> # Initializing a CLAP text configuration
|
| 84 |
+
>>> configuration = ClapTextConfig()
|
| 85 |
+
|
| 86 |
+
>>> # Initializing a model (with random weights) from the configuration
|
| 87 |
+
>>> model = ClapTextModel(configuration)
|
| 88 |
+
|
| 89 |
+
>>> # Accessing the model configuration
|
| 90 |
+
>>> configuration = model.config
|
| 91 |
+
```"""
|
| 92 |
+
|
| 93 |
+
model_type = "clap_text_model"
|
| 94 |
+
base_config_key = "text_config"
|
| 95 |
+
|
| 96 |
+
def __init__(
|
| 97 |
+
self,
|
| 98 |
+
vocab_size=50265,
|
| 99 |
+
hidden_size=768,
|
| 100 |
+
num_hidden_layers=12,
|
| 101 |
+
num_attention_heads=12,
|
| 102 |
+
intermediate_size=3072,
|
| 103 |
+
hidden_act="gelu",
|
| 104 |
+
hidden_dropout_prob=0.1,
|
| 105 |
+
attention_probs_dropout_prob=0.1,
|
| 106 |
+
max_position_embeddings=514,
|
| 107 |
+
type_vocab_size=1,
|
| 108 |
+
initializer_factor=1.0,
|
| 109 |
+
layer_norm_eps=1e-12,
|
| 110 |
+
projection_dim=512,
|
| 111 |
+
pad_token_id=1,
|
| 112 |
+
bos_token_id=0,
|
| 113 |
+
eos_token_id=2,
|
| 114 |
+
position_embedding_type="absolute",
|
| 115 |
+
use_cache=True,
|
| 116 |
+
projection_hidden_act="relu",
|
| 117 |
+
**kwargs,
|
| 118 |
+
):
|
| 119 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 120 |
+
|
| 121 |
+
self.vocab_size = vocab_size
|
| 122 |
+
self.hidden_size = hidden_size
|
| 123 |
+
self.num_hidden_layers = num_hidden_layers
|
| 124 |
+
self.num_attention_heads = num_attention_heads
|
| 125 |
+
self.hidden_act = hidden_act
|
| 126 |
+
self.intermediate_size = intermediate_size
|
| 127 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 128 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 129 |
+
self.max_position_embeddings = max_position_embeddings
|
| 130 |
+
self.type_vocab_size = type_vocab_size
|
| 131 |
+
self.initializer_factor = initializer_factor
|
| 132 |
+
self.layer_norm_eps = layer_norm_eps
|
| 133 |
+
self.position_embedding_type = position_embedding_type
|
| 134 |
+
self.use_cache = use_cache
|
| 135 |
+
self.projection_hidden_act = projection_hidden_act
|
| 136 |
+
self.projection_dim = projection_dim
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class ClapAudioConfig(PretrainedConfig):
|
| 140 |
+
r"""
|
| 141 |
+
This is the configuration class to store the configuration of a [`ClapAudioModel`]. It is used to instantiate a
|
| 142 |
+
CLAP audio encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 143 |
+
configuration with the defaults will yield a similar configuration to that of the audio encoder of the CLAP
|
| 144 |
+
[laion/clap-htsat-fused](https://huggingface.co/laion/clap-htsat-fused) architecture.
|
| 145 |
+
|
| 146 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 147 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
window_size (`int`, *optional*, defaults to 8):
|
| 151 |
+
Image size of the spectrogram
|
| 152 |
+
num_mel_bins (`int`, *optional*, defaults to 64):
|
| 153 |
+
Number of mel features used per frames. Should correspond to the value used in the `ClapProcessor` class.
|
| 154 |
+
spec_size (`int`, *optional*, defaults to 256):
|
| 155 |
+
Desired input size of the spectrogram that the model supports. It can be different from the output of the
|
| 156 |
+
`ClapFeatureExtractor`, in which case the input features will be resized. Corresponds to the `image_size`
|
| 157 |
+
of the audio models.
|
| 158 |
+
hidden_act (`str`, *optional*, defaults to `"gelu"`):
|
| 159 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 160 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 161 |
+
patch_size (`int`, *optional*, defaults to 4):
|
| 162 |
+
Patch size for the audio spectrogram
|
| 163 |
+
patch_stride (`list`, *optional*, defaults to `[4, 4]`):
|
| 164 |
+
Patch stride for the audio spectrogram
|
| 165 |
+
num_classes (`int`, *optional*, defaults to 527):
|
| 166 |
+
Number of classes used for the head training
|
| 167 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 168 |
+
Hidden size of the output of the audio encoder. Correspond to the dimension of the penultimate layer's
|
| 169 |
+
output,which is sent to the projection MLP layer.
|
| 170 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
| 171 |
+
Hidden size of the projection layer.
|
| 172 |
+
depths (`list`, *optional*, defaults to `[2, 2, 6, 2]`):
|
| 173 |
+
Depths used for the Swin Layers of the audio model
|
| 174 |
+
num_attention_heads (`list`, *optional*, defaults to `[4, 8, 16, 32]`):
|
| 175 |
+
Number of attention heads used for the Swin Layers of the audio model
|
| 176 |
+
enable_fusion (`bool`, *optional*, defaults to `False`):
|
| 177 |
+
Whether or not to enable patch fusion. This is the main contribution of the authors, and should give the
|
| 178 |
+
best results.
|
| 179 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 180 |
+
The dropout probability for all fully connected layers in the encoder.
|
| 181 |
+
fusion_type (`[type]`, *optional*):
|
| 182 |
+
Fusion type used for the patch fusion.
|
| 183 |
+
patch_embed_input_channels (`int`, *optional*, defaults to 1):
|
| 184 |
+
Number of channels used for the input spectrogram
|
| 185 |
+
flatten_patch_embeds (`bool`, *optional*, defaults to `True`):
|
| 186 |
+
Whether or not to flatten the patch embeddings
|
| 187 |
+
patch_embeds_hidden_size (`int`, *optional*, defaults to 96):
|
| 188 |
+
Hidden size of the patch embeddings. It is used as the number of output channels.
|
| 189 |
+
enable_patch_layer_norm (`bool`, *optional*, defaults to `True`):
|
| 190 |
+
Whether or not to enable layer normalization for the patch embeddings
|
| 191 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 192 |
+
Drop path rate for the patch fusion
|
| 193 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 194 |
+
The dropout ratio for the attention probabilities.
|
| 195 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 196 |
+
Whether or not to add a bias to the query, key, value projections.
|
| 197 |
+
mlp_ratio (`float`, *optional*, defaults to 4.0):
|
| 198 |
+
Ratio of the mlp hidden dim to embedding dim.
|
| 199 |
+
aff_block_r (`int`, *optional*, defaults to 4):
|
| 200 |
+
downsize_ratio used in the AudioFF block
|
| 201 |
+
num_hidden_layers (`int`, *optional*, defaults to 4):
|
| 202 |
+
Number of hidden layers in the Transformer encoder.
|
| 203 |
+
projection_hidden_act (`str`, *optional*, defaults to `"relu"`):
|
| 204 |
+
The non-linear activation function (function or string) in the projection layer. If string, `"gelu"`,
|
| 205 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 206 |
+
layer_norm_eps (`[type]`, *optional*, defaults to 1e-05):
|
| 207 |
+
The epsilon used by the layer normalization layers.
|
| 208 |
+
initializer_factor (`float`, *optional*, defaults to 1.0):
|
| 209 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
| 210 |
+
testing).
|
| 211 |
+
|
| 212 |
+
Example:
|
| 213 |
+
|
| 214 |
+
```python
|
| 215 |
+
>>> from transformers import ClapAudioConfig, ClapAudioModel
|
| 216 |
+
|
| 217 |
+
>>> # Initializing a ClapAudioConfig with laion/clap-htsat-fused style configuration
|
| 218 |
+
>>> configuration = ClapAudioConfig()
|
| 219 |
+
|
| 220 |
+
>>> # Initializing a ClapAudioModel (with random weights) from the laion/clap-htsat-fused style configuration
|
| 221 |
+
>>> model = ClapAudioModel(configuration)
|
| 222 |
+
|
| 223 |
+
>>> # Accessing the model configuration
|
| 224 |
+
>>> configuration = model.config
|
| 225 |
+
```"""
|
| 226 |
+
|
| 227 |
+
model_type = "clap_audio_model"
|
| 228 |
+
base_config_key = "audio_config"
|
| 229 |
+
|
| 230 |
+
def __init__(
|
| 231 |
+
self,
|
| 232 |
+
window_size=8,
|
| 233 |
+
num_mel_bins=64,
|
| 234 |
+
spec_size=256,
|
| 235 |
+
hidden_act="gelu",
|
| 236 |
+
patch_size=4,
|
| 237 |
+
patch_stride=[4, 4],
|
| 238 |
+
num_classes=527,
|
| 239 |
+
hidden_size=768,
|
| 240 |
+
projection_dim=512,
|
| 241 |
+
depths=[2, 2, 6, 2],
|
| 242 |
+
num_attention_heads=[4, 8, 16, 32],
|
| 243 |
+
enable_fusion=False,
|
| 244 |
+
hidden_dropout_prob=0.1,
|
| 245 |
+
fusion_type=None,
|
| 246 |
+
patch_embed_input_channels=1,
|
| 247 |
+
flatten_patch_embeds=True,
|
| 248 |
+
patch_embeds_hidden_size=96,
|
| 249 |
+
enable_patch_layer_norm=True,
|
| 250 |
+
drop_path_rate=0.0,
|
| 251 |
+
attention_probs_dropout_prob=0.0,
|
| 252 |
+
qkv_bias=True,
|
| 253 |
+
mlp_ratio=4.0,
|
| 254 |
+
aff_block_r=4,
|
| 255 |
+
num_hidden_layers=4,
|
| 256 |
+
projection_hidden_act="relu",
|
| 257 |
+
layer_norm_eps=1e-5,
|
| 258 |
+
initializer_factor=1.0,
|
| 259 |
+
**kwargs,
|
| 260 |
+
):
|
| 261 |
+
super().__init__(**kwargs)
|
| 262 |
+
self.window_size = window_size
|
| 263 |
+
self.num_mel_bins = num_mel_bins
|
| 264 |
+
self.spec_size = spec_size
|
| 265 |
+
self.patch_size = patch_size
|
| 266 |
+
self.patch_stride = patch_stride
|
| 267 |
+
self.num_classes = num_classes
|
| 268 |
+
self.hidden_size = hidden_size
|
| 269 |
+
self.depths = depths
|
| 270 |
+
self.num_hidden_layers = num_hidden_layers
|
| 271 |
+
self.num_attention_heads = num_attention_heads
|
| 272 |
+
self.window_size = window_size
|
| 273 |
+
self.enable_fusion = enable_fusion
|
| 274 |
+
self.fusion_type = fusion_type
|
| 275 |
+
self.hidden_act = hidden_act
|
| 276 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 277 |
+
self.projection_dim = projection_dim
|
| 278 |
+
self.flatten_patch_embeds = flatten_patch_embeds
|
| 279 |
+
self.patch_embeds_hidden_size = patch_embeds_hidden_size
|
| 280 |
+
self.enable_patch_layer_norm = enable_patch_layer_norm
|
| 281 |
+
self.drop_path_rate = drop_path_rate
|
| 282 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 283 |
+
self.qkv_bias = qkv_bias
|
| 284 |
+
self.mlp_ratio = mlp_ratio
|
| 285 |
+
self.patch_embed_input_channels = patch_embed_input_channels
|
| 286 |
+
self.aff_block_r = aff_block_r
|
| 287 |
+
self.layer_norm_eps = layer_norm_eps
|
| 288 |
+
self.initializer_factor = initializer_factor
|
| 289 |
+
self.projection_hidden_act = projection_hidden_act
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
class ClapConfig(PretrainedConfig):
|
| 293 |
+
r"""
|
| 294 |
+
[`ClapConfig`] is the configuration class to store the configuration of a [`ClapModel`]. It is used to instantiate
|
| 295 |
+
a CLAP model according to the specified arguments, defining the text model and audio model configs. Instantiating a
|
| 296 |
+
configuration with the defaults will yield a similar configuration to that of the CLAP
|
| 297 |
+
[laion/clap-htsat-fused](https://huggingface.co/laion/clap-htsat-fused) architecture.
|
| 298 |
+
|
| 299 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 300 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 301 |
+
|
| 302 |
+
Args:
|
| 303 |
+
text_config (`dict`, *optional*):
|
| 304 |
+
Dictionary of configuration options used to initialize [`ClapTextConfig`].
|
| 305 |
+
audio_config (`dict`, *optional*):
|
| 306 |
+
Dictionary of configuration options used to initialize [`ClapAudioConfig`].
|
| 307 |
+
logit_scale_init_value (`float`, *optional*, defaults to 14.29):
|
| 308 |
+
The initial value of the *logit_scale* parameter. Default is used as per the original CLAP implementation.
|
| 309 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
| 310 |
+
Dimensionality of text and audio projection layers.
|
| 311 |
+
projection_hidden_act (`str`, *optional*, defaults to `"relu"`):
|
| 312 |
+
Activation function for the projection layers.
|
| 313 |
+
initializer_factor (`float`, *optional*, defaults to 1.0):
|
| 314 |
+
Factor to scale the initialization of the model weights.
|
| 315 |
+
kwargs (*optional*):
|
| 316 |
+
Dictionary of keyword arguments.
|
| 317 |
+
|
| 318 |
+
Example:
|
| 319 |
+
|
| 320 |
+
```python
|
| 321 |
+
>>> from transformers import ClapConfig, ClapModel
|
| 322 |
+
|
| 323 |
+
>>> # Initializing a ClapConfig with laion-ai/base style configuration
|
| 324 |
+
>>> configuration = ClapConfig()
|
| 325 |
+
|
| 326 |
+
>>> # Initializing a ClapModel (with random weights) from the laion-ai/base style configuration
|
| 327 |
+
>>> model = ClapModel(configuration)
|
| 328 |
+
|
| 329 |
+
>>> # Accessing the model configuration
|
| 330 |
+
>>> configuration = model.config
|
| 331 |
+
|
| 332 |
+
>>> # We can also initialize a ClapConfig from a ClapTextConfig and a ClapAudioConfig
|
| 333 |
+
>>> from transformers import ClapTextConfig, ClapAudioConfig
|
| 334 |
+
|
| 335 |
+
>>> # Initializing a ClapText and ClapAudioConfig configuration
|
| 336 |
+
>>> config_text = ClapTextConfig()
|
| 337 |
+
>>> config_audio = ClapAudioConfig()
|
| 338 |
+
|
| 339 |
+
>>> config = ClapConfig.from_text_audio_configs(config_text, config_audio)
|
| 340 |
+
```"""
|
| 341 |
+
|
| 342 |
+
model_type = "clap"
|
| 343 |
+
sub_configs = {"text_config": ClapTextConfig, "audio_config": ClapAudioConfig}
|
| 344 |
+
|
| 345 |
+
def __init__(
|
| 346 |
+
self,
|
| 347 |
+
text_config=None,
|
| 348 |
+
audio_config=None,
|
| 349 |
+
logit_scale_init_value=(1 / 0.07),
|
| 350 |
+
projection_dim=512,
|
| 351 |
+
projection_hidden_act="relu",
|
| 352 |
+
initializer_factor=1.0,
|
| 353 |
+
**kwargs,
|
| 354 |
+
):
|
| 355 |
+
super().__init__(**kwargs)
|
| 356 |
+
|
| 357 |
+
if text_config is None:
|
| 358 |
+
text_config = {}
|
| 359 |
+
logger.info("text_config is None. Initializing the ClapTextConfig with default values.")
|
| 360 |
+
|
| 361 |
+
if audio_config is None:
|
| 362 |
+
audio_config = {}
|
| 363 |
+
logger.info("audio_config is None. initializing the ClapAudioConfig with default values.")
|
| 364 |
+
|
| 365 |
+
self.text_config = ClapTextConfig(**text_config)
|
| 366 |
+
self.audio_config = ClapAudioConfig(**audio_config)
|
| 367 |
+
self.text_config.projection_dim = projection_dim
|
| 368 |
+
self.audio_config.projection_dim = projection_dim
|
| 369 |
+
|
| 370 |
+
self.text_config.projection_hidden_act = projection_hidden_act
|
| 371 |
+
self.audio_config.projection_hidden_act = projection_hidden_act
|
| 372 |
+
|
| 373 |
+
self.projection_dim = projection_dim
|
| 374 |
+
self.projection_hidden_act = projection_hidden_act
|
| 375 |
+
self.hidden_size = self.text_config.hidden_size
|
| 376 |
+
|
| 377 |
+
self.logit_scale_init_value = logit_scale_init_value
|
| 378 |
+
self.initializer_factor = initializer_factor
|
| 379 |
+
self.num_hidden_layers = self.text_config.num_hidden_layers + len(self.audio_config.depths)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
__all__ = ["ClapAudioConfig", "ClapConfig", "ClapTextConfig"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/clap/feature_extraction_clap.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 CLAP."""
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
from typing import Any, Optional, Union
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
|
| 23 |
+
from ...audio_utils import mel_filter_bank, spectrogram, window_function
|
| 24 |
+
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
|
| 25 |
+
from ...feature_extraction_utils import BatchFeature
|
| 26 |
+
from ...utils import TensorType, logging
|
| 27 |
+
from ...utils.import_utils import requires
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@requires(backends=("torch",))
|
| 34 |
+
class ClapFeatureExtractor(SequenceFeatureExtractor):
|
| 35 |
+
r"""
|
| 36 |
+
Constructs a CLAP feature extractor.
|
| 37 |
+
|
| 38 |
+
This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
|
| 39 |
+
most of the main methods. Users should refer to this superclass for more information regarding those methods.
|
| 40 |
+
|
| 41 |
+
This class extracts mel-filter bank features from raw speech using a custom numpy implementation of the *Short Time
|
| 42 |
+
Fourier Transform* (STFT) which should match pytorch's `torch.stft` equivalent.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
feature_size (`int`, *optional*, defaults to 64):
|
| 46 |
+
The feature dimension of the extracted Mel spectrograms. This corresponds to the number of mel filters
|
| 47 |
+
(`n_mels`).
|
| 48 |
+
sampling_rate (`int`, *optional*, defaults to 48000):
|
| 49 |
+
The sampling rate at which the audio files should be digitalized expressed in hertz (Hz). This only serves
|
| 50 |
+
to warn users if the audio fed to the feature extractor does not have the same sampling rate.
|
| 51 |
+
hop_length (`int`,*optional*, defaults to 480):
|
| 52 |
+
Length of the overlapping windows for the STFT used to obtain the Mel Spectrogram. The audio will be split
|
| 53 |
+
in smaller `frames` with a step of `hop_length` between each frame.
|
| 54 |
+
max_length_s (`int`, *optional*, defaults to 10):
|
| 55 |
+
The maximum input length of the model in seconds. This is used to pad the audio.
|
| 56 |
+
fft_window_size (`int`, *optional*, defaults to 1024):
|
| 57 |
+
Size of the window (in samples) on which the Fourier transform is applied. This controls the frequency
|
| 58 |
+
resolution of the spectrogram. 400 means that the fourier transform is computed on windows of 400 samples.
|
| 59 |
+
padding_value (`float`, *optional*, defaults to 0.0):
|
| 60 |
+
Padding value used to pad the audio. Should correspond to silences.
|
| 61 |
+
return_attention_mask (`bool`, *optional*, defaults to `False`):
|
| 62 |
+
Whether or not the model should return the attention masks corresponding to the input.
|
| 63 |
+
frequency_min (`float`, *optional*, defaults to 0):
|
| 64 |
+
The lowest frequency of interest. The STFT will not be computed for values below this.
|
| 65 |
+
frequency_max (`float`, *optional*, defaults to 14000):
|
| 66 |
+
The highest frequency of interest. The STFT will not be computed for values above this.
|
| 67 |
+
top_db (`float`, *optional*):
|
| 68 |
+
The highest decibel value used to convert the mel spectrogram to the log scale. For more details see the
|
| 69 |
+
`audio_utils.power_to_db` function
|
| 70 |
+
truncation (`str`, *optional*, defaults to `"fusion"`):
|
| 71 |
+
Truncation pattern for long audio inputs. Two patterns are available:
|
| 72 |
+
- `fusion` will use `_random_mel_fusion`, which stacks 3 random crops from the mel spectrogram and a
|
| 73 |
+
downsampled version of the entire mel spectrogram.
|
| 74 |
+
If `config.fusion` is set to True, shorter audios also need to to return 4 mels, which will just be a copy
|
| 75 |
+
of the original mel obtained from the padded audio.
|
| 76 |
+
- `rand_trunc` will select a random crop of the mel spectrogram.
|
| 77 |
+
padding (`str`, *optional*, defaults to `"repeatpad"`):
|
| 78 |
+
Padding pattern for shorter audio inputs. Three patterns were originally implemented:
|
| 79 |
+
- `repeatpad`: the audio is repeated, and then padded to fit the `max_length`.
|
| 80 |
+
- `repeat`: the audio is repeated and then cut to fit the `max_length`
|
| 81 |
+
- `pad`: the audio is padded.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
model_input_names = ["input_features", "is_longer"]
|
| 85 |
+
|
| 86 |
+
def __init__(
|
| 87 |
+
self,
|
| 88 |
+
feature_size=64,
|
| 89 |
+
sampling_rate=48_000,
|
| 90 |
+
hop_length=480,
|
| 91 |
+
max_length_s=10,
|
| 92 |
+
fft_window_size=1024,
|
| 93 |
+
padding_value=0.0,
|
| 94 |
+
return_attention_mask=False, # pad inputs to max length with silence token (zero) and no attention mask
|
| 95 |
+
frequency_min: float = 0,
|
| 96 |
+
frequency_max: float = 14_000,
|
| 97 |
+
top_db: Optional[int] = None,
|
| 98 |
+
truncation: str = "fusion",
|
| 99 |
+
padding: str = "repeatpad",
|
| 100 |
+
**kwargs,
|
| 101 |
+
):
|
| 102 |
+
super().__init__(
|
| 103 |
+
feature_size=feature_size,
|
| 104 |
+
sampling_rate=sampling_rate,
|
| 105 |
+
padding_value=padding_value,
|
| 106 |
+
return_attention_mask=return_attention_mask,
|
| 107 |
+
**kwargs,
|
| 108 |
+
)
|
| 109 |
+
self.top_db = top_db
|
| 110 |
+
self.truncation = truncation
|
| 111 |
+
self.padding = padding
|
| 112 |
+
self.fft_window_size = fft_window_size
|
| 113 |
+
self.nb_frequency_bins = (fft_window_size >> 1) + 1
|
| 114 |
+
self.hop_length = hop_length
|
| 115 |
+
self.max_length_s = max_length_s
|
| 116 |
+
self.nb_max_samples = max_length_s * sampling_rate
|
| 117 |
+
self.sampling_rate = sampling_rate
|
| 118 |
+
self.frequency_min = frequency_min
|
| 119 |
+
self.frequency_max = frequency_max
|
| 120 |
+
self.mel_filters = mel_filter_bank(
|
| 121 |
+
num_frequency_bins=self.nb_frequency_bins,
|
| 122 |
+
num_mel_filters=feature_size,
|
| 123 |
+
min_frequency=frequency_min,
|
| 124 |
+
max_frequency=frequency_max,
|
| 125 |
+
sampling_rate=sampling_rate,
|
| 126 |
+
norm=None,
|
| 127 |
+
mel_scale="htk",
|
| 128 |
+
)
|
| 129 |
+
self.mel_filters_slaney = mel_filter_bank(
|
| 130 |
+
num_frequency_bins=self.nb_frequency_bins,
|
| 131 |
+
num_mel_filters=feature_size,
|
| 132 |
+
min_frequency=frequency_min,
|
| 133 |
+
max_frequency=frequency_max,
|
| 134 |
+
sampling_rate=sampling_rate,
|
| 135 |
+
norm="slaney",
|
| 136 |
+
mel_scale="slaney",
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
def to_dict(self) -> dict[str, Any]:
|
| 140 |
+
"""
|
| 141 |
+
Serializes this instance to a Python dictionary.
|
| 142 |
+
|
| 143 |
+
Returns:
|
| 144 |
+
`dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance, except for the
|
| 145 |
+
mel filter banks, which do not need to be saved or printed as they are too long.
|
| 146 |
+
"""
|
| 147 |
+
output = copy.deepcopy(self.__dict__)
|
| 148 |
+
output["feature_extractor_type"] = self.__class__.__name__
|
| 149 |
+
if "mel_filters" in output:
|
| 150 |
+
del output["mel_filters"]
|
| 151 |
+
if "mel_filters_slaney" in output:
|
| 152 |
+
del output["mel_filters_slaney"]
|
| 153 |
+
return output
|
| 154 |
+
|
| 155 |
+
def _np_extract_fbank_features(self, waveform: np.ndarray, mel_filters: Optional[np.ndarray] = None) -> np.ndarray:
|
| 156 |
+
"""
|
| 157 |
+
Compute the log-mel spectrogram of the provided `waveform` using the Hann window. In CLAP, two different filter
|
| 158 |
+
banks are used depending on the truncation pattern:
|
| 159 |
+
- `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from
|
| 160 |
+
calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation`
|
| 161 |
+
is set to `"fusion"`.
|
| 162 |
+
- `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used
|
| 163 |
+
`librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original
|
| 164 |
+
implementation when the truncation mode is not `"fusion"`.
|
| 165 |
+
"""
|
| 166 |
+
log_mel_spectrogram = spectrogram(
|
| 167 |
+
waveform,
|
| 168 |
+
window_function(self.fft_window_size, "hann"),
|
| 169 |
+
frame_length=self.fft_window_size,
|
| 170 |
+
hop_length=self.hop_length,
|
| 171 |
+
power=2.0,
|
| 172 |
+
mel_filters=mel_filters,
|
| 173 |
+
log_mel="dB",
|
| 174 |
+
)
|
| 175 |
+
return log_mel_spectrogram.T
|
| 176 |
+
|
| 177 |
+
def _random_mel_fusion(self, mel, total_frames, chunk_frames):
|
| 178 |
+
ranges = np.array_split(list(range(0, total_frames - chunk_frames + 1)), 3)
|
| 179 |
+
if len(ranges[1]) == 0:
|
| 180 |
+
# if the audio is too short, we just use the first chunk
|
| 181 |
+
ranges[1] = [0]
|
| 182 |
+
if len(ranges[2]) == 0:
|
| 183 |
+
# if the audio is too short, we just use the first chunk
|
| 184 |
+
ranges[2] = [0]
|
| 185 |
+
# randomly choose index for each part
|
| 186 |
+
idx_front = np.random.choice(ranges[0])
|
| 187 |
+
idx_middle = np.random.choice(ranges[1])
|
| 188 |
+
idx_back = np.random.choice(ranges[2])
|
| 189 |
+
|
| 190 |
+
mel_chunk_front = mel[idx_front : idx_front + chunk_frames, :]
|
| 191 |
+
mel_chunk_middle = mel[idx_middle : idx_middle + chunk_frames, :]
|
| 192 |
+
mel_chunk_back = mel[idx_back : idx_back + chunk_frames, :]
|
| 193 |
+
|
| 194 |
+
mel = torch.tensor(mel[None, None, :])
|
| 195 |
+
mel_shrink = torch.nn.functional.interpolate(
|
| 196 |
+
mel, size=[chunk_frames, 64], mode="bilinear", align_corners=False
|
| 197 |
+
)
|
| 198 |
+
mel_shrink = mel_shrink[0][0].numpy()
|
| 199 |
+
mel_fusion = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back], axis=0)
|
| 200 |
+
return mel_fusion
|
| 201 |
+
|
| 202 |
+
def _get_input_mel(self, waveform: np.ndarray, max_length, truncation, padding) -> np.ndarray:
|
| 203 |
+
"""
|
| 204 |
+
Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments.
|
| 205 |
+
Four different path are possible:
|
| 206 |
+
- `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram
|
| 207 |
+
will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram
|
| 208 |
+
are then stacked together. They will later be used for `feature_fusion`.
|
| 209 |
+
- `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is
|
| 210 |
+
padded based on `padding`.
|
| 211 |
+
- `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded
|
| 212 |
+
based on `padding`, and is repeated `4` times.
|
| 213 |
+
- `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel
|
| 214 |
+
spectrogram will be computed on a random crop of the waveform.
|
| 215 |
+
|
| 216 |
+
"""
|
| 217 |
+
if waveform.shape[0] > max_length:
|
| 218 |
+
if truncation == "rand_trunc":
|
| 219 |
+
longer = True
|
| 220 |
+
# random crop to max_length (for compatibility) -> this should be handled by self.pad
|
| 221 |
+
overflow = len(waveform) - max_length
|
| 222 |
+
idx = np.random.randint(0, overflow + 1)
|
| 223 |
+
waveform = waveform[idx : idx + max_length]
|
| 224 |
+
input_mel = self._np_extract_fbank_features(waveform, self.mel_filters_slaney)[None, :]
|
| 225 |
+
elif truncation == "fusion":
|
| 226 |
+
mel = self._np_extract_fbank_features(waveform, self.mel_filters)
|
| 227 |
+
chunk_frames = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed
|
| 228 |
+
total_frames = mel.shape[0]
|
| 229 |
+
if chunk_frames == total_frames:
|
| 230 |
+
# there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
|
| 231 |
+
# In this case, we just use the whole audio.
|
| 232 |
+
input_mel = np.stack([mel, mel, mel, mel], axis=0)
|
| 233 |
+
longer = False
|
| 234 |
+
else:
|
| 235 |
+
input_mel = self._random_mel_fusion(mel, total_frames, chunk_frames)
|
| 236 |
+
longer = True
|
| 237 |
+
else:
|
| 238 |
+
raise NotImplementedError(f"data_truncating {truncation} not implemented")
|
| 239 |
+
|
| 240 |
+
else:
|
| 241 |
+
longer = False
|
| 242 |
+
# only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
|
| 243 |
+
if waveform.shape[0] < max_length:
|
| 244 |
+
if padding == "repeat":
|
| 245 |
+
n_repeat = int(max_length / len(waveform))
|
| 246 |
+
waveform = np.tile(waveform, n_repeat + 1)[:max_length]
|
| 247 |
+
if padding == "repeatpad":
|
| 248 |
+
n_repeat = int(max_length / len(waveform))
|
| 249 |
+
waveform = np.tile(waveform, n_repeat)
|
| 250 |
+
waveform = np.pad(waveform, (0, max_length - waveform.shape[0]), mode="constant", constant_values=0)
|
| 251 |
+
|
| 252 |
+
if truncation == "fusion":
|
| 253 |
+
input_mel = self._np_extract_fbank_features(waveform, self.mel_filters)
|
| 254 |
+
input_mel = np.stack([input_mel, input_mel, input_mel, input_mel], axis=0)
|
| 255 |
+
else:
|
| 256 |
+
input_mel = self._np_extract_fbank_features(waveform, self.mel_filters_slaney)[None, :]
|
| 257 |
+
|
| 258 |
+
return input_mel, longer
|
| 259 |
+
|
| 260 |
+
def __call__(
|
| 261 |
+
self,
|
| 262 |
+
raw_speech: Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]],
|
| 263 |
+
truncation: Optional[str] = None,
|
| 264 |
+
padding: Optional[str] = None,
|
| 265 |
+
max_length: Optional[int] = None,
|
| 266 |
+
sampling_rate: Optional[int] = None,
|
| 267 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 268 |
+
**kwargs,
|
| 269 |
+
) -> BatchFeature:
|
| 270 |
+
"""
|
| 271 |
+
Main method to featurize and prepare for the model one or several sequence(s).
|
| 272 |
+
|
| 273 |
+
Args:
|
| 274 |
+
raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
|
| 275 |
+
The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
|
| 276 |
+
values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
|
| 277 |
+
stereo, i.e. single float per timestep.
|
| 278 |
+
truncation (`str`, *optional*):
|
| 279 |
+
Truncation pattern for long audio inputs. Two patterns are available:
|
| 280 |
+
- `fusion` will use `_random_mel_fusion`, which stacks 3 random crops from the mel spectrogram and
|
| 281 |
+
a downsampled version of the entire mel spectrogram.
|
| 282 |
+
If `config.fusion` is set to True, shorter audios also need to to return 4 mels, which will just be a
|
| 283 |
+
copy of the original mel obtained from the padded audio.
|
| 284 |
+
- `rand_trunc` will select a random crop of the mel spectrogram.
|
| 285 |
+
padding (`str`, *optional*):
|
| 286 |
+
Padding pattern for shorter audio inputs. Three patterns were originally implemented:
|
| 287 |
+
- `repeatpad`: the audio is repeated, and then padded to fit the `max_length`.
|
| 288 |
+
- `repeat`: the audio is repeated and then cut to fit the `max_length`
|
| 289 |
+
- `pad`: the audio is padded.
|
| 290 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 291 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 292 |
+
|
| 293 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 294 |
+
- `'pt'`: Return PyTorch `torch.np.array` objects.
|
| 295 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 296 |
+
sampling_rate (`int`, *optional*):
|
| 297 |
+
The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
|
| 298 |
+
`sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
|
| 299 |
+
pipeline.
|
| 300 |
+
"""
|
| 301 |
+
truncation = truncation if truncation is not None else self.truncation
|
| 302 |
+
padding = padding if padding else self.padding
|
| 303 |
+
|
| 304 |
+
if sampling_rate is not None:
|
| 305 |
+
if sampling_rate != self.sampling_rate:
|
| 306 |
+
raise ValueError(
|
| 307 |
+
f"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
|
| 308 |
+
f" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
|
| 309 |
+
f" was sampled with {self.sampling_rate} and not {sampling_rate}."
|
| 310 |
+
)
|
| 311 |
+
else:
|
| 312 |
+
logger.warning(
|
| 313 |
+
f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
|
| 314 |
+
"Failing to do so can result in silent errors that might be hard to debug."
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
|
| 318 |
+
if is_batched_numpy and len(raw_speech.shape) > 2:
|
| 319 |
+
raise ValueError(f"Only mono-channel audio is supported for input to {self}")
|
| 320 |
+
is_batched = is_batched_numpy or (
|
| 321 |
+
isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
if is_batched:
|
| 325 |
+
raw_speech = [np.asarray(speech, dtype=np.float64) for speech in raw_speech]
|
| 326 |
+
elif not is_batched and not isinstance(raw_speech, np.ndarray):
|
| 327 |
+
raw_speech = np.asarray(raw_speech, dtype=np.float64)
|
| 328 |
+
elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
|
| 329 |
+
raw_speech = raw_speech.astype(np.float64)
|
| 330 |
+
|
| 331 |
+
# always return batch
|
| 332 |
+
if not is_batched:
|
| 333 |
+
raw_speech = [np.asarray(raw_speech)]
|
| 334 |
+
|
| 335 |
+
# convert to mel spectrogram, truncate and pad if needed.
|
| 336 |
+
padded_inputs = [
|
| 337 |
+
self._get_input_mel(waveform, max_length if max_length else self.nb_max_samples, truncation, padding)
|
| 338 |
+
for waveform in raw_speech
|
| 339 |
+
]
|
| 340 |
+
|
| 341 |
+
input_mel = []
|
| 342 |
+
is_longer = []
|
| 343 |
+
for mel, longer in padded_inputs:
|
| 344 |
+
input_mel.append(mel)
|
| 345 |
+
is_longer.append(longer)
|
| 346 |
+
|
| 347 |
+
if truncation == "fusion" and sum(is_longer) == 0:
|
| 348 |
+
# if no audio is longer than 10s, then randomly select one audio to be longer
|
| 349 |
+
rand_idx = np.random.randint(0, len(input_mel))
|
| 350 |
+
is_longer[rand_idx] = True
|
| 351 |
+
|
| 352 |
+
if isinstance(input_mel[0], list):
|
| 353 |
+
input_mel = [np.asarray(feature, dtype=np.float64) for feature in input_mel]
|
| 354 |
+
|
| 355 |
+
# is_longer is a list of bool
|
| 356 |
+
is_longer = [[longer] for longer in is_longer]
|
| 357 |
+
|
| 358 |
+
input_features = {"input_features": input_mel, "is_longer": is_longer}
|
| 359 |
+
input_features = BatchFeature(input_features)
|
| 360 |
+
|
| 361 |
+
if return_tensors is not None:
|
| 362 |
+
input_features = input_features.convert_to_tensors(return_tensors)
|
| 363 |
+
|
| 364 |
+
return input_features
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
__all__ = ["ClapFeatureExtractor"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/clap/modeling_clap.py
ADDED
|
@@ -0,0 +1,1929 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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023 The LAION-AI Team and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch CLAP model."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
import math
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import Any, Callable, Optional, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from torch import nn
|
| 25 |
+
|
| 26 |
+
from ...activations import ACT2FN
|
| 27 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 28 |
+
from ...modeling_outputs import (
|
| 29 |
+
BaseModelOutput,
|
| 30 |
+
BaseModelOutputWithPooling,
|
| 31 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 32 |
+
)
|
| 33 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 34 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, meshgrid, prune_linear_layer
|
| 35 |
+
from ...utils import ModelOutput, auto_docstring, can_return_tuple, filter_out_non_signature_kwargs, logging, torch_int
|
| 36 |
+
from .configuration_clap import ClapAudioConfig, ClapConfig, ClapTextConfig
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# Adapted from: https://github.com/LAION-AI/CLAP/blob/6ad05a971ba0622f6acee8c41993e0d02bbed639/src/open_clip/utils.py#L191
|
| 43 |
+
def interpolate(hidden_states, ratio):
|
| 44 |
+
"""
|
| 45 |
+
Interpolate data in time domain. This is used to compensate the resolution reduction in downsampling of a CNN.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
hidden_states (`torch.FloatTensor` of shape (batch_size, time_length, classes_num)):
|
| 49 |
+
Input hidden states
|
| 50 |
+
ratio (`int`):
|
| 51 |
+
The ratio of the length of the output to the length of the input.
|
| 52 |
+
"""
|
| 53 |
+
(batch_size, time_length, classes_num) = hidden_states.shape
|
| 54 |
+
upsampled = hidden_states[:, :, None, :].repeat(1, 1, ratio, 1)
|
| 55 |
+
upsampled = upsampled.reshape(batch_size, time_length * ratio, classes_num)
|
| 56 |
+
return upsampled
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# Adapted from https://github.com/LAION-AI/CLAP/blob/6ad05a971ba0622f6acee8c41993e0d02bbed639/src/open_clip/htsat.py#L249
|
| 60 |
+
def window_partition(hidden_states, window_size):
|
| 61 |
+
"""
|
| 62 |
+
Returns the resized hidden states. The output shape should be `(batch_size * num_windows, window_size, window_size,
|
| 63 |
+
num_channels)`
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
hidden_states (`torch.FloatTensor` of shape `(batch_size, height, width, num_channels)`):
|
| 67 |
+
Input hidden states
|
| 68 |
+
window_size (`int`):
|
| 69 |
+
Window size
|
| 70 |
+
"""
|
| 71 |
+
batch_size, height, width, num_channels = hidden_states.shape
|
| 72 |
+
|
| 73 |
+
hidden_states = hidden_states.view(
|
| 74 |
+
batch_size, height // window_size, window_size, width // window_size, window_size, num_channels
|
| 75 |
+
)
|
| 76 |
+
windows = hidden_states.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, num_channels)
|
| 77 |
+
return windows
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# Adapted from https://github.com/LAION-AI/CLAP/blob/6ad05a971ba0622f6acee8c41993e0d02bbed639/src/open_clip/htsat.py#L263
|
| 81 |
+
def window_reverse(windows, window_size, height, width):
|
| 82 |
+
"""
|
| 83 |
+
Merges windows to produce higher resolution features.
|
| 84 |
+
Args:
|
| 85 |
+
windows (`torch.FloatTensor` of shape `(num_windows * batch_size, window_size, window_size, num_channels)`):
|
| 86 |
+
Input windows
|
| 87 |
+
window_size (`int`):
|
| 88 |
+
Window size
|
| 89 |
+
height (`int`):
|
| 90 |
+
Height of the resized audio
|
| 91 |
+
width (`int`):
|
| 92 |
+
Width of the resized audio
|
| 93 |
+
"""
|
| 94 |
+
num_channels = windows.shape[-1]
|
| 95 |
+
windows = windows.view(-1, height // window_size, width // window_size, window_size, window_size, num_channels)
|
| 96 |
+
windows = windows.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, height, width, num_channels)
|
| 97 |
+
return windows
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
|
| 101 |
+
def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
|
| 102 |
+
"""
|
| 103 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
|
| 104 |
+
are ignored. This is modified from fairseq's `utils.make_positions`.
|
| 105 |
+
|
| 106 |
+
Args:
|
| 107 |
+
x: torch.Tensor x:
|
| 108 |
+
|
| 109 |
+
Returns: torch.Tensor
|
| 110 |
+
"""
|
| 111 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
| 112 |
+
mask = input_ids.ne(padding_idx).int()
|
| 113 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
| 114 |
+
return incremental_indices.long() + padding_idx
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# contrastive loss function, adapted from
|
| 118 |
+
# https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html#CLIP-loss-function
|
| 119 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
| 120 |
+
labels = torch.arange(len(logits), device=logits.device)
|
| 121 |
+
return nn.functional.cross_entropy(logits, labels)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@dataclass
|
| 125 |
+
@auto_docstring(
|
| 126 |
+
custom_intro="""
|
| 127 |
+
Base class for text model's outputs that also contains a pooling of the last hidden states.
|
| 128 |
+
"""
|
| 129 |
+
)
|
| 130 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPTextModelOutput with CLIP->Clap
|
| 131 |
+
class ClapTextModelOutput(ModelOutput):
|
| 132 |
+
r"""
|
| 133 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 134 |
+
The text embeddings obtained by applying the projection layer to the pooler_output.
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
| 138 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 139 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 140 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@dataclass
|
| 144 |
+
@auto_docstring(
|
| 145 |
+
custom_intro="""
|
| 146 |
+
ClapAudio model output to mimic the output of the original implementation.
|
| 147 |
+
"""
|
| 148 |
+
)
|
| 149 |
+
class ClapAudioModelOutput(ModelOutput):
|
| 150 |
+
r"""
|
| 151 |
+
audio_embeds (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
|
| 152 |
+
The Audio embeddings obtained by applying the projection layer to the pooler_output.
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
audio_embeds: Optional[torch.FloatTensor] = None
|
| 156 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 157 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 158 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@dataclass
|
| 162 |
+
@auto_docstring
|
| 163 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->Clap, vision->audio, Vision->Audio, image->audio
|
| 164 |
+
class ClapOutput(ModelOutput):
|
| 165 |
+
r"""
|
| 166 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 167 |
+
Contrastive loss for audio-text similarity.
|
| 168 |
+
logits_per_audio (`torch.FloatTensor` of shape `(audio_batch_size, text_batch_size)`):
|
| 169 |
+
The scaled dot product scores between `audio_embeds` and `text_embeds`. This represents the audio-text
|
| 170 |
+
similarity scores.
|
| 171 |
+
logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, audio_batch_size)`):
|
| 172 |
+
The scaled dot product scores between `text_embeds` and `audio_embeds`. This represents the text-audio
|
| 173 |
+
similarity scores.
|
| 174 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 175 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`ClapTextModel`].
|
| 176 |
+
audio_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 177 |
+
The audio embeddings obtained by applying the projection layer to the pooled output of [`ClapAudioModel`].
|
| 178 |
+
text_model_output (`BaseModelOutputWithPooling`):
|
| 179 |
+
The output of the [`ClapTextModel`].
|
| 180 |
+
audio_model_output (`BaseModelOutputWithPooling`):
|
| 181 |
+
The output of the [`ClapAudioModel`].
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
loss: Optional[torch.FloatTensor] = None
|
| 185 |
+
logits_per_audio: Optional[torch.FloatTensor] = None
|
| 186 |
+
logits_per_text: Optional[torch.FloatTensor] = None
|
| 187 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
| 188 |
+
audio_embeds: Optional[torch.FloatTensor] = None
|
| 189 |
+
text_model_output: BaseModelOutputWithPooling = None
|
| 190 |
+
audio_model_output: BaseModelOutputWithPooling = None
|
| 191 |
+
|
| 192 |
+
def to_tuple(self) -> tuple[Any]:
|
| 193 |
+
return tuple(
|
| 194 |
+
self[k] if k not in ["text_model_output", "audio_model_output"] else getattr(self, k).to_tuple()
|
| 195 |
+
for k in self.keys()
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# Adapted from transformers.models.swin.modeling_swin.SwinDropPath
|
| 200 |
+
class ClapDropPath(nn.Module):
|
| 201 |
+
"""
|
| 202 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is a slightly
|
| 203 |
+
refactored version of the `SwinDropPath` implementation.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
def __init__(self, drop_prob=None):
|
| 207 |
+
super().__init__()
|
| 208 |
+
self.drop_prob = drop_prob
|
| 209 |
+
|
| 210 |
+
def forward(self, hidden_states):
|
| 211 |
+
if self.drop_prob == 0.0 or not self.training:
|
| 212 |
+
return hidden_states
|
| 213 |
+
|
| 214 |
+
keep_prob = 1 - self.drop_prob
|
| 215 |
+
# work with diff dim tensors, not just 2D ConvNets
|
| 216 |
+
shape = (hidden_states.shape[0],) + (1,) * (hidden_states.ndim - 1)
|
| 217 |
+
|
| 218 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=hidden_states.dtype, device=hidden_states.device)
|
| 219 |
+
random_tensor.floor_() # binarize
|
| 220 |
+
output = hidden_states.div(keep_prob) * random_tensor
|
| 221 |
+
return output
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# Adapted from https://github.com/LAION-AI/CLAP/blob/6ad05a971ba0622f6acee8c41993e0d02bbed639/src/open_clip/feature_fusion.py#L133
|
| 225 |
+
class ClapAudioAFFBlock(nn.Module):
|
| 226 |
+
r"""
|
| 227 |
+
ATTENTIONAL FEATURE FUSION Block from CLAP, since in CLAP we are always in 2D mode, it is not needed to implement
|
| 228 |
+
the 1D version.
|
| 229 |
+
"""
|
| 230 |
+
|
| 231 |
+
def __init__(self, config: ClapAudioConfig):
|
| 232 |
+
super().__init__()
|
| 233 |
+
channels = config.patch_embeds_hidden_size
|
| 234 |
+
downsize_ratio = config.aff_block_r
|
| 235 |
+
inter_channels = int(channels // downsize_ratio)
|
| 236 |
+
|
| 237 |
+
self.local_att = nn.Sequential(
|
| 238 |
+
nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0),
|
| 239 |
+
nn.BatchNorm2d(inter_channels),
|
| 240 |
+
nn.ReLU(inplace=True),
|
| 241 |
+
nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0),
|
| 242 |
+
nn.BatchNorm2d(channels),
|
| 243 |
+
)
|
| 244 |
+
self.global_att = nn.Sequential(
|
| 245 |
+
nn.AdaptiveAvgPool2d(1),
|
| 246 |
+
nn.Conv2d(channels, inter_channels, kernel_size=1, stride=1, padding=0),
|
| 247 |
+
nn.BatchNorm2d(inter_channels),
|
| 248 |
+
nn.ReLU(inplace=True),
|
| 249 |
+
nn.Conv2d(inter_channels, channels, kernel_size=1, stride=1, padding=0),
|
| 250 |
+
nn.BatchNorm2d(channels),
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
self.sigmoid = nn.Sigmoid()
|
| 254 |
+
|
| 255 |
+
def forward(self, hidden_states, residual):
|
| 256 |
+
attention_input = hidden_states + residual
|
| 257 |
+
|
| 258 |
+
fused_layer_output = self.local_att(attention_input) + self.global_att(attention_input)
|
| 259 |
+
fused_layer_output = self.sigmoid(fused_layer_output)
|
| 260 |
+
|
| 261 |
+
output = 2 * hidden_states * fused_layer_output + 2 * residual * (1 - fused_layer_output)
|
| 262 |
+
return output
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class ClapAudioPatchEmbed(nn.Module):
|
| 266 |
+
"""
|
| 267 |
+
This module converts the hidden states reshaped as an image to patch embeddings ready to be passed to the
|
| 268 |
+
Transformer block.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
def __init__(self, config: ClapAudioConfig):
|
| 272 |
+
super().__init__()
|
| 273 |
+
img_size = (config.spec_size, config.spec_size) if isinstance(config.spec_size, int) else config.spec_size
|
| 274 |
+
patch_size = (
|
| 275 |
+
(config.patch_size, config.patch_size) if isinstance(config.patch_size, int) else config.patch_size
|
| 276 |
+
)
|
| 277 |
+
patch_stride = (
|
| 278 |
+
(config.patch_stride, config.patch_stride) if isinstance(config.patch_stride, int) else config.patch_stride
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
self.img_size = img_size
|
| 282 |
+
self.patch_stride = patch_stride
|
| 283 |
+
|
| 284 |
+
self.grid_size = (img_size[0] // patch_stride[0], img_size[1] // patch_stride[1])
|
| 285 |
+
self.num_patches = self.grid_size[0] * self.grid_size[1]
|
| 286 |
+
|
| 287 |
+
self.flatten = config.flatten_patch_embeds
|
| 288 |
+
self.enable_fusion = config.enable_fusion
|
| 289 |
+
|
| 290 |
+
padding = ((patch_size[0] - patch_stride[0]) // 2, (patch_size[1] - patch_stride[1]) // 2)
|
| 291 |
+
|
| 292 |
+
scale_factor = 4 if (self.enable_fusion) and (config.fusion_type == "channel_map") else 1
|
| 293 |
+
|
| 294 |
+
self.proj = nn.Conv2d(
|
| 295 |
+
config.patch_embed_input_channels * scale_factor,
|
| 296 |
+
config.patch_embeds_hidden_size,
|
| 297 |
+
kernel_size=patch_size,
|
| 298 |
+
stride=patch_stride,
|
| 299 |
+
padding=padding,
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
self.norm = nn.LayerNorm(config.patch_embeds_hidden_size) if config.enable_patch_layer_norm else nn.Identity()
|
| 303 |
+
if self.enable_fusion:
|
| 304 |
+
self.fusion_model = ClapAudioAFFBlock(config)
|
| 305 |
+
self.mel_conv2d = nn.Conv2d(
|
| 306 |
+
config.patch_embed_input_channels,
|
| 307 |
+
config.patch_embeds_hidden_size,
|
| 308 |
+
kernel_size=(patch_size[0], patch_size[1] * 3),
|
| 309 |
+
stride=(patch_stride[0], patch_stride[1] * 3),
|
| 310 |
+
padding=padding,
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
def forward(self, hidden_states, is_longer_idx=None):
|
| 314 |
+
if self.enable_fusion:
|
| 315 |
+
# retrieve the last mel as we have transposed the input
|
| 316 |
+
global_hidden_states = hidden_states[:, 0:1, :, :]
|
| 317 |
+
|
| 318 |
+
# global processing
|
| 319 |
+
batch_size, num_channels, height, width = global_hidden_states.shape
|
| 320 |
+
|
| 321 |
+
if height != self.img_size[0] or width != self.img_size[1]:
|
| 322 |
+
raise ValueError(
|
| 323 |
+
f"Input audio size ({height}*{width}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
global_hidden_states = self.proj(global_hidden_states)
|
| 327 |
+
output_width = global_hidden_states.size(-1)
|
| 328 |
+
if len(is_longer_idx) > 0:
|
| 329 |
+
# local processing
|
| 330 |
+
local_hidden_states = hidden_states[is_longer_idx, 1:, :, :].contiguous()
|
| 331 |
+
batch_size, num_channels, height, width = local_hidden_states.shape
|
| 332 |
+
local_hidden_states = local_hidden_states.view(batch_size * num_channels, 1, height, width)
|
| 333 |
+
|
| 334 |
+
local_hidden_states = self.mel_conv2d(local_hidden_states)
|
| 335 |
+
|
| 336 |
+
_, features, height, width = local_hidden_states.shape
|
| 337 |
+
local_hidden_states = local_hidden_states.view(batch_size, num_channels, features, height, width)
|
| 338 |
+
local_hidden_states = local_hidden_states.permute((0, 2, 3, 1, 4)).contiguous().flatten(3)
|
| 339 |
+
|
| 340 |
+
local_width = local_hidden_states.size(-1)
|
| 341 |
+
local_hidden_states = torch.nn.functional.pad(
|
| 342 |
+
local_hidden_states, (0, output_width - local_width), "constant", 0
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
global_hidden_states[is_longer_idx] = self.fusion_model(
|
| 346 |
+
global_hidden_states[is_longer_idx], local_hidden_states
|
| 347 |
+
)
|
| 348 |
+
hidden_states = global_hidden_states
|
| 349 |
+
else:
|
| 350 |
+
_, _, height, width = hidden_states.shape
|
| 351 |
+
if height != self.img_size[0] or width != self.img_size[1]:
|
| 352 |
+
raise ValueError(
|
| 353 |
+
f"Input audio size ({height}*{width}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
|
| 354 |
+
)
|
| 355 |
+
hidden_states = self.proj(hidden_states)
|
| 356 |
+
|
| 357 |
+
if self.flatten:
|
| 358 |
+
hidden_states = hidden_states.flatten(2).transpose(1, 2)
|
| 359 |
+
hidden_states = self.norm(hidden_states)
|
| 360 |
+
return hidden_states
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
# Copied from transformers.models.swin.modeling_swin.SwinSelfAttention with Swin->ClapAudio
|
| 364 |
+
class ClapAudioSelfAttention(nn.Module):
|
| 365 |
+
def __init__(self, config, dim, num_heads, window_size):
|
| 366 |
+
super().__init__()
|
| 367 |
+
if dim % num_heads != 0:
|
| 368 |
+
raise ValueError(
|
| 369 |
+
f"The hidden size ({dim}) is not a multiple of the number of attention heads ({num_heads})"
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
self.num_attention_heads = num_heads
|
| 373 |
+
self.attention_head_size = int(dim / num_heads)
|
| 374 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 375 |
+
self.window_size = (
|
| 376 |
+
window_size if isinstance(window_size, collections.abc.Iterable) else (window_size, window_size)
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
self.relative_position_bias_table = nn.Parameter(
|
| 380 |
+
torch.zeros((2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1), num_heads)
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
# get pair-wise relative position index for each token inside the window
|
| 384 |
+
coords_h = torch.arange(self.window_size[0])
|
| 385 |
+
coords_w = torch.arange(self.window_size[1])
|
| 386 |
+
coords = torch.stack(meshgrid([coords_h, coords_w], indexing="ij"))
|
| 387 |
+
coords_flatten = torch.flatten(coords, 1)
|
| 388 |
+
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
|
| 389 |
+
relative_coords = relative_coords.permute(1, 2, 0).contiguous()
|
| 390 |
+
relative_coords[:, :, 0] += self.window_size[0] - 1
|
| 391 |
+
relative_coords[:, :, 1] += self.window_size[1] - 1
|
| 392 |
+
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
|
| 393 |
+
relative_position_index = relative_coords.sum(-1)
|
| 394 |
+
self.register_buffer("relative_position_index", relative_position_index)
|
| 395 |
+
|
| 396 |
+
self.query = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
|
| 397 |
+
self.key = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
|
| 398 |
+
self.value = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
|
| 399 |
+
|
| 400 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 401 |
+
|
| 402 |
+
def forward(
|
| 403 |
+
self,
|
| 404 |
+
hidden_states: torch.Tensor,
|
| 405 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 406 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 407 |
+
output_attentions: Optional[bool] = False,
|
| 408 |
+
) -> tuple[torch.Tensor]:
|
| 409 |
+
batch_size, dim, num_channels = hidden_states.shape
|
| 410 |
+
hidden_shape = (batch_size, dim, -1, self.attention_head_size)
|
| 411 |
+
|
| 412 |
+
query_layer = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 413 |
+
key_layer = self.key(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 414 |
+
value_layer = self.value(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 415 |
+
|
| 416 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 417 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 418 |
+
|
| 419 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 420 |
+
|
| 421 |
+
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)]
|
| 422 |
+
relative_position_bias = relative_position_bias.view(
|
| 423 |
+
self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
|
| 427 |
+
attention_scores = attention_scores + relative_position_bias.unsqueeze(0)
|
| 428 |
+
|
| 429 |
+
if attention_mask is not None:
|
| 430 |
+
# Apply the attention mask is (precomputed for all layers in ClapAudioModel forward() function)
|
| 431 |
+
mask_shape = attention_mask.shape[0]
|
| 432 |
+
attention_scores = attention_scores.view(
|
| 433 |
+
batch_size // mask_shape, mask_shape, self.num_attention_heads, dim, dim
|
| 434 |
+
)
|
| 435 |
+
attention_scores = attention_scores + attention_mask.unsqueeze(1).unsqueeze(0)
|
| 436 |
+
attention_scores = attention_scores.view(-1, self.num_attention_heads, dim, dim)
|
| 437 |
+
|
| 438 |
+
# Normalize the attention scores to probabilities.
|
| 439 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 440 |
+
|
| 441 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 442 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 443 |
+
attention_probs = self.dropout(attention_probs)
|
| 444 |
+
|
| 445 |
+
# Mask heads if we want to
|
| 446 |
+
if head_mask is not None:
|
| 447 |
+
attention_probs = attention_probs * head_mask
|
| 448 |
+
|
| 449 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 450 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 451 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 452 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 453 |
+
|
| 454 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 455 |
+
|
| 456 |
+
return outputs
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
# Copied from transformers.models.swin.modeling_swin.SwinSelfOutput with Swin->ClapAudio
|
| 460 |
+
class ClapAudioSelfOutput(nn.Module):
|
| 461 |
+
def __init__(self, config, dim):
|
| 462 |
+
super().__init__()
|
| 463 |
+
self.dense = nn.Linear(dim, dim)
|
| 464 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 465 |
+
|
| 466 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 467 |
+
hidden_states = self.dense(hidden_states)
|
| 468 |
+
hidden_states = self.dropout(hidden_states)
|
| 469 |
+
|
| 470 |
+
return hidden_states
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
# Copied from transformers.models.swin.modeling_swin.SwinAttention with Swin->ClapAudio
|
| 474 |
+
class ClapAudioAttention(nn.Module):
|
| 475 |
+
def __init__(self, config, dim, num_heads, window_size):
|
| 476 |
+
super().__init__()
|
| 477 |
+
self.self = ClapAudioSelfAttention(config, dim, num_heads, window_size)
|
| 478 |
+
self.output = ClapAudioSelfOutput(config, dim)
|
| 479 |
+
self.pruned_heads = set()
|
| 480 |
+
|
| 481 |
+
def prune_heads(self, heads):
|
| 482 |
+
if len(heads) == 0:
|
| 483 |
+
return
|
| 484 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 485 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
# Prune linear layers
|
| 489 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 490 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 491 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 492 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 493 |
+
|
| 494 |
+
# Update hyper params and store pruned heads
|
| 495 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 496 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 497 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 498 |
+
|
| 499 |
+
def forward(
|
| 500 |
+
self,
|
| 501 |
+
hidden_states: torch.Tensor,
|
| 502 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 503 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 504 |
+
output_attentions: Optional[bool] = False,
|
| 505 |
+
) -> tuple[torch.Tensor]:
|
| 506 |
+
self_outputs = self.self(hidden_states, attention_mask, head_mask, output_attentions)
|
| 507 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 508 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 509 |
+
return outputs
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
# Copied from transformers.models.swin.modeling_swin.SwinIntermediate with Swin->ClapAudio
|
| 513 |
+
class ClapAudioIntermediate(nn.Module):
|
| 514 |
+
def __init__(self, config, dim):
|
| 515 |
+
super().__init__()
|
| 516 |
+
self.dense = nn.Linear(dim, int(config.mlp_ratio * dim))
|
| 517 |
+
if isinstance(config.hidden_act, str):
|
| 518 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 519 |
+
else:
|
| 520 |
+
self.intermediate_act_fn = config.hidden_act
|
| 521 |
+
|
| 522 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 523 |
+
hidden_states = self.dense(hidden_states)
|
| 524 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 525 |
+
return hidden_states
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
# Copied from transformers.models.swin.modeling_swin.SwinOutput with Swin->ClapAudio
|
| 529 |
+
class ClapAudioOutput(nn.Module):
|
| 530 |
+
def __init__(self, config, dim):
|
| 531 |
+
super().__init__()
|
| 532 |
+
self.dense = nn.Linear(int(config.mlp_ratio * dim), dim)
|
| 533 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 534 |
+
|
| 535 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 536 |
+
hidden_states = self.dense(hidden_states)
|
| 537 |
+
hidden_states = self.dropout(hidden_states)
|
| 538 |
+
return hidden_states
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
# Copied from transformers.models.swin.modeling_swin.SwinLayer with SwinDropPath->ClapDropPath, Swin->ClapAudio
|
| 542 |
+
class ClapAudioLayer(nn.Module):
|
| 543 |
+
def __init__(self, config, dim, input_resolution, num_heads, drop_path_rate=0.0, shift_size=0):
|
| 544 |
+
super().__init__()
|
| 545 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 546 |
+
self.shift_size = shift_size
|
| 547 |
+
self.window_size = config.window_size
|
| 548 |
+
self.input_resolution = input_resolution
|
| 549 |
+
self.layernorm_before = nn.LayerNorm(dim, eps=config.layer_norm_eps)
|
| 550 |
+
self.attention = ClapAudioAttention(config, dim, num_heads, window_size=self.window_size)
|
| 551 |
+
self.drop_path = ClapDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
|
| 552 |
+
self.layernorm_after = nn.LayerNorm(dim, eps=config.layer_norm_eps)
|
| 553 |
+
self.intermediate = ClapAudioIntermediate(config, dim)
|
| 554 |
+
self.output = ClapAudioOutput(config, dim)
|
| 555 |
+
|
| 556 |
+
def set_shift_and_window_size(self, input_resolution):
|
| 557 |
+
if min(input_resolution) <= self.window_size:
|
| 558 |
+
# if window size is larger than input resolution, we don't partition windows
|
| 559 |
+
self.shift_size = torch_int(0)
|
| 560 |
+
self.window_size = (
|
| 561 |
+
torch.min(torch.tensor(input_resolution)) if torch.jit.is_tracing() else min(input_resolution)
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
def get_attn_mask(self, height, width, dtype, device):
|
| 565 |
+
if self.shift_size > 0:
|
| 566 |
+
# calculate attention mask for SW-MSA
|
| 567 |
+
img_mask = torch.zeros((1, height, width, 1), dtype=dtype, device=device)
|
| 568 |
+
height_slices = (
|
| 569 |
+
slice(0, -self.window_size),
|
| 570 |
+
slice(-self.window_size, -self.shift_size),
|
| 571 |
+
slice(-self.shift_size, None),
|
| 572 |
+
)
|
| 573 |
+
width_slices = (
|
| 574 |
+
slice(0, -self.window_size),
|
| 575 |
+
slice(-self.window_size, -self.shift_size),
|
| 576 |
+
slice(-self.shift_size, None),
|
| 577 |
+
)
|
| 578 |
+
count = 0
|
| 579 |
+
for height_slice in height_slices:
|
| 580 |
+
for width_slice in width_slices:
|
| 581 |
+
img_mask[:, height_slice, width_slice, :] = count
|
| 582 |
+
count += 1
|
| 583 |
+
|
| 584 |
+
mask_windows = window_partition(img_mask, self.window_size)
|
| 585 |
+
mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
|
| 586 |
+
attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
|
| 587 |
+
attn_mask = attn_mask.masked_fill(attn_mask != 0, -100.0).masked_fill(attn_mask == 0, 0.0)
|
| 588 |
+
else:
|
| 589 |
+
attn_mask = None
|
| 590 |
+
return attn_mask
|
| 591 |
+
|
| 592 |
+
def maybe_pad(self, hidden_states, height, width):
|
| 593 |
+
pad_right = (self.window_size - width % self.window_size) % self.window_size
|
| 594 |
+
pad_bottom = (self.window_size - height % self.window_size) % self.window_size
|
| 595 |
+
pad_values = (0, 0, 0, pad_right, 0, pad_bottom)
|
| 596 |
+
hidden_states = nn.functional.pad(hidden_states, pad_values)
|
| 597 |
+
return hidden_states, pad_values
|
| 598 |
+
|
| 599 |
+
def forward(
|
| 600 |
+
self,
|
| 601 |
+
hidden_states: torch.Tensor,
|
| 602 |
+
input_dimensions: tuple[int, int],
|
| 603 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 604 |
+
output_attentions: Optional[bool] = False,
|
| 605 |
+
always_partition: Optional[bool] = False,
|
| 606 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 607 |
+
if not always_partition:
|
| 608 |
+
self.set_shift_and_window_size(input_dimensions)
|
| 609 |
+
else:
|
| 610 |
+
pass
|
| 611 |
+
height, width = input_dimensions
|
| 612 |
+
batch_size, _, channels = hidden_states.size()
|
| 613 |
+
shortcut = hidden_states
|
| 614 |
+
|
| 615 |
+
hidden_states = self.layernorm_before(hidden_states)
|
| 616 |
+
|
| 617 |
+
hidden_states = hidden_states.view(batch_size, height, width, channels)
|
| 618 |
+
|
| 619 |
+
# pad hidden_states to multiples of window size
|
| 620 |
+
hidden_states, pad_values = self.maybe_pad(hidden_states, height, width)
|
| 621 |
+
|
| 622 |
+
_, height_pad, width_pad, _ = hidden_states.shape
|
| 623 |
+
# cyclic shift
|
| 624 |
+
if self.shift_size > 0:
|
| 625 |
+
shifted_hidden_states = torch.roll(hidden_states, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
|
| 626 |
+
else:
|
| 627 |
+
shifted_hidden_states = hidden_states
|
| 628 |
+
|
| 629 |
+
# partition windows
|
| 630 |
+
hidden_states_windows = window_partition(shifted_hidden_states, self.window_size)
|
| 631 |
+
hidden_states_windows = hidden_states_windows.view(-1, self.window_size * self.window_size, channels)
|
| 632 |
+
attn_mask = self.get_attn_mask(
|
| 633 |
+
height_pad, width_pad, dtype=hidden_states.dtype, device=hidden_states_windows.device
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
attention_outputs = self.attention(
|
| 637 |
+
hidden_states_windows, attn_mask, head_mask, output_attentions=output_attentions
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
attention_output = attention_outputs[0]
|
| 641 |
+
|
| 642 |
+
attention_windows = attention_output.view(-1, self.window_size, self.window_size, channels)
|
| 643 |
+
shifted_windows = window_reverse(attention_windows, self.window_size, height_pad, width_pad)
|
| 644 |
+
|
| 645 |
+
# reverse cyclic shift
|
| 646 |
+
if self.shift_size > 0:
|
| 647 |
+
attention_windows = torch.roll(shifted_windows, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
|
| 648 |
+
else:
|
| 649 |
+
attention_windows = shifted_windows
|
| 650 |
+
|
| 651 |
+
was_padded = pad_values[3] > 0 or pad_values[5] > 0
|
| 652 |
+
if was_padded:
|
| 653 |
+
attention_windows = attention_windows[:, :height, :width, :].contiguous()
|
| 654 |
+
|
| 655 |
+
attention_windows = attention_windows.view(batch_size, height * width, channels)
|
| 656 |
+
|
| 657 |
+
hidden_states = shortcut + self.drop_path(attention_windows)
|
| 658 |
+
|
| 659 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 660 |
+
layer_output = self.intermediate(layer_output)
|
| 661 |
+
layer_output = hidden_states + self.output(layer_output)
|
| 662 |
+
|
| 663 |
+
layer_outputs = (layer_output, attention_outputs[1]) if output_attentions else (layer_output,)
|
| 664 |
+
return layer_outputs
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
# Copied from transformers.models.swin.modeling_swin.SwinStage with Swin->ClapAudio
|
| 668 |
+
class ClapAudioStage(GradientCheckpointingLayer):
|
| 669 |
+
def __init__(self, config, dim, input_resolution, depth, num_heads, drop_path, downsample):
|
| 670 |
+
super().__init__()
|
| 671 |
+
self.config = config
|
| 672 |
+
self.dim = dim
|
| 673 |
+
self.blocks = nn.ModuleList(
|
| 674 |
+
[
|
| 675 |
+
ClapAudioLayer(
|
| 676 |
+
config=config,
|
| 677 |
+
dim=dim,
|
| 678 |
+
input_resolution=input_resolution,
|
| 679 |
+
num_heads=num_heads,
|
| 680 |
+
drop_path_rate=drop_path[i],
|
| 681 |
+
shift_size=0 if (i % 2 == 0) else config.window_size // 2,
|
| 682 |
+
)
|
| 683 |
+
for i in range(depth)
|
| 684 |
+
]
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
# patch merging layer
|
| 688 |
+
if downsample is not None:
|
| 689 |
+
self.downsample = downsample(input_resolution, dim=dim, norm_layer=nn.LayerNorm)
|
| 690 |
+
else:
|
| 691 |
+
self.downsample = None
|
| 692 |
+
|
| 693 |
+
self.pointing = False
|
| 694 |
+
|
| 695 |
+
def forward(
|
| 696 |
+
self,
|
| 697 |
+
hidden_states: torch.Tensor,
|
| 698 |
+
input_dimensions: tuple[int, int],
|
| 699 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 700 |
+
output_attentions: Optional[bool] = False,
|
| 701 |
+
always_partition: Optional[bool] = False,
|
| 702 |
+
) -> tuple[torch.Tensor]:
|
| 703 |
+
height, width = input_dimensions
|
| 704 |
+
for i, layer_module in enumerate(self.blocks):
|
| 705 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 706 |
+
|
| 707 |
+
layer_outputs = layer_module(
|
| 708 |
+
hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
hidden_states = layer_outputs[0]
|
| 712 |
+
|
| 713 |
+
hidden_states_before_downsampling = hidden_states
|
| 714 |
+
if self.downsample is not None:
|
| 715 |
+
height_downsampled, width_downsampled = (height + 1) // 2, (width + 1) // 2
|
| 716 |
+
output_dimensions = (height, width, height_downsampled, width_downsampled)
|
| 717 |
+
hidden_states = self.downsample(hidden_states_before_downsampling, input_dimensions)
|
| 718 |
+
else:
|
| 719 |
+
output_dimensions = (height, width, height, width)
|
| 720 |
+
|
| 721 |
+
stage_outputs = (hidden_states, hidden_states_before_downsampling, output_dimensions)
|
| 722 |
+
|
| 723 |
+
if output_attentions:
|
| 724 |
+
stage_outputs += layer_outputs[1:]
|
| 725 |
+
return stage_outputs
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
# Copied from transformers.models.swin.modeling_swin.SwinPatchMerging with Swin->ClapAudio
|
| 729 |
+
class ClapAudioPatchMerging(nn.Module):
|
| 730 |
+
"""
|
| 731 |
+
Patch Merging Layer.
|
| 732 |
+
|
| 733 |
+
Args:
|
| 734 |
+
input_resolution (`tuple[int]`):
|
| 735 |
+
Resolution of input feature.
|
| 736 |
+
dim (`int`):
|
| 737 |
+
Number of input channels.
|
| 738 |
+
norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
|
| 739 |
+
Normalization layer class.
|
| 740 |
+
"""
|
| 741 |
+
|
| 742 |
+
def __init__(self, input_resolution: tuple[int], dim: int, norm_layer: nn.Module = nn.LayerNorm) -> None:
|
| 743 |
+
super().__init__()
|
| 744 |
+
self.input_resolution = input_resolution
|
| 745 |
+
self.dim = dim
|
| 746 |
+
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
|
| 747 |
+
self.norm = norm_layer(4 * dim)
|
| 748 |
+
|
| 749 |
+
def maybe_pad(self, input_feature, height, width):
|
| 750 |
+
should_pad = (height % 2 == 1) or (width % 2 == 1)
|
| 751 |
+
if should_pad:
|
| 752 |
+
pad_values = (0, 0, 0, width % 2, 0, height % 2)
|
| 753 |
+
input_feature = nn.functional.pad(input_feature, pad_values)
|
| 754 |
+
|
| 755 |
+
return input_feature
|
| 756 |
+
|
| 757 |
+
def forward(self, input_feature: torch.Tensor, input_dimensions: tuple[int, int]) -> torch.Tensor:
|
| 758 |
+
height, width = input_dimensions
|
| 759 |
+
# `dim` is height * width
|
| 760 |
+
batch_size, dim, num_channels = input_feature.shape
|
| 761 |
+
|
| 762 |
+
input_feature = input_feature.view(batch_size, height, width, num_channels)
|
| 763 |
+
# pad input to be divisible by width and height, if needed
|
| 764 |
+
input_feature = self.maybe_pad(input_feature, height, width)
|
| 765 |
+
# [batch_size, height/2, width/2, num_channels]
|
| 766 |
+
input_feature_0 = input_feature[:, 0::2, 0::2, :]
|
| 767 |
+
# [batch_size, height/2, width/2, num_channels]
|
| 768 |
+
input_feature_1 = input_feature[:, 1::2, 0::2, :]
|
| 769 |
+
# [batch_size, height/2, width/2, num_channels]
|
| 770 |
+
input_feature_2 = input_feature[:, 0::2, 1::2, :]
|
| 771 |
+
# [batch_size, height/2, width/2, num_channels]
|
| 772 |
+
input_feature_3 = input_feature[:, 1::2, 1::2, :]
|
| 773 |
+
# batch_size height/2 width/2 4*num_channels
|
| 774 |
+
input_feature = torch.cat([input_feature_0, input_feature_1, input_feature_2, input_feature_3], -1)
|
| 775 |
+
input_feature = input_feature.view(batch_size, -1, 4 * num_channels) # batch_size height/2*width/2 4*C
|
| 776 |
+
|
| 777 |
+
input_feature = self.norm(input_feature)
|
| 778 |
+
input_feature = self.reduction(input_feature)
|
| 779 |
+
|
| 780 |
+
return input_feature
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
class ClapAudioEncoder(nn.Module):
|
| 784 |
+
def __init__(self, config):
|
| 785 |
+
super().__init__()
|
| 786 |
+
self.num_layers = len(config.depths)
|
| 787 |
+
|
| 788 |
+
self.config = config
|
| 789 |
+
self.patch_embed = ClapAudioPatchEmbed(config)
|
| 790 |
+
self.enable_fusion = config.enable_fusion
|
| 791 |
+
self.patch_stride = self.patch_embed.patch_stride
|
| 792 |
+
self.spec_size = config.spec_size
|
| 793 |
+
self.freq_ratio = config.spec_size // config.num_mel_bins
|
| 794 |
+
|
| 795 |
+
self.num_features = int(config.patch_embeds_hidden_size * 2 ** (self.num_layers - 1))
|
| 796 |
+
|
| 797 |
+
drop_path_rate = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")]
|
| 798 |
+
|
| 799 |
+
grid_size = self.patch_embed.grid_size
|
| 800 |
+
self.input_resolutions = [(grid_size[0] // (2**i), grid_size[1] // (2**i)) for i in range(self.num_layers)]
|
| 801 |
+
|
| 802 |
+
self.layers = nn.ModuleList(
|
| 803 |
+
[
|
| 804 |
+
ClapAudioStage(
|
| 805 |
+
config=config,
|
| 806 |
+
dim=int(config.patch_embeds_hidden_size * 2**i_layer),
|
| 807 |
+
input_resolution=self.input_resolutions[i_layer],
|
| 808 |
+
depth=config.depths[i_layer],
|
| 809 |
+
num_heads=config.num_attention_heads[i_layer],
|
| 810 |
+
drop_path=drop_path_rate[sum(config.depths[:i_layer]) : sum(config.depths[: i_layer + 1])],
|
| 811 |
+
downsample=ClapAudioPatchMerging if (i_layer < self.num_layers - 1) else None,
|
| 812 |
+
)
|
| 813 |
+
for i_layer in range(self.num_layers)
|
| 814 |
+
]
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
self.gradient_checkpointing = False
|
| 818 |
+
|
| 819 |
+
self.batch_norm = nn.BatchNorm2d(config.num_mel_bins)
|
| 820 |
+
self.norm = nn.LayerNorm(self.num_features)
|
| 821 |
+
self.depths = config.depths
|
| 822 |
+
self.avgpool = nn.AdaptiveAvgPool1d(1)
|
| 823 |
+
|
| 824 |
+
def reshape_mel2img(self, normalized_input_features):
|
| 825 |
+
"""
|
| 826 |
+
The input is 4 normalized log mel spectrograms. It is reshape to the common shape of images. Each channel
|
| 827 |
+
should represent 1 of the 4 crops of the spectrogram. For more details, refer to the [`ClapFeatureExtractor`].
|
| 828 |
+
"""
|
| 829 |
+
_, _, time_length, freq_length = normalized_input_features.shape
|
| 830 |
+
|
| 831 |
+
spec_width = int(self.spec_size * self.freq_ratio)
|
| 832 |
+
spec_height = self.spec_size // self.freq_ratio
|
| 833 |
+
|
| 834 |
+
if time_length > spec_width or freq_length > spec_height:
|
| 835 |
+
raise ValueError("the wav size should be less than or equal to the swin input size")
|
| 836 |
+
|
| 837 |
+
# to avoid bicubic zero error
|
| 838 |
+
if time_length < spec_width:
|
| 839 |
+
normalized_input_features = nn.functional.interpolate(
|
| 840 |
+
normalized_input_features, (spec_width, freq_length), mode="bicubic", align_corners=True
|
| 841 |
+
)
|
| 842 |
+
if freq_length < spec_height:
|
| 843 |
+
normalized_input_features = nn.functional.interpolate(
|
| 844 |
+
normalized_input_features, (time_length, spec_height), mode="bicubic", align_corners=True
|
| 845 |
+
)
|
| 846 |
+
|
| 847 |
+
batch, channels, time, freq = normalized_input_features.shape
|
| 848 |
+
|
| 849 |
+
# batch_size, channels, spec_width, spec_height --> batch_size, channels, spec_height * freq_ratio, spec_width // freq_ratio
|
| 850 |
+
normalized_input_features = normalized_input_features.reshape(
|
| 851 |
+
batch, channels * self.freq_ratio, time // self.freq_ratio, freq
|
| 852 |
+
)
|
| 853 |
+
normalized_input_features = normalized_input_features.permute(0, 1, 3, 2).contiguous()
|
| 854 |
+
normalized_input_features = normalized_input_features.reshape(
|
| 855 |
+
batch, channels, freq * self.freq_ratio, time // self.freq_ratio
|
| 856 |
+
)
|
| 857 |
+
|
| 858 |
+
return normalized_input_features
|
| 859 |
+
|
| 860 |
+
def forward(
|
| 861 |
+
self,
|
| 862 |
+
input_features,
|
| 863 |
+
is_longer: Optional[torch.FloatTensor] = None,
|
| 864 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 865 |
+
output_attentions: Optional[bool] = False,
|
| 866 |
+
output_hidden_states: Optional[bool] = False,
|
| 867 |
+
output_hidden_states_before_downsampling: Optional[bool] = False,
|
| 868 |
+
always_partition: Optional[bool] = False,
|
| 869 |
+
return_dict: Optional[bool] = True,
|
| 870 |
+
) -> Union[tuple, ClapAudioModelOutput]:
|
| 871 |
+
input_features = input_features.transpose(1, 3)
|
| 872 |
+
normalized_input_features = self.batch_norm(input_features)
|
| 873 |
+
normalized_input_features = normalized_input_features.transpose(1, 3)
|
| 874 |
+
|
| 875 |
+
is_longer_list_idx = None
|
| 876 |
+
if self.enable_fusion:
|
| 877 |
+
is_longer_list = is_longer.to(input_features.device)
|
| 878 |
+
is_longer_list_idx = torch.where(is_longer_list == 1)[0]
|
| 879 |
+
|
| 880 |
+
hidden_states = self.reshape_mel2img(normalized_input_features)
|
| 881 |
+
|
| 882 |
+
frames_num = hidden_states.shape[2]
|
| 883 |
+
|
| 884 |
+
hidden_states = self.patch_embed(hidden_states, is_longer_list_idx)
|
| 885 |
+
|
| 886 |
+
all_hidden_states = () if output_hidden_states else None
|
| 887 |
+
all_reshaped_hidden_states = () if output_hidden_states else None
|
| 888 |
+
all_self_attentions = () if output_attentions else None
|
| 889 |
+
|
| 890 |
+
input_dimensions = self.input_resolutions[0]
|
| 891 |
+
|
| 892 |
+
if output_hidden_states:
|
| 893 |
+
batch_size, _, hidden_size = hidden_states.shape
|
| 894 |
+
# rearrange batch_size (height width) channels -> batch_size channel height width
|
| 895 |
+
reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
|
| 896 |
+
reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
|
| 897 |
+
all_hidden_states += (hidden_states,)
|
| 898 |
+
all_reshaped_hidden_states += (reshaped_hidden_state,)
|
| 899 |
+
|
| 900 |
+
for i, layer_module in enumerate(self.layers):
|
| 901 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 902 |
+
|
| 903 |
+
input_dimensions = self.input_resolutions[i]
|
| 904 |
+
|
| 905 |
+
layer_outputs = layer_module(
|
| 906 |
+
hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition
|
| 907 |
+
)
|
| 908 |
+
|
| 909 |
+
hidden_states = layer_outputs[0]
|
| 910 |
+
|
| 911 |
+
hidden_states_before_downsampling = layer_outputs[1]
|
| 912 |
+
output_dimensions = layer_outputs[2]
|
| 913 |
+
|
| 914 |
+
input_dimensions = (output_dimensions[-2], output_dimensions[-1])
|
| 915 |
+
|
| 916 |
+
if output_hidden_states and output_hidden_states_before_downsampling:
|
| 917 |
+
batch_size, _, hidden_size = hidden_states_before_downsampling.shape
|
| 918 |
+
# rearrange batch_size (height width) channels -> batch_size channel height width
|
| 919 |
+
# here we use the original (not downsampled) height and width
|
| 920 |
+
reshaped_hidden_state = hidden_states_before_downsampling.view(
|
| 921 |
+
batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size
|
| 922 |
+
)
|
| 923 |
+
reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
|
| 924 |
+
all_hidden_states += (hidden_states_before_downsampling,)
|
| 925 |
+
all_reshaped_hidden_states += (reshaped_hidden_state,)
|
| 926 |
+
elif output_hidden_states and not output_hidden_states_before_downsampling:
|
| 927 |
+
batch_size, _, hidden_size = hidden_states.shape
|
| 928 |
+
# rearrange batch_size (height width) channels -> batch_size channel height width
|
| 929 |
+
reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
|
| 930 |
+
reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
|
| 931 |
+
all_hidden_states += (hidden_states,)
|
| 932 |
+
all_reshaped_hidden_states += (reshaped_hidden_state,)
|
| 933 |
+
|
| 934 |
+
if output_attentions:
|
| 935 |
+
all_self_attentions += layer_outputs[3:]
|
| 936 |
+
|
| 937 |
+
last_hidden_state = self.norm(hidden_states)
|
| 938 |
+
|
| 939 |
+
batch_size, _, n_channels = last_hidden_state.shape
|
| 940 |
+
|
| 941 |
+
freq_shape = frames_num // (2 ** (len(self.depths) - 1)) // self.patch_stride[0]
|
| 942 |
+
temporal_shape = frames_num // (2 ** (len(self.depths) - 1)) // self.patch_stride[1]
|
| 943 |
+
|
| 944 |
+
last_hidden_state = (
|
| 945 |
+
last_hidden_state.permute(0, 2, 1).contiguous().reshape(batch_size, n_channels, freq_shape, temporal_shape)
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
batch_size, n_channels, n_frequencies, n_temp = last_hidden_state.shape
|
| 949 |
+
# group 2D CNN
|
| 950 |
+
c_freq_bin = n_frequencies // self.freq_ratio
|
| 951 |
+
last_hidden_state = last_hidden_state.reshape(
|
| 952 |
+
batch_size, n_channels, n_frequencies // c_freq_bin, c_freq_bin, n_temp
|
| 953 |
+
)
|
| 954 |
+
last_hidden_state = (
|
| 955 |
+
last_hidden_state.permute(0, 1, 3, 2, 4).contiguous().reshape(batch_size, n_channels, c_freq_bin, -1)
|
| 956 |
+
)
|
| 957 |
+
latent_output = self.avgpool(torch.flatten(last_hidden_state, 2))
|
| 958 |
+
latent_output = torch.flatten(latent_output, 1)
|
| 959 |
+
|
| 960 |
+
if not return_dict:
|
| 961 |
+
return tuple(
|
| 962 |
+
v
|
| 963 |
+
for v in [
|
| 964 |
+
last_hidden_state,
|
| 965 |
+
latent_output,
|
| 966 |
+
all_reshaped_hidden_states,
|
| 967 |
+
all_self_attentions,
|
| 968 |
+
]
|
| 969 |
+
if v is not None
|
| 970 |
+
)
|
| 971 |
+
|
| 972 |
+
return BaseModelOutputWithPooling(
|
| 973 |
+
last_hidden_state=last_hidden_state,
|
| 974 |
+
pooler_output=latent_output,
|
| 975 |
+
hidden_states=all_reshaped_hidden_states,
|
| 976 |
+
attentions=all_self_attentions,
|
| 977 |
+
)
|
| 978 |
+
|
| 979 |
+
|
| 980 |
+
class ClapProjectionLayer(nn.Module):
|
| 981 |
+
def __init__(self, config: Union[ClapAudioConfig, ClapTextConfig]):
|
| 982 |
+
super().__init__()
|
| 983 |
+
self.config = config
|
| 984 |
+
hidden_size = config.hidden_size
|
| 985 |
+
projection_dim = config.projection_dim
|
| 986 |
+
|
| 987 |
+
self.linear1 = nn.Linear(hidden_size, projection_dim)
|
| 988 |
+
self.activation = ACT2FN[config.projection_hidden_act]
|
| 989 |
+
self.linear2 = nn.Linear(projection_dim, projection_dim)
|
| 990 |
+
|
| 991 |
+
def forward(self, hidden_states):
|
| 992 |
+
hidden_states = self.linear1(hidden_states)
|
| 993 |
+
hidden_states = self.activation(hidden_states)
|
| 994 |
+
hidden_states = self.linear2(hidden_states)
|
| 995 |
+
return hidden_states
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->ClapText, persistent=False->persistent=True
|
| 999 |
+
class ClapTextEmbeddings(nn.Module):
|
| 1000 |
+
"""
|
| 1001 |
+
Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
|
| 1002 |
+
"""
|
| 1003 |
+
|
| 1004 |
+
# Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__
|
| 1005 |
+
def __init__(self, config):
|
| 1006 |
+
super().__init__()
|
| 1007 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 1008 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 1009 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 1010 |
+
|
| 1011 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 1012 |
+
# any TensorFlow checkpoint file
|
| 1013 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 1014 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 1015 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 1016 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 1017 |
+
self.register_buffer(
|
| 1018 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=True
|
| 1019 |
+
)
|
| 1020 |
+
self.register_buffer(
|
| 1021 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=True
|
| 1022 |
+
)
|
| 1023 |
+
|
| 1024 |
+
# End copy
|
| 1025 |
+
self.padding_idx = config.pad_token_id
|
| 1026 |
+
self.position_embeddings = nn.Embedding(
|
| 1027 |
+
config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
|
| 1028 |
+
)
|
| 1029 |
+
|
| 1030 |
+
def forward(
|
| 1031 |
+
self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
|
| 1032 |
+
):
|
| 1033 |
+
if position_ids is None:
|
| 1034 |
+
if input_ids is not None:
|
| 1035 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
| 1036 |
+
position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
|
| 1037 |
+
else:
|
| 1038 |
+
position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
|
| 1039 |
+
|
| 1040 |
+
if input_ids is not None:
|
| 1041 |
+
input_shape = input_ids.size()
|
| 1042 |
+
else:
|
| 1043 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1044 |
+
|
| 1045 |
+
seq_length = input_shape[1]
|
| 1046 |
+
|
| 1047 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 1048 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 1049 |
+
# issue #5664
|
| 1050 |
+
if token_type_ids is None:
|
| 1051 |
+
if hasattr(self, "token_type_ids"):
|
| 1052 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 1053 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 1054 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 1055 |
+
else:
|
| 1056 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 1057 |
+
|
| 1058 |
+
if inputs_embeds is None:
|
| 1059 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 1060 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 1061 |
+
|
| 1062 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 1063 |
+
if self.position_embedding_type == "absolute":
|
| 1064 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 1065 |
+
embeddings += position_embeddings
|
| 1066 |
+
embeddings = self.LayerNorm(embeddings)
|
| 1067 |
+
embeddings = self.dropout(embeddings)
|
| 1068 |
+
return embeddings
|
| 1069 |
+
|
| 1070 |
+
def create_position_ids_from_inputs_embeds(self, inputs_embeds):
|
| 1071 |
+
"""
|
| 1072 |
+
We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
|
| 1073 |
+
|
| 1074 |
+
Args:
|
| 1075 |
+
inputs_embeds: torch.Tensor
|
| 1076 |
+
|
| 1077 |
+
Returns: torch.Tensor
|
| 1078 |
+
"""
|
| 1079 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1080 |
+
sequence_length = input_shape[1]
|
| 1081 |
+
|
| 1082 |
+
position_ids = torch.arange(
|
| 1083 |
+
self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
|
| 1084 |
+
)
|
| 1085 |
+
return position_ids.unsqueeze(0).expand(input_shape)
|
| 1086 |
+
|
| 1087 |
+
|
| 1088 |
+
# Copied from transformers.models.align.modeling_align.eager_attention_forward
|
| 1089 |
+
def eager_attention_forward(
|
| 1090 |
+
module: nn.Module,
|
| 1091 |
+
query: torch.Tensor,
|
| 1092 |
+
key: torch.Tensor,
|
| 1093 |
+
value: torch.Tensor,
|
| 1094 |
+
attention_mask: Optional[torch.Tensor],
|
| 1095 |
+
scaling: float,
|
| 1096 |
+
dropout: float = 0.0,
|
| 1097 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1098 |
+
**kwargs,
|
| 1099 |
+
):
|
| 1100 |
+
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
| 1101 |
+
if attention_mask is not None:
|
| 1102 |
+
causal_mask = attention_mask[:, :, :, : key.shape[-2]]
|
| 1103 |
+
attn_weights = attn_weights + causal_mask
|
| 1104 |
+
|
| 1105 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 1106 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 1107 |
+
|
| 1108 |
+
if head_mask is not None:
|
| 1109 |
+
attn_weights = attn_weights * head_mask.view(1, -1, 1, 1)
|
| 1110 |
+
|
| 1111 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 1112 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 1113 |
+
return attn_output, attn_weights
|
| 1114 |
+
|
| 1115 |
+
|
| 1116 |
+
# Copied from transformers.models.align.modeling_align.AlignTextSelfAttention with Align->Clap
|
| 1117 |
+
class ClapTextSelfAttention(nn.Module):
|
| 1118 |
+
def __init__(self, config):
|
| 1119 |
+
super().__init__()
|
| 1120 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 1121 |
+
raise ValueError(
|
| 1122 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 1123 |
+
f"heads ({config.num_attention_heads})"
|
| 1124 |
+
)
|
| 1125 |
+
|
| 1126 |
+
self.config = config
|
| 1127 |
+
self.num_attention_heads = config.num_attention_heads
|
| 1128 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 1129 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 1130 |
+
|
| 1131 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 1132 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 1133 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 1134 |
+
|
| 1135 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 1136 |
+
self.attention_dropout = config.attention_probs_dropout_prob
|
| 1137 |
+
self.scaling = self.attention_head_size**-0.5
|
| 1138 |
+
|
| 1139 |
+
def forward(
|
| 1140 |
+
self,
|
| 1141 |
+
hidden_states: torch.Tensor,
|
| 1142 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1143 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1144 |
+
output_attentions: Optional[bool] = False,
|
| 1145 |
+
**kwargs,
|
| 1146 |
+
) -> tuple[torch.Tensor]:
|
| 1147 |
+
input_shape = hidden_states.shape[:-1]
|
| 1148 |
+
hidden_shape = (*input_shape, -1, self.attention_head_size)
|
| 1149 |
+
|
| 1150 |
+
query_states = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 1151 |
+
key_states = self.key(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 1152 |
+
value_states = self.value(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 1153 |
+
|
| 1154 |
+
attention_interface: Callable = eager_attention_forward
|
| 1155 |
+
if self.config._attn_implementation != "eager":
|
| 1156 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 1157 |
+
|
| 1158 |
+
attn_output, attn_weights = attention_interface(
|
| 1159 |
+
self,
|
| 1160 |
+
query_states,
|
| 1161 |
+
key_states,
|
| 1162 |
+
value_states,
|
| 1163 |
+
attention_mask,
|
| 1164 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 1165 |
+
scaling=self.scaling,
|
| 1166 |
+
head_mask=head_mask,
|
| 1167 |
+
**kwargs,
|
| 1168 |
+
)
|
| 1169 |
+
|
| 1170 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 1171 |
+
outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
|
| 1172 |
+
return outputs
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput
|
| 1176 |
+
class ClapTextSelfOutput(nn.Module):
|
| 1177 |
+
def __init__(self, config):
|
| 1178 |
+
super().__init__()
|
| 1179 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 1180 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 1181 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 1182 |
+
|
| 1183 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 1184 |
+
hidden_states = self.dense(hidden_states)
|
| 1185 |
+
hidden_states = self.dropout(hidden_states)
|
| 1186 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 1187 |
+
return hidden_states
|
| 1188 |
+
|
| 1189 |
+
|
| 1190 |
+
# Copied from transformers.models.align.modeling_align.AlignTextAttention with Align->Clap
|
| 1191 |
+
class ClapTextAttention(nn.Module):
|
| 1192 |
+
def __init__(self, config):
|
| 1193 |
+
super().__init__()
|
| 1194 |
+
self.self = ClapTextSelfAttention(config)
|
| 1195 |
+
self.output = ClapTextSelfOutput(config)
|
| 1196 |
+
self.pruned_heads = set()
|
| 1197 |
+
|
| 1198 |
+
def prune_heads(self, heads):
|
| 1199 |
+
if len(heads) == 0:
|
| 1200 |
+
return
|
| 1201 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 1202 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 1203 |
+
)
|
| 1204 |
+
|
| 1205 |
+
# Prune linear layers
|
| 1206 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 1207 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 1208 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 1209 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 1210 |
+
|
| 1211 |
+
# Update hyper params and store pruned heads
|
| 1212 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 1213 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 1214 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 1215 |
+
|
| 1216 |
+
def forward(
|
| 1217 |
+
self,
|
| 1218 |
+
hidden_states: torch.Tensor,
|
| 1219 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1220 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1221 |
+
output_attentions: Optional[bool] = False,
|
| 1222 |
+
**kwargs,
|
| 1223 |
+
) -> tuple[torch.Tensor]:
|
| 1224 |
+
self_outputs = self.self(
|
| 1225 |
+
hidden_states,
|
| 1226 |
+
attention_mask=attention_mask,
|
| 1227 |
+
head_mask=head_mask,
|
| 1228 |
+
output_attentions=output_attentions,
|
| 1229 |
+
**kwargs,
|
| 1230 |
+
)
|
| 1231 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 1232 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 1233 |
+
return outputs
|
| 1234 |
+
|
| 1235 |
+
|
| 1236 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate
|
| 1237 |
+
class ClapTextIntermediate(nn.Module):
|
| 1238 |
+
def __init__(self, config):
|
| 1239 |
+
super().__init__()
|
| 1240 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 1241 |
+
if isinstance(config.hidden_act, str):
|
| 1242 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 1243 |
+
else:
|
| 1244 |
+
self.intermediate_act_fn = config.hidden_act
|
| 1245 |
+
|
| 1246 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 1247 |
+
hidden_states = self.dense(hidden_states)
|
| 1248 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 1249 |
+
return hidden_states
|
| 1250 |
+
|
| 1251 |
+
|
| 1252 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput
|
| 1253 |
+
class ClapTextOutput(nn.Module):
|
| 1254 |
+
def __init__(self, config):
|
| 1255 |
+
super().__init__()
|
| 1256 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 1257 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 1258 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 1259 |
+
|
| 1260 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 1261 |
+
hidden_states = self.dense(hidden_states)
|
| 1262 |
+
hidden_states = self.dropout(hidden_states)
|
| 1263 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 1264 |
+
return hidden_states
|
| 1265 |
+
|
| 1266 |
+
|
| 1267 |
+
# Copied from transformers.models.align.modeling_align.AlignTextLayer with Align->Clap
|
| 1268 |
+
class ClapTextLayer(GradientCheckpointingLayer):
|
| 1269 |
+
def __init__(self, config):
|
| 1270 |
+
super().__init__()
|
| 1271 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 1272 |
+
self.seq_len_dim = 1
|
| 1273 |
+
self.attention = ClapTextAttention(config)
|
| 1274 |
+
self.intermediate = ClapTextIntermediate(config)
|
| 1275 |
+
self.output = ClapTextOutput(config)
|
| 1276 |
+
|
| 1277 |
+
def forward(
|
| 1278 |
+
self,
|
| 1279 |
+
hidden_states: torch.Tensor,
|
| 1280 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1281 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1282 |
+
output_attentions: Optional[bool] = False,
|
| 1283 |
+
**kwargs,
|
| 1284 |
+
) -> tuple[torch.Tensor]:
|
| 1285 |
+
self_attention_outputs = self.attention(
|
| 1286 |
+
hidden_states,
|
| 1287 |
+
attention_mask=attention_mask,
|
| 1288 |
+
head_mask=head_mask,
|
| 1289 |
+
output_attentions=output_attentions,
|
| 1290 |
+
**kwargs,
|
| 1291 |
+
)
|
| 1292 |
+
attention_output = self_attention_outputs[0]
|
| 1293 |
+
|
| 1294 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 1295 |
+
layer_output = apply_chunking_to_forward(
|
| 1296 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 1297 |
+
)
|
| 1298 |
+
outputs = (layer_output,) + outputs
|
| 1299 |
+
|
| 1300 |
+
return outputs
|
| 1301 |
+
|
| 1302 |
+
def feed_forward_chunk(self, attention_output):
|
| 1303 |
+
intermediate_output = self.intermediate(attention_output)
|
| 1304 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 1305 |
+
return layer_output
|
| 1306 |
+
|
| 1307 |
+
|
| 1308 |
+
# Copied from transformers.models.align.modeling_align.AlignTextEncoder with Align->Clap
|
| 1309 |
+
class ClapTextEncoder(nn.Module):
|
| 1310 |
+
def __init__(self, config):
|
| 1311 |
+
super().__init__()
|
| 1312 |
+
self.config = config
|
| 1313 |
+
self.layer = nn.ModuleList([ClapTextLayer(config) for i in range(config.num_hidden_layers)])
|
| 1314 |
+
self.gradient_checkpointing = False
|
| 1315 |
+
|
| 1316 |
+
@can_return_tuple
|
| 1317 |
+
def forward(
|
| 1318 |
+
self,
|
| 1319 |
+
hidden_states: torch.Tensor,
|
| 1320 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1321 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1322 |
+
output_attentions: Optional[bool] = False,
|
| 1323 |
+
output_hidden_states: Optional[bool] = False,
|
| 1324 |
+
return_dict: Optional[bool] = True,
|
| 1325 |
+
**kwargs,
|
| 1326 |
+
) -> Union[tuple[torch.Tensor], BaseModelOutput]:
|
| 1327 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1328 |
+
all_self_attentions = () if output_attentions else None
|
| 1329 |
+
|
| 1330 |
+
for i, layer_module in enumerate(self.layer):
|
| 1331 |
+
if output_hidden_states:
|
| 1332 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 1333 |
+
|
| 1334 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 1335 |
+
|
| 1336 |
+
layer_outputs = layer_module(
|
| 1337 |
+
hidden_states=hidden_states,
|
| 1338 |
+
attention_mask=attention_mask,
|
| 1339 |
+
head_mask=layer_head_mask,
|
| 1340 |
+
output_attentions=output_attentions,
|
| 1341 |
+
**kwargs,
|
| 1342 |
+
)
|
| 1343 |
+
|
| 1344 |
+
hidden_states = layer_outputs[0]
|
| 1345 |
+
if output_attentions:
|
| 1346 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 1347 |
+
|
| 1348 |
+
if output_hidden_states:
|
| 1349 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 1350 |
+
|
| 1351 |
+
return BaseModelOutput(
|
| 1352 |
+
last_hidden_state=hidden_states,
|
| 1353 |
+
hidden_states=all_hidden_states,
|
| 1354 |
+
attentions=all_self_attentions,
|
| 1355 |
+
)
|
| 1356 |
+
|
| 1357 |
+
|
| 1358 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler
|
| 1359 |
+
class ClapTextPooler(nn.Module):
|
| 1360 |
+
def __init__(self, config):
|
| 1361 |
+
super().__init__()
|
| 1362 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 1363 |
+
self.activation = nn.Tanh()
|
| 1364 |
+
|
| 1365 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 1366 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 1367 |
+
# to the first token.
|
| 1368 |
+
first_token_tensor = hidden_states[:, 0]
|
| 1369 |
+
pooled_output = self.dense(first_token_tensor)
|
| 1370 |
+
pooled_output = self.activation(pooled_output)
|
| 1371 |
+
return pooled_output
|
| 1372 |
+
|
| 1373 |
+
|
| 1374 |
+
@auto_docstring
|
| 1375 |
+
class ClapPreTrainedModel(PreTrainedModel):
|
| 1376 |
+
config: ClapConfig
|
| 1377 |
+
base_model_prefix = "clap"
|
| 1378 |
+
supports_gradient_checkpointing = False
|
| 1379 |
+
|
| 1380 |
+
def _init_weights(self, module: nn.Module):
|
| 1381 |
+
"""Initialize the weights"""
|
| 1382 |
+
factor = self.config.initializer_factor
|
| 1383 |
+
|
| 1384 |
+
if isinstance(module, ClapTextEmbeddings):
|
| 1385 |
+
module.position_embeddings.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
| 1386 |
+
module.token_type_embeddings.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
| 1387 |
+
elif isinstance(module, ClapModel):
|
| 1388 |
+
module.logit_scale_a.data.fill_(math.log(self.config.logit_scale_init_value))
|
| 1389 |
+
module.logit_scale_t.data.fill_(math.log(self.config.logit_scale_init_value))
|
| 1390 |
+
elif isinstance(module, nn.Embedding):
|
| 1391 |
+
module.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
| 1392 |
+
elif isinstance(module, (nn.LayerNorm, nn.BatchNorm2d)):
|
| 1393 |
+
module.bias.data.zero_()
|
| 1394 |
+
module.weight.data.fill_(1.0)
|
| 1395 |
+
elif isinstance(module, (nn.Conv2d, nn.Linear)):
|
| 1396 |
+
in_proj_std = (self.config.hidden_size**-0.5) * ((2 * self.config.num_hidden_layers) ** -0.5) * factor
|
| 1397 |
+
nn.init.normal_(module.weight, std=in_proj_std)
|
| 1398 |
+
if module.bias is not None:
|
| 1399 |
+
module.bias.data.zero_()
|
| 1400 |
+
elif isinstance(module, ClapAudioSelfAttention):
|
| 1401 |
+
module.relative_position_bias_table.data.zero_()
|
| 1402 |
+
|
| 1403 |
+
|
| 1404 |
+
class ClapAudioModel(ClapPreTrainedModel):
|
| 1405 |
+
config: ClapAudioConfig
|
| 1406 |
+
main_input_name = "input_features"
|
| 1407 |
+
|
| 1408 |
+
def __init__(self, config: ClapAudioConfig):
|
| 1409 |
+
super().__init__(config)
|
| 1410 |
+
self.audio_encoder = ClapAudioEncoder(config)
|
| 1411 |
+
# Initialize weights and apply final processing
|
| 1412 |
+
self.post_init()
|
| 1413 |
+
|
| 1414 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1415 |
+
return self.audio_encoder.patch_embed.proj
|
| 1416 |
+
|
| 1417 |
+
@auto_docstring
|
| 1418 |
+
def forward(
|
| 1419 |
+
self,
|
| 1420 |
+
input_features: Optional[torch.FloatTensor] = None,
|
| 1421 |
+
is_longer: Optional[torch.BoolTensor] = None,
|
| 1422 |
+
output_attentions: Optional[bool] = None,
|
| 1423 |
+
output_hidden_states: Optional[bool] = None,
|
| 1424 |
+
return_dict: Optional[bool] = None,
|
| 1425 |
+
) -> Union[tuple, BaseModelOutputWithPooling]:
|
| 1426 |
+
r"""
|
| 1427 |
+
is_longer (`torch.FloatTensor`, of shape `(batch_size, 1)`, *optional*):
|
| 1428 |
+
Whether the audio clip is longer than `max_length`. If `True`, a feature fusion will be enabled to enhance
|
| 1429 |
+
the features.
|
| 1430 |
+
|
| 1431 |
+
Examples:
|
| 1432 |
+
|
| 1433 |
+
```python
|
| 1434 |
+
>>> from datasets import load_dataset
|
| 1435 |
+
>>> from transformers import AutoProcessor, ClapAudioModel
|
| 1436 |
+
|
| 1437 |
+
>>> dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example")
|
| 1438 |
+
>>> audio_sample = dataset["train"]["audio"][0]["array"]
|
| 1439 |
+
|
| 1440 |
+
>>> model = ClapAudioModel.from_pretrained("laion/clap-htsat-fused")
|
| 1441 |
+
>>> processor = AutoProcessor.from_pretrained("laion/clap-htsat-fused")
|
| 1442 |
+
|
| 1443 |
+
>>> inputs = processor(audios=audio_sample, return_tensors="pt")
|
| 1444 |
+
|
| 1445 |
+
>>> outputs = model(**inputs)
|
| 1446 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 1447 |
+
```"""
|
| 1448 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1449 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1450 |
+
output_hidden_states = (
|
| 1451 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1452 |
+
)
|
| 1453 |
+
|
| 1454 |
+
return self.audio_encoder(
|
| 1455 |
+
input_features=input_features,
|
| 1456 |
+
is_longer=is_longer,
|
| 1457 |
+
output_attentions=output_attentions,
|
| 1458 |
+
output_hidden_states=output_hidden_states,
|
| 1459 |
+
return_dict=return_dict,
|
| 1460 |
+
)
|
| 1461 |
+
|
| 1462 |
+
|
| 1463 |
+
@auto_docstring(
|
| 1464 |
+
custom_intro="""
|
| 1465 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 1466 |
+
cross-attention is added between the self-attention layers, following the architecture described in *Attention is
|
| 1467 |
+
all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
|
| 1468 |
+
Kaiser and Illia Polosukhin.
|
| 1469 |
+
|
| 1470 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
| 1471 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
| 1472 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
| 1473 |
+
|
| 1474 |
+
.. _*Attention is all you need*: https://huggingface.co/papers/1706.03762
|
| 1475 |
+
"""
|
| 1476 |
+
)
|
| 1477 |
+
class ClapTextModel(ClapPreTrainedModel):
|
| 1478 |
+
config: ClapTextConfig
|
| 1479 |
+
|
| 1480 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 1481 |
+
r"""
|
| 1482 |
+
add_pooling_layer (bool, *optional*, defaults to `True`):
|
| 1483 |
+
Whether to add a pooling layer
|
| 1484 |
+
"""
|
| 1485 |
+
super().__init__(config)
|
| 1486 |
+
self.config = config
|
| 1487 |
+
|
| 1488 |
+
self.embeddings = ClapTextEmbeddings(config)
|
| 1489 |
+
self.encoder = ClapTextEncoder(config)
|
| 1490 |
+
|
| 1491 |
+
self.pooler = ClapTextPooler(config) if add_pooling_layer else None
|
| 1492 |
+
|
| 1493 |
+
# Initialize weights and apply final processing
|
| 1494 |
+
self.post_init()
|
| 1495 |
+
|
| 1496 |
+
def get_input_embeddings(self):
|
| 1497 |
+
return self.embeddings.word_embeddings
|
| 1498 |
+
|
| 1499 |
+
def set_input_embeddings(self, value):
|
| 1500 |
+
self.embeddings.word_embeddings = value
|
| 1501 |
+
|
| 1502 |
+
@can_return_tuple
|
| 1503 |
+
@auto_docstring
|
| 1504 |
+
def forward(
|
| 1505 |
+
self,
|
| 1506 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1507 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1508 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1509 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1510 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1511 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1512 |
+
output_attentions: Optional[bool] = None,
|
| 1513 |
+
output_hidden_states: Optional[bool] = None,
|
| 1514 |
+
return_dict: Optional[bool] = None,
|
| 1515 |
+
) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
| 1516 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1517 |
+
output_hidden_states = (
|
| 1518 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1519 |
+
)
|
| 1520 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1521 |
+
|
| 1522 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1523 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 1524 |
+
elif input_ids is not None:
|
| 1525 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 1526 |
+
input_shape = input_ids.size()
|
| 1527 |
+
elif inputs_embeds is not None:
|
| 1528 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1529 |
+
else:
|
| 1530 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1531 |
+
|
| 1532 |
+
batch_size, seq_length = input_shape
|
| 1533 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 1534 |
+
|
| 1535 |
+
if attention_mask is None:
|
| 1536 |
+
attention_mask = torch.ones(((batch_size, seq_length)), device=device)
|
| 1537 |
+
|
| 1538 |
+
if token_type_ids is None:
|
| 1539 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 1540 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 1541 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 1542 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 1543 |
+
else:
|
| 1544 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 1545 |
+
|
| 1546 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 1547 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 1548 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 1549 |
+
|
| 1550 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 1551 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 1552 |
+
|
| 1553 |
+
embedding_output = self.embeddings(
|
| 1554 |
+
input_ids=input_ids,
|
| 1555 |
+
position_ids=position_ids,
|
| 1556 |
+
token_type_ids=token_type_ids,
|
| 1557 |
+
inputs_embeds=inputs_embeds,
|
| 1558 |
+
)
|
| 1559 |
+
encoder_outputs = self.encoder(
|
| 1560 |
+
embedding_output,
|
| 1561 |
+
attention_mask=extended_attention_mask,
|
| 1562 |
+
head_mask=head_mask,
|
| 1563 |
+
output_attentions=output_attentions,
|
| 1564 |
+
output_hidden_states=output_hidden_states,
|
| 1565 |
+
return_dict=True,
|
| 1566 |
+
)
|
| 1567 |
+
sequence_output = encoder_outputs[0]
|
| 1568 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 1569 |
+
|
| 1570 |
+
return BaseModelOutputWithPooling(
|
| 1571 |
+
last_hidden_state=sequence_output,
|
| 1572 |
+
pooler_output=pooled_output,
|
| 1573 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1574 |
+
attentions=encoder_outputs.attentions,
|
| 1575 |
+
)
|
| 1576 |
+
|
| 1577 |
+
|
| 1578 |
+
@auto_docstring
|
| 1579 |
+
class ClapModel(ClapPreTrainedModel):
|
| 1580 |
+
config: ClapConfig
|
| 1581 |
+
|
| 1582 |
+
def __init__(self, config: ClapConfig):
|
| 1583 |
+
super().__init__(config)
|
| 1584 |
+
|
| 1585 |
+
if not isinstance(config.text_config, ClapTextConfig):
|
| 1586 |
+
raise TypeError(
|
| 1587 |
+
"config.text_config is expected to be of type ClapTextConfig but is of type"
|
| 1588 |
+
f" {type(config.text_config)}."
|
| 1589 |
+
)
|
| 1590 |
+
|
| 1591 |
+
if not isinstance(config.audio_config, ClapAudioConfig):
|
| 1592 |
+
raise TypeError(
|
| 1593 |
+
"config.audio_config is expected to be of type ClapAudioConfig but is of type"
|
| 1594 |
+
f" {type(config.audio_config)}."
|
| 1595 |
+
)
|
| 1596 |
+
|
| 1597 |
+
text_config = config.text_config
|
| 1598 |
+
audio_config = config.audio_config
|
| 1599 |
+
|
| 1600 |
+
self.logit_scale_a = nn.Parameter(torch.tensor(math.log(config.logit_scale_init_value)))
|
| 1601 |
+
self.logit_scale_t = nn.Parameter(torch.tensor(math.log(config.logit_scale_init_value)))
|
| 1602 |
+
|
| 1603 |
+
self.projection_dim = config.projection_dim
|
| 1604 |
+
|
| 1605 |
+
self.text_model = ClapTextModel(text_config)
|
| 1606 |
+
self.text_projection = ClapProjectionLayer(text_config)
|
| 1607 |
+
|
| 1608 |
+
self.audio_model = ClapAudioModel(audio_config)
|
| 1609 |
+
self.audio_projection = ClapProjectionLayer(audio_config)
|
| 1610 |
+
|
| 1611 |
+
# Initialize weights and apply final processing
|
| 1612 |
+
self.post_init()
|
| 1613 |
+
|
| 1614 |
+
@filter_out_non_signature_kwargs()
|
| 1615 |
+
@auto_docstring
|
| 1616 |
+
def get_text_features(
|
| 1617 |
+
self,
|
| 1618 |
+
input_ids: torch.Tensor,
|
| 1619 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1620 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1621 |
+
) -> torch.FloatTensor:
|
| 1622 |
+
r"""
|
| 1623 |
+
Returns:
|
| 1624 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
| 1625 |
+
applying the projection layer to the pooled output of [`ClapTextModel`].
|
| 1626 |
+
|
| 1627 |
+
Examples:
|
| 1628 |
+
|
| 1629 |
+
```python
|
| 1630 |
+
>>> import torch
|
| 1631 |
+
>>> from transformers import AutoTokenizer, ClapModel
|
| 1632 |
+
|
| 1633 |
+
>>> model = ClapModel.from_pretrained("laion/clap-htsat-unfused")
|
| 1634 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("laion/clap-htsat-unfused")
|
| 1635 |
+
|
| 1636 |
+
>>> inputs = tokenizer(["the sound of a cat", "the sound of a dog"], padding=True, return_tensors="pt")
|
| 1637 |
+
>>> with torch.inference_mode():
|
| 1638 |
+
... text_features = model.get_text_features(**inputs)
|
| 1639 |
+
```"""
|
| 1640 |
+
text_outputs: BaseModelOutputWithPooling = self.text_model(
|
| 1641 |
+
input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids
|
| 1642 |
+
)
|
| 1643 |
+
text_features = self.text_projection(text_outputs.pooler_output)
|
| 1644 |
+
text_features = F.normalize(text_features, dim=-1)
|
| 1645 |
+
|
| 1646 |
+
return text_features
|
| 1647 |
+
|
| 1648 |
+
@filter_out_non_signature_kwargs()
|
| 1649 |
+
@auto_docstring
|
| 1650 |
+
def get_audio_features(
|
| 1651 |
+
self,
|
| 1652 |
+
input_features: torch.Tensor,
|
| 1653 |
+
is_longer: Optional[torch.Tensor] = None,
|
| 1654 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1655 |
+
) -> torch.FloatTensor:
|
| 1656 |
+
r"""
|
| 1657 |
+
is_longer (`torch.FloatTensor`, of shape `(batch_size, 1)`, *optional*):
|
| 1658 |
+
Whether the audio clip is longer than `max_length`. If `True`, a feature fusion will be enabled to enhance
|
| 1659 |
+
the features.
|
| 1660 |
+
|
| 1661 |
+
Returns:
|
| 1662 |
+
audio_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The audio embeddings obtained by
|
| 1663 |
+
applying the projection layer to the pooled output of [`ClapAudioModel`].
|
| 1664 |
+
|
| 1665 |
+
Examples:
|
| 1666 |
+
|
| 1667 |
+
```python
|
| 1668 |
+
>>> import torch
|
| 1669 |
+
>>> from transformers import AutoFeatureExtractor, ClapModel
|
| 1670 |
+
|
| 1671 |
+
>>> model = ClapModel.from_pretrained("laion/clap-htsat-unfused")
|
| 1672 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("laion/clap-htsat-unfused")
|
| 1673 |
+
>>> random_audio = torch.rand((16_000))
|
| 1674 |
+
|
| 1675 |
+
>>> inputs = feature_extractor(random_audio, return_tensors="pt")
|
| 1676 |
+
>>> with torch.inference_mode():
|
| 1677 |
+
... audio_features = model.get_audio_features(**inputs)
|
| 1678 |
+
```"""
|
| 1679 |
+
audio_outputs: BaseModelOutputWithPooling = self.audio_model(
|
| 1680 |
+
input_features=input_features, is_longer=is_longer
|
| 1681 |
+
)
|
| 1682 |
+
audio_features = self.audio_projection(audio_outputs.pooler_output)
|
| 1683 |
+
audio_features = F.normalize(audio_features, dim=-1)
|
| 1684 |
+
|
| 1685 |
+
return audio_features
|
| 1686 |
+
|
| 1687 |
+
@can_return_tuple
|
| 1688 |
+
@auto_docstring
|
| 1689 |
+
def forward(
|
| 1690 |
+
self,
|
| 1691 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1692 |
+
input_features: Optional[torch.FloatTensor] = None,
|
| 1693 |
+
is_longer: Optional[torch.BoolTensor] = None,
|
| 1694 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1695 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1696 |
+
return_loss: Optional[bool] = None,
|
| 1697 |
+
output_attentions: Optional[bool] = None,
|
| 1698 |
+
output_hidden_states: Optional[bool] = None,
|
| 1699 |
+
return_dict: Optional[bool] = None,
|
| 1700 |
+
) -> Union[tuple, ClapOutput]:
|
| 1701 |
+
r"""
|
| 1702 |
+
is_longer (`torch.FloatTensor`, of shape `(batch_size, 1)`, *optional*):
|
| 1703 |
+
Whether the audio clip is longer than `max_length`. If `True`, a feature fusion will be enabled to enhance
|
| 1704 |
+
the features.
|
| 1705 |
+
return_loss (`bool`, *optional*):
|
| 1706 |
+
Whether or not to return the contrastive loss.
|
| 1707 |
+
|
| 1708 |
+
Examples:
|
| 1709 |
+
|
| 1710 |
+
```python
|
| 1711 |
+
>>> from datasets import load_dataset
|
| 1712 |
+
>>> from transformers import AutoProcessor, ClapModel
|
| 1713 |
+
|
| 1714 |
+
>>> dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example")
|
| 1715 |
+
>>> audio_sample = dataset["train"]["audio"][0]["array"]
|
| 1716 |
+
|
| 1717 |
+
>>> model = ClapModel.from_pretrained("laion/clap-htsat-unfused")
|
| 1718 |
+
>>> processor = AutoProcessor.from_pretrained("laion/clap-htsat-unfused")
|
| 1719 |
+
|
| 1720 |
+
>>> input_text = ["Sound of a dog", "Sound of vacuum cleaner"]
|
| 1721 |
+
|
| 1722 |
+
>>> inputs = processor(text=input_text, audios=audio_sample, return_tensors="pt", padding=True)
|
| 1723 |
+
|
| 1724 |
+
>>> outputs = model(**inputs)
|
| 1725 |
+
>>> logits_per_audio = outputs.logits_per_audio # this is the audio-text similarity score
|
| 1726 |
+
>>> probs = logits_per_audio.softmax(dim=-1) # we can take the softmax to get the label probabilities
|
| 1727 |
+
```"""
|
| 1728 |
+
# Use CLAP model's config for some fields (if specified) instead of those of audio & text components.
|
| 1729 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1730 |
+
output_hidden_states = (
|
| 1731 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1732 |
+
)
|
| 1733 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1734 |
+
|
| 1735 |
+
audio_outputs = self.audio_model(
|
| 1736 |
+
input_features=input_features,
|
| 1737 |
+
is_longer=is_longer,
|
| 1738 |
+
output_attentions=output_attentions,
|
| 1739 |
+
output_hidden_states=output_hidden_states,
|
| 1740 |
+
return_dict=True,
|
| 1741 |
+
)
|
| 1742 |
+
|
| 1743 |
+
text_outputs = self.text_model(
|
| 1744 |
+
input_ids=input_ids,
|
| 1745 |
+
attention_mask=attention_mask,
|
| 1746 |
+
position_ids=position_ids,
|
| 1747 |
+
output_attentions=output_attentions,
|
| 1748 |
+
output_hidden_states=output_hidden_states,
|
| 1749 |
+
return_dict=True,
|
| 1750 |
+
)
|
| 1751 |
+
|
| 1752 |
+
audio_embeds = audio_outputs[1] if not return_dict else audio_outputs.pooler_output
|
| 1753 |
+
audio_embeds = self.audio_projection(audio_embeds)
|
| 1754 |
+
|
| 1755 |
+
text_embeds = text_outputs[1] if not return_dict else text_outputs.pooler_output
|
| 1756 |
+
text_embeds = self.text_projection(text_embeds)
|
| 1757 |
+
|
| 1758 |
+
# normalized features
|
| 1759 |
+
audio_embeds = audio_embeds / audio_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1760 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1761 |
+
|
| 1762 |
+
# cosine similarity as logits
|
| 1763 |
+
logit_scale_text = self.logit_scale_t.exp()
|
| 1764 |
+
logit_scale_audio = self.logit_scale_a.exp()
|
| 1765 |
+
logits_per_text = torch.matmul(text_embeds, audio_embeds.t()) * logit_scale_text
|
| 1766 |
+
logits_per_audio = torch.matmul(audio_embeds, text_embeds.t()) * logit_scale_audio
|
| 1767 |
+
|
| 1768 |
+
loss = None
|
| 1769 |
+
if return_loss:
|
| 1770 |
+
caption_loss = contrastive_loss(logits_per_text)
|
| 1771 |
+
audio_loss = contrastive_loss(logits_per_audio.t())
|
| 1772 |
+
loss = (caption_loss + audio_loss) / 2.0
|
| 1773 |
+
|
| 1774 |
+
return ClapOutput(
|
| 1775 |
+
loss=loss,
|
| 1776 |
+
logits_per_audio=logits_per_audio,
|
| 1777 |
+
logits_per_text=logits_per_text,
|
| 1778 |
+
text_embeds=text_embeds,
|
| 1779 |
+
audio_embeds=audio_embeds,
|
| 1780 |
+
text_model_output=text_outputs,
|
| 1781 |
+
audio_model_output=audio_outputs,
|
| 1782 |
+
)
|
| 1783 |
+
|
| 1784 |
+
|
| 1785 |
+
@auto_docstring
|
| 1786 |
+
class ClapTextModelWithProjection(ClapPreTrainedModel):
|
| 1787 |
+
config: ClapTextConfig
|
| 1788 |
+
|
| 1789 |
+
def __init__(self, config: ClapTextConfig):
|
| 1790 |
+
super().__init__(config)
|
| 1791 |
+
self.text_model = ClapTextModel(config)
|
| 1792 |
+
self.text_projection = ClapProjectionLayer(config)
|
| 1793 |
+
# Initialize weights and apply final processing
|
| 1794 |
+
self.post_init()
|
| 1795 |
+
|
| 1796 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1797 |
+
return self.text_model.embeddings.word_embeddings
|
| 1798 |
+
|
| 1799 |
+
def set_input_embeddings(self, value):
|
| 1800 |
+
self.text_model.embeddings.word_embeddings = value
|
| 1801 |
+
|
| 1802 |
+
@can_return_tuple
|
| 1803 |
+
@auto_docstring
|
| 1804 |
+
def forward(
|
| 1805 |
+
self,
|
| 1806 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1807 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1808 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1809 |
+
output_attentions: Optional[bool] = None,
|
| 1810 |
+
output_hidden_states: Optional[bool] = None,
|
| 1811 |
+
return_dict: Optional[bool] = None,
|
| 1812 |
+
) -> Union[tuple, ClapTextModelOutput]:
|
| 1813 |
+
r"""
|
| 1814 |
+
Examples:
|
| 1815 |
+
|
| 1816 |
+
```python
|
| 1817 |
+
>>> from transformers import AutoTokenizer, ClapTextModelWithProjection
|
| 1818 |
+
|
| 1819 |
+
>>> model = ClapTextModelWithProjection.from_pretrained("laion/clap-htsat-unfused")
|
| 1820 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("laion/clap-htsat-unfused")
|
| 1821 |
+
|
| 1822 |
+
>>> inputs = tokenizer(["a sound of a cat", "a sound of a dog"], padding=True, return_tensors="pt")
|
| 1823 |
+
|
| 1824 |
+
>>> outputs = model(**inputs)
|
| 1825 |
+
>>> text_embeds = outputs.text_embeds
|
| 1826 |
+
```"""
|
| 1827 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1828 |
+
|
| 1829 |
+
text_outputs = self.text_model(
|
| 1830 |
+
input_ids=input_ids,
|
| 1831 |
+
attention_mask=attention_mask,
|
| 1832 |
+
position_ids=position_ids,
|
| 1833 |
+
output_attentions=output_attentions,
|
| 1834 |
+
output_hidden_states=output_hidden_states,
|
| 1835 |
+
return_dict=True,
|
| 1836 |
+
)
|
| 1837 |
+
|
| 1838 |
+
pooled_output = text_outputs[1] if not return_dict else text_outputs.pooler_output
|
| 1839 |
+
|
| 1840 |
+
text_embeds = self.text_projection(pooled_output)
|
| 1841 |
+
|
| 1842 |
+
return ClapTextModelOutput(
|
| 1843 |
+
text_embeds=text_embeds,
|
| 1844 |
+
last_hidden_state=text_outputs.last_hidden_state,
|
| 1845 |
+
hidden_states=text_outputs.hidden_states,
|
| 1846 |
+
attentions=text_outputs.attentions,
|
| 1847 |
+
)
|
| 1848 |
+
|
| 1849 |
+
|
| 1850 |
+
@auto_docstring
|
| 1851 |
+
class ClapAudioModelWithProjection(ClapPreTrainedModel):
|
| 1852 |
+
config: ClapAudioConfig
|
| 1853 |
+
main_input_name = "input_features"
|
| 1854 |
+
|
| 1855 |
+
def __init__(self, config: ClapAudioConfig):
|
| 1856 |
+
super().__init__(config)
|
| 1857 |
+
self.audio_model = ClapAudioModel(config)
|
| 1858 |
+
self.audio_projection = ClapProjectionLayer(config)
|
| 1859 |
+
# Initialize weights and apply final processing
|
| 1860 |
+
self.post_init()
|
| 1861 |
+
|
| 1862 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1863 |
+
return self.audio_model.audio_encoder.patch_embed.proj
|
| 1864 |
+
|
| 1865 |
+
@can_return_tuple
|
| 1866 |
+
@auto_docstring
|
| 1867 |
+
def forward(
|
| 1868 |
+
self,
|
| 1869 |
+
input_features: Optional[torch.FloatTensor] = None,
|
| 1870 |
+
is_longer: Optional[torch.BoolTensor] = None,
|
| 1871 |
+
output_attentions: Optional[bool] = None,
|
| 1872 |
+
output_hidden_states: Optional[bool] = None,
|
| 1873 |
+
return_dict: Optional[bool] = None,
|
| 1874 |
+
) -> Union[tuple, ClapAudioModelOutput]:
|
| 1875 |
+
r"""
|
| 1876 |
+
is_longer (`torch.FloatTensor`, of shape `(batch_size, 1)`, *optional*):
|
| 1877 |
+
Whether the audio clip is longer than `max_length`. If `True`, a feature fusion will be enabled to enhance
|
| 1878 |
+
the features.
|
| 1879 |
+
|
| 1880 |
+
Examples:
|
| 1881 |
+
|
| 1882 |
+
```python
|
| 1883 |
+
>>> from datasets import load_dataset
|
| 1884 |
+
>>> from transformers import ClapAudioModelWithProjection, ClapProcessor
|
| 1885 |
+
|
| 1886 |
+
>>> model = ClapAudioModelWithProjection.from_pretrained("laion/clap-htsat-fused")
|
| 1887 |
+
>>> processor = ClapProcessor.from_pretrained("laion/clap-htsat-fused")
|
| 1888 |
+
|
| 1889 |
+
>>> dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example")
|
| 1890 |
+
>>> audio_sample = dataset["train"]["audio"][0]["array"]
|
| 1891 |
+
|
| 1892 |
+
>>> inputs = processor(audios=audio_sample, return_tensors="pt")
|
| 1893 |
+
>>> outputs = model(**inputs)
|
| 1894 |
+
>>> audio_embeds = outputs.audio_embeds
|
| 1895 |
+
```"""
|
| 1896 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1897 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1898 |
+
output_hidden_states = (
|
| 1899 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1900 |
+
)
|
| 1901 |
+
|
| 1902 |
+
audio_outputs = self.audio_model(
|
| 1903 |
+
input_features=input_features,
|
| 1904 |
+
is_longer=is_longer,
|
| 1905 |
+
output_attentions=output_attentions,
|
| 1906 |
+
output_hidden_states=output_hidden_states,
|
| 1907 |
+
return_dict=True,
|
| 1908 |
+
)
|
| 1909 |
+
|
| 1910 |
+
pooled_output = audio_outputs[1] if not return_dict else audio_outputs.pooler_output
|
| 1911 |
+
|
| 1912 |
+
audio_embeds = self.audio_projection(pooled_output)
|
| 1913 |
+
|
| 1914 |
+
return ClapAudioModelOutput(
|
| 1915 |
+
audio_embeds=audio_embeds,
|
| 1916 |
+
last_hidden_state=audio_outputs.last_hidden_state,
|
| 1917 |
+
attentions=audio_outputs.attentions,
|
| 1918 |
+
hidden_states=audio_outputs.hidden_states,
|
| 1919 |
+
)
|
| 1920 |
+
|
| 1921 |
+
|
| 1922 |
+
__all__ = [
|
| 1923 |
+
"ClapModel",
|
| 1924 |
+
"ClapPreTrainedModel",
|
| 1925 |
+
"ClapTextModel",
|
| 1926 |
+
"ClapTextModelWithProjection",
|
| 1927 |
+
"ClapAudioModel",
|
| 1928 |
+
"ClapAudioModelWithProjection",
|
| 1929 |
+
]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/clap/processing_clap.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Audio/Text processor class for CLAP
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from typing import Optional, Union
|
| 20 |
+
|
| 21 |
+
from ...audio_utils import AudioInput
|
| 22 |
+
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
|
| 23 |
+
from ...tokenization_utils_base import PreTokenizedInput, TextInput
|
| 24 |
+
from ...utils import logging
|
| 25 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ClapProcessor(ProcessorMixin):
|
| 32 |
+
r"""
|
| 33 |
+
Constructs a CLAP processor which wraps a CLAP feature extractor and a RoBerta tokenizer into a single processor.
|
| 34 |
+
|
| 35 |
+
[`ClapProcessor`] offers all the functionalities of [`ClapFeatureExtractor`] and [`RobertaTokenizerFast`]. See the
|
| 36 |
+
[`~ClapProcessor.__call__`] and [`~ClapProcessor.decode`] for more information.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
feature_extractor ([`ClapFeatureExtractor`]):
|
| 40 |
+
The audio processor is a required input.
|
| 41 |
+
tokenizer ([`RobertaTokenizerFast`]):
|
| 42 |
+
The tokenizer is a required input.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
feature_extractor_class = "ClapFeatureExtractor"
|
| 46 |
+
tokenizer_class = ("RobertaTokenizer", "RobertaTokenizerFast")
|
| 47 |
+
|
| 48 |
+
def __init__(self, feature_extractor, tokenizer):
|
| 49 |
+
super().__init__(feature_extractor, tokenizer)
|
| 50 |
+
|
| 51 |
+
@deprecate_kwarg("audios", version="v4.59.0", new_name="audio")
|
| 52 |
+
def __call__(
|
| 53 |
+
self,
|
| 54 |
+
text: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] = None,
|
| 55 |
+
audios: Optional[AudioInput] = None,
|
| 56 |
+
audio: Optional[AudioInput] = None,
|
| 57 |
+
**kwargs: Unpack[ProcessingKwargs],
|
| 58 |
+
):
|
| 59 |
+
"""
|
| 60 |
+
Forwards the `audio` and `sampling_rate` arguments to [`~ClapFeatureExtractor.__call__`] and the `text`
|
| 61 |
+
argument to [`~RobertaTokenizerFast.__call__`]. Please refer to the docstring of the above two methods for more
|
| 62 |
+
information.
|
| 63 |
+
"""
|
| 64 |
+
# The `deprecate_kwarg` will not work if the inputs are passed as arguments, so we check
|
| 65 |
+
# again that the correct naming is used
|
| 66 |
+
if audios is not None and audio is None:
|
| 67 |
+
logger.warning(
|
| 68 |
+
"Using `audios` keyword argument is deprecated when calling ClapProcessor, instead use `audio`."
|
| 69 |
+
)
|
| 70 |
+
audio = audios
|
| 71 |
+
|
| 72 |
+
return super().__call__(text=text, audio=audio, **kwargs)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
__all__ = ["ClapProcessor"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_colpali import *
|
| 22 |
+
from .modeling_colpali import *
|
| 23 |
+
from .processing_colpali import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/configuration_colpali.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""ColPali model configuration"""
|
| 16 |
+
|
| 17 |
+
import logging
|
| 18 |
+
from copy import deepcopy
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PretrainedConfig
|
| 21 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.getLogger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ColPaliConfig(PretrainedConfig):
|
| 28 |
+
r"""
|
| 29 |
+
Configuration class to store the configuration of a [`ColPaliForRetrieval`]. It is used to instantiate an instance
|
| 30 |
+
of `ColPaliForRetrieval` according to the specified arguments, defining the model architecture following the methodology
|
| 31 |
+
from the "ColPali: Efficient Document Retrieval with Vision Language Models" paper.
|
| 32 |
+
|
| 33 |
+
Creating a configuration with the default settings will result in a configuration where the VLM backbone is set to the
|
| 34 |
+
default PaliGemma configuration, i.e the one from [vidore/colpali-v1.2](https://huggingface.co/vidore/colpali-v1.2).
|
| 35 |
+
|
| 36 |
+
Note that contrarily to what the class name suggests (actually the name refers to the ColPali **methodology**), you can
|
| 37 |
+
use a different VLM backbone model than PaliGemma by passing the corresponding VLM configuration to the class constructor.
|
| 38 |
+
|
| 39 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 40 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
vlm_config (`PretrainedConfig`, *optional*):
|
| 44 |
+
Configuration of the VLM backbone model.
|
| 45 |
+
text_config (`PretrainedConfig`, *optional*):
|
| 46 |
+
Configuration of the text backbone model. Overrides the `text_config` attribute of the `vlm_config` if provided.
|
| 47 |
+
embedding_dim (`int`, *optional*, defaults to 128):
|
| 48 |
+
Dimension of the multi-vector embeddings produced by the model.
|
| 49 |
+
|
| 50 |
+
Example:
|
| 51 |
+
|
| 52 |
+
```python
|
| 53 |
+
from transformers.models.colpali import ColPaliConfig, ColPaliForRetrieval
|
| 54 |
+
|
| 55 |
+
config = ColPaliConfig()
|
| 56 |
+
model = ColPaliForRetrieval(config)
|
| 57 |
+
```
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
model_type = "colpali"
|
| 61 |
+
sub_configs = {"vlm_config": PretrainedConfig, "text_config": AutoConfig}
|
| 62 |
+
|
| 63 |
+
def __init__(
|
| 64 |
+
self,
|
| 65 |
+
vlm_config=None,
|
| 66 |
+
text_config=None,
|
| 67 |
+
embedding_dim: int = 128,
|
| 68 |
+
**kwargs,
|
| 69 |
+
):
|
| 70 |
+
if vlm_config is None:
|
| 71 |
+
vlm_config = CONFIG_MAPPING["paligemma"]()
|
| 72 |
+
logger.info(
|
| 73 |
+
"`vlm_config` is `None`. Initializing `vlm_config` with the `PaliGemmaConfig` with default values."
|
| 74 |
+
)
|
| 75 |
+
elif isinstance(vlm_config, dict):
|
| 76 |
+
vlm_config = deepcopy(vlm_config)
|
| 77 |
+
if "model_type" not in vlm_config:
|
| 78 |
+
raise KeyError(
|
| 79 |
+
"The `model_type` key is missing in the `vlm_config` dictionary. Please provide the model type."
|
| 80 |
+
)
|
| 81 |
+
elif vlm_config["model_type"] not in CONFIG_MAPPING:
|
| 82 |
+
raise ValueError(
|
| 83 |
+
f"The model type `{vlm_config['model_type']}` is not supported. Please provide a valid model type."
|
| 84 |
+
)
|
| 85 |
+
vlm_config = CONFIG_MAPPING[vlm_config["model_type"]](**vlm_config)
|
| 86 |
+
elif not isinstance(vlm_config, PretrainedConfig):
|
| 87 |
+
raise TypeError(
|
| 88 |
+
f"Invalid type for `vlm_config`. Expected `PretrainedConfig`, `dict`, or `None`, but got {type(vlm_config)}."
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
self.vlm_config = vlm_config
|
| 92 |
+
self.text_config = text_config if text_config is not None else vlm_config.text_config
|
| 93 |
+
if isinstance(self.text_config, dict):
|
| 94 |
+
text_config["model_type"] = text_config.get("model_type", "gemma")
|
| 95 |
+
self.text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
|
| 96 |
+
|
| 97 |
+
self.embedding_dim = embedding_dim
|
| 98 |
+
|
| 99 |
+
super().__init__(**kwargs)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
__all__ = ["ColPaliConfig"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/modeling_colpali.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch ColPali model"""
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
from transformers import AutoModelForImageTextToText
|
| 24 |
+
|
| 25 |
+
from ...cache_utils import Cache
|
| 26 |
+
from ...modeling_utils import PreTrainedModel
|
| 27 |
+
from ...utils import ModelOutput, auto_docstring, can_return_tuple
|
| 28 |
+
from .configuration_colpali import ColPaliConfig
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@auto_docstring
|
| 32 |
+
class ColPaliPreTrainedModel(PreTrainedModel):
|
| 33 |
+
config: ColPaliConfig
|
| 34 |
+
base_model_prefix = "model"
|
| 35 |
+
_no_split_modules = []
|
| 36 |
+
_supports_sdpa = True
|
| 37 |
+
_supports_flash_attn = True
|
| 38 |
+
_supports_flex_attn = True
|
| 39 |
+
|
| 40 |
+
def _init_weights(self, module):
|
| 41 |
+
std = (
|
| 42 |
+
self.config.initializer_range
|
| 43 |
+
if hasattr(self.config, "initializer_range")
|
| 44 |
+
else self.config.vlm_config.text_config.initializer_range
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 48 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 49 |
+
if module.bias is not None:
|
| 50 |
+
module.bias.data.zero_()
|
| 51 |
+
elif isinstance(module, nn.Embedding):
|
| 52 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 53 |
+
if module.padding_idx is not None:
|
| 54 |
+
module.weight.data[module.padding_idx].zero_()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@dataclass
|
| 58 |
+
@auto_docstring(
|
| 59 |
+
custom_intro="""
|
| 60 |
+
Base class for ColPali embeddings output.
|
| 61 |
+
"""
|
| 62 |
+
)
|
| 63 |
+
class ColPaliForRetrievalOutput(ModelOutput):
|
| 64 |
+
r"""
|
| 65 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 66 |
+
Language modeling loss (for next-token prediction).
|
| 67 |
+
embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 68 |
+
The embeddings of the model.
|
| 69 |
+
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 70 |
+
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
|
| 71 |
+
|
| 72 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
| 73 |
+
`past_key_values` input) to speed up sequential decoding.
|
| 74 |
+
image_hidden_states (`torch.FloatTensor`, *optional*):
|
| 75 |
+
A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
|
| 76 |
+
image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
loss: Optional[torch.FloatTensor] = None
|
| 80 |
+
embeddings: Optional[torch.Tensor] = None
|
| 81 |
+
past_key_values: Optional[Cache] = None
|
| 82 |
+
hidden_states: Optional[tuple[torch.FloatTensor]] = None
|
| 83 |
+
attentions: Optional[tuple[torch.FloatTensor]] = None
|
| 84 |
+
image_hidden_states: Optional[torch.FloatTensor] = None
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@auto_docstring(
|
| 88 |
+
custom_intro="""
|
| 89 |
+
The ColPali architecture leverages VLMs to construct efficient multi-vector embeddings directly
|
| 90 |
+
from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
|
| 91 |
+
between these document embeddings and the corresponding query embeddings, using the late interaction method
|
| 92 |
+
introduced in ColBERT.
|
| 93 |
+
|
| 94 |
+
Using ColPali removes the need for potentially complex and brittle layout recognition and OCR pipelines with a
|
| 95 |
+
single model that can take into account both the textual and visual content (layout, charts, etc.) of a document.
|
| 96 |
+
|
| 97 |
+
ColPali is part of the ColVision model family, which was first introduced in the following paper:
|
| 98 |
+
[*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
|
| 99 |
+
"""
|
| 100 |
+
)
|
| 101 |
+
class ColPaliForRetrieval(ColPaliPreTrainedModel):
|
| 102 |
+
_checkpoint_conversion_mapping = {
|
| 103 |
+
"vlm.language_model.model": "vlm.model.language_model",
|
| 104 |
+
"vlm.vision_tower": "vlm.model.vision_tower",
|
| 105 |
+
"vlm.multi_modal_projector": "vlm.model.multi_modal_projector",
|
| 106 |
+
"vlm.language_model.lm_head": "vlm.lm_head",
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
def __init__(self, config: ColPaliConfig):
|
| 110 |
+
super().__init__(config)
|
| 111 |
+
self.config = config
|
| 112 |
+
self.vocab_size = config.vlm_config.text_config.vocab_size
|
| 113 |
+
|
| 114 |
+
self.vlm = AutoModelForImageTextToText.from_config(config.vlm_config)
|
| 115 |
+
self._tied_weights_keys = [f"vlm.language_model.{k}" for k in (self.vlm._tied_weights_keys or [])]
|
| 116 |
+
|
| 117 |
+
self.embedding_dim = self.config.embedding_dim
|
| 118 |
+
self.embedding_proj_layer = nn.Linear(
|
| 119 |
+
self.config.vlm_config.text_config.hidden_size,
|
| 120 |
+
self.embedding_dim,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
self.post_init()
|
| 124 |
+
|
| 125 |
+
@can_return_tuple
|
| 126 |
+
@auto_docstring
|
| 127 |
+
def forward(
|
| 128 |
+
self,
|
| 129 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 130 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 131 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 132 |
+
output_attentions: Optional[bool] = None,
|
| 133 |
+
output_hidden_states: Optional[bool] = None,
|
| 134 |
+
return_dict: Optional[bool] = None,
|
| 135 |
+
**kwargs,
|
| 136 |
+
) -> ColPaliForRetrievalOutput:
|
| 137 |
+
if pixel_values is not None:
|
| 138 |
+
pixel_values = pixel_values.to(dtype=self.dtype)
|
| 139 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 140 |
+
|
| 141 |
+
output_hidden_states = (
|
| 142 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 143 |
+
)
|
| 144 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 145 |
+
|
| 146 |
+
vlm_output = self.vlm.model(
|
| 147 |
+
input_ids=input_ids,
|
| 148 |
+
attention_mask=attention_mask,
|
| 149 |
+
pixel_values=pixel_values,
|
| 150 |
+
output_hidden_states=True,
|
| 151 |
+
return_dict=True,
|
| 152 |
+
output_attentions=output_attentions,
|
| 153 |
+
**kwargs,
|
| 154 |
+
)
|
| 155 |
+
vlm_hidden_states = vlm_output.hidden_states if output_hidden_states else None
|
| 156 |
+
vlm_image_hidden_states = vlm_output.image_hidden_states if pixel_values is not None else None
|
| 157 |
+
|
| 158 |
+
last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size)
|
| 159 |
+
proj_dtype = self.embedding_proj_layer.weight.dtype
|
| 160 |
+
embeddings = self.embedding_proj_layer(last_hidden_states.to(proj_dtype)) # (batch_size, sequence_length, dim)
|
| 161 |
+
|
| 162 |
+
# L2 normalization
|
| 163 |
+
embeddings = embeddings / embeddings.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
|
| 164 |
+
|
| 165 |
+
if attention_mask is not None:
|
| 166 |
+
embeddings = embeddings * attention_mask.unsqueeze(-1) # (batch_size, sequence_length, dim)
|
| 167 |
+
|
| 168 |
+
return ColPaliForRetrievalOutput(
|
| 169 |
+
embeddings=embeddings,
|
| 170 |
+
past_key_values=vlm_output.past_key_values,
|
| 171 |
+
hidden_states=vlm_hidden_states,
|
| 172 |
+
attentions=vlm_output.attentions,
|
| 173 |
+
image_hidden_states=vlm_image_hidden_states,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
def get_input_embeddings(self):
|
| 177 |
+
return self.vlm.get_input_embeddings()
|
| 178 |
+
|
| 179 |
+
def set_input_embeddings(self, value):
|
| 180 |
+
self.vlm.set_input_embeddings(value)
|
| 181 |
+
|
| 182 |
+
def get_output_embeddings(self):
|
| 183 |
+
return self.vlm.get_output_embeddings()
|
| 184 |
+
|
| 185 |
+
def set_output_embeddings(self, new_embeddings):
|
| 186 |
+
self.vlm.set_output_embeddings(new_embeddings)
|
| 187 |
+
|
| 188 |
+
def tie_weights(self):
|
| 189 |
+
return self.vlm.tie_weights()
|
| 190 |
+
|
| 191 |
+
def resize_token_embeddings(
|
| 192 |
+
self,
|
| 193 |
+
new_num_tokens: Optional[int] = None,
|
| 194 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 195 |
+
mean_resizing: bool = True,
|
| 196 |
+
) -> nn.Embedding:
|
| 197 |
+
model_embeds = self.vlm.resize_token_embeddings(
|
| 198 |
+
new_num_tokens=new_num_tokens,
|
| 199 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 200 |
+
mean_resizing=mean_resizing,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
self.config.vlm_config.text_config.vocab_size = model_embeds.num_embeddings
|
| 204 |
+
self.config.vlm_config.vocab_size = model_embeds.num_embeddings
|
| 205 |
+
self.vlm.vocab_size = model_embeds.num_embeddings
|
| 206 |
+
self.vocab_size = model_embeds.num_embeddings
|
| 207 |
+
|
| 208 |
+
return model_embeds
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
__all__ = [
|
| 212 |
+
"ColPaliForRetrieval",
|
| 213 |
+
"ColPaliPreTrainedModel",
|
| 214 |
+
]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/modular_colpali.py
ADDED
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
from transformers.models.paligemma.processing_paligemma import IMAGE_TOKEN, PaliGemmaProcessor, build_string_from_input
|
| 20 |
+
|
| 21 |
+
from ...feature_extraction_utils import BatchFeature
|
| 22 |
+
from ...image_utils import ImageInput, make_flat_list_of_images
|
| 23 |
+
from ...processing_utils import ProcessingKwargs, Unpack
|
| 24 |
+
from ...tokenization_utils_base import PreTokenizedInput, TextInput
|
| 25 |
+
from ...utils import is_torch_available, logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_torch_available():
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class ColPaliProcessorKwargs(ProcessingKwargs, total=False):
|
| 35 |
+
_defaults = {
|
| 36 |
+
"text_kwargs": {
|
| 37 |
+
"padding": "longest",
|
| 38 |
+
},
|
| 39 |
+
"images_kwargs": {
|
| 40 |
+
"data_format": "channels_first",
|
| 41 |
+
"do_convert_rgb": True,
|
| 42 |
+
},
|
| 43 |
+
"common_kwargs": {"return_tensors": "pt"},
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class ColPaliProcessor(PaliGemmaProcessor):
|
| 48 |
+
r"""
|
| 49 |
+
Constructs a ColPali processor which wraps a PaliGemmaProcessor and special methods to process images and queries, as
|
| 50 |
+
well as to compute the late-interaction retrieval score.
|
| 51 |
+
|
| 52 |
+
[`ColPaliProcessor`] offers all the functionalities of [`PaliGemmaProcessor`]. See the [`~PaliGemmaProcessor.__call__`]
|
| 53 |
+
for more information.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
image_processor ([`SiglipImageProcessor`], *optional*):
|
| 57 |
+
The image processor is a required input.
|
| 58 |
+
tokenizer ([`LlamaTokenizerFast`], *optional*):
|
| 59 |
+
The tokenizer is a required input.
|
| 60 |
+
chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
|
| 61 |
+
in a chat into a tokenizable string.
|
| 62 |
+
visual_prompt_prefix (`str`, *optional*, defaults to `"Describe the image."`):
|
| 63 |
+
A string that gets tokenized and prepended to the image tokens.
|
| 64 |
+
query_prefix (`str`, *optional*, defaults to `"Question: "`):
|
| 65 |
+
A prefix to be used for the query.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
def __init__(
|
| 69 |
+
self,
|
| 70 |
+
image_processor=None,
|
| 71 |
+
tokenizer=None,
|
| 72 |
+
chat_template=None,
|
| 73 |
+
visual_prompt_prefix: str = "Describe the image.",
|
| 74 |
+
query_prefix: str = "Question: ",
|
| 75 |
+
):
|
| 76 |
+
super().__init__(image_processor=image_processor, tokenizer=tokenizer, chat_template=chat_template)
|
| 77 |
+
self.visual_prompt_prefix = visual_prompt_prefix
|
| 78 |
+
self.query_prefix = query_prefix
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def query_augmentation_token(self) -> str:
|
| 82 |
+
"""
|
| 83 |
+
Return the query augmentation token.
|
| 84 |
+
|
| 85 |
+
Query augmentation buffers are used as reasoning buffers during inference.
|
| 86 |
+
"""
|
| 87 |
+
return self.tokenizer.pad_token
|
| 88 |
+
|
| 89 |
+
def __call__(
|
| 90 |
+
self,
|
| 91 |
+
images: Optional[ImageInput] = None,
|
| 92 |
+
text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
|
| 93 |
+
audio=None,
|
| 94 |
+
videos=None,
|
| 95 |
+
**kwargs: Unpack[ColPaliProcessorKwargs],
|
| 96 |
+
) -> BatchFeature:
|
| 97 |
+
"""
|
| 98 |
+
Main method to prepare for the model either (1) one or several texts, either (2) one or several image(s). This method is a custom
|
| 99 |
+
wrapper around the PaliGemmaProcessor's [`~PaliGemmaProcessor.__call__`] method adapted for the ColPali model. It cannot process
|
| 100 |
+
both text and images at the same time.
|
| 101 |
+
|
| 102 |
+
When preparing the text(s), this method forwards the `text` and `kwargs` arguments to LlamaTokenizerFast's
|
| 103 |
+
[`~LlamaTokenizerFast.__call__`].
|
| 104 |
+
When preparing the image(s), this method forwards the `images` and `kwargs` arguments to SiglipImageProcessor's
|
| 105 |
+
[`~SiglipImageProcessor.__call__`].
|
| 106 |
+
Please refer to the docstring of the above two methods for more information.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
|
| 110 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 111 |
+
tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
|
| 112 |
+
number of channels, H and W are image height and width.
|
| 113 |
+
text (`str`, `list[str]`, `list[list[str]]`):
|
| 114 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 115 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 116 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 117 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 118 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 119 |
+
|
| 120 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 121 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 122 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 123 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 124 |
+
|
| 125 |
+
Returns:
|
| 126 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 127 |
+
|
| 128 |
+
- **input_ids** -- List of token ids to be fed to a model.
|
| 129 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 130 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 131 |
+
`None`).
|
| 132 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 133 |
+
"""
|
| 134 |
+
output_kwargs = self._merge_kwargs(
|
| 135 |
+
ColPaliProcessorKwargs,
|
| 136 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 137 |
+
**kwargs,
|
| 138 |
+
)
|
| 139 |
+
suffix = output_kwargs["text_kwargs"].pop("suffix", None)
|
| 140 |
+
|
| 141 |
+
return_token_type_ids = suffix is not None
|
| 142 |
+
|
| 143 |
+
if text is None and images is None:
|
| 144 |
+
raise ValueError("Either text or images must be provided")
|
| 145 |
+
if text is not None and images is not None:
|
| 146 |
+
raise ValueError("Only one of text or images can be processed at a time")
|
| 147 |
+
|
| 148 |
+
if images is not None:
|
| 149 |
+
images = self.image_processor.fetch_images(images)
|
| 150 |
+
images = make_flat_list_of_images(images)
|
| 151 |
+
texts_doc = [self.visual_prompt_prefix] * len(images)
|
| 152 |
+
images = [image.convert("RGB") for image in images]
|
| 153 |
+
|
| 154 |
+
input_strings = [
|
| 155 |
+
build_string_from_input(
|
| 156 |
+
prompt=prompt,
|
| 157 |
+
bos_token=self.tokenizer.bos_token,
|
| 158 |
+
image_seq_len=self.image_seq_length,
|
| 159 |
+
image_token=IMAGE_TOKEN,
|
| 160 |
+
num_images=len(image_list) if isinstance(image_list, list) else 1,
|
| 161 |
+
)
|
| 162 |
+
for prompt, image_list in zip(texts_doc, images)
|
| 163 |
+
]
|
| 164 |
+
pixel_values = self.image_processor(images, **output_kwargs["images_kwargs"])["pixel_values"]
|
| 165 |
+
|
| 166 |
+
# max_length has to account for the image tokens
|
| 167 |
+
if output_kwargs["text_kwargs"].get("max_length", None) is not None:
|
| 168 |
+
output_kwargs["text_kwargs"]["max_length"] += self.image_seq_length
|
| 169 |
+
|
| 170 |
+
inputs = self.tokenizer(
|
| 171 |
+
input_strings,
|
| 172 |
+
return_token_type_ids=False,
|
| 173 |
+
**output_kwargs["text_kwargs"],
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
return_data = {**inputs, "pixel_values": pixel_values}
|
| 177 |
+
|
| 178 |
+
if return_token_type_ids:
|
| 179 |
+
labels = inputs["input_ids"].masked_fill(inputs["token_type_ids"] == 0, -100)
|
| 180 |
+
return_data.update({"labels": labels})
|
| 181 |
+
|
| 182 |
+
return BatchFeature(data=return_data)
|
| 183 |
+
|
| 184 |
+
elif text is not None:
|
| 185 |
+
if isinstance(text, str):
|
| 186 |
+
text = [text]
|
| 187 |
+
elif not (isinstance(text, list) and isinstance(text[0], str)):
|
| 188 |
+
raise ValueError("Text must be a string or a list of strings")
|
| 189 |
+
|
| 190 |
+
if suffix is None:
|
| 191 |
+
suffix = self.query_augmentation_token * 10
|
| 192 |
+
|
| 193 |
+
texts_query: list[str] = []
|
| 194 |
+
for query in text:
|
| 195 |
+
query = self.tokenizer.bos_token + self.query_prefix + query + suffix + "\n"
|
| 196 |
+
texts_query.append(query)
|
| 197 |
+
|
| 198 |
+
output_kwargs["text_kwargs"]["max_length"] = output_kwargs["text_kwargs"].get("max_length", 50)
|
| 199 |
+
|
| 200 |
+
batch_query = self.tokenizer(
|
| 201 |
+
texts_query,
|
| 202 |
+
return_token_type_ids=False,
|
| 203 |
+
**output_kwargs["text_kwargs"],
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
return batch_query
|
| 207 |
+
|
| 208 |
+
def process_images(
|
| 209 |
+
self,
|
| 210 |
+
images: Optional[ImageInput] = None,
|
| 211 |
+
**kwargs: Unpack[ColPaliProcessorKwargs],
|
| 212 |
+
) -> BatchFeature:
|
| 213 |
+
"""
|
| 214 |
+
Prepare for the model one or several image(s). This method is a wrapper around the `__call__` method of the ColPaliProcessor's
|
| 215 |
+
[`ColPaliProcessor.__call__`].
|
| 216 |
+
|
| 217 |
+
This method forwards the `images` and `kwargs` arguments to the image processor.
|
| 218 |
+
|
| 219 |
+
Args:
|
| 220 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
|
| 221 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 222 |
+
tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
|
| 223 |
+
number of channels, H and W are image height and width.
|
| 224 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 225 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 226 |
+
|
| 227 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 228 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 229 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 230 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 231 |
+
|
| 232 |
+
Returns:
|
| 233 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 234 |
+
|
| 235 |
+
- **input_ids** -- List of token ids to be fed to a model.
|
| 236 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 237 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 238 |
+
`None`).
|
| 239 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 240 |
+
"""
|
| 241 |
+
return self.__call__(images=images, **kwargs)
|
| 242 |
+
|
| 243 |
+
def process_queries(
|
| 244 |
+
self,
|
| 245 |
+
text: Union[TextInput, list[TextInput]],
|
| 246 |
+
**kwargs: Unpack[ColPaliProcessorKwargs],
|
| 247 |
+
) -> BatchFeature:
|
| 248 |
+
"""
|
| 249 |
+
Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColPaliProcessor's
|
| 250 |
+
[`ColPaliProcessor.__call__`].
|
| 251 |
+
|
| 252 |
+
This method forwards the `text` and `kwargs` arguments to the tokenizer.
|
| 253 |
+
|
| 254 |
+
Args:
|
| 255 |
+
text (`str`, `list[str]`, `list[list[str]]`):
|
| 256 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 257 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 258 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 259 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 260 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 261 |
+
|
| 262 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 263 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 264 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 265 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 266 |
+
|
| 267 |
+
Returns:
|
| 268 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 269 |
+
|
| 270 |
+
- **input_ids** -- List of token ids to be fed to a model.
|
| 271 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 272 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 273 |
+
`None`).
|
| 274 |
+
"""
|
| 275 |
+
return self.__call__(text=text, **kwargs)
|
| 276 |
+
|
| 277 |
+
def score_retrieval(
|
| 278 |
+
self,
|
| 279 |
+
query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
|
| 280 |
+
passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
|
| 281 |
+
batch_size: int = 128,
|
| 282 |
+
output_dtype: Optional["torch.dtype"] = None,
|
| 283 |
+
output_device: Union["torch.device", str] = "cpu",
|
| 284 |
+
) -> "torch.Tensor":
|
| 285 |
+
"""
|
| 286 |
+
Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
|
| 287 |
+
query embeddings (`qs`) and passage embeddings (`ps`). For ColPali, a passage is the
|
| 288 |
+
image of a document page.
|
| 289 |
+
|
| 290 |
+
Because the embedding tensors are multi-vector and can thus have different shapes, they
|
| 291 |
+
should be fed as:
|
| 292 |
+
(1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
|
| 293 |
+
(2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
|
| 294 |
+
obtained by padding the list of tensors.
|
| 295 |
+
|
| 296 |
+
Args:
|
| 297 |
+
query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
|
| 298 |
+
passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
|
| 299 |
+
batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
|
| 300 |
+
output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
|
| 301 |
+
If `None`, the dtype of the input embeddings is used.
|
| 302 |
+
output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
|
| 303 |
+
|
| 304 |
+
Returns:
|
| 305 |
+
`torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
|
| 306 |
+
tensor is saved on the "cpu" device.
|
| 307 |
+
"""
|
| 308 |
+
|
| 309 |
+
if len(query_embeddings) == 0:
|
| 310 |
+
raise ValueError("No queries provided")
|
| 311 |
+
if len(passage_embeddings) == 0:
|
| 312 |
+
raise ValueError("No passages provided")
|
| 313 |
+
|
| 314 |
+
if query_embeddings[0].device != passage_embeddings[0].device:
|
| 315 |
+
raise ValueError("Queries and passages must be on the same device")
|
| 316 |
+
|
| 317 |
+
if query_embeddings[0].dtype != passage_embeddings[0].dtype:
|
| 318 |
+
raise ValueError("Queries and passages must have the same dtype")
|
| 319 |
+
|
| 320 |
+
if output_dtype is None:
|
| 321 |
+
output_dtype = query_embeddings[0].dtype
|
| 322 |
+
|
| 323 |
+
scores: list[torch.Tensor] = []
|
| 324 |
+
|
| 325 |
+
for i in range(0, len(query_embeddings), batch_size):
|
| 326 |
+
batch_scores: list[torch.Tensor] = []
|
| 327 |
+
batch_queries = torch.nn.utils.rnn.pad_sequence(
|
| 328 |
+
query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
|
| 329 |
+
)
|
| 330 |
+
for j in range(0, len(passage_embeddings), batch_size):
|
| 331 |
+
batch_passages = torch.nn.utils.rnn.pad_sequence(
|
| 332 |
+
passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
|
| 333 |
+
)
|
| 334 |
+
batch_scores.append(
|
| 335 |
+
torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
|
| 336 |
+
)
|
| 337 |
+
scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
|
| 338 |
+
|
| 339 |
+
return torch.cat(scores, dim=0)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
__all__ = [
|
| 343 |
+
"ColPaliProcessor",
|
| 344 |
+
]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/processing_colpali.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/colpali/modular_colpali.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_colpali.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
from typing import Optional, Union
|
| 24 |
+
|
| 25 |
+
from ...feature_extraction_utils import BatchFeature
|
| 26 |
+
from ...image_utils import ImageInput, make_flat_list_of_images
|
| 27 |
+
from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
|
| 28 |
+
from ...tokenization_utils_base import AddedToken, PreTokenizedInput, TextInput
|
| 29 |
+
from ...utils import is_torch_available
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if is_torch_available():
|
| 33 |
+
import torch
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ColPaliProcessorKwargs(ProcessingKwargs, total=False):
|
| 37 |
+
_defaults = {
|
| 38 |
+
"text_kwargs": {
|
| 39 |
+
"padding": "longest",
|
| 40 |
+
},
|
| 41 |
+
"images_kwargs": {
|
| 42 |
+
"data_format": "channels_first",
|
| 43 |
+
"do_convert_rgb": True,
|
| 44 |
+
},
|
| 45 |
+
"common_kwargs": {"return_tensors": "pt"},
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
IMAGE_TOKEN = "<image>"
|
| 50 |
+
EXTRA_TOKENS = [f"<loc{i:0>4}>" for i in range(1024)] + [f"<seg{i:0>3}>" for i in range(128)]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def build_string_from_input(prompt, bos_token, image_seq_len, image_token, num_images):
|
| 54 |
+
"""
|
| 55 |
+
Builds a string from the input prompt and image tokens.
|
| 56 |
+
For example, for the call:
|
| 57 |
+
build_string_from_input(
|
| 58 |
+
prompt="Prefix str"
|
| 59 |
+
bos_token="<s>",
|
| 60 |
+
image_seq_len=3,
|
| 61 |
+
image_token="<im>",
|
| 62 |
+
)
|
| 63 |
+
The output will be:
|
| 64 |
+
"<im><im><im><s>Initial str"
|
| 65 |
+
Args:
|
| 66 |
+
prompt (`list[Union[str, ImageInput]]`): The input prompt.
|
| 67 |
+
bos_token (`str`): The beginning of sentence token.
|
| 68 |
+
image_seq_len (`int`): The length of the image sequence.
|
| 69 |
+
image_token (`str`): The image token.
|
| 70 |
+
num_images (`int`): Number of images in the prompt.
|
| 71 |
+
"""
|
| 72 |
+
return f"{image_token * image_seq_len * num_images}{bos_token}{prompt}\n"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class ColPaliProcessor(ProcessorMixin):
|
| 76 |
+
r"""
|
| 77 |
+
Constructs a ColPali processor which wraps a PaliGemmaProcessor and special methods to process images and queries, as
|
| 78 |
+
well as to compute the late-interaction retrieval score.
|
| 79 |
+
|
| 80 |
+
[`ColPaliProcessor`] offers all the functionalities of [`PaliGemmaProcessor`]. See the [`~PaliGemmaProcessor.__call__`]
|
| 81 |
+
for more information.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
image_processor ([`SiglipImageProcessor`], *optional*):
|
| 85 |
+
The image processor is a required input.
|
| 86 |
+
tokenizer ([`LlamaTokenizerFast`], *optional*):
|
| 87 |
+
The tokenizer is a required input.
|
| 88 |
+
chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
|
| 89 |
+
in a chat into a tokenizable string.
|
| 90 |
+
visual_prompt_prefix (`str`, *optional*, defaults to `"Describe the image."`):
|
| 91 |
+
A string that gets tokenized and prepended to the image tokens.
|
| 92 |
+
query_prefix (`str`, *optional*, defaults to `"Question: "`):
|
| 93 |
+
A prefix to be used for the query.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
attributes = ["image_processor", "tokenizer"]
|
| 97 |
+
image_processor_class = ("SiglipImageProcessor", "SiglipImageProcessorFast")
|
| 98 |
+
tokenizer_class = ("GemmaTokenizer", "GemmaTokenizerFast")
|
| 99 |
+
|
| 100 |
+
def __init__(
|
| 101 |
+
self,
|
| 102 |
+
image_processor=None,
|
| 103 |
+
tokenizer=None,
|
| 104 |
+
chat_template=None,
|
| 105 |
+
visual_prompt_prefix: str = "Describe the image.",
|
| 106 |
+
query_prefix: str = "Question: ",
|
| 107 |
+
):
|
| 108 |
+
super().__init__(image_processor, tokenizer, chat_template=chat_template)
|
| 109 |
+
if not hasattr(image_processor, "image_seq_length"):
|
| 110 |
+
raise ValueError("Image processor is missing an `image_seq_length` attribute.")
|
| 111 |
+
|
| 112 |
+
self.image_seq_length = image_processor.image_seq_length
|
| 113 |
+
|
| 114 |
+
if not hasattr(tokenizer, "image_token"):
|
| 115 |
+
image_token = AddedToken(IMAGE_TOKEN, normalized=False, special=True)
|
| 116 |
+
tokens_to_add = {"additional_special_tokens": [image_token]}
|
| 117 |
+
tokenizer.add_special_tokens(tokens_to_add)
|
| 118 |
+
self.image_token_id = tokenizer.convert_tokens_to_ids(IMAGE_TOKEN)
|
| 119 |
+
self.image_token = IMAGE_TOKEN
|
| 120 |
+
else:
|
| 121 |
+
self.image_token_id = tokenizer.image_token_id
|
| 122 |
+
self.image_token = tokenizer.image_token
|
| 123 |
+
|
| 124 |
+
tokenizer.add_tokens(EXTRA_TOKENS)
|
| 125 |
+
tokenizer.add_bos_token = False
|
| 126 |
+
tokenizer.add_eos_token = False
|
| 127 |
+
self.visual_prompt_prefix = visual_prompt_prefix
|
| 128 |
+
self.query_prefix = query_prefix
|
| 129 |
+
|
| 130 |
+
def __call__(
|
| 131 |
+
self,
|
| 132 |
+
images: Optional[ImageInput] = None,
|
| 133 |
+
text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
|
| 134 |
+
audio=None,
|
| 135 |
+
videos=None,
|
| 136 |
+
**kwargs: Unpack[ColPaliProcessorKwargs],
|
| 137 |
+
) -> BatchFeature:
|
| 138 |
+
"""
|
| 139 |
+
Main method to prepare for the model either (1) one or several texts, either (2) one or several image(s). This method is a custom
|
| 140 |
+
wrapper around the PaliGemmaProcessor's [`~PaliGemmaProcessor.__call__`] method adapted for the ColPali model. It cannot process
|
| 141 |
+
both text and images at the same time.
|
| 142 |
+
|
| 143 |
+
When preparing the text(s), this method forwards the `text` and `kwargs` arguments to LlamaTokenizerFast's
|
| 144 |
+
[`~LlamaTokenizerFast.__call__`].
|
| 145 |
+
When preparing the image(s), this method forwards the `images` and `kwargs` arguments to SiglipImageProcessor's
|
| 146 |
+
[`~SiglipImageProcessor.__call__`].
|
| 147 |
+
Please refer to the docstring of the above two methods for more information.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
|
| 151 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 152 |
+
tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
|
| 153 |
+
number of channels, H and W are image height and width.
|
| 154 |
+
text (`str`, `list[str]`, `list[list[str]]`):
|
| 155 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 156 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 157 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 158 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 159 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 160 |
+
|
| 161 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 162 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 163 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 164 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 165 |
+
|
| 166 |
+
Returns:
|
| 167 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 168 |
+
|
| 169 |
+
- **input_ids** -- List of token ids to be fed to a model.
|
| 170 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 171 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 172 |
+
`None`).
|
| 173 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 174 |
+
"""
|
| 175 |
+
output_kwargs = self._merge_kwargs(
|
| 176 |
+
ColPaliProcessorKwargs,
|
| 177 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 178 |
+
**kwargs,
|
| 179 |
+
)
|
| 180 |
+
suffix = output_kwargs["text_kwargs"].pop("suffix", None)
|
| 181 |
+
|
| 182 |
+
return_token_type_ids = suffix is not None
|
| 183 |
+
|
| 184 |
+
if text is None and images is None:
|
| 185 |
+
raise ValueError("Either text or images must be provided")
|
| 186 |
+
if text is not None and images is not None:
|
| 187 |
+
raise ValueError("Only one of text or images can be processed at a time")
|
| 188 |
+
|
| 189 |
+
if images is not None:
|
| 190 |
+
images = self.image_processor.fetch_images(images)
|
| 191 |
+
images = make_flat_list_of_images(images)
|
| 192 |
+
texts_doc = [self.visual_prompt_prefix] * len(images)
|
| 193 |
+
images = [image.convert("RGB") for image in images]
|
| 194 |
+
|
| 195 |
+
input_strings = [
|
| 196 |
+
build_string_from_input(
|
| 197 |
+
prompt=prompt,
|
| 198 |
+
bos_token=self.tokenizer.bos_token,
|
| 199 |
+
image_seq_len=self.image_seq_length,
|
| 200 |
+
image_token=IMAGE_TOKEN,
|
| 201 |
+
num_images=len(image_list) if isinstance(image_list, list) else 1,
|
| 202 |
+
)
|
| 203 |
+
for prompt, image_list in zip(texts_doc, images)
|
| 204 |
+
]
|
| 205 |
+
pixel_values = self.image_processor(images, **output_kwargs["images_kwargs"])["pixel_values"]
|
| 206 |
+
|
| 207 |
+
# max_length has to account for the image tokens
|
| 208 |
+
if output_kwargs["text_kwargs"].get("max_length", None) is not None:
|
| 209 |
+
output_kwargs["text_kwargs"]["max_length"] += self.image_seq_length
|
| 210 |
+
|
| 211 |
+
inputs = self.tokenizer(
|
| 212 |
+
input_strings,
|
| 213 |
+
return_token_type_ids=False,
|
| 214 |
+
**output_kwargs["text_kwargs"],
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
return_data = {**inputs, "pixel_values": pixel_values}
|
| 218 |
+
|
| 219 |
+
if return_token_type_ids:
|
| 220 |
+
labels = inputs["input_ids"].masked_fill(inputs["token_type_ids"] == 0, -100)
|
| 221 |
+
return_data.update({"labels": labels})
|
| 222 |
+
|
| 223 |
+
return BatchFeature(data=return_data)
|
| 224 |
+
|
| 225 |
+
elif text is not None:
|
| 226 |
+
if isinstance(text, str):
|
| 227 |
+
text = [text]
|
| 228 |
+
elif not (isinstance(text, list) and isinstance(text[0], str)):
|
| 229 |
+
raise ValueError("Text must be a string or a list of strings")
|
| 230 |
+
|
| 231 |
+
if suffix is None:
|
| 232 |
+
suffix = self.query_augmentation_token * 10
|
| 233 |
+
|
| 234 |
+
texts_query: list[str] = []
|
| 235 |
+
for query in text:
|
| 236 |
+
query = self.tokenizer.bos_token + self.query_prefix + query + suffix + "\n"
|
| 237 |
+
texts_query.append(query)
|
| 238 |
+
|
| 239 |
+
output_kwargs["text_kwargs"]["max_length"] = output_kwargs["text_kwargs"].get("max_length", 50)
|
| 240 |
+
|
| 241 |
+
batch_query = self.tokenizer(
|
| 242 |
+
texts_query,
|
| 243 |
+
return_token_type_ids=False,
|
| 244 |
+
**output_kwargs["text_kwargs"],
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
return batch_query
|
| 248 |
+
|
| 249 |
+
def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
|
| 250 |
+
"""
|
| 251 |
+
Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
|
| 252 |
+
|
| 253 |
+
Args:
|
| 254 |
+
image_sizes (list[list[str]], *optional*):
|
| 255 |
+
The input sizes formatted as (height, width) per each image.
|
| 256 |
+
Returns:
|
| 257 |
+
`MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
|
| 258 |
+
input modalities, along with other useful data.
|
| 259 |
+
"""
|
| 260 |
+
vision_data = {}
|
| 261 |
+
if image_sizes is not None:
|
| 262 |
+
num_image_tokens = [self.image_seq_length] * len(image_sizes)
|
| 263 |
+
num_image_patches = [1] * len(image_sizes)
|
| 264 |
+
vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
|
| 265 |
+
return MultiModalData(**vision_data)
|
| 266 |
+
|
| 267 |
+
@property
|
| 268 |
+
def query_augmentation_token(self) -> str:
|
| 269 |
+
"""
|
| 270 |
+
Return the query augmentation token.
|
| 271 |
+
|
| 272 |
+
Query augmentation buffers are used as reasoning buffers during inference.
|
| 273 |
+
"""
|
| 274 |
+
return self.tokenizer.pad_token
|
| 275 |
+
|
| 276 |
+
def process_images(
|
| 277 |
+
self,
|
| 278 |
+
images: Optional[ImageInput] = None,
|
| 279 |
+
**kwargs: Unpack[ColPaliProcessorKwargs],
|
| 280 |
+
) -> BatchFeature:
|
| 281 |
+
"""
|
| 282 |
+
Prepare for the model one or several image(s). This method is a wrapper around the `__call__` method of the ColPaliProcessor's
|
| 283 |
+
[`ColPaliProcessor.__call__`].
|
| 284 |
+
|
| 285 |
+
This method forwards the `images` and `kwargs` arguments to the image processor.
|
| 286 |
+
|
| 287 |
+
Args:
|
| 288 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
|
| 289 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 290 |
+
tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
|
| 291 |
+
number of channels, H and W are image height and width.
|
| 292 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 293 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 294 |
+
|
| 295 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 296 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 297 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 298 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 299 |
+
|
| 300 |
+
Returns:
|
| 301 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 302 |
+
|
| 303 |
+
- **input_ids** -- List of token ids to be fed to a model.
|
| 304 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 305 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 306 |
+
`None`).
|
| 307 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 308 |
+
"""
|
| 309 |
+
return self.__call__(images=images, **kwargs)
|
| 310 |
+
|
| 311 |
+
def process_queries(
|
| 312 |
+
self,
|
| 313 |
+
text: Union[TextInput, list[TextInput]],
|
| 314 |
+
**kwargs: Unpack[ColPaliProcessorKwargs],
|
| 315 |
+
) -> BatchFeature:
|
| 316 |
+
"""
|
| 317 |
+
Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColPaliProcessor's
|
| 318 |
+
[`ColPaliProcessor.__call__`].
|
| 319 |
+
|
| 320 |
+
This method forwards the `text` and `kwargs` arguments to the tokenizer.
|
| 321 |
+
|
| 322 |
+
Args:
|
| 323 |
+
text (`str`, `list[str]`, `list[list[str]]`):
|
| 324 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 325 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 326 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 327 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 328 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 329 |
+
|
| 330 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 331 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 332 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 333 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 334 |
+
|
| 335 |
+
Returns:
|
| 336 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 337 |
+
|
| 338 |
+
- **input_ids** -- List of token ids to be fed to a model.
|
| 339 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 340 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 341 |
+
`None`).
|
| 342 |
+
"""
|
| 343 |
+
return self.__call__(text=text, **kwargs)
|
| 344 |
+
|
| 345 |
+
def score_retrieval(
|
| 346 |
+
self,
|
| 347 |
+
query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
|
| 348 |
+
passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
|
| 349 |
+
batch_size: int = 128,
|
| 350 |
+
output_dtype: Optional["torch.dtype"] = None,
|
| 351 |
+
output_device: Union["torch.device", str] = "cpu",
|
| 352 |
+
) -> "torch.Tensor":
|
| 353 |
+
"""
|
| 354 |
+
Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
|
| 355 |
+
query embeddings (`qs`) and passage embeddings (`ps`). For ColPali, a passage is the
|
| 356 |
+
image of a document page.
|
| 357 |
+
|
| 358 |
+
Because the embedding tensors are multi-vector and can thus have different shapes, they
|
| 359 |
+
should be fed as:
|
| 360 |
+
(1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
|
| 361 |
+
(2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
|
| 362 |
+
obtained by padding the list of tensors.
|
| 363 |
+
|
| 364 |
+
Args:
|
| 365 |
+
query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
|
| 366 |
+
passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
|
| 367 |
+
batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
|
| 368 |
+
output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
|
| 369 |
+
If `None`, the dtype of the input embeddings is used.
|
| 370 |
+
output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
|
| 371 |
+
|
| 372 |
+
Returns:
|
| 373 |
+
`torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
|
| 374 |
+
tensor is saved on the "cpu" device.
|
| 375 |
+
"""
|
| 376 |
+
|
| 377 |
+
if len(query_embeddings) == 0:
|
| 378 |
+
raise ValueError("No queries provided")
|
| 379 |
+
if len(passage_embeddings) == 0:
|
| 380 |
+
raise ValueError("No passages provided")
|
| 381 |
+
|
| 382 |
+
if query_embeddings[0].device != passage_embeddings[0].device:
|
| 383 |
+
raise ValueError("Queries and passages must be on the same device")
|
| 384 |
+
|
| 385 |
+
if query_embeddings[0].dtype != passage_embeddings[0].dtype:
|
| 386 |
+
raise ValueError("Queries and passages must have the same dtype")
|
| 387 |
+
|
| 388 |
+
if output_dtype is None:
|
| 389 |
+
output_dtype = query_embeddings[0].dtype
|
| 390 |
+
|
| 391 |
+
scores: list[torch.Tensor] = []
|
| 392 |
+
|
| 393 |
+
for i in range(0, len(query_embeddings), batch_size):
|
| 394 |
+
batch_scores: list[torch.Tensor] = []
|
| 395 |
+
batch_queries = torch.nn.utils.rnn.pad_sequence(
|
| 396 |
+
query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
|
| 397 |
+
)
|
| 398 |
+
for j in range(0, len(passage_embeddings), batch_size):
|
| 399 |
+
batch_passages = torch.nn.utils.rnn.pad_sequence(
|
| 400 |
+
passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
|
| 401 |
+
)
|
| 402 |
+
batch_scores.append(
|
| 403 |
+
torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
|
| 404 |
+
)
|
| 405 |
+
scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
|
| 406 |
+
|
| 407 |
+
return torch.cat(scores, dim=0)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
__all__ = ["ColPaliProcessor"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/cpm/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .tokenization_cpm import *
|
| 22 |
+
from .tokenization_cpm_fast import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/cpm/tokenization_cpm.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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I Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import unicodedata
|
| 19 |
+
from shutil import copyfile
|
| 20 |
+
from typing import Any, Optional
|
| 21 |
+
|
| 22 |
+
import sentencepiece as spm
|
| 23 |
+
|
| 24 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 25 |
+
from ...utils import SPIECE_UNDERLINE, logging
|
| 26 |
+
from ...utils.import_utils import requires
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@requires(backends=("sentencepiece",))
|
| 35 |
+
class CpmTokenizer(PreTrainedTokenizer):
|
| 36 |
+
"""Runs pre-tokenization with Jieba-RS segmentation tool. It is used in CPM models."""
|
| 37 |
+
|
| 38 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
vocab_file,
|
| 43 |
+
do_lower_case=False,
|
| 44 |
+
remove_space=True,
|
| 45 |
+
keep_accents=False,
|
| 46 |
+
bos_token="<s>",
|
| 47 |
+
eos_token="</s>",
|
| 48 |
+
unk_token="<unk>",
|
| 49 |
+
sep_token="<sep>",
|
| 50 |
+
pad_token="<pad>",
|
| 51 |
+
cls_token="<cls>",
|
| 52 |
+
mask_token="<mask>",
|
| 53 |
+
additional_special_tokens=["<eop>", "<eod>"],
|
| 54 |
+
sp_model_kwargs: Optional[dict[str, Any]] = None,
|
| 55 |
+
**kwargs,
|
| 56 |
+
) -> None:
|
| 57 |
+
"""
|
| 58 |
+
Construct a CPM tokenizer. Based on [Jieba-RS](https://pypi.org/project/rjieba/) and
|
| 59 |
+
[SentencePiece](https://github.com/google/sentencepiece).
|
| 60 |
+
|
| 61 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
|
| 62 |
+
refer to this superclass for more information regarding those methods.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
vocab_file (`str`):
|
| 66 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
|
| 67 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 68 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 69 |
+
Whether to lowercase the input when tokenizing.
|
| 70 |
+
remove_space (`bool`, *optional*, defaults to `True`):
|
| 71 |
+
Whether to strip the text when tokenizing (removing excess spaces before and after the string).
|
| 72 |
+
keep_accents (`bool`, *optional*, defaults to `False`):
|
| 73 |
+
Whether to keep accents when tokenizing.
|
| 74 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 75 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
|
| 76 |
+
token.
|
| 77 |
+
|
| 78 |
+
<Tip>
|
| 79 |
+
|
| 80 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 81 |
+
sequence. The token used is the `cls_token`.
|
| 82 |
+
|
| 83 |
+
</Tip>
|
| 84 |
+
|
| 85 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 86 |
+
The end of sequence token.
|
| 87 |
+
|
| 88 |
+
<Tip>
|
| 89 |
+
|
| 90 |
+
When building a sequence using special tokens, this is not the token that is used for the end of
|
| 91 |
+
sequence. The token used is the `sep_token`.
|
| 92 |
+
|
| 93 |
+
</Tip>
|
| 94 |
+
|
| 95 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 96 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
|
| 97 |
+
this token instead.
|
| 98 |
+
sep_token (`str`, *optional*, defaults to `"<sep>"`):
|
| 99 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
|
| 100 |
+
for sequence classification or for a text and a question for question answering. It is also used as the
|
| 101 |
+
last token of a sequence built with special tokens.
|
| 102 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 103 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 104 |
+
cls_token (`str`, *optional*, defaults to `"<cls>"`):
|
| 105 |
+
The classifier token which is used when doing sequence classification (classification of the whole
|
| 106 |
+
sequence instead of per-token classification). It is the first token of the sequence when built with
|
| 107 |
+
special tokens.
|
| 108 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 109 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 110 |
+
modeling. This is the token which the model will try to predict.
|
| 111 |
+
additional_special_tokens (`list[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
|
| 112 |
+
Additional special tokens used by the tokenizer.
|
| 113 |
+
|
| 114 |
+
Attributes:
|
| 115 |
+
sp_model (`SentencePieceProcessor`):
|
| 116 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 117 |
+
"""
|
| 118 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 119 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 120 |
+
|
| 121 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 122 |
+
|
| 123 |
+
self.do_lower_case = do_lower_case
|
| 124 |
+
self.remove_space = remove_space
|
| 125 |
+
self.keep_accents = keep_accents
|
| 126 |
+
self.vocab_file = vocab_file
|
| 127 |
+
|
| 128 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 129 |
+
self.sp_model.Load(vocab_file)
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
import rjieba
|
| 133 |
+
except ModuleNotFoundError as error:
|
| 134 |
+
raise error.__class__(
|
| 135 |
+
"You need to install rjieba to use CpmTokenizer or CpmTokenizerFast. "
|
| 136 |
+
"See https://pypi.org/project/rjieba/ for installation."
|
| 137 |
+
)
|
| 138 |
+
self.jieba = rjieba
|
| 139 |
+
self.translator = str.maketrans(" \n", "\u2582\u2583")
|
| 140 |
+
|
| 141 |
+
super().__init__(
|
| 142 |
+
do_lower_case=do_lower_case,
|
| 143 |
+
remove_space=remove_space,
|
| 144 |
+
keep_accents=keep_accents,
|
| 145 |
+
bos_token=bos_token,
|
| 146 |
+
eos_token=eos_token,
|
| 147 |
+
unk_token=unk_token,
|
| 148 |
+
sep_token=sep_token,
|
| 149 |
+
pad_token=pad_token,
|
| 150 |
+
cls_token=cls_token,
|
| 151 |
+
mask_token=mask_token,
|
| 152 |
+
additional_special_tokens=additional_special_tokens,
|
| 153 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 154 |
+
**kwargs,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
self._pad_token_type_id = 3
|
| 158 |
+
|
| 159 |
+
@property
|
| 160 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
|
| 161 |
+
def vocab_size(self):
|
| 162 |
+
return len(self.sp_model)
|
| 163 |
+
|
| 164 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.get_vocab
|
| 165 |
+
def get_vocab(self):
|
| 166 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 167 |
+
vocab.update(self.added_tokens_encoder)
|
| 168 |
+
return vocab
|
| 169 |
+
|
| 170 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.__getstate__
|
| 171 |
+
def __getstate__(self):
|
| 172 |
+
state = self.__dict__.copy()
|
| 173 |
+
state["sp_model"] = None
|
| 174 |
+
return state
|
| 175 |
+
|
| 176 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.__setstate__
|
| 177 |
+
def __setstate__(self, d):
|
| 178 |
+
self.__dict__ = d
|
| 179 |
+
|
| 180 |
+
# for backward compatibility
|
| 181 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 182 |
+
self.sp_model_kwargs = {}
|
| 183 |
+
|
| 184 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 185 |
+
self.sp_model.Load(self.vocab_file)
|
| 186 |
+
|
| 187 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.preprocess_text
|
| 188 |
+
def preprocess_text(self, inputs):
|
| 189 |
+
if self.remove_space:
|
| 190 |
+
outputs = " ".join(inputs.strip().split())
|
| 191 |
+
else:
|
| 192 |
+
outputs = inputs
|
| 193 |
+
outputs = outputs.replace("``", '"').replace("''", '"')
|
| 194 |
+
|
| 195 |
+
if not self.keep_accents:
|
| 196 |
+
outputs = unicodedata.normalize("NFKD", outputs)
|
| 197 |
+
outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
|
| 198 |
+
if self.do_lower_case:
|
| 199 |
+
outputs = outputs.lower()
|
| 200 |
+
|
| 201 |
+
return outputs
|
| 202 |
+
|
| 203 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer._tokenize
|
| 204 |
+
def _tokenize(self, text: str) -> list[str]:
|
| 205 |
+
"""Tokenize a string."""
|
| 206 |
+
text = self.preprocess_text(text)
|
| 207 |
+
pieces = self.sp_model.encode(text, out_type=str)
|
| 208 |
+
new_pieces = []
|
| 209 |
+
for piece in pieces:
|
| 210 |
+
if len(piece) > 1 and piece[-1] == "," and piece[-2].isdigit():
|
| 211 |
+
cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
|
| 212 |
+
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
|
| 213 |
+
if len(cur_pieces[0]) == 1:
|
| 214 |
+
cur_pieces = cur_pieces[1:]
|
| 215 |
+
else:
|
| 216 |
+
cur_pieces[0] = cur_pieces[0][1:]
|
| 217 |
+
cur_pieces.append(piece[-1])
|
| 218 |
+
new_pieces.extend(cur_pieces)
|
| 219 |
+
else:
|
| 220 |
+
new_pieces.append(piece)
|
| 221 |
+
|
| 222 |
+
return new_pieces
|
| 223 |
+
|
| 224 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer._convert_token_to_id
|
| 225 |
+
def _convert_token_to_id(self, token):
|
| 226 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 227 |
+
return self.sp_model.PieceToId(token)
|
| 228 |
+
|
| 229 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer._convert_id_to_token
|
| 230 |
+
def _convert_id_to_token(self, index):
|
| 231 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 232 |
+
return self.sp_model.IdToPiece(index)
|
| 233 |
+
|
| 234 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.convert_tokens_to_string
|
| 235 |
+
def convert_tokens_to_string(self, tokens):
|
| 236 |
+
"""Converts a sequence of tokens (strings for sub-words) in a single string."""
|
| 237 |
+
out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
|
| 238 |
+
return out_string
|
| 239 |
+
|
| 240 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.build_inputs_with_special_tokens
|
| 241 |
+
def build_inputs_with_special_tokens(
|
| 242 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 243 |
+
) -> list[int]:
|
| 244 |
+
"""
|
| 245 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 246 |
+
adding special tokens. An XLNet sequence has the following format:
|
| 247 |
+
|
| 248 |
+
- single sequence: `X <sep> <cls>`
|
| 249 |
+
- pair of sequences: `A <sep> B <sep> <cls>`
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
token_ids_0 (`list[int]`):
|
| 253 |
+
List of IDs to which the special tokens will be added.
|
| 254 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 255 |
+
Optional second list of IDs for sequence pairs.
|
| 256 |
+
|
| 257 |
+
Returns:
|
| 258 |
+
`list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 259 |
+
"""
|
| 260 |
+
sep = [self.sep_token_id]
|
| 261 |
+
cls = [self.cls_token_id]
|
| 262 |
+
if token_ids_1 is None:
|
| 263 |
+
return token_ids_0 + sep + cls
|
| 264 |
+
return token_ids_0 + sep + token_ids_1 + sep + cls
|
| 265 |
+
|
| 266 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.get_special_tokens_mask
|
| 267 |
+
def get_special_tokens_mask(
|
| 268 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
|
| 269 |
+
) -> list[int]:
|
| 270 |
+
"""
|
| 271 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 272 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 273 |
+
|
| 274 |
+
Args:
|
| 275 |
+
token_ids_0 (`list[int]`):
|
| 276 |
+
List of IDs.
|
| 277 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 278 |
+
Optional second list of IDs for sequence pairs.
|
| 279 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 280 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 281 |
+
|
| 282 |
+
Returns:
|
| 283 |
+
`list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
if already_has_special_tokens:
|
| 287 |
+
return super().get_special_tokens_mask(
|
| 288 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
if token_ids_1 is not None:
|
| 292 |
+
return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1, 1]
|
| 293 |
+
return ([0] * len(token_ids_0)) + [1, 1]
|
| 294 |
+
|
| 295 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.create_token_type_ids_from_sequences
|
| 296 |
+
def create_token_type_ids_from_sequences(
|
| 297 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 298 |
+
) -> list[int]:
|
| 299 |
+
"""
|
| 300 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
|
| 301 |
+
sequence pair mask has the following format:
|
| 302 |
+
|
| 303 |
+
```
|
| 304 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 305 |
+
| first sequence | second sequence |
|
| 306 |
+
```
|
| 307 |
+
|
| 308 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 309 |
+
|
| 310 |
+
Args:
|
| 311 |
+
token_ids_0 (`list[int]`):
|
| 312 |
+
List of IDs.
|
| 313 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 314 |
+
Optional second list of IDs for sequence pairs.
|
| 315 |
+
|
| 316 |
+
Returns:
|
| 317 |
+
`list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 318 |
+
"""
|
| 319 |
+
sep = [self.sep_token_id]
|
| 320 |
+
cls_segment_id = [2]
|
| 321 |
+
|
| 322 |
+
if token_ids_1 is None:
|
| 323 |
+
return len(token_ids_0 + sep) * [0] + cls_segment_id
|
| 324 |
+
return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
|
| 325 |
+
|
| 326 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.save_vocabulary
|
| 327 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 328 |
+
if not os.path.isdir(save_directory):
|
| 329 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 330 |
+
return
|
| 331 |
+
out_vocab_file = os.path.join(
|
| 332 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 336 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 337 |
+
elif not os.path.isfile(self.vocab_file):
|
| 338 |
+
with open(out_vocab_file, "wb") as fi:
|
| 339 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 340 |
+
fi.write(content_spiece_model)
|
| 341 |
+
|
| 342 |
+
return (out_vocab_file,)
|
| 343 |
+
|
| 344 |
+
def _decode(self, *args, **kwargs):
|
| 345 |
+
text = super()._decode(*args, **kwargs)
|
| 346 |
+
text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
|
| 347 |
+
return text
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
__all__ = ["CpmTokenizer"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/cpm/tokenization_cpm_fast.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from shutil import copyfile
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
from ...tokenization_utils_fast import AddedToken, PreTrainedTokenizerFast
|
| 22 |
+
from ...utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class CpmTokenizerFast(PreTrainedTokenizerFast):
|
| 31 |
+
"""Runs pre-tokenization with Jieba-RS segmentation tool. It is used in CPM models."""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
vocab_file=None,
|
| 36 |
+
tokenizer_file=None,
|
| 37 |
+
do_lower_case=False,
|
| 38 |
+
remove_space=True,
|
| 39 |
+
keep_accents=False,
|
| 40 |
+
bos_token="<s>",
|
| 41 |
+
eos_token="</s>",
|
| 42 |
+
unk_token="<unk>",
|
| 43 |
+
sep_token="<sep>",
|
| 44 |
+
pad_token="<pad>",
|
| 45 |
+
cls_token="<cls>",
|
| 46 |
+
mask_token="<mask>",
|
| 47 |
+
additional_special_tokens=["<eop>", "<eod>"],
|
| 48 |
+
**kwargs,
|
| 49 |
+
):
|
| 50 |
+
"""
|
| 51 |
+
Construct a CPM tokenizer. Based on [Jieba-RS](https://pypi.org/project/rjieba/) and
|
| 52 |
+
[SentencePiece](https://github.com/google/sentencepiece).
|
| 53 |
+
|
| 54 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
|
| 55 |
+
refer to this superclass for more information regarding those methods.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
vocab_file (`str`):
|
| 59 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
|
| 60 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 61 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 62 |
+
Whether to lowercase the input when tokenizing.
|
| 63 |
+
remove_space (`bool`, *optional*, defaults to `True`):
|
| 64 |
+
Whether to strip the text when tokenizing (removing excess spaces before and after the string).
|
| 65 |
+
keep_accents (`bool`, *optional*, defaults to `False`):
|
| 66 |
+
Whether to keep accents when tokenizing.
|
| 67 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 68 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
|
| 69 |
+
token.
|
| 70 |
+
|
| 71 |
+
<Tip>
|
| 72 |
+
|
| 73 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 74 |
+
sequence. The token used is the `cls_token`.
|
| 75 |
+
|
| 76 |
+
</Tip>
|
| 77 |
+
|
| 78 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 79 |
+
The end of sequence token.
|
| 80 |
+
|
| 81 |
+
<Tip>
|
| 82 |
+
|
| 83 |
+
When building a sequence using special tokens, this is not the token that is used for the end of
|
| 84 |
+
sequence. The token used is the `sep_token`.
|
| 85 |
+
|
| 86 |
+
</Tip>
|
| 87 |
+
|
| 88 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 89 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
|
| 90 |
+
this token instead.
|
| 91 |
+
sep_token (`str`, *optional*, defaults to `"<sep>"`):
|
| 92 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
|
| 93 |
+
for sequence classification or for a text and a question for question answering. It is also used as the
|
| 94 |
+
last token of a sequence built with special tokens.
|
| 95 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 96 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 97 |
+
cls_token (`str`, *optional*, defaults to `"<cls>"`):
|
| 98 |
+
The classifier token which is used when doing sequence classification (classification of the whole
|
| 99 |
+
sequence instead of per-token classification). It is the first token of the sequence when built with
|
| 100 |
+
special tokens.
|
| 101 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
| 102 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 103 |
+
modeling. This is the token which the model will try to predict.
|
| 104 |
+
additional_special_tokens (`list[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
|
| 105 |
+
Additional special tokens used by the tokenizer.
|
| 106 |
+
|
| 107 |
+
Attributes:
|
| 108 |
+
sp_model (`SentencePieceProcessor`):
|
| 109 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 110 |
+
"""
|
| 111 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
| 112 |
+
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
|
| 113 |
+
|
| 114 |
+
super().__init__(
|
| 115 |
+
vocab_file=vocab_file,
|
| 116 |
+
tokenizer_file=tokenizer_file,
|
| 117 |
+
do_lower_case=do_lower_case,
|
| 118 |
+
remove_space=remove_space,
|
| 119 |
+
keep_accents=keep_accents,
|
| 120 |
+
bos_token=bos_token,
|
| 121 |
+
eos_token=eos_token,
|
| 122 |
+
unk_token=unk_token,
|
| 123 |
+
sep_token=sep_token,
|
| 124 |
+
pad_token=pad_token,
|
| 125 |
+
cls_token=cls_token,
|
| 126 |
+
mask_token=mask_token,
|
| 127 |
+
additional_special_tokens=additional_special_tokens,
|
| 128 |
+
**kwargs,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
self._pad_token_type_id = 3
|
| 132 |
+
self.do_lower_case = do_lower_case
|
| 133 |
+
self.remove_space = remove_space
|
| 134 |
+
self.keep_accents = keep_accents
|
| 135 |
+
self.vocab_file = vocab_file
|
| 136 |
+
|
| 137 |
+
try:
|
| 138 |
+
import rjieba
|
| 139 |
+
except ModuleNotFoundError as error:
|
| 140 |
+
raise error.__class__(
|
| 141 |
+
"You need to install rjieba to use CpmTokenizer or CpmTokenizerFast. "
|
| 142 |
+
"See https://pypi.org/project/rjieba/ for installation."
|
| 143 |
+
)
|
| 144 |
+
self.jieba = rjieba
|
| 145 |
+
self.translator = str.maketrans(" \n", "\u2582\u2583")
|
| 146 |
+
|
| 147 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet_fast.XLNetTokenizerFast.build_inputs_with_special_tokens
|
| 148 |
+
def build_inputs_with_special_tokens(
|
| 149 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 150 |
+
) -> list[int]:
|
| 151 |
+
"""
|
| 152 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 153 |
+
adding special tokens. An XLNet sequence has the following format:
|
| 154 |
+
|
| 155 |
+
- single sequence: `X <sep> <cls>`
|
| 156 |
+
- pair of sequences: `A <sep> B <sep> <cls>`
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
token_ids_0 (`list[int]`):
|
| 160 |
+
List of IDs to which the special tokens will be added.
|
| 161 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 162 |
+
Optional second list of IDs for sequence pairs.
|
| 163 |
+
|
| 164 |
+
Returns:
|
| 165 |
+
`list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 166 |
+
"""
|
| 167 |
+
sep = [self.sep_token_id]
|
| 168 |
+
cls = [self.cls_token_id]
|
| 169 |
+
if token_ids_1 is None:
|
| 170 |
+
return token_ids_0 + sep + cls
|
| 171 |
+
return token_ids_0 + sep + token_ids_1 + sep + cls
|
| 172 |
+
|
| 173 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet_fast.XLNetTokenizerFast.create_token_type_ids_from_sequences
|
| 174 |
+
def create_token_type_ids_from_sequences(
|
| 175 |
+
self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
|
| 176 |
+
) -> list[int]:
|
| 177 |
+
"""
|
| 178 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
|
| 179 |
+
sequence pair mask has the following format:
|
| 180 |
+
|
| 181 |
+
```
|
| 182 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 183 |
+
| first sequence | second sequence |
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 187 |
+
|
| 188 |
+
Args:
|
| 189 |
+
token_ids_0 (`list[int]`):
|
| 190 |
+
List of IDs.
|
| 191 |
+
token_ids_1 (`list[int]`, *optional*):
|
| 192 |
+
Optional second list of IDs for sequence pairs.
|
| 193 |
+
|
| 194 |
+
Returns:
|
| 195 |
+
`list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 196 |
+
"""
|
| 197 |
+
sep = [self.sep_token_id]
|
| 198 |
+
cls_segment_id = [2]
|
| 199 |
+
|
| 200 |
+
if token_ids_1 is None:
|
| 201 |
+
return len(token_ids_0 + sep) * [0] + cls_segment_id
|
| 202 |
+
return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
|
| 203 |
+
|
| 204 |
+
# Copied from transformers.models.xlnet.tokenization_xlnet_fast.XLNetTokenizerFast.save_vocabulary
|
| 205 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 206 |
+
if not self.can_save_slow_tokenizer:
|
| 207 |
+
raise ValueError(
|
| 208 |
+
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
|
| 209 |
+
"tokenizer."
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
if not os.path.isdir(save_directory):
|
| 213 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 214 |
+
return
|
| 215 |
+
out_vocab_file = os.path.join(
|
| 216 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
| 220 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 221 |
+
|
| 222 |
+
return (out_vocab_file,)
|
| 223 |
+
|
| 224 |
+
def _batch_encode_plus(self, batch_text_or_text_pairs, *args, **kwargs):
|
| 225 |
+
batch_text_or_text_pairs = [
|
| 226 |
+
" ".join([x.translate(self.translator) for x in self.jieba.cut(text, False)])
|
| 227 |
+
for text in batch_text_or_text_pairs
|
| 228 |
+
]
|
| 229 |
+
return super()._batch_encode_plus(batch_text_or_text_pairs, *args, **kwargs)
|
| 230 |
+
|
| 231 |
+
def _decode(self, *args, **kwargs):
|
| 232 |
+
text = super()._decode(*args, **kwargs)
|
| 233 |
+
text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
|
| 234 |
+
return text
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
__all__ = ["CpmTokenizerFast"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/__init__.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .bort import *
|
| 22 |
+
from .deta import *
|
| 23 |
+
from .efficientformer import *
|
| 24 |
+
from .ernie_m import *
|
| 25 |
+
from .gptsan_japanese import *
|
| 26 |
+
from .graphormer import *
|
| 27 |
+
from .jukebox import *
|
| 28 |
+
from .mctct import *
|
| 29 |
+
from .mega import *
|
| 30 |
+
from .mmbt import *
|
| 31 |
+
from .nat import *
|
| 32 |
+
from .nezha import *
|
| 33 |
+
from .open_llama import *
|
| 34 |
+
from .qdqbert import *
|
| 35 |
+
from .realm import *
|
| 36 |
+
from .retribert import *
|
| 37 |
+
from .speech_to_text_2 import *
|
| 38 |
+
from .tapex import *
|
| 39 |
+
from .trajectory_transformer import *
|
| 40 |
+
from .transfo_xl import *
|
| 41 |
+
from .tvlt import *
|
| 42 |
+
from .van import *
|
| 43 |
+
from .vit_hybrid import *
|
| 44 |
+
from .xlm_prophetnet import *
|
| 45 |
+
else:
|
| 46 |
+
import sys
|
| 47 |
+
|
| 48 |
+
_file = globals()["__file__"]
|
| 49 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dinov3_vit/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_dinov3_vit import *
|
| 22 |
+
from .image_processing_dinov3_vit_fast import *
|
| 23 |
+
from .modeling_dinov3_vit import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dinov3_vit/configuration_dinov3_vit.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 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 |
+
"""DINOv3 model configuration"""
|
| 16 |
+
|
| 17 |
+
from typing import Optional
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PretrainedConfig
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class DINOv3ViTConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`DINOv3Model`]. It is used to instantiate an
|
| 29 |
+
DINOv3 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 30 |
+
with the defaults will yield a similar configuration to that of the DINOv3
|
| 31 |
+
[facebook/dinov3-vits16-pretrain-lvd1689m](https://huggingface.co/facebook/dinov3-vits16-pretrain-lvd1689m) architecture.
|
| 32 |
+
|
| 33 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 34 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 38 |
+
The size (resolution) of each patch.
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 384):
|
| 40 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 41 |
+
intermediate_size (`int`, *optional*, defaults to 1536):
|
| 42 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer.
|
| 43 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 44 |
+
Number of hidden layers in the Transformer encoder.
|
| 45 |
+
num_attention_heads (`int`, *optional*, defaults to 6):
|
| 46 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 47 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 48 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 49 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 50 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 51 |
+
The dropout ratio for the attention probabilities.
|
| 52 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 53 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 54 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 55 |
+
The epsilon used by the layer normalization layers.
|
| 56 |
+
rope_theta (`float`, *optional*, defaults to 100.0):
|
| 57 |
+
The base period of the RoPE embeddings.
|
| 58 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 59 |
+
The size (resolution) of each image.
|
| 60 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 61 |
+
The number of input channels.
|
| 62 |
+
query_bias (`bool`, *optional*, defaults to `True`):
|
| 63 |
+
Whether to add a bias to the query projection.
|
| 64 |
+
key_bias (`bool`, *optional*, defaults to `False`):
|
| 65 |
+
Whether to add a bias to the key projection.
|
| 66 |
+
value_bias (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether to add a bias to the value projection.
|
| 68 |
+
proj_bias (`bool`, *optional*, defaults to `True`):
|
| 69 |
+
Whether to add a bias to the output projection.
|
| 70 |
+
mlp_bias (`bool`, *optional*, defaults to `True`):
|
| 71 |
+
Whether to add a bias to the MLP layers.
|
| 72 |
+
layerscale_value (`float`, *optional*, defaults to 1.0):
|
| 73 |
+
Initial value to use for layer scale.
|
| 74 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 75 |
+
Stochastic depth rate per sample (when applied in the main path of residual layers).
|
| 76 |
+
use_gated_mlp (`bool`, *optional*, defaults to `False`):
|
| 77 |
+
Whether to use the SwiGLU feedforward neural network.
|
| 78 |
+
num_register_tokens (`int`, *optional*, defaults to 0):
|
| 79 |
+
The number of register tokens.
|
| 80 |
+
pos_embed_shift (`float`, *optional*):
|
| 81 |
+
Amount to randomly shift position embedding coordinates in [-shift, shift],
|
| 82 |
+
applied only in training mode if not `None`.
|
| 83 |
+
pos_embed_jitter (`float`, *optional*):
|
| 84 |
+
Amount to randomly jitter position embedding coordinates in log-uniform value in [1/jitter, jitter],
|
| 85 |
+
applied only in training mode if not `None`.
|
| 86 |
+
pos_embed_rescale (`float`, *optional*, defaults to 2.0):
|
| 87 |
+
Amount to randomly rescale position embedding coordinates in log-uniform value in [1/rescale, rescale],
|
| 88 |
+
applied only in training mode if not `None`.
|
| 89 |
+
|
| 90 |
+
Example:
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
>>> from transformers import DINOv3ViTConfig, DINOv3ViTModel
|
| 94 |
+
|
| 95 |
+
>>> # Initializing a DINOv3 ViT-small style configuration
|
| 96 |
+
>>> config = DINOv3ViTConfig()
|
| 97 |
+
|
| 98 |
+
>>> # Initializing a model (with random weights) from the config
|
| 99 |
+
>>> model = DINOv3ViTModel(config)
|
| 100 |
+
|
| 101 |
+
>>> # Accessing the model config
|
| 102 |
+
>>> config = model.config
|
| 103 |
+
```"""
|
| 104 |
+
|
| 105 |
+
model_type = "dinov3_vit"
|
| 106 |
+
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
patch_size: int = 16,
|
| 110 |
+
hidden_size: int = 384,
|
| 111 |
+
intermediate_size: int = 1536,
|
| 112 |
+
num_hidden_layers: int = 12,
|
| 113 |
+
num_attention_heads: int = 6,
|
| 114 |
+
hidden_act: str = "gelu",
|
| 115 |
+
attention_dropout: float = 0.0,
|
| 116 |
+
initializer_range: float = 0.02,
|
| 117 |
+
layer_norm_eps: float = 1e-5,
|
| 118 |
+
rope_theta: float = 100.0,
|
| 119 |
+
image_size: int = 224,
|
| 120 |
+
num_channels: int = 3,
|
| 121 |
+
query_bias: bool = True,
|
| 122 |
+
key_bias: bool = False,
|
| 123 |
+
value_bias: bool = True,
|
| 124 |
+
proj_bias: bool = True,
|
| 125 |
+
mlp_bias: bool = True,
|
| 126 |
+
layerscale_value: float = 1.0,
|
| 127 |
+
drop_path_rate: float = 0.0,
|
| 128 |
+
use_gated_mlp: bool = False,
|
| 129 |
+
num_register_tokens: int = 0,
|
| 130 |
+
# train augs
|
| 131 |
+
pos_embed_shift: Optional[float] = None,
|
| 132 |
+
pos_embed_jitter: Optional[float] = None,
|
| 133 |
+
pos_embed_rescale: Optional[float] = 2.0,
|
| 134 |
+
**kwargs,
|
| 135 |
+
):
|
| 136 |
+
super().__init__(**kwargs)
|
| 137 |
+
|
| 138 |
+
self.image_size = image_size
|
| 139 |
+
self.patch_size = patch_size
|
| 140 |
+
self.num_channels = num_channels
|
| 141 |
+
self.hidden_size = hidden_size
|
| 142 |
+
self.intermediate_size = intermediate_size
|
| 143 |
+
self.num_hidden_layers = num_hidden_layers
|
| 144 |
+
self.num_attention_heads = num_attention_heads
|
| 145 |
+
self.hidden_act = hidden_act
|
| 146 |
+
self.attention_dropout = attention_dropout
|
| 147 |
+
self.initializer_range = initializer_range
|
| 148 |
+
self.layer_norm_eps = layer_norm_eps
|
| 149 |
+
self.layerscale_value = layerscale_value
|
| 150 |
+
self.drop_path_rate = drop_path_rate
|
| 151 |
+
self.use_gated_mlp = use_gated_mlp
|
| 152 |
+
self.rope_theta = rope_theta
|
| 153 |
+
self.query_bias = query_bias
|
| 154 |
+
self.key_bias = key_bias
|
| 155 |
+
self.value_bias = value_bias
|
| 156 |
+
self.proj_bias = proj_bias
|
| 157 |
+
self.mlp_bias = mlp_bias
|
| 158 |
+
self.num_register_tokens = num_register_tokens
|
| 159 |
+
|
| 160 |
+
# train augs
|
| 161 |
+
self.pos_embed_shift = pos_embed_shift
|
| 162 |
+
self.pos_embed_jitter = pos_embed_jitter
|
| 163 |
+
self.pos_embed_rescale = pos_embed_rescale
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
__all__ = ["DINOv3ViTConfig"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dinov3_vit/image_processing_dinov3_vit_fast.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Fast Image processor class for DINOv3."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from torchvision.transforms.v2 import functional as F
|
| 21 |
+
|
| 22 |
+
from transformers.image_processing_base import BatchFeature
|
| 23 |
+
from transformers.image_processing_utils_fast import BaseImageProcessorFast, group_images_by_shape, reorder_images
|
| 24 |
+
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling, SizeDict
|
| 25 |
+
from transformers.utils import (
|
| 26 |
+
TensorType,
|
| 27 |
+
auto_docstring,
|
| 28 |
+
logging,
|
| 29 |
+
)
|
| 30 |
+
from transformers.utils.import_utils import requires
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@auto_docstring
|
| 37 |
+
@requires(backends=("torchvision", "torch"))
|
| 38 |
+
class DINOv3ViTImageProcessorFast(BaseImageProcessorFast):
|
| 39 |
+
resample = PILImageResampling.BILINEAR
|
| 40 |
+
image_mean = IMAGENET_DEFAULT_MEAN
|
| 41 |
+
image_std = IMAGENET_DEFAULT_STD
|
| 42 |
+
size = {"height": 224, "width": 224}
|
| 43 |
+
do_resize = True
|
| 44 |
+
do_rescale = True
|
| 45 |
+
do_normalize = True
|
| 46 |
+
|
| 47 |
+
# Overridden for DINOv3 to preserve order of transforms
|
| 48 |
+
# rescale -> resize -> normalize
|
| 49 |
+
def _preprocess(
|
| 50 |
+
self,
|
| 51 |
+
images: list["torch.Tensor"],
|
| 52 |
+
do_resize: bool,
|
| 53 |
+
size: SizeDict,
|
| 54 |
+
interpolation: Optional["F.InterpolationMode"],
|
| 55 |
+
do_center_crop: bool,
|
| 56 |
+
crop_size: SizeDict,
|
| 57 |
+
do_rescale: bool,
|
| 58 |
+
rescale_factor: float,
|
| 59 |
+
do_normalize: bool,
|
| 60 |
+
image_mean: Optional[Union[float, list[float]]],
|
| 61 |
+
image_std: Optional[Union[float, list[float]]],
|
| 62 |
+
disable_grouping: Optional[bool],
|
| 63 |
+
return_tensors: Optional[Union[str, TensorType]],
|
| 64 |
+
**kwargs,
|
| 65 |
+
) -> BatchFeature:
|
| 66 |
+
# Group images by size for batched resizing
|
| 67 |
+
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
|
| 68 |
+
resized_images_grouped = {}
|
| 69 |
+
for shape, stacked_images in grouped_images.items():
|
| 70 |
+
if do_rescale:
|
| 71 |
+
stacked_images = self.rescale(stacked_images, rescale_factor)
|
| 72 |
+
if do_resize:
|
| 73 |
+
stacked_images = self.resize(
|
| 74 |
+
image=stacked_images, size=size, interpolation=interpolation, antialias=True
|
| 75 |
+
)
|
| 76 |
+
resized_images_grouped[shape] = stacked_images
|
| 77 |
+
resized_images = reorder_images(resized_images_grouped, grouped_images_index)
|
| 78 |
+
|
| 79 |
+
# Group images by size for further processing
|
| 80 |
+
# Needed in case do_resize is False, or resize returns images with different sizes
|
| 81 |
+
grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
|
| 82 |
+
processed_images_grouped = {}
|
| 83 |
+
for shape, stacked_images in grouped_images.items():
|
| 84 |
+
if do_center_crop:
|
| 85 |
+
stacked_images = self.center_crop(stacked_images, crop_size)
|
| 86 |
+
if do_normalize:
|
| 87 |
+
stacked_images = self.normalize(stacked_images, image_mean, image_std)
|
| 88 |
+
processed_images_grouped[shape] = stacked_images
|
| 89 |
+
|
| 90 |
+
processed_images = reorder_images(processed_images_grouped, grouped_images_index)
|
| 91 |
+
processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images
|
| 92 |
+
|
| 93 |
+
return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
__all__ = ["DINOv3ViTImageProcessorFast"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dinov3_vit/modeling_dinov3_vit.py
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/dinov3_vit/modular_dinov3_vit.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_dinov3_vit.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 Meta AI and The HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
import math
|
| 23 |
+
from typing import Callable, Optional
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import torch
|
| 27 |
+
from torch import nn
|
| 28 |
+
|
| 29 |
+
from ...activations import ACT2FN
|
| 30 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 31 |
+
from ...modeling_outputs import BaseModelOutputWithPooling
|
| 32 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 33 |
+
from ...processing_utils import Unpack
|
| 34 |
+
from ...pytorch_utils import compile_compatible_method_lru_cache
|
| 35 |
+
from ...utils import TransformersKwargs, auto_docstring
|
| 36 |
+
from ...utils.generic import check_model_inputs
|
| 37 |
+
from .configuration_dinov3_vit import DINOv3ViTConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class DINOv3ViTEmbeddings(nn.Module):
|
| 41 |
+
"""
|
| 42 |
+
Construct the CLS token, mask token, position and patch embeddings.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.config = config
|
| 48 |
+
self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 49 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 50 |
+
self.register_tokens = nn.Parameter(torch.empty(1, config.num_register_tokens, config.hidden_size))
|
| 51 |
+
self.patch_embeddings = nn.Conv2d(
|
| 52 |
+
config.num_channels, config.hidden_size, kernel_size=config.patch_size, stride=config.patch_size
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 56 |
+
batch_size = pixel_values.shape[0]
|
| 57 |
+
target_dtype = self.patch_embeddings.weight.dtype
|
| 58 |
+
|
| 59 |
+
# (batch_size, num_channels, height, width) -> (batch_size, num_patches, hidden_size)
|
| 60 |
+
patch_embeddings = self.patch_embeddings(pixel_values.to(dtype=target_dtype))
|
| 61 |
+
patch_embeddings = patch_embeddings.flatten(2).transpose(1, 2)
|
| 62 |
+
|
| 63 |
+
if bool_masked_pos is not None:
|
| 64 |
+
mask_token = self.mask_token.to(patch_embeddings.dtype)
|
| 65 |
+
patch_embeddings = torch.where(bool_masked_pos.unsqueeze(-1), mask_token, patch_embeddings)
|
| 66 |
+
|
| 67 |
+
# Add CLS and register tokens
|
| 68 |
+
cls_token = self.cls_token.expand(batch_size, -1, -1)
|
| 69 |
+
register_tokens = self.register_tokens.expand(batch_size, -1, -1)
|
| 70 |
+
embeddings = torch.cat([cls_token, register_tokens, patch_embeddings], dim=1)
|
| 71 |
+
|
| 72 |
+
return embeddings
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@compile_compatible_method_lru_cache(maxsize=32)
|
| 76 |
+
def get_patches_center_coordinates(
|
| 77 |
+
num_patches_h: int, num_patches_w: int, dtype: torch.dtype, device: torch.device
|
| 78 |
+
) -> torch.Tensor:
|
| 79 |
+
"""
|
| 80 |
+
Computes the 2D coordinates of the centers of image patches, normalized to the range [-1, +1].
|
| 81 |
+
The center of each patch is exactly halfway between its top-left and bottom-right corners.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
num_patches_h (int): Number of patches along the vertical (height) axis.
|
| 85 |
+
num_patches_w (int): Number of patches along the horizontal (width) axis.
|
| 86 |
+
dtype (torch.dtype): The desired data type of the returned tensor.
|
| 87 |
+
|
| 88 |
+
Returns:
|
| 89 |
+
torch.Tensor: A tensor of shape (height * width, 2), where each row contains the (y, x)
|
| 90 |
+
coordinates of a patch center, normalized to [-1, +1].
|
| 91 |
+
"""
|
| 92 |
+
coords_h = torch.arange(0.5, num_patches_h, dtype=dtype, device=device)
|
| 93 |
+
coords_w = torch.arange(0.5, num_patches_w, dtype=dtype, device=device)
|
| 94 |
+
coords_h = coords_h / num_patches_h
|
| 95 |
+
coords_w = coords_w / num_patches_w
|
| 96 |
+
# (height, width, 2) -> (height * width, 2)
|
| 97 |
+
coords = torch.stack(torch.meshgrid(coords_h, coords_w, indexing="ij"), dim=-1)
|
| 98 |
+
coords = coords.flatten(0, 1)
|
| 99 |
+
# Shift range [0, 1] to [-1, +1]
|
| 100 |
+
coords = 2.0 * coords - 1.0
|
| 101 |
+
return coords
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def augment_patches_center_coordinates(
|
| 105 |
+
coords: torch.Tensor,
|
| 106 |
+
shift: Optional[float] = None,
|
| 107 |
+
jitter: Optional[float] = None,
|
| 108 |
+
rescale: Optional[float] = None,
|
| 109 |
+
) -> torch.Tensor:
|
| 110 |
+
# Shift coords by adding a uniform value in [-shift, shift]
|
| 111 |
+
if shift is not None:
|
| 112 |
+
shift_hw = torch.empty((1, 2), device=coords.device, dtype=coords.dtype)
|
| 113 |
+
shift_hw = shift_hw.uniform_(-shift, shift)
|
| 114 |
+
coords = coords + shift_hw
|
| 115 |
+
|
| 116 |
+
# Jitter coords by multiplying the range [-1, 1] by a log-uniform value in [1/jitter, jitter]
|
| 117 |
+
if jitter is not None:
|
| 118 |
+
jitter_range = np.log(jitter)
|
| 119 |
+
jitter_hw = torch.empty((1, 2), device=coords.device, dtype=coords.dtype)
|
| 120 |
+
jitter_hw = jitter_hw.uniform_(-jitter_range, jitter_range).exp()
|
| 121 |
+
coords = coords * jitter_hw
|
| 122 |
+
|
| 123 |
+
# Rescale coords by multiplying the range [-1, 1] by a log-uniform value in [1/rescale, rescale]
|
| 124 |
+
if rescale is not None:
|
| 125 |
+
rescale_range = np.log(rescale)
|
| 126 |
+
rescale_hw = torch.empty(1, device=coords.device, dtype=coords.dtype)
|
| 127 |
+
rescale_hw = rescale_hw.uniform_(-rescale_range, rescale_range).exp()
|
| 128 |
+
coords = coords * rescale_hw
|
| 129 |
+
|
| 130 |
+
return coords
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class DINOv3ViTRopePositionEmbedding(nn.Module):
|
| 134 |
+
inv_freq: torch.Tensor
|
| 135 |
+
|
| 136 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 137 |
+
super().__init__()
|
| 138 |
+
|
| 139 |
+
self.config = config
|
| 140 |
+
self.base = config.rope_theta
|
| 141 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
| 142 |
+
self.num_patches_h = config.image_size // config.patch_size
|
| 143 |
+
self.num_patches_w = config.image_size // config.patch_size
|
| 144 |
+
|
| 145 |
+
inv_freq = 1 / self.base ** torch.arange(0, 1, 4 / self.head_dim, dtype=torch.float32) # (head_dim / 4,)
|
| 146 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 147 |
+
|
| 148 |
+
def forward(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 149 |
+
_, _, height, width = pixel_values.shape
|
| 150 |
+
num_patches_h = height // self.config.patch_size
|
| 151 |
+
num_patches_w = width // self.config.patch_size
|
| 152 |
+
|
| 153 |
+
device = pixel_values.device
|
| 154 |
+
device_type = device.type if isinstance(device.type, str) and device.type != "mps" else "cpu"
|
| 155 |
+
|
| 156 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 157 |
+
# Although we could precompute static patch_coords from image_size and patch_size in the config,
|
| 158 |
+
# the model was trained with random_scale, so it can process images of varying sizes.
|
| 159 |
+
# Therefore, it's better to compute patch_coords dynamically (with lru_cache).
|
| 160 |
+
patch_coords = get_patches_center_coordinates(
|
| 161 |
+
num_patches_h, num_patches_w, dtype=torch.float32, device=device
|
| 162 |
+
)
|
| 163 |
+
if self.training:
|
| 164 |
+
patch_coords = augment_patches_center_coordinates(
|
| 165 |
+
patch_coords,
|
| 166 |
+
shift=self.config.pos_embed_shift,
|
| 167 |
+
jitter=self.config.pos_embed_jitter,
|
| 168 |
+
rescale=self.config.pos_embed_rescale,
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
# (height * width, 2, head_dim / 4) -> (height * width, head_dim / 2) -> (height * width, head_dim)
|
| 172 |
+
angles = 2 * math.pi * patch_coords[:, :, None] * self.inv_freq[None, None, :]
|
| 173 |
+
angles = angles.flatten(1, 2)
|
| 174 |
+
angles = angles.tile(2)
|
| 175 |
+
|
| 176 |
+
cos = torch.cos(angles)
|
| 177 |
+
sin = torch.sin(angles)
|
| 178 |
+
|
| 179 |
+
dtype = pixel_values.dtype
|
| 180 |
+
return cos.to(dtype=dtype), sin.to(dtype=dtype)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def rotate_half(x):
|
| 184 |
+
"""Rotates half the hidden dims of the input."""
|
| 185 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 186 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 187 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def eager_attention_forward(
|
| 191 |
+
module: nn.Module,
|
| 192 |
+
query: torch.Tensor,
|
| 193 |
+
key: torch.Tensor,
|
| 194 |
+
value: torch.Tensor,
|
| 195 |
+
attention_mask: Optional[torch.Tensor],
|
| 196 |
+
scaling: float,
|
| 197 |
+
dropout: float = 0.0,
|
| 198 |
+
**kwargs,
|
| 199 |
+
):
|
| 200 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 201 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
|
| 202 |
+
|
| 203 |
+
# Normalize the attention scores to probabilities.
|
| 204 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 205 |
+
|
| 206 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 207 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 208 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 209 |
+
|
| 210 |
+
# Mask heads if we want to
|
| 211 |
+
if attention_mask is not None:
|
| 212 |
+
attn_weights = attn_weights * attention_mask
|
| 213 |
+
|
| 214 |
+
attn_output = torch.matmul(attn_weights, value)
|
| 215 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 216 |
+
|
| 217 |
+
return attn_output, attn_weights
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def apply_rotary_pos_emb(
|
| 221 |
+
q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, **kwargs
|
| 222 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 223 |
+
"""Applies Rotary Position Embedding to the query and key tensors, but only to the patch tokens,
|
| 224 |
+
ignoring the prefix tokens (cls token and register tokens).
|
| 225 |
+
|
| 226 |
+
Args:
|
| 227 |
+
q (`torch.Tensor`): The query tensor.
|
| 228 |
+
k (`torch.Tensor`): The key tensor.
|
| 229 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 230 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 231 |
+
|
| 232 |
+
Returns:
|
| 233 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 234 |
+
"""
|
| 235 |
+
|
| 236 |
+
num_tokens = q.shape[-2]
|
| 237 |
+
num_patches = sin.shape[-2]
|
| 238 |
+
num_prefix_tokens = num_tokens - num_patches # cls token + register tokens
|
| 239 |
+
|
| 240 |
+
q_prefix_tokens, q_patches = q.split((num_prefix_tokens, num_patches), dim=-2)
|
| 241 |
+
k_prefix_tokens, k_patches = k.split((num_prefix_tokens, num_patches), dim=-2)
|
| 242 |
+
|
| 243 |
+
# apply rope only to patch tokens
|
| 244 |
+
q_patches = (q_patches * cos) + (rotate_half(q_patches) * sin)
|
| 245 |
+
k_patches = (k_patches * cos) + (rotate_half(k_patches) * sin)
|
| 246 |
+
|
| 247 |
+
q = torch.cat((q_prefix_tokens, q_patches), dim=-2)
|
| 248 |
+
k = torch.cat((k_prefix_tokens, k_patches), dim=-2)
|
| 249 |
+
|
| 250 |
+
return q, k
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class DINOv3ViTAttention(nn.Module):
|
| 254 |
+
"""
|
| 255 |
+
Multi-headed attention compatible with ALL_ATTENTION_FUNCTIONS.
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 259 |
+
super().__init__()
|
| 260 |
+
self.config = config
|
| 261 |
+
self.embed_dim = config.hidden_size
|
| 262 |
+
self.num_heads = config.num_attention_heads
|
| 263 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 264 |
+
self.is_causal = False
|
| 265 |
+
|
| 266 |
+
self.scaling = self.head_dim**-0.5
|
| 267 |
+
self.is_causal = False
|
| 268 |
+
|
| 269 |
+
self.dropout = config.attention_dropout
|
| 270 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.key_bias)
|
| 271 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.value_bias)
|
| 272 |
+
|
| 273 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.query_bias)
|
| 274 |
+
self.o_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.proj_bias)
|
| 275 |
+
|
| 276 |
+
def forward(
|
| 277 |
+
self,
|
| 278 |
+
hidden_states: torch.Tensor,
|
| 279 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 280 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
| 281 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 282 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 283 |
+
"""Input shape: Batch x Time x Channel"""
|
| 284 |
+
|
| 285 |
+
batch_size, patches, _ = hidden_states.size()
|
| 286 |
+
|
| 287 |
+
query_states = self.q_proj(hidden_states)
|
| 288 |
+
key_states = self.k_proj(hidden_states)
|
| 289 |
+
value_states = self.v_proj(hidden_states)
|
| 290 |
+
|
| 291 |
+
query_states = query_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
| 292 |
+
key_states = key_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
| 293 |
+
value_states = value_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
| 294 |
+
|
| 295 |
+
cos, sin = position_embeddings
|
| 296 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 297 |
+
|
| 298 |
+
attention_interface: Callable = eager_attention_forward
|
| 299 |
+
if self.config._attn_implementation != "eager":
|
| 300 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 301 |
+
|
| 302 |
+
attn_output, attn_weights = attention_interface(
|
| 303 |
+
self,
|
| 304 |
+
query_states,
|
| 305 |
+
key_states,
|
| 306 |
+
value_states,
|
| 307 |
+
attention_mask,
|
| 308 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 309 |
+
scaling=self.scaling,
|
| 310 |
+
**kwargs,
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
attn_output = attn_output.reshape(batch_size, patches, -1).contiguous()
|
| 314 |
+
attn_output = self.o_proj(attn_output)
|
| 315 |
+
|
| 316 |
+
return attn_output, attn_weights
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class DINOv3ViTLayerScale(nn.Module):
|
| 320 |
+
def __init__(self, config) -> None:
|
| 321 |
+
super().__init__()
|
| 322 |
+
self.lambda1 = nn.Parameter(config.layerscale_value * torch.ones(config.hidden_size))
|
| 323 |
+
|
| 324 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 325 |
+
return hidden_state * self.lambda1
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 329 |
+
"""
|
| 330 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 331 |
+
|
| 332 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 333 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 334 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 335 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 336 |
+
argument.
|
| 337 |
+
"""
|
| 338 |
+
if drop_prob == 0.0 or not training:
|
| 339 |
+
return input
|
| 340 |
+
keep_prob = 1 - drop_prob
|
| 341 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 342 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 343 |
+
random_tensor.floor_() # binarize
|
| 344 |
+
output = input.div(keep_prob) * random_tensor
|
| 345 |
+
return output
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
class DINOv3ViTDropPath(nn.Module):
|
| 349 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 350 |
+
|
| 351 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 352 |
+
super().__init__()
|
| 353 |
+
self.drop_prob = drop_prob
|
| 354 |
+
|
| 355 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 356 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 357 |
+
|
| 358 |
+
def extra_repr(self) -> str:
|
| 359 |
+
return f"p={self.drop_prob}"
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
class DINOv3ViTMLP(nn.Module):
|
| 363 |
+
def __init__(self, config):
|
| 364 |
+
super().__init__()
|
| 365 |
+
self.config = config
|
| 366 |
+
self.hidden_size = config.hidden_size
|
| 367 |
+
self.intermediate_size = config.intermediate_size
|
| 368 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 369 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 370 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 371 |
+
|
| 372 |
+
def forward(self, x):
|
| 373 |
+
return self.down_proj(self.act_fn(self.up_proj(x)))
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
class DINOv3ViTGatedMLP(nn.Module):
|
| 377 |
+
def __init__(self, config):
|
| 378 |
+
super().__init__()
|
| 379 |
+
self.config = config
|
| 380 |
+
self.hidden_size = config.hidden_size
|
| 381 |
+
self.intermediate_size = config.intermediate_size
|
| 382 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 383 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 384 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 385 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 386 |
+
|
| 387 |
+
def forward(self, x):
|
| 388 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 389 |
+
return down_proj
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
class DINOv3ViTLayer(GradientCheckpointingLayer):
|
| 393 |
+
"""This corresponds to the Block class in the original implementation."""
|
| 394 |
+
|
| 395 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 396 |
+
super().__init__()
|
| 397 |
+
|
| 398 |
+
self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 399 |
+
self.attention = DINOv3ViTAttention(config)
|
| 400 |
+
self.layer_scale1 = DINOv3ViTLayerScale(config)
|
| 401 |
+
self.drop_path = DINOv3ViTDropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
|
| 402 |
+
|
| 403 |
+
self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 404 |
+
|
| 405 |
+
if config.use_gated_mlp:
|
| 406 |
+
self.mlp = DINOv3ViTGatedMLP(config)
|
| 407 |
+
else:
|
| 408 |
+
self.mlp = DINOv3ViTMLP(config)
|
| 409 |
+
self.layer_scale2 = DINOv3ViTLayerScale(config)
|
| 410 |
+
|
| 411 |
+
def forward(
|
| 412 |
+
self,
|
| 413 |
+
hidden_states: torch.Tensor,
|
| 414 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 415 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
| 416 |
+
) -> torch.Tensor:
|
| 417 |
+
# Attention with residual connection
|
| 418 |
+
residual = hidden_states
|
| 419 |
+
hidden_states = self.norm1(hidden_states)
|
| 420 |
+
hidden_states, _ = self.attention(
|
| 421 |
+
hidden_states,
|
| 422 |
+
attention_mask=attention_mask,
|
| 423 |
+
position_embeddings=position_embeddings,
|
| 424 |
+
)
|
| 425 |
+
hidden_states = self.layer_scale1(hidden_states)
|
| 426 |
+
hidden_states = self.drop_path(hidden_states) + residual
|
| 427 |
+
|
| 428 |
+
# MLP with residual connection
|
| 429 |
+
residual = hidden_states
|
| 430 |
+
hidden_states = self.norm2(hidden_states)
|
| 431 |
+
hidden_states = self.mlp(hidden_states)
|
| 432 |
+
hidden_states = self.layer_scale2(hidden_states)
|
| 433 |
+
hidden_states = self.drop_path(hidden_states) + residual
|
| 434 |
+
|
| 435 |
+
return hidden_states
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
@auto_docstring
|
| 439 |
+
class DINOv3ViTPreTrainedModel(PreTrainedModel):
|
| 440 |
+
config: DINOv3ViTConfig
|
| 441 |
+
base_model_prefix = "dinov3_vit"
|
| 442 |
+
main_input_name = "pixel_values"
|
| 443 |
+
supports_gradient_checkpointing = True
|
| 444 |
+
_no_split_modules = ["DINOv3ViTLayer"]
|
| 445 |
+
_supports_sdpa = True
|
| 446 |
+
_supports_flash_attn = True
|
| 447 |
+
_supports_flex_attn = True
|
| 448 |
+
_supports_attention_backend = True
|
| 449 |
+
_can_record_outputs = {
|
| 450 |
+
"hidden_states": DINOv3ViTLayer,
|
| 451 |
+
"attentions": DINOv3ViTAttention,
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
def _init_weights(self, module) -> None:
|
| 455 |
+
"""Initialize the weights"""
|
| 456 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 457 |
+
# Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
|
| 458 |
+
# `trunc_normal_cpu` not implemented in `half` issues
|
| 459 |
+
module.weight.data = nn.init.trunc_normal_(
|
| 460 |
+
module.weight.data.to(torch.float32),
|
| 461 |
+
mean=0.0,
|
| 462 |
+
std=self.config.initializer_range,
|
| 463 |
+
).to(module.weight.dtype)
|
| 464 |
+
if module.bias is not None:
|
| 465 |
+
module.bias.data.zero_()
|
| 466 |
+
elif isinstance(module, nn.LayerNorm):
|
| 467 |
+
module.bias.data.zero_()
|
| 468 |
+
module.weight.data.fill_(1.0)
|
| 469 |
+
elif isinstance(module, DINOv3ViTEmbeddings):
|
| 470 |
+
module.cls_token.data = nn.init.trunc_normal_(
|
| 471 |
+
module.cls_token.data.to(torch.float32),
|
| 472 |
+
mean=0.0,
|
| 473 |
+
std=self.config.initializer_range,
|
| 474 |
+
).to(module.cls_token.dtype)
|
| 475 |
+
if module.config.num_register_tokens > 0:
|
| 476 |
+
module.register_tokens.data = nn.init.trunc_normal_(
|
| 477 |
+
module.register_tokens.data.to(torch.float32),
|
| 478 |
+
mean=0.0,
|
| 479 |
+
std=self.config.initializer_range,
|
| 480 |
+
).to(module.register_tokens.dtype)
|
| 481 |
+
module.mask_token.data.zero_()
|
| 482 |
+
elif isinstance(module, DINOv3ViTLayerScale):
|
| 483 |
+
module.lambda1.data.fill_(self.config.layerscale_value)
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
@auto_docstring
|
| 487 |
+
class DINOv3ViTModel(DINOv3ViTPreTrainedModel):
|
| 488 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 489 |
+
super().__init__(config)
|
| 490 |
+
self.config = config
|
| 491 |
+
self.embeddings = DINOv3ViTEmbeddings(config)
|
| 492 |
+
self.rope_embeddings = DINOv3ViTRopePositionEmbedding(config)
|
| 493 |
+
self.layer = nn.ModuleList([DINOv3ViTLayer(config) for _ in range(config.num_hidden_layers)])
|
| 494 |
+
self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 495 |
+
self.gradient_checkpointing = False
|
| 496 |
+
# Initialize weights and apply final processing
|
| 497 |
+
self.post_init()
|
| 498 |
+
|
| 499 |
+
def get_input_embeddings(self):
|
| 500 |
+
return self.embeddings.patch_embeddings
|
| 501 |
+
|
| 502 |
+
@check_model_inputs(tie_last_hidden_states=False)
|
| 503 |
+
@auto_docstring
|
| 504 |
+
def forward(
|
| 505 |
+
self,
|
| 506 |
+
pixel_values: torch.Tensor,
|
| 507 |
+
bool_masked_pos: Optional[torch.Tensor] = None,
|
| 508 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 509 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 510 |
+
) -> BaseModelOutputWithPooling:
|
| 511 |
+
r"""
|
| 512 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
|
| 513 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Only relevant for
|
| 514 |
+
pre-training.
|
| 515 |
+
"""
|
| 516 |
+
|
| 517 |
+
pixel_values = pixel_values.to(self.embeddings.patch_embeddings.weight.dtype)
|
| 518 |
+
hidden_states = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 519 |
+
position_embeddings = self.rope_embeddings(pixel_values)
|
| 520 |
+
|
| 521 |
+
for i, layer_module in enumerate(self.layer):
|
| 522 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 523 |
+
hidden_states = layer_module(
|
| 524 |
+
hidden_states,
|
| 525 |
+
attention_mask=layer_head_mask,
|
| 526 |
+
position_embeddings=position_embeddings,
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
sequence_output = self.norm(hidden_states)
|
| 530 |
+
pooled_output = sequence_output[:, 0, :]
|
| 531 |
+
|
| 532 |
+
return BaseModelOutputWithPooling(
|
| 533 |
+
last_hidden_state=sequence_output,
|
| 534 |
+
pooler_output=pooled_output,
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
__all__ = ["DINOv3ViTModel", "DINOv3ViTPreTrainedModel"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dinov3_vit/modular_dinov3_vit.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 Meta AI 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 DINOv3 model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from typing import Callable, Optional
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
|
| 24 |
+
from transformers.models.arcee.modeling_arcee import ArceeMLP
|
| 25 |
+
from transformers.models.dinov2.modeling_dinov2 import (
|
| 26 |
+
Dinov2DropPath,
|
| 27 |
+
Dinov2LayerScale,
|
| 28 |
+
Dinov2PreTrainedModel,
|
| 29 |
+
eager_attention_forward,
|
| 30 |
+
)
|
| 31 |
+
from transformers.models.llama.modeling_llama import LlamaMLP
|
| 32 |
+
from transformers.models.pixtral.modeling_pixtral import PixtralAttention, rotate_half
|
| 33 |
+
|
| 34 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 35 |
+
from ...modeling_outputs import BaseModelOutputWithPooling
|
| 36 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
|
| 37 |
+
from ...processing_utils import Unpack
|
| 38 |
+
from ...pytorch_utils import compile_compatible_method_lru_cache
|
| 39 |
+
from ...utils import TransformersKwargs, auto_docstring, logging
|
| 40 |
+
from ...utils.generic import check_model_inputs
|
| 41 |
+
from .configuration_dinov3_vit import DINOv3ViTConfig
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class DINOv3ViTEmbeddings(nn.Module):
|
| 48 |
+
"""
|
| 49 |
+
Construct the CLS token, mask token, position and patch embeddings.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.config = config
|
| 55 |
+
self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 56 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 57 |
+
self.register_tokens = nn.Parameter(torch.empty(1, config.num_register_tokens, config.hidden_size))
|
| 58 |
+
self.patch_embeddings = nn.Conv2d(
|
| 59 |
+
config.num_channels, config.hidden_size, kernel_size=config.patch_size, stride=config.patch_size
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 63 |
+
batch_size = pixel_values.shape[0]
|
| 64 |
+
target_dtype = self.patch_embeddings.weight.dtype
|
| 65 |
+
|
| 66 |
+
# (batch_size, num_channels, height, width) -> (batch_size, num_patches, hidden_size)
|
| 67 |
+
patch_embeddings = self.patch_embeddings(pixel_values.to(dtype=target_dtype))
|
| 68 |
+
patch_embeddings = patch_embeddings.flatten(2).transpose(1, 2)
|
| 69 |
+
|
| 70 |
+
if bool_masked_pos is not None:
|
| 71 |
+
mask_token = self.mask_token.to(patch_embeddings.dtype)
|
| 72 |
+
patch_embeddings = torch.where(bool_masked_pos.unsqueeze(-1), mask_token, patch_embeddings)
|
| 73 |
+
|
| 74 |
+
# Add CLS and register tokens
|
| 75 |
+
cls_token = self.cls_token.expand(batch_size, -1, -1)
|
| 76 |
+
register_tokens = self.register_tokens.expand(batch_size, -1, -1)
|
| 77 |
+
embeddings = torch.cat([cls_token, register_tokens, patch_embeddings], dim=1)
|
| 78 |
+
|
| 79 |
+
return embeddings
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@compile_compatible_method_lru_cache(maxsize=32)
|
| 83 |
+
def get_patches_center_coordinates(
|
| 84 |
+
num_patches_h: int, num_patches_w: int, dtype: torch.dtype, device: torch.device
|
| 85 |
+
) -> torch.Tensor:
|
| 86 |
+
"""
|
| 87 |
+
Computes the 2D coordinates of the centers of image patches, normalized to the range [-1, +1].
|
| 88 |
+
The center of each patch is exactly halfway between its top-left and bottom-right corners.
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
num_patches_h (int): Number of patches along the vertical (height) axis.
|
| 92 |
+
num_patches_w (int): Number of patches along the horizontal (width) axis.
|
| 93 |
+
dtype (torch.dtype): The desired data type of the returned tensor.
|
| 94 |
+
|
| 95 |
+
Returns:
|
| 96 |
+
torch.Tensor: A tensor of shape (height * width, 2), where each row contains the (y, x)
|
| 97 |
+
coordinates of a patch center, normalized to [-1, +1].
|
| 98 |
+
"""
|
| 99 |
+
coords_h = torch.arange(0.5, num_patches_h, dtype=dtype, device=device)
|
| 100 |
+
coords_w = torch.arange(0.5, num_patches_w, dtype=dtype, device=device)
|
| 101 |
+
coords_h = coords_h / num_patches_h
|
| 102 |
+
coords_w = coords_w / num_patches_w
|
| 103 |
+
# (height, width, 2) -> (height * width, 2)
|
| 104 |
+
coords = torch.stack(torch.meshgrid(coords_h, coords_w, indexing="ij"), dim=-1)
|
| 105 |
+
coords = coords.flatten(0, 1)
|
| 106 |
+
# Shift range [0, 1] to [-1, +1]
|
| 107 |
+
coords = 2.0 * coords - 1.0
|
| 108 |
+
return coords
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def augment_patches_center_coordinates(
|
| 112 |
+
coords: torch.Tensor,
|
| 113 |
+
shift: Optional[float] = None,
|
| 114 |
+
jitter: Optional[float] = None,
|
| 115 |
+
rescale: Optional[float] = None,
|
| 116 |
+
) -> torch.Tensor:
|
| 117 |
+
# Shift coords by adding a uniform value in [-shift, shift]
|
| 118 |
+
if shift is not None:
|
| 119 |
+
shift_hw = torch.empty((1, 2), device=coords.device, dtype=coords.dtype)
|
| 120 |
+
shift_hw = shift_hw.uniform_(-shift, shift)
|
| 121 |
+
coords = coords + shift_hw
|
| 122 |
+
|
| 123 |
+
# Jitter coords by multiplying the range [-1, 1] by a log-uniform value in [1/jitter, jitter]
|
| 124 |
+
if jitter is not None:
|
| 125 |
+
jitter_range = np.log(jitter)
|
| 126 |
+
jitter_hw = torch.empty((1, 2), device=coords.device, dtype=coords.dtype)
|
| 127 |
+
jitter_hw = jitter_hw.uniform_(-jitter_range, jitter_range).exp()
|
| 128 |
+
coords = coords * jitter_hw
|
| 129 |
+
|
| 130 |
+
# Rescale coords by multiplying the range [-1, 1] by a log-uniform value in [1/rescale, rescale]
|
| 131 |
+
if rescale is not None:
|
| 132 |
+
rescale_range = np.log(rescale)
|
| 133 |
+
rescale_hw = torch.empty(1, device=coords.device, dtype=coords.dtype)
|
| 134 |
+
rescale_hw = rescale_hw.uniform_(-rescale_range, rescale_range).exp()
|
| 135 |
+
coords = coords * rescale_hw
|
| 136 |
+
|
| 137 |
+
return coords
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class DINOv3ViTRopePositionEmbedding(nn.Module):
|
| 141 |
+
inv_freq: torch.Tensor
|
| 142 |
+
|
| 143 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 144 |
+
super().__init__()
|
| 145 |
+
|
| 146 |
+
self.config = config
|
| 147 |
+
self.base = config.rope_theta
|
| 148 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
| 149 |
+
self.num_patches_h = config.image_size // config.patch_size
|
| 150 |
+
self.num_patches_w = config.image_size // config.patch_size
|
| 151 |
+
|
| 152 |
+
inv_freq = 1 / self.base ** torch.arange(0, 1, 4 / self.head_dim, dtype=torch.float32) # (head_dim / 4,)
|
| 153 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 154 |
+
|
| 155 |
+
def forward(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 156 |
+
_, _, height, width = pixel_values.shape
|
| 157 |
+
num_patches_h = height // self.config.patch_size
|
| 158 |
+
num_patches_w = width // self.config.patch_size
|
| 159 |
+
|
| 160 |
+
device = pixel_values.device
|
| 161 |
+
device_type = device.type if isinstance(device.type, str) and device.type != "mps" else "cpu"
|
| 162 |
+
|
| 163 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 164 |
+
# Although we could precompute static patch_coords from image_size and patch_size in the config,
|
| 165 |
+
# the model was trained with random_scale, so it can process images of varying sizes.
|
| 166 |
+
# Therefore, it's better to compute patch_coords dynamically (with lru_cache).
|
| 167 |
+
patch_coords = get_patches_center_coordinates(
|
| 168 |
+
num_patches_h, num_patches_w, dtype=torch.float32, device=device
|
| 169 |
+
)
|
| 170 |
+
if self.training:
|
| 171 |
+
patch_coords = augment_patches_center_coordinates(
|
| 172 |
+
patch_coords,
|
| 173 |
+
shift=self.config.pos_embed_shift,
|
| 174 |
+
jitter=self.config.pos_embed_jitter,
|
| 175 |
+
rescale=self.config.pos_embed_rescale,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# (height * width, 2, head_dim / 4) -> (height * width, head_dim / 2) -> (height * width, head_dim)
|
| 179 |
+
angles = 2 * math.pi * patch_coords[:, :, None] * self.inv_freq[None, None, :]
|
| 180 |
+
angles = angles.flatten(1, 2)
|
| 181 |
+
angles = angles.tile(2)
|
| 182 |
+
|
| 183 |
+
cos = torch.cos(angles)
|
| 184 |
+
sin = torch.sin(angles)
|
| 185 |
+
|
| 186 |
+
dtype = pixel_values.dtype
|
| 187 |
+
return cos.to(dtype=dtype), sin.to(dtype=dtype)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def apply_rotary_pos_emb(
|
| 191 |
+
q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, **kwargs
|
| 192 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 193 |
+
"""Applies Rotary Position Embedding to the query and key tensors, but only to the patch tokens,
|
| 194 |
+
ignoring the prefix tokens (cls token and register tokens).
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
q (`torch.Tensor`): The query tensor.
|
| 198 |
+
k (`torch.Tensor`): The key tensor.
|
| 199 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 200 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
num_tokens = q.shape[-2]
|
| 207 |
+
num_patches = sin.shape[-2]
|
| 208 |
+
num_prefix_tokens = num_tokens - num_patches # cls token + register tokens
|
| 209 |
+
|
| 210 |
+
q_prefix_tokens, q_patches = q.split((num_prefix_tokens, num_patches), dim=-2)
|
| 211 |
+
k_prefix_tokens, k_patches = k.split((num_prefix_tokens, num_patches), dim=-2)
|
| 212 |
+
|
| 213 |
+
# apply rope only to patch tokens
|
| 214 |
+
q_patches = (q_patches * cos) + (rotate_half(q_patches) * sin)
|
| 215 |
+
k_patches = (k_patches * cos) + (rotate_half(k_patches) * sin)
|
| 216 |
+
|
| 217 |
+
q = torch.cat((q_prefix_tokens, q_patches), dim=-2)
|
| 218 |
+
k = torch.cat((k_prefix_tokens, k_patches), dim=-2)
|
| 219 |
+
|
| 220 |
+
return q, k
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class DINOv3ViTAttention(PixtralAttention):
|
| 224 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 225 |
+
super().__init__(config)
|
| 226 |
+
|
| 227 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.query_bias)
|
| 228 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.key_bias)
|
| 229 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.value_bias)
|
| 230 |
+
self.o_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.proj_bias)
|
| 231 |
+
|
| 232 |
+
def forward(
|
| 233 |
+
self,
|
| 234 |
+
hidden_states: torch.Tensor,
|
| 235 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 236 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
| 237 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 238 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 239 |
+
"""Input shape: Batch x Time x Channel"""
|
| 240 |
+
|
| 241 |
+
batch_size, patches, _ = hidden_states.size()
|
| 242 |
+
|
| 243 |
+
query_states = self.q_proj(hidden_states)
|
| 244 |
+
key_states = self.k_proj(hidden_states)
|
| 245 |
+
value_states = self.v_proj(hidden_states)
|
| 246 |
+
|
| 247 |
+
query_states = query_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
| 248 |
+
key_states = key_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
| 249 |
+
value_states = value_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
|
| 250 |
+
|
| 251 |
+
cos, sin = position_embeddings
|
| 252 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 253 |
+
|
| 254 |
+
attention_interface: Callable = eager_attention_forward
|
| 255 |
+
if self.config._attn_implementation != "eager":
|
| 256 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 257 |
+
|
| 258 |
+
attn_output, attn_weights = attention_interface(
|
| 259 |
+
self,
|
| 260 |
+
query_states,
|
| 261 |
+
key_states,
|
| 262 |
+
value_states,
|
| 263 |
+
attention_mask,
|
| 264 |
+
dropout=0.0 if not self.training else self.dropout,
|
| 265 |
+
scaling=self.scaling,
|
| 266 |
+
**kwargs,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
attn_output = attn_output.reshape(batch_size, patches, -1).contiguous()
|
| 270 |
+
attn_output = self.o_proj(attn_output)
|
| 271 |
+
|
| 272 |
+
return attn_output, attn_weights
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class DINOv3ViTLayerScale(Dinov2LayerScale):
|
| 276 |
+
pass
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class DINOv3ViTDropPath(Dinov2DropPath):
|
| 280 |
+
pass
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class DINOv3ViTMLP(ArceeMLP):
|
| 284 |
+
pass
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class DINOv3ViTGatedMLP(LlamaMLP):
|
| 288 |
+
pass
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class DINOv3ViTLayer(GradientCheckpointingLayer):
|
| 292 |
+
"""This corresponds to the Block class in the original implementation."""
|
| 293 |
+
|
| 294 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 295 |
+
super().__init__()
|
| 296 |
+
|
| 297 |
+
self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 298 |
+
self.attention = DINOv3ViTAttention(config)
|
| 299 |
+
self.layer_scale1 = DINOv3ViTLayerScale(config)
|
| 300 |
+
self.drop_path = DINOv3ViTDropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
|
| 301 |
+
|
| 302 |
+
self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 303 |
+
|
| 304 |
+
if config.use_gated_mlp:
|
| 305 |
+
self.mlp = DINOv3ViTGatedMLP(config)
|
| 306 |
+
else:
|
| 307 |
+
self.mlp = DINOv3ViTMLP(config)
|
| 308 |
+
self.layer_scale2 = DINOv3ViTLayerScale(config)
|
| 309 |
+
|
| 310 |
+
def forward(
|
| 311 |
+
self,
|
| 312 |
+
hidden_states: torch.Tensor,
|
| 313 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 314 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
| 315 |
+
) -> torch.Tensor:
|
| 316 |
+
# Attention with residual connection
|
| 317 |
+
residual = hidden_states
|
| 318 |
+
hidden_states = self.norm1(hidden_states)
|
| 319 |
+
hidden_states, _ = self.attention(
|
| 320 |
+
hidden_states,
|
| 321 |
+
attention_mask=attention_mask,
|
| 322 |
+
position_embeddings=position_embeddings,
|
| 323 |
+
)
|
| 324 |
+
hidden_states = self.layer_scale1(hidden_states)
|
| 325 |
+
hidden_states = self.drop_path(hidden_states) + residual
|
| 326 |
+
|
| 327 |
+
# MLP with residual connection
|
| 328 |
+
residual = hidden_states
|
| 329 |
+
hidden_states = self.norm2(hidden_states)
|
| 330 |
+
hidden_states = self.mlp(hidden_states)
|
| 331 |
+
hidden_states = self.layer_scale2(hidden_states)
|
| 332 |
+
hidden_states = self.drop_path(hidden_states) + residual
|
| 333 |
+
|
| 334 |
+
return hidden_states
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
@auto_docstring
|
| 338 |
+
class DINOv3ViTPreTrainedModel(Dinov2PreTrainedModel):
|
| 339 |
+
_can_record_outputs = {
|
| 340 |
+
"hidden_states": DINOv3ViTLayer,
|
| 341 |
+
"attentions": DINOv3ViTAttention,
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
def _init_weights(self, module):
|
| 345 |
+
"""Initialize the weights"""
|
| 346 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 347 |
+
# Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
|
| 348 |
+
# `trunc_normal_cpu` not implemented in `half` issues
|
| 349 |
+
module.weight.data = nn.init.trunc_normal_(
|
| 350 |
+
module.weight.data.to(torch.float32),
|
| 351 |
+
mean=0.0,
|
| 352 |
+
std=self.config.initializer_range,
|
| 353 |
+
).to(module.weight.dtype)
|
| 354 |
+
if module.bias is not None:
|
| 355 |
+
module.bias.data.zero_()
|
| 356 |
+
elif isinstance(module, nn.LayerNorm):
|
| 357 |
+
module.bias.data.zero_()
|
| 358 |
+
module.weight.data.fill_(1.0)
|
| 359 |
+
elif isinstance(module, DINOv3ViTEmbeddings):
|
| 360 |
+
module.cls_token.data = nn.init.trunc_normal_(
|
| 361 |
+
module.cls_token.data.to(torch.float32),
|
| 362 |
+
mean=0.0,
|
| 363 |
+
std=self.config.initializer_range,
|
| 364 |
+
).to(module.cls_token.dtype)
|
| 365 |
+
if module.config.num_register_tokens > 0:
|
| 366 |
+
module.register_tokens.data = nn.init.trunc_normal_(
|
| 367 |
+
module.register_tokens.data.to(torch.float32),
|
| 368 |
+
mean=0.0,
|
| 369 |
+
std=self.config.initializer_range,
|
| 370 |
+
).to(module.register_tokens.dtype)
|
| 371 |
+
module.mask_token.data.zero_()
|
| 372 |
+
elif isinstance(module, DINOv3ViTLayerScale):
|
| 373 |
+
module.lambda1.data.fill_(self.config.layerscale_value)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
@auto_docstring
|
| 377 |
+
class DINOv3ViTModel(DINOv3ViTPreTrainedModel):
|
| 378 |
+
def __init__(self, config: DINOv3ViTConfig):
|
| 379 |
+
super().__init__(config)
|
| 380 |
+
self.config = config
|
| 381 |
+
self.embeddings = DINOv3ViTEmbeddings(config)
|
| 382 |
+
self.rope_embeddings = DINOv3ViTRopePositionEmbedding(config)
|
| 383 |
+
self.layer = nn.ModuleList([DINOv3ViTLayer(config) for _ in range(config.num_hidden_layers)])
|
| 384 |
+
self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 385 |
+
self.gradient_checkpointing = False
|
| 386 |
+
# Initialize weights and apply final processing
|
| 387 |
+
self.post_init()
|
| 388 |
+
|
| 389 |
+
def get_input_embeddings(self):
|
| 390 |
+
return self.embeddings.patch_embeddings
|
| 391 |
+
|
| 392 |
+
@check_model_inputs(tie_last_hidden_states=False)
|
| 393 |
+
@auto_docstring
|
| 394 |
+
def forward(
|
| 395 |
+
self,
|
| 396 |
+
pixel_values: torch.Tensor,
|
| 397 |
+
bool_masked_pos: Optional[torch.Tensor] = None,
|
| 398 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 399 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 400 |
+
) -> BaseModelOutputWithPooling:
|
| 401 |
+
r"""
|
| 402 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
|
| 403 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Only relevant for
|
| 404 |
+
pre-training.
|
| 405 |
+
"""
|
| 406 |
+
|
| 407 |
+
pixel_values = pixel_values.to(self.embeddings.patch_embeddings.weight.dtype)
|
| 408 |
+
hidden_states = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 409 |
+
position_embeddings = self.rope_embeddings(pixel_values)
|
| 410 |
+
|
| 411 |
+
for i, layer_module in enumerate(self.layer):
|
| 412 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 413 |
+
hidden_states = layer_module(
|
| 414 |
+
hidden_states,
|
| 415 |
+
attention_mask=layer_head_mask,
|
| 416 |
+
position_embeddings=position_embeddings,
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
sequence_output = self.norm(hidden_states)
|
| 420 |
+
pooled_output = sequence_output[:, 0, :]
|
| 421 |
+
|
| 422 |
+
return BaseModelOutputWithPooling(
|
| 423 |
+
last_hidden_state=sequence_output,
|
| 424 |
+
pooler_output=pooled_output,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
__all__ = ["DINOv3ViTModel", "DINOv3ViTPreTrainedModel"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dpr/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_dpr import *
|
| 22 |
+
from .modeling_dpr import *
|
| 23 |
+
from .modeling_tf_dpr import *
|
| 24 |
+
from .tokenization_dpr import *
|
| 25 |
+
from .tokenization_dpr_fast import *
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
_file = globals()["__file__"]
|
| 30 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dpr/configuration_dpr.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2010, DPR authors, The Hugging Face 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 |
+
"""DPR model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class DPRConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
[`DPRConfig`] is the configuration class to store the configuration of a *DPRModel*.
|
| 27 |
+
|
| 28 |
+
This is the configuration class to store the configuration of a [`DPRContextEncoder`], [`DPRQuestionEncoder`], or a
|
| 29 |
+
[`DPRReader`]. It is used to instantiate the components of the DPR model according to the specified arguments,
|
| 30 |
+
defining the model component architectures. Instantiating a configuration with the defaults will yield a similar
|
| 31 |
+
configuration to that of the DPRContextEncoder
|
| 32 |
+
[facebook/dpr-ctx_encoder-single-nq-base](https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base)
|
| 33 |
+
architecture.
|
| 34 |
+
|
| 35 |
+
This class is a subclass of [`BertConfig`]. Please check the superclass for the documentation of all kwargs.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 39 |
+
Vocabulary size of the DPR model. Defines the different tokens that can be represented by the *inputs_ids*
|
| 40 |
+
passed to the forward method of [`BertModel`].
|
| 41 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 42 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 43 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 44 |
+
Number of hidden layers in the Transformer encoder.
|
| 45 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 46 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 47 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 48 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 49 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 50 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 51 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 52 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 53 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 54 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 55 |
+
The dropout ratio for the attention probabilities.
|
| 56 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 57 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 58 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 59 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 60 |
+
The vocabulary size of the *token_type_ids* passed into [`BertModel`].
|
| 61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 63 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 64 |
+
The epsilon used by the layer normalization layers.
|
| 65 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
| 66 |
+
Padding token id.
|
| 67 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 68 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 69 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 70 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
|
| 71 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 72 |
+
with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
|
| 73 |
+
projection_dim (`int`, *optional*, defaults to 0):
|
| 74 |
+
Dimension of the projection for the context and question encoders. If it is set to zero (default), then no
|
| 75 |
+
projection is done.
|
| 76 |
+
|
| 77 |
+
Example:
|
| 78 |
+
|
| 79 |
+
```python
|
| 80 |
+
>>> from transformers import DPRConfig, DPRContextEncoder
|
| 81 |
+
|
| 82 |
+
>>> # Initializing a DPR facebook/dpr-ctx_encoder-single-nq-base style configuration
|
| 83 |
+
>>> configuration = DPRConfig()
|
| 84 |
+
|
| 85 |
+
>>> # Initializing a model (with random weights) from the facebook/dpr-ctx_encoder-single-nq-base style configuration
|
| 86 |
+
>>> model = DPRContextEncoder(configuration)
|
| 87 |
+
|
| 88 |
+
>>> # Accessing the model configuration
|
| 89 |
+
>>> configuration = model.config
|
| 90 |
+
```"""
|
| 91 |
+
|
| 92 |
+
model_type = "dpr"
|
| 93 |
+
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
vocab_size=30522,
|
| 97 |
+
hidden_size=768,
|
| 98 |
+
num_hidden_layers=12,
|
| 99 |
+
num_attention_heads=12,
|
| 100 |
+
intermediate_size=3072,
|
| 101 |
+
hidden_act="gelu",
|
| 102 |
+
hidden_dropout_prob=0.1,
|
| 103 |
+
attention_probs_dropout_prob=0.1,
|
| 104 |
+
max_position_embeddings=512,
|
| 105 |
+
type_vocab_size=2,
|
| 106 |
+
initializer_range=0.02,
|
| 107 |
+
layer_norm_eps=1e-12,
|
| 108 |
+
pad_token_id=0,
|
| 109 |
+
position_embedding_type="absolute",
|
| 110 |
+
projection_dim: int = 0,
|
| 111 |
+
**kwargs,
|
| 112 |
+
):
|
| 113 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
| 114 |
+
|
| 115 |
+
self.vocab_size = vocab_size
|
| 116 |
+
self.hidden_size = hidden_size
|
| 117 |
+
self.num_hidden_layers = num_hidden_layers
|
| 118 |
+
self.num_attention_heads = num_attention_heads
|
| 119 |
+
self.hidden_act = hidden_act
|
| 120 |
+
self.intermediate_size = intermediate_size
|
| 121 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 122 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 123 |
+
self.max_position_embeddings = max_position_embeddings
|
| 124 |
+
self.type_vocab_size = type_vocab_size
|
| 125 |
+
self.initializer_range = initializer_range
|
| 126 |
+
self.layer_norm_eps = layer_norm_eps
|
| 127 |
+
self.projection_dim = projection_dim
|
| 128 |
+
self.position_embedding_type = position_embedding_type
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
__all__ = ["DPRConfig"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dpr/modeling_dpr.py
ADDED
|
@@ -0,0 +1,592 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
# Copyright 2018 DPR Authors, The Hugging Face Team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch DPR model for Open Domain Question Answering."""
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import Optional, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import Tensor, nn
|
| 22 |
+
|
| 23 |
+
from ...modeling_outputs import BaseModelOutputWithPooling
|
| 24 |
+
from ...modeling_utils import PreTrainedModel
|
| 25 |
+
from ...utils import (
|
| 26 |
+
ModelOutput,
|
| 27 |
+
auto_docstring,
|
| 28 |
+
logging,
|
| 29 |
+
)
|
| 30 |
+
from ..bert.modeling_bert import BertModel
|
| 31 |
+
from .configuration_dpr import DPRConfig
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
logger = logging.get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
##########
|
| 38 |
+
# Outputs
|
| 39 |
+
##########
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
@auto_docstring(
|
| 44 |
+
custom_intro="""
|
| 45 |
+
Class for outputs of [`DPRQuestionEncoder`].
|
| 46 |
+
"""
|
| 47 |
+
)
|
| 48 |
+
class DPRContextEncoderOutput(ModelOutput):
|
| 49 |
+
r"""
|
| 50 |
+
pooler_output (`torch.FloatTensor` of shape `(batch_size, embeddings_size)`):
|
| 51 |
+
The DPR encoder outputs the *pooler_output* that corresponds to the context representation. Last layer
|
| 52 |
+
hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
|
| 53 |
+
This output is to be used to embed contexts for nearest neighbors queries with questions embeddings.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
pooler_output: torch.FloatTensor
|
| 57 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 58 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass
|
| 62 |
+
@auto_docstring(
|
| 63 |
+
custom_intro="""
|
| 64 |
+
Class for outputs of [`DPRQuestionEncoder`].
|
| 65 |
+
"""
|
| 66 |
+
)
|
| 67 |
+
class DPRQuestionEncoderOutput(ModelOutput):
|
| 68 |
+
r"""
|
| 69 |
+
pooler_output (`torch.FloatTensor` of shape `(batch_size, embeddings_size)`):
|
| 70 |
+
The DPR encoder outputs the *pooler_output* that corresponds to the question representation. Last layer
|
| 71 |
+
hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
|
| 72 |
+
This output is to be used to embed questions for nearest neighbors queries with context embeddings.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
pooler_output: torch.FloatTensor
|
| 76 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 77 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass
|
| 81 |
+
@auto_docstring(
|
| 82 |
+
custom_intro="""
|
| 83 |
+
Class for outputs of [`DPRQuestionEncoder`].
|
| 84 |
+
"""
|
| 85 |
+
)
|
| 86 |
+
class DPRReaderOutput(ModelOutput):
|
| 87 |
+
r"""
|
| 88 |
+
start_logits (`torch.FloatTensor` of shape `(n_passages, sequence_length)`):
|
| 89 |
+
Logits of the start index of the span for each passage.
|
| 90 |
+
end_logits (`torch.FloatTensor` of shape `(n_passages, sequence_length)`):
|
| 91 |
+
Logits of the end index of the span for each passage.
|
| 92 |
+
relevance_logits (`torch.FloatTensor` of shape `(n_passages, )`):
|
| 93 |
+
Outputs of the QA classifier of the DPRReader that corresponds to the scores of each passage to answer the
|
| 94 |
+
question, compared to all the other passages.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
start_logits: torch.FloatTensor
|
| 98 |
+
end_logits: Optional[torch.FloatTensor] = None
|
| 99 |
+
relevance_logits: Optional[torch.FloatTensor] = None
|
| 100 |
+
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 101 |
+
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@auto_docstring
|
| 105 |
+
class DPRPreTrainedModel(PreTrainedModel):
|
| 106 |
+
_supports_sdpa = True
|
| 107 |
+
|
| 108 |
+
def _init_weights(self, module):
|
| 109 |
+
"""Initialize the weights"""
|
| 110 |
+
if isinstance(module, nn.Linear):
|
| 111 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 112 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 113 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 114 |
+
if module.bias is not None:
|
| 115 |
+
module.bias.data.zero_()
|
| 116 |
+
elif isinstance(module, nn.Embedding):
|
| 117 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 118 |
+
if module.padding_idx is not None:
|
| 119 |
+
module.weight.data[module.padding_idx].zero_()
|
| 120 |
+
elif isinstance(module, nn.LayerNorm):
|
| 121 |
+
module.bias.data.zero_()
|
| 122 |
+
module.weight.data.fill_(1.0)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class DPREncoder(DPRPreTrainedModel):
|
| 126 |
+
base_model_prefix = "bert_model"
|
| 127 |
+
|
| 128 |
+
def __init__(self, config: DPRConfig):
|
| 129 |
+
super().__init__(config)
|
| 130 |
+
self.bert_model = BertModel(config, add_pooling_layer=False)
|
| 131 |
+
if self.bert_model.config.hidden_size <= 0:
|
| 132 |
+
raise ValueError("Encoder hidden_size can't be zero")
|
| 133 |
+
self.projection_dim = config.projection_dim
|
| 134 |
+
if self.projection_dim > 0:
|
| 135 |
+
self.encode_proj = nn.Linear(self.bert_model.config.hidden_size, config.projection_dim)
|
| 136 |
+
# Initialize weights and apply final processing
|
| 137 |
+
self.post_init()
|
| 138 |
+
|
| 139 |
+
def forward(
|
| 140 |
+
self,
|
| 141 |
+
input_ids: Tensor,
|
| 142 |
+
attention_mask: Optional[Tensor] = None,
|
| 143 |
+
token_type_ids: Optional[Tensor] = None,
|
| 144 |
+
inputs_embeds: Optional[Tensor] = None,
|
| 145 |
+
output_attentions: bool = False,
|
| 146 |
+
output_hidden_states: bool = False,
|
| 147 |
+
return_dict: bool = False,
|
| 148 |
+
) -> Union[BaseModelOutputWithPooling, tuple[Tensor, ...]]:
|
| 149 |
+
outputs = self.bert_model(
|
| 150 |
+
input_ids=input_ids,
|
| 151 |
+
attention_mask=attention_mask,
|
| 152 |
+
token_type_ids=token_type_ids,
|
| 153 |
+
inputs_embeds=inputs_embeds,
|
| 154 |
+
output_attentions=output_attentions,
|
| 155 |
+
output_hidden_states=output_hidden_states,
|
| 156 |
+
return_dict=return_dict,
|
| 157 |
+
)
|
| 158 |
+
sequence_output = outputs[0]
|
| 159 |
+
pooled_output = sequence_output[:, 0, :]
|
| 160 |
+
|
| 161 |
+
if self.projection_dim > 0:
|
| 162 |
+
pooled_output = self.encode_proj(pooled_output)
|
| 163 |
+
|
| 164 |
+
if not return_dict:
|
| 165 |
+
return (sequence_output, pooled_output) + outputs[2:]
|
| 166 |
+
|
| 167 |
+
return BaseModelOutputWithPooling(
|
| 168 |
+
last_hidden_state=sequence_output,
|
| 169 |
+
pooler_output=pooled_output,
|
| 170 |
+
hidden_states=outputs.hidden_states,
|
| 171 |
+
attentions=outputs.attentions,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def embeddings_size(self) -> int:
|
| 176 |
+
if self.projection_dim > 0:
|
| 177 |
+
return self.encode_proj.out_features
|
| 178 |
+
return self.bert_model.config.hidden_size
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class DPRSpanPredictor(DPRPreTrainedModel):
|
| 182 |
+
base_model_prefix = "encoder"
|
| 183 |
+
|
| 184 |
+
def __init__(self, config: DPRConfig):
|
| 185 |
+
super().__init__(config)
|
| 186 |
+
self.encoder = DPREncoder(config)
|
| 187 |
+
self.qa_outputs = nn.Linear(self.encoder.embeddings_size, 2)
|
| 188 |
+
self.qa_classifier = nn.Linear(self.encoder.embeddings_size, 1)
|
| 189 |
+
# Initialize weights and apply final processing
|
| 190 |
+
self.post_init()
|
| 191 |
+
|
| 192 |
+
def forward(
|
| 193 |
+
self,
|
| 194 |
+
input_ids: Tensor,
|
| 195 |
+
attention_mask: Tensor,
|
| 196 |
+
inputs_embeds: Optional[Tensor] = None,
|
| 197 |
+
output_attentions: bool = False,
|
| 198 |
+
output_hidden_states: bool = False,
|
| 199 |
+
return_dict: bool = False,
|
| 200 |
+
) -> Union[DPRReaderOutput, tuple[Tensor, ...]]:
|
| 201 |
+
# notations: N - number of questions in a batch, M - number of passages per questions, L - sequence length
|
| 202 |
+
n_passages, sequence_length = input_ids.size() if input_ids is not None else inputs_embeds.size()[:2]
|
| 203 |
+
# feed encoder
|
| 204 |
+
outputs = self.encoder(
|
| 205 |
+
input_ids,
|
| 206 |
+
attention_mask=attention_mask,
|
| 207 |
+
inputs_embeds=inputs_embeds,
|
| 208 |
+
output_attentions=output_attentions,
|
| 209 |
+
output_hidden_states=output_hidden_states,
|
| 210 |
+
return_dict=return_dict,
|
| 211 |
+
)
|
| 212 |
+
sequence_output = outputs[0]
|
| 213 |
+
|
| 214 |
+
# compute logits
|
| 215 |
+
logits = self.qa_outputs(sequence_output)
|
| 216 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 217 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 218 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 219 |
+
relevance_logits = self.qa_classifier(sequence_output[:, 0, :])
|
| 220 |
+
|
| 221 |
+
# resize
|
| 222 |
+
start_logits = start_logits.view(n_passages, sequence_length)
|
| 223 |
+
end_logits = end_logits.view(n_passages, sequence_length)
|
| 224 |
+
relevance_logits = relevance_logits.view(n_passages)
|
| 225 |
+
|
| 226 |
+
if not return_dict:
|
| 227 |
+
return (start_logits, end_logits, relevance_logits) + outputs[2:]
|
| 228 |
+
|
| 229 |
+
return DPRReaderOutput(
|
| 230 |
+
start_logits=start_logits,
|
| 231 |
+
end_logits=end_logits,
|
| 232 |
+
relevance_logits=relevance_logits,
|
| 233 |
+
hidden_states=outputs.hidden_states,
|
| 234 |
+
attentions=outputs.attentions,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
##################
|
| 239 |
+
# PreTrainedModel
|
| 240 |
+
##################
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class DPRPretrainedContextEncoder(DPRPreTrainedModel):
|
| 244 |
+
"""
|
| 245 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 246 |
+
models.
|
| 247 |
+
"""
|
| 248 |
+
|
| 249 |
+
config: DPRConfig
|
| 250 |
+
load_tf_weights = None
|
| 251 |
+
base_model_prefix = "ctx_encoder"
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class DPRPretrainedQuestionEncoder(DPRPreTrainedModel):
|
| 255 |
+
"""
|
| 256 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 257 |
+
models.
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
config: DPRConfig
|
| 261 |
+
load_tf_weights = None
|
| 262 |
+
base_model_prefix = "question_encoder"
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class DPRPretrainedReader(DPRPreTrainedModel):
|
| 266 |
+
"""
|
| 267 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 268 |
+
models.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
config: DPRConfig
|
| 272 |
+
load_tf_weights = None
|
| 273 |
+
base_model_prefix = "span_predictor"
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
###############
|
| 277 |
+
# Actual Models
|
| 278 |
+
###############
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@auto_docstring(
|
| 282 |
+
custom_intro="""
|
| 283 |
+
The bare DPRContextEncoder transformer outputting pooler outputs as context representations.
|
| 284 |
+
"""
|
| 285 |
+
)
|
| 286 |
+
class DPRContextEncoder(DPRPretrainedContextEncoder):
|
| 287 |
+
def __init__(self, config: DPRConfig):
|
| 288 |
+
super().__init__(config)
|
| 289 |
+
self.config = config
|
| 290 |
+
self.ctx_encoder = DPREncoder(config)
|
| 291 |
+
# Initialize weights and apply final processing
|
| 292 |
+
self.post_init()
|
| 293 |
+
|
| 294 |
+
@auto_docstring
|
| 295 |
+
def forward(
|
| 296 |
+
self,
|
| 297 |
+
input_ids: Optional[Tensor] = None,
|
| 298 |
+
attention_mask: Optional[Tensor] = None,
|
| 299 |
+
token_type_ids: Optional[Tensor] = None,
|
| 300 |
+
inputs_embeds: Optional[Tensor] = None,
|
| 301 |
+
output_attentions: Optional[bool] = None,
|
| 302 |
+
output_hidden_states: Optional[bool] = None,
|
| 303 |
+
return_dict: Optional[bool] = None,
|
| 304 |
+
) -> Union[DPRContextEncoderOutput, tuple[Tensor, ...]]:
|
| 305 |
+
r"""
|
| 306 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 307 |
+
Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be
|
| 308 |
+
formatted with [CLS] and [SEP] tokens as follows:
|
| 309 |
+
|
| 310 |
+
(a) For sequence pairs (for a pair title+text for example):
|
| 311 |
+
|
| 312 |
+
```
|
| 313 |
+
tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
|
| 314 |
+
token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
|
| 315 |
+
```
|
| 316 |
+
|
| 317 |
+
(b) For single sequences (for a question for example):
|
| 318 |
+
|
| 319 |
+
```
|
| 320 |
+
tokens: [CLS] the dog is hairy . [SEP]
|
| 321 |
+
token_type_ids: 0 0 0 0 0 0 0
|
| 322 |
+
```
|
| 323 |
+
|
| 324 |
+
DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
|
| 325 |
+
rather than the left.
|
| 326 |
+
|
| 327 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 328 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 329 |
+
|
| 330 |
+
[What are input IDs?](../glossary#input-ids)
|
| 331 |
+
|
| 332 |
+
Examples:
|
| 333 |
+
|
| 334 |
+
```python
|
| 335 |
+
>>> from transformers import DPRContextEncoder, DPRContextEncoderTokenizer
|
| 336 |
+
|
| 337 |
+
>>> tokenizer = DPRContextEncoderTokenizer.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
|
| 338 |
+
>>> model = DPRContextEncoder.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
|
| 339 |
+
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"]
|
| 340 |
+
>>> embeddings = model(input_ids).pooler_output
|
| 341 |
+
```"""
|
| 342 |
+
|
| 343 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 344 |
+
output_hidden_states = (
|
| 345 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 346 |
+
)
|
| 347 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 348 |
+
|
| 349 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 350 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 351 |
+
elif input_ids is not None:
|
| 352 |
+
input_shape = input_ids.size()
|
| 353 |
+
elif inputs_embeds is not None:
|
| 354 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 355 |
+
else:
|
| 356 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 357 |
+
|
| 358 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 359 |
+
|
| 360 |
+
if attention_mask is None:
|
| 361 |
+
attention_mask = (
|
| 362 |
+
torch.ones(input_shape, device=device)
|
| 363 |
+
if input_ids is None
|
| 364 |
+
else (input_ids != self.config.pad_token_id)
|
| 365 |
+
)
|
| 366 |
+
if token_type_ids is None:
|
| 367 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 368 |
+
|
| 369 |
+
outputs = self.ctx_encoder(
|
| 370 |
+
input_ids=input_ids,
|
| 371 |
+
attention_mask=attention_mask,
|
| 372 |
+
token_type_ids=token_type_ids,
|
| 373 |
+
inputs_embeds=inputs_embeds,
|
| 374 |
+
output_attentions=output_attentions,
|
| 375 |
+
output_hidden_states=output_hidden_states,
|
| 376 |
+
return_dict=return_dict,
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
if not return_dict:
|
| 380 |
+
return outputs[1:]
|
| 381 |
+
return DPRContextEncoderOutput(
|
| 382 |
+
pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
@auto_docstring(
|
| 387 |
+
custom_intro="""
|
| 388 |
+
The bare DPRQuestionEncoder transformer outputting pooler outputs as question representations.
|
| 389 |
+
"""
|
| 390 |
+
)
|
| 391 |
+
class DPRQuestionEncoder(DPRPretrainedQuestionEncoder):
|
| 392 |
+
def __init__(self, config: DPRConfig):
|
| 393 |
+
super().__init__(config)
|
| 394 |
+
self.config = config
|
| 395 |
+
self.question_encoder = DPREncoder(config)
|
| 396 |
+
# Initialize weights and apply final processing
|
| 397 |
+
self.post_init()
|
| 398 |
+
|
| 399 |
+
@auto_docstring
|
| 400 |
+
def forward(
|
| 401 |
+
self,
|
| 402 |
+
input_ids: Optional[Tensor] = None,
|
| 403 |
+
attention_mask: Optional[Tensor] = None,
|
| 404 |
+
token_type_ids: Optional[Tensor] = None,
|
| 405 |
+
inputs_embeds: Optional[Tensor] = None,
|
| 406 |
+
output_attentions: Optional[bool] = None,
|
| 407 |
+
output_hidden_states: Optional[bool] = None,
|
| 408 |
+
return_dict: Optional[bool] = None,
|
| 409 |
+
) -> Union[DPRQuestionEncoderOutput, tuple[Tensor, ...]]:
|
| 410 |
+
r"""
|
| 411 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 412 |
+
Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be
|
| 413 |
+
formatted with [CLS] and [SEP] tokens as follows:
|
| 414 |
+
|
| 415 |
+
(a) For sequence pairs (for a pair title+text for example):
|
| 416 |
+
|
| 417 |
+
```
|
| 418 |
+
tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
|
| 419 |
+
token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
|
| 420 |
+
```
|
| 421 |
+
|
| 422 |
+
(b) For single sequences (for a question for example):
|
| 423 |
+
|
| 424 |
+
```
|
| 425 |
+
tokens: [CLS] the dog is hairy . [SEP]
|
| 426 |
+
token_type_ids: 0 0 0 0 0 0 0
|
| 427 |
+
```
|
| 428 |
+
|
| 429 |
+
DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
|
| 430 |
+
rather than the left.
|
| 431 |
+
|
| 432 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 433 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 434 |
+
|
| 435 |
+
[What are input IDs?](../glossary#input-ids)
|
| 436 |
+
|
| 437 |
+
Examples:
|
| 438 |
+
|
| 439 |
+
```python
|
| 440 |
+
>>> from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer
|
| 441 |
+
|
| 442 |
+
>>> tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 443 |
+
>>> model = DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 444 |
+
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"]
|
| 445 |
+
>>> embeddings = model(input_ids).pooler_output
|
| 446 |
+
```
|
| 447 |
+
"""
|
| 448 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 449 |
+
output_hidden_states = (
|
| 450 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 451 |
+
)
|
| 452 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 453 |
+
|
| 454 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 455 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 456 |
+
elif input_ids is not None:
|
| 457 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 458 |
+
input_shape = input_ids.size()
|
| 459 |
+
elif inputs_embeds is not None:
|
| 460 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 461 |
+
else:
|
| 462 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 463 |
+
|
| 464 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 465 |
+
|
| 466 |
+
if attention_mask is None:
|
| 467 |
+
attention_mask = (
|
| 468 |
+
torch.ones(input_shape, device=device)
|
| 469 |
+
if input_ids is None
|
| 470 |
+
else (input_ids != self.config.pad_token_id)
|
| 471 |
+
)
|
| 472 |
+
if token_type_ids is None:
|
| 473 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 474 |
+
|
| 475 |
+
outputs = self.question_encoder(
|
| 476 |
+
input_ids=input_ids,
|
| 477 |
+
attention_mask=attention_mask,
|
| 478 |
+
token_type_ids=token_type_ids,
|
| 479 |
+
inputs_embeds=inputs_embeds,
|
| 480 |
+
output_attentions=output_attentions,
|
| 481 |
+
output_hidden_states=output_hidden_states,
|
| 482 |
+
return_dict=return_dict,
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
if not return_dict:
|
| 486 |
+
return outputs[1:]
|
| 487 |
+
return DPRQuestionEncoderOutput(
|
| 488 |
+
pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
@auto_docstring(
|
| 493 |
+
custom_intro="""
|
| 494 |
+
The bare DPRReader transformer outputting span predictions.
|
| 495 |
+
"""
|
| 496 |
+
)
|
| 497 |
+
class DPRReader(DPRPretrainedReader):
|
| 498 |
+
def __init__(self, config: DPRConfig):
|
| 499 |
+
super().__init__(config)
|
| 500 |
+
self.config = config
|
| 501 |
+
self.span_predictor = DPRSpanPredictor(config)
|
| 502 |
+
# Initialize weights and apply final processing
|
| 503 |
+
self.post_init()
|
| 504 |
+
|
| 505 |
+
@auto_docstring
|
| 506 |
+
def forward(
|
| 507 |
+
self,
|
| 508 |
+
input_ids: Optional[Tensor] = None,
|
| 509 |
+
attention_mask: Optional[Tensor] = None,
|
| 510 |
+
inputs_embeds: Optional[Tensor] = None,
|
| 511 |
+
output_attentions: Optional[bool] = None,
|
| 512 |
+
output_hidden_states: Optional[bool] = None,
|
| 513 |
+
return_dict: Optional[bool] = None,
|
| 514 |
+
) -> Union[DPRReaderOutput, tuple[Tensor, ...]]:
|
| 515 |
+
r"""
|
| 516 |
+
input_ids (`tuple[torch.LongTensor]` of shapes `(n_passages, sequence_length)`):
|
| 517 |
+
Indices of input sequence tokens in the vocabulary. It has to be a sequence triplet with 1) the question
|
| 518 |
+
and 2) the passages titles and 3) the passages texts To match pretraining, DPR `input_ids` sequence should
|
| 519 |
+
be formatted with [CLS] and [SEP] with the format:
|
| 520 |
+
|
| 521 |
+
`[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>`
|
| 522 |
+
|
| 523 |
+
DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
|
| 524 |
+
rather than the left.
|
| 525 |
+
|
| 526 |
+
Indices can be obtained using [`DPRReaderTokenizer`]. See this class documentation for more details.
|
| 527 |
+
|
| 528 |
+
[What are input IDs?](../glossary#input-ids)
|
| 529 |
+
inputs_embeds (`torch.FloatTensor` of shape `(n_passages, sequence_length, hidden_size)`, *optional*):
|
| 530 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 531 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 532 |
+
model's internal embedding lookup matrix.
|
| 533 |
+
|
| 534 |
+
Examples:
|
| 535 |
+
|
| 536 |
+
```python
|
| 537 |
+
>>> from transformers import DPRReader, DPRReaderTokenizer
|
| 538 |
+
|
| 539 |
+
>>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 540 |
+
>>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 541 |
+
>>> encoded_inputs = tokenizer(
|
| 542 |
+
... questions=["What is love ?"],
|
| 543 |
+
... titles=["Haddaway"],
|
| 544 |
+
... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
|
| 545 |
+
... return_tensors="pt",
|
| 546 |
+
... )
|
| 547 |
+
>>> outputs = model(**encoded_inputs)
|
| 548 |
+
>>> start_logits = outputs.start_logits
|
| 549 |
+
>>> end_logits = outputs.end_logits
|
| 550 |
+
>>> relevance_logits = outputs.relevance_logits
|
| 551 |
+
```
|
| 552 |
+
"""
|
| 553 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 554 |
+
output_hidden_states = (
|
| 555 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 556 |
+
)
|
| 557 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 558 |
+
|
| 559 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 560 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 561 |
+
elif input_ids is not None:
|
| 562 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 563 |
+
input_shape = input_ids.size()
|
| 564 |
+
elif inputs_embeds is not None:
|
| 565 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 566 |
+
else:
|
| 567 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 568 |
+
|
| 569 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 570 |
+
|
| 571 |
+
if attention_mask is None:
|
| 572 |
+
attention_mask = torch.ones(input_shape, device=device)
|
| 573 |
+
|
| 574 |
+
return self.span_predictor(
|
| 575 |
+
input_ids,
|
| 576 |
+
attention_mask,
|
| 577 |
+
inputs_embeds=inputs_embeds,
|
| 578 |
+
output_attentions=output_attentions,
|
| 579 |
+
output_hidden_states=output_hidden_states,
|
| 580 |
+
return_dict=return_dict,
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
__all__ = [
|
| 585 |
+
"DPRContextEncoder",
|
| 586 |
+
"DPRPretrainedContextEncoder",
|
| 587 |
+
"DPRPreTrainedModel",
|
| 588 |
+
"DPRPretrainedQuestionEncoder",
|
| 589 |
+
"DPRPretrainedReader",
|
| 590 |
+
"DPRQuestionEncoder",
|
| 591 |
+
"DPRReader",
|
| 592 |
+
]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dpr/modeling_tf_dpr.py
ADDED
|
@@ -0,0 +1,799 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 DPR Authors, The Hugging Face Team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""TensorFlow DPR model for Open Domain Question Answering."""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
|
| 22 |
+
import tensorflow as tf
|
| 23 |
+
|
| 24 |
+
from ...modeling_tf_outputs import TFBaseModelOutputWithPooling
|
| 25 |
+
from ...modeling_tf_utils import TFModelInputType, TFPreTrainedModel, get_initializer, keras, shape_list, unpack_inputs
|
| 26 |
+
from ...utils import (
|
| 27 |
+
ModelOutput,
|
| 28 |
+
add_start_docstrings,
|
| 29 |
+
add_start_docstrings_to_model_forward,
|
| 30 |
+
logging,
|
| 31 |
+
replace_return_docstrings,
|
| 32 |
+
)
|
| 33 |
+
from ..bert.modeling_tf_bert import TFBertMainLayer
|
| 34 |
+
from .configuration_dpr import DPRConfig
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__)
|
| 38 |
+
|
| 39 |
+
_CONFIG_FOR_DOC = "DPRConfig"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
##########
|
| 43 |
+
# Outputs
|
| 44 |
+
##########
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class TFDPRContextEncoderOutput(ModelOutput):
|
| 49 |
+
r"""
|
| 50 |
+
Class for outputs of [`TFDPRContextEncoder`].
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
pooler_output (`tf.Tensor` of shape `(batch_size, embeddings_size)`):
|
| 54 |
+
The DPR encoder outputs the *pooler_output* that corresponds to the context representation. Last layer
|
| 55 |
+
hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
|
| 56 |
+
This output is to be used to embed contexts for nearest neighbors queries with questions embeddings.
|
| 57 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 58 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 59 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 60 |
+
|
| 61 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 62 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 63 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 64 |
+
sequence_length)`.
|
| 65 |
+
|
| 66 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 67 |
+
heads.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
pooler_output: tf.Tensor | None = None
|
| 71 |
+
hidden_states: tuple[tf.Tensor, ...] | None = None
|
| 72 |
+
attentions: tuple[tf.Tensor, ...] | None = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@dataclass
|
| 76 |
+
class TFDPRQuestionEncoderOutput(ModelOutput):
|
| 77 |
+
"""
|
| 78 |
+
Class for outputs of [`TFDPRQuestionEncoder`].
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
pooler_output (`tf.Tensor` of shape `(batch_size, embeddings_size)`):
|
| 82 |
+
The DPR encoder outputs the *pooler_output* that corresponds to the question representation. Last layer
|
| 83 |
+
hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
|
| 84 |
+
This output is to be used to embed questions for nearest neighbors queries with context embeddings.
|
| 85 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 86 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 87 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 88 |
+
|
| 89 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 90 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 91 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 92 |
+
sequence_length)`.
|
| 93 |
+
|
| 94 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 95 |
+
heads.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
pooler_output: tf.Tensor | None = None
|
| 99 |
+
hidden_states: tuple[tf.Tensor, ...] | None = None
|
| 100 |
+
attentions: tuple[tf.Tensor, ...] | None = None
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@dataclass
|
| 104 |
+
class TFDPRReaderOutput(ModelOutput):
|
| 105 |
+
"""
|
| 106 |
+
Class for outputs of [`TFDPRReaderEncoder`].
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
start_logits (`tf.Tensor` of shape `(n_passages, sequence_length)`):
|
| 110 |
+
Logits of the start index of the span for each passage.
|
| 111 |
+
end_logits (`tf.Tensor` of shape `(n_passages, sequence_length)`):
|
| 112 |
+
Logits of the end index of the span for each passage.
|
| 113 |
+
relevance_logits (`tf.Tensor` of shape `(n_passages, )`):
|
| 114 |
+
Outputs of the QA classifier of the DPRReader that corresponds to the scores of each passage to answer the
|
| 115 |
+
question, compared to all the other passages.
|
| 116 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 117 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 118 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 119 |
+
|
| 120 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 121 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 122 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 123 |
+
sequence_length)`.
|
| 124 |
+
|
| 125 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 126 |
+
heads.
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
start_logits: tf.Tensor | None = None
|
| 130 |
+
end_logits: tf.Tensor | None = None
|
| 131 |
+
relevance_logits: tf.Tensor | None = None
|
| 132 |
+
hidden_states: tuple[tf.Tensor, ...] | None = None
|
| 133 |
+
attentions: tuple[tf.Tensor, ...] | None = None
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class TFDPREncoderLayer(keras.layers.Layer):
|
| 137 |
+
base_model_prefix = "bert_model"
|
| 138 |
+
|
| 139 |
+
def __init__(self, config: DPRConfig, **kwargs):
|
| 140 |
+
super().__init__(**kwargs)
|
| 141 |
+
|
| 142 |
+
# resolve name conflict with TFBertMainLayer instead of TFBertModel
|
| 143 |
+
self.bert_model = TFBertMainLayer(config, add_pooling_layer=False, name="bert_model")
|
| 144 |
+
self.config = config
|
| 145 |
+
|
| 146 |
+
if self.config.hidden_size <= 0:
|
| 147 |
+
raise ValueError("Encoder hidden_size can't be zero")
|
| 148 |
+
self.projection_dim = config.projection_dim
|
| 149 |
+
if self.projection_dim > 0:
|
| 150 |
+
self.encode_proj = keras.layers.Dense(
|
| 151 |
+
config.projection_dim, kernel_initializer=get_initializer(config.initializer_range), name="encode_proj"
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
@unpack_inputs
|
| 155 |
+
def call(
|
| 156 |
+
self,
|
| 157 |
+
input_ids: tf.Tensor | None = None,
|
| 158 |
+
attention_mask: tf.Tensor | None = None,
|
| 159 |
+
token_type_ids: tf.Tensor | None = None,
|
| 160 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 161 |
+
output_attentions: bool | None = None,
|
| 162 |
+
output_hidden_states: bool | None = None,
|
| 163 |
+
return_dict: bool | None = None,
|
| 164 |
+
training: bool = False,
|
| 165 |
+
) -> TFBaseModelOutputWithPooling | tuple[tf.Tensor, ...]:
|
| 166 |
+
outputs = self.bert_model(
|
| 167 |
+
input_ids=input_ids,
|
| 168 |
+
attention_mask=attention_mask,
|
| 169 |
+
token_type_ids=token_type_ids,
|
| 170 |
+
inputs_embeds=inputs_embeds,
|
| 171 |
+
output_attentions=output_attentions,
|
| 172 |
+
output_hidden_states=output_hidden_states,
|
| 173 |
+
return_dict=return_dict,
|
| 174 |
+
training=training,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
sequence_output = outputs[0]
|
| 178 |
+
pooled_output = sequence_output[:, 0, :]
|
| 179 |
+
if self.projection_dim > 0:
|
| 180 |
+
pooled_output = self.encode_proj(pooled_output)
|
| 181 |
+
|
| 182 |
+
if not return_dict:
|
| 183 |
+
return (sequence_output, pooled_output) + outputs[1:]
|
| 184 |
+
|
| 185 |
+
return TFBaseModelOutputWithPooling(
|
| 186 |
+
last_hidden_state=sequence_output,
|
| 187 |
+
pooler_output=pooled_output,
|
| 188 |
+
hidden_states=outputs.hidden_states,
|
| 189 |
+
attentions=outputs.attentions,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
@property
|
| 193 |
+
def embeddings_size(self) -> int:
|
| 194 |
+
if self.projection_dim > 0:
|
| 195 |
+
return self.projection_dim
|
| 196 |
+
return self.bert_model.config.hidden_size
|
| 197 |
+
|
| 198 |
+
def build(self, input_shape=None):
|
| 199 |
+
if self.built:
|
| 200 |
+
return
|
| 201 |
+
self.built = True
|
| 202 |
+
if getattr(self, "bert_model", None) is not None:
|
| 203 |
+
with tf.name_scope(self.bert_model.name):
|
| 204 |
+
self.bert_model.build(None)
|
| 205 |
+
if getattr(self, "encode_proj", None) is not None:
|
| 206 |
+
with tf.name_scope(self.encode_proj.name):
|
| 207 |
+
self.encode_proj.build(None)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class TFDPRSpanPredictorLayer(keras.layers.Layer):
|
| 211 |
+
base_model_prefix = "encoder"
|
| 212 |
+
|
| 213 |
+
def __init__(self, config: DPRConfig, **kwargs):
|
| 214 |
+
super().__init__(**kwargs)
|
| 215 |
+
self.config = config
|
| 216 |
+
self.encoder = TFDPREncoderLayer(config, name="encoder")
|
| 217 |
+
|
| 218 |
+
self.qa_outputs = keras.layers.Dense(
|
| 219 |
+
2, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
|
| 220 |
+
)
|
| 221 |
+
self.qa_classifier = keras.layers.Dense(
|
| 222 |
+
1, kernel_initializer=get_initializer(config.initializer_range), name="qa_classifier"
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
@unpack_inputs
|
| 226 |
+
def call(
|
| 227 |
+
self,
|
| 228 |
+
input_ids: tf.Tensor | None = None,
|
| 229 |
+
attention_mask: tf.Tensor | None = None,
|
| 230 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 231 |
+
output_attentions: bool = False,
|
| 232 |
+
output_hidden_states: bool = False,
|
| 233 |
+
return_dict: bool = False,
|
| 234 |
+
training: bool = False,
|
| 235 |
+
) -> TFDPRReaderOutput | tuple[tf.Tensor, ...]:
|
| 236 |
+
# notations: N - number of questions in a batch, M - number of passages per questions, L - sequence length
|
| 237 |
+
n_passages, sequence_length = shape_list(input_ids) if input_ids is not None else shape_list(inputs_embeds)[:2]
|
| 238 |
+
# feed encoder
|
| 239 |
+
outputs = self.encoder(
|
| 240 |
+
input_ids=input_ids,
|
| 241 |
+
attention_mask=attention_mask,
|
| 242 |
+
inputs_embeds=inputs_embeds,
|
| 243 |
+
output_attentions=output_attentions,
|
| 244 |
+
output_hidden_states=output_hidden_states,
|
| 245 |
+
return_dict=return_dict,
|
| 246 |
+
training=training,
|
| 247 |
+
)
|
| 248 |
+
sequence_output = outputs[0]
|
| 249 |
+
|
| 250 |
+
# compute logits
|
| 251 |
+
logits = self.qa_outputs(sequence_output)
|
| 252 |
+
start_logits, end_logits = tf.split(logits, 2, axis=-1)
|
| 253 |
+
start_logits = tf.squeeze(start_logits, axis=-1)
|
| 254 |
+
end_logits = tf.squeeze(end_logits, axis=-1)
|
| 255 |
+
relevance_logits = self.qa_classifier(sequence_output[:, 0, :])
|
| 256 |
+
|
| 257 |
+
# resize
|
| 258 |
+
start_logits = tf.reshape(start_logits, [n_passages, sequence_length])
|
| 259 |
+
end_logits = tf.reshape(end_logits, [n_passages, sequence_length])
|
| 260 |
+
relevance_logits = tf.reshape(relevance_logits, [n_passages])
|
| 261 |
+
|
| 262 |
+
if not return_dict:
|
| 263 |
+
return (start_logits, end_logits, relevance_logits) + outputs[2:]
|
| 264 |
+
|
| 265 |
+
return TFDPRReaderOutput(
|
| 266 |
+
start_logits=start_logits,
|
| 267 |
+
end_logits=end_logits,
|
| 268 |
+
relevance_logits=relevance_logits,
|
| 269 |
+
hidden_states=outputs.hidden_states,
|
| 270 |
+
attentions=outputs.attentions,
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
def build(self, input_shape=None):
|
| 274 |
+
if self.built:
|
| 275 |
+
return
|
| 276 |
+
self.built = True
|
| 277 |
+
if getattr(self, "encoder", None) is not None:
|
| 278 |
+
with tf.name_scope(self.encoder.name):
|
| 279 |
+
self.encoder.build(None)
|
| 280 |
+
if getattr(self, "qa_outputs", None) is not None:
|
| 281 |
+
with tf.name_scope(self.qa_outputs.name):
|
| 282 |
+
self.qa_outputs.build([None, None, self.encoder.embeddings_size])
|
| 283 |
+
if getattr(self, "qa_classifier", None) is not None:
|
| 284 |
+
with tf.name_scope(self.qa_classifier.name):
|
| 285 |
+
self.qa_classifier.build([None, None, self.encoder.embeddings_size])
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class TFDPRSpanPredictor(TFPreTrainedModel):
|
| 289 |
+
base_model_prefix = "encoder"
|
| 290 |
+
|
| 291 |
+
def __init__(self, config: DPRConfig, **kwargs):
|
| 292 |
+
super().__init__(config, **kwargs)
|
| 293 |
+
self.encoder = TFDPRSpanPredictorLayer(config)
|
| 294 |
+
|
| 295 |
+
@unpack_inputs
|
| 296 |
+
def call(
|
| 297 |
+
self,
|
| 298 |
+
input_ids: tf.Tensor | None = None,
|
| 299 |
+
attention_mask: tf.Tensor | None = None,
|
| 300 |
+
token_type_ids: tf.Tensor | None = None,
|
| 301 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 302 |
+
output_attentions: bool = False,
|
| 303 |
+
output_hidden_states: bool = False,
|
| 304 |
+
return_dict: bool = False,
|
| 305 |
+
training: bool = False,
|
| 306 |
+
) -> TFDPRReaderOutput | tuple[tf.Tensor, ...]:
|
| 307 |
+
outputs = self.encoder(
|
| 308 |
+
input_ids=input_ids,
|
| 309 |
+
attention_mask=attention_mask,
|
| 310 |
+
inputs_embeds=inputs_embeds,
|
| 311 |
+
output_attentions=output_attentions,
|
| 312 |
+
output_hidden_states=output_hidden_states,
|
| 313 |
+
return_dict=return_dict,
|
| 314 |
+
training=training,
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
return outputs
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class TFDPREncoder(TFPreTrainedModel):
|
| 321 |
+
base_model_prefix = "encoder"
|
| 322 |
+
|
| 323 |
+
def __init__(self, config: DPRConfig, **kwargs):
|
| 324 |
+
super().__init__(config, **kwargs)
|
| 325 |
+
|
| 326 |
+
self.encoder = TFDPREncoderLayer(config)
|
| 327 |
+
|
| 328 |
+
@unpack_inputs
|
| 329 |
+
def call(
|
| 330 |
+
self,
|
| 331 |
+
input_ids: tf.Tensor | None = None,
|
| 332 |
+
attention_mask: tf.Tensor | None = None,
|
| 333 |
+
token_type_ids: tf.Tensor | None = None,
|
| 334 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 335 |
+
output_attentions: bool = False,
|
| 336 |
+
output_hidden_states: bool = False,
|
| 337 |
+
return_dict: bool = False,
|
| 338 |
+
training: bool = False,
|
| 339 |
+
) -> TFDPRReaderOutput | tuple[tf.Tensor, ...]:
|
| 340 |
+
outputs = self.encoder(
|
| 341 |
+
input_ids=input_ids,
|
| 342 |
+
attention_mask=attention_mask,
|
| 343 |
+
inputs_embeds=inputs_embeds,
|
| 344 |
+
output_attentions=output_attentions,
|
| 345 |
+
output_hidden_states=output_hidden_states,
|
| 346 |
+
return_dict=return_dict,
|
| 347 |
+
training=training,
|
| 348 |
+
)
|
| 349 |
+
return outputs
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
##################
|
| 353 |
+
# PreTrainedModel
|
| 354 |
+
##################
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
class TFDPRPretrainedContextEncoder(TFPreTrainedModel):
|
| 358 |
+
"""
|
| 359 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 360 |
+
models.
|
| 361 |
+
"""
|
| 362 |
+
|
| 363 |
+
config_class = DPRConfig
|
| 364 |
+
base_model_prefix = "ctx_encoder"
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
class TFDPRPretrainedQuestionEncoder(TFPreTrainedModel):
|
| 368 |
+
"""
|
| 369 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 370 |
+
models.
|
| 371 |
+
"""
|
| 372 |
+
|
| 373 |
+
config_class = DPRConfig
|
| 374 |
+
base_model_prefix = "question_encoder"
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
class TFDPRPretrainedReader(TFPreTrainedModel):
|
| 378 |
+
"""
|
| 379 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 380 |
+
models.
|
| 381 |
+
"""
|
| 382 |
+
|
| 383 |
+
config_class = DPRConfig
|
| 384 |
+
base_model_prefix = "reader"
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
###############
|
| 388 |
+
# Actual Models
|
| 389 |
+
###############
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
TF_DPR_START_DOCSTRING = r"""
|
| 393 |
+
|
| 394 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 395 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 396 |
+
etc.)
|
| 397 |
+
|
| 398 |
+
This model is also a Tensorflow [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)
|
| 399 |
+
subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to
|
| 400 |
+
general usage and behavior.
|
| 401 |
+
|
| 402 |
+
<Tip>
|
| 403 |
+
|
| 404 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 405 |
+
|
| 406 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 407 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 408 |
+
|
| 409 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 410 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 411 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 412 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 413 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 414 |
+
positional argument:
|
| 415 |
+
|
| 416 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 417 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 418 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 419 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 420 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 421 |
+
|
| 422 |
+
Note that when creating models and layers with
|
| 423 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 424 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 425 |
+
|
| 426 |
+
</Tip>
|
| 427 |
+
|
| 428 |
+
Parameters:
|
| 429 |
+
config ([`DPRConfig`]): Model configuration class with all the parameters of the model.
|
| 430 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 431 |
+
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 432 |
+
"""
|
| 433 |
+
|
| 434 |
+
TF_DPR_ENCODERS_INPUTS_DOCSTRING = r"""
|
| 435 |
+
Args:
|
| 436 |
+
input_ids (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length)`):
|
| 437 |
+
Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be
|
| 438 |
+
formatted with [CLS] and [SEP] tokens as follows:
|
| 439 |
+
|
| 440 |
+
(a) For sequence pairs (for a pair title+text for example):
|
| 441 |
+
|
| 442 |
+
```
|
| 443 |
+
tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
|
| 444 |
+
token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
|
| 445 |
+
```
|
| 446 |
+
|
| 447 |
+
(b) For single sequences (for a question for example):
|
| 448 |
+
|
| 449 |
+
```
|
| 450 |
+
tokens: [CLS] the dog is hairy . [SEP]
|
| 451 |
+
token_type_ids: 0 0 0 0 0 0 0
|
| 452 |
+
```
|
| 453 |
+
|
| 454 |
+
DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
|
| 455 |
+
rather than the left.
|
| 456 |
+
|
| 457 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 458 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 459 |
+
|
| 460 |
+
[What are input IDs?](../glossary#input-ids)
|
| 461 |
+
attention_mask (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 462 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 463 |
+
|
| 464 |
+
- 1 for tokens that are **not masked**,
|
| 465 |
+
- 0 for tokens that are **masked**.
|
| 466 |
+
|
| 467 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 468 |
+
token_type_ids (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 469 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 470 |
+
1]`:
|
| 471 |
+
|
| 472 |
+
- 0 corresponds to a *sentence A* token,
|
| 473 |
+
- 1 corresponds to a *sentence B* token.
|
| 474 |
+
|
| 475 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 476 |
+
inputs_embeds (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 477 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 478 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 479 |
+
model's internal embedding lookup matrix.
|
| 480 |
+
output_attentions (`bool`, *optional*):
|
| 481 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 482 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 483 |
+
config will be used instead.
|
| 484 |
+
output_hidden_states (`bool`, *optional*):
|
| 485 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 486 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 487 |
+
used instead.
|
| 488 |
+
return_dict (`bool`, *optional*):
|
| 489 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 490 |
+
eager mode, in graph mode the value will always be set to True.
|
| 491 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 492 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 493 |
+
behaviors between training and evaluation).
|
| 494 |
+
"""
|
| 495 |
+
|
| 496 |
+
TF_DPR_READER_INPUTS_DOCSTRING = r"""
|
| 497 |
+
Args:
|
| 498 |
+
input_ids (`Numpy array` or `tf.Tensor` of shapes `(n_passages, sequence_length)`):
|
| 499 |
+
Indices of input sequence tokens in the vocabulary. It has to be a sequence triplet with 1) the question
|
| 500 |
+
and 2) the passages titles and 3) the passages texts To match pretraining, DPR `input_ids` sequence should
|
| 501 |
+
be formatted with [CLS] and [SEP] with the format:
|
| 502 |
+
|
| 503 |
+
`[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>`
|
| 504 |
+
|
| 505 |
+
DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
|
| 506 |
+
rather than the left.
|
| 507 |
+
|
| 508 |
+
Indices can be obtained using [`DPRReaderTokenizer`]. See this class documentation for more details.
|
| 509 |
+
attention_mask (`Numpy array` or `tf.Tensor` of shape `(n_passages, sequence_length)`, *optional*):
|
| 510 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 511 |
+
|
| 512 |
+
- 1 for tokens that are **not masked**,
|
| 513 |
+
- 0 for tokens that are **masked**.
|
| 514 |
+
|
| 515 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 516 |
+
inputs_embeds (`Numpy array` or `tf.Tensor` of shape `(n_passages, sequence_length, hidden_size)`, *optional*):
|
| 517 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 518 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 519 |
+
model's internal embedding lookup matrix.
|
| 520 |
+
output_hidden_states (`bool`, *optional*):
|
| 521 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 522 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 523 |
+
used instead.
|
| 524 |
+
return_dict (`bool`, *optional*):
|
| 525 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 526 |
+
eager mode, in graph mode the value will always be set to True.
|
| 527 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 528 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 529 |
+
behaviors between training and evaluation).
|
| 530 |
+
"""
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
@add_start_docstrings(
|
| 534 |
+
"The bare DPRContextEncoder transformer outputting pooler outputs as context representations.",
|
| 535 |
+
TF_DPR_START_DOCSTRING,
|
| 536 |
+
)
|
| 537 |
+
class TFDPRContextEncoder(TFDPRPretrainedContextEncoder):
|
| 538 |
+
def __init__(self, config: DPRConfig, *args, **kwargs):
|
| 539 |
+
super().__init__(config, *args, **kwargs)
|
| 540 |
+
self.ctx_encoder = TFDPREncoderLayer(config, name="ctx_encoder")
|
| 541 |
+
|
| 542 |
+
def get_input_embeddings(self):
|
| 543 |
+
try:
|
| 544 |
+
return self.ctx_encoder.bert_model.get_input_embeddings()
|
| 545 |
+
except AttributeError:
|
| 546 |
+
self.build()
|
| 547 |
+
return self.ctx_encoder.bert_model.get_input_embeddings()
|
| 548 |
+
|
| 549 |
+
@unpack_inputs
|
| 550 |
+
@add_start_docstrings_to_model_forward(TF_DPR_ENCODERS_INPUTS_DOCSTRING)
|
| 551 |
+
@replace_return_docstrings(output_type=TFDPRContextEncoderOutput, config_class=_CONFIG_FOR_DOC)
|
| 552 |
+
def call(
|
| 553 |
+
self,
|
| 554 |
+
input_ids: TFModelInputType | None = None,
|
| 555 |
+
attention_mask: tf.Tensor | None = None,
|
| 556 |
+
token_type_ids: tf.Tensor | None = None,
|
| 557 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 558 |
+
output_attentions: bool | None = None,
|
| 559 |
+
output_hidden_states: bool | None = None,
|
| 560 |
+
return_dict: bool | None = None,
|
| 561 |
+
training: bool = False,
|
| 562 |
+
) -> TFDPRContextEncoderOutput | tuple[tf.Tensor, ...]:
|
| 563 |
+
r"""
|
| 564 |
+
Return:
|
| 565 |
+
|
| 566 |
+
Examples:
|
| 567 |
+
|
| 568 |
+
```python
|
| 569 |
+
>>> from transformers import TFDPRContextEncoder, DPRContextEncoderTokenizer
|
| 570 |
+
|
| 571 |
+
>>> tokenizer = DPRContextEncoderTokenizer.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
|
| 572 |
+
>>> model = TFDPRContextEncoder.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base", from_pt=True)
|
| 573 |
+
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="tf")["input_ids"]
|
| 574 |
+
>>> embeddings = model(input_ids).pooler_output
|
| 575 |
+
```
|
| 576 |
+
"""
|
| 577 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 578 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 579 |
+
elif input_ids is not None:
|
| 580 |
+
input_shape = shape_list(input_ids)
|
| 581 |
+
elif inputs_embeds is not None:
|
| 582 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 583 |
+
else:
|
| 584 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 585 |
+
|
| 586 |
+
if attention_mask is None:
|
| 587 |
+
attention_mask = (
|
| 588 |
+
tf.ones(input_shape, dtype=tf.dtypes.int32)
|
| 589 |
+
if input_ids is None
|
| 590 |
+
else (input_ids != self.config.pad_token_id)
|
| 591 |
+
)
|
| 592 |
+
if token_type_ids is None:
|
| 593 |
+
token_type_ids = tf.zeros(input_shape, dtype=tf.dtypes.int32)
|
| 594 |
+
|
| 595 |
+
outputs = self.ctx_encoder(
|
| 596 |
+
input_ids=input_ids,
|
| 597 |
+
attention_mask=attention_mask,
|
| 598 |
+
token_type_ids=token_type_ids,
|
| 599 |
+
inputs_embeds=inputs_embeds,
|
| 600 |
+
output_attentions=output_attentions,
|
| 601 |
+
output_hidden_states=output_hidden_states,
|
| 602 |
+
return_dict=return_dict,
|
| 603 |
+
training=training,
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
if not return_dict:
|
| 607 |
+
return outputs[1:]
|
| 608 |
+
|
| 609 |
+
return TFDPRContextEncoderOutput(
|
| 610 |
+
pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
|
| 611 |
+
)
|
| 612 |
+
|
| 613 |
+
def build(self, input_shape=None):
|
| 614 |
+
if self.built:
|
| 615 |
+
return
|
| 616 |
+
self.built = True
|
| 617 |
+
if getattr(self, "ctx_encoder", None) is not None:
|
| 618 |
+
with tf.name_scope(self.ctx_encoder.name):
|
| 619 |
+
self.ctx_encoder.build(None)
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
@add_start_docstrings(
|
| 623 |
+
"The bare DPRQuestionEncoder transformer outputting pooler outputs as question representations.",
|
| 624 |
+
TF_DPR_START_DOCSTRING,
|
| 625 |
+
)
|
| 626 |
+
class TFDPRQuestionEncoder(TFDPRPretrainedQuestionEncoder):
|
| 627 |
+
def __init__(self, config: DPRConfig, *args, **kwargs):
|
| 628 |
+
super().__init__(config, *args, **kwargs)
|
| 629 |
+
self.question_encoder = TFDPREncoderLayer(config, name="question_encoder")
|
| 630 |
+
|
| 631 |
+
def get_input_embeddings(self):
|
| 632 |
+
try:
|
| 633 |
+
return self.question_encoder.bert_model.get_input_embeddings()
|
| 634 |
+
except AttributeError:
|
| 635 |
+
self.build()
|
| 636 |
+
return self.question_encoder.bert_model.get_input_embeddings()
|
| 637 |
+
|
| 638 |
+
@unpack_inputs
|
| 639 |
+
@add_start_docstrings_to_model_forward(TF_DPR_ENCODERS_INPUTS_DOCSTRING)
|
| 640 |
+
@replace_return_docstrings(output_type=TFDPRQuestionEncoderOutput, config_class=_CONFIG_FOR_DOC)
|
| 641 |
+
def call(
|
| 642 |
+
self,
|
| 643 |
+
input_ids: TFModelInputType | None = None,
|
| 644 |
+
attention_mask: tf.Tensor | None = None,
|
| 645 |
+
token_type_ids: tf.Tensor | None = None,
|
| 646 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 647 |
+
output_attentions: bool | None = None,
|
| 648 |
+
output_hidden_states: bool | None = None,
|
| 649 |
+
return_dict: bool | None = None,
|
| 650 |
+
training: bool = False,
|
| 651 |
+
) -> TFDPRQuestionEncoderOutput | tuple[tf.Tensor, ...]:
|
| 652 |
+
r"""
|
| 653 |
+
Return:
|
| 654 |
+
|
| 655 |
+
Examples:
|
| 656 |
+
|
| 657 |
+
```python
|
| 658 |
+
>>> from transformers import TFDPRQuestionEncoder, DPRQuestionEncoderTokenizer
|
| 659 |
+
|
| 660 |
+
>>> tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 661 |
+
>>> model = TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base", from_pt=True)
|
| 662 |
+
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="tf")["input_ids"]
|
| 663 |
+
>>> embeddings = model(input_ids).pooler_output
|
| 664 |
+
```
|
| 665 |
+
"""
|
| 666 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 667 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 668 |
+
elif input_ids is not None:
|
| 669 |
+
input_shape = shape_list(input_ids)
|
| 670 |
+
elif inputs_embeds is not None:
|
| 671 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 672 |
+
else:
|
| 673 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 674 |
+
|
| 675 |
+
if attention_mask is None:
|
| 676 |
+
attention_mask = (
|
| 677 |
+
tf.ones(input_shape, dtype=tf.dtypes.int32)
|
| 678 |
+
if input_ids is None
|
| 679 |
+
else (input_ids != self.config.pad_token_id)
|
| 680 |
+
)
|
| 681 |
+
if token_type_ids is None:
|
| 682 |
+
token_type_ids = tf.zeros(input_shape, dtype=tf.dtypes.int32)
|
| 683 |
+
|
| 684 |
+
outputs = self.question_encoder(
|
| 685 |
+
input_ids=input_ids,
|
| 686 |
+
attention_mask=attention_mask,
|
| 687 |
+
token_type_ids=token_type_ids,
|
| 688 |
+
inputs_embeds=inputs_embeds,
|
| 689 |
+
output_attentions=output_attentions,
|
| 690 |
+
output_hidden_states=output_hidden_states,
|
| 691 |
+
return_dict=return_dict,
|
| 692 |
+
training=training,
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
if not return_dict:
|
| 696 |
+
return outputs[1:]
|
| 697 |
+
return TFDPRQuestionEncoderOutput(
|
| 698 |
+
pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
def build(self, input_shape=None):
|
| 702 |
+
if self.built:
|
| 703 |
+
return
|
| 704 |
+
self.built = True
|
| 705 |
+
if getattr(self, "question_encoder", None) is not None:
|
| 706 |
+
with tf.name_scope(self.question_encoder.name):
|
| 707 |
+
self.question_encoder.build(None)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
@add_start_docstrings(
|
| 711 |
+
"The bare DPRReader transformer outputting span predictions.",
|
| 712 |
+
TF_DPR_START_DOCSTRING,
|
| 713 |
+
)
|
| 714 |
+
class TFDPRReader(TFDPRPretrainedReader):
|
| 715 |
+
def __init__(self, config: DPRConfig, *args, **kwargs):
|
| 716 |
+
super().__init__(config, *args, **kwargs)
|
| 717 |
+
self.span_predictor = TFDPRSpanPredictorLayer(config, name="span_predictor")
|
| 718 |
+
|
| 719 |
+
def get_input_embeddings(self):
|
| 720 |
+
try:
|
| 721 |
+
return self.span_predictor.encoder.bert_model.get_input_embeddings()
|
| 722 |
+
except AttributeError:
|
| 723 |
+
self.build()
|
| 724 |
+
return self.span_predictor.encoder.bert_model.get_input_embeddings()
|
| 725 |
+
|
| 726 |
+
@unpack_inputs
|
| 727 |
+
@add_start_docstrings_to_model_forward(TF_DPR_READER_INPUTS_DOCSTRING)
|
| 728 |
+
@replace_return_docstrings(output_type=TFDPRReaderOutput, config_class=_CONFIG_FOR_DOC)
|
| 729 |
+
def call(
|
| 730 |
+
self,
|
| 731 |
+
input_ids: TFModelInputType | None = None,
|
| 732 |
+
attention_mask: tf.Tensor | None = None,
|
| 733 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 734 |
+
output_attentions: bool | None = None,
|
| 735 |
+
output_hidden_states: bool | None = None,
|
| 736 |
+
return_dict: bool | None = None,
|
| 737 |
+
training: bool = False,
|
| 738 |
+
) -> TFDPRReaderOutput | tuple[tf.Tensor, ...]:
|
| 739 |
+
r"""
|
| 740 |
+
Return:
|
| 741 |
+
|
| 742 |
+
Examples:
|
| 743 |
+
|
| 744 |
+
```python
|
| 745 |
+
>>> from transformers import TFDPRReader, DPRReaderTokenizer
|
| 746 |
+
|
| 747 |
+
>>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 748 |
+
>>> model = TFDPRReader.from_pretrained("facebook/dpr-reader-single-nq-base", from_pt=True)
|
| 749 |
+
>>> encoded_inputs = tokenizer(
|
| 750 |
+
... questions=["What is love ?"],
|
| 751 |
+
... titles=["Haddaway"],
|
| 752 |
+
... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
|
| 753 |
+
... return_tensors="tf",
|
| 754 |
+
... )
|
| 755 |
+
>>> outputs = model(encoded_inputs)
|
| 756 |
+
>>> start_logits = outputs.start_logits
|
| 757 |
+
>>> end_logits = outputs.end_logits
|
| 758 |
+
>>> relevance_logits = outputs.relevance_logits
|
| 759 |
+
```
|
| 760 |
+
"""
|
| 761 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 762 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 763 |
+
elif input_ids is not None:
|
| 764 |
+
input_shape = shape_list(input_ids)
|
| 765 |
+
elif inputs_embeds is not None:
|
| 766 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 767 |
+
else:
|
| 768 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 769 |
+
|
| 770 |
+
if attention_mask is None:
|
| 771 |
+
attention_mask = tf.ones(input_shape, dtype=tf.dtypes.int32)
|
| 772 |
+
|
| 773 |
+
return self.span_predictor(
|
| 774 |
+
input_ids=input_ids,
|
| 775 |
+
attention_mask=attention_mask,
|
| 776 |
+
inputs_embeds=inputs_embeds,
|
| 777 |
+
output_attentions=output_attentions,
|
| 778 |
+
output_hidden_states=output_hidden_states,
|
| 779 |
+
return_dict=return_dict,
|
| 780 |
+
training=training,
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
def build(self, input_shape=None):
|
| 784 |
+
if self.built:
|
| 785 |
+
return
|
| 786 |
+
self.built = True
|
| 787 |
+
if getattr(self, "span_predictor", None) is not None:
|
| 788 |
+
with tf.name_scope(self.span_predictor.name):
|
| 789 |
+
self.span_predictor.build(None)
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
__all__ = [
|
| 793 |
+
"TFDPRContextEncoder",
|
| 794 |
+
"TFDPRPretrainedContextEncoder",
|
| 795 |
+
"TFDPRPretrainedQuestionEncoder",
|
| 796 |
+
"TFDPRPretrainedReader",
|
| 797 |
+
"TFDPRQuestionEncoder",
|
| 798 |
+
"TFDPRReader",
|
| 799 |
+
]
|
data/tefig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. team, The Hugging Face 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 DPR."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
from typing import Optional, Union
|
| 19 |
+
|
| 20 |
+
from ...tokenization_utils_base import BatchEncoding
|
| 21 |
+
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
|
| 22 |
+
from ..bert.tokenization_bert import BertTokenizer
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class DPRContextEncoderTokenizer(BertTokenizer):
|
| 31 |
+
r"""
|
| 32 |
+
Construct a DPRContextEncoder tokenizer.
|
| 33 |
+
|
| 34 |
+
[`DPRContextEncoderTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation
|
| 35 |
+
splitting and wordpiece.
|
| 36 |
+
|
| 37 |
+
Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class DPRQuestionEncoderTokenizer(BertTokenizer):
|
| 44 |
+
r"""
|
| 45 |
+
Constructs a DPRQuestionEncoder tokenizer.
|
| 46 |
+
|
| 47 |
+
[`DPRQuestionEncoderTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation
|
| 48 |
+
splitting and wordpiece.
|
| 49 |
+
|
| 50 |
+
Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
DPRSpanPrediction = collections.namedtuple(
|
| 57 |
+
"DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"]
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
DPRReaderOutput = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"])
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
CUSTOM_DPR_READER_DOCSTRING = r"""
|
| 64 |
+
Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.
|
| 65 |
+
It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),
|
| 66 |
+
using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`
|
| 67 |
+
with the format:
|
| 68 |
+
|
| 69 |
+
```
|
| 70 |
+
[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
questions (`str` or `list[str]`):
|
| 75 |
+
The questions to be encoded. You can specify one question for many passages. In this case, the question
|
| 76 |
+
will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in
|
| 77 |
+
`titles` or `texts`.
|
| 78 |
+
titles (`str` or `list[str]`):
|
| 79 |
+
The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
|
| 80 |
+
texts (`str` or `list[str]`):
|
| 81 |
+
The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
|
| 82 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
| 83 |
+
Activates and controls padding. Accepts the following values:
|
| 84 |
+
|
| 85 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
|
| 86 |
+
if provided).
|
| 87 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 88 |
+
acceptable input length for the model if that argument is not provided.
|
| 89 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 90 |
+
lengths).
|
| 91 |
+
truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
|
| 92 |
+
Activates and controls truncation. Accepts the following values:
|
| 93 |
+
|
| 94 |
+
- `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to
|
| 95 |
+
the maximum acceptable input length for the model if that argument is not provided. This will truncate
|
| 96 |
+
token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch
|
| 97 |
+
of pairs) is provided.
|
| 98 |
+
- `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
|
| 99 |
+
acceptable input length for the model if that argument is not provided. This will only truncate the first
|
| 100 |
+
sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 101 |
+
- `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
|
| 102 |
+
acceptable input length for the model if that argument is not provided. This will only truncate the
|
| 103 |
+
second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 104 |
+
- `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
|
| 105 |
+
greater than the model maximum admissible input size).
|
| 106 |
+
max_length (`int`, *optional*):
|
| 107 |
+
Controls the maximum length to use by one of the truncation/padding parameters.
|
| 108 |
+
|
| 109 |
+
If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
|
| 110 |
+
is required by one of the truncation/padding parameters. If the model has no specific maximum input
|
| 111 |
+
length (like XLNet) truncation/padding to a maximum length will be deactivated.
|
| 112 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 113 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 114 |
+
|
| 115 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 116 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 117 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 118 |
+
return_attention_mask (`bool`, *optional*):
|
| 119 |
+
Whether or not to return the attention mask. If not set, will return the attention mask according to the
|
| 120 |
+
specific tokenizer's default, defined by the `return_outputs` attribute.
|
| 121 |
+
|
| 122 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 123 |
+
|
| 124 |
+
Returns:
|
| 125 |
+
`dict[str, list[list[int]]]`: A dictionary with the following keys:
|
| 126 |
+
|
| 127 |
+
- `input_ids`: List of token ids to be fed to a model.
|
| 128 |
+
- `attention_mask`: List of indices specifying which tokens should be attended to by the model.
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@add_start_docstrings(CUSTOM_DPR_READER_DOCSTRING)
|
| 133 |
+
class CustomDPRReaderTokenizerMixin:
|
| 134 |
+
def __call__(
|
| 135 |
+
self,
|
| 136 |
+
questions,
|
| 137 |
+
titles: Optional[str] = None,
|
| 138 |
+
texts: Optional[str] = None,
|
| 139 |
+
padding: Union[bool, str] = False,
|
| 140 |
+
truncation: Union[bool, str] = False,
|
| 141 |
+
max_length: Optional[int] = None,
|
| 142 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 143 |
+
return_attention_mask: Optional[bool] = None,
|
| 144 |
+
**kwargs,
|
| 145 |
+
) -> BatchEncoding:
|
| 146 |
+
if titles is None and texts is None:
|
| 147 |
+
return super().__call__(
|
| 148 |
+
questions,
|
| 149 |
+
padding=padding,
|
| 150 |
+
truncation=truncation,
|
| 151 |
+
max_length=max_length,
|
| 152 |
+
return_tensors=return_tensors,
|
| 153 |
+
return_attention_mask=return_attention_mask,
|
| 154 |
+
**kwargs,
|
| 155 |
+
)
|
| 156 |
+
elif titles is None or texts is None:
|
| 157 |
+
text_pair = titles if texts is None else texts
|
| 158 |
+
return super().__call__(
|
| 159 |
+
questions,
|
| 160 |
+
text_pair,
|
| 161 |
+
padding=padding,
|
| 162 |
+
truncation=truncation,
|
| 163 |
+
max_length=max_length,
|
| 164 |
+
return_tensors=return_tensors,
|
| 165 |
+
return_attention_mask=return_attention_mask,
|
| 166 |
+
**kwargs,
|
| 167 |
+
)
|
| 168 |
+
titles = titles if not isinstance(titles, str) else [titles]
|
| 169 |
+
texts = texts if not isinstance(texts, str) else [texts]
|
| 170 |
+
n_passages = len(titles)
|
| 171 |
+
questions = questions if not isinstance(questions, str) else [questions] * n_passages
|
| 172 |
+
if len(titles) != len(texts):
|
| 173 |
+
raise ValueError(
|
| 174 |
+
f"There should be as many titles than texts but got {len(titles)} titles and {len(texts)} texts."
|
| 175 |
+
)
|
| 176 |
+
encoded_question_and_titles = super().__call__(questions, titles, padding=False, truncation=False)["input_ids"]
|
| 177 |
+
encoded_texts = super().__call__(texts, add_special_tokens=False, padding=False, truncation=False)["input_ids"]
|
| 178 |
+
encoded_inputs = {
|
| 179 |
+
"input_ids": [
|
| 180 |
+
(encoded_question_and_title + encoded_text)[:max_length]
|
| 181 |
+
if max_length is not None and truncation
|
| 182 |
+
else encoded_question_and_title + encoded_text
|
| 183 |
+
for encoded_question_and_title, encoded_text in zip(encoded_question_and_titles, encoded_texts)
|
| 184 |
+
]
|
| 185 |
+
}
|
| 186 |
+
if return_attention_mask is not False:
|
| 187 |
+
attention_mask = []
|
| 188 |
+
for input_ids in encoded_inputs["input_ids"]:
|
| 189 |
+
attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids])
|
| 190 |
+
encoded_inputs["attention_mask"] = attention_mask
|
| 191 |
+
return self.pad(encoded_inputs, padding=padding, max_length=max_length, return_tensors=return_tensors)
|
| 192 |
+
|
| 193 |
+
def decode_best_spans(
|
| 194 |
+
self,
|
| 195 |
+
reader_input: BatchEncoding,
|
| 196 |
+
reader_output: DPRReaderOutput,
|
| 197 |
+
num_spans: int = 16,
|
| 198 |
+
max_answer_length: int = 64,
|
| 199 |
+
num_spans_per_passage: int = 4,
|
| 200 |
+
) -> list[DPRSpanPrediction]:
|
| 201 |
+
"""
|
| 202 |
+
Get the span predictions for the extractive Q&A model.
|
| 203 |
+
|
| 204 |
+
Returns: *List* of *DPRReaderOutput* sorted by descending *(relevance_score, span_score)*. Each
|
| 205 |
+
*DPRReaderOutput* is a *Tuple* with:
|
| 206 |
+
|
| 207 |
+
- **span_score**: `float` that corresponds to the score given by the reader for this span compared to other
|
| 208 |
+
spans in the same passage. It corresponds to the sum of the start and end logits of the span.
|
| 209 |
+
- **relevance_score**: `float` that corresponds to the score of the each passage to answer the question,
|
| 210 |
+
compared to all the other passages. It corresponds to the output of the QA classifier of the DPRReader.
|
| 211 |
+
- **doc_id**: `int` the id of the passage. - **start_index**: `int` the start index of the span
|
| 212 |
+
(inclusive). - **end_index**: `int` the end index of the span (inclusive).
|
| 213 |
+
|
| 214 |
+
Examples:
|
| 215 |
+
|
| 216 |
+
```python
|
| 217 |
+
>>> from transformers import DPRReader, DPRReaderTokenizer
|
| 218 |
+
|
| 219 |
+
>>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 220 |
+
>>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 221 |
+
>>> encoded_inputs = tokenizer(
|
| 222 |
+
... questions=["What is love ?"],
|
| 223 |
+
... titles=["Haddaway"],
|
| 224 |
+
... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
|
| 225 |
+
... return_tensors="pt",
|
| 226 |
+
... )
|
| 227 |
+
>>> outputs = model(**encoded_inputs)
|
| 228 |
+
>>> predicted_spans = tokenizer.decode_best_spans(encoded_inputs, outputs)
|
| 229 |
+
>>> print(predicted_spans[0].text) # best span
|
| 230 |
+
a song
|
| 231 |
+
```"""
|
| 232 |
+
input_ids = reader_input["input_ids"]
|
| 233 |
+
start_logits, end_logits, relevance_logits = reader_output[:3]
|
| 234 |
+
n_passages = len(relevance_logits)
|
| 235 |
+
sorted_docs = sorted(range(n_passages), reverse=True, key=relevance_logits.__getitem__)
|
| 236 |
+
nbest_spans_predictions: list[DPRReaderOutput] = []
|
| 237 |
+
for doc_id in sorted_docs:
|
| 238 |
+
sequence_ids = list(input_ids[doc_id])
|
| 239 |
+
# assuming question & title information is at the beginning of the sequence
|
| 240 |
+
passage_offset = sequence_ids.index(self.sep_token_id, 2) + 1 # second sep id
|
| 241 |
+
if sequence_ids[-1] == self.pad_token_id:
|
| 242 |
+
sequence_len = sequence_ids.index(self.pad_token_id)
|
| 243 |
+
else:
|
| 244 |
+
sequence_len = len(sequence_ids)
|
| 245 |
+
|
| 246 |
+
best_spans = self._get_best_spans(
|
| 247 |
+
start_logits=start_logits[doc_id][passage_offset:sequence_len],
|
| 248 |
+
end_logits=end_logits[doc_id][passage_offset:sequence_len],
|
| 249 |
+
max_answer_length=max_answer_length,
|
| 250 |
+
top_spans=num_spans_per_passage,
|
| 251 |
+
)
|
| 252 |
+
for start_index, end_index in best_spans:
|
| 253 |
+
start_index += passage_offset
|
| 254 |
+
end_index += passage_offset
|
| 255 |
+
nbest_spans_predictions.append(
|
| 256 |
+
DPRSpanPrediction(
|
| 257 |
+
span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index],
|
| 258 |
+
relevance_score=relevance_logits[doc_id],
|
| 259 |
+
doc_id=doc_id,
|
| 260 |
+
start_index=start_index,
|
| 261 |
+
end_index=end_index,
|
| 262 |
+
text=self.decode(sequence_ids[start_index : end_index + 1]),
|
| 263 |
+
)
|
| 264 |
+
)
|
| 265 |
+
if len(nbest_spans_predictions) >= num_spans:
|
| 266 |
+
break
|
| 267 |
+
return nbest_spans_predictions[:num_spans]
|
| 268 |
+
|
| 269 |
+
def _get_best_spans(
|
| 270 |
+
self,
|
| 271 |
+
start_logits: list[int],
|
| 272 |
+
end_logits: list[int],
|
| 273 |
+
max_answer_length: int,
|
| 274 |
+
top_spans: int,
|
| 275 |
+
) -> list[DPRSpanPrediction]:
|
| 276 |
+
"""
|
| 277 |
+
Finds the best answer span for the extractive Q&A model for one passage. It returns the best span by descending
|
| 278 |
+
`span_score` order and keeping max `top_spans` spans. Spans longer that `max_answer_length` are ignored.
|
| 279 |
+
"""
|
| 280 |
+
scores = []
|
| 281 |
+
for start_index, start_score in enumerate(start_logits):
|
| 282 |
+
for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]):
|
| 283 |
+
scores.append(((start_index, start_index + answer_length), start_score + end_score))
|
| 284 |
+
scores = sorted(scores, key=lambda x: x[1], reverse=True)
|
| 285 |
+
chosen_span_intervals = []
|
| 286 |
+
for (start_index, end_index), score in scores:
|
| 287 |
+
if start_index > end_index:
|
| 288 |
+
raise ValueError(f"Wrong span indices: [{start_index}:{end_index}]")
|
| 289 |
+
length = end_index - start_index + 1
|
| 290 |
+
if length > max_answer_length:
|
| 291 |
+
raise ValueError(f"Span is too long: {length} > {max_answer_length}")
|
| 292 |
+
if any(
|
| 293 |
+
start_index <= prev_start_index <= prev_end_index <= end_index
|
| 294 |
+
or prev_start_index <= start_index <= end_index <= prev_end_index
|
| 295 |
+
for (prev_start_index, prev_end_index) in chosen_span_intervals
|
| 296 |
+
):
|
| 297 |
+
continue
|
| 298 |
+
chosen_span_intervals.append((start_index, end_index))
|
| 299 |
+
|
| 300 |
+
if len(chosen_span_intervals) == top_spans:
|
| 301 |
+
break
|
| 302 |
+
return chosen_span_intervals
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
@add_end_docstrings(CUSTOM_DPR_READER_DOCSTRING)
|
| 306 |
+
class DPRReaderTokenizer(CustomDPRReaderTokenizerMixin, BertTokenizer):
|
| 307 |
+
r"""
|
| 308 |
+
Construct a DPRReader tokenizer.
|
| 309 |
+
|
| 310 |
+
[`DPRReaderTokenizer`] is almost identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation
|
| 311 |
+
splitting and wordpiece. The difference is that is has three inputs strings: question, titles and texts that are
|
| 312 |
+
combined to be fed to the [`DPRReader`] model.
|
| 313 |
+
|
| 314 |
+
Refer to superclass [`BertTokenizer`] for usage examples and documentation concerning parameters.
|
| 315 |
+
"""
|
| 316 |
+
|
| 317 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 318 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
__all__ = ["DPRContextEncoderTokenizer", "DPRQuestionEncoderTokenizer", "DPRReaderOutput", "DPRReaderTokenizer"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/dpr/tokenization_dpr_fast.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team, The Hugging Face 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 DPR."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
from typing import Optional, Union
|
| 19 |
+
|
| 20 |
+
from ...tokenization_utils_base import BatchEncoding
|
| 21 |
+
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
|
| 22 |
+
from ..bert.tokenization_bert_fast import BertTokenizerFast
|
| 23 |
+
from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class DPRContextEncoderTokenizerFast(BertTokenizerFast):
|
| 32 |
+
r"""
|
| 33 |
+
Construct a "fast" DPRContextEncoder tokenizer (backed by HuggingFace's *tokenizers* library).
|
| 34 |
+
|
| 35 |
+
[`DPRContextEncoderTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization:
|
| 36 |
+
punctuation splitting and wordpiece.
|
| 37 |
+
|
| 38 |
+
Refer to superclass [`BertTokenizerFast`] for usage examples and documentation concerning parameters.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 42 |
+
slow_tokenizer_class = DPRContextEncoderTokenizer
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class DPRQuestionEncoderTokenizerFast(BertTokenizerFast):
|
| 46 |
+
r"""
|
| 47 |
+
Constructs a "fast" DPRQuestionEncoder tokenizer (backed by HuggingFace's *tokenizers* library).
|
| 48 |
+
|
| 49 |
+
[`DPRQuestionEncoderTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization:
|
| 50 |
+
punctuation splitting and wordpiece.
|
| 51 |
+
|
| 52 |
+
Refer to superclass [`BertTokenizerFast`] for usage examples and documentation concerning parameters.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 56 |
+
slow_tokenizer_class = DPRQuestionEncoderTokenizer
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
DPRSpanPrediction = collections.namedtuple(
|
| 60 |
+
"DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"]
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
DPRReaderOutput = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
CUSTOM_DPR_READER_DOCSTRING = r"""
|
| 67 |
+
Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.
|
| 68 |
+
It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),
|
| 69 |
+
using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`
|
| 70 |
+
with the format:
|
| 71 |
+
|
| 72 |
+
[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
questions (`str` or `list[str]`):
|
| 76 |
+
The questions to be encoded. You can specify one question for many passages. In this case, the question
|
| 77 |
+
will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in
|
| 78 |
+
`titles` or `texts`.
|
| 79 |
+
titles (`str` or `list[str]`):
|
| 80 |
+
The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
|
| 81 |
+
texts (`str` or `list[str]`):
|
| 82 |
+
The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
|
| 83 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
|
| 84 |
+
Activates and controls padding. Accepts the following values:
|
| 85 |
+
|
| 86 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
|
| 87 |
+
if provided).
|
| 88 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 89 |
+
acceptable input length for the model if that argument is not provided.
|
| 90 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 91 |
+
lengths).
|
| 92 |
+
truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
|
| 93 |
+
Activates and controls truncation. Accepts the following values:
|
| 94 |
+
|
| 95 |
+
- `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to
|
| 96 |
+
the maximum acceptable input length for the model if that argument is not provided. This will truncate
|
| 97 |
+
token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch
|
| 98 |
+
of pairs) is provided.
|
| 99 |
+
- `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
|
| 100 |
+
acceptable input length for the model if that argument is not provided. This will only truncate the first
|
| 101 |
+
sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 102 |
+
- `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
|
| 103 |
+
acceptable input length for the model if that argument is not provided. This will only truncate the
|
| 104 |
+
second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 105 |
+
- `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
|
| 106 |
+
greater than the model maximum admissible input size).
|
| 107 |
+
max_length (`int`, *optional*):
|
| 108 |
+
Controls the maximum length to use by one of the truncation/padding parameters.
|
| 109 |
+
|
| 110 |
+
If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
|
| 111 |
+
is required by one of the truncation/padding parameters. If the model has no specific maximum input
|
| 112 |
+
length (like XLNet) truncation/padding to a maximum length will be deactivated.
|
| 113 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 114 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 115 |
+
|
| 116 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 117 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 118 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 119 |
+
return_attention_mask (`bool`, *optional*):
|
| 120 |
+
Whether or not to return the attention mask. If not set, will return the attention mask according to the
|
| 121 |
+
specific tokenizer's default, defined by the `return_outputs` attribute.
|
| 122 |
+
|
| 123 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 124 |
+
|
| 125 |
+
Return:
|
| 126 |
+
`dict[str, list[list[int]]]`: A dictionary with the following keys:
|
| 127 |
+
|
| 128 |
+
- `input_ids`: List of token ids to be fed to a model.
|
| 129 |
+
- `attention_mask`: List of indices specifying which tokens should be attended to by the model.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@add_start_docstrings(CUSTOM_DPR_READER_DOCSTRING)
|
| 134 |
+
class CustomDPRReaderTokenizerMixin:
|
| 135 |
+
def __call__(
|
| 136 |
+
self,
|
| 137 |
+
questions,
|
| 138 |
+
titles: Optional[str] = None,
|
| 139 |
+
texts: Optional[str] = None,
|
| 140 |
+
padding: Union[bool, str] = False,
|
| 141 |
+
truncation: Union[bool, str] = False,
|
| 142 |
+
max_length: Optional[int] = None,
|
| 143 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 144 |
+
return_attention_mask: Optional[bool] = None,
|
| 145 |
+
**kwargs,
|
| 146 |
+
) -> BatchEncoding:
|
| 147 |
+
if titles is None and texts is None:
|
| 148 |
+
return super().__call__(
|
| 149 |
+
questions,
|
| 150 |
+
padding=padding,
|
| 151 |
+
truncation=truncation,
|
| 152 |
+
max_length=max_length,
|
| 153 |
+
return_tensors=return_tensors,
|
| 154 |
+
return_attention_mask=return_attention_mask,
|
| 155 |
+
**kwargs,
|
| 156 |
+
)
|
| 157 |
+
elif titles is None or texts is None:
|
| 158 |
+
text_pair = titles if texts is None else texts
|
| 159 |
+
return super().__call__(
|
| 160 |
+
questions,
|
| 161 |
+
text_pair,
|
| 162 |
+
padding=padding,
|
| 163 |
+
truncation=truncation,
|
| 164 |
+
max_length=max_length,
|
| 165 |
+
return_tensors=return_tensors,
|
| 166 |
+
return_attention_mask=return_attention_mask,
|
| 167 |
+
**kwargs,
|
| 168 |
+
)
|
| 169 |
+
titles = titles if not isinstance(titles, str) else [titles]
|
| 170 |
+
texts = texts if not isinstance(texts, str) else [texts]
|
| 171 |
+
n_passages = len(titles)
|
| 172 |
+
questions = questions if not isinstance(questions, str) else [questions] * n_passages
|
| 173 |
+
assert len(titles) == len(texts), (
|
| 174 |
+
f"There should be as many titles than texts but got {len(titles)} titles and {len(texts)} texts."
|
| 175 |
+
)
|
| 176 |
+
encoded_question_and_titles = super().__call__(questions, titles, padding=False, truncation=False)["input_ids"]
|
| 177 |
+
encoded_texts = super().__call__(texts, add_special_tokens=False, padding=False, truncation=False)["input_ids"]
|
| 178 |
+
encoded_inputs = {
|
| 179 |
+
"input_ids": [
|
| 180 |
+
(encoded_question_and_title + encoded_text)[:max_length]
|
| 181 |
+
if max_length is not None and truncation
|
| 182 |
+
else encoded_question_and_title + encoded_text
|
| 183 |
+
for encoded_question_and_title, encoded_text in zip(encoded_question_and_titles, encoded_texts)
|
| 184 |
+
]
|
| 185 |
+
}
|
| 186 |
+
if return_attention_mask is not False:
|
| 187 |
+
attention_mask = []
|
| 188 |
+
for input_ids in encoded_inputs["input_ids"]:
|
| 189 |
+
attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids])
|
| 190 |
+
encoded_inputs["attention_mask"] = attention_mask
|
| 191 |
+
return self.pad(encoded_inputs, padding=padding, max_length=max_length, return_tensors=return_tensors)
|
| 192 |
+
|
| 193 |
+
def decode_best_spans(
|
| 194 |
+
self,
|
| 195 |
+
reader_input: BatchEncoding,
|
| 196 |
+
reader_output: DPRReaderOutput,
|
| 197 |
+
num_spans: int = 16,
|
| 198 |
+
max_answer_length: int = 64,
|
| 199 |
+
num_spans_per_passage: int = 4,
|
| 200 |
+
) -> list[DPRSpanPrediction]:
|
| 201 |
+
"""
|
| 202 |
+
Get the span predictions for the extractive Q&A model.
|
| 203 |
+
|
| 204 |
+
Returns: *List* of *DPRReaderOutput* sorted by descending *(relevance_score, span_score)*. Each
|
| 205 |
+
*DPRReaderOutput* is a *Tuple* with:
|
| 206 |
+
|
| 207 |
+
- **span_score**: `float` that corresponds to the score given by the reader for this span compared to other
|
| 208 |
+
spans in the same passage. It corresponds to the sum of the start and end logits of the span.
|
| 209 |
+
- **relevance_score**: `float` that corresponds to the score of the each passage to answer the question,
|
| 210 |
+
compared to all the other passages. It corresponds to the output of the QA classifier of the DPRReader.
|
| 211 |
+
- **doc_id**: `int` the id of the passage. - ***start_index**: `int` the start index of the span
|
| 212 |
+
(inclusive). - **end_index**: `int` the end index of the span (inclusive).
|
| 213 |
+
|
| 214 |
+
Examples:
|
| 215 |
+
|
| 216 |
+
```python
|
| 217 |
+
>>> from transformers import DPRReader, DPRReaderTokenizer
|
| 218 |
+
|
| 219 |
+
>>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 220 |
+
>>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 221 |
+
>>> encoded_inputs = tokenizer(
|
| 222 |
+
... questions=["What is love ?"],
|
| 223 |
+
... titles=["Haddaway"],
|
| 224 |
+
... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
|
| 225 |
+
... return_tensors="pt",
|
| 226 |
+
... )
|
| 227 |
+
>>> outputs = model(**encoded_inputs)
|
| 228 |
+
>>> predicted_spans = tokenizer.decode_best_spans(encoded_inputs, outputs)
|
| 229 |
+
>>> print(predicted_spans[0].text) # best span
|
| 230 |
+
a song
|
| 231 |
+
```"""
|
| 232 |
+
input_ids = reader_input["input_ids"]
|
| 233 |
+
start_logits, end_logits, relevance_logits = reader_output[:3]
|
| 234 |
+
n_passages = len(relevance_logits)
|
| 235 |
+
sorted_docs = sorted(range(n_passages), reverse=True, key=relevance_logits.__getitem__)
|
| 236 |
+
nbest_spans_predictions: list[DPRReaderOutput] = []
|
| 237 |
+
for doc_id in sorted_docs:
|
| 238 |
+
sequence_ids = list(input_ids[doc_id])
|
| 239 |
+
# assuming question & title information is at the beginning of the sequence
|
| 240 |
+
passage_offset = sequence_ids.index(self.sep_token_id, 2) + 1 # second sep id
|
| 241 |
+
if sequence_ids[-1] == self.pad_token_id:
|
| 242 |
+
sequence_len = sequence_ids.index(self.pad_token_id)
|
| 243 |
+
else:
|
| 244 |
+
sequence_len = len(sequence_ids)
|
| 245 |
+
|
| 246 |
+
best_spans = self._get_best_spans(
|
| 247 |
+
start_logits=start_logits[doc_id][passage_offset:sequence_len],
|
| 248 |
+
end_logits=end_logits[doc_id][passage_offset:sequence_len],
|
| 249 |
+
max_answer_length=max_answer_length,
|
| 250 |
+
top_spans=num_spans_per_passage,
|
| 251 |
+
)
|
| 252 |
+
for start_index, end_index in best_spans:
|
| 253 |
+
start_index += passage_offset
|
| 254 |
+
end_index += passage_offset
|
| 255 |
+
nbest_spans_predictions.append(
|
| 256 |
+
DPRSpanPrediction(
|
| 257 |
+
span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index],
|
| 258 |
+
relevance_score=relevance_logits[doc_id],
|
| 259 |
+
doc_id=doc_id,
|
| 260 |
+
start_index=start_index,
|
| 261 |
+
end_index=end_index,
|
| 262 |
+
text=self.decode(sequence_ids[start_index : end_index + 1]),
|
| 263 |
+
)
|
| 264 |
+
)
|
| 265 |
+
if len(nbest_spans_predictions) >= num_spans:
|
| 266 |
+
break
|
| 267 |
+
return nbest_spans_predictions[:num_spans]
|
| 268 |
+
|
| 269 |
+
def _get_best_spans(
|
| 270 |
+
self,
|
| 271 |
+
start_logits: list[int],
|
| 272 |
+
end_logits: list[int],
|
| 273 |
+
max_answer_length: int,
|
| 274 |
+
top_spans: int,
|
| 275 |
+
) -> list[DPRSpanPrediction]:
|
| 276 |
+
"""
|
| 277 |
+
Finds the best answer span for the extractive Q&A model for one passage. It returns the best span by descending
|
| 278 |
+
`span_score` order and keeping max `top_spans` spans. Spans longer that `max_answer_length` are ignored.
|
| 279 |
+
"""
|
| 280 |
+
scores = []
|
| 281 |
+
for start_index, start_score in enumerate(start_logits):
|
| 282 |
+
for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]):
|
| 283 |
+
scores.append(((start_index, start_index + answer_length), start_score + end_score))
|
| 284 |
+
scores = sorted(scores, key=lambda x: x[1], reverse=True)
|
| 285 |
+
chosen_span_intervals = []
|
| 286 |
+
for (start_index, end_index), score in scores:
|
| 287 |
+
assert start_index <= end_index, f"Wrong span indices: [{start_index}:{end_index}]"
|
| 288 |
+
length = end_index - start_index + 1
|
| 289 |
+
assert length <= max_answer_length, f"Span is too long: {length} > {max_answer_length}"
|
| 290 |
+
if any(
|
| 291 |
+
start_index <= prev_start_index <= prev_end_index <= end_index
|
| 292 |
+
or prev_start_index <= start_index <= end_index <= prev_end_index
|
| 293 |
+
for (prev_start_index, prev_end_index) in chosen_span_intervals
|
| 294 |
+
):
|
| 295 |
+
continue
|
| 296 |
+
chosen_span_intervals.append((start_index, end_index))
|
| 297 |
+
|
| 298 |
+
if len(chosen_span_intervals) == top_spans:
|
| 299 |
+
break
|
| 300 |
+
return chosen_span_intervals
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
@add_end_docstrings(CUSTOM_DPR_READER_DOCSTRING)
|
| 304 |
+
class DPRReaderTokenizerFast(CustomDPRReaderTokenizerMixin, BertTokenizerFast):
|
| 305 |
+
r"""
|
| 306 |
+
Constructs a "fast" DPRReader tokenizer (backed by HuggingFace's *tokenizers* library).
|
| 307 |
+
|
| 308 |
+
[`DPRReaderTokenizerFast`] is almost identical to [`BertTokenizerFast`] and runs end-to-end tokenization:
|
| 309 |
+
punctuation splitting and wordpiece. The difference is that is has three inputs strings: question, titles and texts
|
| 310 |
+
that are combined to be fed to the [`DPRReader`] model.
|
| 311 |
+
|
| 312 |
+
Refer to superclass [`BertTokenizerFast`] for usage examples and documentation concerning parameters.
|
| 313 |
+
|
| 314 |
+
"""
|
| 315 |
+
|
| 316 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 317 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 318 |
+
slow_tokenizer_class = DPRReaderTokenizer
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
__all__ = ["DPRContextEncoderTokenizerFast", "DPRQuestionEncoderTokenizerFast", "DPRReaderTokenizerFast"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm4_moe/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_glm4_moe import *
|
| 22 |
+
from .modeling_glm4_moe import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm4_moe/configuration_glm4_moe.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/glm4_moe/modular_glm4_moe.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_glm4_moe.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 The ZhipuAI Inc. team and HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
from ...configuration_utils import PretrainedConfig
|
| 23 |
+
from ...modeling_rope_utils import rope_config_validation
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Glm4MoeConfig(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`Glm4MoeModel`]. It is used to instantiate a
|
| 29 |
+
Glm4Moe model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 30 |
+
with the defaults will yield a similar configuration to that of [THUDM/GLM-4-100B-A10B](https://huggingface.co/THUDM/GLM-4-100B-A10B).
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
vocab_size (`int`, *optional*, defaults to 151552):
|
| 38 |
+
Vocabulary size of the Glm4Moe model. Defines the number of different tokens that can be represented by the
|
| 39 |
+
`inputs_ids` passed when calling [`Glm4MoeModel`]
|
| 40 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 41 |
+
Dimension of the hidden representations.
|
| 42 |
+
intermediate_size (`int`, *optional*, defaults to 10944):
|
| 43 |
+
Dimension of the MLP representations.
|
| 44 |
+
num_hidden_layers (`int`, *optional*, defaults to 46):
|
| 45 |
+
Number of hidden layers in the Transformer encoder.
|
| 46 |
+
num_attention_heads (`int`, *optional*, defaults to 96):
|
| 47 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 48 |
+
partial_rotary_factor (`float`, *optional*, defaults to 0.5):
|
| 49 |
+
The factor of the partial rotary position.
|
| 50 |
+
num_key_value_heads (`int`, *optional*, defaults to 8):
|
| 51 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 52 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 53 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 54 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 55 |
+
by meanpooling all the original heads within that group. For more details, check out [this
|
| 56 |
+
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
|
| 57 |
+
|
| 58 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 59 |
+
The non-linear activation function (function or string) in the decoder.
|
| 60 |
+
max_position_embeddings (`int`, *optional*, defaults to 131072):
|
| 61 |
+
The maximum sequence length that this model might ever be used with.
|
| 62 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 63 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 64 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 65 |
+
The epsilon used by the rms normalization layers.
|
| 66 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 68 |
+
relevant if `config.is_decoder=True`.
|
| 69 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 70 |
+
Whether the model's input and output word embeddings should be tied.
|
| 71 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 72 |
+
The base period of the RoPE embeddings.
|
| 73 |
+
rope_scaling (`Dict`, *optional*):
|
| 74 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
| 75 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
| 76 |
+
accordingly.
|
| 77 |
+
Expected contents:
|
| 78 |
+
`rope_type` (`str`):
|
| 79 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
| 80 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
| 81 |
+
`factor` (`float`, *optional*):
|
| 82 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
| 83 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
| 84 |
+
original maximum pre-trained length.
|
| 85 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
| 86 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
| 87 |
+
pretraining.
|
| 88 |
+
`attention_factor` (`float`, *optional*):
|
| 89 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
| 90 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
| 91 |
+
`factor` field to infer the suggested value.
|
| 92 |
+
`beta_fast` (`float`, *optional*):
|
| 93 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
| 94 |
+
ramp function. If unspecified, it defaults to 32.
|
| 95 |
+
`beta_slow` (`float`, *optional*):
|
| 96 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
| 97 |
+
ramp function. If unspecified, it defaults to 1.
|
| 98 |
+
`short_factor` (`list[float]`, *optional*):
|
| 99 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
| 100 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 101 |
+
size divided by the number of attention heads divided by 2
|
| 102 |
+
`long_factor` (`list[float]`, *optional*):
|
| 103 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
| 104 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 105 |
+
size divided by the number of attention heads divided by 2
|
| 106 |
+
`low_freq_factor` (`float`, *optional*):
|
| 107 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
| 108 |
+
`high_freq_factor` (`float`, *optional*):
|
| 109 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
| 110 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
| 111 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
| 112 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 113 |
+
The dropout ratio for the attention probabilities.
|
| 114 |
+
moe_intermediate_size (`int`, *optional*, defaults to 1408):
|
| 115 |
+
Intermediate size of the routed expert.
|
| 116 |
+
num_experts_per_tok (`int`, *optional*, defaults to 8):
|
| 117 |
+
number of experts per token.
|
| 118 |
+
n_shared_experts (`int`, *optional*, defaults to 1):
|
| 119 |
+
Number of shared experts.
|
| 120 |
+
n_routed_experts (`int`, *optional*, defaults to 128):
|
| 121 |
+
Number of routed experts.
|
| 122 |
+
routed_scaling_factor (`float`, *optional*, defaults to 1.0):
|
| 123 |
+
Scaling factor or routed experts.
|
| 124 |
+
n_group (`int`, *optional*, defaults to 1):
|
| 125 |
+
Number of groups for routed experts.
|
| 126 |
+
topk_group (`int`, *optional*, defaults to 1):
|
| 127 |
+
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
|
| 128 |
+
first_k_dense_replace (`int`, *optional*, defaults to 1):
|
| 129 |
+
Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
|
| 130 |
+
\--k dense layers--/
|
| 131 |
+
norm_topk_prob (`bool`, *optional*, defaults to `True`):
|
| 132 |
+
Whether to normalize the topk probabilities.
|
| 133 |
+
use_qk_norm (`bool`, *optional*, defaults to `False`):
|
| 134 |
+
Whether to use query-key normalization in the attention
|
| 135 |
+
```python
|
| 136 |
+
>>> from transformers import Glm4MoeModel, Glm4MoeConfig
|
| 137 |
+
|
| 138 |
+
>>> # Initializing a Glm4Moe style configuration
|
| 139 |
+
>>> configuration = Glm4MoeConfig()
|
| 140 |
+
|
| 141 |
+
>>> # Initializing a model from the GLM-4-MOE-100B-A10B style configuration
|
| 142 |
+
>>> model = Glm4MoeModel(configuration)
|
| 143 |
+
|
| 144 |
+
>>> # Accessing the model configuration
|
| 145 |
+
>>> configuration = model.config
|
| 146 |
+
```"""
|
| 147 |
+
|
| 148 |
+
model_type = "glm4_moe"
|
| 149 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 150 |
+
|
| 151 |
+
# Default tensor parallel plan for base model `Glm4Moe`
|
| 152 |
+
base_model_tp_plan = {
|
| 153 |
+
"layers.*.self_attn.q_proj": "colwise",
|
| 154 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 155 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 156 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 157 |
+
"layers.*.mlp.experts.*.gate_proj": "colwise",
|
| 158 |
+
"layers.*.mlp.experts.*.up_proj": "colwise",
|
| 159 |
+
"layers.*.mlp.experts.*.down_proj": "rowwise",
|
| 160 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 161 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 162 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 163 |
+
}
|
| 164 |
+
base_model_pp_plan = {
|
| 165 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 166 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 167 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
def __init__(
|
| 171 |
+
self,
|
| 172 |
+
vocab_size=151552,
|
| 173 |
+
hidden_size=4096,
|
| 174 |
+
intermediate_size=10944,
|
| 175 |
+
num_hidden_layers=46,
|
| 176 |
+
num_attention_heads=96,
|
| 177 |
+
partial_rotary_factor=0.5,
|
| 178 |
+
num_key_value_heads=8,
|
| 179 |
+
hidden_act="silu",
|
| 180 |
+
max_position_embeddings=131072,
|
| 181 |
+
initializer_range=0.02,
|
| 182 |
+
rms_norm_eps=1e-5,
|
| 183 |
+
use_cache=True,
|
| 184 |
+
tie_word_embeddings=False,
|
| 185 |
+
rope_theta=10000.0,
|
| 186 |
+
rope_scaling=None,
|
| 187 |
+
attention_bias=False,
|
| 188 |
+
attention_dropout=0.0,
|
| 189 |
+
moe_intermediate_size=1408,
|
| 190 |
+
num_experts_per_tok=8,
|
| 191 |
+
n_shared_experts=1,
|
| 192 |
+
n_routed_experts=128,
|
| 193 |
+
routed_scaling_factor=1.0,
|
| 194 |
+
n_group=1,
|
| 195 |
+
topk_group=1,
|
| 196 |
+
first_k_dense_replace=1,
|
| 197 |
+
norm_topk_prob=True,
|
| 198 |
+
use_qk_norm=False,
|
| 199 |
+
**kwargs,
|
| 200 |
+
):
|
| 201 |
+
self.vocab_size = vocab_size
|
| 202 |
+
self.max_position_embeddings = max_position_embeddings
|
| 203 |
+
self.hidden_size = hidden_size
|
| 204 |
+
self.intermediate_size = intermediate_size
|
| 205 |
+
self.num_hidden_layers = num_hidden_layers
|
| 206 |
+
self.num_attention_heads = num_attention_heads
|
| 207 |
+
self.partial_rotary_factor = partial_rotary_factor
|
| 208 |
+
|
| 209 |
+
self.num_key_value_heads = num_key_value_heads
|
| 210 |
+
self.hidden_act = hidden_act
|
| 211 |
+
self.initializer_range = initializer_range
|
| 212 |
+
self.rms_norm_eps = rms_norm_eps
|
| 213 |
+
self.use_cache = use_cache
|
| 214 |
+
self.rope_theta = rope_theta
|
| 215 |
+
self.rope_scaling = rope_scaling
|
| 216 |
+
self.attention_bias = attention_bias
|
| 217 |
+
self.attention_dropout = attention_dropout
|
| 218 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 219 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
| 220 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
| 221 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
| 222 |
+
rope_config_validation(self)
|
| 223 |
+
|
| 224 |
+
# MoE arguments
|
| 225 |
+
self.moe_intermediate_size = moe_intermediate_size
|
| 226 |
+
self.num_experts_per_tok = num_experts_per_tok
|
| 227 |
+
self.n_group = n_group
|
| 228 |
+
self.topk_group = topk_group
|
| 229 |
+
self.n_shared_experts = n_shared_experts
|
| 230 |
+
self.n_routed_experts = n_routed_experts
|
| 231 |
+
self.routed_scaling_factor = routed_scaling_factor
|
| 232 |
+
self.first_k_dense_replace = first_k_dense_replace
|
| 233 |
+
self.norm_topk_prob = norm_topk_prob
|
| 234 |
+
self.use_qk_norm = use_qk_norm
|
| 235 |
+
|
| 236 |
+
super().__init__(
|
| 237 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 238 |
+
**kwargs,
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
__all__ = ["Glm4MoeConfig"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm4_moe/modeling_glm4_moe.py
ADDED
|
@@ -0,0 +1,616 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/glm4_moe/modular_glm4_moe.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_glm4_moe.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 The ZhipuAI Inc. team and HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
from typing import Callable, Optional, Union
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn.functional as F
|
| 26 |
+
from torch import nn
|
| 27 |
+
|
| 28 |
+
from ...activations import ACT2FN
|
| 29 |
+
from ...cache_utils import Cache, DynamicCache
|
| 30 |
+
from ...generation import GenerationMixin
|
| 31 |
+
from ...integrations import use_kernel_forward_from_hub
|
| 32 |
+
from ...masking_utils import create_causal_mask
|
| 33 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 34 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 35 |
+
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 36 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 37 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 38 |
+
from ...processing_utils import Unpack
|
| 39 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 40 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 41 |
+
from ...utils.generic import check_model_inputs
|
| 42 |
+
from .configuration_glm4_moe import Glm4MoeConfig
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 46 |
+
"""
|
| 47 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 48 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 49 |
+
"""
|
| 50 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 51 |
+
if n_rep == 1:
|
| 52 |
+
return hidden_states
|
| 53 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 54 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def eager_attention_forward(
|
| 58 |
+
module: nn.Module,
|
| 59 |
+
query: torch.Tensor,
|
| 60 |
+
key: torch.Tensor,
|
| 61 |
+
value: torch.Tensor,
|
| 62 |
+
attention_mask: Optional[torch.Tensor],
|
| 63 |
+
scaling: float,
|
| 64 |
+
dropout: float = 0.0,
|
| 65 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 66 |
+
):
|
| 67 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 68 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 69 |
+
|
| 70 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 71 |
+
if attention_mask is not None:
|
| 72 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 73 |
+
attn_weights = attn_weights + causal_mask
|
| 74 |
+
|
| 75 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 76 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 77 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 78 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 79 |
+
|
| 80 |
+
return attn_output, attn_weights
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def rotate_half(x):
|
| 84 |
+
"""Rotates half the hidden dims of the input."""
|
| 85 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 86 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 87 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 91 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
q (`torch.Tensor`): The query tensor.
|
| 95 |
+
k (`torch.Tensor`): The key tensor.
|
| 96 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 97 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 98 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 99 |
+
Deprecated and unused.
|
| 100 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 101 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 102 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 103 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 104 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 105 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 106 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 107 |
+
Returns:
|
| 108 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 109 |
+
"""
|
| 110 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 111 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 112 |
+
|
| 113 |
+
# Keep half or full tensor for later concatenation
|
| 114 |
+
rotary_dim = cos.shape[-1]
|
| 115 |
+
q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
|
| 116 |
+
k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
|
| 117 |
+
|
| 118 |
+
# Apply rotary embeddings on the first half or full tensor
|
| 119 |
+
q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
|
| 120 |
+
k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
|
| 121 |
+
|
| 122 |
+
# Concatenate back to full shape
|
| 123 |
+
q_embed = torch.cat([q_embed, q_pass], dim=-1)
|
| 124 |
+
k_embed = torch.cat([k_embed, k_pass], dim=-1)
|
| 125 |
+
return q_embed, k_embed
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class Glm4MoeAttention(nn.Module):
|
| 129 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 130 |
+
|
| 131 |
+
def __init__(self, config: Glm4MoeConfig, layer_idx: Optional[int] = None):
|
| 132 |
+
super().__init__()
|
| 133 |
+
self.config = config
|
| 134 |
+
self.layer_idx = layer_idx
|
| 135 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 136 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 137 |
+
self.scaling = self.head_dim**-0.5
|
| 138 |
+
self.rope_scaling = config.rope_scaling
|
| 139 |
+
self.attention_dropout = config.attention_dropout
|
| 140 |
+
self.is_causal = True
|
| 141 |
+
|
| 142 |
+
self.q_proj = nn.Linear(
|
| 143 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 144 |
+
)
|
| 145 |
+
self.k_proj = nn.Linear(
|
| 146 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 147 |
+
)
|
| 148 |
+
self.v_proj = nn.Linear(
|
| 149 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 150 |
+
)
|
| 151 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 152 |
+
self.use_qk_norm = config.use_qk_norm
|
| 153 |
+
if self.use_qk_norm:
|
| 154 |
+
self.q_norm = Glm4MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 155 |
+
self.k_norm = Glm4MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 156 |
+
|
| 157 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 158 |
+
def forward(
|
| 159 |
+
self,
|
| 160 |
+
hidden_states: torch.Tensor,
|
| 161 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 162 |
+
attention_mask: Optional[torch.Tensor],
|
| 163 |
+
past_key_values: Optional[Cache] = None,
|
| 164 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 165 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 166 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 167 |
+
input_shape = hidden_states.shape[:-1]
|
| 168 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 169 |
+
|
| 170 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape)
|
| 171 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape)
|
| 172 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape)
|
| 173 |
+
|
| 174 |
+
if self.use_qk_norm: # main diff from Llama
|
| 175 |
+
query_states = self.q_norm(query_states)
|
| 176 |
+
key_states = self.k_norm(key_states)
|
| 177 |
+
|
| 178 |
+
query_states = query_states.transpose(1, 2)
|
| 179 |
+
key_states = key_states.transpose(1, 2)
|
| 180 |
+
value_states = value_states.transpose(1, 2)
|
| 181 |
+
|
| 182 |
+
cos, sin = position_embeddings
|
| 183 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 184 |
+
|
| 185 |
+
if past_key_values is not None:
|
| 186 |
+
# sin and cos are specific to RoPE models; position_ids needed for the static cache
|
| 187 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 188 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 189 |
+
|
| 190 |
+
attention_interface: Callable = eager_attention_forward
|
| 191 |
+
if self.config._attn_implementation != "eager":
|
| 192 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 193 |
+
|
| 194 |
+
attn_output, attn_weights = attention_interface(
|
| 195 |
+
self,
|
| 196 |
+
query_states,
|
| 197 |
+
key_states,
|
| 198 |
+
value_states,
|
| 199 |
+
attention_mask,
|
| 200 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 201 |
+
scaling=self.scaling,
|
| 202 |
+
**kwargs,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 206 |
+
attn_output = self.o_proj(attn_output)
|
| 207 |
+
return attn_output, attn_weights
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class Glm4MoeMLP(nn.Module):
|
| 211 |
+
def __init__(self, config, hidden_size=None, intermediate_size=None):
|
| 212 |
+
super().__init__()
|
| 213 |
+
self.config = config
|
| 214 |
+
self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
|
| 215 |
+
self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
|
| 216 |
+
|
| 217 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 218 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 219 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 220 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 221 |
+
|
| 222 |
+
def forward(self, x):
|
| 223 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 224 |
+
return down_proj
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class Glm4MoeTopkRouter(nn.Module):
|
| 228 |
+
def __init__(self, config: Glm4MoeConfig):
|
| 229 |
+
super().__init__()
|
| 230 |
+
self.config = config
|
| 231 |
+
self.top_k = config.num_experts_per_tok
|
| 232 |
+
self.n_routed_experts = config.n_routed_experts
|
| 233 |
+
self.routed_scaling_factor = config.routed_scaling_factor
|
| 234 |
+
self.n_group = config.n_group
|
| 235 |
+
self.topk_group = config.topk_group
|
| 236 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 237 |
+
|
| 238 |
+
self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
|
| 239 |
+
self.register_buffer("e_score_correction_bias", torch.zeros((self.n_routed_experts), dtype=torch.float32))
|
| 240 |
+
|
| 241 |
+
@torch.no_grad()
|
| 242 |
+
def get_topk_indices(self, scores):
|
| 243 |
+
scores_for_choice = scores.view(-1, self.n_routed_experts) + self.e_score_correction_bias.unsqueeze(0)
|
| 244 |
+
group_scores = (
|
| 245 |
+
scores_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
|
| 246 |
+
.topk(2, dim=-1)[0]
|
| 247 |
+
.sum(dim=-1)
|
| 248 |
+
)
|
| 249 |
+
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
|
| 250 |
+
group_mask = torch.zeros_like(group_scores)
|
| 251 |
+
group_mask.scatter_(1, group_idx, 1)
|
| 252 |
+
score_mask = (
|
| 253 |
+
group_mask.unsqueeze(-1)
|
| 254 |
+
.expand(-1, self.n_group, self.n_routed_experts // self.n_group)
|
| 255 |
+
.reshape(-1, self.n_routed_experts)
|
| 256 |
+
)
|
| 257 |
+
scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
|
| 258 |
+
topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
|
| 259 |
+
return topk_indices
|
| 260 |
+
|
| 261 |
+
def forward(self, hidden_states):
|
| 262 |
+
hidden_states = hidden_states.view(-1, self.config.hidden_size)
|
| 263 |
+
router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
|
| 264 |
+
scores = router_logits.sigmoid()
|
| 265 |
+
topk_indices = self.get_topk_indices(scores)
|
| 266 |
+
topk_weights = scores.gather(1, topk_indices)
|
| 267 |
+
if self.norm_topk_prob:
|
| 268 |
+
denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
|
| 269 |
+
topk_weights /= denominator
|
| 270 |
+
topk_weights = topk_weights * self.routed_scaling_factor
|
| 271 |
+
return topk_indices, topk_weights
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 275 |
+
class Glm4MoeRMSNorm(nn.Module):
|
| 276 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 277 |
+
"""
|
| 278 |
+
Glm4MoeRMSNorm is equivalent to T5LayerNorm
|
| 279 |
+
"""
|
| 280 |
+
super().__init__()
|
| 281 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 282 |
+
self.variance_epsilon = eps
|
| 283 |
+
|
| 284 |
+
def forward(self, hidden_states):
|
| 285 |
+
input_dtype = hidden_states.dtype
|
| 286 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 287 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 288 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 289 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 290 |
+
|
| 291 |
+
def extra_repr(self):
|
| 292 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class Glm4MoeMoE(nn.Module):
|
| 296 |
+
"""
|
| 297 |
+
A mixed expert module containing shared experts.
|
| 298 |
+
"""
|
| 299 |
+
|
| 300 |
+
def __init__(self, config):
|
| 301 |
+
super().__init__()
|
| 302 |
+
self.config = config
|
| 303 |
+
self.experts = nn.ModuleList(
|
| 304 |
+
[
|
| 305 |
+
Glm4MoeMLP(config, intermediate_size=config.moe_intermediate_size)
|
| 306 |
+
for _ in range(config.n_routed_experts)
|
| 307 |
+
]
|
| 308 |
+
)
|
| 309 |
+
self.gate = Glm4MoeTopkRouter(config)
|
| 310 |
+
self.shared_experts = Glm4MoeMLP(
|
| 311 |
+
config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, topk_weights: torch.Tensor):
|
| 315 |
+
r"""
|
| 316 |
+
CALL FOR CONTRIBUTION! I don't have time to optimise this right now, but expert weights need to be fused
|
| 317 |
+
to not have to do a loop here (deepseek has 256 experts soooo yeah).
|
| 318 |
+
"""
|
| 319 |
+
final_hidden_states = torch.zeros_like(hidden_states, dtype=topk_weights.dtype)
|
| 320 |
+
expert_mask = torch.nn.functional.one_hot(topk_indices, num_classes=len(self.experts))
|
| 321 |
+
expert_mask = expert_mask.permute(2, 0, 1)
|
| 322 |
+
|
| 323 |
+
for expert_idx in range(len(self.experts)):
|
| 324 |
+
expert = self.experts[expert_idx]
|
| 325 |
+
mask = expert_mask[expert_idx]
|
| 326 |
+
token_indices, weight_indices = torch.where(mask)
|
| 327 |
+
|
| 328 |
+
if token_indices.numel() > 0:
|
| 329 |
+
expert_weights = topk_weights[token_indices, weight_indices]
|
| 330 |
+
expert_input = hidden_states[token_indices]
|
| 331 |
+
expert_output = expert(expert_input)
|
| 332 |
+
weighted_output = expert_output * expert_weights.unsqueeze(-1)
|
| 333 |
+
final_hidden_states.index_add_(0, token_indices, weighted_output)
|
| 334 |
+
|
| 335 |
+
# in original deepseek, the output of the experts are gathered once we leave this module
|
| 336 |
+
# thus the moe module is itelsf an IsolatedParallel module
|
| 337 |
+
# and all expert are "local" meaning we shard but we don't gather
|
| 338 |
+
return final_hidden_states.type(hidden_states.dtype)
|
| 339 |
+
|
| 340 |
+
def forward(self, hidden_states):
|
| 341 |
+
residuals = hidden_states
|
| 342 |
+
orig_shape = hidden_states.shape
|
| 343 |
+
topk_indices, topk_weights = self.gate(hidden_states)
|
| 344 |
+
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
|
| 345 |
+
hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape)
|
| 346 |
+
hidden_states = hidden_states + self.shared_experts(residuals)
|
| 347 |
+
return hidden_states
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
|
| 351 |
+
def __init__(self, config: Glm4MoeConfig, layer_idx: int):
|
| 352 |
+
super().__init__()
|
| 353 |
+
self.hidden_size = config.hidden_size
|
| 354 |
+
|
| 355 |
+
self.self_attn = Glm4MoeAttention(config=config, layer_idx=layer_idx)
|
| 356 |
+
|
| 357 |
+
if layer_idx >= config.first_k_dense_replace:
|
| 358 |
+
self.mlp = Glm4MoeMoE(config)
|
| 359 |
+
else:
|
| 360 |
+
self.mlp = Glm4MoeMLP(config)
|
| 361 |
+
|
| 362 |
+
self.input_layernorm = Glm4MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 363 |
+
self.post_attention_layernorm = Glm4MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 364 |
+
|
| 365 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 366 |
+
def forward(
|
| 367 |
+
self,
|
| 368 |
+
hidden_states: torch.Tensor,
|
| 369 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 370 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 371 |
+
past_key_values: Optional[Cache] = None,
|
| 372 |
+
use_cache: Optional[bool] = False,
|
| 373 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 374 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 375 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 376 |
+
) -> torch.Tensor:
|
| 377 |
+
residual = hidden_states
|
| 378 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 379 |
+
# Self Attention
|
| 380 |
+
hidden_states, _ = self.self_attn(
|
| 381 |
+
hidden_states=hidden_states,
|
| 382 |
+
attention_mask=attention_mask,
|
| 383 |
+
position_ids=position_ids,
|
| 384 |
+
past_key_values=past_key_values,
|
| 385 |
+
use_cache=use_cache,
|
| 386 |
+
cache_position=cache_position,
|
| 387 |
+
position_embeddings=position_embeddings,
|
| 388 |
+
**kwargs,
|
| 389 |
+
)
|
| 390 |
+
hidden_states = residual + hidden_states
|
| 391 |
+
|
| 392 |
+
# Fully Connected
|
| 393 |
+
residual = hidden_states
|
| 394 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 395 |
+
hidden_states = self.mlp(hidden_states)
|
| 396 |
+
hidden_states = residual + hidden_states
|
| 397 |
+
return hidden_states
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
@auto_docstring
|
| 401 |
+
class Glm4MoePreTrainedModel(PreTrainedModel):
|
| 402 |
+
config: Glm4MoeConfig
|
| 403 |
+
base_model_prefix = "model"
|
| 404 |
+
supports_gradient_checkpointing = True
|
| 405 |
+
_no_split_modules = ["Glm4MoeDecoderLayer"]
|
| 406 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 407 |
+
_supports_flash_attn = True
|
| 408 |
+
_supports_sdpa = True
|
| 409 |
+
_supports_flex_attn = True
|
| 410 |
+
_can_compile_fullgraph = False
|
| 411 |
+
_supports_attention_backend = True
|
| 412 |
+
_can_record_outputs = {
|
| 413 |
+
"hidden_states": Glm4MoeDecoderLayer,
|
| 414 |
+
"attentions": Glm4MoeAttention,
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
def _init_weights(self, module):
|
| 418 |
+
super()._init_weights(module)
|
| 419 |
+
if isinstance(module, Glm4MoeTopkRouter):
|
| 420 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
class Glm4MoeRotaryEmbedding(nn.Module):
|
| 424 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 425 |
+
|
| 426 |
+
def __init__(self, config: Glm4MoeConfig, device=None):
|
| 427 |
+
super().__init__()
|
| 428 |
+
# BC: "rope_type" was originally "type"
|
| 429 |
+
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
|
| 430 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 431 |
+
else:
|
| 432 |
+
self.rope_type = "default"
|
| 433 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 434 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 435 |
+
|
| 436 |
+
self.config = config
|
| 437 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 438 |
+
|
| 439 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 440 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 441 |
+
self.original_inv_freq = self.inv_freq
|
| 442 |
+
|
| 443 |
+
@torch.no_grad()
|
| 444 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 445 |
+
def forward(self, x, position_ids):
|
| 446 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 447 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 448 |
+
|
| 449 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 450 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 451 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 452 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 453 |
+
cos = emb.cos() * self.attention_scaling
|
| 454 |
+
sin = emb.sin() * self.attention_scaling
|
| 455 |
+
|
| 456 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
@auto_docstring
|
| 460 |
+
class Glm4MoeModel(Glm4MoePreTrainedModel):
|
| 461 |
+
_keys_to_ignore_on_load_unexpected = [r"model\.layers\.92.*", r"model\.layers\.46.*"]
|
| 462 |
+
|
| 463 |
+
def __init__(self, config: Glm4MoeConfig):
|
| 464 |
+
super().__init__(config)
|
| 465 |
+
self.padding_idx = config.pad_token_id
|
| 466 |
+
self.vocab_size = config.vocab_size
|
| 467 |
+
|
| 468 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 469 |
+
self.layers = nn.ModuleList(
|
| 470 |
+
[Glm4MoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 471 |
+
)
|
| 472 |
+
self.norm = Glm4MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 473 |
+
self.rotary_emb = Glm4MoeRotaryEmbedding(config=config)
|
| 474 |
+
self.gradient_checkpointing = False
|
| 475 |
+
|
| 476 |
+
# Initialize weights and apply final processing
|
| 477 |
+
self.post_init()
|
| 478 |
+
|
| 479 |
+
@check_model_inputs
|
| 480 |
+
@auto_docstring
|
| 481 |
+
def forward(
|
| 482 |
+
self,
|
| 483 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 484 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 485 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 486 |
+
past_key_values: Optional[Cache] = None,
|
| 487 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 488 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 489 |
+
use_cache: Optional[bool] = None,
|
| 490 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 491 |
+
) -> BaseModelOutputWithPast:
|
| 492 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 493 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 494 |
+
|
| 495 |
+
if inputs_embeds is None:
|
| 496 |
+
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
| 497 |
+
|
| 498 |
+
if use_cache and past_key_values is None:
|
| 499 |
+
past_key_values = DynamicCache(config=self.config)
|
| 500 |
+
|
| 501 |
+
if cache_position is None:
|
| 502 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 503 |
+
cache_position: torch.Tensor = torch.arange(
|
| 504 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
if position_ids is None:
|
| 508 |
+
position_ids = cache_position.unsqueeze(0)
|
| 509 |
+
|
| 510 |
+
causal_mask = create_causal_mask(
|
| 511 |
+
config=self.config,
|
| 512 |
+
input_embeds=inputs_embeds,
|
| 513 |
+
attention_mask=attention_mask,
|
| 514 |
+
cache_position=cache_position,
|
| 515 |
+
past_key_values=past_key_values,
|
| 516 |
+
position_ids=position_ids,
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
hidden_states = inputs_embeds
|
| 520 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 521 |
+
|
| 522 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
| 523 |
+
hidden_states = decoder_layer(
|
| 524 |
+
hidden_states,
|
| 525 |
+
attention_mask=causal_mask,
|
| 526 |
+
position_ids=position_ids,
|
| 527 |
+
past_key_values=past_key_values,
|
| 528 |
+
cache_position=cache_position,
|
| 529 |
+
position_embeddings=position_embeddings,
|
| 530 |
+
**kwargs,
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
hidden_states = self.norm(hidden_states)
|
| 534 |
+
return BaseModelOutputWithPast(
|
| 535 |
+
last_hidden_state=hidden_states,
|
| 536 |
+
past_key_values=past_key_values,
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
@auto_docstring
|
| 541 |
+
class Glm4MoeForCausalLM(Glm4MoePreTrainedModel, GenerationMixin):
|
| 542 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 543 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 544 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 545 |
+
|
| 546 |
+
def __init__(self, config):
|
| 547 |
+
super().__init__(config)
|
| 548 |
+
self.model = Glm4MoeModel(config)
|
| 549 |
+
self.vocab_size = config.vocab_size
|
| 550 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 551 |
+
|
| 552 |
+
# Initialize weights and apply final processing
|
| 553 |
+
self.post_init()
|
| 554 |
+
|
| 555 |
+
@can_return_tuple
|
| 556 |
+
@auto_docstring
|
| 557 |
+
def forward(
|
| 558 |
+
self,
|
| 559 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 560 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 561 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 562 |
+
past_key_values: Optional[Cache] = None,
|
| 563 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 564 |
+
labels: Optional[torch.LongTensor] = None,
|
| 565 |
+
use_cache: Optional[bool] = None,
|
| 566 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 567 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 568 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 569 |
+
) -> CausalLMOutputWithPast:
|
| 570 |
+
r"""
|
| 571 |
+
Example:
|
| 572 |
+
|
| 573 |
+
```python
|
| 574 |
+
>>> from transformers import AutoTokenizer, Glm4MoeForCausalLM
|
| 575 |
+
|
| 576 |
+
>>> model = Glm4MoeForCausalLM.from_pretrained("meta-glm4_moe/Glm4Moe-2-7b-hf")
|
| 577 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-glm4_moe/Glm4Moe-2-7b-hf")
|
| 578 |
+
|
| 579 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 580 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 581 |
+
|
| 582 |
+
>>> # Generate
|
| 583 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 584 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 585 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 586 |
+
```"""
|
| 587 |
+
outputs: BaseModelOutputWithPast = self.model(
|
| 588 |
+
input_ids=input_ids,
|
| 589 |
+
attention_mask=attention_mask,
|
| 590 |
+
position_ids=position_ids,
|
| 591 |
+
past_key_values=past_key_values,
|
| 592 |
+
inputs_embeds=inputs_embeds,
|
| 593 |
+
use_cache=use_cache,
|
| 594 |
+
cache_position=cache_position,
|
| 595 |
+
**kwargs,
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
hidden_states = outputs.last_hidden_state
|
| 599 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 600 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 601 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 602 |
+
|
| 603 |
+
loss = None
|
| 604 |
+
if labels is not None:
|
| 605 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 606 |
+
|
| 607 |
+
return CausalLMOutputWithPast(
|
| 608 |
+
loss=loss,
|
| 609 |
+
logits=logits,
|
| 610 |
+
past_key_values=outputs.past_key_values,
|
| 611 |
+
hidden_states=outputs.hidden_states,
|
| 612 |
+
attentions=outputs.attentions,
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
__all__ = ["Glm4MoePreTrainedModel", "Glm4MoeModel", "Glm4MoeForCausalLM"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glm4_moe/modular_glm4_moe.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The ZhipuAI Inc. team and 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 GLM-4-MOE model."""
|
| 16 |
+
|
| 17 |
+
from typing import Optional
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from torch import nn
|
| 21 |
+
|
| 22 |
+
from ...configuration_utils import PretrainedConfig
|
| 23 |
+
from ...modeling_rope_utils import rope_config_validation
|
| 24 |
+
from ...utils import logging
|
| 25 |
+
from ..cohere.modeling_cohere import CohereAttention
|
| 26 |
+
from ..deepseek_v3.modeling_deepseek_v3 import (
|
| 27 |
+
DeepseekV3DecoderLayer,
|
| 28 |
+
DeepseekV3ForCausalLM,
|
| 29 |
+
DeepseekV3MLP,
|
| 30 |
+
DeepseekV3Model,
|
| 31 |
+
DeepseekV3PreTrainedModel,
|
| 32 |
+
DeepseekV3RMSNorm,
|
| 33 |
+
DeepseekV3TopkRouter,
|
| 34 |
+
)
|
| 35 |
+
from ..gpt_neox.modeling_gpt_neox import apply_rotary_pos_emb # noqa
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
logger = logging.get_logger(__name__)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Glm4MoeConfig(PretrainedConfig):
|
| 42 |
+
r"""
|
| 43 |
+
This is the configuration class to store the configuration of a [`Glm4MoeModel`]. It is used to instantiate a
|
| 44 |
+
Glm4Moe model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 45 |
+
with the defaults will yield a similar configuration to that of [THUDM/GLM-4-100B-A10B](https://huggingface.co/THUDM/GLM-4-100B-A10B).
|
| 46 |
+
|
| 47 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 48 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
vocab_size (`int`, *optional*, defaults to 151552):
|
| 53 |
+
Vocabulary size of the Glm4Moe model. Defines the number of different tokens that can be represented by the
|
| 54 |
+
`inputs_ids` passed when calling [`Glm4MoeModel`]
|
| 55 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 56 |
+
Dimension of the hidden representations.
|
| 57 |
+
intermediate_size (`int`, *optional*, defaults to 10944):
|
| 58 |
+
Dimension of the MLP representations.
|
| 59 |
+
num_hidden_layers (`int`, *optional*, defaults to 46):
|
| 60 |
+
Number of hidden layers in the Transformer encoder.
|
| 61 |
+
num_attention_heads (`int`, *optional*, defaults to 96):
|
| 62 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 63 |
+
partial_rotary_factor (`float`, *optional*, defaults to 0.5):
|
| 64 |
+
The factor of the partial rotary position.
|
| 65 |
+
num_key_value_heads (`int`, *optional*, defaults to 8):
|
| 66 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 67 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 68 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 69 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 70 |
+
by meanpooling all the original heads within that group. For more details, check out [this
|
| 71 |
+
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
|
| 72 |
+
|
| 73 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 74 |
+
The non-linear activation function (function or string) in the decoder.
|
| 75 |
+
max_position_embeddings (`int`, *optional*, defaults to 131072):
|
| 76 |
+
The maximum sequence length that this model might ever be used with.
|
| 77 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 78 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 79 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 80 |
+
The epsilon used by the rms normalization layers.
|
| 81 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 82 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 83 |
+
relevant if `config.is_decoder=True`.
|
| 84 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 85 |
+
Whether the model's input and output word embeddings should be tied.
|
| 86 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 87 |
+
The base period of the RoPE embeddings.
|
| 88 |
+
rope_scaling (`Dict`, *optional*):
|
| 89 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
| 90 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
| 91 |
+
accordingly.
|
| 92 |
+
Expected contents:
|
| 93 |
+
`rope_type` (`str`):
|
| 94 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
| 95 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
| 96 |
+
`factor` (`float`, *optional*):
|
| 97 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
| 98 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
| 99 |
+
original maximum pre-trained length.
|
| 100 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
| 101 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
| 102 |
+
pretraining.
|
| 103 |
+
`attention_factor` (`float`, *optional*):
|
| 104 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
| 105 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
| 106 |
+
`factor` field to infer the suggested value.
|
| 107 |
+
`beta_fast` (`float`, *optional*):
|
| 108 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
| 109 |
+
ramp function. If unspecified, it defaults to 32.
|
| 110 |
+
`beta_slow` (`float`, *optional*):
|
| 111 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
| 112 |
+
ramp function. If unspecified, it defaults to 1.
|
| 113 |
+
`short_factor` (`list[float]`, *optional*):
|
| 114 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
| 115 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 116 |
+
size divided by the number of attention heads divided by 2
|
| 117 |
+
`long_factor` (`list[float]`, *optional*):
|
| 118 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
| 119 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
| 120 |
+
size divided by the number of attention heads divided by 2
|
| 121 |
+
`low_freq_factor` (`float`, *optional*):
|
| 122 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
| 123 |
+
`high_freq_factor` (`float`, *optional*):
|
| 124 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
| 125 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
| 126 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
| 127 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 128 |
+
The dropout ratio for the attention probabilities.
|
| 129 |
+
moe_intermediate_size (`int`, *optional*, defaults to 1408):
|
| 130 |
+
Intermediate size of the routed expert.
|
| 131 |
+
num_experts_per_tok (`int`, *optional*, defaults to 8):
|
| 132 |
+
number of experts per token.
|
| 133 |
+
n_shared_experts (`int`, *optional*, defaults to 1):
|
| 134 |
+
Number of shared experts.
|
| 135 |
+
n_routed_experts (`int`, *optional*, defaults to 128):
|
| 136 |
+
Number of routed experts.
|
| 137 |
+
routed_scaling_factor (`float`, *optional*, defaults to 1.0):
|
| 138 |
+
Scaling factor or routed experts.
|
| 139 |
+
n_group (`int`, *optional*, defaults to 1):
|
| 140 |
+
Number of groups for routed experts.
|
| 141 |
+
topk_group (`int`, *optional*, defaults to 1):
|
| 142 |
+
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
|
| 143 |
+
first_k_dense_replace (`int`, *optional*, defaults to 1):
|
| 144 |
+
Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
|
| 145 |
+
\--k dense layers--/
|
| 146 |
+
norm_topk_prob (`bool`, *optional*, defaults to `True`):
|
| 147 |
+
Whether to normalize the topk probabilities.
|
| 148 |
+
use_qk_norm (`bool`, *optional*, defaults to `False`):
|
| 149 |
+
Whether to use query-key normalization in the attention
|
| 150 |
+
```python
|
| 151 |
+
>>> from transformers import Glm4MoeModel, Glm4MoeConfig
|
| 152 |
+
|
| 153 |
+
>>> # Initializing a Glm4Moe style configuration
|
| 154 |
+
>>> configuration = Glm4MoeConfig()
|
| 155 |
+
|
| 156 |
+
>>> # Initializing a model from the GLM-4-MOE-100B-A10B style configuration
|
| 157 |
+
>>> model = Glm4MoeModel(configuration)
|
| 158 |
+
|
| 159 |
+
>>> # Accessing the model configuration
|
| 160 |
+
>>> configuration = model.config
|
| 161 |
+
```"""
|
| 162 |
+
|
| 163 |
+
model_type = "glm4_moe"
|
| 164 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 165 |
+
|
| 166 |
+
# Default tensor parallel plan for base model `Glm4Moe`
|
| 167 |
+
base_model_tp_plan = {
|
| 168 |
+
"layers.*.self_attn.q_proj": "colwise",
|
| 169 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 170 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 171 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 172 |
+
"layers.*.mlp.experts.*.gate_proj": "colwise",
|
| 173 |
+
"layers.*.mlp.experts.*.up_proj": "colwise",
|
| 174 |
+
"layers.*.mlp.experts.*.down_proj": "rowwise",
|
| 175 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 176 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 177 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 178 |
+
}
|
| 179 |
+
base_model_pp_plan = {
|
| 180 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 181 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 182 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
def __init__(
|
| 186 |
+
self,
|
| 187 |
+
vocab_size=151552,
|
| 188 |
+
hidden_size=4096,
|
| 189 |
+
intermediate_size=10944,
|
| 190 |
+
num_hidden_layers=46,
|
| 191 |
+
num_attention_heads=96,
|
| 192 |
+
partial_rotary_factor=0.5,
|
| 193 |
+
num_key_value_heads=8,
|
| 194 |
+
hidden_act="silu",
|
| 195 |
+
max_position_embeddings=131072,
|
| 196 |
+
initializer_range=0.02,
|
| 197 |
+
rms_norm_eps=1e-5,
|
| 198 |
+
use_cache=True,
|
| 199 |
+
tie_word_embeddings=False,
|
| 200 |
+
rope_theta=10000.0,
|
| 201 |
+
rope_scaling=None,
|
| 202 |
+
attention_bias=False,
|
| 203 |
+
attention_dropout=0.0,
|
| 204 |
+
moe_intermediate_size=1408,
|
| 205 |
+
num_experts_per_tok=8,
|
| 206 |
+
n_shared_experts=1,
|
| 207 |
+
n_routed_experts=128,
|
| 208 |
+
routed_scaling_factor=1.0,
|
| 209 |
+
n_group=1,
|
| 210 |
+
topk_group=1,
|
| 211 |
+
first_k_dense_replace=1,
|
| 212 |
+
norm_topk_prob=True,
|
| 213 |
+
use_qk_norm=False,
|
| 214 |
+
**kwargs,
|
| 215 |
+
):
|
| 216 |
+
self.vocab_size = vocab_size
|
| 217 |
+
self.max_position_embeddings = max_position_embeddings
|
| 218 |
+
self.hidden_size = hidden_size
|
| 219 |
+
self.intermediate_size = intermediate_size
|
| 220 |
+
self.num_hidden_layers = num_hidden_layers
|
| 221 |
+
self.num_attention_heads = num_attention_heads
|
| 222 |
+
self.partial_rotary_factor = partial_rotary_factor
|
| 223 |
+
|
| 224 |
+
self.num_key_value_heads = num_key_value_heads
|
| 225 |
+
self.hidden_act = hidden_act
|
| 226 |
+
self.initializer_range = initializer_range
|
| 227 |
+
self.rms_norm_eps = rms_norm_eps
|
| 228 |
+
self.use_cache = use_cache
|
| 229 |
+
self.rope_theta = rope_theta
|
| 230 |
+
self.rope_scaling = rope_scaling
|
| 231 |
+
self.attention_bias = attention_bias
|
| 232 |
+
self.attention_dropout = attention_dropout
|
| 233 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 234 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
| 235 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
| 236 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
| 237 |
+
rope_config_validation(self)
|
| 238 |
+
|
| 239 |
+
# MoE arguments
|
| 240 |
+
self.moe_intermediate_size = moe_intermediate_size
|
| 241 |
+
self.num_experts_per_tok = num_experts_per_tok
|
| 242 |
+
self.n_group = n_group
|
| 243 |
+
self.topk_group = topk_group
|
| 244 |
+
self.n_shared_experts = n_shared_experts
|
| 245 |
+
self.n_routed_experts = n_routed_experts
|
| 246 |
+
self.routed_scaling_factor = routed_scaling_factor
|
| 247 |
+
self.first_k_dense_replace = first_k_dense_replace
|
| 248 |
+
self.norm_topk_prob = norm_topk_prob
|
| 249 |
+
self.use_qk_norm = use_qk_norm
|
| 250 |
+
|
| 251 |
+
super().__init__(
|
| 252 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 253 |
+
**kwargs,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class Glm4MoeAttention(CohereAttention):
|
| 258 |
+
def __init__(self, config: Glm4MoeConfig, layer_idx: Optional[int] = None):
|
| 259 |
+
nn.Module.__init__(self)
|
| 260 |
+
self.config = config
|
| 261 |
+
self.layer_idx = layer_idx
|
| 262 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 263 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 264 |
+
self.scaling = self.head_dim**-0.5
|
| 265 |
+
self.rope_scaling = config.rope_scaling
|
| 266 |
+
self.attention_dropout = config.attention_dropout
|
| 267 |
+
self.is_causal = True
|
| 268 |
+
|
| 269 |
+
self.q_proj = nn.Linear(
|
| 270 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 271 |
+
)
|
| 272 |
+
self.k_proj = nn.Linear(
|
| 273 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 274 |
+
)
|
| 275 |
+
self.v_proj = nn.Linear(
|
| 276 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 277 |
+
)
|
| 278 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 279 |
+
self.use_qk_norm = config.use_qk_norm
|
| 280 |
+
if self.use_qk_norm:
|
| 281 |
+
self.q_norm = Glm4MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 282 |
+
self.k_norm = Glm4MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class Glm4MoeMLP(DeepseekV3MLP):
|
| 286 |
+
pass
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
class Glm4MoeTopkRouter(DeepseekV3TopkRouter):
|
| 290 |
+
def __init__(self, config: Glm4MoeConfig):
|
| 291 |
+
nn.Module.__init__(self)
|
| 292 |
+
self.config = config
|
| 293 |
+
self.top_k = config.num_experts_per_tok
|
| 294 |
+
self.n_routed_experts = config.n_routed_experts
|
| 295 |
+
self.routed_scaling_factor = config.routed_scaling_factor
|
| 296 |
+
self.n_group = config.n_group
|
| 297 |
+
self.topk_group = config.topk_group
|
| 298 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 299 |
+
|
| 300 |
+
self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
|
| 301 |
+
self.register_buffer("e_score_correction_bias", torch.zeros((self.n_routed_experts), dtype=torch.float32))
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class Glm4MoeRMSNorm(DeepseekV3RMSNorm):
|
| 305 |
+
pass
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
class Glm4MoeDecoderLayer(DeepseekV3DecoderLayer):
|
| 309 |
+
pass
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
class Glm4MoePreTrainedModel(DeepseekV3PreTrainedModel):
|
| 313 |
+
_can_compile_fullgraph = False
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class Glm4MoeModel(DeepseekV3Model):
|
| 317 |
+
_keys_to_ignore_on_load_unexpected = [r"model\.layers\.92.*", r"model\.layers\.46.*"]
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class Glm4MoeForCausalLM(DeepseekV3ForCausalLM):
|
| 321 |
+
pass
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
__all__ = [
|
| 325 |
+
"Glm4MoeConfig",
|
| 326 |
+
"Glm4MoePreTrainedModel",
|
| 327 |
+
"Glm4MoeModel",
|
| 328 |
+
"Glm4MoeForCausalLM",
|
| 329 |
+
]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glpn/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_glpn import *
|
| 22 |
+
from .feature_extraction_glpn import *
|
| 23 |
+
from .image_processing_glpn import *
|
| 24 |
+
from .modeling_glpn import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glpn/configuration_glpn.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 KAIST 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 |
+
"""GLPN model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class GLPNConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`GLPNModel`]. It is used to instantiate an GLPN
|
| 27 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 28 |
+
defaults will yield a similar configuration to that of the GLPN
|
| 29 |
+
[vinvino02/glpn-kitti](https://huggingface.co/vinvino02/glpn-kitti) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 36 |
+
The number of input channels.
|
| 37 |
+
num_encoder_blocks (`int`, *optional*, defaults to 4):
|
| 38 |
+
The number of encoder blocks (i.e. stages in the Mix Transformer encoder).
|
| 39 |
+
depths (`list[int]`, *optional*, defaults to `[2, 2, 2, 2]`):
|
| 40 |
+
The number of layers in each encoder block.
|
| 41 |
+
sr_ratios (`list[int]`, *optional*, defaults to `[8, 4, 2, 1]`):
|
| 42 |
+
Sequence reduction ratios in each encoder block.
|
| 43 |
+
hidden_sizes (`list[int]`, *optional*, defaults to `[32, 64, 160, 256]`):
|
| 44 |
+
Dimension of each of the encoder blocks.
|
| 45 |
+
patch_sizes (`list[int]`, *optional*, defaults to `[7, 3, 3, 3]`):
|
| 46 |
+
Patch size before each encoder block.
|
| 47 |
+
strides (`list[int]`, *optional*, defaults to `[4, 2, 2, 2]`):
|
| 48 |
+
Stride before each encoder block.
|
| 49 |
+
num_attention_heads (`list[int]`, *optional*, defaults to `[1, 2, 5, 8]`):
|
| 50 |
+
Number of attention heads for each attention layer in each block of the Transformer encoder.
|
| 51 |
+
mlp_ratios (`list[int]`, *optional*, defaults to `[4, 4, 4, 4]`):
|
| 52 |
+
Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the
|
| 53 |
+
encoder blocks.
|
| 54 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 55 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 56 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 57 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 58 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 59 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 60 |
+
The dropout ratio for the attention probabilities.
|
| 61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 63 |
+
drop_path_rate (`float`, *optional*, defaults to 0.1):
|
| 64 |
+
The dropout probability for stochastic depth, used in the blocks of the Transformer encoder.
|
| 65 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 66 |
+
The epsilon used by the layer normalization layers.
|
| 67 |
+
decoder_hidden_size (`int`, *optional*, defaults to 64):
|
| 68 |
+
The dimension of the decoder.
|
| 69 |
+
max_depth (`int`, *optional*, defaults to 10):
|
| 70 |
+
The maximum depth of the decoder.
|
| 71 |
+
head_in_index (`int`, *optional*, defaults to -1):
|
| 72 |
+
The index of the features to use in the head.
|
| 73 |
+
|
| 74 |
+
Example:
|
| 75 |
+
|
| 76 |
+
```python
|
| 77 |
+
>>> from transformers import GLPNModel, GLPNConfig
|
| 78 |
+
|
| 79 |
+
>>> # Initializing a GLPN vinvino02/glpn-kitti style configuration
|
| 80 |
+
>>> configuration = GLPNConfig()
|
| 81 |
+
|
| 82 |
+
>>> # Initializing a model from the vinvino02/glpn-kitti style configuration
|
| 83 |
+
>>> model = GLPNModel(configuration)
|
| 84 |
+
|
| 85 |
+
>>> # Accessing the model configuration
|
| 86 |
+
>>> configuration = model.config
|
| 87 |
+
```"""
|
| 88 |
+
|
| 89 |
+
model_type = "glpn"
|
| 90 |
+
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
num_channels=3,
|
| 94 |
+
num_encoder_blocks=4,
|
| 95 |
+
depths=[2, 2, 2, 2],
|
| 96 |
+
sr_ratios=[8, 4, 2, 1],
|
| 97 |
+
hidden_sizes=[32, 64, 160, 256],
|
| 98 |
+
patch_sizes=[7, 3, 3, 3],
|
| 99 |
+
strides=[4, 2, 2, 2],
|
| 100 |
+
num_attention_heads=[1, 2, 5, 8],
|
| 101 |
+
mlp_ratios=[4, 4, 4, 4],
|
| 102 |
+
hidden_act="gelu",
|
| 103 |
+
hidden_dropout_prob=0.0,
|
| 104 |
+
attention_probs_dropout_prob=0.0,
|
| 105 |
+
initializer_range=0.02,
|
| 106 |
+
drop_path_rate=0.1,
|
| 107 |
+
layer_norm_eps=1e-6,
|
| 108 |
+
decoder_hidden_size=64,
|
| 109 |
+
max_depth=10,
|
| 110 |
+
head_in_index=-1,
|
| 111 |
+
**kwargs,
|
| 112 |
+
):
|
| 113 |
+
super().__init__(**kwargs)
|
| 114 |
+
|
| 115 |
+
self.num_channels = num_channels
|
| 116 |
+
self.num_encoder_blocks = num_encoder_blocks
|
| 117 |
+
self.depths = depths
|
| 118 |
+
self.sr_ratios = sr_ratios
|
| 119 |
+
self.hidden_sizes = hidden_sizes
|
| 120 |
+
self.patch_sizes = patch_sizes
|
| 121 |
+
self.strides = strides
|
| 122 |
+
self.mlp_ratios = mlp_ratios
|
| 123 |
+
self.num_attention_heads = num_attention_heads
|
| 124 |
+
self.hidden_act = hidden_act
|
| 125 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 126 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 127 |
+
self.initializer_range = initializer_range
|
| 128 |
+
self.drop_path_rate = drop_path_rate
|
| 129 |
+
self.layer_norm_eps = layer_norm_eps
|
| 130 |
+
self.decoder_hidden_size = decoder_hidden_size
|
| 131 |
+
self.max_depth = max_depth
|
| 132 |
+
self.head_in_index = head_in_index
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
__all__ = ["GLPNConfig"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glpn/feature_extraction_glpn.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Feature extractor class for GLPN."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
from ...utils.import_utils import requires
|
| 21 |
+
from .image_processing_glpn import GLPNImageProcessor
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@requires(backends=("vision",))
|
| 28 |
+
class GLPNFeatureExtractor(GLPNImageProcessor):
|
| 29 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 30 |
+
warnings.warn(
|
| 31 |
+
"The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
|
| 32 |
+
" use GLPNImageProcessor instead.",
|
| 33 |
+
FutureWarning,
|
| 34 |
+
)
|
| 35 |
+
super().__init__(*args, **kwargs)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
__all__ = ["GLPNFeatureExtractor"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glpn/image_processing_glpn.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Image processor class for GLPN."""
|
| 16 |
+
|
| 17 |
+
from typing import TYPE_CHECKING, Optional, Union
|
| 18 |
+
|
| 19 |
+
from ...utils.import_utils import requires
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from ...modeling_outputs import DepthEstimatorOutput
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import PIL.Image
|
| 27 |
+
|
| 28 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature
|
| 29 |
+
from ...image_transforms import resize, to_channel_dimension_format
|
| 30 |
+
from ...image_utils import (
|
| 31 |
+
ChannelDimension,
|
| 32 |
+
PILImageResampling,
|
| 33 |
+
get_image_size,
|
| 34 |
+
infer_channel_dimension_format,
|
| 35 |
+
is_scaled_image,
|
| 36 |
+
is_torch_available,
|
| 37 |
+
make_flat_list_of_images,
|
| 38 |
+
to_numpy_array,
|
| 39 |
+
valid_images,
|
| 40 |
+
validate_preprocess_arguments,
|
| 41 |
+
)
|
| 42 |
+
from ...utils import TensorType, filter_out_non_signature_kwargs, logging, requires_backends
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if is_torch_available():
|
| 46 |
+
import torch
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
logger = logging.get_logger(__name__)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@requires(backends=("vision",))
|
| 53 |
+
class GLPNImageProcessor(BaseImageProcessor):
|
| 54 |
+
r"""
|
| 55 |
+
Constructs a GLPN image processor.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 59 |
+
Whether to resize the image's (height, width) dimensions, rounding them down to the closest multiple of
|
| 60 |
+
`size_divisor`. Can be overridden by `do_resize` in `preprocess`.
|
| 61 |
+
size_divisor (`int`, *optional*, defaults to 32):
|
| 62 |
+
When `do_resize` is `True`, images are resized so their height and width are rounded down to the closest
|
| 63 |
+
multiple of `size_divisor`. Can be overridden by `size_divisor` in `preprocess`.
|
| 64 |
+
resample (`PIL.Image` resampling filter, *optional*, defaults to `Resampling.BILINEAR`):
|
| 65 |
+
Resampling filter to use if resizing the image. Can be overridden by `resample` in `preprocess`.
|
| 66 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). Can be
|
| 68 |
+
overridden by `do_rescale` in `preprocess`.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
model_input_names = ["pixel_values"]
|
| 72 |
+
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
do_resize: bool = True,
|
| 76 |
+
size_divisor: int = 32,
|
| 77 |
+
resample=PILImageResampling.BILINEAR,
|
| 78 |
+
do_rescale: bool = True,
|
| 79 |
+
**kwargs,
|
| 80 |
+
) -> None:
|
| 81 |
+
self.do_resize = do_resize
|
| 82 |
+
self.do_rescale = do_rescale
|
| 83 |
+
self.size_divisor = size_divisor
|
| 84 |
+
self.resample = resample
|
| 85 |
+
super().__init__(**kwargs)
|
| 86 |
+
|
| 87 |
+
def resize(
|
| 88 |
+
self,
|
| 89 |
+
image: np.ndarray,
|
| 90 |
+
size_divisor: int,
|
| 91 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 92 |
+
data_format: Optional[ChannelDimension] = None,
|
| 93 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 94 |
+
**kwargs,
|
| 95 |
+
) -> np.ndarray:
|
| 96 |
+
"""
|
| 97 |
+
Resize the image, rounding the (height, width) dimensions down to the closest multiple of size_divisor.
|
| 98 |
+
|
| 99 |
+
If the image is of dimension (3, 260, 170) and size_divisor is 32, the image will be resized to (3, 256, 160).
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
image (`np.ndarray`):
|
| 103 |
+
The image to resize.
|
| 104 |
+
size_divisor (`int`):
|
| 105 |
+
The image is resized so its height and width are rounded down to the closest multiple of
|
| 106 |
+
`size_divisor`.
|
| 107 |
+
resample:
|
| 108 |
+
`PIL.Image` resampling filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
|
| 109 |
+
data_format (`ChannelDimension` or `str`, *optional*):
|
| 110 |
+
The channel dimension format for the output image. If `None`, the channel dimension format of the input
|
| 111 |
+
image is used. Can be one of:
|
| 112 |
+
- `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 113 |
+
- `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 114 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 115 |
+
The channel dimension format of the input image. If not set, the channel dimension format is inferred
|
| 116 |
+
from the input image. Can be one of:
|
| 117 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 118 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
`np.ndarray`: The resized image.
|
| 122 |
+
"""
|
| 123 |
+
height, width = get_image_size(image, channel_dim=input_data_format)
|
| 124 |
+
# Rounds the height and width down to the closest multiple of size_divisor
|
| 125 |
+
new_h = height // size_divisor * size_divisor
|
| 126 |
+
new_w = width // size_divisor * size_divisor
|
| 127 |
+
image = resize(
|
| 128 |
+
image,
|
| 129 |
+
(new_h, new_w),
|
| 130 |
+
resample=resample,
|
| 131 |
+
data_format=data_format,
|
| 132 |
+
input_data_format=input_data_format,
|
| 133 |
+
**kwargs,
|
| 134 |
+
)
|
| 135 |
+
return image
|
| 136 |
+
|
| 137 |
+
@filter_out_non_signature_kwargs()
|
| 138 |
+
def preprocess(
|
| 139 |
+
self,
|
| 140 |
+
images: Union["PIL.Image.Image", TensorType, list["PIL.Image.Image"], list[TensorType]],
|
| 141 |
+
do_resize: Optional[bool] = None,
|
| 142 |
+
size_divisor: Optional[int] = None,
|
| 143 |
+
resample=None,
|
| 144 |
+
do_rescale: Optional[bool] = None,
|
| 145 |
+
return_tensors: Optional[Union[TensorType, str]] = None,
|
| 146 |
+
data_format: ChannelDimension = ChannelDimension.FIRST,
|
| 147 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 148 |
+
) -> BatchFeature:
|
| 149 |
+
"""
|
| 150 |
+
Preprocess the given images.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
images (`PIL.Image.Image` or `TensorType` or `list[np.ndarray]` or `list[TensorType]`):
|
| 154 |
+
Images to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 155 |
+
passing in images with pixel values between 0 and 1, set `do_normalize=False`.
|
| 156 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 157 |
+
Whether to resize the input such that the (height, width) dimensions are a multiple of `size_divisor`.
|
| 158 |
+
size_divisor (`int`, *optional*, defaults to `self.size_divisor`):
|
| 159 |
+
When `do_resize` is `True`, images are resized so their height and width are rounded down to the
|
| 160 |
+
closest multiple of `size_divisor`.
|
| 161 |
+
resample (`PIL.Image` resampling filter, *optional*, defaults to `self.resample`):
|
| 162 |
+
`PIL.Image` resampling filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
|
| 163 |
+
an effect if `do_resize` is set to `True`.
|
| 164 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 165 |
+
Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.).
|
| 166 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 167 |
+
The type of tensors to return. Can be one of:
|
| 168 |
+
- `None`: Return a list of `np.ndarray`.
|
| 169 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 170 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 171 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 172 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 173 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 174 |
+
The channel dimension format for the output image. Can be one of:
|
| 175 |
+
- `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 176 |
+
- `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 177 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 178 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 179 |
+
from the input image. Can be one of:
|
| 180 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 181 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 182 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 183 |
+
"""
|
| 184 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 185 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 186 |
+
size_divisor = size_divisor if size_divisor is not None else self.size_divisor
|
| 187 |
+
resample = resample if resample is not None else self.resample
|
| 188 |
+
|
| 189 |
+
images = make_flat_list_of_images(images)
|
| 190 |
+
|
| 191 |
+
if not valid_images(images):
|
| 192 |
+
raise ValueError(
|
| 193 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 194 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
# Here, the rescale() method uses a constant rescale_factor. It does not need to be validated
|
| 198 |
+
# with a rescale_factor.
|
| 199 |
+
validate_preprocess_arguments(
|
| 200 |
+
do_resize=do_resize,
|
| 201 |
+
size=size_divisor, # Here, size_divisor is used as a parameter for optimal resizing instead of size.
|
| 202 |
+
resample=resample,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
# All transformations expect numpy arrays.
|
| 206 |
+
images = [to_numpy_array(img) for img in images]
|
| 207 |
+
|
| 208 |
+
if do_rescale and is_scaled_image(images[0]):
|
| 209 |
+
logger.warning_once(
|
| 210 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 211 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
if input_data_format is None:
|
| 215 |
+
# We assume that all images have the same channel dimension format.
|
| 216 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 217 |
+
|
| 218 |
+
if do_resize:
|
| 219 |
+
images = [
|
| 220 |
+
self.resize(image, size_divisor=size_divisor, resample=resample, input_data_format=input_data_format)
|
| 221 |
+
for image in images
|
| 222 |
+
]
|
| 223 |
+
|
| 224 |
+
if do_rescale:
|
| 225 |
+
images = [self.rescale(image, scale=1 / 255, input_data_format=input_data_format) for image in images]
|
| 226 |
+
|
| 227 |
+
images = [
|
| 228 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
|
| 229 |
+
]
|
| 230 |
+
|
| 231 |
+
data = {"pixel_values": images}
|
| 232 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 233 |
+
|
| 234 |
+
def post_process_depth_estimation(
|
| 235 |
+
self,
|
| 236 |
+
outputs: "DepthEstimatorOutput",
|
| 237 |
+
target_sizes: Optional[Union[TensorType, list[tuple[int, int]], None]] = None,
|
| 238 |
+
) -> list[dict[str, TensorType]]:
|
| 239 |
+
"""
|
| 240 |
+
Converts the raw output of [`DepthEstimatorOutput`] into final depth predictions and depth PIL images.
|
| 241 |
+
Only supports PyTorch.
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
outputs ([`DepthEstimatorOutput`]):
|
| 245 |
+
Raw outputs of the model.
|
| 246 |
+
target_sizes (`TensorType` or `list[tuple[int, int]]`, *optional*):
|
| 247 |
+
Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
|
| 248 |
+
(height, width) of each image in the batch. If left to None, predictions will not be resized.
|
| 249 |
+
|
| 250 |
+
Returns:
|
| 251 |
+
`list[dict[str, TensorType]]`: A list of dictionaries of tensors representing the processed depth
|
| 252 |
+
predictions.
|
| 253 |
+
"""
|
| 254 |
+
requires_backends(self, "torch")
|
| 255 |
+
|
| 256 |
+
predicted_depth = outputs.predicted_depth
|
| 257 |
+
|
| 258 |
+
if (target_sizes is not None) and (len(predicted_depth) != len(target_sizes)):
|
| 259 |
+
raise ValueError(
|
| 260 |
+
"Make sure that you pass in as many target sizes as the batch dimension of the predicted depth"
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
results = []
|
| 264 |
+
target_sizes = [None] * len(predicted_depth) if target_sizes is None else target_sizes
|
| 265 |
+
for depth, target_size in zip(predicted_depth, target_sizes):
|
| 266 |
+
if target_size is not None:
|
| 267 |
+
depth = depth[None, None, ...]
|
| 268 |
+
depth = torch.nn.functional.interpolate(depth, size=target_size, mode="bicubic", align_corners=False)
|
| 269 |
+
depth = depth.squeeze()
|
| 270 |
+
|
| 271 |
+
results.append({"predicted_depth": depth})
|
| 272 |
+
|
| 273 |
+
return results
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
__all__ = ["GLPNImageProcessor"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/glpn/modeling_glpn.py
ADDED
|
@@ -0,0 +1,724 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 KAIST 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 GLPN model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from typing import Optional, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
from ...activations import ACT2FN
|
| 24 |
+
from ...modeling_outputs import BaseModelOutput, DepthEstimatorOutput
|
| 25 |
+
from ...modeling_utils import PreTrainedModel
|
| 26 |
+
from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
|
| 27 |
+
from ...utils import auto_docstring, logging
|
| 28 |
+
from .configuration_glpn import GLPNConfig
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# Copied from transformers.models.beit.modeling_beit.drop_path
|
| 35 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 36 |
+
"""
|
| 37 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 38 |
+
|
| 39 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 40 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 41 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 42 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 43 |
+
argument.
|
| 44 |
+
"""
|
| 45 |
+
if drop_prob == 0.0 or not training:
|
| 46 |
+
return input
|
| 47 |
+
keep_prob = 1 - drop_prob
|
| 48 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 49 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 50 |
+
random_tensor.floor_() # binarize
|
| 51 |
+
output = input.div(keep_prob) * random_tensor
|
| 52 |
+
return output
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# Copied from transformers.models.segformer.modeling_segformer.SegformerDropPath
|
| 56 |
+
class GLPNDropPath(nn.Module):
|
| 57 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 58 |
+
|
| 59 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.drop_prob = drop_prob
|
| 62 |
+
|
| 63 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 64 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 65 |
+
|
| 66 |
+
def extra_repr(self) -> str:
|
| 67 |
+
return f"p={self.drop_prob}"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# Copied from transformers.models.segformer.modeling_segformer.SegformerOverlapPatchEmbeddings
|
| 71 |
+
class GLPNOverlapPatchEmbeddings(nn.Module):
|
| 72 |
+
"""Construct the overlapping patch embeddings."""
|
| 73 |
+
|
| 74 |
+
def __init__(self, patch_size, stride, num_channels, hidden_size):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.proj = nn.Conv2d(
|
| 77 |
+
num_channels,
|
| 78 |
+
hidden_size,
|
| 79 |
+
kernel_size=patch_size,
|
| 80 |
+
stride=stride,
|
| 81 |
+
padding=patch_size // 2,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
self.layer_norm = nn.LayerNorm(hidden_size)
|
| 85 |
+
|
| 86 |
+
def forward(self, pixel_values):
|
| 87 |
+
embeddings = self.proj(pixel_values)
|
| 88 |
+
_, _, height, width = embeddings.shape
|
| 89 |
+
# (batch_size, num_channels, height, width) -> (batch_size, num_channels, height*width) -> (batch_size, height*width, num_channels)
|
| 90 |
+
# this can be fed to a Transformer layer
|
| 91 |
+
embeddings = embeddings.flatten(2).transpose(1, 2)
|
| 92 |
+
embeddings = self.layer_norm(embeddings)
|
| 93 |
+
return embeddings, height, width
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# Copied from transformers.models.segformer.modeling_segformer.SegformerEfficientSelfAttention
|
| 97 |
+
class GLPNEfficientSelfAttention(nn.Module):
|
| 98 |
+
"""SegFormer's efficient self-attention mechanism. Employs the sequence reduction process introduced in the [PvT
|
| 99 |
+
paper](https://huggingface.co/papers/2102.12122)."""
|
| 100 |
+
|
| 101 |
+
def __init__(self, config, hidden_size, num_attention_heads, sequence_reduction_ratio):
|
| 102 |
+
super().__init__()
|
| 103 |
+
self.hidden_size = hidden_size
|
| 104 |
+
self.num_attention_heads = num_attention_heads
|
| 105 |
+
|
| 106 |
+
if self.hidden_size % self.num_attention_heads != 0:
|
| 107 |
+
raise ValueError(
|
| 108 |
+
f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
|
| 109 |
+
f"heads ({self.num_attention_heads})"
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
self.attention_head_size = int(self.hidden_size / self.num_attention_heads)
|
| 113 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 114 |
+
|
| 115 |
+
self.query = nn.Linear(self.hidden_size, self.all_head_size)
|
| 116 |
+
self.key = nn.Linear(self.hidden_size, self.all_head_size)
|
| 117 |
+
self.value = nn.Linear(self.hidden_size, self.all_head_size)
|
| 118 |
+
|
| 119 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 120 |
+
|
| 121 |
+
self.sr_ratio = sequence_reduction_ratio
|
| 122 |
+
if sequence_reduction_ratio > 1:
|
| 123 |
+
self.sr = nn.Conv2d(
|
| 124 |
+
hidden_size, hidden_size, kernel_size=sequence_reduction_ratio, stride=sequence_reduction_ratio
|
| 125 |
+
)
|
| 126 |
+
self.layer_norm = nn.LayerNorm(hidden_size)
|
| 127 |
+
|
| 128 |
+
def forward(
|
| 129 |
+
self,
|
| 130 |
+
hidden_states,
|
| 131 |
+
height,
|
| 132 |
+
width,
|
| 133 |
+
output_attentions=False,
|
| 134 |
+
):
|
| 135 |
+
batch_size, seq_length, _ = hidden_states.shape
|
| 136 |
+
query_layer = (
|
| 137 |
+
self.query(hidden_states)
|
| 138 |
+
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
|
| 139 |
+
.transpose(1, 2)
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
if self.sr_ratio > 1:
|
| 143 |
+
batch_size, seq_len, num_channels = hidden_states.shape
|
| 144 |
+
# Reshape to (batch_size, num_channels, height, width)
|
| 145 |
+
hidden_states = hidden_states.permute(0, 2, 1).reshape(batch_size, num_channels, height, width)
|
| 146 |
+
# Apply sequence reduction
|
| 147 |
+
hidden_states = self.sr(hidden_states)
|
| 148 |
+
# Reshape back to (batch_size, seq_len, num_channels)
|
| 149 |
+
hidden_states = hidden_states.reshape(batch_size, num_channels, -1).permute(0, 2, 1)
|
| 150 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 151 |
+
|
| 152 |
+
key_layer = (
|
| 153 |
+
self.key(hidden_states)
|
| 154 |
+
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
|
| 155 |
+
.transpose(1, 2)
|
| 156 |
+
)
|
| 157 |
+
value_layer = (
|
| 158 |
+
self.value(hidden_states)
|
| 159 |
+
.view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
|
| 160 |
+
.transpose(1, 2)
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 164 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 165 |
+
|
| 166 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 167 |
+
|
| 168 |
+
# Normalize the attention scores to probabilities.
|
| 169 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 170 |
+
|
| 171 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 172 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 173 |
+
attention_probs = self.dropout(attention_probs)
|
| 174 |
+
|
| 175 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 176 |
+
|
| 177 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 178 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 179 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 180 |
+
|
| 181 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 182 |
+
|
| 183 |
+
return outputs
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# Copied from transformers.models.segformer.modeling_segformer.SegformerSelfOutput
|
| 187 |
+
class GLPNSelfOutput(nn.Module):
|
| 188 |
+
def __init__(self, config, hidden_size):
|
| 189 |
+
super().__init__()
|
| 190 |
+
self.dense = nn.Linear(hidden_size, hidden_size)
|
| 191 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 192 |
+
|
| 193 |
+
def forward(self, hidden_states, input_tensor):
|
| 194 |
+
hidden_states = self.dense(hidden_states)
|
| 195 |
+
hidden_states = self.dropout(hidden_states)
|
| 196 |
+
return hidden_states
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# Copied from transformers.models.segformer.modeling_segformer.SegformerAttention with Segformer->GLPN
|
| 200 |
+
class GLPNAttention(nn.Module):
|
| 201 |
+
def __init__(self, config, hidden_size, num_attention_heads, sequence_reduction_ratio):
|
| 202 |
+
super().__init__()
|
| 203 |
+
self.self = GLPNEfficientSelfAttention(
|
| 204 |
+
config=config,
|
| 205 |
+
hidden_size=hidden_size,
|
| 206 |
+
num_attention_heads=num_attention_heads,
|
| 207 |
+
sequence_reduction_ratio=sequence_reduction_ratio,
|
| 208 |
+
)
|
| 209 |
+
self.output = GLPNSelfOutput(config, hidden_size=hidden_size)
|
| 210 |
+
self.pruned_heads = set()
|
| 211 |
+
|
| 212 |
+
def prune_heads(self, heads):
|
| 213 |
+
if len(heads) == 0:
|
| 214 |
+
return
|
| 215 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 216 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
# Prune linear layers
|
| 220 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 221 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 222 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 223 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 224 |
+
|
| 225 |
+
# Update hyper params and store pruned heads
|
| 226 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 227 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 228 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 229 |
+
|
| 230 |
+
def forward(self, hidden_states, height, width, output_attentions=False):
|
| 231 |
+
self_outputs = self.self(hidden_states, height, width, output_attentions)
|
| 232 |
+
|
| 233 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 234 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 235 |
+
return outputs
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
# Copied from transformers.models.segformer.modeling_segformer.SegformerDWConv
|
| 239 |
+
class GLPNDWConv(nn.Module):
|
| 240 |
+
def __init__(self, dim=768):
|
| 241 |
+
super().__init__()
|
| 242 |
+
self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
|
| 243 |
+
|
| 244 |
+
def forward(self, hidden_states, height, width):
|
| 245 |
+
batch_size, seq_len, num_channels = hidden_states.shape
|
| 246 |
+
hidden_states = hidden_states.transpose(1, 2).view(batch_size, num_channels, height, width)
|
| 247 |
+
hidden_states = self.dwconv(hidden_states)
|
| 248 |
+
hidden_states = hidden_states.flatten(2).transpose(1, 2)
|
| 249 |
+
|
| 250 |
+
return hidden_states
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
# Copied from transformers.models.segformer.modeling_segformer.SegformerMixFFN with Segformer->GLPN
|
| 254 |
+
class GLPNMixFFN(nn.Module):
|
| 255 |
+
def __init__(self, config, in_features, hidden_features=None, out_features=None):
|
| 256 |
+
super().__init__()
|
| 257 |
+
out_features = out_features or in_features
|
| 258 |
+
self.dense1 = nn.Linear(in_features, hidden_features)
|
| 259 |
+
self.dwconv = GLPNDWConv(hidden_features)
|
| 260 |
+
if isinstance(config.hidden_act, str):
|
| 261 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 262 |
+
else:
|
| 263 |
+
self.intermediate_act_fn = config.hidden_act
|
| 264 |
+
self.dense2 = nn.Linear(hidden_features, out_features)
|
| 265 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 266 |
+
|
| 267 |
+
def forward(self, hidden_states, height, width):
|
| 268 |
+
hidden_states = self.dense1(hidden_states)
|
| 269 |
+
hidden_states = self.dwconv(hidden_states, height, width)
|
| 270 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 271 |
+
hidden_states = self.dropout(hidden_states)
|
| 272 |
+
hidden_states = self.dense2(hidden_states)
|
| 273 |
+
hidden_states = self.dropout(hidden_states)
|
| 274 |
+
return hidden_states
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
# Copied from transformers.models.segformer.modeling_segformer.SegformerLayer with Segformer->GLPN
|
| 278 |
+
class GLPNLayer(nn.Module):
|
| 279 |
+
"""This corresponds to the Block class in the original implementation."""
|
| 280 |
+
|
| 281 |
+
def __init__(self, config, hidden_size, num_attention_heads, drop_path, sequence_reduction_ratio, mlp_ratio):
|
| 282 |
+
super().__init__()
|
| 283 |
+
self.layer_norm_1 = nn.LayerNorm(hidden_size)
|
| 284 |
+
self.attention = GLPNAttention(
|
| 285 |
+
config,
|
| 286 |
+
hidden_size=hidden_size,
|
| 287 |
+
num_attention_heads=num_attention_heads,
|
| 288 |
+
sequence_reduction_ratio=sequence_reduction_ratio,
|
| 289 |
+
)
|
| 290 |
+
self.drop_path = GLPNDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 291 |
+
self.layer_norm_2 = nn.LayerNorm(hidden_size)
|
| 292 |
+
mlp_hidden_size = int(hidden_size * mlp_ratio)
|
| 293 |
+
self.mlp = GLPNMixFFN(config, in_features=hidden_size, hidden_features=mlp_hidden_size)
|
| 294 |
+
|
| 295 |
+
def forward(self, hidden_states, height, width, output_attentions=False):
|
| 296 |
+
self_attention_outputs = self.attention(
|
| 297 |
+
self.layer_norm_1(hidden_states), # in GLPN, layernorm is applied before self-attention
|
| 298 |
+
height,
|
| 299 |
+
width,
|
| 300 |
+
output_attentions=output_attentions,
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
attention_output = self_attention_outputs[0]
|
| 304 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 305 |
+
|
| 306 |
+
# first residual connection (with stochastic depth)
|
| 307 |
+
attention_output = self.drop_path(attention_output)
|
| 308 |
+
hidden_states = attention_output + hidden_states
|
| 309 |
+
|
| 310 |
+
mlp_output = self.mlp(self.layer_norm_2(hidden_states), height, width)
|
| 311 |
+
|
| 312 |
+
# second residual connection (with stochastic depth)
|
| 313 |
+
mlp_output = self.drop_path(mlp_output)
|
| 314 |
+
layer_output = mlp_output + hidden_states
|
| 315 |
+
|
| 316 |
+
outputs = (layer_output,) + outputs
|
| 317 |
+
|
| 318 |
+
return outputs
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class GLPNEncoder(nn.Module):
|
| 322 |
+
def __init__(self, config):
|
| 323 |
+
super().__init__()
|
| 324 |
+
self.config = config
|
| 325 |
+
|
| 326 |
+
# stochastic depth decay rule
|
| 327 |
+
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")]
|
| 328 |
+
|
| 329 |
+
# patch embeddings
|
| 330 |
+
embeddings = []
|
| 331 |
+
for i in range(config.num_encoder_blocks):
|
| 332 |
+
embeddings.append(
|
| 333 |
+
GLPNOverlapPatchEmbeddings(
|
| 334 |
+
patch_size=config.patch_sizes[i],
|
| 335 |
+
stride=config.strides[i],
|
| 336 |
+
num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1],
|
| 337 |
+
hidden_size=config.hidden_sizes[i],
|
| 338 |
+
)
|
| 339 |
+
)
|
| 340 |
+
self.patch_embeddings = nn.ModuleList(embeddings)
|
| 341 |
+
|
| 342 |
+
# Transformer blocks
|
| 343 |
+
blocks = []
|
| 344 |
+
cur = 0
|
| 345 |
+
for i in range(config.num_encoder_blocks):
|
| 346 |
+
# each block consists of layers
|
| 347 |
+
layers = []
|
| 348 |
+
if i != 0:
|
| 349 |
+
cur += config.depths[i - 1]
|
| 350 |
+
for j in range(config.depths[i]):
|
| 351 |
+
layers.append(
|
| 352 |
+
GLPNLayer(
|
| 353 |
+
config,
|
| 354 |
+
hidden_size=config.hidden_sizes[i],
|
| 355 |
+
num_attention_heads=config.num_attention_heads[i],
|
| 356 |
+
drop_path=dpr[cur + j],
|
| 357 |
+
sequence_reduction_ratio=config.sr_ratios[i],
|
| 358 |
+
mlp_ratio=config.mlp_ratios[i],
|
| 359 |
+
)
|
| 360 |
+
)
|
| 361 |
+
blocks.append(nn.ModuleList(layers))
|
| 362 |
+
|
| 363 |
+
self.block = nn.ModuleList(blocks)
|
| 364 |
+
|
| 365 |
+
# Layer norms
|
| 366 |
+
self.layer_norm = nn.ModuleList(
|
| 367 |
+
[nn.LayerNorm(config.hidden_sizes[i]) for i in range(config.num_encoder_blocks)]
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
def forward(
|
| 371 |
+
self,
|
| 372 |
+
pixel_values,
|
| 373 |
+
output_attentions=False,
|
| 374 |
+
output_hidden_states=False,
|
| 375 |
+
return_dict=True,
|
| 376 |
+
):
|
| 377 |
+
all_hidden_states = () if output_hidden_states else None
|
| 378 |
+
all_self_attentions = () if output_attentions else None
|
| 379 |
+
|
| 380 |
+
batch_size = pixel_values.shape[0]
|
| 381 |
+
|
| 382 |
+
hidden_states = pixel_values
|
| 383 |
+
for idx, x in enumerate(zip(self.patch_embeddings, self.block, self.layer_norm)):
|
| 384 |
+
embedding_layer, block_layer, norm_layer = x
|
| 385 |
+
# first, obtain patch embeddings
|
| 386 |
+
hidden_states, height, width = embedding_layer(hidden_states)
|
| 387 |
+
# second, send embeddings through blocks
|
| 388 |
+
for i, blk in enumerate(block_layer):
|
| 389 |
+
layer_outputs = blk(hidden_states, height, width, output_attentions)
|
| 390 |
+
hidden_states = layer_outputs[0]
|
| 391 |
+
if output_attentions:
|
| 392 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 393 |
+
# third, apply layer norm
|
| 394 |
+
hidden_states = norm_layer(hidden_states)
|
| 395 |
+
# fourth, optionally reshape back to (batch_size, num_channels, height, width)
|
| 396 |
+
hidden_states = hidden_states.reshape(batch_size, height, width, -1).permute(0, 3, 1, 2).contiguous()
|
| 397 |
+
if output_hidden_states:
|
| 398 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 399 |
+
|
| 400 |
+
if not return_dict:
|
| 401 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
| 402 |
+
return BaseModelOutput(
|
| 403 |
+
last_hidden_state=hidden_states,
|
| 404 |
+
hidden_states=all_hidden_states,
|
| 405 |
+
attentions=all_self_attentions,
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@auto_docstring
|
| 410 |
+
class GLPNPreTrainedModel(PreTrainedModel):
|
| 411 |
+
config: GLPNConfig
|
| 412 |
+
base_model_prefix = "glpn"
|
| 413 |
+
main_input_name = "pixel_values"
|
| 414 |
+
_no_split_modules = []
|
| 415 |
+
|
| 416 |
+
# Copied from transformers.models.segformer.modeling_segformer.SegformerPreTrainedModel._init_weights
|
| 417 |
+
def _init_weights(self, module):
|
| 418 |
+
"""Initialize the weights"""
|
| 419 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 420 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 421 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 422 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 423 |
+
if module.bias is not None:
|
| 424 |
+
module.bias.data.zero_()
|
| 425 |
+
elif isinstance(module, nn.Embedding):
|
| 426 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 427 |
+
if module.padding_idx is not None:
|
| 428 |
+
module.weight.data[module.padding_idx].zero_()
|
| 429 |
+
elif isinstance(module, (nn.LayerNorm, nn.BatchNorm2d)):
|
| 430 |
+
module.bias.data.zero_()
|
| 431 |
+
module.weight.data.fill_(1.0)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
@auto_docstring
|
| 435 |
+
class GLPNModel(GLPNPreTrainedModel):
|
| 436 |
+
# Copied from transformers.models.segformer.modeling_segformer.SegformerModel.__init__ with Segformer->GLPN
|
| 437 |
+
def __init__(self, config):
|
| 438 |
+
super().__init__(config)
|
| 439 |
+
self.config = config
|
| 440 |
+
|
| 441 |
+
# hierarchical Transformer encoder
|
| 442 |
+
self.encoder = GLPNEncoder(config)
|
| 443 |
+
|
| 444 |
+
# Initialize weights and apply final processing
|
| 445 |
+
self.post_init()
|
| 446 |
+
|
| 447 |
+
def _prune_heads(self, heads_to_prune):
|
| 448 |
+
"""
|
| 449 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 450 |
+
class PreTrainedModel
|
| 451 |
+
"""
|
| 452 |
+
for layer, heads in heads_to_prune.items():
|
| 453 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 454 |
+
|
| 455 |
+
@auto_docstring
|
| 456 |
+
# Copied from transformers.models.segformer.modeling_segformer.SegformerModel.forward
|
| 457 |
+
def forward(
|
| 458 |
+
self,
|
| 459 |
+
pixel_values: torch.FloatTensor,
|
| 460 |
+
output_attentions: Optional[bool] = None,
|
| 461 |
+
output_hidden_states: Optional[bool] = None,
|
| 462 |
+
return_dict: Optional[bool] = None,
|
| 463 |
+
) -> Union[tuple, BaseModelOutput]:
|
| 464 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 465 |
+
output_hidden_states = (
|
| 466 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 467 |
+
)
|
| 468 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 469 |
+
|
| 470 |
+
encoder_outputs = self.encoder(
|
| 471 |
+
pixel_values,
|
| 472 |
+
output_attentions=output_attentions,
|
| 473 |
+
output_hidden_states=output_hidden_states,
|
| 474 |
+
return_dict=return_dict,
|
| 475 |
+
)
|
| 476 |
+
sequence_output = encoder_outputs[0]
|
| 477 |
+
|
| 478 |
+
if not return_dict:
|
| 479 |
+
return (sequence_output,) + encoder_outputs[1:]
|
| 480 |
+
|
| 481 |
+
return BaseModelOutput(
|
| 482 |
+
last_hidden_state=sequence_output,
|
| 483 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 484 |
+
attentions=encoder_outputs.attentions,
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
class GLPNSelectiveFeatureFusion(nn.Module):
|
| 489 |
+
"""
|
| 490 |
+
Selective Feature Fusion module, as explained in the [paper](https://huggingface.co/papers/2201.07436) (section 3.4). This
|
| 491 |
+
module adaptively selects and integrates local and global features by attaining an attention map for each feature.
|
| 492 |
+
"""
|
| 493 |
+
|
| 494 |
+
def __init__(self, in_channel=64):
|
| 495 |
+
super().__init__()
|
| 496 |
+
|
| 497 |
+
self.convolutional_layer1 = nn.Sequential(
|
| 498 |
+
nn.Conv2d(in_channels=int(in_channel * 2), out_channels=in_channel, kernel_size=3, stride=1, padding=1),
|
| 499 |
+
nn.BatchNorm2d(in_channel),
|
| 500 |
+
nn.ReLU(),
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
self.convolutional_layer2 = nn.Sequential(
|
| 504 |
+
nn.Conv2d(in_channels=in_channel, out_channels=int(in_channel / 2), kernel_size=3, stride=1, padding=1),
|
| 505 |
+
nn.BatchNorm2d(int(in_channel / 2)),
|
| 506 |
+
nn.ReLU(),
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
self.convolutional_layer3 = nn.Conv2d(
|
| 510 |
+
in_channels=int(in_channel / 2), out_channels=2, kernel_size=3, stride=1, padding=1
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
self.sigmoid = nn.Sigmoid()
|
| 514 |
+
|
| 515 |
+
def forward(self, local_features, global_features):
|
| 516 |
+
# concatenate features along the channel dimension
|
| 517 |
+
features = torch.cat((local_features, global_features), dim=1)
|
| 518 |
+
# pass through convolutional layers
|
| 519 |
+
features = self.convolutional_layer1(features)
|
| 520 |
+
features = self.convolutional_layer2(features)
|
| 521 |
+
features = self.convolutional_layer3(features)
|
| 522 |
+
# apply sigmoid to get two-channel attention map
|
| 523 |
+
attn = self.sigmoid(features)
|
| 524 |
+
# construct hybrid features by adding element-wise
|
| 525 |
+
hybrid_features = local_features * attn[:, 0, :, :].unsqueeze(1) + global_features * attn[
|
| 526 |
+
:, 1, :, :
|
| 527 |
+
].unsqueeze(1)
|
| 528 |
+
|
| 529 |
+
return hybrid_features
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
class GLPNDecoderStage(nn.Module):
|
| 533 |
+
def __init__(self, in_channels, out_channels):
|
| 534 |
+
super().__init__()
|
| 535 |
+
should_skip = in_channels == out_channels
|
| 536 |
+
self.convolution = nn.Conv2d(in_channels, out_channels, kernel_size=1) if not should_skip else nn.Identity()
|
| 537 |
+
self.fusion = GLPNSelectiveFeatureFusion(out_channels)
|
| 538 |
+
self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 539 |
+
|
| 540 |
+
def forward(self, hidden_state, residual=None):
|
| 541 |
+
hidden_state = self.convolution(hidden_state)
|
| 542 |
+
if residual is not None:
|
| 543 |
+
hidden_state = self.fusion(hidden_state, residual)
|
| 544 |
+
hidden_state = self.upsample(hidden_state)
|
| 545 |
+
|
| 546 |
+
return hidden_state
|
| 547 |
+
|
| 548 |
+
hidden_state = self.upsample(hidden_state)
|
| 549 |
+
return hidden_state
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
class GLPNDecoder(nn.Module):
|
| 553 |
+
def __init__(self, config):
|
| 554 |
+
super().__init__()
|
| 555 |
+
# we use features from end -> start
|
| 556 |
+
reserved_hidden_sizes = config.hidden_sizes[::-1]
|
| 557 |
+
out_channels = config.decoder_hidden_size
|
| 558 |
+
|
| 559 |
+
self.stages = nn.ModuleList(
|
| 560 |
+
[GLPNDecoderStage(hidden_size, out_channels) for hidden_size in reserved_hidden_sizes]
|
| 561 |
+
)
|
| 562 |
+
# don't fuse in first stage
|
| 563 |
+
self.stages[0].fusion = None
|
| 564 |
+
|
| 565 |
+
self.final_upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
|
| 566 |
+
|
| 567 |
+
def forward(self, hidden_states: list[torch.Tensor]) -> list[torch.Tensor]:
|
| 568 |
+
stage_hidden_states = []
|
| 569 |
+
stage_hidden_state = None
|
| 570 |
+
for hidden_state, stage in zip(hidden_states[::-1], self.stages):
|
| 571 |
+
stage_hidden_state = stage(hidden_state, stage_hidden_state)
|
| 572 |
+
stage_hidden_states.append(stage_hidden_state)
|
| 573 |
+
|
| 574 |
+
stage_hidden_states[-1] = self.final_upsample(stage_hidden_state)
|
| 575 |
+
|
| 576 |
+
return stage_hidden_states
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
class SiLogLoss(nn.Module):
|
| 580 |
+
r"""
|
| 581 |
+
Implements the Scale-invariant log scale loss [Eigen et al., 2014](https://huggingface.co/papers/1406.2283).
|
| 582 |
+
|
| 583 |
+
$$L=\frac{1}{n} \sum_{i} d_{i}^{2}-\frac{1}{2 n^{2}}\left(\sum_{i} d_{i}^{2}\right)$$ where $d_{i}=\log y_{i}-\log
|
| 584 |
+
y_{i}^{*}$.
|
| 585 |
+
|
| 586 |
+
"""
|
| 587 |
+
|
| 588 |
+
def __init__(self, lambd=0.5):
|
| 589 |
+
super().__init__()
|
| 590 |
+
self.lambd = lambd
|
| 591 |
+
|
| 592 |
+
def forward(self, pred, target):
|
| 593 |
+
valid_mask = (target > 0).detach()
|
| 594 |
+
diff_log = torch.log(target[valid_mask]) - torch.log(pred[valid_mask])
|
| 595 |
+
loss = torch.sqrt(torch.pow(diff_log, 2).mean() - self.lambd * torch.pow(diff_log.mean(), 2))
|
| 596 |
+
|
| 597 |
+
return loss
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
class GLPNDepthEstimationHead(nn.Module):
|
| 601 |
+
def __init__(self, config):
|
| 602 |
+
super().__init__()
|
| 603 |
+
|
| 604 |
+
self.config = config
|
| 605 |
+
|
| 606 |
+
channels = config.decoder_hidden_size
|
| 607 |
+
self.head = nn.Sequential(
|
| 608 |
+
nn.Conv2d(channels, channels, kernel_size=3, stride=1, padding=1),
|
| 609 |
+
nn.ReLU(inplace=False),
|
| 610 |
+
nn.Conv2d(channels, 1, kernel_size=3, stride=1, padding=1),
|
| 611 |
+
)
|
| 612 |
+
|
| 613 |
+
def forward(self, hidden_states: list[torch.Tensor]) -> torch.Tensor:
|
| 614 |
+
# use last features of the decoder
|
| 615 |
+
hidden_states = hidden_states[self.config.head_in_index]
|
| 616 |
+
|
| 617 |
+
hidden_states = self.head(hidden_states)
|
| 618 |
+
|
| 619 |
+
predicted_depth = torch.sigmoid(hidden_states) * self.config.max_depth
|
| 620 |
+
predicted_depth = predicted_depth.squeeze(dim=1)
|
| 621 |
+
|
| 622 |
+
return predicted_depth
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
@auto_docstring(
|
| 626 |
+
custom_intro="""
|
| 627 |
+
GLPN Model transformer with a lightweight depth estimation head on top e.g. for KITTI, NYUv2.
|
| 628 |
+
"""
|
| 629 |
+
)
|
| 630 |
+
class GLPNForDepthEstimation(GLPNPreTrainedModel):
|
| 631 |
+
def __init__(self, config):
|
| 632 |
+
super().__init__(config)
|
| 633 |
+
|
| 634 |
+
self.glpn = GLPNModel(config)
|
| 635 |
+
self.decoder = GLPNDecoder(config)
|
| 636 |
+
self.head = GLPNDepthEstimationHead(config)
|
| 637 |
+
|
| 638 |
+
# Initialize weights and apply final processing
|
| 639 |
+
self.post_init()
|
| 640 |
+
|
| 641 |
+
@auto_docstring
|
| 642 |
+
def forward(
|
| 643 |
+
self,
|
| 644 |
+
pixel_values: torch.FloatTensor,
|
| 645 |
+
labels: Optional[torch.FloatTensor] = None,
|
| 646 |
+
output_attentions: Optional[bool] = None,
|
| 647 |
+
output_hidden_states: Optional[bool] = None,
|
| 648 |
+
return_dict: Optional[bool] = None,
|
| 649 |
+
) -> Union[tuple[torch.Tensor], DepthEstimatorOutput]:
|
| 650 |
+
r"""
|
| 651 |
+
labels (`torch.FloatTensor` of shape `(batch_size, height, width)`, *optional*):
|
| 652 |
+
Ground truth depth estimation maps for computing the loss.
|
| 653 |
+
|
| 654 |
+
Examples:
|
| 655 |
+
|
| 656 |
+
```python
|
| 657 |
+
>>> from transformers import AutoImageProcessor, GLPNForDepthEstimation
|
| 658 |
+
>>> import torch
|
| 659 |
+
>>> import numpy as np
|
| 660 |
+
>>> from PIL import Image
|
| 661 |
+
>>> import requests
|
| 662 |
+
|
| 663 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 664 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 665 |
+
|
| 666 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("vinvino02/glpn-kitti")
|
| 667 |
+
>>> model = GLPNForDepthEstimation.from_pretrained("vinvino02/glpn-kitti")
|
| 668 |
+
|
| 669 |
+
>>> # prepare image for the model
|
| 670 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 671 |
+
|
| 672 |
+
>>> with torch.no_grad():
|
| 673 |
+
... outputs = model(**inputs)
|
| 674 |
+
|
| 675 |
+
>>> # interpolate to original size
|
| 676 |
+
>>> post_processed_output = image_processor.post_process_depth_estimation(
|
| 677 |
+
... outputs,
|
| 678 |
+
... target_sizes=[(image.height, image.width)],
|
| 679 |
+
... )
|
| 680 |
+
|
| 681 |
+
>>> # visualize the prediction
|
| 682 |
+
>>> predicted_depth = post_processed_output[0]["predicted_depth"]
|
| 683 |
+
>>> depth = predicted_depth * 255 / predicted_depth.max()
|
| 684 |
+
>>> depth = depth.detach().cpu().numpy()
|
| 685 |
+
>>> depth = Image.fromarray(depth.astype("uint8"))
|
| 686 |
+
```"""
|
| 687 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 688 |
+
output_hidden_states = (
|
| 689 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
outputs = self.glpn(
|
| 693 |
+
pixel_values,
|
| 694 |
+
output_attentions=output_attentions,
|
| 695 |
+
output_hidden_states=True, # we need the intermediate hidden states
|
| 696 |
+
return_dict=return_dict,
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
hidden_states = outputs.hidden_states if return_dict else outputs[1]
|
| 700 |
+
|
| 701 |
+
out = self.decoder(hidden_states)
|
| 702 |
+
predicted_depth = self.head(out)
|
| 703 |
+
|
| 704 |
+
loss = None
|
| 705 |
+
if labels is not None:
|
| 706 |
+
loss_fct = SiLogLoss()
|
| 707 |
+
loss = loss_fct(predicted_depth, labels)
|
| 708 |
+
|
| 709 |
+
if not return_dict:
|
| 710 |
+
if output_hidden_states:
|
| 711 |
+
output = (predicted_depth,) + outputs[1:]
|
| 712 |
+
else:
|
| 713 |
+
output = (predicted_depth,) + outputs[2:]
|
| 714 |
+
return ((loss,) + output) if loss is not None else output
|
| 715 |
+
|
| 716 |
+
return DepthEstimatorOutput(
|
| 717 |
+
loss=loss,
|
| 718 |
+
predicted_depth=predicted_depth,
|
| 719 |
+
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
| 720 |
+
attentions=outputs.attentions,
|
| 721 |
+
)
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
__all__ = ["GLPNForDepthEstimation", "GLPNLayer", "GLPNModel", "GLPNPreTrainedModel"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_oss/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_gpt_oss import *
|
| 22 |
+
from .modeling_gpt_oss import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_oss/configuration_gpt_oss.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""openai model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig, layer_type_validation
|
| 18 |
+
from ...modeling_rope_utils import rope_config_validation
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class GptOssConfig(PretrainedConfig):
|
| 22 |
+
r"""
|
| 23 |
+
This will yield a configuration to that of the BERT
|
| 24 |
+
[google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased) architecture.
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
model_type = "gpt_oss"
|
| 29 |
+
base_model_pp_plan = {
|
| 30 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 31 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 32 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 33 |
+
}
|
| 34 |
+
base_model_tp_plan = {
|
| 35 |
+
"layers.*.self_attn.q_proj": "colwise",
|
| 36 |
+
"layers.*.self_attn.k_proj": "colwise",
|
| 37 |
+
"layers.*.self_attn.v_proj": "colwise",
|
| 38 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
| 39 |
+
"layers.*.self_attn.sinks": "local_rowwise",
|
| 40 |
+
"layers.*.mlp.experts": "gather",
|
| 41 |
+
"layers.*.mlp.router": "ep_router",
|
| 42 |
+
"layers.*.mlp.experts.gate_up_proj": "grouped_gemm",
|
| 43 |
+
"layers.*.mlp.experts.gate_up_proj_bias": "grouped_gemm",
|
| 44 |
+
"layers.*.mlp.experts.down_proj": "grouped_gemm",
|
| 45 |
+
"layers.*.mlp.experts.down_proj_bias": "grouped_gemm",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
num_hidden_layers: int = 36,
|
| 51 |
+
num_local_experts: int = 128,
|
| 52 |
+
vocab_size: int = 201088,
|
| 53 |
+
hidden_size: int = 2880,
|
| 54 |
+
intermediate_size: int = 2880,
|
| 55 |
+
head_dim: int = 64,
|
| 56 |
+
num_attention_heads: int = 64,
|
| 57 |
+
num_key_value_heads: int = 8,
|
| 58 |
+
sliding_window: int = 128,
|
| 59 |
+
rope_theta: float = 150000.0,
|
| 60 |
+
tie_word_embeddings=False,
|
| 61 |
+
hidden_act: str = "silu",
|
| 62 |
+
initializer_range: float = 0.02,
|
| 63 |
+
max_position_embeddings=131072,
|
| 64 |
+
rms_norm_eps: float = 1e-5,
|
| 65 |
+
rope_scaling={
|
| 66 |
+
"rope_type": "yarn",
|
| 67 |
+
"factor": 32.0,
|
| 68 |
+
"beta_fast": 32.0,
|
| 69 |
+
"beta_slow": 1.0,
|
| 70 |
+
"truncate": False,
|
| 71 |
+
"original_max_position_embeddings": 4096,
|
| 72 |
+
},
|
| 73 |
+
attention_dropout: float = 0.0,
|
| 74 |
+
num_experts_per_tok=4,
|
| 75 |
+
router_aux_loss_coef: float = 0.9,
|
| 76 |
+
output_router_logits=False,
|
| 77 |
+
use_cache=True,
|
| 78 |
+
layer_types=None,
|
| 79 |
+
**kwargs,
|
| 80 |
+
):
|
| 81 |
+
self.vocab_size = vocab_size
|
| 82 |
+
self.hidden_size = hidden_size
|
| 83 |
+
self.intermediate_size = intermediate_size
|
| 84 |
+
self.num_hidden_layers = num_hidden_layers
|
| 85 |
+
self.num_attention_heads = num_attention_heads
|
| 86 |
+
self.num_local_experts = num_local_experts
|
| 87 |
+
self.sliding_window = sliding_window
|
| 88 |
+
self.num_experts_per_tok = num_experts_per_tok
|
| 89 |
+
# for backward compatibility
|
| 90 |
+
if num_key_value_heads is None:
|
| 91 |
+
num_key_value_heads = num_attention_heads
|
| 92 |
+
|
| 93 |
+
self.num_key_value_heads = num_key_value_heads
|
| 94 |
+
self.hidden_act = hidden_act
|
| 95 |
+
self.initializer_range = initializer_range
|
| 96 |
+
self.rms_norm_eps = rms_norm_eps
|
| 97 |
+
self.rope_theta = rope_theta
|
| 98 |
+
self.rope_scaling = rope_scaling
|
| 99 |
+
self.attention_dropout = attention_dropout
|
| 100 |
+
self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
|
| 101 |
+
self.layer_types = layer_types
|
| 102 |
+
if self.layer_types is None:
|
| 103 |
+
self.layer_types = [
|
| 104 |
+
"sliding_attention" if bool((i + 1) % 2) else "full_attention" for i in range(self.num_hidden_layers)
|
| 105 |
+
]
|
| 106 |
+
layer_type_validation(self.layer_types, self.num_hidden_layers)
|
| 107 |
+
|
| 108 |
+
self.attention_bias = True
|
| 109 |
+
self.max_position_embeddings = max_position_embeddings
|
| 110 |
+
self.router_aux_loss_coef = router_aux_loss_coef
|
| 111 |
+
self.output_router_logits = output_router_logits
|
| 112 |
+
self.use_cache = use_cache
|
| 113 |
+
|
| 114 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 115 |
+
# BC: if there is a 'type' field, copy it it to 'rope_type'.
|
| 116 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
| 117 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
| 118 |
+
rope_config_validation(self)
|
| 119 |
+
|
| 120 |
+
super().__init__(
|
| 121 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 122 |
+
**kwargs,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
__all__ = ["GptOssConfig"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/gpt_oss/modeling_gpt_oss.py
ADDED
|
@@ -0,0 +1,725 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 2 |
+
# This file was automatically generated from src/transformers/models/gpt_oss/modular_gpt_oss.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_gpt_oss.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
from typing import Callable, Optional, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from torch import nn
|
| 25 |
+
from torch.nn import functional as F
|
| 26 |
+
|
| 27 |
+
from ...cache_utils import Cache, DynamicCache
|
| 28 |
+
from ...generation import GenerationMixin
|
| 29 |
+
from ...integrations.hub_kernels import use_kernel_forward_from_hub
|
| 30 |
+
from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
| 31 |
+
from ...modeling_layers import (
|
| 32 |
+
GenericForSequenceClassification,
|
| 33 |
+
GenericForTokenClassification,
|
| 34 |
+
GradientCheckpointingLayer,
|
| 35 |
+
)
|
| 36 |
+
from ...modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
|
| 37 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 38 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 39 |
+
from ...processing_utils import Unpack
|
| 40 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 41 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 42 |
+
from ...utils.generic import OutputRecorder, check_model_inputs
|
| 43 |
+
from .configuration_gpt_oss import GptOssConfig
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 47 |
+
class GptOssRMSNorm(nn.Module):
|
| 48 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 49 |
+
"""
|
| 50 |
+
GptOssRMSNorm is equivalent to T5LayerNorm
|
| 51 |
+
"""
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 54 |
+
self.variance_epsilon = eps
|
| 55 |
+
|
| 56 |
+
def forward(self, hidden_states):
|
| 57 |
+
input_dtype = hidden_states.dtype
|
| 58 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 59 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 60 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 61 |
+
return (self.weight * hidden_states).to(input_dtype) # main diff with Llama
|
| 62 |
+
|
| 63 |
+
def extra_repr(self):
|
| 64 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class GptOssExperts(nn.Module):
|
| 68 |
+
def __init__(self, config):
|
| 69 |
+
super().__init__()
|
| 70 |
+
self.intermediate_size = config.intermediate_size
|
| 71 |
+
self.num_experts = config.num_local_experts
|
| 72 |
+
self.hidden_size = config.hidden_size
|
| 73 |
+
self.expert_dim = self.intermediate_size
|
| 74 |
+
self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_size, 2 * self.expert_dim))
|
| 75 |
+
self.gate_up_proj_bias = nn.Parameter(torch.empty(self.num_experts, 2 * self.expert_dim))
|
| 76 |
+
self.down_proj = nn.Parameter(torch.empty((self.num_experts, self.expert_dim, self.hidden_size)))
|
| 77 |
+
self.down_proj_bias = nn.Parameter(torch.empty(self.num_experts, self.hidden_size))
|
| 78 |
+
self.alpha = 1.702
|
| 79 |
+
self.limit = 7.0
|
| 80 |
+
|
| 81 |
+
def forward(self, hidden_states: torch.Tensor, router_indices=None, routing_weights=None) -> torch.Tensor:
|
| 82 |
+
"""
|
| 83 |
+
When training it is more efficient to just loop over the experts and compute the output for each expert
|
| 84 |
+
as otherwise the memory would explode.
|
| 85 |
+
|
| 86 |
+
For inference we can sacrifice some memory and compute the output for all experts at once. By repeating the inputs.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
hidden_states (torch.Tensor): (batch_size, seq_len, hidden_size)
|
| 90 |
+
selected_experts (torch.Tensor): (batch_size * token_num, top_k)
|
| 91 |
+
routing_weights (torch.Tensor): (batch_size * token_num, num_experts)
|
| 92 |
+
Returns:
|
| 93 |
+
torch.Tensor
|
| 94 |
+
"""
|
| 95 |
+
batch_size = hidden_states.shape[0]
|
| 96 |
+
hidden_states = hidden_states.reshape(-1, self.hidden_size) # (num_tokens, hidden_size)
|
| 97 |
+
num_experts = routing_weights.shape[1]
|
| 98 |
+
if hidden_states.device.type == "cpu" or self.training:
|
| 99 |
+
next_states = torch.zeros_like(hidden_states, dtype=hidden_states.dtype, device=hidden_states.device)
|
| 100 |
+
with torch.no_grad():
|
| 101 |
+
expert_mask = torch.nn.functional.one_hot(
|
| 102 |
+
router_indices, num_classes=num_experts + 1
|
| 103 |
+
) # masking is also a class
|
| 104 |
+
expert_mask = expert_mask.permute(2, 1, 0)
|
| 105 |
+
# we sum on the top_k and on the sequence length to get which experts
|
| 106 |
+
# are hit this time around
|
| 107 |
+
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
|
| 108 |
+
for expert_idx in expert_hit[:]:
|
| 109 |
+
# expert_idx only have 1 element, so we can use scale for fast indexing
|
| 110 |
+
expert_idx = expert_idx[0]
|
| 111 |
+
# skip masking index
|
| 112 |
+
if expert_idx == num_experts:
|
| 113 |
+
continue
|
| 114 |
+
with torch.no_grad():
|
| 115 |
+
_, token_idx = torch.where(expert_mask[expert_idx])
|
| 116 |
+
current_state = hidden_states[token_idx]
|
| 117 |
+
gate_up = current_state @ self.gate_up_proj[expert_idx] + self.gate_up_proj_bias[expert_idx]
|
| 118 |
+
gate, up = gate_up[..., ::2], gate_up[..., 1::2]
|
| 119 |
+
gate = gate.clamp(min=None, max=self.limit)
|
| 120 |
+
up = up.clamp(min=-self.limit, max=self.limit)
|
| 121 |
+
glu = gate * torch.sigmoid(gate * self.alpha)
|
| 122 |
+
gated_output = (up + 1) * glu
|
| 123 |
+
out = gated_output @ self.down_proj[expert_idx] + self.down_proj_bias[expert_idx]
|
| 124 |
+
weighted_output = out * routing_weights[token_idx, expert_idx, None]
|
| 125 |
+
next_states.index_add_(0, token_idx, weighted_output.to(hidden_states.dtype))
|
| 126 |
+
next_states = next_states.view(batch_size, -1, self.hidden_size)
|
| 127 |
+
else:
|
| 128 |
+
hidden_states = hidden_states.repeat(num_experts, 1)
|
| 129 |
+
hidden_states = hidden_states.view(num_experts, -1, self.hidden_size)
|
| 130 |
+
gate_up = torch.bmm(hidden_states, self.gate_up_proj) + self.gate_up_proj_bias[..., None, :]
|
| 131 |
+
gate, up = gate_up[..., ::2], gate_up[..., 1::2]
|
| 132 |
+
gate = gate.clamp(min=None, max=self.limit)
|
| 133 |
+
up = up.clamp(min=-self.limit, max=self.limit)
|
| 134 |
+
glu = gate * torch.sigmoid(gate * self.alpha)
|
| 135 |
+
next_states = torch.bmm(((up + 1) * glu), self.down_proj)
|
| 136 |
+
next_states = next_states + self.down_proj_bias[..., None, :]
|
| 137 |
+
next_states = next_states.view(num_experts, batch_size, -1, self.hidden_size)
|
| 138 |
+
next_states = next_states * routing_weights.transpose(0, 1).view(num_experts, batch_size, -1)[..., None]
|
| 139 |
+
next_states = next_states.sum(dim=0)
|
| 140 |
+
return next_states
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class GptOssTopKRouter(nn.Module):
|
| 144 |
+
def __init__(self, config):
|
| 145 |
+
super().__init__()
|
| 146 |
+
self.top_k = config.num_experts_per_tok
|
| 147 |
+
self.num_experts = config.num_local_experts
|
| 148 |
+
self.hidden_dim = config.hidden_size
|
| 149 |
+
self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim))
|
| 150 |
+
self.bias = nn.Parameter(torch.empty(self.num_experts))
|
| 151 |
+
|
| 152 |
+
def forward(self, hidden_states):
|
| 153 |
+
hidden_states = hidden_states.reshape(-1, self.hidden_dim)
|
| 154 |
+
router_logits = F.linear(hidden_states, self.weight, self.bias) # (seq_len, num_experts)
|
| 155 |
+
router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=-1) # (seq_len, top_k)
|
| 156 |
+
router_top_value = torch.nn.functional.softmax(router_top_value, dim=1, dtype=router_top_value.dtype)
|
| 157 |
+
router_scores = torch.zeros_like(router_logits).scatter_(1, router_indices, router_top_value)
|
| 158 |
+
return router_scores, router_indices
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@use_kernel_forward_from_hub("MegaBlocksMoeMLP")
|
| 162 |
+
class GptOssMLP(nn.Module):
|
| 163 |
+
def __init__(self, config):
|
| 164 |
+
super().__init__()
|
| 165 |
+
self.router = GptOssTopKRouter(config)
|
| 166 |
+
self.experts = GptOssExperts(config)
|
| 167 |
+
|
| 168 |
+
def forward(self, hidden_states):
|
| 169 |
+
router_scores, router_indices = self.router(hidden_states) # (num_experts, seq_len)
|
| 170 |
+
routed_out = self.experts(hidden_states, router_indices=router_indices, routing_weights=router_scores)
|
| 171 |
+
return routed_out, router_scores
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class GptOssRotaryEmbedding(nn.Module):
|
| 175 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 176 |
+
|
| 177 |
+
def __init__(self, config: GptOssConfig, device=None):
|
| 178 |
+
super().__init__()
|
| 179 |
+
# BC: "rope_type" was originally "type"
|
| 180 |
+
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
|
| 181 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 182 |
+
else:
|
| 183 |
+
self.rope_type = "default"
|
| 184 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 185 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 186 |
+
|
| 187 |
+
self.config = config
|
| 188 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 189 |
+
|
| 190 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
| 191 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 192 |
+
self.original_inv_freq = self.inv_freq
|
| 193 |
+
|
| 194 |
+
@torch.no_grad()
|
| 195 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 196 |
+
def forward(self, x, position_ids):
|
| 197 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 198 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 199 |
+
|
| 200 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 201 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 202 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 203 |
+
emb = freqs
|
| 204 |
+
cos = emb.cos() * self.attention_scaling
|
| 205 |
+
sin = emb.sin() * self.attention_scaling
|
| 206 |
+
|
| 207 |
+
return cos.to(x.dtype), sin.to(x.dtype)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 211 |
+
"""
|
| 212 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 213 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 214 |
+
"""
|
| 215 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 216 |
+
if n_rep == 1:
|
| 217 |
+
return hidden_states
|
| 218 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 219 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _apply_rotary_emb(
|
| 223 |
+
x: torch.Tensor,
|
| 224 |
+
cos: torch.Tensor,
|
| 225 |
+
sin: torch.Tensor,
|
| 226 |
+
) -> torch.Tensor:
|
| 227 |
+
first_half, second_half = torch.chunk(x, 2, dim=-1)
|
| 228 |
+
first_ = first_half * cos - second_half * sin
|
| 229 |
+
second_ = second_half * cos + first_half * sin
|
| 230 |
+
return torch.cat((first_, second_), dim=-1)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 234 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 235 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 236 |
+
q_embed = _apply_rotary_emb(q, cos, sin)
|
| 237 |
+
k_embed = _apply_rotary_emb(k, cos, sin)
|
| 238 |
+
return q_embed, k_embed
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def eager_attention_forward(
|
| 242 |
+
module: nn.Module,
|
| 243 |
+
query: torch.Tensor,
|
| 244 |
+
key: torch.Tensor,
|
| 245 |
+
value: torch.Tensor,
|
| 246 |
+
attention_mask: Optional[torch.Tensor],
|
| 247 |
+
scaling: float,
|
| 248 |
+
dropout: float = 0.0,
|
| 249 |
+
**kwargs,
|
| 250 |
+
):
|
| 251 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 252 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 253 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 254 |
+
if attention_mask is not None:
|
| 255 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 256 |
+
attn_weights = attn_weights + causal_mask
|
| 257 |
+
|
| 258 |
+
sinks = module.sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
|
| 259 |
+
combined_logits = torch.cat([attn_weights, sinks], dim=-1)
|
| 260 |
+
|
| 261 |
+
# This was not in the original implementation and slightly affect results; it prevents overflow in BF16/FP16
|
| 262 |
+
# when training with bsz>1 we clamp max values.
|
| 263 |
+
|
| 264 |
+
combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
|
| 265 |
+
probs = F.softmax(combined_logits, dim=-1, dtype=combined_logits.dtype)
|
| 266 |
+
scores = probs[..., :-1] # we drop the sink here
|
| 267 |
+
attn_weights = nn.functional.dropout(scores, p=dropout, training=module.training)
|
| 268 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 269 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 270 |
+
return attn_output, attn_weights
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class GptOssAttention(nn.Module):
|
| 274 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 275 |
+
|
| 276 |
+
def __init__(self, config: GptOssConfig, layer_idx: int):
|
| 277 |
+
super().__init__()
|
| 278 |
+
self.config = config
|
| 279 |
+
self.layer_idx = layer_idx
|
| 280 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 281 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 282 |
+
self.scaling = self.head_dim**-0.5
|
| 283 |
+
self.attention_dropout = config.attention_dropout
|
| 284 |
+
self.is_causal = True
|
| 285 |
+
self.q_proj = nn.Linear(
|
| 286 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 287 |
+
)
|
| 288 |
+
self.k_proj = nn.Linear(
|
| 289 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 290 |
+
)
|
| 291 |
+
self.v_proj = nn.Linear(
|
| 292 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 293 |
+
)
|
| 294 |
+
self.o_proj = nn.Linear(
|
| 295 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 296 |
+
)
|
| 297 |
+
self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
|
| 298 |
+
self.sinks = nn.Parameter(torch.empty(config.num_attention_heads))
|
| 299 |
+
|
| 300 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 301 |
+
def forward(
|
| 302 |
+
self,
|
| 303 |
+
hidden_states: torch.Tensor,
|
| 304 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 305 |
+
attention_mask: Optional[torch.Tensor],
|
| 306 |
+
past_key_values: Optional[Cache] = None,
|
| 307 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 308 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 309 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 310 |
+
input_shape = hidden_states.shape[:-1]
|
| 311 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 312 |
+
|
| 313 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 314 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 315 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 316 |
+
|
| 317 |
+
cos, sin = position_embeddings
|
| 318 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 319 |
+
|
| 320 |
+
if past_key_values is not None:
|
| 321 |
+
cache_kwargs = {"cache_position": cache_position}
|
| 322 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 323 |
+
|
| 324 |
+
attention_interface: Callable = eager_attention_forward
|
| 325 |
+
if self.config._attn_implementation != "eager":
|
| 326 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 327 |
+
|
| 328 |
+
attn_output, attn_weights = attention_interface(
|
| 329 |
+
self,
|
| 330 |
+
query_states,
|
| 331 |
+
key_states,
|
| 332 |
+
value_states,
|
| 333 |
+
attention_mask,
|
| 334 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 335 |
+
scaling=self.scaling,
|
| 336 |
+
sliding_window=self.sliding_window,
|
| 337 |
+
s_aux=self.sinks, # diff with Llama
|
| 338 |
+
**kwargs,
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 342 |
+
attn_output = self.o_proj(attn_output)
|
| 343 |
+
return attn_output, attn_weights
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class GptOssDecoderLayer(GradientCheckpointingLayer):
|
| 347 |
+
def __init__(self, config: GptOssConfig, layer_idx: int):
|
| 348 |
+
super().__init__()
|
| 349 |
+
self.hidden_size = config.hidden_size
|
| 350 |
+
self.self_attn = GptOssAttention(config=config, layer_idx=layer_idx)
|
| 351 |
+
self.mlp = GptOssMLP(config)
|
| 352 |
+
self.input_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 353 |
+
self.post_attention_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 354 |
+
self.attention_type = config.layer_types[layer_idx]
|
| 355 |
+
|
| 356 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 357 |
+
def forward(
|
| 358 |
+
self,
|
| 359 |
+
hidden_states: torch.Tensor,
|
| 360 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 361 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 362 |
+
past_key_values: Optional[Cache] = None,
|
| 363 |
+
use_cache: Optional[bool] = False,
|
| 364 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 365 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 366 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 367 |
+
) -> torch.Tensor:
|
| 368 |
+
residual = hidden_states
|
| 369 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 370 |
+
# Self Attention
|
| 371 |
+
hidden_states, _ = self.self_attn(
|
| 372 |
+
hidden_states=hidden_states,
|
| 373 |
+
attention_mask=attention_mask,
|
| 374 |
+
position_ids=position_ids,
|
| 375 |
+
past_key_values=past_key_values,
|
| 376 |
+
use_cache=use_cache,
|
| 377 |
+
cache_position=cache_position,
|
| 378 |
+
position_embeddings=position_embeddings,
|
| 379 |
+
**kwargs,
|
| 380 |
+
)
|
| 381 |
+
hidden_states = residual + hidden_states
|
| 382 |
+
|
| 383 |
+
# Fully Connected
|
| 384 |
+
residual = hidden_states
|
| 385 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 386 |
+
hidden_states, _ = self.mlp(hidden_states) # diff with llama: router scores
|
| 387 |
+
hidden_states = residual + hidden_states
|
| 388 |
+
return hidden_states
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
@auto_docstring
|
| 392 |
+
class GptOssPreTrainedModel(PreTrainedModel):
|
| 393 |
+
config: GptOssConfig
|
| 394 |
+
base_model_prefix = "model"
|
| 395 |
+
supports_gradient_checkpointing = True
|
| 396 |
+
_no_split_modules = ["GptOssDecoderLayer"]
|
| 397 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 398 |
+
_supports_flash_attn = True
|
| 399 |
+
_supports_sdpa = False
|
| 400 |
+
_supports_flex_attn = True
|
| 401 |
+
|
| 402 |
+
_can_compile_fullgraph = True
|
| 403 |
+
_supports_attention_backend = True
|
| 404 |
+
_can_record_outputs = {
|
| 405 |
+
"router_logits": OutputRecorder(GptOssTopKRouter, index=0),
|
| 406 |
+
"hidden_states": GptOssDecoderLayer,
|
| 407 |
+
"attentions": GptOssAttention,
|
| 408 |
+
}
|
| 409 |
+
_keep_in_fp32_modules = ["post_attention_layernorm", "input_layernorm", "norm"]
|
| 410 |
+
_supports_flash_attention = False
|
| 411 |
+
_supports_flex_attention = False
|
| 412 |
+
|
| 413 |
+
def _init_weights(self, module):
|
| 414 |
+
std = self.config.initializer_range
|
| 415 |
+
if isinstance(module, nn.Linear):
|
| 416 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 417 |
+
if module.bias is not None:
|
| 418 |
+
module.bias.data.zero_()
|
| 419 |
+
elif isinstance(module, nn.Parameter):
|
| 420 |
+
module.data.normal_(mean=0.0, std=std)
|
| 421 |
+
elif isinstance(module, nn.Embedding):
|
| 422 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 423 |
+
if module.padding_idx is not None:
|
| 424 |
+
module.weight.data[module.padding_idx].zero_()
|
| 425 |
+
elif isinstance(module, GptOssRMSNorm):
|
| 426 |
+
module.weight.data.fill_(1.0)
|
| 427 |
+
elif isinstance(module, GptOssExperts):
|
| 428 |
+
module.gate_up_proj.data.normal_(mean=0.0, std=std)
|
| 429 |
+
module.gate_up_proj_bias.data.zero_()
|
| 430 |
+
module.down_proj.data.normal_(mean=0.0, std=std)
|
| 431 |
+
module.down_proj_bias.data.zero_()
|
| 432 |
+
elif isinstance(module, GptOssAttention):
|
| 433 |
+
module.sinks.data.normal_(mean=0.0, std=std)
|
| 434 |
+
elif isinstance(module, GptOssTopKRouter):
|
| 435 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 436 |
+
module.bias.data.normal_(mean=0.0, std=std)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
@auto_docstring
|
| 440 |
+
class GptOssModel(GptOssPreTrainedModel):
|
| 441 |
+
_no_split_modules = ["GptOssDecoderLayer"]
|
| 442 |
+
|
| 443 |
+
def __init__(self, config: GptOssConfig):
|
| 444 |
+
super().__init__(config)
|
| 445 |
+
self.padding_idx = config.pad_token_id
|
| 446 |
+
self.vocab_size = config.vocab_size
|
| 447 |
+
|
| 448 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 449 |
+
self.layers = nn.ModuleList(
|
| 450 |
+
[GptOssDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 451 |
+
)
|
| 452 |
+
self.norm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 453 |
+
self.rotary_emb = GptOssRotaryEmbedding(config=config)
|
| 454 |
+
self.gradient_checkpointing = False
|
| 455 |
+
|
| 456 |
+
# Initialize weights and apply final processing
|
| 457 |
+
self.post_init()
|
| 458 |
+
|
| 459 |
+
@check_model_inputs
|
| 460 |
+
@auto_docstring
|
| 461 |
+
def forward(
|
| 462 |
+
self,
|
| 463 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 464 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 465 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 466 |
+
past_key_values: Optional[Cache] = None,
|
| 467 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 468 |
+
use_cache: Optional[bool] = None,
|
| 469 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 470 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 471 |
+
) -> MoeModelOutputWithPast:
|
| 472 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 473 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 474 |
+
|
| 475 |
+
if use_cache and past_key_values is None:
|
| 476 |
+
past_key_values = DynamicCache(config=self.config)
|
| 477 |
+
|
| 478 |
+
if inputs_embeds is None:
|
| 479 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 480 |
+
|
| 481 |
+
if cache_position is None:
|
| 482 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 483 |
+
cache_position = torch.arange(
|
| 484 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 485 |
+
)
|
| 486 |
+
if position_ids is None:
|
| 487 |
+
position_ids = cache_position.unsqueeze(0)
|
| 488 |
+
|
| 489 |
+
# It may already have been prepared by e.g. `generate`
|
| 490 |
+
if not isinstance(causal_mask_mapping := attention_mask, dict):
|
| 491 |
+
mask_kwargs = {
|
| 492 |
+
"config": self.config,
|
| 493 |
+
"input_embeds": inputs_embeds,
|
| 494 |
+
"attention_mask": attention_mask,
|
| 495 |
+
"cache_position": cache_position,
|
| 496 |
+
"past_key_values": past_key_values,
|
| 497 |
+
}
|
| 498 |
+
causal_mask_mapping = {
|
| 499 |
+
"full_attention": create_causal_mask(**mask_kwargs),
|
| 500 |
+
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
hidden_states = inputs_embeds
|
| 504 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 505 |
+
|
| 506 |
+
for decoder_layer in self.layers:
|
| 507 |
+
hidden_states = decoder_layer(
|
| 508 |
+
hidden_states,
|
| 509 |
+
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
|
| 510 |
+
position_ids=position_ids,
|
| 511 |
+
past_key_values=past_key_values,
|
| 512 |
+
use_cache=use_cache,
|
| 513 |
+
cache_position=cache_position,
|
| 514 |
+
position_embeddings=position_embeddings,
|
| 515 |
+
**kwargs,
|
| 516 |
+
)
|
| 517 |
+
hidden_states = self.norm(hidden_states)
|
| 518 |
+
return MoeModelOutputWithPast(
|
| 519 |
+
last_hidden_state=hidden_states,
|
| 520 |
+
past_key_values=past_key_values,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def load_balancing_loss_func(
|
| 525 |
+
gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
|
| 526 |
+
num_experts: Optional[int] = None,
|
| 527 |
+
top_k=2,
|
| 528 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 529 |
+
) -> Union[torch.Tensor, int]:
|
| 530 |
+
r"""
|
| 531 |
+
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
|
| 532 |
+
|
| 533 |
+
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
|
| 534 |
+
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
|
| 535 |
+
experts is too unbalanced.
|
| 536 |
+
|
| 537 |
+
Args:
|
| 538 |
+
gate_logits:
|
| 539 |
+
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
|
| 540 |
+
shape [batch_size X sequence_length, num_experts].
|
| 541 |
+
num_experts:
|
| 542 |
+
Number of experts
|
| 543 |
+
top_k:
|
| 544 |
+
The number of experts to route per-token, can be also interpreted as the `top-k` routing
|
| 545 |
+
parameter.
|
| 546 |
+
attention_mask (`torch.Tensor`, *optional*):
|
| 547 |
+
The attention_mask used in forward function
|
| 548 |
+
shape [batch_size X sequence_length] if not None.
|
| 549 |
+
|
| 550 |
+
Returns:
|
| 551 |
+
The auxiliary loss.
|
| 552 |
+
"""
|
| 553 |
+
if gate_logits is None or not isinstance(gate_logits, tuple):
|
| 554 |
+
return 0
|
| 555 |
+
|
| 556 |
+
if isinstance(gate_logits, tuple):
|
| 557 |
+
compute_device = gate_logits[0].device
|
| 558 |
+
concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
|
| 559 |
+
|
| 560 |
+
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
|
| 561 |
+
|
| 562 |
+
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
|
| 563 |
+
|
| 564 |
+
expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
|
| 565 |
+
|
| 566 |
+
if attention_mask is None:
|
| 567 |
+
# Compute the percentage of tokens routed to each experts
|
| 568 |
+
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
|
| 569 |
+
|
| 570 |
+
# Compute the average probability of routing to these experts
|
| 571 |
+
router_prob_per_expert = torch.mean(routing_weights, dim=0)
|
| 572 |
+
else:
|
| 573 |
+
batch_size, sequence_length = attention_mask.shape
|
| 574 |
+
num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
|
| 575 |
+
|
| 576 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
|
| 577 |
+
expert_attention_mask = (
|
| 578 |
+
attention_mask[None, :, :, None, None]
|
| 579 |
+
.expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
|
| 580 |
+
.reshape(-1, top_k, num_experts)
|
| 581 |
+
.to(compute_device)
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
# Compute the percentage of tokens routed to each experts
|
| 585 |
+
tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
|
| 586 |
+
expert_attention_mask, dim=0
|
| 587 |
+
)
|
| 588 |
+
|
| 589 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
|
| 590 |
+
router_per_expert_attention_mask = (
|
| 591 |
+
attention_mask[None, :, :, None]
|
| 592 |
+
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
|
| 593 |
+
.reshape(-1, num_experts)
|
| 594 |
+
.to(compute_device)
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
# Compute the average probability of routing to these experts
|
| 598 |
+
router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
|
| 599 |
+
router_per_expert_attention_mask, dim=0
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
|
| 603 |
+
return overall_loss * num_experts
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
@auto_docstring
|
| 607 |
+
class GptOssForCausalLM(GptOssPreTrainedModel, GenerationMixin):
|
| 608 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 609 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
| 610 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 611 |
+
|
| 612 |
+
def __init__(self, config):
|
| 613 |
+
super().__init__(config)
|
| 614 |
+
self.model = GptOssModel(config)
|
| 615 |
+
self.vocab_size = config.vocab_size
|
| 616 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 617 |
+
self.router_aux_loss_coef = config.router_aux_loss_coef
|
| 618 |
+
self.num_experts = config.num_local_experts
|
| 619 |
+
self.num_experts_per_tok = config.num_experts_per_tok
|
| 620 |
+
|
| 621 |
+
# Initialize weights and apply final processing
|
| 622 |
+
self.post_init()
|
| 623 |
+
|
| 624 |
+
@can_return_tuple
|
| 625 |
+
@auto_docstring
|
| 626 |
+
def forward(
|
| 627 |
+
self,
|
| 628 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 629 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 630 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 631 |
+
past_key_values: Optional[Cache] = None,
|
| 632 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 633 |
+
labels: Optional[torch.LongTensor] = None,
|
| 634 |
+
use_cache: Optional[bool] = None,
|
| 635 |
+
output_router_logits: Optional[bool] = None,
|
| 636 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 637 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 638 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 639 |
+
) -> MoeCausalLMOutputWithPast:
|
| 640 |
+
r"""
|
| 641 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 642 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 643 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 644 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 645 |
+
|
| 646 |
+
Example:
|
| 647 |
+
|
| 648 |
+
```python
|
| 649 |
+
>>> from transformers import AutoTokenizer, GptOssForCausalLM
|
| 650 |
+
|
| 651 |
+
>>> model = GptOssForCausalLM.from_pretrained("mistralai/GptOss-8x7B-v0.1")
|
| 652 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/GptOss-8x7B-v0.1")
|
| 653 |
+
|
| 654 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 655 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 656 |
+
|
| 657 |
+
>>> # Generate
|
| 658 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 659 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 660 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 661 |
+
```"""
|
| 662 |
+
|
| 663 |
+
output_router_logits = (
|
| 664 |
+
output_router_logits if output_router_logits is not None else self.config.output_router_logits
|
| 665 |
+
)
|
| 666 |
+
|
| 667 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 668 |
+
outputs: MoeModelOutputWithPast = self.model(
|
| 669 |
+
input_ids=input_ids,
|
| 670 |
+
attention_mask=attention_mask,
|
| 671 |
+
position_ids=position_ids,
|
| 672 |
+
past_key_values=past_key_values,
|
| 673 |
+
inputs_embeds=inputs_embeds,
|
| 674 |
+
use_cache=use_cache,
|
| 675 |
+
output_router_logits=output_router_logits,
|
| 676 |
+
cache_position=cache_position,
|
| 677 |
+
**kwargs,
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
hidden_states = outputs.last_hidden_state
|
| 681 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 682 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 683 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 684 |
+
|
| 685 |
+
loss = None
|
| 686 |
+
if labels is not None:
|
| 687 |
+
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
| 688 |
+
|
| 689 |
+
aux_loss = None
|
| 690 |
+
if output_router_logits:
|
| 691 |
+
aux_loss = load_balancing_loss_func(
|
| 692 |
+
outputs.router_logits,
|
| 693 |
+
self.num_experts,
|
| 694 |
+
self.num_experts_per_tok,
|
| 695 |
+
attention_mask,
|
| 696 |
+
)
|
| 697 |
+
if labels is not None:
|
| 698 |
+
loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
|
| 699 |
+
|
| 700 |
+
return MoeCausalLMOutputWithPast(
|
| 701 |
+
loss=loss,
|
| 702 |
+
aux_loss=aux_loss,
|
| 703 |
+
logits=logits,
|
| 704 |
+
past_key_values=outputs.past_key_values,
|
| 705 |
+
hidden_states=outputs.hidden_states,
|
| 706 |
+
attentions=outputs.attentions,
|
| 707 |
+
router_logits=outputs.router_logits,
|
| 708 |
+
)
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
class GptOssForSequenceClassification(GenericForSequenceClassification, GptOssPreTrainedModel):
|
| 712 |
+
pass
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
class GptOssForTokenClassification(GenericForTokenClassification, GptOssPreTrainedModel):
|
| 716 |
+
pass
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
__all__ = [
|
| 720 |
+
"GptOssForCausalLM",
|
| 721 |
+
"GptOssForSequenceClassification",
|
| 722 |
+
"GptOssForTokenClassification",
|
| 723 |
+
"GptOssModel",
|
| 724 |
+
"GptOssPreTrainedModel",
|
| 725 |
+
]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
from typing import Callable, Optional
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import nn
|
| 19 |
+
from torch.nn import functional as F
|
| 20 |
+
|
| 21 |
+
from ...cache_utils import Cache, DynamicCache
|
| 22 |
+
from ...integrations.hub_kernels import use_kernel_forward_from_hub
|
| 23 |
+
from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
| 24 |
+
from ...modeling_outputs import (
|
| 25 |
+
MoeModelOutputWithPast,
|
| 26 |
+
)
|
| 27 |
+
from ...modeling_rope_utils import dynamic_rope_update
|
| 28 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
|
| 29 |
+
from ...processing_utils import Unpack
|
| 30 |
+
from ...utils import (
|
| 31 |
+
TransformersKwargs,
|
| 32 |
+
auto_docstring,
|
| 33 |
+
logging,
|
| 34 |
+
)
|
| 35 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 36 |
+
from ...utils.generic import OutputRecorder, check_model_inputs
|
| 37 |
+
from ..llama.modeling_llama import (
|
| 38 |
+
LlamaDecoderLayer,
|
| 39 |
+
LlamaPreTrainedModel,
|
| 40 |
+
LlamaRMSNorm,
|
| 41 |
+
LlamaRotaryEmbedding,
|
| 42 |
+
repeat_kv,
|
| 43 |
+
)
|
| 44 |
+
from ..mixtral.modeling_mixtral import (
|
| 45 |
+
MixtralForCausalLM,
|
| 46 |
+
MixtralForSequenceClassification,
|
| 47 |
+
MixtralForTokenClassification,
|
| 48 |
+
MixtralModel,
|
| 49 |
+
)
|
| 50 |
+
from ..qwen2.modeling_qwen2 import Qwen2Attention
|
| 51 |
+
from .configuration_gpt_oss import GptOssConfig
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
logger = logging.get_logger(__name__)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class GptOssRMSNorm(LlamaRMSNorm):
|
| 58 |
+
def forward(self, hidden_states):
|
| 59 |
+
input_dtype = hidden_states.dtype
|
| 60 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 61 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 62 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 63 |
+
return (self.weight * hidden_states).to(input_dtype) # main diff with Llama
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class GptOssExperts(nn.Module):
|
| 67 |
+
def __init__(self, config):
|
| 68 |
+
super().__init__()
|
| 69 |
+
self.intermediate_size = config.intermediate_size
|
| 70 |
+
self.num_experts = config.num_local_experts
|
| 71 |
+
self.hidden_size = config.hidden_size
|
| 72 |
+
self.expert_dim = self.intermediate_size
|
| 73 |
+
self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_size, 2 * self.expert_dim))
|
| 74 |
+
self.gate_up_proj_bias = nn.Parameter(torch.empty(self.num_experts, 2 * self.expert_dim))
|
| 75 |
+
self.down_proj = nn.Parameter(torch.empty((self.num_experts, self.expert_dim, self.hidden_size)))
|
| 76 |
+
self.down_proj_bias = nn.Parameter(torch.empty(self.num_experts, self.hidden_size))
|
| 77 |
+
self.alpha = 1.702
|
| 78 |
+
self.limit = 7.0
|
| 79 |
+
|
| 80 |
+
def forward(self, hidden_states: torch.Tensor, router_indices=None, routing_weights=None) -> torch.Tensor:
|
| 81 |
+
"""
|
| 82 |
+
When training it is more efficient to just loop over the experts and compute the output for each expert
|
| 83 |
+
as otherwise the memory would explode.
|
| 84 |
+
|
| 85 |
+
For inference we can sacrifice some memory and compute the output for all experts at once. By repeating the inputs.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
hidden_states (torch.Tensor): (batch_size, seq_len, hidden_size)
|
| 89 |
+
selected_experts (torch.Tensor): (batch_size * token_num, top_k)
|
| 90 |
+
routing_weights (torch.Tensor): (batch_size * token_num, num_experts)
|
| 91 |
+
Returns:
|
| 92 |
+
torch.Tensor
|
| 93 |
+
"""
|
| 94 |
+
batch_size = hidden_states.shape[0]
|
| 95 |
+
hidden_states = hidden_states.reshape(-1, self.hidden_size) # (num_tokens, hidden_size)
|
| 96 |
+
num_experts = routing_weights.shape[1]
|
| 97 |
+
if hidden_states.device.type == "cpu" or self.training:
|
| 98 |
+
next_states = torch.zeros_like(hidden_states, dtype=hidden_states.dtype, device=hidden_states.device)
|
| 99 |
+
with torch.no_grad():
|
| 100 |
+
expert_mask = torch.nn.functional.one_hot(
|
| 101 |
+
router_indices, num_classes=num_experts + 1
|
| 102 |
+
) # masking is also a class
|
| 103 |
+
expert_mask = expert_mask.permute(2, 1, 0)
|
| 104 |
+
# we sum on the top_k and on the sequence length to get which experts
|
| 105 |
+
# are hit this time around
|
| 106 |
+
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
|
| 107 |
+
for expert_idx in expert_hit[:]:
|
| 108 |
+
# expert_idx only have 1 element, so we can use scale for fast indexing
|
| 109 |
+
expert_idx = expert_idx[0]
|
| 110 |
+
# skip masking index
|
| 111 |
+
if expert_idx == num_experts:
|
| 112 |
+
continue
|
| 113 |
+
with torch.no_grad():
|
| 114 |
+
_, token_idx = torch.where(expert_mask[expert_idx])
|
| 115 |
+
current_state = hidden_states[token_idx]
|
| 116 |
+
gate_up = current_state @ self.gate_up_proj[expert_idx] + self.gate_up_proj_bias[expert_idx]
|
| 117 |
+
gate, up = gate_up[..., ::2], gate_up[..., 1::2]
|
| 118 |
+
gate = gate.clamp(min=None, max=self.limit)
|
| 119 |
+
up = up.clamp(min=-self.limit, max=self.limit)
|
| 120 |
+
glu = gate * torch.sigmoid(gate * self.alpha)
|
| 121 |
+
gated_output = (up + 1) * glu
|
| 122 |
+
out = gated_output @ self.down_proj[expert_idx] + self.down_proj_bias[expert_idx]
|
| 123 |
+
weighted_output = out * routing_weights[token_idx, expert_idx, None]
|
| 124 |
+
next_states.index_add_(0, token_idx, weighted_output.to(hidden_states.dtype))
|
| 125 |
+
next_states = next_states.view(batch_size, -1, self.hidden_size)
|
| 126 |
+
else:
|
| 127 |
+
hidden_states = hidden_states.repeat(num_experts, 1)
|
| 128 |
+
hidden_states = hidden_states.view(num_experts, -1, self.hidden_size)
|
| 129 |
+
gate_up = torch.bmm(hidden_states, self.gate_up_proj) + self.gate_up_proj_bias[..., None, :]
|
| 130 |
+
gate, up = gate_up[..., ::2], gate_up[..., 1::2]
|
| 131 |
+
gate = gate.clamp(min=None, max=self.limit)
|
| 132 |
+
up = up.clamp(min=-self.limit, max=self.limit)
|
| 133 |
+
glu = gate * torch.sigmoid(gate * self.alpha)
|
| 134 |
+
next_states = torch.bmm(((up + 1) * glu), self.down_proj)
|
| 135 |
+
next_states = next_states + self.down_proj_bias[..., None, :]
|
| 136 |
+
next_states = next_states.view(num_experts, batch_size, -1, self.hidden_size)
|
| 137 |
+
next_states = next_states * routing_weights.transpose(0, 1).view(num_experts, batch_size, -1)[..., None]
|
| 138 |
+
next_states = next_states.sum(dim=0)
|
| 139 |
+
return next_states
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class GptOssTopKRouter(nn.Module):
|
| 143 |
+
def __init__(self, config):
|
| 144 |
+
super().__init__()
|
| 145 |
+
self.top_k = config.num_experts_per_tok
|
| 146 |
+
self.num_experts = config.num_local_experts
|
| 147 |
+
self.hidden_dim = config.hidden_size
|
| 148 |
+
self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim))
|
| 149 |
+
self.bias = nn.Parameter(torch.empty(self.num_experts))
|
| 150 |
+
|
| 151 |
+
def forward(self, hidden_states):
|
| 152 |
+
hidden_states = hidden_states.reshape(-1, self.hidden_dim)
|
| 153 |
+
router_logits = F.linear(hidden_states, self.weight, self.bias) # (seq_len, num_experts)
|
| 154 |
+
router_top_value, router_indices = torch.topk(router_logits, self.top_k, dim=-1) # (seq_len, top_k)
|
| 155 |
+
router_top_value = torch.nn.functional.softmax(router_top_value, dim=1, dtype=router_top_value.dtype)
|
| 156 |
+
router_scores = torch.zeros_like(router_logits).scatter_(1, router_indices, router_top_value)
|
| 157 |
+
return router_scores, router_indices
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@use_kernel_forward_from_hub("MegaBlocksMoeMLP")
|
| 161 |
+
class GptOssMLP(nn.Module):
|
| 162 |
+
def __init__(self, config):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.router = GptOssTopKRouter(config)
|
| 165 |
+
self.experts = GptOssExperts(config)
|
| 166 |
+
|
| 167 |
+
def forward(self, hidden_states):
|
| 168 |
+
router_scores, router_indices = self.router(hidden_states) # (num_experts, seq_len)
|
| 169 |
+
routed_out = self.experts(hidden_states, router_indices=router_indices, routing_weights=router_scores)
|
| 170 |
+
return routed_out, router_scores
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class GptOssRotaryEmbedding(LlamaRotaryEmbedding):
|
| 174 |
+
@torch.no_grad()
|
| 175 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 176 |
+
def forward(self, x, position_ids):
|
| 177 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 178 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 179 |
+
|
| 180 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 181 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
| 182 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 183 |
+
emb = freqs
|
| 184 |
+
cos = emb.cos() * self.attention_scaling
|
| 185 |
+
sin = emb.sin() * self.attention_scaling
|
| 186 |
+
|
| 187 |
+
return cos.to(x.dtype), sin.to(x.dtype)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _apply_rotary_emb(
|
| 191 |
+
x: torch.Tensor,
|
| 192 |
+
cos: torch.Tensor,
|
| 193 |
+
sin: torch.Tensor,
|
| 194 |
+
) -> torch.Tensor:
|
| 195 |
+
first_half, second_half = torch.chunk(x, 2, dim=-1)
|
| 196 |
+
first_ = first_half * cos - second_half * sin
|
| 197 |
+
second_ = second_half * cos + first_half * sin
|
| 198 |
+
return torch.cat((first_, second_), dim=-1)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 202 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 203 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 204 |
+
q_embed = _apply_rotary_emb(q, cos, sin)
|
| 205 |
+
k_embed = _apply_rotary_emb(k, cos, sin)
|
| 206 |
+
return q_embed, k_embed
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def eager_attention_forward(
|
| 210 |
+
module: nn.Module,
|
| 211 |
+
query: torch.Tensor,
|
| 212 |
+
key: torch.Tensor,
|
| 213 |
+
value: torch.Tensor,
|
| 214 |
+
attention_mask: Optional[torch.Tensor],
|
| 215 |
+
scaling: float,
|
| 216 |
+
dropout: float = 0.0,
|
| 217 |
+
**kwargs,
|
| 218 |
+
):
|
| 219 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 220 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 221 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 222 |
+
if attention_mask is not None:
|
| 223 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 224 |
+
attn_weights = attn_weights + causal_mask
|
| 225 |
+
|
| 226 |
+
sinks = module.sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
|
| 227 |
+
combined_logits = torch.cat([attn_weights, sinks], dim=-1)
|
| 228 |
+
|
| 229 |
+
# This was not in the original implementation and slightly affect results; it prevents overflow in BF16/FP16
|
| 230 |
+
# when training with bsz>1 we clamp max values.
|
| 231 |
+
|
| 232 |
+
combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
|
| 233 |
+
probs = F.softmax(combined_logits, dim=-1, dtype=combined_logits.dtype)
|
| 234 |
+
scores = probs[..., :-1] # we drop the sink here
|
| 235 |
+
attn_weights = nn.functional.dropout(scores, p=dropout, training=module.training)
|
| 236 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 237 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 238 |
+
return attn_output, attn_weights
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
class GptOssAttention(Qwen2Attention):
|
| 242 |
+
def __init__(self, config: GptOssConfig, layer_idx: int):
|
| 243 |
+
super().__init__(config, layer_idx)
|
| 244 |
+
self.q_proj = nn.Linear(
|
| 245 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 246 |
+
)
|
| 247 |
+
self.k_proj = nn.Linear(
|
| 248 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 249 |
+
)
|
| 250 |
+
self.v_proj = nn.Linear(
|
| 251 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 252 |
+
)
|
| 253 |
+
self.o_proj = nn.Linear(
|
| 254 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 255 |
+
)
|
| 256 |
+
self.sinks = nn.Parameter(torch.empty(config.num_attention_heads))
|
| 257 |
+
|
| 258 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 259 |
+
def forward(
|
| 260 |
+
self,
|
| 261 |
+
hidden_states: torch.Tensor,
|
| 262 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 263 |
+
attention_mask: Optional[torch.Tensor],
|
| 264 |
+
past_key_values: Optional[Cache] = None,
|
| 265 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 266 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 267 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 268 |
+
input_shape = hidden_states.shape[:-1]
|
| 269 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 270 |
+
|
| 271 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 272 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 273 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 274 |
+
|
| 275 |
+
cos, sin = position_embeddings
|
| 276 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 277 |
+
|
| 278 |
+
if past_key_values is not None:
|
| 279 |
+
cache_kwargs = {"cache_position": cache_position}
|
| 280 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 281 |
+
|
| 282 |
+
attention_interface: Callable = eager_attention_forward
|
| 283 |
+
if self.config._attn_implementation != "eager":
|
| 284 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 285 |
+
|
| 286 |
+
attn_output, attn_weights = attention_interface(
|
| 287 |
+
self,
|
| 288 |
+
query_states,
|
| 289 |
+
key_states,
|
| 290 |
+
value_states,
|
| 291 |
+
attention_mask,
|
| 292 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 293 |
+
scaling=self.scaling,
|
| 294 |
+
sliding_window=self.sliding_window,
|
| 295 |
+
s_aux=self.sinks, # diff with Llama
|
| 296 |
+
**kwargs,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 300 |
+
attn_output = self.o_proj(attn_output)
|
| 301 |
+
return attn_output, attn_weights
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class GptOssDecoderLayer(LlamaDecoderLayer):
|
| 305 |
+
def __init__(self, config: GptOssConfig, layer_idx: int):
|
| 306 |
+
super().__init__(config, layer_idx)
|
| 307 |
+
self.hidden_size = config.hidden_size
|
| 308 |
+
self.self_attn = GptOssAttention(config=config, layer_idx=layer_idx)
|
| 309 |
+
self.mlp = GptOssMLP(config)
|
| 310 |
+
self.input_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 311 |
+
self.post_attention_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 312 |
+
self.attention_type = config.layer_types[layer_idx]
|
| 313 |
+
|
| 314 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 315 |
+
def forward(
|
| 316 |
+
self,
|
| 317 |
+
hidden_states: torch.Tensor,
|
| 318 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 319 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 320 |
+
past_key_values: Optional[Cache] = None,
|
| 321 |
+
use_cache: Optional[bool] = False,
|
| 322 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 323 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 324 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 325 |
+
) -> torch.Tensor:
|
| 326 |
+
residual = hidden_states
|
| 327 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 328 |
+
# Self Attention
|
| 329 |
+
hidden_states, _ = self.self_attn(
|
| 330 |
+
hidden_states=hidden_states,
|
| 331 |
+
attention_mask=attention_mask,
|
| 332 |
+
position_ids=position_ids,
|
| 333 |
+
past_key_values=past_key_values,
|
| 334 |
+
use_cache=use_cache,
|
| 335 |
+
cache_position=cache_position,
|
| 336 |
+
position_embeddings=position_embeddings,
|
| 337 |
+
**kwargs,
|
| 338 |
+
)
|
| 339 |
+
hidden_states = residual + hidden_states
|
| 340 |
+
|
| 341 |
+
# Fully Connected
|
| 342 |
+
residual = hidden_states
|
| 343 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 344 |
+
hidden_states, _ = self.mlp(hidden_states) # diff with llama: router scores
|
| 345 |
+
hidden_states = residual + hidden_states
|
| 346 |
+
return hidden_states
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class GptOssPreTrainedModel(LlamaPreTrainedModel):
|
| 350 |
+
_keep_in_fp32_modules = ["post_attention_layernorm", "input_layernorm", "norm"]
|
| 351 |
+
_supports_sdpa = False
|
| 352 |
+
_supports_flash_attention = False
|
| 353 |
+
_supports_flex_attention = False
|
| 354 |
+
_can_record_outputs = {
|
| 355 |
+
"router_logits": OutputRecorder(GptOssTopKRouter, index=0),
|
| 356 |
+
"hidden_states": GptOssDecoderLayer,
|
| 357 |
+
"attentions": GptOssAttention,
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
def _init_weights(self, module):
|
| 361 |
+
std = self.config.initializer_range
|
| 362 |
+
if isinstance(module, nn.Linear):
|
| 363 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 364 |
+
if module.bias is not None:
|
| 365 |
+
module.bias.data.zero_()
|
| 366 |
+
elif isinstance(module, nn.Parameter):
|
| 367 |
+
module.data.normal_(mean=0.0, std=std)
|
| 368 |
+
elif isinstance(module, nn.Embedding):
|
| 369 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 370 |
+
if module.padding_idx is not None:
|
| 371 |
+
module.weight.data[module.padding_idx].zero_()
|
| 372 |
+
elif isinstance(module, GptOssRMSNorm):
|
| 373 |
+
module.weight.data.fill_(1.0)
|
| 374 |
+
elif isinstance(module, GptOssExperts):
|
| 375 |
+
module.gate_up_proj.data.normal_(mean=0.0, std=std)
|
| 376 |
+
module.gate_up_proj_bias.data.zero_()
|
| 377 |
+
module.down_proj.data.normal_(mean=0.0, std=std)
|
| 378 |
+
module.down_proj_bias.data.zero_()
|
| 379 |
+
elif isinstance(module, GptOssAttention):
|
| 380 |
+
module.sinks.data.normal_(mean=0.0, std=std)
|
| 381 |
+
elif isinstance(module, GptOssTopKRouter):
|
| 382 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 383 |
+
module.bias.data.normal_(mean=0.0, std=std)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
class GptOssModel(MixtralModel):
|
| 387 |
+
_no_split_modules = ["GptOssDecoderLayer"]
|
| 388 |
+
|
| 389 |
+
@check_model_inputs
|
| 390 |
+
@auto_docstring
|
| 391 |
+
def forward(
|
| 392 |
+
self,
|
| 393 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 394 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 395 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 396 |
+
past_key_values: Optional[Cache] = None,
|
| 397 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 398 |
+
use_cache: Optional[bool] = None,
|
| 399 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 400 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 401 |
+
) -> MoeModelOutputWithPast:
|
| 402 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 403 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 404 |
+
|
| 405 |
+
if use_cache and past_key_values is None:
|
| 406 |
+
past_key_values = DynamicCache(config=self.config)
|
| 407 |
+
|
| 408 |
+
if inputs_embeds is None:
|
| 409 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 410 |
+
|
| 411 |
+
if cache_position is None:
|
| 412 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 413 |
+
cache_position = torch.arange(
|
| 414 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 415 |
+
)
|
| 416 |
+
if position_ids is None:
|
| 417 |
+
position_ids = cache_position.unsqueeze(0)
|
| 418 |
+
|
| 419 |
+
# It may already have been prepared by e.g. `generate`
|
| 420 |
+
if not isinstance(causal_mask_mapping := attention_mask, dict):
|
| 421 |
+
mask_kwargs = {
|
| 422 |
+
"config": self.config,
|
| 423 |
+
"input_embeds": inputs_embeds,
|
| 424 |
+
"attention_mask": attention_mask,
|
| 425 |
+
"cache_position": cache_position,
|
| 426 |
+
"past_key_values": past_key_values,
|
| 427 |
+
}
|
| 428 |
+
causal_mask_mapping = {
|
| 429 |
+
"full_attention": create_causal_mask(**mask_kwargs),
|
| 430 |
+
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
hidden_states = inputs_embeds
|
| 434 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 435 |
+
|
| 436 |
+
for decoder_layer in self.layers:
|
| 437 |
+
hidden_states = decoder_layer(
|
| 438 |
+
hidden_states,
|
| 439 |
+
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
|
| 440 |
+
position_ids=position_ids,
|
| 441 |
+
past_key_values=past_key_values,
|
| 442 |
+
use_cache=use_cache,
|
| 443 |
+
cache_position=cache_position,
|
| 444 |
+
position_embeddings=position_embeddings,
|
| 445 |
+
**kwargs,
|
| 446 |
+
)
|
| 447 |
+
hidden_states = self.norm(hidden_states)
|
| 448 |
+
return MoeModelOutputWithPast(
|
| 449 |
+
last_hidden_state=hidden_states,
|
| 450 |
+
past_key_values=past_key_values,
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
class GptOssForCausalLM(MixtralForCausalLM):
|
| 455 |
+
pass
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
class GptOssForSequenceClassification(MixtralForSequenceClassification):
|
| 459 |
+
pass
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
class GptOssForTokenClassification(MixtralForTokenClassification):
|
| 463 |
+
pass
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
__all__ = [
|
| 467 |
+
"GptOssForCausalLM",
|
| 468 |
+
"GptOssForSequenceClassification",
|
| 469 |
+
"GptOssForTokenClassification",
|
| 470 |
+
"GptOssModel",
|
| 471 |
+
"GptOssPreTrainedModel",
|
| 472 |
+
]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/hgnet_v2/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from typing import TYPE_CHECKING
|
| 17 |
+
|
| 18 |
+
from ...utils import _LazyModule
|
| 19 |
+
from ...utils.import_utils import define_import_structure
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from .configuration_hgnet_v2 import *
|
| 24 |
+
from .modeling_hgnet_v2 import *
|
| 25 |
+
else:
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
_file = globals()["__file__"]
|
| 29 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/hgnet_v2/configuration_hgnet_v2.py
ADDED
|
@@ -0,0 +1,152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🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/hgnet_v2/modular_hgnet_v2.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_hgnet_v2.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
from ...configuration_utils import PretrainedConfig
|
| 24 |
+
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# TODO: Modular conversion for resnet must be fixed as
|
| 28 |
+
# it provides incorrect import for configuration like resnet_resnet
|
| 29 |
+
class HGNetV2Config(BackboneConfigMixin, PretrainedConfig):
|
| 30 |
+
"""
|
| 31 |
+
This is the configuration class to store the configuration of a [`HGNetV2Backbone`]. It is used to instantiate a HGNet-V2
|
| 32 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 33 |
+
defaults will yield a similar configuration to that of D-FINE-X-COCO B4 "[ustc-community/dfine_x_coco"](https://huggingface.co/ustc-community/dfine_x_coco").
|
| 34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 35 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 39 |
+
The number of input channels.
|
| 40 |
+
embedding_size (`int`, *optional*, defaults to 64):
|
| 41 |
+
Dimensionality (hidden size) for the embedding layer.
|
| 42 |
+
depths (`list[int]`, *optional*, defaults to `[3, 4, 6, 3]`):
|
| 43 |
+
Depth (number of layers) for each stage.
|
| 44 |
+
hidden_sizes (`list[int]`, *optional*, defaults to `[256, 512, 1024, 2048]`):
|
| 45 |
+
Dimensionality (hidden size) at each stage.
|
| 46 |
+
hidden_act (`str`, *optional*, defaults to `"relu"`):
|
| 47 |
+
The non-linear activation function in each block. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"`
|
| 48 |
+
are supported.
|
| 49 |
+
out_features (`list[str]`, *optional*):
|
| 50 |
+
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
|
| 51 |
+
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
|
| 52 |
+
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
|
| 53 |
+
same order as defined in the `stage_names` attribute.
|
| 54 |
+
out_indices (`list[int]`, *optional*):
|
| 55 |
+
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
|
| 56 |
+
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
|
| 57 |
+
If unset and `out_features` is unset, will default to the last stage. Must be in the
|
| 58 |
+
same order as defined in the `stage_names` attribute.
|
| 59 |
+
stem_channels (`list[int]`, *optional*, defaults to `[3, 32, 48]`):
|
| 60 |
+
Channel dimensions for the stem layers:
|
| 61 |
+
- First number (3) is input image channels
|
| 62 |
+
- Second number (32) is intermediate stem channels
|
| 63 |
+
- Third number (48) is output stem channels
|
| 64 |
+
stage_in_channels (`list[int]`, *optional*, defaults to `[48, 128, 512, 1024]`):
|
| 65 |
+
Input channel dimensions for each stage of the backbone.
|
| 66 |
+
This defines how many channels the input to each stage will have.
|
| 67 |
+
stage_mid_channels (`list[int]`, *optional*, defaults to `[48, 96, 192, 384]`):
|
| 68 |
+
Mid-channel dimensions for each stage of the backbone.
|
| 69 |
+
This defines the number of channels used in the intermediate layers of each stage.
|
| 70 |
+
stage_out_channels (`list[int]`, *optional*, defaults to `[128, 512, 1024, 2048]`):
|
| 71 |
+
Output channel dimensions for each stage of the backbone.
|
| 72 |
+
This defines how many channels the output of each stage will have.
|
| 73 |
+
stage_num_blocks (`list[int]`, *optional*, defaults to `[1, 1, 3, 1]`):
|
| 74 |
+
Number of blocks to be used in each stage of the backbone.
|
| 75 |
+
This controls the depth of each stage by specifying how many convolutional blocks to stack.
|
| 76 |
+
stage_downsample (`list[bool]`, *optional*, defaults to `[False, True, True, True]`):
|
| 77 |
+
Indicates whether to downsample the feature maps at each stage.
|
| 78 |
+
If `True`, the spatial dimensions of the feature maps will be reduced.
|
| 79 |
+
stage_light_block (`list[bool]`, *optional*, defaults to `[False, False, True, True]`):
|
| 80 |
+
Indicates whether to use light blocks in each stage.
|
| 81 |
+
Light blocks are a variant of convolutional blocks that may have fewer parameters.
|
| 82 |
+
stage_kernel_size (`list[int]`, *optional*, defaults to `[3, 3, 5, 5]`):
|
| 83 |
+
Kernel sizes for the convolutional layers in each stage.
|
| 84 |
+
stage_numb_of_layers (`list[int]`, *optional*, defaults to `[6, 6, 6, 6]`):
|
| 85 |
+
Number of layers to be used in each block of the stage.
|
| 86 |
+
use_learnable_affine_block (`bool`, *optional*, defaults to `False`):
|
| 87 |
+
Whether to use Learnable Affine Blocks (LAB) in the network.
|
| 88 |
+
LAB adds learnable scale and bias parameters after certain operations.
|
| 89 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 90 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
model_type = "hgnet_v2"
|
| 94 |
+
|
| 95 |
+
def __init__(
|
| 96 |
+
self,
|
| 97 |
+
num_channels=3,
|
| 98 |
+
embedding_size=64,
|
| 99 |
+
depths=[3, 4, 6, 3],
|
| 100 |
+
hidden_sizes=[256, 512, 1024, 2048],
|
| 101 |
+
hidden_act="relu",
|
| 102 |
+
out_features=None,
|
| 103 |
+
out_indices=None,
|
| 104 |
+
stem_channels=[3, 32, 48],
|
| 105 |
+
stage_in_channels=[48, 128, 512, 1024],
|
| 106 |
+
stage_mid_channels=[48, 96, 192, 384],
|
| 107 |
+
stage_out_channels=[128, 512, 1024, 2048],
|
| 108 |
+
stage_num_blocks=[1, 1, 3, 1],
|
| 109 |
+
stage_downsample=[False, True, True, True],
|
| 110 |
+
stage_light_block=[False, False, True, True],
|
| 111 |
+
stage_kernel_size=[3, 3, 5, 5],
|
| 112 |
+
stage_numb_of_layers=[6, 6, 6, 6],
|
| 113 |
+
use_learnable_affine_block=False,
|
| 114 |
+
initializer_range=0.02,
|
| 115 |
+
**kwargs,
|
| 116 |
+
):
|
| 117 |
+
super().__init__(**kwargs)
|
| 118 |
+
self.num_channels = num_channels
|
| 119 |
+
self.embedding_size = embedding_size
|
| 120 |
+
self.depths = depths
|
| 121 |
+
self.hidden_sizes = hidden_sizes
|
| 122 |
+
self.hidden_act = hidden_act
|
| 123 |
+
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(depths) + 1)]
|
| 124 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 125 |
+
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
|
| 126 |
+
)
|
| 127 |
+
self.stem_channels = stem_channels
|
| 128 |
+
self.stage_in_channels = stage_in_channels
|
| 129 |
+
self.stage_mid_channels = stage_mid_channels
|
| 130 |
+
self.stage_out_channels = stage_out_channels
|
| 131 |
+
self.stage_num_blocks = stage_num_blocks
|
| 132 |
+
self.stage_downsample = stage_downsample
|
| 133 |
+
self.stage_light_block = stage_light_block
|
| 134 |
+
self.stage_kernel_size = stage_kernel_size
|
| 135 |
+
self.stage_numb_of_layers = stage_numb_of_layers
|
| 136 |
+
self.use_learnable_affine_block = use_learnable_affine_block
|
| 137 |
+
self.initializer_range = initializer_range
|
| 138 |
+
|
| 139 |
+
if not (
|
| 140 |
+
len(stage_in_channels)
|
| 141 |
+
== len(stage_mid_channels)
|
| 142 |
+
== len(stage_out_channels)
|
| 143 |
+
== len(stage_num_blocks)
|
| 144 |
+
== len(stage_downsample)
|
| 145 |
+
== len(stage_light_block)
|
| 146 |
+
== len(stage_kernel_size)
|
| 147 |
+
== len(stage_numb_of_layers)
|
| 148 |
+
):
|
| 149 |
+
raise ValueError("All stage configuration lists must have the same length.")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
__all__ = ["HGNetV2Config"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/hgnet_v2/modeling_hgnet_v2.py
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/hgnet_v2/modular_hgnet_v2.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_hgnet_v2.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
from typing import Optional
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
from torch import Tensor, nn
|
| 28 |
+
|
| 29 |
+
from ...activations import ACT2FN
|
| 30 |
+
from ...modeling_outputs import BackboneOutput, BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
|
| 31 |
+
from ...modeling_utils import PreTrainedModel
|
| 32 |
+
from ...utils import auto_docstring
|
| 33 |
+
from ...utils.backbone_utils import BackboneMixin
|
| 34 |
+
from .configuration_hgnet_v2 import HGNetV2Config
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# General docstring
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@auto_docstring
|
| 41 |
+
class HGNetV2PreTrainedModel(PreTrainedModel):
|
| 42 |
+
config: HGNetV2Config
|
| 43 |
+
base_model_prefix = "hgnetv2"
|
| 44 |
+
main_input_name = "pixel_values"
|
| 45 |
+
_no_split_modules = ["HGNetV2BasicLayer"]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class HGNetV2LearnableAffineBlock(nn.Module):
|
| 49 |
+
def __init__(self, scale_value: float = 1.0, bias_value: float = 0.0):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.scale = nn.Parameter(torch.tensor([scale_value]), requires_grad=True)
|
| 52 |
+
self.bias = nn.Parameter(torch.tensor([bias_value]), requires_grad=True)
|
| 53 |
+
|
| 54 |
+
def forward(self, hidden_state: Tensor) -> Tensor:
|
| 55 |
+
hidden_state = self.scale * hidden_state + self.bias
|
| 56 |
+
return hidden_state
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class HGNetV2ConvLayer(nn.Module):
|
| 60 |
+
def __init__(
|
| 61 |
+
self,
|
| 62 |
+
in_channels: int,
|
| 63 |
+
out_channels: int,
|
| 64 |
+
kernel_size: int,
|
| 65 |
+
stride: int = 1,
|
| 66 |
+
groups: int = 1,
|
| 67 |
+
activation: str = "relu",
|
| 68 |
+
use_learnable_affine_block: bool = False,
|
| 69 |
+
):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.convolution = nn.Conv2d(
|
| 72 |
+
in_channels,
|
| 73 |
+
out_channels,
|
| 74 |
+
kernel_size=kernel_size,
|
| 75 |
+
stride=stride,
|
| 76 |
+
groups=groups,
|
| 77 |
+
padding=(kernel_size - 1) // 2,
|
| 78 |
+
bias=False,
|
| 79 |
+
)
|
| 80 |
+
self.normalization = nn.BatchNorm2d(out_channels)
|
| 81 |
+
self.activation = ACT2FN[activation] if activation is not None else nn.Identity()
|
| 82 |
+
if activation and use_learnable_affine_block:
|
| 83 |
+
self.lab = HGNetV2LearnableAffineBlock()
|
| 84 |
+
else:
|
| 85 |
+
self.lab = nn.Identity()
|
| 86 |
+
|
| 87 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 88 |
+
hidden_state = self.convolution(input)
|
| 89 |
+
hidden_state = self.normalization(hidden_state)
|
| 90 |
+
hidden_state = self.activation(hidden_state)
|
| 91 |
+
hidden_state = self.lab(hidden_state)
|
| 92 |
+
return hidden_state
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class HGNetV2ConvLayerLight(nn.Module):
|
| 96 |
+
def __init__(
|
| 97 |
+
self, in_channels: int, out_channels: int, kernel_size: int, use_learnable_affine_block: bool = False
|
| 98 |
+
):
|
| 99 |
+
super().__init__()
|
| 100 |
+
self.conv1 = HGNetV2ConvLayer(
|
| 101 |
+
in_channels,
|
| 102 |
+
out_channels,
|
| 103 |
+
kernel_size=1,
|
| 104 |
+
activation=None,
|
| 105 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 106 |
+
)
|
| 107 |
+
self.conv2 = HGNetV2ConvLayer(
|
| 108 |
+
out_channels,
|
| 109 |
+
out_channels,
|
| 110 |
+
kernel_size=kernel_size,
|
| 111 |
+
groups=out_channels,
|
| 112 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def forward(self, hidden_state: Tensor) -> Tensor:
|
| 116 |
+
hidden_state = self.conv1(hidden_state)
|
| 117 |
+
hidden_state = self.conv2(hidden_state)
|
| 118 |
+
return hidden_state
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class HGNetV2Embeddings(nn.Module):
|
| 122 |
+
def __init__(self, config: HGNetV2Config):
|
| 123 |
+
super().__init__()
|
| 124 |
+
|
| 125 |
+
self.stem1 = HGNetV2ConvLayer(
|
| 126 |
+
config.stem_channels[0],
|
| 127 |
+
config.stem_channels[1],
|
| 128 |
+
kernel_size=3,
|
| 129 |
+
stride=2,
|
| 130 |
+
activation=config.hidden_act,
|
| 131 |
+
use_learnable_affine_block=config.use_learnable_affine_block,
|
| 132 |
+
)
|
| 133 |
+
self.stem2a = HGNetV2ConvLayer(
|
| 134 |
+
config.stem_channels[1],
|
| 135 |
+
config.stem_channels[1] // 2,
|
| 136 |
+
kernel_size=2,
|
| 137 |
+
stride=1,
|
| 138 |
+
activation=config.hidden_act,
|
| 139 |
+
use_learnable_affine_block=config.use_learnable_affine_block,
|
| 140 |
+
)
|
| 141 |
+
self.stem2b = HGNetV2ConvLayer(
|
| 142 |
+
config.stem_channels[1] // 2,
|
| 143 |
+
config.stem_channels[1],
|
| 144 |
+
kernel_size=2,
|
| 145 |
+
stride=1,
|
| 146 |
+
activation=config.hidden_act,
|
| 147 |
+
use_learnable_affine_block=config.use_learnable_affine_block,
|
| 148 |
+
)
|
| 149 |
+
self.stem3 = HGNetV2ConvLayer(
|
| 150 |
+
config.stem_channels[1] * 2,
|
| 151 |
+
config.stem_channels[1],
|
| 152 |
+
kernel_size=3,
|
| 153 |
+
stride=2,
|
| 154 |
+
activation=config.hidden_act,
|
| 155 |
+
use_learnable_affine_block=config.use_learnable_affine_block,
|
| 156 |
+
)
|
| 157 |
+
self.stem4 = HGNetV2ConvLayer(
|
| 158 |
+
config.stem_channels[1],
|
| 159 |
+
config.stem_channels[2],
|
| 160 |
+
kernel_size=1,
|
| 161 |
+
stride=1,
|
| 162 |
+
activation=config.hidden_act,
|
| 163 |
+
use_learnable_affine_block=config.use_learnable_affine_block,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
self.pool = nn.MaxPool2d(kernel_size=2, stride=1, ceil_mode=True)
|
| 167 |
+
self.num_channels = config.num_channels
|
| 168 |
+
|
| 169 |
+
def forward(self, pixel_values: Tensor) -> Tensor:
|
| 170 |
+
num_channels = pixel_values.shape[1]
|
| 171 |
+
if num_channels != self.num_channels:
|
| 172 |
+
raise ValueError(
|
| 173 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 174 |
+
)
|
| 175 |
+
embedding = self.stem1(pixel_values)
|
| 176 |
+
embedding = F.pad(embedding, (0, 1, 0, 1))
|
| 177 |
+
emb_stem_2a = self.stem2a(embedding)
|
| 178 |
+
emb_stem_2a = F.pad(emb_stem_2a, (0, 1, 0, 1))
|
| 179 |
+
emb_stem_2a = self.stem2b(emb_stem_2a)
|
| 180 |
+
pooled_emb = self.pool(embedding)
|
| 181 |
+
embedding = torch.cat([pooled_emb, emb_stem_2a], dim=1)
|
| 182 |
+
embedding = self.stem3(embedding)
|
| 183 |
+
embedding = self.stem4(embedding)
|
| 184 |
+
return embedding
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class HGNetV2BasicLayer(nn.Module):
|
| 188 |
+
def __init__(
|
| 189 |
+
self,
|
| 190 |
+
in_channels: int,
|
| 191 |
+
middle_channels: int,
|
| 192 |
+
out_channels: int,
|
| 193 |
+
layer_num: int,
|
| 194 |
+
kernel_size: int = 3,
|
| 195 |
+
residual: bool = False,
|
| 196 |
+
light_block: bool = False,
|
| 197 |
+
drop_path: float = 0.0,
|
| 198 |
+
use_learnable_affine_block: bool = False,
|
| 199 |
+
):
|
| 200 |
+
super().__init__()
|
| 201 |
+
self.residual = residual
|
| 202 |
+
|
| 203 |
+
self.layers = nn.ModuleList()
|
| 204 |
+
for i in range(layer_num):
|
| 205 |
+
temp_in_channels = in_channels if i == 0 else middle_channels
|
| 206 |
+
if light_block:
|
| 207 |
+
block = HGNetV2ConvLayerLight(
|
| 208 |
+
in_channels=temp_in_channels,
|
| 209 |
+
out_channels=middle_channels,
|
| 210 |
+
kernel_size=kernel_size,
|
| 211 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 212 |
+
)
|
| 213 |
+
else:
|
| 214 |
+
block = HGNetV2ConvLayer(
|
| 215 |
+
in_channels=temp_in_channels,
|
| 216 |
+
out_channels=middle_channels,
|
| 217 |
+
kernel_size=kernel_size,
|
| 218 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 219 |
+
stride=1,
|
| 220 |
+
)
|
| 221 |
+
self.layers.append(block)
|
| 222 |
+
|
| 223 |
+
# feature aggregation
|
| 224 |
+
total_channels = in_channels + layer_num * middle_channels
|
| 225 |
+
aggregation_squeeze_conv = HGNetV2ConvLayer(
|
| 226 |
+
total_channels,
|
| 227 |
+
out_channels // 2,
|
| 228 |
+
kernel_size=1,
|
| 229 |
+
stride=1,
|
| 230 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 231 |
+
)
|
| 232 |
+
aggregation_excitation_conv = HGNetV2ConvLayer(
|
| 233 |
+
out_channels // 2,
|
| 234 |
+
out_channels,
|
| 235 |
+
kernel_size=1,
|
| 236 |
+
stride=1,
|
| 237 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 238 |
+
)
|
| 239 |
+
self.aggregation = nn.Sequential(
|
| 240 |
+
aggregation_squeeze_conv,
|
| 241 |
+
aggregation_excitation_conv,
|
| 242 |
+
)
|
| 243 |
+
self.drop_path = nn.Dropout(drop_path) if drop_path else nn.Identity()
|
| 244 |
+
|
| 245 |
+
def forward(self, hidden_state: Tensor) -> Tensor:
|
| 246 |
+
identity = hidden_state
|
| 247 |
+
output = [hidden_state]
|
| 248 |
+
for layer in self.layers:
|
| 249 |
+
hidden_state = layer(hidden_state)
|
| 250 |
+
output.append(hidden_state)
|
| 251 |
+
hidden_state = torch.cat(output, dim=1)
|
| 252 |
+
hidden_state = self.aggregation(hidden_state)
|
| 253 |
+
if self.residual:
|
| 254 |
+
hidden_state = self.drop_path(hidden_state) + identity
|
| 255 |
+
return hidden_state
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class HGNetV2Stage(nn.Module):
|
| 259 |
+
def __init__(self, config: HGNetV2Config, stage_index: int, drop_path: float = 0.0):
|
| 260 |
+
super().__init__()
|
| 261 |
+
in_channels = config.stage_in_channels[stage_index]
|
| 262 |
+
mid_channels = config.stage_mid_channels[stage_index]
|
| 263 |
+
out_channels = config.stage_out_channels[stage_index]
|
| 264 |
+
num_blocks = config.stage_num_blocks[stage_index]
|
| 265 |
+
num_layers = config.stage_numb_of_layers[stage_index]
|
| 266 |
+
downsample = config.stage_downsample[stage_index]
|
| 267 |
+
light_block = config.stage_light_block[stage_index]
|
| 268 |
+
kernel_size = config.stage_kernel_size[stage_index]
|
| 269 |
+
use_learnable_affine_block = config.use_learnable_affine_block
|
| 270 |
+
|
| 271 |
+
if downsample:
|
| 272 |
+
self.downsample = HGNetV2ConvLayer(
|
| 273 |
+
in_channels, in_channels, kernel_size=3, stride=2, groups=in_channels, activation=None
|
| 274 |
+
)
|
| 275 |
+
else:
|
| 276 |
+
self.downsample = nn.Identity()
|
| 277 |
+
|
| 278 |
+
blocks_list = []
|
| 279 |
+
for i in range(num_blocks):
|
| 280 |
+
blocks_list.append(
|
| 281 |
+
HGNetV2BasicLayer(
|
| 282 |
+
in_channels if i == 0 else out_channels,
|
| 283 |
+
mid_channels,
|
| 284 |
+
out_channels,
|
| 285 |
+
num_layers,
|
| 286 |
+
residual=(i != 0),
|
| 287 |
+
kernel_size=kernel_size,
|
| 288 |
+
light_block=light_block,
|
| 289 |
+
drop_path=drop_path,
|
| 290 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 291 |
+
)
|
| 292 |
+
)
|
| 293 |
+
self.blocks = nn.ModuleList(blocks_list)
|
| 294 |
+
|
| 295 |
+
def forward(self, hidden_state: Tensor) -> Tensor:
|
| 296 |
+
hidden_state = self.downsample(hidden_state)
|
| 297 |
+
for block in self.blocks:
|
| 298 |
+
hidden_state = block(hidden_state)
|
| 299 |
+
return hidden_state
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
class HGNetV2Encoder(nn.Module):
|
| 303 |
+
def __init__(self, config: HGNetV2Config):
|
| 304 |
+
super().__init__()
|
| 305 |
+
self.stages = nn.ModuleList([])
|
| 306 |
+
for stage_index in range(len(config.stage_in_channels)):
|
| 307 |
+
resnet_stage = HGNetV2Stage(config, stage_index)
|
| 308 |
+
self.stages.append(resnet_stage)
|
| 309 |
+
|
| 310 |
+
def forward(
|
| 311 |
+
self, hidden_state: Tensor, output_hidden_states: bool = False, return_dict: bool = True
|
| 312 |
+
) -> BaseModelOutputWithNoAttention:
|
| 313 |
+
hidden_states = () if output_hidden_states else None
|
| 314 |
+
|
| 315 |
+
for stage in self.stages:
|
| 316 |
+
if output_hidden_states:
|
| 317 |
+
hidden_states = hidden_states + (hidden_state,)
|
| 318 |
+
|
| 319 |
+
hidden_state = stage(hidden_state)
|
| 320 |
+
|
| 321 |
+
if output_hidden_states:
|
| 322 |
+
hidden_states = hidden_states + (hidden_state,)
|
| 323 |
+
|
| 324 |
+
if not return_dict:
|
| 325 |
+
return tuple(v for v in [hidden_state, hidden_states] if v is not None)
|
| 326 |
+
|
| 327 |
+
return BaseModelOutputWithNoAttention(
|
| 328 |
+
last_hidden_state=hidden_state,
|
| 329 |
+
hidden_states=hidden_states,
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class HGNetV2Backbone(HGNetV2PreTrainedModel, BackboneMixin):
|
| 334 |
+
has_attentions = False
|
| 335 |
+
|
| 336 |
+
def __init__(self, config: HGNetV2Config):
|
| 337 |
+
super().__init__(config)
|
| 338 |
+
super()._init_backbone(config)
|
| 339 |
+
self.depths = config.depths
|
| 340 |
+
self.num_features = [config.embedding_size] + config.hidden_sizes
|
| 341 |
+
self.embedder = HGNetV2Embeddings(config)
|
| 342 |
+
self.encoder = HGNetV2Encoder(config)
|
| 343 |
+
|
| 344 |
+
# initialize weights and apply final processing
|
| 345 |
+
self.post_init()
|
| 346 |
+
|
| 347 |
+
@auto_docstring
|
| 348 |
+
def forward(
|
| 349 |
+
self, pixel_values: Tensor, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None
|
| 350 |
+
) -> BackboneOutput:
|
| 351 |
+
r"""
|
| 352 |
+
Examples:
|
| 353 |
+
|
| 354 |
+
```python
|
| 355 |
+
>>> from transformers import HGNetV2Config, HGNetV2Backbone
|
| 356 |
+
>>> import torch
|
| 357 |
+
|
| 358 |
+
>>> config = HGNetV2Config()
|
| 359 |
+
>>> model = HGNetV2Backbone(config)
|
| 360 |
+
|
| 361 |
+
>>> pixel_values = torch.randn(1, 3, 224, 224)
|
| 362 |
+
|
| 363 |
+
>>> with torch.no_grad():
|
| 364 |
+
... outputs = model(pixel_values)
|
| 365 |
+
|
| 366 |
+
>>> feature_maps = outputs.feature_maps
|
| 367 |
+
>>> list(feature_maps[-1].shape)
|
| 368 |
+
[1, 2048, 7, 7]
|
| 369 |
+
```"""
|
| 370 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 371 |
+
output_hidden_states = (
|
| 372 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
embedding_output = self.embedder(pixel_values)
|
| 376 |
+
|
| 377 |
+
outputs = self.encoder(embedding_output, output_hidden_states=True, return_dict=True)
|
| 378 |
+
|
| 379 |
+
hidden_states = outputs.hidden_states
|
| 380 |
+
|
| 381 |
+
feature_maps = ()
|
| 382 |
+
for idx, stage in enumerate(self.stage_names):
|
| 383 |
+
if stage in self.out_features:
|
| 384 |
+
feature_maps += (hidden_states[idx],)
|
| 385 |
+
|
| 386 |
+
if not return_dict:
|
| 387 |
+
output = (feature_maps,)
|
| 388 |
+
if output_hidden_states:
|
| 389 |
+
output += (outputs.hidden_states,)
|
| 390 |
+
return output
|
| 391 |
+
|
| 392 |
+
return BackboneOutput(
|
| 393 |
+
feature_maps=feature_maps,
|
| 394 |
+
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
| 395 |
+
attentions=None,
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
@auto_docstring(
|
| 400 |
+
custom_intro="""
|
| 401 |
+
HGNetV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
|
| 402 |
+
ImageNet.
|
| 403 |
+
"""
|
| 404 |
+
)
|
| 405 |
+
class HGNetV2ForImageClassification(HGNetV2PreTrainedModel):
|
| 406 |
+
def __init__(self, config: HGNetV2Config):
|
| 407 |
+
super().__init__(config)
|
| 408 |
+
self.num_labels = config.num_labels
|
| 409 |
+
self.embedder = HGNetV2Embeddings(config)
|
| 410 |
+
self.encoder = HGNetV2Encoder(config)
|
| 411 |
+
self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
|
| 412 |
+
self.flatten = nn.Flatten()
|
| 413 |
+
self.fc = nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 414 |
+
|
| 415 |
+
# classification head
|
| 416 |
+
self.classifier = nn.ModuleList([self.avg_pool, self.flatten])
|
| 417 |
+
|
| 418 |
+
# initialize weights and apply final processing
|
| 419 |
+
self.post_init()
|
| 420 |
+
|
| 421 |
+
@auto_docstring
|
| 422 |
+
def forward(
|
| 423 |
+
self,
|
| 424 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 425 |
+
labels: Optional[torch.LongTensor] = None,
|
| 426 |
+
output_hidden_states: Optional[bool] = None,
|
| 427 |
+
return_dict: Optional[bool] = None,
|
| 428 |
+
) -> ImageClassifierOutputWithNoAttention:
|
| 429 |
+
r"""
|
| 430 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 431 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 432 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 433 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 434 |
+
|
| 435 |
+
Examples:
|
| 436 |
+
```python
|
| 437 |
+
>>> import torch
|
| 438 |
+
>>> import requests
|
| 439 |
+
>>> from transformers import HGNetV2ForImageClassification, AutoImageProcessor
|
| 440 |
+
>>> from PIL import Image
|
| 441 |
+
|
| 442 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 443 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 444 |
+
|
| 445 |
+
>>> model = HGNetV2ForImageClassification.from_pretrained("ustc-community/hgnet-v2")
|
| 446 |
+
>>> processor = AutoImageProcessor.from_pretrained("ustc-community/hgnet-v2")
|
| 447 |
+
|
| 448 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 449 |
+
>>> with torch.no_grad():
|
| 450 |
+
... outputs = model(**inputs)
|
| 451 |
+
>>> outputs.logits.shape
|
| 452 |
+
torch.Size([1, 2])
|
| 453 |
+
```"""
|
| 454 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 455 |
+
output_hidden_states = (
|
| 456 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 457 |
+
)
|
| 458 |
+
embedding_output = self.embedder(pixel_values)
|
| 459 |
+
outputs = self.encoder(embedding_output, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 460 |
+
last_hidden_state = outputs[0]
|
| 461 |
+
for layer in self.classifier:
|
| 462 |
+
last_hidden_state = layer(last_hidden_state)
|
| 463 |
+
logits = self.fc(last_hidden_state)
|
| 464 |
+
loss = None
|
| 465 |
+
|
| 466 |
+
if labels is not None:
|
| 467 |
+
loss = self.loss_function(labels, logits, self.config)
|
| 468 |
+
|
| 469 |
+
if not return_dict:
|
| 470 |
+
output = (logits,) + outputs[2:]
|
| 471 |
+
return (loss,) + output if loss is not None else output
|
| 472 |
+
|
| 473 |
+
return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
__all__ = ["HGNetV2Backbone", "HGNetV2PreTrainedModel", "HGNetV2ForImageClassification"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/hgnet_v2/modular_hgnet_v2.py
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 Baidu Inc and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from typing import Optional
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn.functional as F
|
| 21 |
+
from torch import Tensor, nn
|
| 22 |
+
|
| 23 |
+
from ...configuration_utils import PretrainedConfig
|
| 24 |
+
from ...modeling_outputs import (
|
| 25 |
+
BackboneOutput,
|
| 26 |
+
BaseModelOutputWithNoAttention,
|
| 27 |
+
ImageClassifierOutputWithNoAttention,
|
| 28 |
+
)
|
| 29 |
+
from ...modeling_utils import PreTrainedModel
|
| 30 |
+
from ...utils import (
|
| 31 |
+
auto_docstring,
|
| 32 |
+
)
|
| 33 |
+
from ...utils.backbone_utils import BackboneConfigMixin, BackboneMixin, get_aligned_output_features_output_indices
|
| 34 |
+
from ..rt_detr.modeling_rt_detr_resnet import RTDetrResNetConvLayer
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# TODO: Modular conversion for resnet must be fixed as
|
| 38 |
+
# it provides incorrect import for configuration like resnet_resnet
|
| 39 |
+
class HGNetV2Config(BackboneConfigMixin, PretrainedConfig):
|
| 40 |
+
"""
|
| 41 |
+
This is the configuration class to store the configuration of a [`HGNetV2Backbone`]. It is used to instantiate a HGNet-V2
|
| 42 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 43 |
+
defaults will yield a similar configuration to that of D-FINE-X-COCO B4 "[ustc-community/dfine_x_coco"](https://huggingface.co/ustc-community/dfine_x_coco").
|
| 44 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 45 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 49 |
+
The number of input channels.
|
| 50 |
+
embedding_size (`int`, *optional*, defaults to 64):
|
| 51 |
+
Dimensionality (hidden size) for the embedding layer.
|
| 52 |
+
depths (`list[int]`, *optional*, defaults to `[3, 4, 6, 3]`):
|
| 53 |
+
Depth (number of layers) for each stage.
|
| 54 |
+
hidden_sizes (`list[int]`, *optional*, defaults to `[256, 512, 1024, 2048]`):
|
| 55 |
+
Dimensionality (hidden size) at each stage.
|
| 56 |
+
hidden_act (`str`, *optional*, defaults to `"relu"`):
|
| 57 |
+
The non-linear activation function in each block. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"`
|
| 58 |
+
are supported.
|
| 59 |
+
out_features (`list[str]`, *optional*):
|
| 60 |
+
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
|
| 61 |
+
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
|
| 62 |
+
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
|
| 63 |
+
same order as defined in the `stage_names` attribute.
|
| 64 |
+
out_indices (`list[int]`, *optional*):
|
| 65 |
+
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
|
| 66 |
+
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
|
| 67 |
+
If unset and `out_features` is unset, will default to the last stage. Must be in the
|
| 68 |
+
same order as defined in the `stage_names` attribute.
|
| 69 |
+
stem_channels (`list[int]`, *optional*, defaults to `[3, 32, 48]`):
|
| 70 |
+
Channel dimensions for the stem layers:
|
| 71 |
+
- First number (3) is input image channels
|
| 72 |
+
- Second number (32) is intermediate stem channels
|
| 73 |
+
- Third number (48) is output stem channels
|
| 74 |
+
stage_in_channels (`list[int]`, *optional*, defaults to `[48, 128, 512, 1024]`):
|
| 75 |
+
Input channel dimensions for each stage of the backbone.
|
| 76 |
+
This defines how many channels the input to each stage will have.
|
| 77 |
+
stage_mid_channels (`list[int]`, *optional*, defaults to `[48, 96, 192, 384]`):
|
| 78 |
+
Mid-channel dimensions for each stage of the backbone.
|
| 79 |
+
This defines the number of channels used in the intermediate layers of each stage.
|
| 80 |
+
stage_out_channels (`list[int]`, *optional*, defaults to `[128, 512, 1024, 2048]`):
|
| 81 |
+
Output channel dimensions for each stage of the backbone.
|
| 82 |
+
This defines how many channels the output of each stage will have.
|
| 83 |
+
stage_num_blocks (`list[int]`, *optional*, defaults to `[1, 1, 3, 1]`):
|
| 84 |
+
Number of blocks to be used in each stage of the backbone.
|
| 85 |
+
This controls the depth of each stage by specifying how many convolutional blocks to stack.
|
| 86 |
+
stage_downsample (`list[bool]`, *optional*, defaults to `[False, True, True, True]`):
|
| 87 |
+
Indicates whether to downsample the feature maps at each stage.
|
| 88 |
+
If `True`, the spatial dimensions of the feature maps will be reduced.
|
| 89 |
+
stage_light_block (`list[bool]`, *optional*, defaults to `[False, False, True, True]`):
|
| 90 |
+
Indicates whether to use light blocks in each stage.
|
| 91 |
+
Light blocks are a variant of convolutional blocks that may have fewer parameters.
|
| 92 |
+
stage_kernel_size (`list[int]`, *optional*, defaults to `[3, 3, 5, 5]`):
|
| 93 |
+
Kernel sizes for the convolutional layers in each stage.
|
| 94 |
+
stage_numb_of_layers (`list[int]`, *optional*, defaults to `[6, 6, 6, 6]`):
|
| 95 |
+
Number of layers to be used in each block of the stage.
|
| 96 |
+
use_learnable_affine_block (`bool`, *optional*, defaults to `False`):
|
| 97 |
+
Whether to use Learnable Affine Blocks (LAB) in the network.
|
| 98 |
+
LAB adds learnable scale and bias parameters after certain operations.
|
| 99 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 100 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
model_type = "hgnet_v2"
|
| 104 |
+
|
| 105 |
+
def __init__(
|
| 106 |
+
self,
|
| 107 |
+
num_channels=3,
|
| 108 |
+
embedding_size=64,
|
| 109 |
+
depths=[3, 4, 6, 3],
|
| 110 |
+
hidden_sizes=[256, 512, 1024, 2048],
|
| 111 |
+
hidden_act="relu",
|
| 112 |
+
out_features=None,
|
| 113 |
+
out_indices=None,
|
| 114 |
+
stem_channels=[3, 32, 48],
|
| 115 |
+
stage_in_channels=[48, 128, 512, 1024],
|
| 116 |
+
stage_mid_channels=[48, 96, 192, 384],
|
| 117 |
+
stage_out_channels=[128, 512, 1024, 2048],
|
| 118 |
+
stage_num_blocks=[1, 1, 3, 1],
|
| 119 |
+
stage_downsample=[False, True, True, True],
|
| 120 |
+
stage_light_block=[False, False, True, True],
|
| 121 |
+
stage_kernel_size=[3, 3, 5, 5],
|
| 122 |
+
stage_numb_of_layers=[6, 6, 6, 6],
|
| 123 |
+
use_learnable_affine_block=False,
|
| 124 |
+
initializer_range=0.02,
|
| 125 |
+
**kwargs,
|
| 126 |
+
):
|
| 127 |
+
super().__init__(**kwargs)
|
| 128 |
+
self.num_channels = num_channels
|
| 129 |
+
self.embedding_size = embedding_size
|
| 130 |
+
self.depths = depths
|
| 131 |
+
self.hidden_sizes = hidden_sizes
|
| 132 |
+
self.hidden_act = hidden_act
|
| 133 |
+
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(depths) + 1)]
|
| 134 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 135 |
+
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
|
| 136 |
+
)
|
| 137 |
+
self.stem_channels = stem_channels
|
| 138 |
+
self.stage_in_channels = stage_in_channels
|
| 139 |
+
self.stage_mid_channels = stage_mid_channels
|
| 140 |
+
self.stage_out_channels = stage_out_channels
|
| 141 |
+
self.stage_num_blocks = stage_num_blocks
|
| 142 |
+
self.stage_downsample = stage_downsample
|
| 143 |
+
self.stage_light_block = stage_light_block
|
| 144 |
+
self.stage_kernel_size = stage_kernel_size
|
| 145 |
+
self.stage_numb_of_layers = stage_numb_of_layers
|
| 146 |
+
self.use_learnable_affine_block = use_learnable_affine_block
|
| 147 |
+
self.initializer_range = initializer_range
|
| 148 |
+
|
| 149 |
+
if not (
|
| 150 |
+
len(stage_in_channels)
|
| 151 |
+
== len(stage_mid_channels)
|
| 152 |
+
== len(stage_out_channels)
|
| 153 |
+
== len(stage_num_blocks)
|
| 154 |
+
== len(stage_downsample)
|
| 155 |
+
== len(stage_light_block)
|
| 156 |
+
== len(stage_kernel_size)
|
| 157 |
+
== len(stage_numb_of_layers)
|
| 158 |
+
):
|
| 159 |
+
raise ValueError("All stage configuration lists must have the same length.")
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# General docstring
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@auto_docstring
|
| 166 |
+
class HGNetV2PreTrainedModel(PreTrainedModel):
|
| 167 |
+
config: HGNetV2Config
|
| 168 |
+
base_model_prefix = "hgnetv2"
|
| 169 |
+
main_input_name = "pixel_values"
|
| 170 |
+
_no_split_modules = ["HGNetV2BasicLayer"]
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class HGNetV2LearnableAffineBlock(nn.Module):
|
| 174 |
+
def __init__(self, scale_value: float = 1.0, bias_value: float = 0.0):
|
| 175 |
+
super().__init__()
|
| 176 |
+
self.scale = nn.Parameter(torch.tensor([scale_value]), requires_grad=True)
|
| 177 |
+
self.bias = nn.Parameter(torch.tensor([bias_value]), requires_grad=True)
|
| 178 |
+
|
| 179 |
+
def forward(self, hidden_state: Tensor) -> Tensor:
|
| 180 |
+
hidden_state = self.scale * hidden_state + self.bias
|
| 181 |
+
return hidden_state
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class HGNetV2ConvLayer(RTDetrResNetConvLayer):
|
| 185 |
+
def __init__(
|
| 186 |
+
self,
|
| 187 |
+
in_channels: int,
|
| 188 |
+
out_channels: int,
|
| 189 |
+
kernel_size: int,
|
| 190 |
+
stride: int = 1,
|
| 191 |
+
groups: int = 1,
|
| 192 |
+
activation: str = "relu",
|
| 193 |
+
use_learnable_affine_block: bool = False,
|
| 194 |
+
):
|
| 195 |
+
super().__init__(in_channels, out_channels, kernel_size, stride, activation)
|
| 196 |
+
self.convolution = nn.Conv2d(
|
| 197 |
+
in_channels,
|
| 198 |
+
out_channels,
|
| 199 |
+
kernel_size=kernel_size,
|
| 200 |
+
stride=stride,
|
| 201 |
+
groups=groups,
|
| 202 |
+
padding=(kernel_size - 1) // 2,
|
| 203 |
+
bias=False,
|
| 204 |
+
)
|
| 205 |
+
if activation and use_learnable_affine_block:
|
| 206 |
+
self.lab = HGNetV2LearnableAffineBlock()
|
| 207 |
+
else:
|
| 208 |
+
self.lab = nn.Identity()
|
| 209 |
+
|
| 210 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 211 |
+
hidden_state = self.convolution(input)
|
| 212 |
+
hidden_state = self.normalization(hidden_state)
|
| 213 |
+
hidden_state = self.activation(hidden_state)
|
| 214 |
+
hidden_state = self.lab(hidden_state)
|
| 215 |
+
return hidden_state
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class HGNetV2ConvLayerLight(nn.Module):
|
| 219 |
+
def __init__(
|
| 220 |
+
self, in_channels: int, out_channels: int, kernel_size: int, use_learnable_affine_block: bool = False
|
| 221 |
+
):
|
| 222 |
+
super().__init__()
|
| 223 |
+
self.conv1 = HGNetV2ConvLayer(
|
| 224 |
+
in_channels,
|
| 225 |
+
out_channels,
|
| 226 |
+
kernel_size=1,
|
| 227 |
+
activation=None,
|
| 228 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 229 |
+
)
|
| 230 |
+
self.conv2 = HGNetV2ConvLayer(
|
| 231 |
+
out_channels,
|
| 232 |
+
out_channels,
|
| 233 |
+
kernel_size=kernel_size,
|
| 234 |
+
groups=out_channels,
|
| 235 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
def forward(self, hidden_state: Tensor) -> Tensor:
|
| 239 |
+
hidden_state = self.conv1(hidden_state)
|
| 240 |
+
hidden_state = self.conv2(hidden_state)
|
| 241 |
+
return hidden_state
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
class HGNetV2Embeddings(nn.Module):
|
| 245 |
+
def __init__(self, config: HGNetV2Config):
|
| 246 |
+
super().__init__()
|
| 247 |
+
|
| 248 |
+
self.stem1 = HGNetV2ConvLayer(
|
| 249 |
+
config.stem_channels[0],
|
| 250 |
+
config.stem_channels[1],
|
| 251 |
+
kernel_size=3,
|
| 252 |
+
stride=2,
|
| 253 |
+
activation=config.hidden_act,
|
| 254 |
+
use_learnable_affine_block=config.use_learnable_affine_block,
|
| 255 |
+
)
|
| 256 |
+
self.stem2a = HGNetV2ConvLayer(
|
| 257 |
+
config.stem_channels[1],
|
| 258 |
+
config.stem_channels[1] // 2,
|
| 259 |
+
kernel_size=2,
|
| 260 |
+
stride=1,
|
| 261 |
+
activation=config.hidden_act,
|
| 262 |
+
use_learnable_affine_block=config.use_learnable_affine_block,
|
| 263 |
+
)
|
| 264 |
+
self.stem2b = HGNetV2ConvLayer(
|
| 265 |
+
config.stem_channels[1] // 2,
|
| 266 |
+
config.stem_channels[1],
|
| 267 |
+
kernel_size=2,
|
| 268 |
+
stride=1,
|
| 269 |
+
activation=config.hidden_act,
|
| 270 |
+
use_learnable_affine_block=config.use_learnable_affine_block,
|
| 271 |
+
)
|
| 272 |
+
self.stem3 = HGNetV2ConvLayer(
|
| 273 |
+
config.stem_channels[1] * 2,
|
| 274 |
+
config.stem_channels[1],
|
| 275 |
+
kernel_size=3,
|
| 276 |
+
stride=2,
|
| 277 |
+
activation=config.hidden_act,
|
| 278 |
+
use_learnable_affine_block=config.use_learnable_affine_block,
|
| 279 |
+
)
|
| 280 |
+
self.stem4 = HGNetV2ConvLayer(
|
| 281 |
+
config.stem_channels[1],
|
| 282 |
+
config.stem_channels[2],
|
| 283 |
+
kernel_size=1,
|
| 284 |
+
stride=1,
|
| 285 |
+
activation=config.hidden_act,
|
| 286 |
+
use_learnable_affine_block=config.use_learnable_affine_block,
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
self.pool = nn.MaxPool2d(kernel_size=2, stride=1, ceil_mode=True)
|
| 290 |
+
self.num_channels = config.num_channels
|
| 291 |
+
|
| 292 |
+
def forward(self, pixel_values: Tensor) -> Tensor:
|
| 293 |
+
num_channels = pixel_values.shape[1]
|
| 294 |
+
if num_channels != self.num_channels:
|
| 295 |
+
raise ValueError(
|
| 296 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 297 |
+
)
|
| 298 |
+
embedding = self.stem1(pixel_values)
|
| 299 |
+
embedding = F.pad(embedding, (0, 1, 0, 1))
|
| 300 |
+
emb_stem_2a = self.stem2a(embedding)
|
| 301 |
+
emb_stem_2a = F.pad(emb_stem_2a, (0, 1, 0, 1))
|
| 302 |
+
emb_stem_2a = self.stem2b(emb_stem_2a)
|
| 303 |
+
pooled_emb = self.pool(embedding)
|
| 304 |
+
embedding = torch.cat([pooled_emb, emb_stem_2a], dim=1)
|
| 305 |
+
embedding = self.stem3(embedding)
|
| 306 |
+
embedding = self.stem4(embedding)
|
| 307 |
+
return embedding
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
class HGNetV2BasicLayer(nn.Module):
|
| 311 |
+
def __init__(
|
| 312 |
+
self,
|
| 313 |
+
in_channels: int,
|
| 314 |
+
middle_channels: int,
|
| 315 |
+
out_channels: int,
|
| 316 |
+
layer_num: int,
|
| 317 |
+
kernel_size: int = 3,
|
| 318 |
+
residual: bool = False,
|
| 319 |
+
light_block: bool = False,
|
| 320 |
+
drop_path: float = 0.0,
|
| 321 |
+
use_learnable_affine_block: bool = False,
|
| 322 |
+
):
|
| 323 |
+
super().__init__()
|
| 324 |
+
self.residual = residual
|
| 325 |
+
|
| 326 |
+
self.layers = nn.ModuleList()
|
| 327 |
+
for i in range(layer_num):
|
| 328 |
+
temp_in_channels = in_channels if i == 0 else middle_channels
|
| 329 |
+
if light_block:
|
| 330 |
+
block = HGNetV2ConvLayerLight(
|
| 331 |
+
in_channels=temp_in_channels,
|
| 332 |
+
out_channels=middle_channels,
|
| 333 |
+
kernel_size=kernel_size,
|
| 334 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 335 |
+
)
|
| 336 |
+
else:
|
| 337 |
+
block = HGNetV2ConvLayer(
|
| 338 |
+
in_channels=temp_in_channels,
|
| 339 |
+
out_channels=middle_channels,
|
| 340 |
+
kernel_size=kernel_size,
|
| 341 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 342 |
+
stride=1,
|
| 343 |
+
)
|
| 344 |
+
self.layers.append(block)
|
| 345 |
+
|
| 346 |
+
# feature aggregation
|
| 347 |
+
total_channels = in_channels + layer_num * middle_channels
|
| 348 |
+
aggregation_squeeze_conv = HGNetV2ConvLayer(
|
| 349 |
+
total_channels,
|
| 350 |
+
out_channels // 2,
|
| 351 |
+
kernel_size=1,
|
| 352 |
+
stride=1,
|
| 353 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 354 |
+
)
|
| 355 |
+
aggregation_excitation_conv = HGNetV2ConvLayer(
|
| 356 |
+
out_channels // 2,
|
| 357 |
+
out_channels,
|
| 358 |
+
kernel_size=1,
|
| 359 |
+
stride=1,
|
| 360 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 361 |
+
)
|
| 362 |
+
self.aggregation = nn.Sequential(
|
| 363 |
+
aggregation_squeeze_conv,
|
| 364 |
+
aggregation_excitation_conv,
|
| 365 |
+
)
|
| 366 |
+
self.drop_path = nn.Dropout(drop_path) if drop_path else nn.Identity()
|
| 367 |
+
|
| 368 |
+
def forward(self, hidden_state: Tensor) -> Tensor:
|
| 369 |
+
identity = hidden_state
|
| 370 |
+
output = [hidden_state]
|
| 371 |
+
for layer in self.layers:
|
| 372 |
+
hidden_state = layer(hidden_state)
|
| 373 |
+
output.append(hidden_state)
|
| 374 |
+
hidden_state = torch.cat(output, dim=1)
|
| 375 |
+
hidden_state = self.aggregation(hidden_state)
|
| 376 |
+
if self.residual:
|
| 377 |
+
hidden_state = self.drop_path(hidden_state) + identity
|
| 378 |
+
return hidden_state
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
class HGNetV2Stage(nn.Module):
|
| 382 |
+
def __init__(self, config: HGNetV2Config, stage_index: int, drop_path: float = 0.0):
|
| 383 |
+
super().__init__()
|
| 384 |
+
in_channels = config.stage_in_channels[stage_index]
|
| 385 |
+
mid_channels = config.stage_mid_channels[stage_index]
|
| 386 |
+
out_channels = config.stage_out_channels[stage_index]
|
| 387 |
+
num_blocks = config.stage_num_blocks[stage_index]
|
| 388 |
+
num_layers = config.stage_numb_of_layers[stage_index]
|
| 389 |
+
downsample = config.stage_downsample[stage_index]
|
| 390 |
+
light_block = config.stage_light_block[stage_index]
|
| 391 |
+
kernel_size = config.stage_kernel_size[stage_index]
|
| 392 |
+
use_learnable_affine_block = config.use_learnable_affine_block
|
| 393 |
+
|
| 394 |
+
if downsample:
|
| 395 |
+
self.downsample = HGNetV2ConvLayer(
|
| 396 |
+
in_channels, in_channels, kernel_size=3, stride=2, groups=in_channels, activation=None
|
| 397 |
+
)
|
| 398 |
+
else:
|
| 399 |
+
self.downsample = nn.Identity()
|
| 400 |
+
|
| 401 |
+
blocks_list = []
|
| 402 |
+
for i in range(num_blocks):
|
| 403 |
+
blocks_list.append(
|
| 404 |
+
HGNetV2BasicLayer(
|
| 405 |
+
in_channels if i == 0 else out_channels,
|
| 406 |
+
mid_channels,
|
| 407 |
+
out_channels,
|
| 408 |
+
num_layers,
|
| 409 |
+
residual=(i != 0),
|
| 410 |
+
kernel_size=kernel_size,
|
| 411 |
+
light_block=light_block,
|
| 412 |
+
drop_path=drop_path,
|
| 413 |
+
use_learnable_affine_block=use_learnable_affine_block,
|
| 414 |
+
)
|
| 415 |
+
)
|
| 416 |
+
self.blocks = nn.ModuleList(blocks_list)
|
| 417 |
+
|
| 418 |
+
def forward(self, hidden_state: Tensor) -> Tensor:
|
| 419 |
+
hidden_state = self.downsample(hidden_state)
|
| 420 |
+
for block in self.blocks:
|
| 421 |
+
hidden_state = block(hidden_state)
|
| 422 |
+
return hidden_state
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
class HGNetV2Encoder(nn.Module):
|
| 426 |
+
def __init__(self, config: HGNetV2Config):
|
| 427 |
+
super().__init__()
|
| 428 |
+
self.stages = nn.ModuleList([])
|
| 429 |
+
for stage_index in range(len(config.stage_in_channels)):
|
| 430 |
+
resnet_stage = HGNetV2Stage(config, stage_index)
|
| 431 |
+
self.stages.append(resnet_stage)
|
| 432 |
+
|
| 433 |
+
def forward(
|
| 434 |
+
self, hidden_state: Tensor, output_hidden_states: bool = False, return_dict: bool = True
|
| 435 |
+
) -> BaseModelOutputWithNoAttention:
|
| 436 |
+
hidden_states = () if output_hidden_states else None
|
| 437 |
+
|
| 438 |
+
for stage in self.stages:
|
| 439 |
+
if output_hidden_states:
|
| 440 |
+
hidden_states = hidden_states + (hidden_state,)
|
| 441 |
+
|
| 442 |
+
hidden_state = stage(hidden_state)
|
| 443 |
+
|
| 444 |
+
if output_hidden_states:
|
| 445 |
+
hidden_states = hidden_states + (hidden_state,)
|
| 446 |
+
|
| 447 |
+
if not return_dict:
|
| 448 |
+
return tuple(v for v in [hidden_state, hidden_states] if v is not None)
|
| 449 |
+
|
| 450 |
+
return BaseModelOutputWithNoAttention(
|
| 451 |
+
last_hidden_state=hidden_state,
|
| 452 |
+
hidden_states=hidden_states,
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
class HGNetV2Backbone(HGNetV2PreTrainedModel, BackboneMixin):
|
| 457 |
+
has_attentions = False
|
| 458 |
+
|
| 459 |
+
def __init__(self, config: HGNetV2Config):
|
| 460 |
+
super().__init__(config)
|
| 461 |
+
super()._init_backbone(config)
|
| 462 |
+
self.depths = config.depths
|
| 463 |
+
self.num_features = [config.embedding_size] + config.hidden_sizes
|
| 464 |
+
self.embedder = HGNetV2Embeddings(config)
|
| 465 |
+
self.encoder = HGNetV2Encoder(config)
|
| 466 |
+
|
| 467 |
+
# initialize weights and apply final processing
|
| 468 |
+
self.post_init()
|
| 469 |
+
|
| 470 |
+
@auto_docstring
|
| 471 |
+
def forward(
|
| 472 |
+
self, pixel_values: Tensor, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None
|
| 473 |
+
) -> BackboneOutput:
|
| 474 |
+
r"""
|
| 475 |
+
Examples:
|
| 476 |
+
|
| 477 |
+
```python
|
| 478 |
+
>>> from transformers import HGNetV2Config, HGNetV2Backbone
|
| 479 |
+
>>> import torch
|
| 480 |
+
|
| 481 |
+
>>> config = HGNetV2Config()
|
| 482 |
+
>>> model = HGNetV2Backbone(config)
|
| 483 |
+
|
| 484 |
+
>>> pixel_values = torch.randn(1, 3, 224, 224)
|
| 485 |
+
|
| 486 |
+
>>> with torch.no_grad():
|
| 487 |
+
... outputs = model(pixel_values)
|
| 488 |
+
|
| 489 |
+
>>> feature_maps = outputs.feature_maps
|
| 490 |
+
>>> list(feature_maps[-1].shape)
|
| 491 |
+
[1, 2048, 7, 7]
|
| 492 |
+
```"""
|
| 493 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 494 |
+
output_hidden_states = (
|
| 495 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
embedding_output = self.embedder(pixel_values)
|
| 499 |
+
|
| 500 |
+
outputs = self.encoder(embedding_output, output_hidden_states=True, return_dict=True)
|
| 501 |
+
|
| 502 |
+
hidden_states = outputs.hidden_states
|
| 503 |
+
|
| 504 |
+
feature_maps = ()
|
| 505 |
+
for idx, stage in enumerate(self.stage_names):
|
| 506 |
+
if stage in self.out_features:
|
| 507 |
+
feature_maps += (hidden_states[idx],)
|
| 508 |
+
|
| 509 |
+
if not return_dict:
|
| 510 |
+
output = (feature_maps,)
|
| 511 |
+
if output_hidden_states:
|
| 512 |
+
output += (outputs.hidden_states,)
|
| 513 |
+
return output
|
| 514 |
+
|
| 515 |
+
return BackboneOutput(
|
| 516 |
+
feature_maps=feature_maps,
|
| 517 |
+
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
| 518 |
+
attentions=None,
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
@auto_docstring(
|
| 523 |
+
custom_intro="""
|
| 524 |
+
HGNetV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
|
| 525 |
+
ImageNet.
|
| 526 |
+
"""
|
| 527 |
+
)
|
| 528 |
+
class HGNetV2ForImageClassification(HGNetV2PreTrainedModel):
|
| 529 |
+
def __init__(self, config: HGNetV2Config):
|
| 530 |
+
super().__init__(config)
|
| 531 |
+
self.num_labels = config.num_labels
|
| 532 |
+
self.embedder = HGNetV2Embeddings(config)
|
| 533 |
+
self.encoder = HGNetV2Encoder(config)
|
| 534 |
+
self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
|
| 535 |
+
self.flatten = nn.Flatten()
|
| 536 |
+
self.fc = nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 537 |
+
|
| 538 |
+
# classification head
|
| 539 |
+
self.classifier = nn.ModuleList([self.avg_pool, self.flatten])
|
| 540 |
+
|
| 541 |
+
# initialize weights and apply final processing
|
| 542 |
+
self.post_init()
|
| 543 |
+
|
| 544 |
+
@auto_docstring
|
| 545 |
+
def forward(
|
| 546 |
+
self,
|
| 547 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 548 |
+
labels: Optional[torch.LongTensor] = None,
|
| 549 |
+
output_hidden_states: Optional[bool] = None,
|
| 550 |
+
return_dict: Optional[bool] = None,
|
| 551 |
+
) -> ImageClassifierOutputWithNoAttention:
|
| 552 |
+
r"""
|
| 553 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 554 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 555 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 556 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 557 |
+
|
| 558 |
+
Examples:
|
| 559 |
+
```python
|
| 560 |
+
>>> import torch
|
| 561 |
+
>>> import requests
|
| 562 |
+
>>> from transformers import HGNetV2ForImageClassification, AutoImageProcessor
|
| 563 |
+
>>> from PIL import Image
|
| 564 |
+
|
| 565 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 566 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 567 |
+
|
| 568 |
+
>>> model = HGNetV2ForImageClassification.from_pretrained("ustc-community/hgnet-v2")
|
| 569 |
+
>>> processor = AutoImageProcessor.from_pretrained("ustc-community/hgnet-v2")
|
| 570 |
+
|
| 571 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 572 |
+
>>> with torch.no_grad():
|
| 573 |
+
... outputs = model(**inputs)
|
| 574 |
+
>>> outputs.logits.shape
|
| 575 |
+
torch.Size([1, 2])
|
| 576 |
+
```"""
|
| 577 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 578 |
+
output_hidden_states = (
|
| 579 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 580 |
+
)
|
| 581 |
+
embedding_output = self.embedder(pixel_values)
|
| 582 |
+
outputs = self.encoder(embedding_output, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 583 |
+
last_hidden_state = outputs[0]
|
| 584 |
+
for layer in self.classifier:
|
| 585 |
+
last_hidden_state = layer(last_hidden_state)
|
| 586 |
+
logits = self.fc(last_hidden_state)
|
| 587 |
+
loss = None
|
| 588 |
+
|
| 589 |
+
if labels is not None:
|
| 590 |
+
loss = self.loss_function(labels, logits, self.config)
|
| 591 |
+
|
| 592 |
+
if not return_dict:
|
| 593 |
+
output = (logits,) + outputs[2:]
|
| 594 |
+
return (loss,) + output if loss is not None else output
|
| 595 |
+
|
| 596 |
+
return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
__all__ = ["HGNetV2Config", "HGNetV2Backbone", "HGNetV2PreTrainedModel", "HGNetV2ForImageClassification"]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/hunyuan_v1_moe/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from ...utils import _LazyModule
|
| 4 |
+
from ...utils.import_utils import define_import_structure
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from .configuration_hunyuan_v1_moe import *
|
| 9 |
+
from .modeling_hunyuan import *
|
| 10 |
+
else:
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
_file = globals()["__file__"]
|
| 14 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/hunyuan_v1_moe/configuration_hunyuan_v1_moe.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright (C) 2025 THL A29 Limited, a Tencent company 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 |
+
"""HunYuanMoEV1 model configuration"""
|
| 16 |
+
|
| 17 |
+
from typing import Union
|
| 18 |
+
|
| 19 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 20 |
+
from transformers.utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class HunYuanMoEV1Config(PretrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
This is the configuration class to store the configuration of a [`HunYuanMoEV1Model`]. It is used to instantiate an
|
| 29 |
+
HunYuan model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 30 |
+
with the defaults will yield a similar configuration to that of the HunYuan-7B.
|
| 31 |
+
Hunyuan-A13B-Instruct [tencent/Hunyuan-A13B-Instruct](https://huggingface.co/tencent/Hunyuan-A13B-Instruct).
|
| 32 |
+
|
| 33 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 34 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
vocab_size (`int`, *optional*, defaults to 290943):
|
| 39 |
+
Vocabulary size of the HunYuan model. Defines the number of different tokens that can be represented by the
|
| 40 |
+
`inputs_ids` passed when calling [`HunYuanMoEV1Model`]
|
| 41 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 42 |
+
Dimension of the hidden representations.
|
| 43 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
| 44 |
+
Dimension of the MLP representations or shared MLP representations.
|
| 45 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
| 46 |
+
Number of hidden layers in the Transformer decoder.
|
| 47 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 48 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 49 |
+
num_key_value_heads (`int`, *optional*):
|
| 50 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 51 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 52 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 53 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 54 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 55 |
+
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
|
| 56 |
+
`num_attention_heads`.
|
| 57 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 58 |
+
The non-linear activation function (function or string) in the decoder.
|
| 59 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
| 60 |
+
The maximum sequence length that this model might ever be used with.
|
| 61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 63 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 64 |
+
The epsilon used by the rms normalization layers.
|
| 65 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 66 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 67 |
+
relevant if `config.is_decoder=True`.
|
| 68 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
| 69 |
+
Padding token id.
|
| 70 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
| 71 |
+
Beginning of stream token id.
|
| 72 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
| 73 |
+
End of stream token id.
|
| 74 |
+
eod_token_id (int, *optional*, defaults to 3):
|
| 75 |
+
Token ID representing the end-of-document marker. Used to indicate the termination of a text sequence.
|
| 76 |
+
Example: In multi-document processing, this token helps the model distinguish between separate documents.
|
| 77 |
+
sep_token_id (`int`, *optional*, defaults to 4):
|
| 78 |
+
Token ID representing the separator token (`[SEP]`), used to demarcate boundaries between different text segments.
|
| 79 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
| 80 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
| 81 |
+
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
| 82 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
| 83 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
| 84 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 85 |
+
Whether to tie weight embeddings
|
| 86 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 87 |
+
The base period of the RoPE embeddings.
|
| 88 |
+
rope_scaling (`Dict`, *optional*):
|
| 89 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
| 90 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
| 91 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
| 92 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
| 93 |
+
these scaling strategies behave:
|
| 94 |
+
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
| 95 |
+
experimental feature, subject to breaking API changes in future versions.
|
| 96 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
| 97 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
| 98 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 99 |
+
The dropout ratio for the attention probabilities.
|
| 100 |
+
num_experts (`int` or `List`, *optional*, defaults to 1):
|
| 101 |
+
The number of experts for moe. If it is a list, it will be used as the number of experts for each layer.
|
| 102 |
+
moe_topk (int or List, *optional*, defaults to 1):
|
| 103 |
+
Number of experts selected per token (Top-K routing). List form enables layer-wise customization.
|
| 104 |
+
head_dim (`int`, *optional*, defaults to 128):
|
| 105 |
+
The attention head dimension.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
model_type = "hunyuan_v1_moe"
|
| 109 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 110 |
+
|
| 111 |
+
def __init__(
|
| 112 |
+
self,
|
| 113 |
+
vocab_size=290943,
|
| 114 |
+
hidden_size=4096,
|
| 115 |
+
intermediate_size: int = 11008,
|
| 116 |
+
num_hidden_layers=32,
|
| 117 |
+
num_attention_heads=32,
|
| 118 |
+
num_key_value_heads=None,
|
| 119 |
+
hidden_act="silu",
|
| 120 |
+
max_position_embeddings=2048,
|
| 121 |
+
initializer_range=0.02,
|
| 122 |
+
rms_norm_eps=1e-5,
|
| 123 |
+
use_cache=True,
|
| 124 |
+
pad_token_id=0,
|
| 125 |
+
bos_token_id=1,
|
| 126 |
+
eos_token_id=2,
|
| 127 |
+
eod_token_id=3,
|
| 128 |
+
sep_token_id=4,
|
| 129 |
+
pretraining_tp=1,
|
| 130 |
+
tie_word_embeddings=False,
|
| 131 |
+
rope_theta=10000.0,
|
| 132 |
+
rope_scaling=None,
|
| 133 |
+
attention_bias=False,
|
| 134 |
+
attention_dropout=0.0,
|
| 135 |
+
num_experts: Union[int, list] = 1,
|
| 136 |
+
moe_topk: Union[int, list] = 1,
|
| 137 |
+
head_dim=None,
|
| 138 |
+
**kwargs,
|
| 139 |
+
):
|
| 140 |
+
self.vocab_size = vocab_size
|
| 141 |
+
self.max_position_embeddings = max_position_embeddings
|
| 142 |
+
self.hidden_size = hidden_size
|
| 143 |
+
self.intermediate_size = intermediate_size
|
| 144 |
+
self.num_hidden_layers = num_hidden_layers
|
| 145 |
+
self.num_attention_heads = num_attention_heads
|
| 146 |
+
self.num_experts = num_experts
|
| 147 |
+
self.moe_topk = moe_topk
|
| 148 |
+
|
| 149 |
+
self.head_dim = head_dim
|
| 150 |
+
# for backward compatibility
|
| 151 |
+
if num_key_value_heads is None:
|
| 152 |
+
num_key_value_heads = num_attention_heads
|
| 153 |
+
|
| 154 |
+
self.num_key_value_heads = num_key_value_heads
|
| 155 |
+
self.hidden_act = hidden_act
|
| 156 |
+
self.initializer_range = initializer_range
|
| 157 |
+
self.rms_norm_eps = rms_norm_eps
|
| 158 |
+
self.pretraining_tp = pretraining_tp
|
| 159 |
+
self.use_cache = use_cache
|
| 160 |
+
self.rope_theta = rope_theta
|
| 161 |
+
self.rope_scaling = rope_scaling
|
| 162 |
+
# self._rope_scaling_validation() # TODO: Need validation?
|
| 163 |
+
self.attention_bias = attention_bias
|
| 164 |
+
self.attention_dropout = attention_dropout
|
| 165 |
+
|
| 166 |
+
super().__init__(
|
| 167 |
+
pad_token_id=pad_token_id,
|
| 168 |
+
bos_token_id=bos_token_id,
|
| 169 |
+
eos_token_id=eos_token_id,
|
| 170 |
+
sep_token_id=sep_token_id,
|
| 171 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 172 |
+
**kwargs,
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
def _rope_scaling_validation(self):
|
| 176 |
+
"""
|
| 177 |
+
Validate the `rope_scaling` configuration.
|
| 178 |
+
"""
|
| 179 |
+
if self.rope_scaling is None:
|
| 180 |
+
return
|
| 181 |
+
|
| 182 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
| 183 |
+
raise ValueError(
|
| 184 |
+
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor` or `type` and `alpha`, "
|
| 185 |
+
f"got {self.rope_scaling}"
|
| 186 |
+
)
|
| 187 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
| 188 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
| 189 |
+
rope_scaling_alpha = self.rope_scaling.get("alpha", None)
|
| 190 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
| 191 |
+
raise ValueError(
|
| 192 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
| 193 |
+
)
|
| 194 |
+
if rope_scaling_factor is None and rope_scaling_alpha is None:
|
| 195 |
+
raise ValueError("`rope_scaling`'s factor or alpha field must be have one, got both of none")
|
| 196 |
+
if rope_scaling_factor is not None:
|
| 197 |
+
if not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
| 198 |
+
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1.0, got {rope_scaling_factor}")
|
| 199 |
+
if rope_scaling_alpha is not None:
|
| 200 |
+
if not isinstance(rope_scaling_alpha, float) or rope_scaling_alpha <= 1.0:
|
| 201 |
+
raise ValueError(f"`rope_scaling`'s alpha field must be a float > 1.0, got {rope_scaling_alpha}")
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
__all__ = ["HunYuanMoEV1Config"]
|