Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/__init__.py +71 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/configuration_bert_generation.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/configuration_bert_generation.py +124 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/modeling_bert_generation.py +1008 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/tokenization_bert_generation.py +185 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__init__.py +138 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_tf_blenderbot_small.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small_fast.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/configuration_blenderbot_small.py +392 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/modeling_blenderbot_small.py +1570 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py +1522 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py +1529 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/tokenization_blenderbot_small.py +258 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/tokenization_blenderbot_small_fast.py +140 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/byt5/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/byt5/__pycache__/tokenization_byt5.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/byt5/convert_byt5_original_tf_checkpoint_to_pytorch.py +60 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__init__.py +88 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/configuration_chinese_clip.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/convert_chinese_clip_original_pytorch_to_hf.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/feature_extraction_chinese_clip.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/modeling_chinese_clip.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/processing_chinese_clip.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/configuration_chinese_clip.py +472 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/image_processing_chinese_clip.py +312 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/modeling_chinese_clip.py +1564 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/processing_chinese_clip.py +142 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__pycache__/configuration_efficientformer.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__pycache__/modeling_efficientformer.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/configuration_efficientformer.py +173 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/__init__.py +57 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/collating_graphormer.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/configuration_graphormer.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/algos_graphormer.pyx +107 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/collating_graphormer.py +134 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/configuration_graphormer.py +221 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/roc_bert/__pycache__/configuration_roc_bert.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/vitmatte/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/vitmatte/__pycache__/configuration_vitmatte.cpython-310.pyc +0 -0
- evalkit_cambrian/lib/python3.10/site-packages/transformers/models/vitmatte/__pycache__/convert_vitmatte_to_hf.cpython-310.pyc +0 -0
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/__init__.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_import_structure = {"configuration_bert_generation": ["BertGenerationConfig"]}
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
if not is_sentencepiece_available():
|
| 24 |
+
raise OptionalDependencyNotAvailable()
|
| 25 |
+
except OptionalDependencyNotAvailable:
|
| 26 |
+
pass
|
| 27 |
+
else:
|
| 28 |
+
_import_structure["tokenization_bert_generation"] = ["BertGenerationTokenizer"]
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
if not is_torch_available():
|
| 32 |
+
raise OptionalDependencyNotAvailable()
|
| 33 |
+
except OptionalDependencyNotAvailable:
|
| 34 |
+
pass
|
| 35 |
+
else:
|
| 36 |
+
_import_structure["modeling_bert_generation"] = [
|
| 37 |
+
"BertGenerationDecoder",
|
| 38 |
+
"BertGenerationEncoder",
|
| 39 |
+
"BertGenerationPreTrainedModel",
|
| 40 |
+
"load_tf_weights_in_bert_generation",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if TYPE_CHECKING:
|
| 45 |
+
from .configuration_bert_generation import BertGenerationConfig
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
if not is_sentencepiece_available():
|
| 49 |
+
raise OptionalDependencyNotAvailable()
|
| 50 |
+
except OptionalDependencyNotAvailable:
|
| 51 |
+
pass
|
| 52 |
+
else:
|
| 53 |
+
from .tokenization_bert_generation import BertGenerationTokenizer
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
if not is_torch_available():
|
| 57 |
+
raise OptionalDependencyNotAvailable()
|
| 58 |
+
except OptionalDependencyNotAvailable:
|
| 59 |
+
pass
|
| 60 |
+
else:
|
| 61 |
+
from .modeling_bert_generation import (
|
| 62 |
+
BertGenerationDecoder,
|
| 63 |
+
BertGenerationEncoder,
|
| 64 |
+
BertGenerationPreTrainedModel,
|
| 65 |
+
load_tf_weights_in_bert_generation,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
else:
|
| 69 |
+
import sys
|
| 70 |
+
|
| 71 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.14 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/configuration_bert_generation.cpython-310.pyc
ADDED
|
Binary file (5.65 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-310.pyc
ADDED
|
Binary file (31.7 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-310.pyc
ADDED
|
Binary file (7.18 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/configuration_bert_generation.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 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 |
+
""" BertGeneration model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class BertGenerationConfig(PretrainedConfig):
|
| 21 |
+
r"""
|
| 22 |
+
This is the configuration class to store the configuration of a [`BertGenerationPreTrainedModel`]. It is used to
|
| 23 |
+
instantiate a BertGeneration model according to the specified arguments, defining the model architecture.
|
| 24 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the BertGeneration
|
| 25 |
+
[google/bert_for_seq_generation_L-24_bbc_encoder](https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder)
|
| 26 |
+
architecture.
|
| 27 |
+
|
| 28 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 29 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
vocab_size (`int`, *optional*, defaults to 50358):
|
| 33 |
+
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
|
| 34 |
+
`inputs_ids` passed when calling [`BertGeneration`].
|
| 35 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
| 36 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 37 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
| 38 |
+
Number of hidden layers in the Transformer encoder.
|
| 39 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 40 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 41 |
+
intermediate_size (`int`, *optional*, defaults to 4096):
|
| 42 |
+
Dimensionality of the "intermediate" (often called feed-forward) layer in the Transformer encoder.
|
| 43 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 44 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 45 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 46 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 47 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 48 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 49 |
+
The dropout ratio for the attention probabilities.
|
| 50 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 51 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 52 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 53 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 54 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 55 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 56 |
+
The epsilon used by the layer normalization layers.
|
| 57 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
| 58 |
+
Padding token id.
|
| 59 |
+
bos_token_id (`int`, *optional*, defaults to 2):
|
| 60 |
+
Beginning of stream token id.
|
| 61 |
+
eos_token_id (`int`, *optional*, defaults to 1):
|
| 62 |
+
End of stream token id.
|
| 63 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 64 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 65 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 66 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 67 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 68 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 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 |
+
|
| 73 |
+
Examples:
|
| 74 |
+
|
| 75 |
+
```python
|
| 76 |
+
>>> from transformers import BertGenerationConfig, BertGenerationEncoder
|
| 77 |
+
|
| 78 |
+
>>> # Initializing a BertGeneration config
|
| 79 |
+
>>> configuration = BertGenerationConfig()
|
| 80 |
+
|
| 81 |
+
>>> # Initializing a model (with random weights) from the config
|
| 82 |
+
>>> model = BertGenerationEncoder(configuration)
|
| 83 |
+
|
| 84 |
+
>>> # Accessing the model configuration
|
| 85 |
+
>>> configuration = model.config
|
| 86 |
+
```"""
|
| 87 |
+
|
| 88 |
+
model_type = "bert-generation"
|
| 89 |
+
|
| 90 |
+
def __init__(
|
| 91 |
+
self,
|
| 92 |
+
vocab_size=50358,
|
| 93 |
+
hidden_size=1024,
|
| 94 |
+
num_hidden_layers=24,
|
| 95 |
+
num_attention_heads=16,
|
| 96 |
+
intermediate_size=4096,
|
| 97 |
+
hidden_act="gelu",
|
| 98 |
+
hidden_dropout_prob=0.1,
|
| 99 |
+
attention_probs_dropout_prob=0.1,
|
| 100 |
+
max_position_embeddings=512,
|
| 101 |
+
initializer_range=0.02,
|
| 102 |
+
layer_norm_eps=1e-12,
|
| 103 |
+
pad_token_id=0,
|
| 104 |
+
bos_token_id=2,
|
| 105 |
+
eos_token_id=1,
|
| 106 |
+
position_embedding_type="absolute",
|
| 107 |
+
use_cache=True,
|
| 108 |
+
**kwargs,
|
| 109 |
+
):
|
| 110 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 111 |
+
|
| 112 |
+
self.vocab_size = vocab_size
|
| 113 |
+
self.hidden_size = hidden_size
|
| 114 |
+
self.num_hidden_layers = num_hidden_layers
|
| 115 |
+
self.num_attention_heads = num_attention_heads
|
| 116 |
+
self.hidden_act = hidden_act
|
| 117 |
+
self.intermediate_size = intermediate_size
|
| 118 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 119 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 120 |
+
self.max_position_embeddings = max_position_embeddings
|
| 121 |
+
self.initializer_range = initializer_range
|
| 122 |
+
self.layer_norm_eps = layer_norm_eps
|
| 123 |
+
self.position_embedding_type = position_embedding_type
|
| 124 |
+
self.use_cache = use_cache
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/modeling_bert_generation.py
ADDED
|
@@ -0,0 +1,1008 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 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 |
+
"""PyTorch BERT model specific for generation."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from typing import Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.utils.checkpoint
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import CrossEntropyLoss
|
| 24 |
+
|
| 25 |
+
from ...activations import ACT2FN
|
| 26 |
+
from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
|
| 27 |
+
from ...modeling_utils import PreTrainedModel
|
| 28 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 29 |
+
from ...utils import (
|
| 30 |
+
add_code_sample_docstrings,
|
| 31 |
+
add_start_docstrings,
|
| 32 |
+
add_start_docstrings_to_model_forward,
|
| 33 |
+
logging,
|
| 34 |
+
replace_return_docstrings,
|
| 35 |
+
)
|
| 36 |
+
from .configuration_bert_generation import BertGenerationConfig
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
_CHECKPOINT_FOR_DOC = "google/bert_for_seq_generation_L-24_bbc_encoder"
|
| 42 |
+
_CONFIG_FOR_DOC = "BertGenerationConfig"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->BertGeneration
|
| 46 |
+
class BertGenerationSelfOutput(nn.Module):
|
| 47 |
+
def __init__(self, config):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 50 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 51 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 52 |
+
|
| 53 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 54 |
+
hidden_states = self.dense(hidden_states)
|
| 55 |
+
hidden_states = self.dropout(hidden_states)
|
| 56 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 57 |
+
return hidden_states
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->BertGeneration
|
| 61 |
+
class BertGenerationSelfAttention(nn.Module):
|
| 62 |
+
def __init__(self, config, position_embedding_type=None):
|
| 63 |
+
super().__init__()
|
| 64 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 65 |
+
raise ValueError(
|
| 66 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 67 |
+
f"heads ({config.num_attention_heads})"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
self.num_attention_heads = config.num_attention_heads
|
| 71 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 72 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 73 |
+
|
| 74 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 75 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 76 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 77 |
+
|
| 78 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 79 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
| 80 |
+
config, "position_embedding_type", "absolute"
|
| 81 |
+
)
|
| 82 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 83 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 84 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 85 |
+
|
| 86 |
+
self.is_decoder = config.is_decoder
|
| 87 |
+
|
| 88 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 89 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 90 |
+
x = x.view(new_x_shape)
|
| 91 |
+
return x.permute(0, 2, 1, 3)
|
| 92 |
+
|
| 93 |
+
def forward(
|
| 94 |
+
self,
|
| 95 |
+
hidden_states: torch.Tensor,
|
| 96 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 97 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 98 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 99 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 100 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 101 |
+
output_attentions: Optional[bool] = False,
|
| 102 |
+
) -> Tuple[torch.Tensor]:
|
| 103 |
+
mixed_query_layer = self.query(hidden_states)
|
| 104 |
+
|
| 105 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 106 |
+
# and values come from an encoder; the attention mask needs to be
|
| 107 |
+
# such that the encoder's padding tokens are not attended to.
|
| 108 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 109 |
+
|
| 110 |
+
if is_cross_attention and past_key_value is not None:
|
| 111 |
+
# reuse k,v, cross_attentions
|
| 112 |
+
key_layer = past_key_value[0]
|
| 113 |
+
value_layer = past_key_value[1]
|
| 114 |
+
attention_mask = encoder_attention_mask
|
| 115 |
+
elif is_cross_attention:
|
| 116 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 117 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 118 |
+
attention_mask = encoder_attention_mask
|
| 119 |
+
elif past_key_value is not None:
|
| 120 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 121 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 122 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
| 123 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
| 124 |
+
else:
|
| 125 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 126 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 127 |
+
|
| 128 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 129 |
+
|
| 130 |
+
use_cache = past_key_value is not None
|
| 131 |
+
if self.is_decoder:
|
| 132 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 133 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 134 |
+
# key/value_states (first "if" case)
|
| 135 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 136 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 137 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 138 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 139 |
+
past_key_value = (key_layer, value_layer)
|
| 140 |
+
|
| 141 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 142 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 143 |
+
|
| 144 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 145 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
| 146 |
+
if use_cache:
|
| 147 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
| 148 |
+
-1, 1
|
| 149 |
+
)
|
| 150 |
+
else:
|
| 151 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 152 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 153 |
+
distance = position_ids_l - position_ids_r
|
| 154 |
+
|
| 155 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 156 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 157 |
+
|
| 158 |
+
if self.position_embedding_type == "relative_key":
|
| 159 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 160 |
+
attention_scores = attention_scores + relative_position_scores
|
| 161 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 162 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 163 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 164 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 165 |
+
|
| 166 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 167 |
+
if attention_mask is not None:
|
| 168 |
+
# Apply the attention mask is (precomputed for all layers in BertGenerationModel forward() function)
|
| 169 |
+
attention_scores = attention_scores + attention_mask
|
| 170 |
+
|
| 171 |
+
# Normalize the attention scores to probabilities.
|
| 172 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 173 |
+
|
| 174 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 175 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 176 |
+
attention_probs = self.dropout(attention_probs)
|
| 177 |
+
|
| 178 |
+
# Mask heads if we want to
|
| 179 |
+
if head_mask is not None:
|
| 180 |
+
attention_probs = attention_probs * head_mask
|
| 181 |
+
|
| 182 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 183 |
+
|
| 184 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 185 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 186 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 187 |
+
|
| 188 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 189 |
+
|
| 190 |
+
if self.is_decoder:
|
| 191 |
+
outputs = outputs + (past_key_value,)
|
| 192 |
+
return outputs
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->BertGeneration
|
| 196 |
+
class BertGenerationAttention(nn.Module):
|
| 197 |
+
def __init__(self, config, position_embedding_type=None):
|
| 198 |
+
super().__init__()
|
| 199 |
+
self.self = BertGenerationSelfAttention(config, position_embedding_type=position_embedding_type)
|
| 200 |
+
self.output = BertGenerationSelfOutput(config)
|
| 201 |
+
self.pruned_heads = set()
|
| 202 |
+
|
| 203 |
+
def prune_heads(self, heads):
|
| 204 |
+
if len(heads) == 0:
|
| 205 |
+
return
|
| 206 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 207 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# Prune linear layers
|
| 211 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 212 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 213 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 214 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 215 |
+
|
| 216 |
+
# Update hyper params and store pruned heads
|
| 217 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 218 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 219 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 220 |
+
|
| 221 |
+
def forward(
|
| 222 |
+
self,
|
| 223 |
+
hidden_states: torch.Tensor,
|
| 224 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 225 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 226 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 227 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 228 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 229 |
+
output_attentions: Optional[bool] = False,
|
| 230 |
+
) -> Tuple[torch.Tensor]:
|
| 231 |
+
self_outputs = self.self(
|
| 232 |
+
hidden_states,
|
| 233 |
+
attention_mask,
|
| 234 |
+
head_mask,
|
| 235 |
+
encoder_hidden_states,
|
| 236 |
+
encoder_attention_mask,
|
| 237 |
+
past_key_value,
|
| 238 |
+
output_attentions,
|
| 239 |
+
)
|
| 240 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 241 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 242 |
+
return outputs
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->BertGeneration
|
| 246 |
+
class BertGenerationIntermediate(nn.Module):
|
| 247 |
+
def __init__(self, config):
|
| 248 |
+
super().__init__()
|
| 249 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 250 |
+
if isinstance(config.hidden_act, str):
|
| 251 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 252 |
+
else:
|
| 253 |
+
self.intermediate_act_fn = config.hidden_act
|
| 254 |
+
|
| 255 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 256 |
+
hidden_states = self.dense(hidden_states)
|
| 257 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 258 |
+
return hidden_states
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->BertGeneration
|
| 262 |
+
class BertGenerationOutput(nn.Module):
|
| 263 |
+
def __init__(self, config):
|
| 264 |
+
super().__init__()
|
| 265 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 266 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 267 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 268 |
+
|
| 269 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 270 |
+
hidden_states = self.dense(hidden_states)
|
| 271 |
+
hidden_states = self.dropout(hidden_states)
|
| 272 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 273 |
+
return hidden_states
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->BertGeneration
|
| 277 |
+
class BertGenerationLayer(nn.Module):
|
| 278 |
+
def __init__(self, config):
|
| 279 |
+
super().__init__()
|
| 280 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 281 |
+
self.seq_len_dim = 1
|
| 282 |
+
self.attention = BertGenerationAttention(config)
|
| 283 |
+
self.is_decoder = config.is_decoder
|
| 284 |
+
self.add_cross_attention = config.add_cross_attention
|
| 285 |
+
if self.add_cross_attention:
|
| 286 |
+
if not self.is_decoder:
|
| 287 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 288 |
+
self.crossattention = BertGenerationAttention(config, position_embedding_type="absolute")
|
| 289 |
+
self.intermediate = BertGenerationIntermediate(config)
|
| 290 |
+
self.output = BertGenerationOutput(config)
|
| 291 |
+
|
| 292 |
+
def forward(
|
| 293 |
+
self,
|
| 294 |
+
hidden_states: torch.Tensor,
|
| 295 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 296 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 297 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 298 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 299 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 300 |
+
output_attentions: Optional[bool] = False,
|
| 301 |
+
) -> Tuple[torch.Tensor]:
|
| 302 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 303 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 304 |
+
self_attention_outputs = self.attention(
|
| 305 |
+
hidden_states,
|
| 306 |
+
attention_mask,
|
| 307 |
+
head_mask,
|
| 308 |
+
output_attentions=output_attentions,
|
| 309 |
+
past_key_value=self_attn_past_key_value,
|
| 310 |
+
)
|
| 311 |
+
attention_output = self_attention_outputs[0]
|
| 312 |
+
|
| 313 |
+
# if decoder, the last output is tuple of self-attn cache
|
| 314 |
+
if self.is_decoder:
|
| 315 |
+
outputs = self_attention_outputs[1:-1]
|
| 316 |
+
present_key_value = self_attention_outputs[-1]
|
| 317 |
+
else:
|
| 318 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 319 |
+
|
| 320 |
+
cross_attn_present_key_value = None
|
| 321 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 322 |
+
if not hasattr(self, "crossattention"):
|
| 323 |
+
raise ValueError(
|
| 324 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 325 |
+
" by setting `config.add_cross_attention=True`"
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
| 329 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 330 |
+
cross_attention_outputs = self.crossattention(
|
| 331 |
+
attention_output,
|
| 332 |
+
attention_mask,
|
| 333 |
+
head_mask,
|
| 334 |
+
encoder_hidden_states,
|
| 335 |
+
encoder_attention_mask,
|
| 336 |
+
cross_attn_past_key_value,
|
| 337 |
+
output_attentions,
|
| 338 |
+
)
|
| 339 |
+
attention_output = cross_attention_outputs[0]
|
| 340 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 341 |
+
|
| 342 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
| 343 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
| 344 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 345 |
+
|
| 346 |
+
layer_output = apply_chunking_to_forward(
|
| 347 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 348 |
+
)
|
| 349 |
+
outputs = (layer_output,) + outputs
|
| 350 |
+
|
| 351 |
+
# if decoder, return the attn key/values as the last output
|
| 352 |
+
if self.is_decoder:
|
| 353 |
+
outputs = outputs + (present_key_value,)
|
| 354 |
+
|
| 355 |
+
return outputs
|
| 356 |
+
|
| 357 |
+
def feed_forward_chunk(self, attention_output):
|
| 358 |
+
intermediate_output = self.intermediate(attention_output)
|
| 359 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 360 |
+
return layer_output
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
# Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->BertGeneration
|
| 364 |
+
class BertEncoder(nn.Module):
|
| 365 |
+
def __init__(self, config):
|
| 366 |
+
super().__init__()
|
| 367 |
+
self.config = config
|
| 368 |
+
self.layer = nn.ModuleList([BertGenerationLayer(config) for _ in range(config.num_hidden_layers)])
|
| 369 |
+
self.gradient_checkpointing = False
|
| 370 |
+
|
| 371 |
+
def forward(
|
| 372 |
+
self,
|
| 373 |
+
hidden_states: torch.Tensor,
|
| 374 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 375 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 376 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 377 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 378 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 379 |
+
use_cache: Optional[bool] = None,
|
| 380 |
+
output_attentions: Optional[bool] = False,
|
| 381 |
+
output_hidden_states: Optional[bool] = False,
|
| 382 |
+
return_dict: Optional[bool] = True,
|
| 383 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
| 384 |
+
all_hidden_states = () if output_hidden_states else None
|
| 385 |
+
all_self_attentions = () if output_attentions else None
|
| 386 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 387 |
+
|
| 388 |
+
if self.gradient_checkpointing and self.training:
|
| 389 |
+
if use_cache:
|
| 390 |
+
logger.warning_once(
|
| 391 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 392 |
+
)
|
| 393 |
+
use_cache = False
|
| 394 |
+
|
| 395 |
+
next_decoder_cache = () if use_cache else None
|
| 396 |
+
for i, layer_module in enumerate(self.layer):
|
| 397 |
+
if output_hidden_states:
|
| 398 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 399 |
+
|
| 400 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 401 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 402 |
+
|
| 403 |
+
if self.gradient_checkpointing and self.training:
|
| 404 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 405 |
+
layer_module.__call__,
|
| 406 |
+
hidden_states,
|
| 407 |
+
attention_mask,
|
| 408 |
+
layer_head_mask,
|
| 409 |
+
encoder_hidden_states,
|
| 410 |
+
encoder_attention_mask,
|
| 411 |
+
past_key_value,
|
| 412 |
+
output_attentions,
|
| 413 |
+
)
|
| 414 |
+
else:
|
| 415 |
+
layer_outputs = layer_module(
|
| 416 |
+
hidden_states,
|
| 417 |
+
attention_mask,
|
| 418 |
+
layer_head_mask,
|
| 419 |
+
encoder_hidden_states,
|
| 420 |
+
encoder_attention_mask,
|
| 421 |
+
past_key_value,
|
| 422 |
+
output_attentions,
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
hidden_states = layer_outputs[0]
|
| 426 |
+
if use_cache:
|
| 427 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 428 |
+
if output_attentions:
|
| 429 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 430 |
+
if self.config.add_cross_attention:
|
| 431 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 432 |
+
|
| 433 |
+
if output_hidden_states:
|
| 434 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 435 |
+
|
| 436 |
+
if not return_dict:
|
| 437 |
+
return tuple(
|
| 438 |
+
v
|
| 439 |
+
for v in [
|
| 440 |
+
hidden_states,
|
| 441 |
+
next_decoder_cache,
|
| 442 |
+
all_hidden_states,
|
| 443 |
+
all_self_attentions,
|
| 444 |
+
all_cross_attentions,
|
| 445 |
+
]
|
| 446 |
+
if v is not None
|
| 447 |
+
)
|
| 448 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 449 |
+
last_hidden_state=hidden_states,
|
| 450 |
+
past_key_values=next_decoder_cache,
|
| 451 |
+
hidden_states=all_hidden_states,
|
| 452 |
+
attentions=all_self_attentions,
|
| 453 |
+
cross_attentions=all_cross_attentions,
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def load_tf_weights_in_bert_generation(
|
| 458 |
+
model, tf_hub_path, model_class, is_encoder_named_decoder=False, is_encoder=False
|
| 459 |
+
):
|
| 460 |
+
try:
|
| 461 |
+
import numpy as np
|
| 462 |
+
import tensorflow.compat.v1 as tf
|
| 463 |
+
import tensorflow_hub as hub
|
| 464 |
+
import tensorflow_text # noqa: F401
|
| 465 |
+
|
| 466 |
+
tf.disable_eager_execution()
|
| 467 |
+
except ImportError:
|
| 468 |
+
logger.error(
|
| 469 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
| 470 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
| 471 |
+
)
|
| 472 |
+
raise
|
| 473 |
+
tf_model = hub.Module(tf_hub_path)
|
| 474 |
+
init = tf.global_variables_initializer()
|
| 475 |
+
with tf.Session() as sess:
|
| 476 |
+
init.run()
|
| 477 |
+
all_variables = tf_model.variable_map
|
| 478 |
+
keep_track_variables = all_variables.copy()
|
| 479 |
+
for key in list(all_variables.keys()):
|
| 480 |
+
if "global" in key:
|
| 481 |
+
logger.info(f"Skipping {key}...")
|
| 482 |
+
continue
|
| 483 |
+
if not is_encoder:
|
| 484 |
+
model_pointer = getattr(model, model_class)
|
| 485 |
+
else:
|
| 486 |
+
model_pointer = model
|
| 487 |
+
is_embedding = False
|
| 488 |
+
logger.info(f"Trying to match {key}...")
|
| 489 |
+
# remove start_string = "module/bert/"
|
| 490 |
+
sub_layers = key.split("/")[2:]
|
| 491 |
+
if is_encoder_named_decoder and sub_layers[0] == "encoder":
|
| 492 |
+
logger.info(f"Skipping encoder layer {key} for decoder")
|
| 493 |
+
continue
|
| 494 |
+
if is_encoder and sub_layers[0] == "decoder":
|
| 495 |
+
logger.info(f"Skipping decoder layer {key} for encoder")
|
| 496 |
+
continue
|
| 497 |
+
for i, sub_layer in enumerate(sub_layers):
|
| 498 |
+
if sub_layer == "embeddings":
|
| 499 |
+
is_embedding = True
|
| 500 |
+
elif sub_layer == "LayerNorm":
|
| 501 |
+
is_embedding = False
|
| 502 |
+
if "layer" in sub_layer:
|
| 503 |
+
model_pointer = model_pointer.layer[int(sub_layer.split("_")[-1])]
|
| 504 |
+
elif sub_layer in ["kernel", "gamma"]:
|
| 505 |
+
model_pointer = model_pointer.weight
|
| 506 |
+
elif sub_layer == "beta":
|
| 507 |
+
model_pointer = model_pointer.bias
|
| 508 |
+
elif sub_layer == "encdec":
|
| 509 |
+
model_pointer = model_pointer.crossattention.self
|
| 510 |
+
elif sub_layer == "encdec_output":
|
| 511 |
+
model_pointer = model_pointer.crossattention.output
|
| 512 |
+
elif is_encoder_named_decoder and sub_layer == "decoder":
|
| 513 |
+
model_pointer = model_pointer.encoder
|
| 514 |
+
else:
|
| 515 |
+
if sub_layer == "attention" and "encdec" in sub_layers[i + 1]:
|
| 516 |
+
continue
|
| 517 |
+
try:
|
| 518 |
+
model_pointer = getattr(model_pointer, sub_layer)
|
| 519 |
+
except AttributeError:
|
| 520 |
+
logger.info(f"Skipping to initialize {key} at {sub_layer}...")
|
| 521 |
+
raise AttributeError
|
| 522 |
+
|
| 523 |
+
array = np.asarray(sess.run(all_variables[key]))
|
| 524 |
+
if not is_embedding:
|
| 525 |
+
logger.info(f"Transposing numpy weight of shape {array.shape} for {key}")
|
| 526 |
+
array = np.transpose(array)
|
| 527 |
+
else:
|
| 528 |
+
model_pointer = model_pointer.weight
|
| 529 |
+
|
| 530 |
+
if model_pointer.shape != array.shape:
|
| 531 |
+
raise ValueError(f"Pointer shape {model_pointer.shape} and array shape {array.shape} mismatched")
|
| 532 |
+
logger.info(f"Initialize PyTorch weight {key}")
|
| 533 |
+
|
| 534 |
+
model_pointer.data = torch.from_numpy(array.astype(np.float32))
|
| 535 |
+
keep_track_variables.pop(key, None)
|
| 536 |
+
|
| 537 |
+
logger.info(f"Weights not copied to PyTorch model: {', '.join(keep_track_variables.keys())}")
|
| 538 |
+
return model
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
class BertGenerationEmbeddings(nn.Module):
|
| 542 |
+
"""Construct the embeddings from word and position embeddings."""
|
| 543 |
+
|
| 544 |
+
def __init__(self, config):
|
| 545 |
+
super().__init__()
|
| 546 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 547 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 548 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 549 |
+
# any TensorFlow checkpoint file
|
| 550 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 551 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 552 |
+
|
| 553 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 554 |
+
self.register_buffer(
|
| 555 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
def forward(self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0):
|
| 559 |
+
if input_ids is not None:
|
| 560 |
+
input_shape = input_ids.size()
|
| 561 |
+
else:
|
| 562 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 563 |
+
|
| 564 |
+
seq_length = input_shape[1]
|
| 565 |
+
|
| 566 |
+
if position_ids is None:
|
| 567 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 568 |
+
|
| 569 |
+
if inputs_embeds is None:
|
| 570 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 571 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 572 |
+
|
| 573 |
+
embeddings = inputs_embeds + position_embeddings
|
| 574 |
+
embeddings = self.LayerNorm(embeddings)
|
| 575 |
+
embeddings = self.dropout(embeddings)
|
| 576 |
+
return embeddings
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
class BertGenerationPreTrainedModel(PreTrainedModel):
|
| 580 |
+
"""
|
| 581 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 582 |
+
models.
|
| 583 |
+
"""
|
| 584 |
+
|
| 585 |
+
config_class = BertGenerationConfig
|
| 586 |
+
base_model_prefix = "bert"
|
| 587 |
+
supports_gradient_checkpointing = True
|
| 588 |
+
|
| 589 |
+
def _init_weights(self, module):
|
| 590 |
+
"""Initialize the weights"""
|
| 591 |
+
if isinstance(module, nn.Linear):
|
| 592 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 593 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 594 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 595 |
+
if module.bias is not None:
|
| 596 |
+
module.bias.data.zero_()
|
| 597 |
+
elif isinstance(module, nn.Embedding):
|
| 598 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 599 |
+
if module.padding_idx is not None:
|
| 600 |
+
module.weight.data[module.padding_idx].zero_()
|
| 601 |
+
elif isinstance(module, nn.LayerNorm):
|
| 602 |
+
module.bias.data.zero_()
|
| 603 |
+
module.weight.data.fill_(1.0)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
BERT_GENERATION_START_DOCSTRING = r"""
|
| 607 |
+
|
| 608 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 609 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 610 |
+
etc.)
|
| 611 |
+
|
| 612 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 613 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 614 |
+
and behavior.
|
| 615 |
+
|
| 616 |
+
Parameters:
|
| 617 |
+
config ([`BertGenerationConfig`]): Model configuration class with all the parameters of the model.
|
| 618 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 619 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 620 |
+
"""
|
| 621 |
+
|
| 622 |
+
BERT_GENERATION_INPUTS_DOCSTRING = r"""
|
| 623 |
+
Args:
|
| 624 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
| 625 |
+
Indices of input sequence tokens in the vocabulary.
|
| 626 |
+
|
| 627 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 628 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 629 |
+
|
| 630 |
+
[What are input IDs?](../glossary#input-ids)
|
| 631 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
| 632 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 633 |
+
|
| 634 |
+
- 1 for tokens that are **not masked**,
|
| 635 |
+
- 0 for tokens that are **masked**.
|
| 636 |
+
|
| 637 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 638 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 639 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 640 |
+
config.max_position_embeddings - 1]`.
|
| 641 |
+
|
| 642 |
+
[What are position IDs?](../glossary#position-ids)
|
| 643 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 644 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 645 |
+
|
| 646 |
+
- 1 indicates the head is **not masked**,
|
| 647 |
+
- 0 indicates the head is **masked**.
|
| 648 |
+
|
| 649 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 650 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 651 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 652 |
+
model's internal embedding lookup matrix.
|
| 653 |
+
output_attentions (`bool`, *optional*):
|
| 654 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 655 |
+
tensors for more detail.
|
| 656 |
+
output_hidden_states (`bool`, *optional*):
|
| 657 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 658 |
+
more detail.
|
| 659 |
+
return_dict (`bool`, *optional*):
|
| 660 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 661 |
+
"""
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
@add_start_docstrings(
|
| 665 |
+
"The bare BertGeneration model transformer outputting raw hidden-states without any specific head on top.",
|
| 666 |
+
BERT_GENERATION_START_DOCSTRING,
|
| 667 |
+
)
|
| 668 |
+
class BertGenerationEncoder(BertGenerationPreTrainedModel):
|
| 669 |
+
"""
|
| 670 |
+
|
| 671 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 672 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
| 673 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
| 674 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
| 675 |
+
|
| 676 |
+
This model should be used when leveraging Bert or Roberta checkpoints for the [`EncoderDecoderModel`] class as
|
| 677 |
+
described in [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461)
|
| 678 |
+
by Sascha Rothe, Shashi Narayan, and Aliaksei Severyn.
|
| 679 |
+
|
| 680 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
| 681 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
| 682 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
| 683 |
+
"""
|
| 684 |
+
|
| 685 |
+
def __init__(self, config):
|
| 686 |
+
super().__init__(config)
|
| 687 |
+
self.config = config
|
| 688 |
+
|
| 689 |
+
self.embeddings = BertGenerationEmbeddings(config)
|
| 690 |
+
self.encoder = BertEncoder(config)
|
| 691 |
+
|
| 692 |
+
# Initialize weights and apply final processing
|
| 693 |
+
self.post_init()
|
| 694 |
+
|
| 695 |
+
def get_input_embeddings(self):
|
| 696 |
+
return self.embeddings.word_embeddings
|
| 697 |
+
|
| 698 |
+
def set_input_embeddings(self, value):
|
| 699 |
+
self.embeddings.word_embeddings = value
|
| 700 |
+
|
| 701 |
+
def _prune_heads(self, heads_to_prune):
|
| 702 |
+
"""
|
| 703 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 704 |
+
class PreTrainedModel
|
| 705 |
+
"""
|
| 706 |
+
for layer, heads in heads_to_prune.items():
|
| 707 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 708 |
+
|
| 709 |
+
@add_start_docstrings_to_model_forward(BERT_GENERATION_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 710 |
+
@add_code_sample_docstrings(
|
| 711 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 712 |
+
output_type=BaseModelOutputWithPastAndCrossAttentions,
|
| 713 |
+
config_class=_CONFIG_FOR_DOC,
|
| 714 |
+
)
|
| 715 |
+
def forward(
|
| 716 |
+
self,
|
| 717 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 718 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 719 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 720 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 721 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 722 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 723 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 724 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 725 |
+
use_cache: Optional[bool] = None,
|
| 726 |
+
output_attentions: Optional[bool] = None,
|
| 727 |
+
output_hidden_states: Optional[bool] = None,
|
| 728 |
+
return_dict: Optional[bool] = None,
|
| 729 |
+
) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
|
| 730 |
+
r"""
|
| 731 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 732 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 733 |
+
the model is configured as a decoder.
|
| 734 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 735 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 736 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: `1` for
|
| 737 |
+
tokens that are NOT MASKED, `0` for MASKED tokens.
|
| 738 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
| 739 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 740 |
+
|
| 741 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 742 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 743 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 744 |
+
use_cache (`bool`, *optional*):
|
| 745 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 746 |
+
`past_key_values`).
|
| 747 |
+
"""
|
| 748 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 749 |
+
output_hidden_states = (
|
| 750 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 751 |
+
)
|
| 752 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 753 |
+
|
| 754 |
+
if self.config.is_decoder:
|
| 755 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 756 |
+
else:
|
| 757 |
+
use_cache = False
|
| 758 |
+
|
| 759 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 760 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 761 |
+
elif input_ids is not None:
|
| 762 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 763 |
+
input_shape = input_ids.size()
|
| 764 |
+
elif inputs_embeds is not None:
|
| 765 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 766 |
+
else:
|
| 767 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 768 |
+
|
| 769 |
+
batch_size, seq_length = input_shape
|
| 770 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 771 |
+
|
| 772 |
+
# past_key_values_length
|
| 773 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 774 |
+
|
| 775 |
+
if attention_mask is None:
|
| 776 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
| 777 |
+
|
| 778 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 779 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 780 |
+
extended_attention_mask = None
|
| 781 |
+
if not use_cache:
|
| 782 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 783 |
+
|
| 784 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
| 785 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 786 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
| 787 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
| 788 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
| 789 |
+
if encoder_attention_mask is None:
|
| 790 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
| 791 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
| 792 |
+
else:
|
| 793 |
+
encoder_extended_attention_mask = None
|
| 794 |
+
|
| 795 |
+
# Prepare head mask if needed
|
| 796 |
+
# 1.0 in head_mask indicate we keep the head
|
| 797 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 798 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 799 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 800 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 801 |
+
|
| 802 |
+
embedding_output = self.embeddings(
|
| 803 |
+
input_ids=input_ids,
|
| 804 |
+
position_ids=position_ids,
|
| 805 |
+
inputs_embeds=inputs_embeds,
|
| 806 |
+
past_key_values_length=past_key_values_length,
|
| 807 |
+
)
|
| 808 |
+
|
| 809 |
+
encoder_outputs = self.encoder(
|
| 810 |
+
embedding_output,
|
| 811 |
+
attention_mask=extended_attention_mask,
|
| 812 |
+
head_mask=head_mask,
|
| 813 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 814 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 815 |
+
past_key_values=past_key_values,
|
| 816 |
+
use_cache=use_cache,
|
| 817 |
+
output_attentions=output_attentions,
|
| 818 |
+
output_hidden_states=output_hidden_states,
|
| 819 |
+
return_dict=return_dict,
|
| 820 |
+
)
|
| 821 |
+
sequence_output = encoder_outputs[0]
|
| 822 |
+
|
| 823 |
+
if not return_dict:
|
| 824 |
+
return (sequence_output,) + encoder_outputs[1:]
|
| 825 |
+
|
| 826 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 827 |
+
last_hidden_state=sequence_output,
|
| 828 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 829 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 830 |
+
attentions=encoder_outputs.attentions,
|
| 831 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 832 |
+
)
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
class BertGenerationOnlyLMHead(nn.Module):
|
| 836 |
+
def __init__(self, config):
|
| 837 |
+
super().__init__()
|
| 838 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
|
| 839 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 840 |
+
self.decoder.bias = self.bias
|
| 841 |
+
|
| 842 |
+
def forward(self, hidden_states):
|
| 843 |
+
logits = self.decoder(hidden_states)
|
| 844 |
+
return logits
|
| 845 |
+
|
| 846 |
+
def _tie_weights(self):
|
| 847 |
+
# To tie those two weights if they get disconnected (on TPU or when the bias is resized)
|
| 848 |
+
self.bias = self.decoder.bias
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
@add_start_docstrings(
|
| 852 |
+
"""BertGeneration Model with a `language modeling` head on top for CLM fine-tuning.""",
|
| 853 |
+
BERT_GENERATION_START_DOCSTRING,
|
| 854 |
+
)
|
| 855 |
+
class BertGenerationDecoder(BertGenerationPreTrainedModel):
|
| 856 |
+
_tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
|
| 857 |
+
|
| 858 |
+
def __init__(self, config):
|
| 859 |
+
super().__init__(config)
|
| 860 |
+
|
| 861 |
+
if not config.is_decoder:
|
| 862 |
+
logger.warning("If you want to use `BertGenerationDecoder` as a standalone, add `is_decoder=True.`")
|
| 863 |
+
|
| 864 |
+
self.bert = BertGenerationEncoder(config)
|
| 865 |
+
self.lm_head = BertGenerationOnlyLMHead(config)
|
| 866 |
+
|
| 867 |
+
# Initialize weights and apply final processing
|
| 868 |
+
self.post_init()
|
| 869 |
+
|
| 870 |
+
def get_output_embeddings(self):
|
| 871 |
+
return self.lm_head.decoder
|
| 872 |
+
|
| 873 |
+
def set_output_embeddings(self, new_embeddings):
|
| 874 |
+
self.lm_head.decoder = new_embeddings
|
| 875 |
+
|
| 876 |
+
@add_start_docstrings_to_model_forward(BERT_GENERATION_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 877 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
|
| 878 |
+
def forward(
|
| 879 |
+
self,
|
| 880 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 881 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 882 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 883 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 884 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 885 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 886 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 887 |
+
labels: Optional[torch.Tensor] = None,
|
| 888 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 889 |
+
use_cache: Optional[bool] = None,
|
| 890 |
+
output_attentions: Optional[bool] = None,
|
| 891 |
+
output_hidden_states: Optional[bool] = None,
|
| 892 |
+
return_dict: Optional[bool] = None,
|
| 893 |
+
) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
|
| 894 |
+
r"""
|
| 895 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 896 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 897 |
+
the model is configured as a decoder.
|
| 898 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 899 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 900 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 901 |
+
|
| 902 |
+
- 1 for tokens that are **not masked**,
|
| 903 |
+
- 0 for tokens that are **masked**.
|
| 904 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 905 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
| 906 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
| 907 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 908 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
| 909 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 910 |
+
|
| 911 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 912 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 913 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 914 |
+
use_cache (`bool`, *optional*):
|
| 915 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 916 |
+
`past_key_values`).
|
| 917 |
+
|
| 918 |
+
Returns:
|
| 919 |
+
|
| 920 |
+
Example:
|
| 921 |
+
|
| 922 |
+
```python
|
| 923 |
+
>>> from transformers import AutoTokenizer, BertGenerationDecoder, BertGenerationConfig
|
| 924 |
+
>>> import torch
|
| 925 |
+
|
| 926 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder")
|
| 927 |
+
>>> config = BertGenerationConfig.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder")
|
| 928 |
+
>>> config.is_decoder = True
|
| 929 |
+
>>> model = BertGenerationDecoder.from_pretrained(
|
| 930 |
+
... "google/bert_for_seq_generation_L-24_bbc_encoder", config=config
|
| 931 |
+
... )
|
| 932 |
+
|
| 933 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_token_type_ids=False, return_tensors="pt")
|
| 934 |
+
>>> outputs = model(**inputs)
|
| 935 |
+
|
| 936 |
+
>>> prediction_logits = outputs.logits
|
| 937 |
+
```"""
|
| 938 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 939 |
+
if labels is not None:
|
| 940 |
+
use_cache = False
|
| 941 |
+
|
| 942 |
+
outputs = self.bert(
|
| 943 |
+
input_ids,
|
| 944 |
+
attention_mask=attention_mask,
|
| 945 |
+
position_ids=position_ids,
|
| 946 |
+
head_mask=head_mask,
|
| 947 |
+
inputs_embeds=inputs_embeds,
|
| 948 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 949 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 950 |
+
past_key_values=past_key_values,
|
| 951 |
+
use_cache=use_cache,
|
| 952 |
+
output_attentions=output_attentions,
|
| 953 |
+
output_hidden_states=output_hidden_states,
|
| 954 |
+
return_dict=return_dict,
|
| 955 |
+
)
|
| 956 |
+
|
| 957 |
+
sequence_output = outputs[0]
|
| 958 |
+
prediction_scores = self.lm_head(sequence_output)
|
| 959 |
+
|
| 960 |
+
lm_loss = None
|
| 961 |
+
if labels is not None:
|
| 962 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
| 963 |
+
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
|
| 964 |
+
labels = labels[:, 1:].contiguous()
|
| 965 |
+
loss_fct = CrossEntropyLoss()
|
| 966 |
+
lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 967 |
+
|
| 968 |
+
if not return_dict:
|
| 969 |
+
output = (prediction_scores,) + outputs[1:]
|
| 970 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
| 971 |
+
|
| 972 |
+
return CausalLMOutputWithCrossAttentions(
|
| 973 |
+
loss=lm_loss,
|
| 974 |
+
logits=prediction_scores,
|
| 975 |
+
past_key_values=outputs.past_key_values,
|
| 976 |
+
hidden_states=outputs.hidden_states,
|
| 977 |
+
attentions=outputs.attentions,
|
| 978 |
+
cross_attentions=outputs.cross_attentions,
|
| 979 |
+
)
|
| 980 |
+
|
| 981 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
|
| 982 |
+
input_shape = input_ids.shape
|
| 983 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
| 984 |
+
if attention_mask is None:
|
| 985 |
+
attention_mask = input_ids.new_ones(input_shape)
|
| 986 |
+
|
| 987 |
+
# cut decoder_input_ids if past_key_values is used
|
| 988 |
+
if past_key_values is not None:
|
| 989 |
+
past_length = past_key_values[0][0].shape[2]
|
| 990 |
+
|
| 991 |
+
# Some generation methods already pass only the last input ID
|
| 992 |
+
if input_ids.shape[1] > past_length:
|
| 993 |
+
remove_prefix_length = past_length
|
| 994 |
+
else:
|
| 995 |
+
# Default to old behavior: keep only final ID
|
| 996 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
| 997 |
+
|
| 998 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
| 999 |
+
|
| 1000 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
|
| 1001 |
+
|
| 1002 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
| 1003 |
+
reordered_past = ()
|
| 1004 |
+
for layer_past in past_key_values:
|
| 1005 |
+
reordered_past += (
|
| 1006 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 1007 |
+
)
|
| 1008 |
+
return reordered_past
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/bert_generation/tokenization_bert_generation.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ATION. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Tokenization class for model BertGeneration."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
from shutil import copyfile
|
| 20 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import sentencepiece as spm
|
| 23 |
+
|
| 24 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 25 |
+
from ...utils import logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
|
| 31 |
+
|
| 32 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
| 33 |
+
"vocab_file": {
|
| 34 |
+
"bert_for_seq_generation": (
|
| 35 |
+
"https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model"
|
| 36 |
+
),
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {"bert_for_seq_generation": 512}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class BertGenerationTokenizer(PreTrainedTokenizer):
|
| 44 |
+
"""
|
| 45 |
+
Construct a BertGeneration tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
| 46 |
+
|
| 47 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 48 |
+
this superclass for more information regarding those methods.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
vocab_file (`str`):
|
| 52 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 53 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 54 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 55 |
+
The begin of sequence token.
|
| 56 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 57 |
+
The end of sequence token.
|
| 58 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 59 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 60 |
+
token instead.
|
| 61 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 62 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 63 |
+
sep_token (`str`, *optional*, defaults to `"<::::>"`):
|
| 64 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 65 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 66 |
+
token of a sequence built with special tokens.
|
| 67 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 68 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 69 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 70 |
+
to set:
|
| 71 |
+
|
| 72 |
+
- `enable_sampling`: Enable subword regularization.
|
| 73 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 74 |
+
|
| 75 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 76 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 77 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 78 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 79 |
+
|
| 80 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 81 |
+
BPE-dropout.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 85 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
| 86 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
| 87 |
+
prefix_tokens: List[int] = []
|
| 88 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 89 |
+
|
| 90 |
+
def __init__(
|
| 91 |
+
self,
|
| 92 |
+
vocab_file,
|
| 93 |
+
bos_token="<s>",
|
| 94 |
+
eos_token="</s>",
|
| 95 |
+
unk_token="<unk>",
|
| 96 |
+
pad_token="<pad>",
|
| 97 |
+
sep_token="<::::>",
|
| 98 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
| 99 |
+
**kwargs,
|
| 100 |
+
) -> None:
|
| 101 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 102 |
+
|
| 103 |
+
self.vocab_file = vocab_file
|
| 104 |
+
|
| 105 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 106 |
+
self.sp_model.Load(vocab_file)
|
| 107 |
+
|
| 108 |
+
# Add extra_ids to the special token list
|
| 109 |
+
super().__init__(
|
| 110 |
+
bos_token=bos_token,
|
| 111 |
+
eos_token=eos_token,
|
| 112 |
+
unk_token=unk_token,
|
| 113 |
+
pad_token=pad_token,
|
| 114 |
+
sep_token=sep_token,
|
| 115 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 116 |
+
**kwargs,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
@property
|
| 120 |
+
def vocab_size(self):
|
| 121 |
+
return self.sp_model.get_piece_size()
|
| 122 |
+
|
| 123 |
+
def get_vocab(self):
|
| 124 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 125 |
+
vocab.update(self.added_tokens_encoder)
|
| 126 |
+
return vocab
|
| 127 |
+
|
| 128 |
+
def __getstate__(self):
|
| 129 |
+
state = self.__dict__.copy()
|
| 130 |
+
state["sp_model"] = None
|
| 131 |
+
return state
|
| 132 |
+
|
| 133 |
+
def __setstate__(self, d):
|
| 134 |
+
self.__dict__ = d
|
| 135 |
+
|
| 136 |
+
# for backward compatibility
|
| 137 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 138 |
+
self.sp_model_kwargs = {}
|
| 139 |
+
|
| 140 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 141 |
+
self.sp_model.Load(self.vocab_file)
|
| 142 |
+
|
| 143 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 144 |
+
"""Take as input a string and return a list of strings (tokens) for words/sub-words"""
|
| 145 |
+
return self.sp_model.encode(text, out_type=str)
|
| 146 |
+
|
| 147 |
+
def _convert_token_to_id(self, token):
|
| 148 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 149 |
+
return self.sp_model.piece_to_id(token)
|
| 150 |
+
|
| 151 |
+
def _convert_id_to_token(self, index):
|
| 152 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 153 |
+
token = self.sp_model.IdToPiece(index)
|
| 154 |
+
return token
|
| 155 |
+
|
| 156 |
+
def convert_tokens_to_string(self, tokens):
|
| 157 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 158 |
+
current_sub_tokens = []
|
| 159 |
+
out_string = ""
|
| 160 |
+
for token in tokens:
|
| 161 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
| 162 |
+
if token in self.all_special_tokens:
|
| 163 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
| 164 |
+
current_sub_tokens = []
|
| 165 |
+
else:
|
| 166 |
+
current_sub_tokens.append(token)
|
| 167 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
| 168 |
+
return out_string.strip()
|
| 169 |
+
|
| 170 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 171 |
+
if not os.path.isdir(save_directory):
|
| 172 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 173 |
+
return
|
| 174 |
+
out_vocab_file = os.path.join(
|
| 175 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 179 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 180 |
+
elif not os.path.isfile(self.vocab_file):
|
| 181 |
+
with open(out_vocab_file, "wb") as fi:
|
| 182 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 183 |
+
fi.write(content_spiece_model)
|
| 184 |
+
|
| 185 |
+
return (out_vocab_file,)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__init__.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 (
|
| 17 |
+
OptionalDependencyNotAvailable,
|
| 18 |
+
_LazyModule,
|
| 19 |
+
is_flax_available,
|
| 20 |
+
is_tf_available,
|
| 21 |
+
is_tokenizers_available,
|
| 22 |
+
is_torch_available,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
_import_structure = {
|
| 27 |
+
"configuration_blenderbot_small": [
|
| 28 |
+
"BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
| 29 |
+
"BlenderbotSmallConfig",
|
| 30 |
+
"BlenderbotSmallOnnxConfig",
|
| 31 |
+
],
|
| 32 |
+
"tokenization_blenderbot_small": ["BlenderbotSmallTokenizer"],
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
if not is_tokenizers_available():
|
| 37 |
+
raise OptionalDependencyNotAvailable()
|
| 38 |
+
except OptionalDependencyNotAvailable:
|
| 39 |
+
pass
|
| 40 |
+
else:
|
| 41 |
+
_import_structure["tokenization_blenderbot_small_fast"] = ["BlenderbotSmallTokenizerFast"]
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
if not is_torch_available():
|
| 45 |
+
raise OptionalDependencyNotAvailable()
|
| 46 |
+
except OptionalDependencyNotAvailable:
|
| 47 |
+
pass
|
| 48 |
+
else:
|
| 49 |
+
_import_structure["modeling_blenderbot_small"] = [
|
| 50 |
+
"BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 51 |
+
"BlenderbotSmallForCausalLM",
|
| 52 |
+
"BlenderbotSmallForConditionalGeneration",
|
| 53 |
+
"BlenderbotSmallModel",
|
| 54 |
+
"BlenderbotSmallPreTrainedModel",
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
if not is_tf_available():
|
| 59 |
+
raise OptionalDependencyNotAvailable()
|
| 60 |
+
except OptionalDependencyNotAvailable:
|
| 61 |
+
pass
|
| 62 |
+
else:
|
| 63 |
+
_import_structure["modeling_tf_blenderbot_small"] = [
|
| 64 |
+
"TFBlenderbotSmallForConditionalGeneration",
|
| 65 |
+
"TFBlenderbotSmallModel",
|
| 66 |
+
"TFBlenderbotSmallPreTrainedModel",
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
if not is_flax_available():
|
| 71 |
+
raise OptionalDependencyNotAvailable()
|
| 72 |
+
except OptionalDependencyNotAvailable:
|
| 73 |
+
pass
|
| 74 |
+
else:
|
| 75 |
+
_import_structure["modeling_flax_blenderbot_small"] = [
|
| 76 |
+
"FlaxBlenderbotSmallForConditionalGeneration",
|
| 77 |
+
"FlaxBlenderbotSmallModel",
|
| 78 |
+
"FlaxBlenderbotSmallPreTrainedModel",
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
if TYPE_CHECKING:
|
| 82 |
+
from .configuration_blenderbot_small import (
|
| 83 |
+
BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
| 84 |
+
BlenderbotSmallConfig,
|
| 85 |
+
BlenderbotSmallOnnxConfig,
|
| 86 |
+
)
|
| 87 |
+
from .tokenization_blenderbot_small import BlenderbotSmallTokenizer
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
if not is_tokenizers_available():
|
| 91 |
+
raise OptionalDependencyNotAvailable()
|
| 92 |
+
except OptionalDependencyNotAvailable:
|
| 93 |
+
pass
|
| 94 |
+
else:
|
| 95 |
+
from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
if not is_torch_available():
|
| 99 |
+
raise OptionalDependencyNotAvailable()
|
| 100 |
+
except OptionalDependencyNotAvailable:
|
| 101 |
+
pass
|
| 102 |
+
else:
|
| 103 |
+
from .modeling_blenderbot_small import (
|
| 104 |
+
BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 105 |
+
BlenderbotSmallForCausalLM,
|
| 106 |
+
BlenderbotSmallForConditionalGeneration,
|
| 107 |
+
BlenderbotSmallModel,
|
| 108 |
+
BlenderbotSmallPreTrainedModel,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
if not is_tf_available():
|
| 113 |
+
raise OptionalDependencyNotAvailable()
|
| 114 |
+
except OptionalDependencyNotAvailable:
|
| 115 |
+
pass
|
| 116 |
+
else:
|
| 117 |
+
from .modeling_tf_blenderbot_small import (
|
| 118 |
+
TFBlenderbotSmallForConditionalGeneration,
|
| 119 |
+
TFBlenderbotSmallModel,
|
| 120 |
+
TFBlenderbotSmallPreTrainedModel,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
try:
|
| 124 |
+
if not is_flax_available():
|
| 125 |
+
raise OptionalDependencyNotAvailable()
|
| 126 |
+
except OptionalDependencyNotAvailable:
|
| 127 |
+
pass
|
| 128 |
+
else:
|
| 129 |
+
from .modeling_flax_blenderbot_small import (
|
| 130 |
+
FlaxBlenderbotSmallForConditionalGeneration,
|
| 131 |
+
FlaxBlenderbotSmallModel,
|
| 132 |
+
FlaxBlenderbotSmallPreTrainedModel,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
else:
|
| 136 |
+
import sys
|
| 137 |
+
|
| 138 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (2.05 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-310.pyc
ADDED
|
Binary file (12.5 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-310.pyc
ADDED
|
Binary file (52.5 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-310.pyc
ADDED
|
Binary file (43.2 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_tf_blenderbot_small.cpython-310.pyc
ADDED
|
Binary file (49.3 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-310.pyc
ADDED
|
Binary file (8.73 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small_fast.cpython-310.pyc
ADDED
|
Binary file (4.14 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/configuration_blenderbot_small.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Facebook, Inc. and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" BlenderbotSmall model configuration"""
|
| 16 |
+
|
| 17 |
+
from collections import OrderedDict
|
| 18 |
+
from typing import Any, Mapping, Optional
|
| 19 |
+
|
| 20 |
+
from ... import PreTrainedTokenizer
|
| 21 |
+
from ...configuration_utils import PretrainedConfig
|
| 22 |
+
from ...file_utils import TensorType, is_torch_available
|
| 23 |
+
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeq2SeqConfigWithPast
|
| 24 |
+
from ...onnx.utils import compute_effective_axis_dimension
|
| 25 |
+
from ...utils import logging
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 31 |
+
"facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json",
|
| 32 |
+
# See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class BlenderbotSmallConfig(PretrainedConfig):
|
| 37 |
+
r"""
|
| 38 |
+
This is the configuration class to store the configuration of a [`BlenderbotSmallModel`]. It is used to instantiate
|
| 39 |
+
an BlenderbotSmall model according to the specified arguments, defining the model architecture. Instantiating a
|
| 40 |
+
configuration with the defaults will yield a similar configuration to that of the BlenderbotSmall
|
| 41 |
+
[facebook/blenderbot_small-90M](https://huggingface.co/facebook/blenderbot_small-90M) architecture.
|
| 42 |
+
|
| 43 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 44 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
vocab_size (`int`, *optional*, defaults to 50265):
|
| 49 |
+
Vocabulary size of the BlenderbotSmall model. Defines the number of different tokens that can be
|
| 50 |
+
represented by the `inputs_ids` passed when calling [`BlenderbotSmallModel`] or [`TFBlenderbotSmallModel`].
|
| 51 |
+
d_model (`int`, *optional*, defaults to 512):
|
| 52 |
+
Dimensionality of the layers and the pooler layer.
|
| 53 |
+
encoder_layers (`int`, *optional*, defaults to 8):
|
| 54 |
+
Number of encoder layers.
|
| 55 |
+
decoder_layers (`int`, *optional*, defaults to 8):
|
| 56 |
+
Number of decoder layers.
|
| 57 |
+
encoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 58 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 59 |
+
decoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 60 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 61 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 2048):
|
| 62 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
|
| 63 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 2048):
|
| 64 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
|
| 65 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 66 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 67 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 68 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 69 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 70 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 71 |
+
The dropout ratio for the attention probabilities.
|
| 72 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 73 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 74 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 75 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 76 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 77 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 78 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 79 |
+
encoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 80 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 81 |
+
for more details.
|
| 82 |
+
decoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 83 |
+
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 84 |
+
for more details.
|
| 85 |
+
scale_embedding (`bool`, *optional*, defaults to `False`):
|
| 86 |
+
Scale embeddings by diving by sqrt(d_model).
|
| 87 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 88 |
+
Whether or not the model should return the last key/values attentions (not used by all models)
|
| 89 |
+
forced_eos_token_id (`int`, *optional*, defaults to 2):
|
| 90 |
+
The id of the token to force as the last generated token when `max_length` is reached. Usually set to
|
| 91 |
+
`eos_token_id`.
|
| 92 |
+
|
| 93 |
+
Example:
|
| 94 |
+
|
| 95 |
+
```python
|
| 96 |
+
>>> from transformers import BlenderbotSmallConfig, BlenderbotSmallModel
|
| 97 |
+
|
| 98 |
+
>>> # Initializing a BlenderbotSmall facebook/blenderbot_small-90M style configuration
|
| 99 |
+
>>> configuration = BlenderbotSmallConfig()
|
| 100 |
+
|
| 101 |
+
>>> # Initializing a model (with random weights) from the facebook/blenderbot_small-90M style configuration
|
| 102 |
+
>>> model = BlenderbotSmallModel(configuration)
|
| 103 |
+
|
| 104 |
+
>>> # Accessing the model configuration
|
| 105 |
+
>>> configuration = model.config
|
| 106 |
+
```"""
|
| 107 |
+
|
| 108 |
+
model_type = "blenderbot-small"
|
| 109 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 110 |
+
attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
|
| 111 |
+
|
| 112 |
+
def __init__(
|
| 113 |
+
self,
|
| 114 |
+
vocab_size=50265,
|
| 115 |
+
max_position_embeddings=512,
|
| 116 |
+
encoder_layers=8,
|
| 117 |
+
encoder_ffn_dim=2048,
|
| 118 |
+
encoder_attention_heads=16,
|
| 119 |
+
decoder_layers=8,
|
| 120 |
+
decoder_ffn_dim=2048,
|
| 121 |
+
decoder_attention_heads=16,
|
| 122 |
+
encoder_layerdrop=0.0,
|
| 123 |
+
decoder_layerdrop=0.0,
|
| 124 |
+
use_cache=True,
|
| 125 |
+
is_encoder_decoder=True,
|
| 126 |
+
activation_function="gelu",
|
| 127 |
+
d_model=512,
|
| 128 |
+
dropout=0.1,
|
| 129 |
+
attention_dropout=0.0,
|
| 130 |
+
activation_dropout=0.0,
|
| 131 |
+
init_std=0.02,
|
| 132 |
+
decoder_start_token_id=1,
|
| 133 |
+
scale_embedding=False,
|
| 134 |
+
pad_token_id=0,
|
| 135 |
+
bos_token_id=1,
|
| 136 |
+
eos_token_id=2,
|
| 137 |
+
forced_eos_token_id=2,
|
| 138 |
+
**kwargs,
|
| 139 |
+
):
|
| 140 |
+
self.vocab_size = vocab_size
|
| 141 |
+
self.max_position_embeddings = max_position_embeddings
|
| 142 |
+
self.d_model = d_model
|
| 143 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 144 |
+
self.encoder_layers = encoder_layers
|
| 145 |
+
self.encoder_attention_heads = encoder_attention_heads
|
| 146 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 147 |
+
self.decoder_layers = decoder_layers
|
| 148 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 149 |
+
self.dropout = dropout
|
| 150 |
+
self.attention_dropout = attention_dropout
|
| 151 |
+
self.activation_dropout = activation_dropout
|
| 152 |
+
self.activation_function = activation_function
|
| 153 |
+
self.init_std = init_std
|
| 154 |
+
self.encoder_layerdrop = encoder_layerdrop
|
| 155 |
+
self.decoder_layerdrop = decoder_layerdrop
|
| 156 |
+
self.use_cache = use_cache
|
| 157 |
+
self.num_hidden_layers = encoder_layers
|
| 158 |
+
self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
|
| 159 |
+
|
| 160 |
+
super().__init__(
|
| 161 |
+
pad_token_id=pad_token_id,
|
| 162 |
+
bos_token_id=bos_token_id,
|
| 163 |
+
eos_token_id=eos_token_id,
|
| 164 |
+
is_encoder_decoder=is_encoder_decoder,
|
| 165 |
+
decoder_start_token_id=decoder_start_token_id,
|
| 166 |
+
forced_eos_token_id=forced_eos_token_id,
|
| 167 |
+
**kwargs,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig
|
| 172 |
+
class BlenderbotSmallOnnxConfig(OnnxSeq2SeqConfigWithPast):
|
| 173 |
+
@property
|
| 174 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 175 |
+
if self.task in ["default", "seq2seq-lm"]:
|
| 176 |
+
common_inputs = OrderedDict(
|
| 177 |
+
[
|
| 178 |
+
("input_ids", {0: "batch", 1: "encoder_sequence"}),
|
| 179 |
+
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
|
| 180 |
+
]
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
if self.use_past:
|
| 184 |
+
common_inputs["decoder_input_ids"] = {0: "batch"}
|
| 185 |
+
common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
|
| 186 |
+
else:
|
| 187 |
+
common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
|
| 188 |
+
common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
|
| 189 |
+
|
| 190 |
+
if self.use_past:
|
| 191 |
+
self.fill_with_past_key_values_(common_inputs, direction="inputs")
|
| 192 |
+
elif self.task == "causal-lm":
|
| 193 |
+
# TODO: figure this case out.
|
| 194 |
+
common_inputs = OrderedDict(
|
| 195 |
+
[
|
| 196 |
+
("input_ids", {0: "batch", 1: "encoder_sequence"}),
|
| 197 |
+
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
|
| 198 |
+
]
|
| 199 |
+
)
|
| 200 |
+
if self.use_past:
|
| 201 |
+
num_encoder_layers, _ = self.num_layers
|
| 202 |
+
for i in range(num_encoder_layers):
|
| 203 |
+
common_inputs[f"past_key_values.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
|
| 204 |
+
common_inputs[f"past_key_values.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
|
| 205 |
+
else:
|
| 206 |
+
common_inputs = OrderedDict(
|
| 207 |
+
[
|
| 208 |
+
("input_ids", {0: "batch", 1: "encoder_sequence"}),
|
| 209 |
+
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
|
| 210 |
+
("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
|
| 211 |
+
("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
|
| 212 |
+
]
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
return common_inputs
|
| 216 |
+
|
| 217 |
+
@property
|
| 218 |
+
def outputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 219 |
+
if self.task in ["default", "seq2seq-lm"]:
|
| 220 |
+
common_outputs = super().outputs
|
| 221 |
+
else:
|
| 222 |
+
common_outputs = super(OnnxConfigWithPast, self).outputs
|
| 223 |
+
if self.use_past:
|
| 224 |
+
num_encoder_layers, _ = self.num_layers
|
| 225 |
+
for i in range(num_encoder_layers):
|
| 226 |
+
common_outputs[f"present.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
|
| 227 |
+
common_outputs[f"present.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
|
| 228 |
+
return common_outputs
|
| 229 |
+
|
| 230 |
+
def _generate_dummy_inputs_for_default_and_seq2seq_lm(
|
| 231 |
+
self,
|
| 232 |
+
tokenizer: PreTrainedTokenizer,
|
| 233 |
+
batch_size: int = -1,
|
| 234 |
+
seq_length: int = -1,
|
| 235 |
+
is_pair: bool = False,
|
| 236 |
+
framework: Optional[TensorType] = None,
|
| 237 |
+
) -> Mapping[str, Any]:
|
| 238 |
+
encoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 239 |
+
tokenizer, batch_size, seq_length, is_pair, framework
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# Generate decoder inputs
|
| 243 |
+
decoder_seq_length = seq_length if not self.use_past else 1
|
| 244 |
+
decoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 245 |
+
tokenizer, batch_size, decoder_seq_length, is_pair, framework
|
| 246 |
+
)
|
| 247 |
+
decoder_inputs = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
|
| 248 |
+
common_inputs = dict(**encoder_inputs, **decoder_inputs)
|
| 249 |
+
|
| 250 |
+
if self.use_past:
|
| 251 |
+
if not is_torch_available():
|
| 252 |
+
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
|
| 253 |
+
else:
|
| 254 |
+
import torch
|
| 255 |
+
batch, encoder_seq_length = common_inputs["input_ids"].shape
|
| 256 |
+
decoder_seq_length = common_inputs["decoder_input_ids"].shape[1]
|
| 257 |
+
num_encoder_attention_heads, num_decoder_attention_heads = self.num_attention_heads
|
| 258 |
+
encoder_shape = (
|
| 259 |
+
batch,
|
| 260 |
+
num_encoder_attention_heads,
|
| 261 |
+
encoder_seq_length,
|
| 262 |
+
self._config.hidden_size // num_encoder_attention_heads,
|
| 263 |
+
)
|
| 264 |
+
decoder_past_length = decoder_seq_length + 3
|
| 265 |
+
decoder_shape = (
|
| 266 |
+
batch,
|
| 267 |
+
num_decoder_attention_heads,
|
| 268 |
+
decoder_past_length,
|
| 269 |
+
self._config.hidden_size // num_decoder_attention_heads,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
common_inputs["decoder_attention_mask"] = torch.cat(
|
| 273 |
+
[common_inputs["decoder_attention_mask"], torch.ones(batch, decoder_past_length)], dim=1
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
common_inputs["past_key_values"] = []
|
| 277 |
+
# If the number of encoder and decoder layers are present in the model configuration, both are considered
|
| 278 |
+
num_encoder_layers, num_decoder_layers = self.num_layers
|
| 279 |
+
min_num_layers = min(num_encoder_layers, num_decoder_layers)
|
| 280 |
+
max_num_layers = max(num_encoder_layers, num_decoder_layers) - min_num_layers
|
| 281 |
+
remaining_side_name = "encoder" if num_encoder_layers > num_decoder_layers else "decoder"
|
| 282 |
+
|
| 283 |
+
for _ in range(min_num_layers):
|
| 284 |
+
common_inputs["past_key_values"].append(
|
| 285 |
+
(
|
| 286 |
+
torch.zeros(decoder_shape),
|
| 287 |
+
torch.zeros(decoder_shape),
|
| 288 |
+
torch.zeros(encoder_shape),
|
| 289 |
+
torch.zeros(encoder_shape),
|
| 290 |
+
)
|
| 291 |
+
)
|
| 292 |
+
# TODO: test this.
|
| 293 |
+
shape = encoder_shape if remaining_side_name == "encoder" else decoder_shape
|
| 294 |
+
for _ in range(min_num_layers, max_num_layers):
|
| 295 |
+
common_inputs["past_key_values"].append((torch.zeros(shape), torch.zeros(shape)))
|
| 296 |
+
return common_inputs
|
| 297 |
+
|
| 298 |
+
def _generate_dummy_inputs_for_causal_lm(
|
| 299 |
+
self,
|
| 300 |
+
tokenizer: PreTrainedTokenizer,
|
| 301 |
+
batch_size: int = -1,
|
| 302 |
+
seq_length: int = -1,
|
| 303 |
+
is_pair: bool = False,
|
| 304 |
+
framework: Optional[TensorType] = None,
|
| 305 |
+
) -> Mapping[str, Any]:
|
| 306 |
+
common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 307 |
+
tokenizer, batch_size, seq_length, is_pair, framework
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
if self.use_past:
|
| 311 |
+
if not is_torch_available():
|
| 312 |
+
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
|
| 313 |
+
else:
|
| 314 |
+
import torch
|
| 315 |
+
batch, seqlen = common_inputs["input_ids"].shape
|
| 316 |
+
# Not using the same length for past_key_values
|
| 317 |
+
past_key_values_length = seqlen + 2
|
| 318 |
+
num_encoder_layers, _ = self.num_layers
|
| 319 |
+
num_encoder_attention_heads, _ = self.num_attention_heads
|
| 320 |
+
past_shape = (
|
| 321 |
+
batch,
|
| 322 |
+
num_encoder_attention_heads,
|
| 323 |
+
past_key_values_length,
|
| 324 |
+
self._config.hidden_size // num_encoder_attention_heads,
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
mask_dtype = common_inputs["attention_mask"].dtype
|
| 328 |
+
common_inputs["attention_mask"] = torch.cat(
|
| 329 |
+
[common_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
|
| 330 |
+
)
|
| 331 |
+
common_inputs["past_key_values"] = [
|
| 332 |
+
(torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(num_encoder_layers)
|
| 333 |
+
]
|
| 334 |
+
return common_inputs
|
| 335 |
+
|
| 336 |
+
def _generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 337 |
+
self,
|
| 338 |
+
tokenizer: PreTrainedTokenizer,
|
| 339 |
+
batch_size: int = -1,
|
| 340 |
+
seq_length: int = -1,
|
| 341 |
+
is_pair: bool = False,
|
| 342 |
+
framework: Optional[TensorType] = None,
|
| 343 |
+
) -> Mapping[str, Any]:
|
| 344 |
+
# Copied from OnnxConfig.generate_dummy_inputs
|
| 345 |
+
# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
|
| 346 |
+
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
|
| 347 |
+
batch_size = compute_effective_axis_dimension(
|
| 348 |
+
batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
|
| 352 |
+
token_to_add = tokenizer.num_special_tokens_to_add(is_pair)
|
| 353 |
+
seq_length = compute_effective_axis_dimension(
|
| 354 |
+
seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
# Generate dummy inputs according to compute batch and sequence
|
| 358 |
+
dummy_input = [" ".join([tokenizer.unk_token]) * seq_length] * batch_size
|
| 359 |
+
common_inputs = dict(tokenizer(dummy_input, return_tensors=framework))
|
| 360 |
+
return common_inputs
|
| 361 |
+
|
| 362 |
+
def generate_dummy_inputs(
|
| 363 |
+
self,
|
| 364 |
+
tokenizer: PreTrainedTokenizer,
|
| 365 |
+
batch_size: int = -1,
|
| 366 |
+
seq_length: int = -1,
|
| 367 |
+
is_pair: bool = False,
|
| 368 |
+
framework: Optional[TensorType] = None,
|
| 369 |
+
) -> Mapping[str, Any]:
|
| 370 |
+
if self.task in ["default", "seq2seq-lm"]:
|
| 371 |
+
common_inputs = self._generate_dummy_inputs_for_default_and_seq2seq_lm(
|
| 372 |
+
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
elif self.task == "causal-lm":
|
| 376 |
+
common_inputs = self._generate_dummy_inputs_for_causal_lm(
|
| 377 |
+
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
| 378 |
+
)
|
| 379 |
+
else:
|
| 380 |
+
common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 381 |
+
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
return common_inputs
|
| 385 |
+
|
| 386 |
+
def _flatten_past_key_values_(self, flattened_output, name, idx, t):
|
| 387 |
+
if self.task in ["default", "seq2seq-lm"]:
|
| 388 |
+
flattened_output = super()._flatten_past_key_values_(flattened_output, name, idx, t)
|
| 389 |
+
else:
|
| 390 |
+
flattened_output = super(OnnxSeq2SeqConfigWithPast, self)._flatten_past_key_values_(
|
| 391 |
+
flattened_output, name, idx, t
|
| 392 |
+
)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/modeling_blenderbot_small.py
ADDED
|
@@ -0,0 +1,1570 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Facebook, Inc. and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" PyTorch BlenderbotSmall model."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import copy
|
| 19 |
+
import math
|
| 20 |
+
from typing import List, Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.utils.checkpoint
|
| 24 |
+
from torch import nn
|
| 25 |
+
from torch.nn import CrossEntropyLoss
|
| 26 |
+
|
| 27 |
+
from ...activations import ACT2FN
|
| 28 |
+
from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
|
| 29 |
+
from ...modeling_outputs import (
|
| 30 |
+
BaseModelOutput,
|
| 31 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 32 |
+
CausalLMOutputWithCrossAttentions,
|
| 33 |
+
Seq2SeqLMOutput,
|
| 34 |
+
Seq2SeqModelOutput,
|
| 35 |
+
)
|
| 36 |
+
from ...modeling_utils import PreTrainedModel
|
| 37 |
+
from ...utils import (
|
| 38 |
+
add_end_docstrings,
|
| 39 |
+
add_start_docstrings,
|
| 40 |
+
add_start_docstrings_to_model_forward,
|
| 41 |
+
logging,
|
| 42 |
+
replace_return_docstrings,
|
| 43 |
+
)
|
| 44 |
+
from .configuration_blenderbot_small import BlenderbotSmallConfig
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
_CONFIG_FOR_DOC = "BlenderbotSmallConfig"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 53 |
+
"facebook/blenderbot_small-90M",
|
| 54 |
+
# See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# Copied from transformers.models.bart.modeling_bart.shift_tokens_right
|
| 59 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 60 |
+
"""
|
| 61 |
+
Shift input ids one token to the right.
|
| 62 |
+
"""
|
| 63 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 64 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 65 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 66 |
+
|
| 67 |
+
if pad_token_id is None:
|
| 68 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 69 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 70 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 71 |
+
|
| 72 |
+
return shifted_input_ids
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# Copied from transformers.models.blenderbot.modeling_blenderbot.BlenderbotLearnedPositionalEmbedding with Blenderbot->BlenderbotSmall
|
| 76 |
+
class BlenderbotSmallLearnedPositionalEmbedding(nn.Embedding):
|
| 77 |
+
"""
|
| 78 |
+
This module learns positional embeddings up to a fixed maximum size.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
def __init__(self, num_embeddings: int, embedding_dim: int):
|
| 82 |
+
super().__init__(num_embeddings, embedding_dim)
|
| 83 |
+
|
| 84 |
+
def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0):
|
| 85 |
+
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
|
| 86 |
+
bsz, seq_len = input_ids_shape[:2]
|
| 87 |
+
positions = torch.arange(
|
| 88 |
+
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
|
| 89 |
+
)
|
| 90 |
+
return super().forward(positions)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->BlenderbotSmall
|
| 94 |
+
class BlenderbotSmallAttention(nn.Module):
|
| 95 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 96 |
+
|
| 97 |
+
def __init__(
|
| 98 |
+
self,
|
| 99 |
+
embed_dim: int,
|
| 100 |
+
num_heads: int,
|
| 101 |
+
dropout: float = 0.0,
|
| 102 |
+
is_decoder: bool = False,
|
| 103 |
+
bias: bool = True,
|
| 104 |
+
is_causal: bool = False,
|
| 105 |
+
config: Optional[BlenderbotSmallConfig] = None,
|
| 106 |
+
):
|
| 107 |
+
super().__init__()
|
| 108 |
+
self.embed_dim = embed_dim
|
| 109 |
+
self.num_heads = num_heads
|
| 110 |
+
self.dropout = dropout
|
| 111 |
+
self.head_dim = embed_dim // num_heads
|
| 112 |
+
self.config = config
|
| 113 |
+
|
| 114 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 115 |
+
raise ValueError(
|
| 116 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 117 |
+
f" and `num_heads`: {num_heads})."
|
| 118 |
+
)
|
| 119 |
+
self.scaling = self.head_dim**-0.5
|
| 120 |
+
self.is_decoder = is_decoder
|
| 121 |
+
self.is_causal = is_causal
|
| 122 |
+
|
| 123 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 124 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 125 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 126 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 127 |
+
|
| 128 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 129 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 130 |
+
|
| 131 |
+
def forward(
|
| 132 |
+
self,
|
| 133 |
+
hidden_states: torch.Tensor,
|
| 134 |
+
key_value_states: Optional[torch.Tensor] = None,
|
| 135 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 136 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 137 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 138 |
+
output_attentions: bool = False,
|
| 139 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 140 |
+
"""Input shape: Batch x Time x Channel"""
|
| 141 |
+
|
| 142 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 143 |
+
# for the decoder
|
| 144 |
+
is_cross_attention = key_value_states is not None
|
| 145 |
+
|
| 146 |
+
bsz, tgt_len, _ = hidden_states.size()
|
| 147 |
+
|
| 148 |
+
# get query proj
|
| 149 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 150 |
+
# get key, value proj
|
| 151 |
+
# `past_key_value[0].shape[2] == key_value_states.shape[1]`
|
| 152 |
+
# is checking that the `sequence_length` of the `past_key_value` is the same as
|
| 153 |
+
# the provided `key_value_states` to support prefix tuning
|
| 154 |
+
if (
|
| 155 |
+
is_cross_attention
|
| 156 |
+
and past_key_value is not None
|
| 157 |
+
and past_key_value[0].shape[2] == key_value_states.shape[1]
|
| 158 |
+
):
|
| 159 |
+
# reuse k,v, cross_attentions
|
| 160 |
+
key_states = past_key_value[0]
|
| 161 |
+
value_states = past_key_value[1]
|
| 162 |
+
elif is_cross_attention:
|
| 163 |
+
# cross_attentions
|
| 164 |
+
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
|
| 165 |
+
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
|
| 166 |
+
elif past_key_value is not None:
|
| 167 |
+
# reuse k, v, self_attention
|
| 168 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 169 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 170 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 171 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 172 |
+
else:
|
| 173 |
+
# self_attention
|
| 174 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 175 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 176 |
+
|
| 177 |
+
if self.is_decoder:
|
| 178 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 179 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 180 |
+
# key/value_states (first "if" case)
|
| 181 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 182 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 183 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 184 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 185 |
+
past_key_value = (key_states, value_states)
|
| 186 |
+
|
| 187 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 188 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 189 |
+
key_states = key_states.reshape(*proj_shape)
|
| 190 |
+
value_states = value_states.reshape(*proj_shape)
|
| 191 |
+
|
| 192 |
+
src_len = key_states.size(1)
|
| 193 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 194 |
+
|
| 195 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 196 |
+
raise ValueError(
|
| 197 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 198 |
+
f" {attn_weights.size()}"
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
if attention_mask is not None:
|
| 202 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 203 |
+
raise ValueError(
|
| 204 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 205 |
+
)
|
| 206 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 207 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 208 |
+
|
| 209 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 210 |
+
|
| 211 |
+
if layer_head_mask is not None:
|
| 212 |
+
if layer_head_mask.size() != (self.num_heads,):
|
| 213 |
+
raise ValueError(
|
| 214 |
+
f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
|
| 215 |
+
f" {layer_head_mask.size()}"
|
| 216 |
+
)
|
| 217 |
+
attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 218 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 219 |
+
|
| 220 |
+
if output_attentions:
|
| 221 |
+
# this operation is a bit awkward, but it's required to
|
| 222 |
+
# make sure that attn_weights keeps its gradient.
|
| 223 |
+
# In order to do so, attn_weights have to be reshaped
|
| 224 |
+
# twice and have to be reused in the following
|
| 225 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 226 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 227 |
+
else:
|
| 228 |
+
attn_weights_reshaped = None
|
| 229 |
+
|
| 230 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 231 |
+
|
| 232 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 233 |
+
|
| 234 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 235 |
+
raise ValueError(
|
| 236 |
+
f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 237 |
+
f" {attn_output.size()}"
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 241 |
+
attn_output = attn_output.transpose(1, 2)
|
| 242 |
+
|
| 243 |
+
# Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
|
| 244 |
+
# partitioned across GPUs when using tensor-parallelism.
|
| 245 |
+
attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
|
| 246 |
+
|
| 247 |
+
attn_output = self.out_proj(attn_output)
|
| 248 |
+
|
| 249 |
+
return attn_output, attn_weights_reshaped, past_key_value
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
# Copied from transformers.models.bart.modeling_bart.BartEncoderLayer with Bart->BlenderbotSmall, BART->BLENDERBOT_SMALL
|
| 253 |
+
class BlenderbotSmallEncoderLayer(nn.Module):
|
| 254 |
+
def __init__(self, config: BlenderbotSmallConfig):
|
| 255 |
+
super().__init__()
|
| 256 |
+
self.embed_dim = config.d_model
|
| 257 |
+
|
| 258 |
+
self.self_attn = BLENDERBOT_SMALL_ATTENTION_CLASSES[config._attn_implementation](
|
| 259 |
+
embed_dim=self.embed_dim,
|
| 260 |
+
num_heads=config.encoder_attention_heads,
|
| 261 |
+
dropout=config.attention_dropout,
|
| 262 |
+
config=config,
|
| 263 |
+
)
|
| 264 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 265 |
+
self.dropout = config.dropout
|
| 266 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 267 |
+
self.activation_dropout = config.activation_dropout
|
| 268 |
+
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
|
| 269 |
+
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
|
| 270 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 271 |
+
|
| 272 |
+
def forward(
|
| 273 |
+
self,
|
| 274 |
+
hidden_states: torch.FloatTensor,
|
| 275 |
+
attention_mask: torch.FloatTensor,
|
| 276 |
+
layer_head_mask: torch.FloatTensor,
|
| 277 |
+
output_attentions: Optional[bool] = False,
|
| 278 |
+
) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]:
|
| 279 |
+
"""
|
| 280 |
+
Args:
|
| 281 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 282 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 283 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 284 |
+
layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
|
| 285 |
+
`(encoder_attention_heads,)`.
|
| 286 |
+
output_attentions (`bool`, *optional*):
|
| 287 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 288 |
+
returned tensors for more detail.
|
| 289 |
+
"""
|
| 290 |
+
residual = hidden_states
|
| 291 |
+
hidden_states, attn_weights, _ = self.self_attn(
|
| 292 |
+
hidden_states=hidden_states,
|
| 293 |
+
attention_mask=attention_mask,
|
| 294 |
+
layer_head_mask=layer_head_mask,
|
| 295 |
+
output_attentions=output_attentions,
|
| 296 |
+
)
|
| 297 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 298 |
+
hidden_states = residual + hidden_states
|
| 299 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 300 |
+
|
| 301 |
+
residual = hidden_states
|
| 302 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 303 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 304 |
+
hidden_states = self.fc2(hidden_states)
|
| 305 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 306 |
+
hidden_states = residual + hidden_states
|
| 307 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 308 |
+
|
| 309 |
+
if hidden_states.dtype == torch.float16 and (
|
| 310 |
+
torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
|
| 311 |
+
):
|
| 312 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 313 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 314 |
+
|
| 315 |
+
outputs = (hidden_states,)
|
| 316 |
+
|
| 317 |
+
if output_attentions:
|
| 318 |
+
outputs += (attn_weights,)
|
| 319 |
+
|
| 320 |
+
return outputs
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
# TODO: Implement attention with SDPA for TimeSeriesTransformer.
|
| 324 |
+
BLENDERBOT_SMALL_ATTENTION_CLASSES = {
|
| 325 |
+
"eager": BlenderbotSmallAttention,
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoderLayer with Bart->BlenderbotSmall, BART->BLENDERBOT_SMALL
|
| 330 |
+
class BlenderbotSmallDecoderLayer(nn.Module):
|
| 331 |
+
def __init__(self, config: BlenderbotSmallConfig):
|
| 332 |
+
super().__init__()
|
| 333 |
+
self.embed_dim = config.d_model
|
| 334 |
+
|
| 335 |
+
self.self_attn = BLENDERBOT_SMALL_ATTENTION_CLASSES[config._attn_implementation](
|
| 336 |
+
embed_dim=self.embed_dim,
|
| 337 |
+
num_heads=config.decoder_attention_heads,
|
| 338 |
+
dropout=config.attention_dropout,
|
| 339 |
+
is_decoder=True,
|
| 340 |
+
is_causal=True,
|
| 341 |
+
config=config,
|
| 342 |
+
)
|
| 343 |
+
self.dropout = config.dropout
|
| 344 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 345 |
+
self.activation_dropout = config.activation_dropout
|
| 346 |
+
|
| 347 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 348 |
+
self.encoder_attn = BLENDERBOT_SMALL_ATTENTION_CLASSES[config._attn_implementation](
|
| 349 |
+
self.embed_dim,
|
| 350 |
+
config.decoder_attention_heads,
|
| 351 |
+
dropout=config.attention_dropout,
|
| 352 |
+
is_decoder=True,
|
| 353 |
+
config=config,
|
| 354 |
+
)
|
| 355 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 356 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 357 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 358 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 359 |
+
|
| 360 |
+
def forward(
|
| 361 |
+
self,
|
| 362 |
+
hidden_states: torch.Tensor,
|
| 363 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 364 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 365 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 366 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 367 |
+
cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
|
| 368 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 369 |
+
output_attentions: Optional[bool] = False,
|
| 370 |
+
use_cache: Optional[bool] = True,
|
| 371 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 372 |
+
"""
|
| 373 |
+
Args:
|
| 374 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 375 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 376 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 377 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 378 |
+
cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 379 |
+
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
|
| 380 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 381 |
+
layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
|
| 382 |
+
`(encoder_attention_heads,)`.
|
| 383 |
+
cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
|
| 384 |
+
size `(decoder_attention_heads,)`.
|
| 385 |
+
past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
|
| 386 |
+
output_attentions (`bool`, *optional*):
|
| 387 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 388 |
+
returned tensors for more detail.
|
| 389 |
+
"""
|
| 390 |
+
residual = hidden_states
|
| 391 |
+
|
| 392 |
+
# Self Attention
|
| 393 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 394 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 395 |
+
# add present self-attn cache to positions 1,2 of present_key_value tuple
|
| 396 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 397 |
+
hidden_states=hidden_states,
|
| 398 |
+
past_key_value=self_attn_past_key_value,
|
| 399 |
+
attention_mask=attention_mask,
|
| 400 |
+
layer_head_mask=layer_head_mask,
|
| 401 |
+
output_attentions=output_attentions,
|
| 402 |
+
)
|
| 403 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 404 |
+
hidden_states = residual + hidden_states
|
| 405 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 406 |
+
|
| 407 |
+
# Cross-Attention Block
|
| 408 |
+
cross_attn_present_key_value = None
|
| 409 |
+
cross_attn_weights = None
|
| 410 |
+
if encoder_hidden_states is not None:
|
| 411 |
+
residual = hidden_states
|
| 412 |
+
|
| 413 |
+
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
|
| 414 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 415 |
+
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
|
| 416 |
+
hidden_states=hidden_states,
|
| 417 |
+
key_value_states=encoder_hidden_states,
|
| 418 |
+
attention_mask=encoder_attention_mask,
|
| 419 |
+
layer_head_mask=cross_attn_layer_head_mask,
|
| 420 |
+
past_key_value=cross_attn_past_key_value,
|
| 421 |
+
output_attentions=output_attentions,
|
| 422 |
+
)
|
| 423 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 424 |
+
hidden_states = residual + hidden_states
|
| 425 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 426 |
+
|
| 427 |
+
# add cross-attn to positions 3,4 of present_key_value tuple
|
| 428 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 429 |
+
|
| 430 |
+
# Fully Connected
|
| 431 |
+
residual = hidden_states
|
| 432 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 433 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 434 |
+
hidden_states = self.fc2(hidden_states)
|
| 435 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 436 |
+
hidden_states = residual + hidden_states
|
| 437 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 438 |
+
|
| 439 |
+
outputs = (hidden_states,)
|
| 440 |
+
|
| 441 |
+
if output_attentions:
|
| 442 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 443 |
+
|
| 444 |
+
if use_cache:
|
| 445 |
+
outputs += (present_key_value,)
|
| 446 |
+
|
| 447 |
+
return outputs
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
class BlenderbotSmallPreTrainedModel(PreTrainedModel):
|
| 451 |
+
config_class = BlenderbotSmallConfig
|
| 452 |
+
base_model_prefix = "model"
|
| 453 |
+
supports_gradient_checkpointing = True
|
| 454 |
+
|
| 455 |
+
def _init_weights(self, module):
|
| 456 |
+
std = self.config.init_std
|
| 457 |
+
if isinstance(module, nn.Linear):
|
| 458 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 459 |
+
if module.bias is not None:
|
| 460 |
+
module.bias.data.zero_()
|
| 461 |
+
elif isinstance(module, nn.Embedding):
|
| 462 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 463 |
+
if module.padding_idx is not None:
|
| 464 |
+
module.weight.data[module.padding_idx].zero_()
|
| 465 |
+
|
| 466 |
+
@property
|
| 467 |
+
def dummy_inputs(self):
|
| 468 |
+
pad_token = self.config.pad_token_id
|
| 469 |
+
input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
|
| 470 |
+
dummy_inputs = {
|
| 471 |
+
"attention_mask": input_ids.ne(pad_token),
|
| 472 |
+
"input_ids": input_ids,
|
| 473 |
+
"decoder_input_ids": input_ids,
|
| 474 |
+
}
|
| 475 |
+
return dummy_inputs
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
BLENDERBOT_SMALL_START_DOCSTRING = r"""
|
| 479 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 480 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 481 |
+
etc.)
|
| 482 |
+
|
| 483 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 484 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 485 |
+
and behavior.
|
| 486 |
+
|
| 487 |
+
Parameters:
|
| 488 |
+
config ([`BlenderbotSmallConfig`]):
|
| 489 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 490 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 491 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 492 |
+
"""
|
| 493 |
+
|
| 494 |
+
BLENDERBOT_SMALL_GENERATION_EXAMPLE = r"""
|
| 495 |
+
Conversation example:
|
| 496 |
+
|
| 497 |
+
```python
|
| 498 |
+
>>> from transformers import AutoTokenizer, BlenderbotSmallForConditionalGeneration
|
| 499 |
+
|
| 500 |
+
>>> mname = "facebook/blenderbot_small-90M"
|
| 501 |
+
>>> model = BlenderbotSmallForConditionalGeneration.from_pretrained(mname)
|
| 502 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(mname)
|
| 503 |
+
>>> UTTERANCE = "My friends are cool but they eat too many carbs."
|
| 504 |
+
>>> print("Human: ", UTTERANCE)
|
| 505 |
+
Human: My friends are cool but they eat too many carbs.
|
| 506 |
+
|
| 507 |
+
>>> inputs = tokenizer([UTTERANCE], return_tensors="pt")
|
| 508 |
+
>>> reply_ids = model.generate(**inputs)
|
| 509 |
+
>>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
|
| 510 |
+
Bot: what kind of carbs do they eat? i don't know much about carbs.
|
| 511 |
+
|
| 512 |
+
>>> REPLY = "I'm not sure"
|
| 513 |
+
>>> print("Human: ", REPLY)
|
| 514 |
+
Human: I'm not sure
|
| 515 |
+
|
| 516 |
+
>>> NEXT_UTTERANCE = (
|
| 517 |
+
... "My friends are cool but they eat too many carbs.__end__ __start__what kind of carbs do they eat? "
|
| 518 |
+
... "i don't know much about carbs__end__ "
|
| 519 |
+
... "__start__ I'm not sure."
|
| 520 |
+
... )
|
| 521 |
+
>>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="pt")
|
| 522 |
+
>>> next_reply_ids = model.generate(**inputs)
|
| 523 |
+
>>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
|
| 524 |
+
Bot: they eat a lot of carbs. carbs are high in fat, protein, and fats.
|
| 525 |
+
```
|
| 526 |
+
"""
|
| 527 |
+
|
| 528 |
+
BLENDERBOT_SMALL_INPUTS_DOCSTRING = r"""
|
| 529 |
+
Args:
|
| 530 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 531 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 532 |
+
it.
|
| 533 |
+
|
| 534 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 535 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 536 |
+
|
| 537 |
+
[What are input IDs?](../glossary#input-ids)
|
| 538 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 539 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 540 |
+
|
| 541 |
+
- 1 for tokens that are **not masked**,
|
| 542 |
+
- 0 for tokens that are **masked**.
|
| 543 |
+
|
| 544 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 545 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 546 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 547 |
+
|
| 548 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 549 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 550 |
+
|
| 551 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 552 |
+
|
| 553 |
+
BlenderbotSmall uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 554 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 555 |
+
`past_key_values`).
|
| 556 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 557 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 558 |
+
be used by default.
|
| 559 |
+
head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
|
| 560 |
+
Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
|
| 561 |
+
|
| 562 |
+
- 1 indicates the head is **not masked**,
|
| 563 |
+
- 0 indicates the head is **masked**.
|
| 564 |
+
|
| 565 |
+
decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 566 |
+
Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
|
| 567 |
+
|
| 568 |
+
- 1 indicates the head is **not masked**,
|
| 569 |
+
- 0 indicates the head is **masked**.
|
| 570 |
+
|
| 571 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 572 |
+
Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
|
| 573 |
+
1]`:
|
| 574 |
+
|
| 575 |
+
- 1 indicates the head is **not masked**,
|
| 576 |
+
- 0 indicates the head is **masked**.
|
| 577 |
+
|
| 578 |
+
encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
|
| 579 |
+
Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
|
| 580 |
+
`last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
|
| 581 |
+
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
|
| 582 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 583 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 584 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
| 585 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 586 |
+
|
| 587 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 588 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 589 |
+
|
| 590 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 591 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 592 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 593 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 594 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 595 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 596 |
+
than the model's internal embedding lookup matrix.
|
| 597 |
+
decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
|
| 598 |
+
Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
|
| 599 |
+
representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
|
| 600 |
+
input (see `past_key_values`). This is useful if you want more control over how to convert
|
| 601 |
+
`decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
|
| 602 |
+
|
| 603 |
+
If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
|
| 604 |
+
of `inputs_embeds`.
|
| 605 |
+
use_cache (`bool`, *optional*):
|
| 606 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 607 |
+
`past_key_values`).
|
| 608 |
+
output_attentions (`bool`, *optional*):
|
| 609 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 610 |
+
tensors for more detail.
|
| 611 |
+
output_hidden_states (`bool`, *optional*):
|
| 612 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 613 |
+
more detail.
|
| 614 |
+
return_dict (`bool`, *optional*):
|
| 615 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 616 |
+
"""
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
class BlenderbotSmallEncoder(BlenderbotSmallPreTrainedModel):
|
| 620 |
+
"""
|
| 621 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 622 |
+
[`BlenderbotSmallEncoderLayer`].
|
| 623 |
+
|
| 624 |
+
Args:
|
| 625 |
+
config: BlenderbotSmallConfig
|
| 626 |
+
embed_tokens (nn.Embedding): output embedding
|
| 627 |
+
"""
|
| 628 |
+
|
| 629 |
+
def __init__(self, config: BlenderbotSmallConfig, embed_tokens: Optional[nn.Embedding] = None):
|
| 630 |
+
super().__init__(config)
|
| 631 |
+
|
| 632 |
+
self.dropout = config.dropout
|
| 633 |
+
self.layerdrop = config.encoder_layerdrop
|
| 634 |
+
|
| 635 |
+
embed_dim = config.d_model
|
| 636 |
+
self.padding_idx = config.pad_token_id
|
| 637 |
+
self.max_source_positions = config.max_position_embeddings
|
| 638 |
+
self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
|
| 639 |
+
|
| 640 |
+
if embed_tokens is not None:
|
| 641 |
+
self.embed_tokens = embed_tokens
|
| 642 |
+
else:
|
| 643 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
|
| 644 |
+
|
| 645 |
+
self.embed_positions = BlenderbotSmallLearnedPositionalEmbedding(
|
| 646 |
+
config.max_position_embeddings,
|
| 647 |
+
embed_dim,
|
| 648 |
+
)
|
| 649 |
+
self.layers = nn.ModuleList([BlenderbotSmallEncoderLayer(config) for _ in range(config.encoder_layers)])
|
| 650 |
+
self.layernorm_embedding = nn.LayerNorm(embed_dim)
|
| 651 |
+
|
| 652 |
+
self.gradient_checkpointing = False
|
| 653 |
+
# Initialize weights and apply final processing
|
| 654 |
+
self.post_init()
|
| 655 |
+
|
| 656 |
+
def forward(
|
| 657 |
+
self,
|
| 658 |
+
input_ids=None,
|
| 659 |
+
attention_mask=None,
|
| 660 |
+
head_mask=None,
|
| 661 |
+
inputs_embeds=None,
|
| 662 |
+
output_attentions=None,
|
| 663 |
+
output_hidden_states=None,
|
| 664 |
+
return_dict=None,
|
| 665 |
+
):
|
| 666 |
+
r"""
|
| 667 |
+
Args:
|
| 668 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 669 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 670 |
+
provide it.
|
| 671 |
+
|
| 672 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 673 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 674 |
+
|
| 675 |
+
[What are input IDs?](../glossary#input-ids)
|
| 676 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 677 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 678 |
+
|
| 679 |
+
- 1 for tokens that are **not masked**,
|
| 680 |
+
- 0 for tokens that are **masked**.
|
| 681 |
+
|
| 682 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 683 |
+
head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
|
| 684 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 685 |
+
|
| 686 |
+
- 1 indicates the head is **not masked**,
|
| 687 |
+
- 0 indicates the head is **masked**.
|
| 688 |
+
|
| 689 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 690 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 691 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 692 |
+
than the model's internal embedding lookup matrix.
|
| 693 |
+
output_attentions (`bool`, *optional*):
|
| 694 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 695 |
+
returned tensors for more detail.
|
| 696 |
+
output_hidden_states (`bool`, *optional*):
|
| 697 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 698 |
+
for more detail.
|
| 699 |
+
return_dict (`bool`, *optional*):
|
| 700 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 701 |
+
"""
|
| 702 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 703 |
+
output_hidden_states = (
|
| 704 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 705 |
+
)
|
| 706 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 707 |
+
|
| 708 |
+
# retrieve input_ids and inputs_embeds
|
| 709 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 710 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 711 |
+
elif input_ids is not None:
|
| 712 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 713 |
+
input_shape = input_ids.size()
|
| 714 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 715 |
+
elif inputs_embeds is not None:
|
| 716 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 717 |
+
else:
|
| 718 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 719 |
+
|
| 720 |
+
if inputs_embeds is None:
|
| 721 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 722 |
+
|
| 723 |
+
embed_pos = self.embed_positions(input_shape)
|
| 724 |
+
|
| 725 |
+
hidden_states = inputs_embeds + embed_pos
|
| 726 |
+
hidden_states = self.layernorm_embedding(hidden_states)
|
| 727 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 728 |
+
|
| 729 |
+
# expand attention_mask
|
| 730 |
+
if attention_mask is not None:
|
| 731 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 732 |
+
attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
|
| 733 |
+
|
| 734 |
+
encoder_states = () if output_hidden_states else None
|
| 735 |
+
all_attentions = () if output_attentions else None
|
| 736 |
+
|
| 737 |
+
# check if head_mask has a correct number of layers specified if desired
|
| 738 |
+
if head_mask is not None:
|
| 739 |
+
if head_mask.size()[0] != len(self.layers):
|
| 740 |
+
raise ValueError(
|
| 741 |
+
f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
|
| 742 |
+
f" {head_mask.size()[0]}."
|
| 743 |
+
)
|
| 744 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 745 |
+
if output_hidden_states:
|
| 746 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 747 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 748 |
+
to_drop = False
|
| 749 |
+
if self.training:
|
| 750 |
+
dropout_probability = torch.rand([])
|
| 751 |
+
if dropout_probability < self.layerdrop: # skip the layer
|
| 752 |
+
to_drop = True
|
| 753 |
+
|
| 754 |
+
if to_drop:
|
| 755 |
+
layer_outputs = (None, None)
|
| 756 |
+
else:
|
| 757 |
+
if self.gradient_checkpointing and self.training:
|
| 758 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 759 |
+
encoder_layer.__call__,
|
| 760 |
+
hidden_states,
|
| 761 |
+
attention_mask,
|
| 762 |
+
(head_mask[idx] if head_mask is not None else None),
|
| 763 |
+
output_attentions,
|
| 764 |
+
)
|
| 765 |
+
else:
|
| 766 |
+
layer_outputs = encoder_layer(
|
| 767 |
+
hidden_states,
|
| 768 |
+
attention_mask,
|
| 769 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 770 |
+
output_attentions=output_attentions,
|
| 771 |
+
)
|
| 772 |
+
|
| 773 |
+
hidden_states = layer_outputs[0]
|
| 774 |
+
|
| 775 |
+
if output_attentions:
|
| 776 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 777 |
+
|
| 778 |
+
if output_hidden_states:
|
| 779 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 780 |
+
|
| 781 |
+
if not return_dict:
|
| 782 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 783 |
+
return BaseModelOutput(
|
| 784 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
class BlenderbotSmallDecoder(BlenderbotSmallPreTrainedModel):
|
| 789 |
+
"""
|
| 790 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`BlenderbotSmallDecoderLayer`]
|
| 791 |
+
|
| 792 |
+
Args:
|
| 793 |
+
config: BlenderbotSmallConfig
|
| 794 |
+
embed_tokens (nn.Embedding): output embedding
|
| 795 |
+
"""
|
| 796 |
+
|
| 797 |
+
def __init__(self, config: BlenderbotSmallConfig, embed_tokens: Optional[nn.Embedding] = None):
|
| 798 |
+
super().__init__(config)
|
| 799 |
+
self.dropout = config.dropout
|
| 800 |
+
self.layerdrop = config.decoder_layerdrop
|
| 801 |
+
self.padding_idx = config.pad_token_id
|
| 802 |
+
self.max_target_positions = config.max_position_embeddings
|
| 803 |
+
self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 804 |
+
|
| 805 |
+
if embed_tokens is not None:
|
| 806 |
+
self.embed_tokens = embed_tokens
|
| 807 |
+
else:
|
| 808 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
|
| 809 |
+
|
| 810 |
+
self.embed_positions = BlenderbotSmallLearnedPositionalEmbedding(
|
| 811 |
+
config.max_position_embeddings,
|
| 812 |
+
config.d_model,
|
| 813 |
+
)
|
| 814 |
+
self.layers = nn.ModuleList([BlenderbotSmallDecoderLayer(config) for _ in range(config.decoder_layers)])
|
| 815 |
+
self.layernorm_embedding = nn.LayerNorm(config.d_model)
|
| 816 |
+
|
| 817 |
+
self.gradient_checkpointing = False
|
| 818 |
+
# Initialize weights and apply final processing
|
| 819 |
+
self.post_init()
|
| 820 |
+
|
| 821 |
+
def get_input_embeddings(self):
|
| 822 |
+
return self.embed_tokens
|
| 823 |
+
|
| 824 |
+
def set_input_embeddings(self, value):
|
| 825 |
+
self.embed_tokens = value
|
| 826 |
+
|
| 827 |
+
def forward(
|
| 828 |
+
self,
|
| 829 |
+
input_ids=None,
|
| 830 |
+
attention_mask=None,
|
| 831 |
+
encoder_hidden_states=None,
|
| 832 |
+
encoder_attention_mask=None,
|
| 833 |
+
head_mask=None,
|
| 834 |
+
cross_attn_head_mask=None,
|
| 835 |
+
past_key_values=None,
|
| 836 |
+
inputs_embeds=None,
|
| 837 |
+
use_cache=None,
|
| 838 |
+
output_attentions=None,
|
| 839 |
+
output_hidden_states=None,
|
| 840 |
+
return_dict=None,
|
| 841 |
+
):
|
| 842 |
+
r"""
|
| 843 |
+
Args:
|
| 844 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 845 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 846 |
+
provide it.
|
| 847 |
+
|
| 848 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 849 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 850 |
+
|
| 851 |
+
[What are input IDs?](../glossary#input-ids)
|
| 852 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 853 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 854 |
+
|
| 855 |
+
- 1 for tokens that are **not masked**,
|
| 856 |
+
- 0 for tokens that are **masked**.
|
| 857 |
+
|
| 858 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 859 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 860 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 861 |
+
of the decoder.
|
| 862 |
+
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 863 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 864 |
+
selected in `[0, 1]`:
|
| 865 |
+
|
| 866 |
+
- 1 for tokens that are **not masked**,
|
| 867 |
+
- 0 for tokens that are **masked**.
|
| 868 |
+
|
| 869 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 870 |
+
head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 871 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 872 |
+
|
| 873 |
+
- 1 indicates the head is **not masked**,
|
| 874 |
+
- 0 indicates the head is **masked**.
|
| 875 |
+
|
| 876 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 877 |
+
Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
|
| 878 |
+
cross-attention on hidden heads. Mask values selected in `[0, 1]`:
|
| 879 |
+
|
| 880 |
+
- 1 indicates the head is **not masked**,
|
| 881 |
+
- 0 indicates the head is **masked**.
|
| 882 |
+
|
| 883 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 884 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 885 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
|
| 886 |
+
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 887 |
+
|
| 888 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 889 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 890 |
+
|
| 891 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 892 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 893 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 894 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 895 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 896 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 897 |
+
than the model's internal embedding lookup matrix.
|
| 898 |
+
output_attentions (`bool`, *optional*):
|
| 899 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 900 |
+
returned tensors for more detail.
|
| 901 |
+
output_hidden_states (`bool`, *optional*):
|
| 902 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 903 |
+
for more detail.
|
| 904 |
+
return_dict (`bool`, *optional*):
|
| 905 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 906 |
+
"""
|
| 907 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 908 |
+
output_hidden_states = (
|
| 909 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 910 |
+
)
|
| 911 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 912 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 913 |
+
|
| 914 |
+
# retrieve input_ids and inputs_embeds
|
| 915 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 916 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 917 |
+
elif input_ids is not None:
|
| 918 |
+
input_shape = input_ids.size()
|
| 919 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 920 |
+
elif inputs_embeds is not None:
|
| 921 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 922 |
+
else:
|
| 923 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 924 |
+
|
| 925 |
+
# past_key_values_length
|
| 926 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 927 |
+
|
| 928 |
+
if inputs_embeds is None:
|
| 929 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 930 |
+
|
| 931 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
| 932 |
+
attention_mask, input_shape, inputs_embeds, past_key_values_length
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
# expand encoder attention mask
|
| 936 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 937 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 938 |
+
encoder_attention_mask = _prepare_4d_attention_mask(
|
| 939 |
+
encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
|
| 940 |
+
)
|
| 941 |
+
|
| 942 |
+
# embed positions
|
| 943 |
+
positions = self.embed_positions(input_shape, past_key_values_length)
|
| 944 |
+
|
| 945 |
+
# BlenderbotSmall applies layer norm on hidden_states
|
| 946 |
+
inputs_embeds = self.layernorm_embedding(inputs_embeds)
|
| 947 |
+
hidden_states = inputs_embeds + positions
|
| 948 |
+
|
| 949 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 950 |
+
|
| 951 |
+
if self.gradient_checkpointing and self.training:
|
| 952 |
+
if use_cache:
|
| 953 |
+
logger.warning_once(
|
| 954 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 955 |
+
)
|
| 956 |
+
use_cache = False
|
| 957 |
+
|
| 958 |
+
# decoder layers
|
| 959 |
+
all_hidden_states = () if output_hidden_states else None
|
| 960 |
+
all_self_attns = () if output_attentions else None
|
| 961 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 962 |
+
next_decoder_cache = () if use_cache else None
|
| 963 |
+
|
| 964 |
+
# check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
|
| 965 |
+
for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
|
| 966 |
+
if attn_mask is not None:
|
| 967 |
+
if attn_mask.size()[0] != len(self.layers):
|
| 968 |
+
raise ValueError(
|
| 969 |
+
f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
|
| 970 |
+
f" {head_mask.size()[0]}."
|
| 971 |
+
)
|
| 972 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 973 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 974 |
+
if output_hidden_states:
|
| 975 |
+
all_hidden_states += (hidden_states,)
|
| 976 |
+
if self.training:
|
| 977 |
+
dropout_probability = torch.rand([])
|
| 978 |
+
if dropout_probability < self.layerdrop:
|
| 979 |
+
continue
|
| 980 |
+
|
| 981 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 982 |
+
|
| 983 |
+
if self.gradient_checkpointing and self.training:
|
| 984 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 985 |
+
decoder_layer.__call__,
|
| 986 |
+
hidden_states,
|
| 987 |
+
attention_mask,
|
| 988 |
+
encoder_hidden_states,
|
| 989 |
+
encoder_attention_mask,
|
| 990 |
+
head_mask[idx] if head_mask is not None else None,
|
| 991 |
+
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
|
| 992 |
+
None,
|
| 993 |
+
output_attentions,
|
| 994 |
+
use_cache,
|
| 995 |
+
)
|
| 996 |
+
else:
|
| 997 |
+
layer_outputs = decoder_layer(
|
| 998 |
+
hidden_states,
|
| 999 |
+
attention_mask=attention_mask,
|
| 1000 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1001 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1002 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 1003 |
+
cross_attn_layer_head_mask=(
|
| 1004 |
+
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
|
| 1005 |
+
),
|
| 1006 |
+
past_key_value=past_key_value,
|
| 1007 |
+
output_attentions=output_attentions,
|
| 1008 |
+
use_cache=use_cache,
|
| 1009 |
+
)
|
| 1010 |
+
hidden_states = layer_outputs[0]
|
| 1011 |
+
|
| 1012 |
+
if use_cache:
|
| 1013 |
+
next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
|
| 1014 |
+
|
| 1015 |
+
if output_attentions:
|
| 1016 |
+
all_self_attns += (layer_outputs[1],)
|
| 1017 |
+
|
| 1018 |
+
if encoder_hidden_states is not None:
|
| 1019 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 1020 |
+
|
| 1021 |
+
# add hidden states from the last decoder layer
|
| 1022 |
+
if output_hidden_states:
|
| 1023 |
+
all_hidden_states += (hidden_states,)
|
| 1024 |
+
|
| 1025 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 1026 |
+
if not return_dict:
|
| 1027 |
+
return tuple(
|
| 1028 |
+
v
|
| 1029 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 1030 |
+
if v is not None
|
| 1031 |
+
)
|
| 1032 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 1033 |
+
last_hidden_state=hidden_states,
|
| 1034 |
+
past_key_values=next_cache,
|
| 1035 |
+
hidden_states=all_hidden_states,
|
| 1036 |
+
attentions=all_self_attns,
|
| 1037 |
+
cross_attentions=all_cross_attentions,
|
| 1038 |
+
)
|
| 1039 |
+
|
| 1040 |
+
|
| 1041 |
+
@add_start_docstrings(
|
| 1042 |
+
"The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top.",
|
| 1043 |
+
BLENDERBOT_SMALL_START_DOCSTRING,
|
| 1044 |
+
)
|
| 1045 |
+
class BlenderbotSmallModel(BlenderbotSmallPreTrainedModel):
|
| 1046 |
+
_tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]
|
| 1047 |
+
|
| 1048 |
+
def __init__(self, config: BlenderbotSmallConfig):
|
| 1049 |
+
super().__init__(config)
|
| 1050 |
+
|
| 1051 |
+
padding_idx, vocab_size = config.pad_token_id, config.vocab_size
|
| 1052 |
+
self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
|
| 1053 |
+
|
| 1054 |
+
self.encoder = BlenderbotSmallEncoder(config, self.shared)
|
| 1055 |
+
self.decoder = BlenderbotSmallDecoder(config, self.shared)
|
| 1056 |
+
|
| 1057 |
+
# Initialize weights and apply final processing
|
| 1058 |
+
self.post_init()
|
| 1059 |
+
|
| 1060 |
+
def get_input_embeddings(self):
|
| 1061 |
+
return self.shared
|
| 1062 |
+
|
| 1063 |
+
def set_input_embeddings(self, value):
|
| 1064 |
+
self.shared = value
|
| 1065 |
+
self.encoder.embed_tokens = self.shared
|
| 1066 |
+
self.decoder.embed_tokens = self.shared
|
| 1067 |
+
|
| 1068 |
+
def get_encoder(self):
|
| 1069 |
+
return self.encoder
|
| 1070 |
+
|
| 1071 |
+
def get_decoder(self):
|
| 1072 |
+
return self.decoder
|
| 1073 |
+
|
| 1074 |
+
@add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING)
|
| 1075 |
+
@replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 1076 |
+
def forward(
|
| 1077 |
+
self,
|
| 1078 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1079 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1080 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
| 1081 |
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
| 1082 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1083 |
+
decoder_head_mask: Optional[torch.Tensor] = None,
|
| 1084 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1085 |
+
encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
|
| 1086 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1087 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1088 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1089 |
+
use_cache: Optional[bool] = None,
|
| 1090 |
+
output_attentions: Optional[bool] = None,
|
| 1091 |
+
output_hidden_states: Optional[bool] = None,
|
| 1092 |
+
return_dict: Optional[bool] = None,
|
| 1093 |
+
) -> Union[Tuple[torch.FloatTensor], Seq2SeqModelOutput]:
|
| 1094 |
+
r"""
|
| 1095 |
+
Returns:
|
| 1096 |
+
|
| 1097 |
+
Example:
|
| 1098 |
+
|
| 1099 |
+
```python
|
| 1100 |
+
>>> from transformers import AutoTokenizer, BlenderbotSmallModel
|
| 1101 |
+
|
| 1102 |
+
>>> model = BlenderbotSmallModel.from_pretrained("facebook/blenderbot_small-90M")
|
| 1103 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
|
| 1104 |
+
|
| 1105 |
+
>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
|
| 1106 |
+
>>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt") # Batch size 1
|
| 1107 |
+
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
|
| 1108 |
+
|
| 1109 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 1110 |
+
>>> list(last_hidden_states.shape)
|
| 1111 |
+
[1, 3, 512]
|
| 1112 |
+
```"""
|
| 1113 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1114 |
+
output_hidden_states = (
|
| 1115 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1116 |
+
)
|
| 1117 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1118 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1119 |
+
|
| 1120 |
+
if encoder_outputs is None:
|
| 1121 |
+
encoder_outputs = self.encoder(
|
| 1122 |
+
input_ids=input_ids,
|
| 1123 |
+
attention_mask=attention_mask,
|
| 1124 |
+
head_mask=head_mask,
|
| 1125 |
+
inputs_embeds=inputs_embeds,
|
| 1126 |
+
output_attentions=output_attentions,
|
| 1127 |
+
output_hidden_states=output_hidden_states,
|
| 1128 |
+
return_dict=return_dict,
|
| 1129 |
+
)
|
| 1130 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
|
| 1131 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 1132 |
+
encoder_outputs = BaseModelOutput(
|
| 1133 |
+
last_hidden_state=encoder_outputs[0],
|
| 1134 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1135 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1136 |
+
)
|
| 1137 |
+
|
| 1138 |
+
# decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
|
| 1139 |
+
decoder_outputs = self.decoder(
|
| 1140 |
+
input_ids=decoder_input_ids,
|
| 1141 |
+
attention_mask=decoder_attention_mask,
|
| 1142 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1143 |
+
encoder_attention_mask=attention_mask,
|
| 1144 |
+
head_mask=decoder_head_mask,
|
| 1145 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1146 |
+
past_key_values=past_key_values,
|
| 1147 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1148 |
+
use_cache=use_cache,
|
| 1149 |
+
output_attentions=output_attentions,
|
| 1150 |
+
output_hidden_states=output_hidden_states,
|
| 1151 |
+
return_dict=return_dict,
|
| 1152 |
+
)
|
| 1153 |
+
|
| 1154 |
+
if not return_dict:
|
| 1155 |
+
return decoder_outputs + encoder_outputs
|
| 1156 |
+
|
| 1157 |
+
return Seq2SeqModelOutput(
|
| 1158 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1159 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1160 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1161 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1162 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1163 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1164 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1165 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1166 |
+
)
|
| 1167 |
+
|
| 1168 |
+
|
| 1169 |
+
@add_start_docstrings(
|
| 1170 |
+
"The BlenderbotSmall Model with a language modeling head. Can be used for summarization.",
|
| 1171 |
+
BLENDERBOT_SMALL_START_DOCSTRING,
|
| 1172 |
+
)
|
| 1173 |
+
class BlenderbotSmallForConditionalGeneration(BlenderbotSmallPreTrainedModel):
|
| 1174 |
+
base_model_prefix = "model"
|
| 1175 |
+
_keys_to_ignore_on_load_missing = ["final_logits_bias"]
|
| 1176 |
+
_tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight", "lm_head.weight"]
|
| 1177 |
+
|
| 1178 |
+
def __init__(self, config: BlenderbotSmallConfig):
|
| 1179 |
+
super().__init__(config)
|
| 1180 |
+
self.model = BlenderbotSmallModel(config)
|
| 1181 |
+
self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
|
| 1182 |
+
self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
|
| 1183 |
+
|
| 1184 |
+
# Initialize weights and apply final processing
|
| 1185 |
+
self.post_init()
|
| 1186 |
+
|
| 1187 |
+
def get_encoder(self):
|
| 1188 |
+
return self.model.get_encoder()
|
| 1189 |
+
|
| 1190 |
+
def get_decoder(self):
|
| 1191 |
+
return self.model.get_decoder()
|
| 1192 |
+
|
| 1193 |
+
def resize_token_embeddings(self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None) -> nn.Embedding:
|
| 1194 |
+
new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
|
| 1195 |
+
self._resize_final_logits_bias(new_embeddings.weight.shape[0])
|
| 1196 |
+
return new_embeddings
|
| 1197 |
+
|
| 1198 |
+
def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
|
| 1199 |
+
old_num_tokens = self.final_logits_bias.shape[-1]
|
| 1200 |
+
if new_num_tokens <= old_num_tokens:
|
| 1201 |
+
new_bias = self.final_logits_bias[:, :new_num_tokens]
|
| 1202 |
+
else:
|
| 1203 |
+
extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
|
| 1204 |
+
new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
|
| 1205 |
+
self.register_buffer("final_logits_bias", new_bias)
|
| 1206 |
+
|
| 1207 |
+
def get_output_embeddings(self):
|
| 1208 |
+
return self.lm_head
|
| 1209 |
+
|
| 1210 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1211 |
+
self.lm_head = new_embeddings
|
| 1212 |
+
|
| 1213 |
+
@add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING)
|
| 1214 |
+
@replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 1215 |
+
@add_end_docstrings(BLENDERBOT_SMALL_GENERATION_EXAMPLE)
|
| 1216 |
+
def forward(
|
| 1217 |
+
self,
|
| 1218 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1219 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1220 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
| 1221 |
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
| 1222 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1223 |
+
decoder_head_mask: Optional[torch.Tensor] = None,
|
| 1224 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1225 |
+
encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
|
| 1226 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1227 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1228 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1229 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1230 |
+
use_cache: Optional[bool] = None,
|
| 1231 |
+
output_attentions: Optional[bool] = None,
|
| 1232 |
+
output_hidden_states: Optional[bool] = None,
|
| 1233 |
+
return_dict: Optional[bool] = None,
|
| 1234 |
+
) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:
|
| 1235 |
+
r"""
|
| 1236 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1237 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1238 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1239 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1240 |
+
|
| 1241 |
+
Returns:
|
| 1242 |
+
"""
|
| 1243 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1244 |
+
|
| 1245 |
+
if labels is not None:
|
| 1246 |
+
if use_cache:
|
| 1247 |
+
logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
|
| 1248 |
+
use_cache = False
|
| 1249 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1250 |
+
decoder_input_ids = shift_tokens_right(
|
| 1251 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1252 |
+
)
|
| 1253 |
+
|
| 1254 |
+
outputs = self.model(
|
| 1255 |
+
input_ids,
|
| 1256 |
+
attention_mask=attention_mask,
|
| 1257 |
+
decoder_input_ids=decoder_input_ids,
|
| 1258 |
+
encoder_outputs=encoder_outputs,
|
| 1259 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1260 |
+
head_mask=head_mask,
|
| 1261 |
+
decoder_head_mask=decoder_head_mask,
|
| 1262 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1263 |
+
past_key_values=past_key_values,
|
| 1264 |
+
inputs_embeds=inputs_embeds,
|
| 1265 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1266 |
+
use_cache=use_cache,
|
| 1267 |
+
output_attentions=output_attentions,
|
| 1268 |
+
output_hidden_states=output_hidden_states,
|
| 1269 |
+
return_dict=return_dict,
|
| 1270 |
+
)
|
| 1271 |
+
lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
|
| 1272 |
+
|
| 1273 |
+
masked_lm_loss = None
|
| 1274 |
+
if labels is not None:
|
| 1275 |
+
loss_fct = CrossEntropyLoss()
|
| 1276 |
+
masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1277 |
+
|
| 1278 |
+
if not return_dict:
|
| 1279 |
+
output = (lm_logits,) + outputs[1:]
|
| 1280 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1281 |
+
|
| 1282 |
+
return Seq2SeqLMOutput(
|
| 1283 |
+
loss=masked_lm_loss,
|
| 1284 |
+
logits=lm_logits,
|
| 1285 |
+
past_key_values=outputs.past_key_values,
|
| 1286 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1287 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1288 |
+
cross_attentions=outputs.cross_attentions,
|
| 1289 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1290 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1291 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1292 |
+
)
|
| 1293 |
+
|
| 1294 |
+
def prepare_inputs_for_generation(
|
| 1295 |
+
self,
|
| 1296 |
+
decoder_input_ids,
|
| 1297 |
+
past_key_values=None,
|
| 1298 |
+
attention_mask=None,
|
| 1299 |
+
head_mask=None,
|
| 1300 |
+
decoder_head_mask=None,
|
| 1301 |
+
cross_attn_head_mask=None,
|
| 1302 |
+
use_cache=None,
|
| 1303 |
+
encoder_outputs=None,
|
| 1304 |
+
**kwargs,
|
| 1305 |
+
):
|
| 1306 |
+
# cut decoder_input_ids if past is used
|
| 1307 |
+
if past_key_values is not None:
|
| 1308 |
+
past_length = past_key_values[0][0].shape[2]
|
| 1309 |
+
|
| 1310 |
+
# Some generation methods already pass only the last input ID
|
| 1311 |
+
if decoder_input_ids.shape[1] > past_length:
|
| 1312 |
+
remove_prefix_length = past_length
|
| 1313 |
+
else:
|
| 1314 |
+
# Default to old behavior: keep only final ID
|
| 1315 |
+
remove_prefix_length = decoder_input_ids.shape[1] - 1
|
| 1316 |
+
|
| 1317 |
+
decoder_input_ids = decoder_input_ids[:, remove_prefix_length:]
|
| 1318 |
+
|
| 1319 |
+
return {
|
| 1320 |
+
"input_ids": None, # encoder_outputs is defined. input_ids not needed
|
| 1321 |
+
"encoder_outputs": encoder_outputs,
|
| 1322 |
+
"past_key_values": past_key_values,
|
| 1323 |
+
"decoder_input_ids": decoder_input_ids,
|
| 1324 |
+
"attention_mask": attention_mask,
|
| 1325 |
+
"head_mask": head_mask,
|
| 1326 |
+
"decoder_head_mask": decoder_head_mask,
|
| 1327 |
+
"cross_attn_head_mask": cross_attn_head_mask,
|
| 1328 |
+
"use_cache": use_cache, # change this to avoid caching (presumably for debugging)
|
| 1329 |
+
}
|
| 1330 |
+
|
| 1331 |
+
@staticmethod
|
| 1332 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 1333 |
+
reordered_past = ()
|
| 1334 |
+
for layer_past in past_key_values:
|
| 1335 |
+
# cached cross_attention states don't have to be reordered -> they are always the same
|
| 1336 |
+
reordered_past += (
|
| 1337 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2])
|
| 1338 |
+
+ layer_past[2:],
|
| 1339 |
+
)
|
| 1340 |
+
return reordered_past
|
| 1341 |
+
|
| 1342 |
+
|
| 1343 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->BlenderbotSmall
|
| 1344 |
+
class BlenderbotSmallDecoderWrapper(BlenderbotSmallPreTrainedModel):
|
| 1345 |
+
"""
|
| 1346 |
+
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
|
| 1347 |
+
used in combination with the [`EncoderDecoderModel`] framework.
|
| 1348 |
+
"""
|
| 1349 |
+
|
| 1350 |
+
def __init__(self, config):
|
| 1351 |
+
super().__init__(config)
|
| 1352 |
+
self.decoder = BlenderbotSmallDecoder(config)
|
| 1353 |
+
|
| 1354 |
+
def forward(self, *args, **kwargs):
|
| 1355 |
+
return self.decoder(*args, **kwargs)
|
| 1356 |
+
|
| 1357 |
+
|
| 1358 |
+
# Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->BlenderbotSmall, facebook/bart-base->facebook/blenderbot_small-90M
|
| 1359 |
+
class BlenderbotSmallForCausalLM(BlenderbotSmallPreTrainedModel):
|
| 1360 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 1361 |
+
|
| 1362 |
+
def __init__(self, config):
|
| 1363 |
+
config = copy.deepcopy(config)
|
| 1364 |
+
config.is_decoder = True
|
| 1365 |
+
config.is_encoder_decoder = False
|
| 1366 |
+
super().__init__(config)
|
| 1367 |
+
self.model = BlenderbotSmallDecoderWrapper(config)
|
| 1368 |
+
|
| 1369 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1370 |
+
|
| 1371 |
+
# Initialize weights and apply final processing
|
| 1372 |
+
self.post_init()
|
| 1373 |
+
|
| 1374 |
+
def get_input_embeddings(self):
|
| 1375 |
+
return self.model.decoder.embed_tokens
|
| 1376 |
+
|
| 1377 |
+
def set_input_embeddings(self, value):
|
| 1378 |
+
self.model.decoder.embed_tokens = value
|
| 1379 |
+
|
| 1380 |
+
def get_output_embeddings(self):
|
| 1381 |
+
return self.lm_head
|
| 1382 |
+
|
| 1383 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1384 |
+
self.lm_head = new_embeddings
|
| 1385 |
+
|
| 1386 |
+
def set_decoder(self, decoder):
|
| 1387 |
+
self.model.decoder = decoder
|
| 1388 |
+
|
| 1389 |
+
def get_decoder(self):
|
| 1390 |
+
return self.model.decoder
|
| 1391 |
+
|
| 1392 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
|
| 1393 |
+
def forward(
|
| 1394 |
+
self,
|
| 1395 |
+
input_ids: torch.LongTensor = None,
|
| 1396 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1397 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 1398 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 1399 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1400 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1401 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1402 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1403 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1404 |
+
use_cache: Optional[bool] = None,
|
| 1405 |
+
output_attentions: Optional[bool] = None,
|
| 1406 |
+
output_hidden_states: Optional[bool] = None,
|
| 1407 |
+
return_dict: Optional[bool] = None,
|
| 1408 |
+
) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
|
| 1409 |
+
r"""
|
| 1410 |
+
Args:
|
| 1411 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 1412 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 1413 |
+
provide it.
|
| 1414 |
+
|
| 1415 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1416 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1417 |
+
|
| 1418 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1419 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1420 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1421 |
+
|
| 1422 |
+
- 1 for tokens that are **not masked**,
|
| 1423 |
+
- 0 for tokens that are **masked**.
|
| 1424 |
+
|
| 1425 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1426 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1427 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 1428 |
+
if the model is configured as a decoder.
|
| 1429 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1430 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
|
| 1431 |
+
in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1432 |
+
head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 1433 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 1434 |
+
|
| 1435 |
+
- 1 indicates the head is **not masked**,
|
| 1436 |
+
- 0 indicates the head is **masked**.
|
| 1437 |
+
|
| 1438 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 1439 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 1440 |
+
|
| 1441 |
+
- 1 indicates the head is **not masked**,
|
| 1442 |
+
- 0 indicates the head is **masked**.
|
| 1443 |
+
|
| 1444 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 1445 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 1446 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
|
| 1447 |
+
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
|
| 1448 |
+
tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
|
| 1449 |
+
|
| 1450 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 1451 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 1452 |
+
|
| 1453 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 1454 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 1455 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1456 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1457 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1458 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1459 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1460 |
+
use_cache (`bool`, *optional*):
|
| 1461 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 1462 |
+
(see `past_key_values`).
|
| 1463 |
+
|
| 1464 |
+
- 1 for tokens that are **not masked**,
|
| 1465 |
+
- 0 for tokens that are **masked**.
|
| 1466 |
+
output_attentions (`bool`, *optional*):
|
| 1467 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 1468 |
+
returned tensors for more detail.
|
| 1469 |
+
output_hidden_states (`bool`, *optional*):
|
| 1470 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 1471 |
+
for more detail.
|
| 1472 |
+
return_dict (`bool`, *optional*):
|
| 1473 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 1474 |
+
|
| 1475 |
+
Returns:
|
| 1476 |
+
|
| 1477 |
+
Example:
|
| 1478 |
+
|
| 1479 |
+
```python
|
| 1480 |
+
>>> from transformers import AutoTokenizer, BlenderbotSmallForCausalLM
|
| 1481 |
+
|
| 1482 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
|
| 1483 |
+
>>> model = BlenderbotSmallForCausalLM.from_pretrained("facebook/blenderbot_small-90M", add_cross_attention=False)
|
| 1484 |
+
>>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
|
| 1485 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 1486 |
+
>>> outputs = model(**inputs)
|
| 1487 |
+
|
| 1488 |
+
>>> logits = outputs.logits
|
| 1489 |
+
>>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
|
| 1490 |
+
>>> list(logits.shape) == expected_shape
|
| 1491 |
+
True
|
| 1492 |
+
```"""
|
| 1493 |
+
|
| 1494 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1495 |
+
output_hidden_states = (
|
| 1496 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1497 |
+
)
|
| 1498 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1499 |
+
|
| 1500 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1501 |
+
outputs = self.model.decoder(
|
| 1502 |
+
input_ids=input_ids,
|
| 1503 |
+
attention_mask=attention_mask,
|
| 1504 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1505 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1506 |
+
head_mask=head_mask,
|
| 1507 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1508 |
+
past_key_values=past_key_values,
|
| 1509 |
+
inputs_embeds=inputs_embeds,
|
| 1510 |
+
use_cache=use_cache,
|
| 1511 |
+
output_attentions=output_attentions,
|
| 1512 |
+
output_hidden_states=output_hidden_states,
|
| 1513 |
+
return_dict=return_dict,
|
| 1514 |
+
)
|
| 1515 |
+
|
| 1516 |
+
logits = self.lm_head(outputs[0])
|
| 1517 |
+
|
| 1518 |
+
loss = None
|
| 1519 |
+
if labels is not None:
|
| 1520 |
+
labels = labels.to(logits.device)
|
| 1521 |
+
loss_fct = CrossEntropyLoss()
|
| 1522 |
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1523 |
+
|
| 1524 |
+
if not return_dict:
|
| 1525 |
+
output = (logits,) + outputs[1:]
|
| 1526 |
+
return (loss,) + output if loss is not None else output
|
| 1527 |
+
|
| 1528 |
+
return CausalLMOutputWithCrossAttentions(
|
| 1529 |
+
loss=loss,
|
| 1530 |
+
logits=logits,
|
| 1531 |
+
past_key_values=outputs.past_key_values,
|
| 1532 |
+
hidden_states=outputs.hidden_states,
|
| 1533 |
+
attentions=outputs.attentions,
|
| 1534 |
+
cross_attentions=outputs.cross_attentions,
|
| 1535 |
+
)
|
| 1536 |
+
|
| 1537 |
+
def prepare_inputs_for_generation(
|
| 1538 |
+
self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
|
| 1539 |
+
):
|
| 1540 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
| 1541 |
+
if attention_mask is None:
|
| 1542 |
+
attention_mask = input_ids.new_ones(input_ids.shape)
|
| 1543 |
+
|
| 1544 |
+
if past_key_values:
|
| 1545 |
+
past_length = past_key_values[0][0].shape[2]
|
| 1546 |
+
|
| 1547 |
+
# Some generation methods already pass only the last input ID
|
| 1548 |
+
if input_ids.shape[1] > past_length:
|
| 1549 |
+
remove_prefix_length = past_length
|
| 1550 |
+
else:
|
| 1551 |
+
# Default to old behavior: keep only final ID
|
| 1552 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
| 1553 |
+
|
| 1554 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
| 1555 |
+
# first step, decoder_cached_states are empty
|
| 1556 |
+
return {
|
| 1557 |
+
"input_ids": input_ids, # encoder_outputs is defined. input_ids not needed
|
| 1558 |
+
"attention_mask": attention_mask,
|
| 1559 |
+
"past_key_values": past_key_values,
|
| 1560 |
+
"use_cache": use_cache,
|
| 1561 |
+
}
|
| 1562 |
+
|
| 1563 |
+
@staticmethod
|
| 1564 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 1565 |
+
reordered_past = ()
|
| 1566 |
+
for layer_past in past_key_values:
|
| 1567 |
+
reordered_past += (
|
| 1568 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 1569 |
+
)
|
| 1570 |
+
return reordered_past
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py
ADDED
|
@@ -0,0 +1,1522 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Facebook, Inc. and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Flax BlenderbotSmall model."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
import random
|
| 20 |
+
from functools import partial
|
| 21 |
+
from typing import Callable, Optional, Tuple
|
| 22 |
+
|
| 23 |
+
import flax.linen as nn
|
| 24 |
+
import jax
|
| 25 |
+
import jax.numpy as jnp
|
| 26 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
| 27 |
+
from flax.linen import combine_masks, make_causal_mask
|
| 28 |
+
from flax.linen.attention import dot_product_attention_weights
|
| 29 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 30 |
+
from jax import lax
|
| 31 |
+
from jax.random import PRNGKey
|
| 32 |
+
|
| 33 |
+
from ...modeling_flax_outputs import (
|
| 34 |
+
FlaxBaseModelOutput,
|
| 35 |
+
FlaxBaseModelOutputWithPastAndCrossAttentions,
|
| 36 |
+
FlaxCausalLMOutputWithCrossAttentions,
|
| 37 |
+
FlaxSeq2SeqLMOutput,
|
| 38 |
+
FlaxSeq2SeqModelOutput,
|
| 39 |
+
)
|
| 40 |
+
from ...modeling_flax_utils import (
|
| 41 |
+
ACT2FN,
|
| 42 |
+
FlaxPreTrainedModel,
|
| 43 |
+
append_call_sample_docstring,
|
| 44 |
+
append_replace_return_docstrings,
|
| 45 |
+
overwrite_call_docstring,
|
| 46 |
+
)
|
| 47 |
+
from ...utils import add_start_docstrings, logging, replace_return_docstrings
|
| 48 |
+
from .configuration_blenderbot_small import BlenderbotSmallConfig
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
logger = logging.get_logger(__name__)
|
| 52 |
+
|
| 53 |
+
_CHECKPOINT_FOR_DOC = "facebook/blenderbot_small-90M"
|
| 54 |
+
_CONFIG_FOR_DOC = "BlenderbotSmallConfig"
|
| 55 |
+
|
| 56 |
+
BLENDERBOT_SMALL_START_DOCSTRING = r"""
|
| 57 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 58 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 59 |
+
etc.)
|
| 60 |
+
|
| 61 |
+
This model is also a Flax Linen
|
| 62 |
+
[flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
|
| 63 |
+
regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
|
| 64 |
+
|
| 65 |
+
Finally, this model supports inherent JAX features such as:
|
| 66 |
+
|
| 67 |
+
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
|
| 68 |
+
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
|
| 69 |
+
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
|
| 70 |
+
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
|
| 71 |
+
|
| 72 |
+
Parameters:
|
| 73 |
+
config ([`BlenderbotSmallConfig`]): Model configuration class with all the parameters of the model.
|
| 74 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 75 |
+
configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 76 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
| 77 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
| 78 |
+
`jax.numpy.bfloat16` (on TPUs).
|
| 79 |
+
|
| 80 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
| 81 |
+
specified all the computation will be performed with the given `dtype`.
|
| 82 |
+
|
| 83 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
| 84 |
+
parameters.**
|
| 85 |
+
|
| 86 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
| 87 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
BLENDERBOT_SMALL_INPUTS_DOCSTRING = r"""
|
| 91 |
+
Args:
|
| 92 |
+
input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
|
| 93 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 94 |
+
it.
|
| 95 |
+
|
| 96 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 97 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 98 |
+
|
| 99 |
+
[What are input IDs?](../glossary#input-ids)
|
| 100 |
+
attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 101 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 102 |
+
|
| 103 |
+
- 1 for tokens that are **not masked**,
|
| 104 |
+
- 0 for tokens that are **masked**.
|
| 105 |
+
|
| 106 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 107 |
+
decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 108 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 109 |
+
|
| 110 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 111 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 112 |
+
|
| 113 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 114 |
+
|
| 115 |
+
For translation and summarization training, `decoder_input_ids` should be provided. If no
|
| 116 |
+
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
|
| 117 |
+
for denoising pre-training following the paper.
|
| 118 |
+
decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 119 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 120 |
+
be used by default.
|
| 121 |
+
|
| 122 |
+
If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
|
| 123 |
+
paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
|
| 124 |
+
position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 125 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 126 |
+
config.max_position_embeddings - 1]`.
|
| 127 |
+
decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 128 |
+
Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
|
| 129 |
+
range `[0, config.max_position_embeddings - 1]`.
|
| 130 |
+
output_attentions (`bool`, *optional*):
|
| 131 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 132 |
+
tensors for more detail.
|
| 133 |
+
output_hidden_states (`bool`, *optional*):
|
| 134 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 135 |
+
more detail.
|
| 136 |
+
return_dict (`bool`, *optional*):
|
| 137 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
BLENDERBOT_SMALL_ENCODE_INPUTS_DOCSTRING = r"""
|
| 142 |
+
Args:
|
| 143 |
+
input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
|
| 144 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 145 |
+
it.
|
| 146 |
+
|
| 147 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 148 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 149 |
+
|
| 150 |
+
[What are input IDs?](../glossary#input-ids)
|
| 151 |
+
attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 152 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 153 |
+
|
| 154 |
+
- 1 for tokens that are **not masked**,
|
| 155 |
+
- 0 for tokens that are **masked**.
|
| 156 |
+
|
| 157 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 158 |
+
position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 159 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 160 |
+
config.max_position_embeddings - 1]`.
|
| 161 |
+
output_attentions (`bool`, *optional*):
|
| 162 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 163 |
+
tensors for more detail.
|
| 164 |
+
output_hidden_states (`bool`, *optional*):
|
| 165 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 166 |
+
more detail.
|
| 167 |
+
return_dict (`bool`, *optional*):
|
| 168 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
BLENDERBOT_SMALL_DECODE_INPUTS_DOCSTRING = r"""
|
| 172 |
+
Args:
|
| 173 |
+
decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`):
|
| 174 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 175 |
+
|
| 176 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 177 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 178 |
+
|
| 179 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 180 |
+
|
| 181 |
+
For translation and summarization training, `decoder_input_ids` should be provided. If no
|
| 182 |
+
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
|
| 183 |
+
for denoising pre-training following the paper.
|
| 184 |
+
encoder_outputs (`tuple(tuple(jnp.ndarray)`):
|
| 185 |
+
Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
|
| 186 |
+
`last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
|
| 187 |
+
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
|
| 188 |
+
encoder_attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 189 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 190 |
+
|
| 191 |
+
- 1 for tokens that are **not masked**,
|
| 192 |
+
- 0 for tokens that are **masked**.
|
| 193 |
+
|
| 194 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 195 |
+
decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 196 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 197 |
+
be used by default.
|
| 198 |
+
|
| 199 |
+
If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
|
| 200 |
+
paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
|
| 201 |
+
decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 202 |
+
Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
|
| 203 |
+
range `[0, config.max_position_embeddings - 1]`.
|
| 204 |
+
past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
|
| 205 |
+
Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
|
| 206 |
+
auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
|
| 207 |
+
output_attentions (`bool`, *optional*):
|
| 208 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 209 |
+
tensors for more detail.
|
| 210 |
+
output_hidden_states (`bool`, *optional*):
|
| 211 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 212 |
+
more detail.
|
| 213 |
+
return_dict (`bool`, *optional*):
|
| 214 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 215 |
+
"""
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# Copied from transformers.models.bart.modeling_flax_bart.shift_tokens_right
|
| 219 |
+
def shift_tokens_right(input_ids: jnp.ndarray, pad_token_id: int, decoder_start_token_id: int) -> jnp.ndarray:
|
| 220 |
+
"""
|
| 221 |
+
Shift input ids one token to the right.
|
| 222 |
+
"""
|
| 223 |
+
shifted_input_ids = jnp.zeros_like(input_ids)
|
| 224 |
+
shifted_input_ids = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1])
|
| 225 |
+
shifted_input_ids = shifted_input_ids.at[:, 0].set(decoder_start_token_id)
|
| 226 |
+
|
| 227 |
+
shifted_input_ids = jnp.where(shifted_input_ids == -100, pad_token_id, shifted_input_ids)
|
| 228 |
+
return shifted_input_ids
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartAttention with Bart->BlenderbotSmall
|
| 232 |
+
class FlaxBlenderbotSmallAttention(nn.Module):
|
| 233 |
+
config: BlenderbotSmallConfig
|
| 234 |
+
embed_dim: int
|
| 235 |
+
num_heads: int
|
| 236 |
+
dropout: float = 0.0
|
| 237 |
+
causal: bool = False
|
| 238 |
+
bias: bool = True
|
| 239 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 240 |
+
|
| 241 |
+
def setup(self) -> None:
|
| 242 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 243 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 244 |
+
raise ValueError(
|
| 245 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 246 |
+
f" and `num_heads`: {self.num_heads})."
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
dense = partial(
|
| 250 |
+
nn.Dense,
|
| 251 |
+
self.embed_dim,
|
| 252 |
+
use_bias=self.bias,
|
| 253 |
+
dtype=self.dtype,
|
| 254 |
+
kernel_init=jax.nn.initializers.normal(self.config.init_std),
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
self.q_proj, self.k_proj, self.v_proj = dense(), dense(), dense()
|
| 258 |
+
self.out_proj = dense()
|
| 259 |
+
|
| 260 |
+
self.dropout_layer = nn.Dropout(rate=self.dropout)
|
| 261 |
+
|
| 262 |
+
if self.causal:
|
| 263 |
+
self.causal_mask = make_causal_mask(
|
| 264 |
+
jnp.ones((1, self.config.max_position_embeddings), dtype="bool"), dtype="bool"
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
def _split_heads(self, hidden_states):
|
| 268 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (self.num_heads, self.head_dim))
|
| 269 |
+
|
| 270 |
+
def _merge_heads(self, hidden_states):
|
| 271 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
|
| 272 |
+
|
| 273 |
+
@nn.compact
|
| 274 |
+
def _concatenate_to_cache(self, key, value, query, attention_mask):
|
| 275 |
+
"""
|
| 276 |
+
This function takes projected key, value states from a single input token and concatenates the states to cached
|
| 277 |
+
states from previous steps. This function is slighly adapted from the official Flax repository:
|
| 278 |
+
https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
|
| 279 |
+
"""
|
| 280 |
+
# detect if we're initializing by absence of existing cache data.
|
| 281 |
+
is_initialized = self.has_variable("cache", "cached_key")
|
| 282 |
+
cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
|
| 283 |
+
cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
|
| 284 |
+
cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
|
| 285 |
+
|
| 286 |
+
if is_initialized:
|
| 287 |
+
*batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
|
| 288 |
+
# update key, value caches with our new 1d spatial slices
|
| 289 |
+
cur_index = cache_index.value
|
| 290 |
+
indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
|
| 291 |
+
key = lax.dynamic_update_slice(cached_key.value, key, indices)
|
| 292 |
+
value = lax.dynamic_update_slice(cached_value.value, value, indices)
|
| 293 |
+
cached_key.value = key
|
| 294 |
+
cached_value.value = value
|
| 295 |
+
num_updated_cache_vectors = query.shape[1]
|
| 296 |
+
cache_index.value = cache_index.value + num_updated_cache_vectors
|
| 297 |
+
# causal mask for cached decoder self-attention: our single query position should only attend to those key positions that have already been generated and cached, not the remaining zero elements.
|
| 298 |
+
pad_mask = jnp.broadcast_to(
|
| 299 |
+
jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
|
| 300 |
+
tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
|
| 301 |
+
)
|
| 302 |
+
attention_mask = combine_masks(pad_mask, attention_mask)
|
| 303 |
+
return key, value, attention_mask
|
| 304 |
+
|
| 305 |
+
def __call__(
|
| 306 |
+
self,
|
| 307 |
+
hidden_states: jnp.ndarray,
|
| 308 |
+
key_value_states: Optional[jnp.ndarray] = None,
|
| 309 |
+
attention_mask: Optional[jnp.ndarray] = None,
|
| 310 |
+
init_cache: bool = False,
|
| 311 |
+
deterministic: bool = True,
|
| 312 |
+
) -> Tuple[jnp.ndarray]:
|
| 313 |
+
"""Input shape: Batch x Time x Channel"""
|
| 314 |
+
|
| 315 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 316 |
+
# for the decoder
|
| 317 |
+
is_cross_attention = key_value_states is not None
|
| 318 |
+
batch_size = hidden_states.shape[0]
|
| 319 |
+
|
| 320 |
+
# get query proj
|
| 321 |
+
query_states = self.q_proj(hidden_states)
|
| 322 |
+
# get key, value proj
|
| 323 |
+
if is_cross_attention:
|
| 324 |
+
# cross_attentions
|
| 325 |
+
key_states = self.k_proj(key_value_states)
|
| 326 |
+
value_states = self.v_proj(key_value_states)
|
| 327 |
+
else:
|
| 328 |
+
# self_attention
|
| 329 |
+
key_states = self.k_proj(hidden_states)
|
| 330 |
+
value_states = self.v_proj(hidden_states)
|
| 331 |
+
|
| 332 |
+
query_states = self._split_heads(query_states)
|
| 333 |
+
key_states = self._split_heads(key_states)
|
| 334 |
+
value_states = self._split_heads(value_states)
|
| 335 |
+
|
| 336 |
+
# handle cache prepare causal attention mask
|
| 337 |
+
if self.causal:
|
| 338 |
+
query_length, key_length = query_states.shape[1], key_states.shape[1]
|
| 339 |
+
if self.has_variable("cache", "cached_key"):
|
| 340 |
+
mask_shift = self.variables["cache"]["cache_index"]
|
| 341 |
+
max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
|
| 342 |
+
causal_mask = lax.dynamic_slice(
|
| 343 |
+
self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
|
| 344 |
+
)
|
| 345 |
+
else:
|
| 346 |
+
causal_mask = self.causal_mask[:, :, :query_length, :key_length]
|
| 347 |
+
causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
|
| 348 |
+
|
| 349 |
+
# combine masks if needed
|
| 350 |
+
if attention_mask is not None and self.causal:
|
| 351 |
+
attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
|
| 352 |
+
attention_mask = combine_masks(attention_mask, causal_mask)
|
| 353 |
+
elif self.causal:
|
| 354 |
+
attention_mask = causal_mask
|
| 355 |
+
elif attention_mask is not None:
|
| 356 |
+
attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
|
| 357 |
+
|
| 358 |
+
# During fast autoregressive decoding, we feed one position at a time,
|
| 359 |
+
# and cache the keys and values step by step.
|
| 360 |
+
if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
|
| 361 |
+
key_states, value_states, attention_mask = self._concatenate_to_cache(
|
| 362 |
+
key_states, value_states, query_states, attention_mask
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
# Convert the boolean attention mask to an attention bias.
|
| 366 |
+
if attention_mask is not None:
|
| 367 |
+
# attention mask in the form of attention bias
|
| 368 |
+
attention_bias = lax.select(
|
| 369 |
+
attention_mask > 0,
|
| 370 |
+
jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
|
| 371 |
+
jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
|
| 372 |
+
)
|
| 373 |
+
else:
|
| 374 |
+
attention_bias = None
|
| 375 |
+
|
| 376 |
+
dropout_rng = None
|
| 377 |
+
if not deterministic and self.dropout > 0.0:
|
| 378 |
+
dropout_rng = self.make_rng("dropout")
|
| 379 |
+
|
| 380 |
+
attn_weights = dot_product_attention_weights(
|
| 381 |
+
query_states,
|
| 382 |
+
key_states,
|
| 383 |
+
bias=attention_bias,
|
| 384 |
+
dropout_rng=dropout_rng,
|
| 385 |
+
dropout_rate=self.dropout,
|
| 386 |
+
broadcast_dropout=True,
|
| 387 |
+
deterministic=deterministic,
|
| 388 |
+
dtype=self.dtype,
|
| 389 |
+
precision=None,
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
|
| 393 |
+
attn_output = self._merge_heads(attn_output)
|
| 394 |
+
attn_output = self.out_proj(attn_output)
|
| 395 |
+
|
| 396 |
+
return attn_output, attn_weights
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartEncoderLayer with Bart->BlenderbotSmall
|
| 400 |
+
class FlaxBlenderbotSmallEncoderLayer(nn.Module):
|
| 401 |
+
config: BlenderbotSmallConfig
|
| 402 |
+
dtype: jnp.dtype = jnp.float32
|
| 403 |
+
|
| 404 |
+
def setup(self) -> None:
|
| 405 |
+
self.embed_dim = self.config.d_model
|
| 406 |
+
self.self_attn = FlaxBlenderbotSmallAttention(
|
| 407 |
+
config=self.config,
|
| 408 |
+
embed_dim=self.embed_dim,
|
| 409 |
+
num_heads=self.config.encoder_attention_heads,
|
| 410 |
+
dropout=self.config.attention_dropout,
|
| 411 |
+
dtype=self.dtype,
|
| 412 |
+
)
|
| 413 |
+
self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 414 |
+
self.dropout_layer = nn.Dropout(rate=self.config.dropout)
|
| 415 |
+
self.activation_fn = ACT2FN[self.config.activation_function]
|
| 416 |
+
self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
|
| 417 |
+
self.fc1 = nn.Dense(
|
| 418 |
+
self.config.encoder_ffn_dim,
|
| 419 |
+
dtype=self.dtype,
|
| 420 |
+
kernel_init=jax.nn.initializers.normal(self.config.init_std),
|
| 421 |
+
)
|
| 422 |
+
self.fc2 = nn.Dense(
|
| 423 |
+
self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
|
| 424 |
+
)
|
| 425 |
+
self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 426 |
+
|
| 427 |
+
def __call__(
|
| 428 |
+
self,
|
| 429 |
+
hidden_states: jnp.ndarray,
|
| 430 |
+
attention_mask: jnp.ndarray,
|
| 431 |
+
output_attentions: bool = True,
|
| 432 |
+
deterministic: bool = True,
|
| 433 |
+
) -> Tuple[jnp.ndarray]:
|
| 434 |
+
residual = hidden_states
|
| 435 |
+
hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask)
|
| 436 |
+
|
| 437 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 438 |
+
hidden_states = residual + hidden_states
|
| 439 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 440 |
+
|
| 441 |
+
residual = hidden_states
|
| 442 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 443 |
+
hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
|
| 444 |
+
hidden_states = self.fc2(hidden_states)
|
| 445 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 446 |
+
hidden_states = residual + hidden_states
|
| 447 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 448 |
+
|
| 449 |
+
outputs = (hidden_states,)
|
| 450 |
+
|
| 451 |
+
if output_attentions:
|
| 452 |
+
outputs += (attn_weights,)
|
| 453 |
+
|
| 454 |
+
return outputs
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartEncoderLayerCollection with Bart->BlenderbotSmall
|
| 458 |
+
class FlaxBlenderbotSmallEncoderLayerCollection(nn.Module):
|
| 459 |
+
config: BlenderbotSmallConfig
|
| 460 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 461 |
+
|
| 462 |
+
def setup(self):
|
| 463 |
+
self.layers = [
|
| 464 |
+
FlaxBlenderbotSmallEncoderLayer(self.config, name=str(i), dtype=self.dtype)
|
| 465 |
+
for i in range(self.config.encoder_layers)
|
| 466 |
+
]
|
| 467 |
+
self.layerdrop = self.config.encoder_layerdrop
|
| 468 |
+
|
| 469 |
+
def __call__(
|
| 470 |
+
self,
|
| 471 |
+
hidden_states,
|
| 472 |
+
attention_mask,
|
| 473 |
+
deterministic: bool = True,
|
| 474 |
+
output_attentions: bool = False,
|
| 475 |
+
output_hidden_states: bool = False,
|
| 476 |
+
return_dict: bool = True,
|
| 477 |
+
):
|
| 478 |
+
all_attentions = () if output_attentions else None
|
| 479 |
+
all_hidden_states = () if output_hidden_states else None
|
| 480 |
+
|
| 481 |
+
for encoder_layer in self.layers:
|
| 482 |
+
if output_hidden_states:
|
| 483 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 484 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 485 |
+
dropout_probability = random.uniform(0, 1)
|
| 486 |
+
if not deterministic and (dropout_probability < self.layerdrop): # skip the layer
|
| 487 |
+
layer_outputs = (None, None)
|
| 488 |
+
else:
|
| 489 |
+
layer_outputs = encoder_layer(
|
| 490 |
+
hidden_states,
|
| 491 |
+
attention_mask,
|
| 492 |
+
output_attentions,
|
| 493 |
+
deterministic,
|
| 494 |
+
)
|
| 495 |
+
hidden_states = layer_outputs[0]
|
| 496 |
+
if output_attentions:
|
| 497 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 498 |
+
|
| 499 |
+
if output_hidden_states:
|
| 500 |
+
all_hidden_states += (hidden_states,)
|
| 501 |
+
|
| 502 |
+
outputs = (hidden_states, all_hidden_states, all_attentions)
|
| 503 |
+
|
| 504 |
+
if not return_dict:
|
| 505 |
+
return tuple(v for v in outputs if v is not None)
|
| 506 |
+
|
| 507 |
+
return FlaxBaseModelOutput(
|
| 508 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderLayer with Bart->BlenderbotSmall
|
| 513 |
+
class FlaxBlenderbotSmallDecoderLayer(nn.Module):
|
| 514 |
+
config: BlenderbotSmallConfig
|
| 515 |
+
dtype: jnp.dtype = jnp.float32
|
| 516 |
+
|
| 517 |
+
def setup(self) -> None:
|
| 518 |
+
self.embed_dim = self.config.d_model
|
| 519 |
+
self.self_attn = FlaxBlenderbotSmallAttention(
|
| 520 |
+
config=self.config,
|
| 521 |
+
embed_dim=self.embed_dim,
|
| 522 |
+
num_heads=self.config.decoder_attention_heads,
|
| 523 |
+
dropout=self.config.attention_dropout,
|
| 524 |
+
causal=True,
|
| 525 |
+
dtype=self.dtype,
|
| 526 |
+
)
|
| 527 |
+
self.dropout_layer = nn.Dropout(rate=self.config.dropout)
|
| 528 |
+
self.activation_fn = ACT2FN[self.config.activation_function]
|
| 529 |
+
self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
|
| 530 |
+
|
| 531 |
+
self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 532 |
+
self.encoder_attn = FlaxBlenderbotSmallAttention(
|
| 533 |
+
config=self.config,
|
| 534 |
+
embed_dim=self.embed_dim,
|
| 535 |
+
num_heads=self.config.decoder_attention_heads,
|
| 536 |
+
dropout=self.config.attention_dropout,
|
| 537 |
+
dtype=self.dtype,
|
| 538 |
+
)
|
| 539 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 540 |
+
self.fc1 = nn.Dense(
|
| 541 |
+
self.config.decoder_ffn_dim,
|
| 542 |
+
dtype=self.dtype,
|
| 543 |
+
kernel_init=jax.nn.initializers.normal(self.config.init_std),
|
| 544 |
+
)
|
| 545 |
+
self.fc2 = nn.Dense(
|
| 546 |
+
self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
|
| 547 |
+
)
|
| 548 |
+
self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 549 |
+
|
| 550 |
+
def __call__(
|
| 551 |
+
self,
|
| 552 |
+
hidden_states: jnp.ndarray,
|
| 553 |
+
attention_mask: jnp.ndarray,
|
| 554 |
+
encoder_hidden_states: Optional[jnp.ndarray] = None,
|
| 555 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 556 |
+
init_cache: bool = False,
|
| 557 |
+
output_attentions: bool = True,
|
| 558 |
+
deterministic: bool = True,
|
| 559 |
+
) -> Tuple[jnp.ndarray]:
|
| 560 |
+
residual = hidden_states
|
| 561 |
+
|
| 562 |
+
# Self Attention
|
| 563 |
+
hidden_states, self_attn_weights = self.self_attn(
|
| 564 |
+
hidden_states=hidden_states, attention_mask=attention_mask, init_cache=init_cache
|
| 565 |
+
)
|
| 566 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 567 |
+
hidden_states = residual + hidden_states
|
| 568 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 569 |
+
|
| 570 |
+
# Cross-Attention Block
|
| 571 |
+
cross_attn_weights = None
|
| 572 |
+
if encoder_hidden_states is not None:
|
| 573 |
+
residual = hidden_states
|
| 574 |
+
|
| 575 |
+
hidden_states, cross_attn_weights = self.encoder_attn(
|
| 576 |
+
hidden_states=hidden_states,
|
| 577 |
+
key_value_states=encoder_hidden_states,
|
| 578 |
+
attention_mask=encoder_attention_mask,
|
| 579 |
+
)
|
| 580 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 581 |
+
hidden_states = residual + hidden_states
|
| 582 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 583 |
+
|
| 584 |
+
# Fully Connected
|
| 585 |
+
residual = hidden_states
|
| 586 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 587 |
+
hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
|
| 588 |
+
hidden_states = self.fc2(hidden_states)
|
| 589 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 590 |
+
hidden_states = residual + hidden_states
|
| 591 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 592 |
+
|
| 593 |
+
outputs = (hidden_states,)
|
| 594 |
+
|
| 595 |
+
if output_attentions:
|
| 596 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 597 |
+
|
| 598 |
+
return outputs
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderLayerCollection with Bart->BlenderbotSmall
|
| 602 |
+
class FlaxBlenderbotSmallDecoderLayerCollection(nn.Module):
|
| 603 |
+
config: BlenderbotSmallConfig
|
| 604 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 605 |
+
|
| 606 |
+
def setup(self):
|
| 607 |
+
self.layers = [
|
| 608 |
+
FlaxBlenderbotSmallDecoderLayer(self.config, name=str(i), dtype=self.dtype)
|
| 609 |
+
for i in range(self.config.decoder_layers)
|
| 610 |
+
]
|
| 611 |
+
self.layerdrop = self.config.decoder_layerdrop
|
| 612 |
+
|
| 613 |
+
def __call__(
|
| 614 |
+
self,
|
| 615 |
+
hidden_states,
|
| 616 |
+
attention_mask,
|
| 617 |
+
encoder_hidden_states: Optional[jnp.ndarray] = None,
|
| 618 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 619 |
+
deterministic: bool = True,
|
| 620 |
+
init_cache: bool = False,
|
| 621 |
+
output_attentions: bool = False,
|
| 622 |
+
output_hidden_states: bool = False,
|
| 623 |
+
return_dict: bool = True,
|
| 624 |
+
):
|
| 625 |
+
# decoder layers
|
| 626 |
+
all_hidden_states = () if output_hidden_states else None
|
| 627 |
+
all_self_attns = () if output_attentions else None
|
| 628 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 629 |
+
|
| 630 |
+
for decoder_layer in self.layers:
|
| 631 |
+
if output_hidden_states:
|
| 632 |
+
all_hidden_states += (hidden_states,)
|
| 633 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 634 |
+
dropout_probability = random.uniform(0, 1)
|
| 635 |
+
if not deterministic and (dropout_probability < self.layerdrop):
|
| 636 |
+
layer_outputs = (None, None, None)
|
| 637 |
+
else:
|
| 638 |
+
layer_outputs = decoder_layer(
|
| 639 |
+
hidden_states,
|
| 640 |
+
attention_mask=attention_mask,
|
| 641 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 642 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 643 |
+
init_cache=init_cache,
|
| 644 |
+
output_attentions=output_attentions,
|
| 645 |
+
deterministic=deterministic,
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
hidden_states = layer_outputs[0]
|
| 649 |
+
if output_attentions:
|
| 650 |
+
all_self_attns += (layer_outputs[1],)
|
| 651 |
+
|
| 652 |
+
if encoder_hidden_states is not None:
|
| 653 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 654 |
+
|
| 655 |
+
# add hidden states from the last decoder layer
|
| 656 |
+
if output_hidden_states:
|
| 657 |
+
all_hidden_states += (hidden_states,)
|
| 658 |
+
|
| 659 |
+
outputs = [hidden_states, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 660 |
+
|
| 661 |
+
if not return_dict:
|
| 662 |
+
return tuple(v for v in outputs if v is not None)
|
| 663 |
+
|
| 664 |
+
return FlaxBaseModelOutputWithPastAndCrossAttentions(
|
| 665 |
+
last_hidden_state=hidden_states,
|
| 666 |
+
hidden_states=all_hidden_states,
|
| 667 |
+
attentions=all_self_attns,
|
| 668 |
+
cross_attentions=all_cross_attentions,
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
class FlaxBlenderbotSmallEncoder(nn.Module):
|
| 673 |
+
config: BlenderbotSmallConfig
|
| 674 |
+
embed_tokens: nn.Embed
|
| 675 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 676 |
+
|
| 677 |
+
def setup(self):
|
| 678 |
+
self.dropout_layer = nn.Dropout(rate=self.config.dropout)
|
| 679 |
+
|
| 680 |
+
embed_dim = self.config.d_model
|
| 681 |
+
self.padding_idx = self.config.pad_token_id
|
| 682 |
+
self.max_source_positions = self.config.max_position_embeddings
|
| 683 |
+
self.embed_scale = math.sqrt(embed_dim) if self.config.scale_embedding else 1.0
|
| 684 |
+
|
| 685 |
+
self.embed_positions = nn.Embed(
|
| 686 |
+
self.config.max_position_embeddings,
|
| 687 |
+
embed_dim,
|
| 688 |
+
embedding_init=jax.nn.initializers.normal(self.config.init_std),
|
| 689 |
+
)
|
| 690 |
+
self.layers = FlaxBlenderbotSmallEncoderLayerCollection(self.config, self.dtype)
|
| 691 |
+
self.layernorm_embedding = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 692 |
+
|
| 693 |
+
def __call__(
|
| 694 |
+
self,
|
| 695 |
+
input_ids,
|
| 696 |
+
attention_mask,
|
| 697 |
+
position_ids,
|
| 698 |
+
output_attentions: bool = False,
|
| 699 |
+
output_hidden_states: bool = False,
|
| 700 |
+
return_dict: bool = True,
|
| 701 |
+
deterministic: bool = True,
|
| 702 |
+
):
|
| 703 |
+
input_shape = input_ids.shape
|
| 704 |
+
input_ids = input_ids.reshape(-1, input_shape[-1])
|
| 705 |
+
|
| 706 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 707 |
+
|
| 708 |
+
embed_pos = self.embed_positions(position_ids)
|
| 709 |
+
|
| 710 |
+
hidden_states = inputs_embeds + embed_pos
|
| 711 |
+
hidden_states = self.layernorm_embedding(hidden_states)
|
| 712 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 713 |
+
|
| 714 |
+
outputs = self.layers(
|
| 715 |
+
hidden_states,
|
| 716 |
+
attention_mask,
|
| 717 |
+
deterministic=deterministic,
|
| 718 |
+
output_attentions=output_attentions,
|
| 719 |
+
output_hidden_states=output_hidden_states,
|
| 720 |
+
return_dict=return_dict,
|
| 721 |
+
)
|
| 722 |
+
|
| 723 |
+
if not return_dict:
|
| 724 |
+
return outputs
|
| 725 |
+
|
| 726 |
+
return FlaxBaseModelOutput(
|
| 727 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 728 |
+
hidden_states=outputs.hidden_states,
|
| 729 |
+
attentions=outputs.attentions,
|
| 730 |
+
)
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
class FlaxBlenderbotSmallDecoder(nn.Module):
|
| 734 |
+
config: BlenderbotSmallConfig
|
| 735 |
+
embed_tokens: nn.Embed
|
| 736 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 737 |
+
|
| 738 |
+
def setup(self):
|
| 739 |
+
self.dropout_layer = nn.Dropout(rate=self.config.dropout)
|
| 740 |
+
|
| 741 |
+
embed_dim = self.config.d_model
|
| 742 |
+
self.padding_idx = self.config.pad_token_id
|
| 743 |
+
self.max_target_positions = self.config.max_position_embeddings
|
| 744 |
+
self.embed_scale = math.sqrt(self.config.d_model) if self.config.scale_embedding else 1.0
|
| 745 |
+
|
| 746 |
+
self.embed_positions = nn.Embed(
|
| 747 |
+
self.config.max_position_embeddings,
|
| 748 |
+
embed_dim,
|
| 749 |
+
embedding_init=jax.nn.initializers.normal(self.config.init_std),
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
self.layers = FlaxBlenderbotSmallDecoderLayerCollection(self.config, self.dtype)
|
| 753 |
+
self.layernorm_embedding = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
|
| 754 |
+
|
| 755 |
+
def __call__(
|
| 756 |
+
self,
|
| 757 |
+
input_ids,
|
| 758 |
+
attention_mask,
|
| 759 |
+
position_ids,
|
| 760 |
+
encoder_hidden_states: Optional[jnp.ndarray] = None,
|
| 761 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 762 |
+
init_cache: bool = False,
|
| 763 |
+
output_attentions: bool = False,
|
| 764 |
+
output_hidden_states: bool = False,
|
| 765 |
+
return_dict: bool = True,
|
| 766 |
+
deterministic: bool = True,
|
| 767 |
+
):
|
| 768 |
+
input_shape = input_ids.shape
|
| 769 |
+
input_ids = input_ids.reshape(-1, input_shape[-1])
|
| 770 |
+
|
| 771 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 772 |
+
|
| 773 |
+
# embed positions
|
| 774 |
+
positions = self.embed_positions(position_ids)
|
| 775 |
+
|
| 776 |
+
# BlenderbotSmall applies layer norm on inputs_embeds in decoder
|
| 777 |
+
inputs_embeds = self.layernorm_embedding(inputs_embeds)
|
| 778 |
+
hidden_states = inputs_embeds + positions
|
| 779 |
+
|
| 780 |
+
hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 781 |
+
|
| 782 |
+
outputs = self.layers(
|
| 783 |
+
hidden_states,
|
| 784 |
+
attention_mask,
|
| 785 |
+
encoder_hidden_states,
|
| 786 |
+
encoder_attention_mask,
|
| 787 |
+
deterministic=deterministic,
|
| 788 |
+
init_cache=init_cache,
|
| 789 |
+
output_attentions=output_attentions,
|
| 790 |
+
output_hidden_states=output_hidden_states,
|
| 791 |
+
return_dict=return_dict,
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
if not return_dict:
|
| 795 |
+
return outputs
|
| 796 |
+
|
| 797 |
+
return FlaxBaseModelOutputWithPastAndCrossAttentions(
|
| 798 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 799 |
+
hidden_states=outputs.hidden_states,
|
| 800 |
+
attentions=outputs.attentions,
|
| 801 |
+
cross_attentions=outputs.cross_attentions,
|
| 802 |
+
)
|
| 803 |
+
|
| 804 |
+
|
| 805 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartModule with Bart->BlenderbotSmall
|
| 806 |
+
class FlaxBlenderbotSmallModule(nn.Module):
|
| 807 |
+
config: BlenderbotSmallConfig
|
| 808 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 809 |
+
|
| 810 |
+
def setup(self):
|
| 811 |
+
self.shared = nn.Embed(
|
| 812 |
+
self.config.vocab_size,
|
| 813 |
+
self.config.d_model,
|
| 814 |
+
embedding_init=jax.nn.initializers.normal(self.config.init_std),
|
| 815 |
+
dtype=self.dtype,
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
self.encoder = FlaxBlenderbotSmallEncoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
|
| 819 |
+
self.decoder = FlaxBlenderbotSmallDecoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
|
| 820 |
+
|
| 821 |
+
def _get_encoder_module(self):
|
| 822 |
+
return self.encoder
|
| 823 |
+
|
| 824 |
+
def _get_decoder_module(self):
|
| 825 |
+
return self.decoder
|
| 826 |
+
|
| 827 |
+
def __call__(
|
| 828 |
+
self,
|
| 829 |
+
input_ids,
|
| 830 |
+
attention_mask,
|
| 831 |
+
decoder_input_ids,
|
| 832 |
+
decoder_attention_mask,
|
| 833 |
+
position_ids,
|
| 834 |
+
decoder_position_ids,
|
| 835 |
+
output_attentions: bool = False,
|
| 836 |
+
output_hidden_states: bool = False,
|
| 837 |
+
return_dict: bool = True,
|
| 838 |
+
deterministic: bool = True,
|
| 839 |
+
):
|
| 840 |
+
encoder_outputs = self.encoder(
|
| 841 |
+
input_ids=input_ids,
|
| 842 |
+
attention_mask=attention_mask,
|
| 843 |
+
position_ids=position_ids,
|
| 844 |
+
output_attentions=output_attentions,
|
| 845 |
+
output_hidden_states=output_hidden_states,
|
| 846 |
+
return_dict=return_dict,
|
| 847 |
+
deterministic=deterministic,
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
decoder_outputs = self.decoder(
|
| 851 |
+
input_ids=decoder_input_ids,
|
| 852 |
+
attention_mask=decoder_attention_mask,
|
| 853 |
+
position_ids=decoder_position_ids,
|
| 854 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 855 |
+
encoder_attention_mask=attention_mask,
|
| 856 |
+
output_attentions=output_attentions,
|
| 857 |
+
output_hidden_states=output_hidden_states,
|
| 858 |
+
return_dict=return_dict,
|
| 859 |
+
deterministic=deterministic,
|
| 860 |
+
)
|
| 861 |
+
|
| 862 |
+
if not return_dict:
|
| 863 |
+
return decoder_outputs + encoder_outputs
|
| 864 |
+
|
| 865 |
+
return FlaxSeq2SeqModelOutput(
|
| 866 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 867 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 868 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 869 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 870 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 871 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 872 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 873 |
+
)
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
class FlaxBlenderbotSmallPreTrainedModel(FlaxPreTrainedModel):
|
| 877 |
+
config_class = BlenderbotSmallConfig
|
| 878 |
+
base_model_prefix: str = "model"
|
| 879 |
+
module_class: nn.Module = None
|
| 880 |
+
|
| 881 |
+
def __init__(
|
| 882 |
+
self,
|
| 883 |
+
config: BlenderbotSmallConfig,
|
| 884 |
+
input_shape: Tuple[int] = (1, 1),
|
| 885 |
+
seed: int = 0,
|
| 886 |
+
dtype: jnp.dtype = jnp.float32,
|
| 887 |
+
_do_init: bool = True,
|
| 888 |
+
**kwargs,
|
| 889 |
+
):
|
| 890 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
| 891 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
| 892 |
+
|
| 893 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
|
| 894 |
+
# init input tensors
|
| 895 |
+
input_ids = jnp.zeros(input_shape, dtype="i4")
|
| 896 |
+
# make sure initialization pass will work for FlaxBlenderbotSmallForSequenceClassificationModule
|
| 897 |
+
input_ids = input_ids.at[(..., -1)].set(self.config.eos_token_id)
|
| 898 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 899 |
+
decoder_input_ids = input_ids
|
| 900 |
+
decoder_attention_mask = jnp.ones_like(input_ids)
|
| 901 |
+
|
| 902 |
+
batch_size, sequence_length = input_ids.shape
|
| 903 |
+
position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
|
| 904 |
+
decoder_position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
|
| 905 |
+
|
| 906 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
| 907 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
| 908 |
+
|
| 909 |
+
random_params = self.module.init(
|
| 910 |
+
rngs,
|
| 911 |
+
input_ids,
|
| 912 |
+
attention_mask,
|
| 913 |
+
decoder_input_ids,
|
| 914 |
+
decoder_attention_mask,
|
| 915 |
+
position_ids,
|
| 916 |
+
decoder_position_ids,
|
| 917 |
+
)["params"]
|
| 918 |
+
|
| 919 |
+
if params is not None:
|
| 920 |
+
random_params = flatten_dict(unfreeze(random_params))
|
| 921 |
+
params = flatten_dict(unfreeze(params))
|
| 922 |
+
for missing_key in self._missing_keys:
|
| 923 |
+
params[missing_key] = random_params[missing_key]
|
| 924 |
+
self._missing_keys = set()
|
| 925 |
+
return freeze(unflatten_dict(params))
|
| 926 |
+
else:
|
| 927 |
+
return random_params
|
| 928 |
+
|
| 929 |
+
def init_cache(self, batch_size, max_length, encoder_outputs):
|
| 930 |
+
r"""
|
| 931 |
+
Args:
|
| 932 |
+
batch_size (`int`):
|
| 933 |
+
batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
|
| 934 |
+
max_length (`int`):
|
| 935 |
+
maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
|
| 936 |
+
cache.
|
| 937 |
+
encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`):
|
| 938 |
+
`encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:
|
| 939 |
+
`attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*)
|
| 940 |
+
is a sequence of hidden-states at the output of the last layer of the encoder. Used in the
|
| 941 |
+
cross-attention of the decoder.
|
| 942 |
+
"""
|
| 943 |
+
# init input variables to retrieve cache
|
| 944 |
+
decoder_input_ids = jnp.ones((batch_size, max_length), dtype="i4")
|
| 945 |
+
decoder_attention_mask = jnp.ones_like(decoder_input_ids)
|
| 946 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 947 |
+
jnp.arange(jnp.atleast_2d(decoder_input_ids).shape[-1]), decoder_input_ids.shape
|
| 948 |
+
)
|
| 949 |
+
|
| 950 |
+
def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
|
| 951 |
+
decoder_module = module._get_decoder_module()
|
| 952 |
+
return decoder_module(
|
| 953 |
+
decoder_input_ids,
|
| 954 |
+
decoder_attention_mask,
|
| 955 |
+
decoder_position_ids,
|
| 956 |
+
**kwargs,
|
| 957 |
+
)
|
| 958 |
+
|
| 959 |
+
init_variables = self.module.init(
|
| 960 |
+
jax.random.PRNGKey(0),
|
| 961 |
+
decoder_input_ids=decoder_input_ids,
|
| 962 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 963 |
+
decoder_position_ids=decoder_position_ids,
|
| 964 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 965 |
+
init_cache=True,
|
| 966 |
+
method=_decoder_forward, # we only need to call the decoder to init the cache
|
| 967 |
+
)
|
| 968 |
+
return unfreeze(init_variables["cache"])
|
| 969 |
+
|
| 970 |
+
@add_start_docstrings(BLENDERBOT_SMALL_ENCODE_INPUTS_DOCSTRING)
|
| 971 |
+
@replace_return_docstrings(output_type=FlaxBaseModelOutput, config_class=BlenderbotSmallConfig)
|
| 972 |
+
def encode(
|
| 973 |
+
self,
|
| 974 |
+
input_ids: jnp.ndarray,
|
| 975 |
+
attention_mask: Optional[jnp.ndarray] = None,
|
| 976 |
+
position_ids: Optional[jnp.ndarray] = None,
|
| 977 |
+
output_attentions: Optional[bool] = None,
|
| 978 |
+
output_hidden_states: Optional[bool] = None,
|
| 979 |
+
return_dict: Optional[bool] = None,
|
| 980 |
+
train: bool = False,
|
| 981 |
+
params: dict = None,
|
| 982 |
+
dropout_rng: PRNGKey = None,
|
| 983 |
+
):
|
| 984 |
+
r"""
|
| 985 |
+
Returns:
|
| 986 |
+
|
| 987 |
+
Example:
|
| 988 |
+
|
| 989 |
+
```python
|
| 990 |
+
>>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
|
| 991 |
+
|
| 992 |
+
>>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
|
| 993 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
|
| 994 |
+
|
| 995 |
+
>>> text = "My friends are cool but they eat too many carbs."
|
| 996 |
+
>>> inputs = tokenizer(text, max_length=1024, return_tensors="np")
|
| 997 |
+
>>> encoder_outputs = model.encode(**inputs)
|
| 998 |
+
```"""
|
| 999 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1000 |
+
output_hidden_states = (
|
| 1001 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1002 |
+
)
|
| 1003 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1004 |
+
|
| 1005 |
+
if attention_mask is None:
|
| 1006 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 1007 |
+
if position_ids is None:
|
| 1008 |
+
batch_size, sequence_length = input_ids.shape
|
| 1009 |
+
position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
|
| 1010 |
+
|
| 1011 |
+
# Handle any PRNG if needed
|
| 1012 |
+
rngs = {}
|
| 1013 |
+
if dropout_rng is not None:
|
| 1014 |
+
rngs["dropout"] = dropout_rng
|
| 1015 |
+
|
| 1016 |
+
def _encoder_forward(module, input_ids, attention_mask, position_ids, **kwargs):
|
| 1017 |
+
encode_module = module._get_encoder_module()
|
| 1018 |
+
return encode_module(input_ids, attention_mask, position_ids, **kwargs)
|
| 1019 |
+
|
| 1020 |
+
return self.module.apply(
|
| 1021 |
+
{"params": params or self.params},
|
| 1022 |
+
input_ids=jnp.array(input_ids, dtype="i4"),
|
| 1023 |
+
attention_mask=jnp.array(attention_mask, dtype="i4"),
|
| 1024 |
+
position_ids=jnp.array(position_ids, dtype="i4"),
|
| 1025 |
+
output_attentions=output_attentions,
|
| 1026 |
+
output_hidden_states=output_hidden_states,
|
| 1027 |
+
return_dict=return_dict,
|
| 1028 |
+
deterministic=not train,
|
| 1029 |
+
rngs=rngs,
|
| 1030 |
+
method=_encoder_forward,
|
| 1031 |
+
)
|
| 1032 |
+
|
| 1033 |
+
@add_start_docstrings(BLENDERBOT_SMALL_DECODE_INPUTS_DOCSTRING)
|
| 1034 |
+
@replace_return_docstrings(
|
| 1035 |
+
output_type=FlaxBaseModelOutputWithPastAndCrossAttentions, config_class=BlenderbotSmallConfig
|
| 1036 |
+
)
|
| 1037 |
+
def decode(
|
| 1038 |
+
self,
|
| 1039 |
+
decoder_input_ids,
|
| 1040 |
+
encoder_outputs,
|
| 1041 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 1042 |
+
decoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 1043 |
+
decoder_position_ids: Optional[jnp.ndarray] = None,
|
| 1044 |
+
past_key_values: dict = None,
|
| 1045 |
+
output_attentions: Optional[bool] = None,
|
| 1046 |
+
output_hidden_states: Optional[bool] = None,
|
| 1047 |
+
return_dict: Optional[bool] = None,
|
| 1048 |
+
train: bool = False,
|
| 1049 |
+
params: dict = None,
|
| 1050 |
+
dropout_rng: PRNGKey = None,
|
| 1051 |
+
):
|
| 1052 |
+
r"""
|
| 1053 |
+
Returns:
|
| 1054 |
+
|
| 1055 |
+
Example:
|
| 1056 |
+
|
| 1057 |
+
```python
|
| 1058 |
+
>>> import jax.numpy as jnp
|
| 1059 |
+
>>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
|
| 1060 |
+
|
| 1061 |
+
>>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
|
| 1062 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
|
| 1063 |
+
|
| 1064 |
+
>>> text = "My friends are cool but they eat too many carbs."
|
| 1065 |
+
>>> inputs = tokenizer(text, max_length=1024, return_tensors="np")
|
| 1066 |
+
>>> encoder_outputs = model.encode(**inputs)
|
| 1067 |
+
|
| 1068 |
+
>>> decoder_start_token_id = model.config.decoder_start_token_id
|
| 1069 |
+
>>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
|
| 1070 |
+
|
| 1071 |
+
>>> outputs = model.decode(decoder_input_ids, encoder_outputs)
|
| 1072 |
+
>>> last_decoder_hidden_states = outputs.last_hidden_state
|
| 1073 |
+
```"""
|
| 1074 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1075 |
+
output_hidden_states = (
|
| 1076 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1077 |
+
)
|
| 1078 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1079 |
+
|
| 1080 |
+
encoder_hidden_states = encoder_outputs[0]
|
| 1081 |
+
if encoder_attention_mask is None:
|
| 1082 |
+
batch_size, sequence_length = encoder_hidden_states.shape[:2]
|
| 1083 |
+
encoder_attention_mask = jnp.ones((batch_size, sequence_length))
|
| 1084 |
+
|
| 1085 |
+
batch_size, sequence_length = decoder_input_ids.shape
|
| 1086 |
+
if decoder_attention_mask is None:
|
| 1087 |
+
decoder_attention_mask = jnp.ones((batch_size, sequence_length))
|
| 1088 |
+
|
| 1089 |
+
if decoder_position_ids is None:
|
| 1090 |
+
if past_key_values is not None:
|
| 1091 |
+
raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
|
| 1092 |
+
|
| 1093 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 1094 |
+
jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
|
| 1095 |
+
)
|
| 1096 |
+
|
| 1097 |
+
# Handle any PRNG if needed
|
| 1098 |
+
rngs = {}
|
| 1099 |
+
if dropout_rng is not None:
|
| 1100 |
+
rngs["dropout"] = dropout_rng
|
| 1101 |
+
|
| 1102 |
+
inputs = {"params": params or self.params}
|
| 1103 |
+
|
| 1104 |
+
# if past_key_values are passed then cache is already initialized a private flag init_cache has to be
|
| 1105 |
+
# passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
|
| 1106 |
+
# it can be changed by FlaxBlenderbotSmallAttention module
|
| 1107 |
+
if past_key_values:
|
| 1108 |
+
inputs["cache"] = past_key_values
|
| 1109 |
+
mutable = ["cache"]
|
| 1110 |
+
else:
|
| 1111 |
+
mutable = False
|
| 1112 |
+
|
| 1113 |
+
def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
|
| 1114 |
+
decoder_module = module._get_decoder_module()
|
| 1115 |
+
return decoder_module(
|
| 1116 |
+
decoder_input_ids,
|
| 1117 |
+
decoder_attention_mask,
|
| 1118 |
+
decoder_position_ids,
|
| 1119 |
+
**kwargs,
|
| 1120 |
+
)
|
| 1121 |
+
|
| 1122 |
+
outputs = self.module.apply(
|
| 1123 |
+
inputs,
|
| 1124 |
+
decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
|
| 1125 |
+
decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
|
| 1126 |
+
decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
|
| 1127 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1128 |
+
encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
|
| 1129 |
+
output_attentions=output_attentions,
|
| 1130 |
+
output_hidden_states=output_hidden_states,
|
| 1131 |
+
return_dict=return_dict,
|
| 1132 |
+
deterministic=not train,
|
| 1133 |
+
rngs=rngs,
|
| 1134 |
+
mutable=mutable,
|
| 1135 |
+
method=_decoder_forward,
|
| 1136 |
+
)
|
| 1137 |
+
|
| 1138 |
+
# add updated cache to model output
|
| 1139 |
+
if past_key_values is not None and return_dict:
|
| 1140 |
+
outputs, past = outputs
|
| 1141 |
+
outputs["past_key_values"] = unfreeze(past["cache"])
|
| 1142 |
+
return outputs
|
| 1143 |
+
elif past_key_values is not None and not return_dict:
|
| 1144 |
+
outputs, past = outputs
|
| 1145 |
+
outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
|
| 1146 |
+
|
| 1147 |
+
return outputs
|
| 1148 |
+
|
| 1149 |
+
def __call__(
|
| 1150 |
+
self,
|
| 1151 |
+
input_ids: jnp.ndarray,
|
| 1152 |
+
attention_mask: Optional[jnp.ndarray] = None,
|
| 1153 |
+
decoder_input_ids: Optional[jnp.ndarray] = None,
|
| 1154 |
+
decoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 1155 |
+
position_ids: Optional[jnp.ndarray] = None,
|
| 1156 |
+
decoder_position_ids: Optional[jnp.ndarray] = None,
|
| 1157 |
+
output_attentions: Optional[bool] = None,
|
| 1158 |
+
output_hidden_states: Optional[bool] = None,
|
| 1159 |
+
return_dict: Optional[bool] = None,
|
| 1160 |
+
train: bool = False,
|
| 1161 |
+
params: dict = None,
|
| 1162 |
+
dropout_rng: PRNGKey = None,
|
| 1163 |
+
):
|
| 1164 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1165 |
+
output_hidden_states = (
|
| 1166 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1167 |
+
)
|
| 1168 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1169 |
+
|
| 1170 |
+
# prepare encoder inputs
|
| 1171 |
+
if attention_mask is None:
|
| 1172 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 1173 |
+
if position_ids is None:
|
| 1174 |
+
batch_size, sequence_length = input_ids.shape
|
| 1175 |
+
position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
|
| 1176 |
+
|
| 1177 |
+
# prepare decoder inputs
|
| 1178 |
+
if decoder_input_ids is None:
|
| 1179 |
+
decoder_input_ids = shift_tokens_right(
|
| 1180 |
+
input_ids, self.config.pad_token_id, decoder_start_token_id=self.config.decoder_start_token_id
|
| 1181 |
+
)
|
| 1182 |
+
if decoder_attention_mask is None:
|
| 1183 |
+
decoder_attention_mask = jnp.ones_like(decoder_input_ids)
|
| 1184 |
+
if decoder_position_ids is None:
|
| 1185 |
+
batch_size, sequence_length = decoder_input_ids.shape
|
| 1186 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 1187 |
+
jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
|
| 1188 |
+
)
|
| 1189 |
+
|
| 1190 |
+
# Handle any PRNG if needed
|
| 1191 |
+
rngs = {"dropout": dropout_rng} if dropout_rng is not None else {}
|
| 1192 |
+
|
| 1193 |
+
return self.module.apply(
|
| 1194 |
+
{"params": params or self.params},
|
| 1195 |
+
input_ids=jnp.array(input_ids, dtype="i4"),
|
| 1196 |
+
attention_mask=jnp.array(attention_mask, dtype="i4"),
|
| 1197 |
+
position_ids=jnp.array(position_ids, dtype="i4"),
|
| 1198 |
+
decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
|
| 1199 |
+
decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
|
| 1200 |
+
decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
|
| 1201 |
+
output_attentions=output_attentions,
|
| 1202 |
+
output_hidden_states=output_hidden_states,
|
| 1203 |
+
return_dict=return_dict,
|
| 1204 |
+
deterministic=not train,
|
| 1205 |
+
rngs=rngs,
|
| 1206 |
+
)
|
| 1207 |
+
|
| 1208 |
+
|
| 1209 |
+
@add_start_docstrings(
|
| 1210 |
+
"The bare BlenderbotSmall Model transformer outputting raw hidden-states without any specific head on top.",
|
| 1211 |
+
BLENDERBOT_SMALL_START_DOCSTRING,
|
| 1212 |
+
)
|
| 1213 |
+
class FlaxBlenderbotSmallModel(FlaxBlenderbotSmallPreTrainedModel):
|
| 1214 |
+
config: BlenderbotSmallConfig
|
| 1215 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 1216 |
+
module_class = FlaxBlenderbotSmallModule
|
| 1217 |
+
|
| 1218 |
+
|
| 1219 |
+
append_call_sample_docstring(FlaxBlenderbotSmallModel, _CHECKPOINT_FOR_DOC, FlaxSeq2SeqModelOutput, _CONFIG_FOR_DOC)
|
| 1220 |
+
|
| 1221 |
+
|
| 1222 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartForConditionalGenerationModule with Bart->BlenderbotSmall
|
| 1223 |
+
class FlaxBlenderbotSmallForConditionalGenerationModule(nn.Module):
|
| 1224 |
+
config: BlenderbotSmallConfig
|
| 1225 |
+
dtype: jnp.dtype = jnp.float32
|
| 1226 |
+
bias_init: Callable[..., jnp.ndarray] = jax.nn.initializers.zeros
|
| 1227 |
+
|
| 1228 |
+
def setup(self):
|
| 1229 |
+
self.model = FlaxBlenderbotSmallModule(config=self.config, dtype=self.dtype)
|
| 1230 |
+
self.lm_head = nn.Dense(
|
| 1231 |
+
self.model.shared.num_embeddings,
|
| 1232 |
+
use_bias=False,
|
| 1233 |
+
dtype=self.dtype,
|
| 1234 |
+
kernel_init=jax.nn.initializers.normal(self.config.init_std),
|
| 1235 |
+
)
|
| 1236 |
+
self.final_logits_bias = self.param("final_logits_bias", self.bias_init, (1, self.model.shared.num_embeddings))
|
| 1237 |
+
|
| 1238 |
+
def _get_encoder_module(self):
|
| 1239 |
+
return self.model.encoder
|
| 1240 |
+
|
| 1241 |
+
def _get_decoder_module(self):
|
| 1242 |
+
return self.model.decoder
|
| 1243 |
+
|
| 1244 |
+
def __call__(
|
| 1245 |
+
self,
|
| 1246 |
+
input_ids,
|
| 1247 |
+
attention_mask,
|
| 1248 |
+
decoder_input_ids,
|
| 1249 |
+
decoder_attention_mask,
|
| 1250 |
+
position_ids,
|
| 1251 |
+
decoder_position_ids,
|
| 1252 |
+
output_attentions: bool = False,
|
| 1253 |
+
output_hidden_states: bool = False,
|
| 1254 |
+
return_dict: bool = True,
|
| 1255 |
+
deterministic: bool = True,
|
| 1256 |
+
):
|
| 1257 |
+
outputs = self.model(
|
| 1258 |
+
input_ids=input_ids,
|
| 1259 |
+
attention_mask=attention_mask,
|
| 1260 |
+
decoder_input_ids=decoder_input_ids,
|
| 1261 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1262 |
+
position_ids=position_ids,
|
| 1263 |
+
decoder_position_ids=decoder_position_ids,
|
| 1264 |
+
output_attentions=output_attentions,
|
| 1265 |
+
output_hidden_states=output_hidden_states,
|
| 1266 |
+
return_dict=return_dict,
|
| 1267 |
+
deterministic=deterministic,
|
| 1268 |
+
)
|
| 1269 |
+
|
| 1270 |
+
hidden_states = outputs[0]
|
| 1271 |
+
|
| 1272 |
+
if self.config.tie_word_embeddings:
|
| 1273 |
+
shared_embedding = self.model.variables["params"]["shared"]["embedding"]
|
| 1274 |
+
lm_logits = self.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
|
| 1275 |
+
else:
|
| 1276 |
+
lm_logits = self.lm_head(hidden_states)
|
| 1277 |
+
|
| 1278 |
+
lm_logits += jax.lax.stop_gradient(self.final_logits_bias.astype(self.dtype))
|
| 1279 |
+
|
| 1280 |
+
if not return_dict:
|
| 1281 |
+
output = (lm_logits,) + outputs[1:]
|
| 1282 |
+
return output
|
| 1283 |
+
|
| 1284 |
+
return FlaxSeq2SeqLMOutput(
|
| 1285 |
+
logits=lm_logits,
|
| 1286 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1287 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1288 |
+
cross_attentions=outputs.cross_attentions,
|
| 1289 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1290 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1291 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1292 |
+
)
|
| 1293 |
+
|
| 1294 |
+
|
| 1295 |
+
@add_start_docstrings(
|
| 1296 |
+
"The BLENDERBOT_SMALL Model with a language modeling head. Can be used for summarization.",
|
| 1297 |
+
BLENDERBOT_SMALL_START_DOCSTRING,
|
| 1298 |
+
)
|
| 1299 |
+
class FlaxBlenderbotSmallForConditionalGeneration(FlaxBlenderbotSmallPreTrainedModel):
|
| 1300 |
+
module_class = FlaxBlenderbotSmallForConditionalGenerationModule
|
| 1301 |
+
dtype: jnp.dtype = jnp.float32
|
| 1302 |
+
|
| 1303 |
+
@add_start_docstrings(BLENDERBOT_SMALL_DECODE_INPUTS_DOCSTRING)
|
| 1304 |
+
@replace_return_docstrings(output_type=FlaxCausalLMOutputWithCrossAttentions, config_class=BlenderbotSmallConfig)
|
| 1305 |
+
def decode(
|
| 1306 |
+
self,
|
| 1307 |
+
decoder_input_ids,
|
| 1308 |
+
encoder_outputs,
|
| 1309 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 1310 |
+
decoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 1311 |
+
decoder_position_ids: Optional[jnp.ndarray] = None,
|
| 1312 |
+
past_key_values: dict = None,
|
| 1313 |
+
output_attentions: Optional[bool] = None,
|
| 1314 |
+
output_hidden_states: Optional[bool] = None,
|
| 1315 |
+
return_dict: Optional[bool] = None,
|
| 1316 |
+
deterministic: bool = True,
|
| 1317 |
+
params: dict = None,
|
| 1318 |
+
dropout_rng: PRNGKey = None,
|
| 1319 |
+
):
|
| 1320 |
+
r"""
|
| 1321 |
+
Returns:
|
| 1322 |
+
|
| 1323 |
+
Example:
|
| 1324 |
+
|
| 1325 |
+
```python
|
| 1326 |
+
>>> import jax.numpy as jnp
|
| 1327 |
+
>>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
|
| 1328 |
+
|
| 1329 |
+
>>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
|
| 1330 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
|
| 1331 |
+
|
| 1332 |
+
>>> text = "My friends are cool but they eat too many carbs."
|
| 1333 |
+
>>> inputs = tokenizer(text, max_length=1024, return_tensors="np")
|
| 1334 |
+
>>> encoder_outputs = model.encode(**inputs)
|
| 1335 |
+
|
| 1336 |
+
>>> decoder_start_token_id = model.config.decoder_start_token_id
|
| 1337 |
+
>>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
|
| 1338 |
+
|
| 1339 |
+
>>> outputs = model.decode(decoder_input_ids, encoder_outputs)
|
| 1340 |
+
>>> logits = outputs.logits
|
| 1341 |
+
```"""
|
| 1342 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1343 |
+
output_hidden_states = (
|
| 1344 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1345 |
+
)
|
| 1346 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1347 |
+
|
| 1348 |
+
encoder_hidden_states = encoder_outputs[0]
|
| 1349 |
+
if encoder_attention_mask is None:
|
| 1350 |
+
batch_size, sequence_length = encoder_hidden_states.shape[:2]
|
| 1351 |
+
encoder_attention_mask = jnp.ones((batch_size, sequence_length))
|
| 1352 |
+
|
| 1353 |
+
batch_size, sequence_length = decoder_input_ids.shape
|
| 1354 |
+
if decoder_attention_mask is None:
|
| 1355 |
+
decoder_attention_mask = jnp.ones((batch_size, sequence_length))
|
| 1356 |
+
|
| 1357 |
+
if decoder_position_ids is None:
|
| 1358 |
+
if past_key_values is not None:
|
| 1359 |
+
raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
|
| 1360 |
+
|
| 1361 |
+
decoder_position_ids = jnp.broadcast_to(
|
| 1362 |
+
jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
|
| 1363 |
+
)
|
| 1364 |
+
|
| 1365 |
+
# Handle any PRNG if needed
|
| 1366 |
+
rngs = {}
|
| 1367 |
+
if dropout_rng is not None:
|
| 1368 |
+
rngs["dropout"] = dropout_rng
|
| 1369 |
+
|
| 1370 |
+
inputs = {"params": params or self.params}
|
| 1371 |
+
|
| 1372 |
+
# if past_key_values are passed then cache is already initialized a private flag init_cache has to be
|
| 1373 |
+
# passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
|
| 1374 |
+
# it can be changed by FlaxBlenderbotSmallAttention module
|
| 1375 |
+
if past_key_values:
|
| 1376 |
+
inputs["cache"] = past_key_values
|
| 1377 |
+
mutable = ["cache"]
|
| 1378 |
+
else:
|
| 1379 |
+
mutable = False
|
| 1380 |
+
|
| 1381 |
+
def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
|
| 1382 |
+
decoder_module = module._get_decoder_module()
|
| 1383 |
+
outputs = decoder_module(
|
| 1384 |
+
decoder_input_ids,
|
| 1385 |
+
decoder_attention_mask,
|
| 1386 |
+
decoder_position_ids,
|
| 1387 |
+
**kwargs,
|
| 1388 |
+
)
|
| 1389 |
+
hidden_states = outputs[0]
|
| 1390 |
+
|
| 1391 |
+
if self.config.tie_word_embeddings:
|
| 1392 |
+
shared_embedding = module.model.variables["params"]["shared"]["embedding"]
|
| 1393 |
+
lm_logits = module.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
|
| 1394 |
+
else:
|
| 1395 |
+
lm_logits = module.lm_head(hidden_states)
|
| 1396 |
+
|
| 1397 |
+
lm_logits += module.final_logits_bias.astype(self.dtype)
|
| 1398 |
+
return lm_logits, outputs
|
| 1399 |
+
|
| 1400 |
+
outputs = self.module.apply(
|
| 1401 |
+
inputs,
|
| 1402 |
+
decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
|
| 1403 |
+
decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
|
| 1404 |
+
decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
|
| 1405 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1406 |
+
encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
|
| 1407 |
+
output_attentions=output_attentions,
|
| 1408 |
+
output_hidden_states=output_hidden_states,
|
| 1409 |
+
return_dict=return_dict,
|
| 1410 |
+
deterministic=deterministic,
|
| 1411 |
+
rngs=rngs,
|
| 1412 |
+
mutable=mutable,
|
| 1413 |
+
method=_decoder_forward,
|
| 1414 |
+
)
|
| 1415 |
+
|
| 1416 |
+
if past_key_values is None:
|
| 1417 |
+
lm_logits, decoder_outputs = outputs
|
| 1418 |
+
else:
|
| 1419 |
+
(lm_logits, decoder_outputs), past = outputs
|
| 1420 |
+
|
| 1421 |
+
if return_dict:
|
| 1422 |
+
outputs = FlaxCausalLMOutputWithCrossAttentions(
|
| 1423 |
+
logits=lm_logits,
|
| 1424 |
+
hidden_states=decoder_outputs.hidden_states,
|
| 1425 |
+
attentions=decoder_outputs.attentions,
|
| 1426 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1427 |
+
)
|
| 1428 |
+
else:
|
| 1429 |
+
outputs = (lm_logits,) + decoder_outputs[1:]
|
| 1430 |
+
|
| 1431 |
+
# add updated cache to model output
|
| 1432 |
+
if past_key_values is not None and return_dict:
|
| 1433 |
+
outputs["past_key_values"] = unfreeze(past["cache"])
|
| 1434 |
+
return outputs
|
| 1435 |
+
elif past_key_values is not None and not return_dict:
|
| 1436 |
+
outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
|
| 1437 |
+
|
| 1438 |
+
return outputs
|
| 1439 |
+
|
| 1440 |
+
def prepare_inputs_for_generation(
|
| 1441 |
+
self,
|
| 1442 |
+
decoder_input_ids,
|
| 1443 |
+
max_length,
|
| 1444 |
+
attention_mask: Optional[jax.Array] = None,
|
| 1445 |
+
decoder_attention_mask: Optional[jax.Array] = None,
|
| 1446 |
+
encoder_outputs=None,
|
| 1447 |
+
**kwargs,
|
| 1448 |
+
):
|
| 1449 |
+
# initializing the cache
|
| 1450 |
+
batch_size, seq_length = decoder_input_ids.shape
|
| 1451 |
+
|
| 1452 |
+
past_key_values = self.init_cache(batch_size, max_length, encoder_outputs)
|
| 1453 |
+
# Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
|
| 1454 |
+
# But since the decoder uses a causal mask, those positions are masked anyways.
|
| 1455 |
+
# Thus we can create a single static attention_mask here, which is more efficient for compilation
|
| 1456 |
+
extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
|
| 1457 |
+
if decoder_attention_mask is not None:
|
| 1458 |
+
position_ids = decoder_attention_mask.cumsum(axis=-1) - 1
|
| 1459 |
+
extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, decoder_attention_mask, (0, 0))
|
| 1460 |
+
else:
|
| 1461 |
+
position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
|
| 1462 |
+
|
| 1463 |
+
return {
|
| 1464 |
+
"past_key_values": past_key_values,
|
| 1465 |
+
"encoder_outputs": encoder_outputs,
|
| 1466 |
+
"encoder_attention_mask": attention_mask,
|
| 1467 |
+
"decoder_attention_mask": extended_attention_mask,
|
| 1468 |
+
"decoder_position_ids": position_ids,
|
| 1469 |
+
}
|
| 1470 |
+
|
| 1471 |
+
def update_inputs_for_generation(self, model_outputs, model_kwargs):
|
| 1472 |
+
model_kwargs["past_key_values"] = model_outputs.past_key_values
|
| 1473 |
+
model_kwargs["decoder_position_ids"] = model_kwargs["decoder_position_ids"][:, -1:] + 1
|
| 1474 |
+
return model_kwargs
|
| 1475 |
+
|
| 1476 |
+
|
| 1477 |
+
FLAX_BLENDERBOT_SMALL_CONDITIONAL_GENERATION_DOCSTRING = """
|
| 1478 |
+
Returns:
|
| 1479 |
+
|
| 1480 |
+
Summarization example:
|
| 1481 |
+
|
| 1482 |
+
```py
|
| 1483 |
+
>>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
|
| 1484 |
+
|
| 1485 |
+
>>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
|
| 1486 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
|
| 1487 |
+
|
| 1488 |
+
>>> ARTICLE_TO_SUMMARIZE = "My friends are cool but they eat too many carbs."
|
| 1489 |
+
>>> inputs = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors="np")
|
| 1490 |
+
|
| 1491 |
+
>>> # Generate Summary
|
| 1492 |
+
>>> summary_ids = model.generate(inputs["input_ids"]).sequences
|
| 1493 |
+
>>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False))
|
| 1494 |
+
```
|
| 1495 |
+
|
| 1496 |
+
Mask filling example:
|
| 1497 |
+
|
| 1498 |
+
```py
|
| 1499 |
+
>>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
|
| 1500 |
+
|
| 1501 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
|
| 1502 |
+
>>> TXT = "My friends are <mask> but they eat too many carbs."
|
| 1503 |
+
|
| 1504 |
+
>>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
|
| 1505 |
+
>>> input_ids = tokenizer([TXT], return_tensors="np")["input_ids"]
|
| 1506 |
+
>>> logits = model(input_ids).logits
|
| 1507 |
+
|
| 1508 |
+
>>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item()
|
| 1509 |
+
>>> probs = jax.nn.softmax(logits[0, masked_index], axis=0)
|
| 1510 |
+
>>> values, predictions = jax.lax.top_k(probs)
|
| 1511 |
+
|
| 1512 |
+
>>> tokenizer.decode(predictions).split()
|
| 1513 |
+
```
|
| 1514 |
+
"""
|
| 1515 |
+
|
| 1516 |
+
overwrite_call_docstring(
|
| 1517 |
+
FlaxBlenderbotSmallForConditionalGeneration,
|
| 1518 |
+
BLENDERBOT_SMALL_INPUTS_DOCSTRING + FLAX_BLENDERBOT_SMALL_CONDITIONAL_GENERATION_DOCSTRING,
|
| 1519 |
+
)
|
| 1520 |
+
append_replace_return_docstrings(
|
| 1521 |
+
FlaxBlenderbotSmallForConditionalGeneration, output_type=FlaxSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC
|
| 1522 |
+
)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py
ADDED
|
@@ -0,0 +1,1529 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Facebook, Inc and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" TF 2.0 BlenderbotSmall model."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import random
|
| 21 |
+
from typing import List, Optional, Tuple, Union
|
| 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 |
+
TFBaseModelOutput,
|
| 29 |
+
TFBaseModelOutputWithPastAndCrossAttentions,
|
| 30 |
+
TFSeq2SeqLMOutput,
|
| 31 |
+
TFSeq2SeqModelOutput,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# Public API
|
| 35 |
+
from ...modeling_tf_utils import (
|
| 36 |
+
TFCausalLanguageModelingLoss,
|
| 37 |
+
TFPreTrainedModel,
|
| 38 |
+
keras_serializable,
|
| 39 |
+
unpack_inputs,
|
| 40 |
+
)
|
| 41 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
| 42 |
+
from ...utils import (
|
| 43 |
+
add_code_sample_docstrings,
|
| 44 |
+
add_end_docstrings,
|
| 45 |
+
add_start_docstrings,
|
| 46 |
+
add_start_docstrings_to_model_forward,
|
| 47 |
+
logging,
|
| 48 |
+
replace_return_docstrings,
|
| 49 |
+
)
|
| 50 |
+
from .configuration_blenderbot_small import BlenderbotSmallConfig
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
logger = logging.get_logger(__name__)
|
| 54 |
+
|
| 55 |
+
_CHECKPOINT_FOR_DOC = "facebook/blenderbot_small-90M"
|
| 56 |
+
_CONFIG_FOR_DOC = "BlenderbotSmallConfig"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
LARGE_NEGATIVE = -1e8
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right
|
| 63 |
+
def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 64 |
+
pad_token_id = tf.cast(pad_token_id, input_ids.dtype)
|
| 65 |
+
decoder_start_token_id = tf.cast(decoder_start_token_id, input_ids.dtype)
|
| 66 |
+
start_tokens = tf.fill(
|
| 67 |
+
(shape_list(input_ids)[0], 1), tf.convert_to_tensor(decoder_start_token_id, input_ids.dtype)
|
| 68 |
+
)
|
| 69 |
+
shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
|
| 70 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 71 |
+
shifted_input_ids = tf.where(
|
| 72 |
+
shifted_input_ids == -100,
|
| 73 |
+
tf.fill(shape_list(shifted_input_ids), tf.convert_to_tensor(pad_token_id, input_ids.dtype)),
|
| 74 |
+
shifted_input_ids,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# "Verify that `labels` has only positive values and -100"
|
| 78 |
+
assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=input_ids.dtype))
|
| 79 |
+
|
| 80 |
+
# Make sure the assertion op is called by wrapping the result in an identity no-op
|
| 81 |
+
with tf.control_dependencies([assert_gte0]):
|
| 82 |
+
shifted_input_ids = tf.identity(shifted_input_ids)
|
| 83 |
+
|
| 84 |
+
return shifted_input_ids
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# Copied from transformers.models.bart.modeling_tf_bart._make_causal_mask
|
| 88 |
+
def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0):
|
| 89 |
+
"""
|
| 90 |
+
Make causal mask used for bi-directional self-attention.
|
| 91 |
+
"""
|
| 92 |
+
bsz = input_ids_shape[0]
|
| 93 |
+
tgt_len = input_ids_shape[1]
|
| 94 |
+
mask = tf.ones((tgt_len, tgt_len)) * LARGE_NEGATIVE
|
| 95 |
+
mask_cond = tf.range(shape_list(mask)[-1])
|
| 96 |
+
|
| 97 |
+
mask = tf.where(mask_cond < tf.reshape(mask_cond + 1, (shape_list(mask)[-1], 1)), 0.0, mask)
|
| 98 |
+
|
| 99 |
+
if past_key_values_length > 0:
|
| 100 |
+
mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1)
|
| 101 |
+
|
| 102 |
+
return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# Copied from transformers.models.bart.modeling_tf_bart._expand_mask
|
| 106 |
+
def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None):
|
| 107 |
+
"""
|
| 108 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
| 109 |
+
"""
|
| 110 |
+
src_len = shape_list(mask)[1]
|
| 111 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
| 112 |
+
one_cst = tf.constant(1.0)
|
| 113 |
+
mask = tf.cast(mask, dtype=one_cst.dtype)
|
| 114 |
+
expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))
|
| 115 |
+
|
| 116 |
+
return (one_cst - expanded_mask) * LARGE_NEGATIVE
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# Copied from transformers.models.blenderbot.modeling_tf_blenderbot.TFBlenderbotLearnedPositionalEmbedding with Blenderbot->BlenderbotSmall
|
| 120 |
+
class TFBlenderbotSmallLearnedPositionalEmbedding(tf.keras.layers.Embedding):
|
| 121 |
+
"""
|
| 122 |
+
This module learns positional embeddings up to a fixed maximum size.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
def __init__(self, num_embeddings: int, embedding_dim: int, **kwargs):
|
| 126 |
+
super().__init__(num_embeddings, embedding_dim, **kwargs)
|
| 127 |
+
|
| 128 |
+
def call(
|
| 129 |
+
self, input_shape: tf.TensorShape, past_key_values_length: int = 0, position_ids: tf.Tensor | None = None
|
| 130 |
+
):
|
| 131 |
+
"""Input is expected to be of size [bsz x seqlen]."""
|
| 132 |
+
if position_ids is None:
|
| 133 |
+
seq_len = input_shape[1]
|
| 134 |
+
position_ids = tf.range(seq_len, delta=1, name="range")
|
| 135 |
+
position_ids += past_key_values_length
|
| 136 |
+
|
| 137 |
+
return super().call(tf.cast(position_ids, dtype=tf.int32))
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with Bart->BlenderbotSmall
|
| 141 |
+
class TFBlenderbotSmallAttention(tf.keras.layers.Layer):
|
| 142 |
+
"""Multi-headed attention from "Attention Is All You Need"""
|
| 143 |
+
|
| 144 |
+
def __init__(
|
| 145 |
+
self,
|
| 146 |
+
embed_dim: int,
|
| 147 |
+
num_heads: int,
|
| 148 |
+
dropout: float = 0.0,
|
| 149 |
+
is_decoder: bool = False,
|
| 150 |
+
bias: bool = True,
|
| 151 |
+
**kwargs,
|
| 152 |
+
):
|
| 153 |
+
super().__init__(**kwargs)
|
| 154 |
+
self.embed_dim = embed_dim
|
| 155 |
+
|
| 156 |
+
self.num_heads = num_heads
|
| 157 |
+
self.dropout = tf.keras.layers.Dropout(dropout)
|
| 158 |
+
self.head_dim = embed_dim // num_heads
|
| 159 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 160 |
+
raise ValueError(
|
| 161 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 162 |
+
f" and `num_heads`: {num_heads})."
|
| 163 |
+
)
|
| 164 |
+
self.scaling = self.head_dim**-0.5
|
| 165 |
+
self.is_decoder = is_decoder
|
| 166 |
+
|
| 167 |
+
self.k_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj")
|
| 168 |
+
self.q_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj")
|
| 169 |
+
self.v_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj")
|
| 170 |
+
self.out_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj")
|
| 171 |
+
|
| 172 |
+
def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int):
|
| 173 |
+
return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3))
|
| 174 |
+
|
| 175 |
+
def call(
|
| 176 |
+
self,
|
| 177 |
+
hidden_states: tf.Tensor,
|
| 178 |
+
key_value_states: tf.Tensor | None = None,
|
| 179 |
+
past_key_value: Tuple[Tuple[tf.Tensor]] | None = None,
|
| 180 |
+
attention_mask: tf.Tensor | None = None,
|
| 181 |
+
layer_head_mask: tf.Tensor | None = None,
|
| 182 |
+
training: Optional[bool] = False,
|
| 183 |
+
) -> Tuple[tf.Tensor, tf.Tensor | None]:
|
| 184 |
+
"""Input shape: Batch x Time x Channel"""
|
| 185 |
+
|
| 186 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 187 |
+
# for the decoder
|
| 188 |
+
is_cross_attention = key_value_states is not None
|
| 189 |
+
bsz, tgt_len, embed_dim = shape_list(hidden_states)
|
| 190 |
+
|
| 191 |
+
# get query proj
|
| 192 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 193 |
+
# get key, value proj
|
| 194 |
+
if is_cross_attention and past_key_value is not None:
|
| 195 |
+
# reuse k,v, cross_attentions
|
| 196 |
+
key_states = past_key_value[0]
|
| 197 |
+
value_states = past_key_value[1]
|
| 198 |
+
elif is_cross_attention:
|
| 199 |
+
# cross_attentions
|
| 200 |
+
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
|
| 201 |
+
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
|
| 202 |
+
elif past_key_value is not None:
|
| 203 |
+
# reuse k, v, self_attention
|
| 204 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 205 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 206 |
+
key_states = tf.concat([past_key_value[0], key_states], axis=2)
|
| 207 |
+
value_states = tf.concat([past_key_value[1], value_states], axis=2)
|
| 208 |
+
else:
|
| 209 |
+
# self_attention
|
| 210 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 211 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 212 |
+
|
| 213 |
+
if self.is_decoder:
|
| 214 |
+
# if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
|
| 215 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 216 |
+
# key/value_states (first "if" case)
|
| 217 |
+
# if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
|
| 218 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 219 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 220 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 221 |
+
past_key_value = (key_states, value_states)
|
| 222 |
+
|
| 223 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 224 |
+
query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape)
|
| 225 |
+
key_states = tf.reshape(key_states, proj_shape)
|
| 226 |
+
value_states = tf.reshape(value_states, proj_shape)
|
| 227 |
+
|
| 228 |
+
src_len = shape_list(key_states)[1]
|
| 229 |
+
attn_weights = tf.matmul(query_states, key_states, transpose_b=True)
|
| 230 |
+
|
| 231 |
+
tf.debugging.assert_equal(
|
| 232 |
+
shape_list(attn_weights),
|
| 233 |
+
[bsz * self.num_heads, tgt_len, src_len],
|
| 234 |
+
message=(
|
| 235 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 236 |
+
f" {shape_list(attn_weights)}"
|
| 237 |
+
),
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
if attention_mask is not None:
|
| 241 |
+
tf.debugging.assert_equal(
|
| 242 |
+
shape_list(attention_mask),
|
| 243 |
+
[bsz, 1, tgt_len, src_len],
|
| 244 |
+
message=(
|
| 245 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
| 246 |
+
f" {shape_list(attention_mask)}"
|
| 247 |
+
),
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype)
|
| 251 |
+
attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask
|
| 252 |
+
attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
|
| 253 |
+
|
| 254 |
+
attn_weights = stable_softmax(attn_weights, axis=-1)
|
| 255 |
+
|
| 256 |
+
if layer_head_mask is not None:
|
| 257 |
+
tf.debugging.assert_equal(
|
| 258 |
+
shape_list(layer_head_mask),
|
| 259 |
+
[self.num_heads],
|
| 260 |
+
message=(
|
| 261 |
+
f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
|
| 262 |
+
f" {shape_list(layer_head_mask)}"
|
| 263 |
+
),
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(
|
| 267 |
+
attn_weights, (bsz, self.num_heads, tgt_len, src_len)
|
| 268 |
+
)
|
| 269 |
+
attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
|
| 270 |
+
|
| 271 |
+
attn_probs = self.dropout(attn_weights, training=training)
|
| 272 |
+
attn_output = tf.matmul(attn_probs, value_states)
|
| 273 |
+
|
| 274 |
+
tf.debugging.assert_equal(
|
| 275 |
+
shape_list(attn_output),
|
| 276 |
+
[bsz * self.num_heads, tgt_len, self.head_dim],
|
| 277 |
+
message=(
|
| 278 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 279 |
+
f" {shape_list(attn_output)}"
|
| 280 |
+
),
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
attn_output = tf.transpose(
|
| 284 |
+
tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3)
|
| 285 |
+
)
|
| 286 |
+
attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim))
|
| 287 |
+
|
| 288 |
+
attn_output = self.out_proj(attn_output)
|
| 289 |
+
attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len))
|
| 290 |
+
|
| 291 |
+
return attn_output, attn_weights, past_key_value
|
| 292 |
+
|
| 293 |
+
def build(self, input_shape=None):
|
| 294 |
+
if self.built:
|
| 295 |
+
return
|
| 296 |
+
self.built = True
|
| 297 |
+
if getattr(self, "k_proj", None) is not None:
|
| 298 |
+
with tf.name_scope(self.k_proj.name):
|
| 299 |
+
self.k_proj.build([None, None, self.embed_dim])
|
| 300 |
+
if getattr(self, "q_proj", None) is not None:
|
| 301 |
+
with tf.name_scope(self.q_proj.name):
|
| 302 |
+
self.q_proj.build([None, None, self.embed_dim])
|
| 303 |
+
if getattr(self, "v_proj", None) is not None:
|
| 304 |
+
with tf.name_scope(self.v_proj.name):
|
| 305 |
+
self.v_proj.build([None, None, self.embed_dim])
|
| 306 |
+
if getattr(self, "out_proj", None) is not None:
|
| 307 |
+
with tf.name_scope(self.out_proj.name):
|
| 308 |
+
self.out_proj.build([None, None, self.embed_dim])
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
# Copied from transformers.models.bart.modeling_tf_bart.TFBartEncoderLayer with Bart->BlenderbotSmall
|
| 312 |
+
class TFBlenderbotSmallEncoderLayer(tf.keras.layers.Layer):
|
| 313 |
+
def __init__(self, config: BlenderbotSmallConfig, **kwargs):
|
| 314 |
+
super().__init__(**kwargs)
|
| 315 |
+
self.embed_dim = config.d_model
|
| 316 |
+
self.self_attn = TFBlenderbotSmallAttention(
|
| 317 |
+
self.embed_dim, config.encoder_attention_heads, dropout=config.attention_dropout, name="self_attn"
|
| 318 |
+
)
|
| 319 |
+
self.self_attn_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
|
| 320 |
+
self.dropout = tf.keras.layers.Dropout(config.dropout)
|
| 321 |
+
self.activation_fn = get_tf_activation(config.activation_function)
|
| 322 |
+
self.activation_dropout = tf.keras.layers.Dropout(config.activation_dropout)
|
| 323 |
+
self.fc1 = tf.keras.layers.Dense(config.encoder_ffn_dim, name="fc1")
|
| 324 |
+
self.fc2 = tf.keras.layers.Dense(self.embed_dim, name="fc2")
|
| 325 |
+
self.final_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
|
| 326 |
+
self.config = config
|
| 327 |
+
|
| 328 |
+
def call(
|
| 329 |
+
self,
|
| 330 |
+
hidden_states: tf.Tensor,
|
| 331 |
+
attention_mask: np.ndarray | tf.Tensor | None,
|
| 332 |
+
layer_head_mask: tf.Tensor | None,
|
| 333 |
+
training: Optional[bool] = False,
|
| 334 |
+
) -> tf.Tensor:
|
| 335 |
+
"""
|
| 336 |
+
Args:
|
| 337 |
+
hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 338 |
+
attention_mask (`tf.Tensor`): attention mask of size
|
| 339 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 340 |
+
layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
|
| 341 |
+
`(encoder_attention_heads,)`
|
| 342 |
+
"""
|
| 343 |
+
residual = hidden_states
|
| 344 |
+
hidden_states, self_attn_weights, _ = self.self_attn(
|
| 345 |
+
hidden_states=hidden_states, attention_mask=attention_mask, layer_head_mask=layer_head_mask
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
tf.debugging.assert_equal(
|
| 349 |
+
shape_list(hidden_states),
|
| 350 |
+
shape_list(residual),
|
| 351 |
+
message=f"Self attn modified the shape of query {shape_list(residual)} to {shape_list(hidden_states)}",
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 355 |
+
hidden_states = residual + hidden_states
|
| 356 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 357 |
+
|
| 358 |
+
residual = hidden_states
|
| 359 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 360 |
+
hidden_states = self.activation_dropout(hidden_states, training=training)
|
| 361 |
+
hidden_states = self.fc2(hidden_states)
|
| 362 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 363 |
+
hidden_states = residual + hidden_states
|
| 364 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 365 |
+
|
| 366 |
+
return hidden_states, self_attn_weights
|
| 367 |
+
|
| 368 |
+
def build(self, input_shape=None):
|
| 369 |
+
if self.built:
|
| 370 |
+
return
|
| 371 |
+
self.built = True
|
| 372 |
+
if getattr(self, "self_attn", None) is not None:
|
| 373 |
+
with tf.name_scope(self.self_attn.name):
|
| 374 |
+
self.self_attn.build(None)
|
| 375 |
+
if getattr(self, "self_attn_layer_norm", None) is not None:
|
| 376 |
+
with tf.name_scope(self.self_attn_layer_norm.name):
|
| 377 |
+
self.self_attn_layer_norm.build([None, None, self.embed_dim])
|
| 378 |
+
if getattr(self, "fc1", None) is not None:
|
| 379 |
+
with tf.name_scope(self.fc1.name):
|
| 380 |
+
self.fc1.build([None, None, self.embed_dim])
|
| 381 |
+
if getattr(self, "fc2", None) is not None:
|
| 382 |
+
with tf.name_scope(self.fc2.name):
|
| 383 |
+
self.fc2.build([None, None, self.config.encoder_ffn_dim])
|
| 384 |
+
if getattr(self, "final_layer_norm", None) is not None:
|
| 385 |
+
with tf.name_scope(self.final_layer_norm.name):
|
| 386 |
+
self.final_layer_norm.build([None, None, self.embed_dim])
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
# Copied from transformers.models.bart.modeling_tf_bart.TFBartDecoderLayer with Bart->BlenderbotSmall
|
| 390 |
+
class TFBlenderbotSmallDecoderLayer(tf.keras.layers.Layer):
|
| 391 |
+
def __init__(self, config: BlenderbotSmallConfig, **kwargs):
|
| 392 |
+
super().__init__(**kwargs)
|
| 393 |
+
self.embed_dim = config.d_model
|
| 394 |
+
self.self_attn = TFBlenderbotSmallAttention(
|
| 395 |
+
embed_dim=self.embed_dim,
|
| 396 |
+
num_heads=config.decoder_attention_heads,
|
| 397 |
+
dropout=config.attention_dropout,
|
| 398 |
+
name="self_attn",
|
| 399 |
+
is_decoder=True,
|
| 400 |
+
)
|
| 401 |
+
self.dropout = tf.keras.layers.Dropout(config.dropout)
|
| 402 |
+
self.activation_fn = get_tf_activation(config.activation_function)
|
| 403 |
+
self.activation_dropout = tf.keras.layers.Dropout(config.activation_dropout)
|
| 404 |
+
|
| 405 |
+
self.self_attn_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
|
| 406 |
+
self.encoder_attn = TFBlenderbotSmallAttention(
|
| 407 |
+
self.embed_dim,
|
| 408 |
+
config.decoder_attention_heads,
|
| 409 |
+
dropout=config.attention_dropout,
|
| 410 |
+
name="encoder_attn",
|
| 411 |
+
is_decoder=True,
|
| 412 |
+
)
|
| 413 |
+
self.encoder_attn_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="encoder_attn_layer_norm")
|
| 414 |
+
self.fc1 = tf.keras.layers.Dense(config.decoder_ffn_dim, name="fc1")
|
| 415 |
+
self.fc2 = tf.keras.layers.Dense(self.embed_dim, name="fc2")
|
| 416 |
+
self.final_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
|
| 417 |
+
self.config = config
|
| 418 |
+
|
| 419 |
+
def call(
|
| 420 |
+
self,
|
| 421 |
+
hidden_states: tf.Tensor,
|
| 422 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 423 |
+
encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
|
| 424 |
+
encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 425 |
+
layer_head_mask: tf.Tensor | None = None,
|
| 426 |
+
cross_attn_layer_head_mask: tf.Tensor | None = None,
|
| 427 |
+
past_key_value: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
|
| 428 |
+
training: Optional[bool] = False,
|
| 429 |
+
) -> Tuple[tf.Tensor, tf.Tensor, Tuple[Tuple[tf.Tensor]]]:
|
| 430 |
+
"""
|
| 431 |
+
Args:
|
| 432 |
+
hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 433 |
+
attention_mask (`tf.Tensor`): attention mask of size
|
| 434 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 435 |
+
encoder_hidden_states (`tf.Tensor`):
|
| 436 |
+
cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 437 |
+
encoder_attention_mask (`tf.Tensor`): encoder attention mask of size
|
| 438 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 439 |
+
layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
|
| 440 |
+
`(decoder_attention_heads,)`
|
| 441 |
+
cross_attn_layer_head_mask (`tf.Tensor`): mask for heads of the cross-attention module.
|
| 442 |
+
`(decoder_attention_heads,)`
|
| 443 |
+
past_key_value (`Tuple(tf.Tensor)`): cached past key and value projection states
|
| 444 |
+
"""
|
| 445 |
+
residual = hidden_states
|
| 446 |
+
|
| 447 |
+
# Self Attention
|
| 448 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 449 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 450 |
+
# add present self-attn cache to positions 1,2 of present_key_value tuple
|
| 451 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 452 |
+
hidden_states=hidden_states,
|
| 453 |
+
past_key_value=self_attn_past_key_value,
|
| 454 |
+
attention_mask=attention_mask,
|
| 455 |
+
layer_head_mask=layer_head_mask,
|
| 456 |
+
)
|
| 457 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 458 |
+
hidden_states = residual + hidden_states
|
| 459 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 460 |
+
|
| 461 |
+
# Cross-Attention Block
|
| 462 |
+
cross_attn_present_key_value = None
|
| 463 |
+
cross_attn_weights = None
|
| 464 |
+
if encoder_hidden_states is not None:
|
| 465 |
+
residual = hidden_states
|
| 466 |
+
|
| 467 |
+
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
|
| 468 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 469 |
+
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
|
| 470 |
+
hidden_states=hidden_states,
|
| 471 |
+
key_value_states=encoder_hidden_states,
|
| 472 |
+
attention_mask=encoder_attention_mask,
|
| 473 |
+
layer_head_mask=cross_attn_layer_head_mask,
|
| 474 |
+
past_key_value=cross_attn_past_key_value,
|
| 475 |
+
)
|
| 476 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 477 |
+
hidden_states = residual + hidden_states
|
| 478 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 479 |
+
|
| 480 |
+
# add cross-attn to positions 3,4 of present_key_value tuple
|
| 481 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 482 |
+
|
| 483 |
+
# Fully Connected
|
| 484 |
+
residual = hidden_states
|
| 485 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 486 |
+
hidden_states = self.activation_dropout(hidden_states, training=training)
|
| 487 |
+
hidden_states = self.fc2(hidden_states)
|
| 488 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 489 |
+
hidden_states = residual + hidden_states
|
| 490 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 491 |
+
|
| 492 |
+
return (
|
| 493 |
+
hidden_states,
|
| 494 |
+
self_attn_weights,
|
| 495 |
+
cross_attn_weights,
|
| 496 |
+
present_key_value,
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
def build(self, input_shape=None):
|
| 500 |
+
if self.built:
|
| 501 |
+
return
|
| 502 |
+
self.built = True
|
| 503 |
+
if getattr(self, "self_attn", None) is not None:
|
| 504 |
+
with tf.name_scope(self.self_attn.name):
|
| 505 |
+
self.self_attn.build(None)
|
| 506 |
+
if getattr(self, "self_attn_layer_norm", None) is not None:
|
| 507 |
+
with tf.name_scope(self.self_attn_layer_norm.name):
|
| 508 |
+
self.self_attn_layer_norm.build([None, None, self.embed_dim])
|
| 509 |
+
if getattr(self, "encoder_attn", None) is not None:
|
| 510 |
+
with tf.name_scope(self.encoder_attn.name):
|
| 511 |
+
self.encoder_attn.build(None)
|
| 512 |
+
if getattr(self, "encoder_attn_layer_norm", None) is not None:
|
| 513 |
+
with tf.name_scope(self.encoder_attn_layer_norm.name):
|
| 514 |
+
self.encoder_attn_layer_norm.build([None, None, self.embed_dim])
|
| 515 |
+
if getattr(self, "fc1", None) is not None:
|
| 516 |
+
with tf.name_scope(self.fc1.name):
|
| 517 |
+
self.fc1.build([None, None, self.embed_dim])
|
| 518 |
+
if getattr(self, "fc2", None) is not None:
|
| 519 |
+
with tf.name_scope(self.fc2.name):
|
| 520 |
+
self.fc2.build([None, None, self.config.decoder_ffn_dim])
|
| 521 |
+
if getattr(self, "final_layer_norm", None) is not None:
|
| 522 |
+
with tf.name_scope(self.final_layer_norm.name):
|
| 523 |
+
self.final_layer_norm.build([None, None, self.embed_dim])
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
class TFBlenderbotSmallPreTrainedModel(TFPreTrainedModel):
|
| 527 |
+
config_class = BlenderbotSmallConfig
|
| 528 |
+
base_model_prefix = "model"
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
BLENDERBOT_SMALL_START_DOCSTRING = r"""
|
| 532 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 533 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 534 |
+
etc.)
|
| 535 |
+
|
| 536 |
+
This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 537 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 538 |
+
behavior.
|
| 539 |
+
|
| 540 |
+
<Tip>
|
| 541 |
+
|
| 542 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 543 |
+
|
| 544 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 545 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 546 |
+
|
| 547 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 548 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 549 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 550 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 551 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 552 |
+
positional argument:
|
| 553 |
+
|
| 554 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 555 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 556 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 557 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 558 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 559 |
+
|
| 560 |
+
Note that when creating models and layers with
|
| 561 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 562 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 563 |
+
|
| 564 |
+
</Tip>
|
| 565 |
+
|
| 566 |
+
Args:
|
| 567 |
+
config ([`BlenderbotSmallConfig`]): Model configuration class with all the parameters of the model.
|
| 568 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 569 |
+
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 570 |
+
"""
|
| 571 |
+
|
| 572 |
+
BLENDERBOT_SMALL_GENERATION_EXAMPLE = r"""
|
| 573 |
+
Conversation example::
|
| 574 |
+
|
| 575 |
+
```py
|
| 576 |
+
>>> from transformers import AutoTokenizer, TFBlenderbotSmallForConditionalGeneration
|
| 577 |
+
|
| 578 |
+
>>> mname = "facebook/blenderbot_small-90M"
|
| 579 |
+
>>> model = BlenderbotSmallForConditionalGeneration.from_pretrained(mname)
|
| 580 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(mname)
|
| 581 |
+
|
| 582 |
+
>>> UTTERANCE = "My friends are cool but they eat too many carbs."
|
| 583 |
+
>>> print("Human: ", UTTERANCE)
|
| 584 |
+
>>> inputs = tokenizer([UTTERANCE], return_tensors="tf")
|
| 585 |
+
|
| 586 |
+
>>> reply_ids = model.generate(**inputs)
|
| 587 |
+
>>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
|
| 588 |
+
what kind of carbs do they eat? i don't know much about carbs.
|
| 589 |
+
|
| 590 |
+
>>> REPLY = "I'm not sure"
|
| 591 |
+
>>> print("Human: ", REPLY)
|
| 592 |
+
>>> NEXT_UTTERANCE = (
|
| 593 |
+
... "My friends are cool but they eat too many carbs.</s> "
|
| 594 |
+
... "<s>what kind of carbs do they eat? i don't know much about carbs.</s> "
|
| 595 |
+
... "<s>I'm not sure."
|
| 596 |
+
... )
|
| 597 |
+
|
| 598 |
+
>>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="tf")
|
| 599 |
+
>>> inputs.pop("token_type_ids")
|
| 600 |
+
>>> next_reply_ids = model.generate(**inputs)
|
| 601 |
+
>>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
|
| 602 |
+
```
|
| 603 |
+
"""
|
| 604 |
+
|
| 605 |
+
BLENDERBOT_SMALL_INPUTS_DOCSTRING = r"""
|
| 606 |
+
Args:
|
| 607 |
+
input_ids (`tf.Tensor` of shape `({0})`):
|
| 608 |
+
Indices of input sequence tokens in the vocabulary.
|
| 609 |
+
|
| 610 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 611 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 612 |
+
|
| 613 |
+
[What are input IDs?](../glossary#input-ids)
|
| 614 |
+
attention_mask (`tf.Tensor` of shape `({0})`, *optional*):
|
| 615 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 616 |
+
|
| 617 |
+
- 1 for tokens that are **not masked**,
|
| 618 |
+
- 0 for tokens that are **masked**.
|
| 619 |
+
|
| 620 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 621 |
+
decoder_input_ids (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 622 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 623 |
+
|
| 624 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 625 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 626 |
+
|
| 627 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 628 |
+
|
| 629 |
+
BlenderbotSmall uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 630 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 631 |
+
`past_key_values`).
|
| 632 |
+
decoder_attention_mask (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 633 |
+
will be made by default and ignore pad tokens. It is not recommended to set this for most use cases.
|
| 634 |
+
decoder_position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 635 |
+
Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
|
| 636 |
+
range `[0, config.max_position_embeddings - 1]`.
|
| 637 |
+
head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
|
| 638 |
+
Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
|
| 639 |
+
|
| 640 |
+
- 1 indicates the head is **not masked**,
|
| 641 |
+
- 0 indicates the head is **masked**.
|
| 642 |
+
|
| 643 |
+
decoder_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 644 |
+
Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
|
| 645 |
+
|
| 646 |
+
- 1 indicates the head is **not masked**,
|
| 647 |
+
- 0 indicates the head is **masked**.
|
| 648 |
+
|
| 649 |
+
cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 650 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 651 |
+
|
| 652 |
+
- 1 indicates the head is **not masked**,
|
| 653 |
+
- 0 indicates the head is **masked**.
|
| 654 |
+
|
| 655 |
+
encoder_outputs (`tf.FloatTensor`, *optional*):
|
| 656 |
+
hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
|
| 657 |
+
of shape `(batch_size, sequence_length, hidden_size)` is a sequence of
|
| 658 |
+
past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
|
| 659 |
+
contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 660 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 661 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 662 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 663 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 664 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 665 |
+
`past_key_values`). Set to `False` during training, `True` during generation
|
| 666 |
+
output_attentions (`bool`, *optional*):
|
| 667 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 668 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 669 |
+
config will be used instead.
|
| 670 |
+
output_hidden_states (`bool`, *optional*):
|
| 671 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 672 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 673 |
+
used instead.
|
| 674 |
+
return_dict (`bool`, *optional*):
|
| 675 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 676 |
+
eager mode, in graph mode the value will always be set to True.
|
| 677 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 678 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 679 |
+
behaviors between training and evaluation).
|
| 680 |
+
"""
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
@keras_serializable
|
| 684 |
+
class TFBlenderbotSmallEncoder(tf.keras.layers.Layer):
|
| 685 |
+
config_class = BlenderbotSmallConfig
|
| 686 |
+
"""
|
| 687 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 688 |
+
[`TFBlenderbotSmallEncoderLayer`].
|
| 689 |
+
|
| 690 |
+
Args:
|
| 691 |
+
config: BlenderbotSmallConfig
|
| 692 |
+
"""
|
| 693 |
+
|
| 694 |
+
def __init__(
|
| 695 |
+
self, config: BlenderbotSmallConfig, embed_tokens: Optional[tf.keras.layers.Embedding] = None, **kwargs
|
| 696 |
+
):
|
| 697 |
+
super().__init__(**kwargs)
|
| 698 |
+
self.config = config
|
| 699 |
+
self.dropout = tf.keras.layers.Dropout(config.dropout)
|
| 700 |
+
self.layerdrop = config.encoder_layerdrop
|
| 701 |
+
self.padding_idx = config.pad_token_id
|
| 702 |
+
self.max_source_positions = config.max_position_embeddings
|
| 703 |
+
self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
|
| 704 |
+
|
| 705 |
+
self.embed_tokens = embed_tokens
|
| 706 |
+
self.embed_positions = TFBlenderbotSmallLearnedPositionalEmbedding(
|
| 707 |
+
config.max_position_embeddings,
|
| 708 |
+
config.d_model,
|
| 709 |
+
name="embed_positions",
|
| 710 |
+
)
|
| 711 |
+
self.layers = [TFBlenderbotSmallEncoderLayer(config, name=f"layers.{i}") for i in range(config.encoder_layers)]
|
| 712 |
+
self.layernorm_embedding = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_embedding")
|
| 713 |
+
self.embed_dim = config.d_model
|
| 714 |
+
|
| 715 |
+
def get_embed_tokens(self):
|
| 716 |
+
return self.embed_tokens
|
| 717 |
+
|
| 718 |
+
def set_embed_tokens(self, embed_tokens):
|
| 719 |
+
self.embed_tokens = embed_tokens
|
| 720 |
+
|
| 721 |
+
@unpack_inputs
|
| 722 |
+
def call(
|
| 723 |
+
self,
|
| 724 |
+
input_ids=None,
|
| 725 |
+
inputs_embeds=None,
|
| 726 |
+
attention_mask=None,
|
| 727 |
+
head_mask=None,
|
| 728 |
+
output_attentions=None,
|
| 729 |
+
output_hidden_states=None,
|
| 730 |
+
return_dict=None,
|
| 731 |
+
training=False,
|
| 732 |
+
):
|
| 733 |
+
"""
|
| 734 |
+
Args:
|
| 735 |
+
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
|
| 736 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 737 |
+
provide it.
|
| 738 |
+
|
| 739 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 740 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 741 |
+
|
| 742 |
+
[What are input IDs?](../glossary#input-ids)
|
| 743 |
+
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 744 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 745 |
+
|
| 746 |
+
- 1 for tokens that are **not masked**,
|
| 747 |
+
- 0 for tokens that are **masked**.
|
| 748 |
+
|
| 749 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 750 |
+
head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, `optional):
|
| 751 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 752 |
+
|
| 753 |
+
- 1 indicates the head is **not masked**,
|
| 754 |
+
- 0 indicates the head is **masked**.
|
| 755 |
+
|
| 756 |
+
inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 757 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 758 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 759 |
+
than the model's internal embedding lookup matrix.
|
| 760 |
+
output_attentions (`bool`, *optional*):
|
| 761 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 762 |
+
returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value
|
| 763 |
+
in the config will be used instead.
|
| 764 |
+
output_hidden_states (`bool`, *optional*):
|
| 765 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 766 |
+
for more detail. This argument can be used only in eager mode, in graph mode the value in the config
|
| 767 |
+
will be used instead.
|
| 768 |
+
return_dict (`bool`, *optional*):
|
| 769 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used
|
| 770 |
+
in eager mode, in graph mode the value will always be set to True.
|
| 771 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 772 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 773 |
+
behaviors between training and evaluation).
|
| 774 |
+
"""
|
| 775 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 776 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 777 |
+
elif input_ids is not None:
|
| 778 |
+
input_shape = shape_list(input_ids)
|
| 779 |
+
elif inputs_embeds is not None:
|
| 780 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 781 |
+
else:
|
| 782 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 783 |
+
|
| 784 |
+
if inputs_embeds is None:
|
| 785 |
+
check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
|
| 786 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 787 |
+
|
| 788 |
+
embed_pos = self.embed_positions(input_shape)
|
| 789 |
+
hidden_states = inputs_embeds + embed_pos
|
| 790 |
+
hidden_states = self.layernorm_embedding(hidden_states)
|
| 791 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 792 |
+
|
| 793 |
+
# check attention mask and invert
|
| 794 |
+
if attention_mask is not None:
|
| 795 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 796 |
+
attention_mask = _expand_mask(attention_mask)
|
| 797 |
+
else:
|
| 798 |
+
attention_mask = None
|
| 799 |
+
|
| 800 |
+
encoder_states = () if output_hidden_states else None
|
| 801 |
+
all_attentions = () if output_attentions else None
|
| 802 |
+
|
| 803 |
+
# check if head_mask has a correct number of layers specified if desired
|
| 804 |
+
if head_mask is not None:
|
| 805 |
+
tf.debugging.assert_equal(
|
| 806 |
+
shape_list(head_mask)[0],
|
| 807 |
+
len(self.layers),
|
| 808 |
+
message=(
|
| 809 |
+
f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
|
| 810 |
+
f" {shape_list(head_mask)[0]}."
|
| 811 |
+
),
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
# encoder layers
|
| 815 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 816 |
+
if output_hidden_states:
|
| 817 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 818 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 819 |
+
dropout_probability = random.uniform(0, 1)
|
| 820 |
+
if training and (dropout_probability < self.layerdrop): # skip the layer
|
| 821 |
+
continue
|
| 822 |
+
|
| 823 |
+
hidden_states, attn = encoder_layer(
|
| 824 |
+
hidden_states,
|
| 825 |
+
attention_mask,
|
| 826 |
+
head_mask[idx] if head_mask is not None else None,
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
if output_attentions:
|
| 830 |
+
all_attentions += (attn,)
|
| 831 |
+
|
| 832 |
+
if output_hidden_states:
|
| 833 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 834 |
+
|
| 835 |
+
if not return_dict:
|
| 836 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 837 |
+
return TFBaseModelOutput(
|
| 838 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
+
def build(self, input_shape=None):
|
| 842 |
+
if self.built:
|
| 843 |
+
return
|
| 844 |
+
self.built = True
|
| 845 |
+
if getattr(self, "embed_positions", None) is not None:
|
| 846 |
+
with tf.name_scope(self.embed_positions.name):
|
| 847 |
+
self.embed_positions.build(None)
|
| 848 |
+
if getattr(self, "layernorm_embedding", None) is not None:
|
| 849 |
+
with tf.name_scope(self.layernorm_embedding.name):
|
| 850 |
+
self.layernorm_embedding.build([None, None, self.embed_dim])
|
| 851 |
+
if getattr(self, "layers", None) is not None:
|
| 852 |
+
for layer in self.layers:
|
| 853 |
+
with tf.name_scope(layer.name):
|
| 854 |
+
layer.build(None)
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
@keras_serializable
|
| 858 |
+
class TFBlenderbotSmallDecoder(tf.keras.layers.Layer):
|
| 859 |
+
config_class = BlenderbotSmallConfig
|
| 860 |
+
"""
|
| 861 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TFBlenderbotSmallDecoderLayer`]
|
| 862 |
+
|
| 863 |
+
Args:
|
| 864 |
+
config: BlenderbotSmallConfig
|
| 865 |
+
embed_tokens: output embedding
|
| 866 |
+
"""
|
| 867 |
+
|
| 868 |
+
def __init__(
|
| 869 |
+
self, config: BlenderbotSmallConfig, embed_tokens: Optional[tf.keras.layers.Embedding] = None, **kwargs
|
| 870 |
+
):
|
| 871 |
+
super().__init__(**kwargs)
|
| 872 |
+
self.config = config
|
| 873 |
+
self.padding_idx = config.pad_token_id
|
| 874 |
+
self.embed_tokens = embed_tokens
|
| 875 |
+
self.layerdrop = config.decoder_layerdrop
|
| 876 |
+
self.embed_positions = TFBlenderbotSmallLearnedPositionalEmbedding(
|
| 877 |
+
config.max_position_embeddings,
|
| 878 |
+
config.d_model,
|
| 879 |
+
name="embed_positions",
|
| 880 |
+
)
|
| 881 |
+
self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
|
| 882 |
+
self.layers = [TFBlenderbotSmallDecoderLayer(config, name=f"layers.{i}") for i in range(config.decoder_layers)]
|
| 883 |
+
self.layernorm_embedding = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_embedding")
|
| 884 |
+
|
| 885 |
+
self.dropout = tf.keras.layers.Dropout(config.dropout)
|
| 886 |
+
|
| 887 |
+
def get_embed_tokens(self):
|
| 888 |
+
return self.embed_tokens
|
| 889 |
+
|
| 890 |
+
def set_embed_tokens(self, embed_tokens):
|
| 891 |
+
self.embed_tokens = embed_tokens
|
| 892 |
+
|
| 893 |
+
@unpack_inputs
|
| 894 |
+
def call(
|
| 895 |
+
self,
|
| 896 |
+
input_ids=None,
|
| 897 |
+
inputs_embeds=None,
|
| 898 |
+
attention_mask=None,
|
| 899 |
+
position_ids=None,
|
| 900 |
+
encoder_hidden_states=None,
|
| 901 |
+
encoder_attention_mask=None,
|
| 902 |
+
head_mask=None,
|
| 903 |
+
cross_attn_head_mask=None,
|
| 904 |
+
past_key_values=None,
|
| 905 |
+
use_cache=None,
|
| 906 |
+
output_attentions=None,
|
| 907 |
+
output_hidden_states=None,
|
| 908 |
+
return_dict=None,
|
| 909 |
+
training=False,
|
| 910 |
+
):
|
| 911 |
+
r"""
|
| 912 |
+
Args:
|
| 913 |
+
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
|
| 914 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 915 |
+
provide it.
|
| 916 |
+
|
| 917 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 918 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 919 |
+
|
| 920 |
+
[What are input IDs?](../glossary#input-ids)
|
| 921 |
+
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 922 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 923 |
+
|
| 924 |
+
- 1 for tokens that are **not masked**,
|
| 925 |
+
- 0 for tokens that are **masked**.
|
| 926 |
+
|
| 927 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 928 |
+
position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 929 |
+
Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
|
| 930 |
+
range `[0, config.max_position_embeddings - 1]`.
|
| 931 |
+
encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 932 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 933 |
+
of the decoder.
|
| 934 |
+
encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 935 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 936 |
+
selected in `[0, 1]`:
|
| 937 |
+
|
| 938 |
+
- 1 for tokens that are **not masked**,
|
| 939 |
+
- 0 for tokens that are **masked**.
|
| 940 |
+
|
| 941 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 942 |
+
head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 943 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 944 |
+
|
| 945 |
+
- 1 indicates the head is **not masked**,
|
| 946 |
+
- 0 indicates the head is **masked**.
|
| 947 |
+
|
| 948 |
+
cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 949 |
+
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
|
| 950 |
+
|
| 951 |
+
- 1 indicates the head is **not masked**,
|
| 952 |
+
- 0 indicates the head is **masked**.
|
| 953 |
+
|
| 954 |
+
past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
| 955 |
+
Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up
|
| 956 |
+
decoding.
|
| 957 |
+
|
| 958 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 959 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 960 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 961 |
+
inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 962 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 963 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 964 |
+
than the model's internal embedding lookup matrix.
|
| 965 |
+
output_attentions (`bool`, *optional*):
|
| 966 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 967 |
+
returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value
|
| 968 |
+
in the config will be used instead.
|
| 969 |
+
output_hidden_states (`bool`, *optional*):
|
| 970 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 971 |
+
for more detail. This argument can be used only in eager mode, in graph mode the value in the config
|
| 972 |
+
will be used instead.
|
| 973 |
+
return_dict (`bool`, *optional*):
|
| 974 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used
|
| 975 |
+
in eager mode, in graph mode the value will always be set to True.
|
| 976 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 977 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 978 |
+
behaviors between training and evaluation).
|
| 979 |
+
"""
|
| 980 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 981 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 982 |
+
elif input_ids is not None:
|
| 983 |
+
input_shape = shape_list(input_ids)
|
| 984 |
+
elif inputs_embeds is not None:
|
| 985 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 986 |
+
else:
|
| 987 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 988 |
+
|
| 989 |
+
past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0
|
| 990 |
+
|
| 991 |
+
if inputs_embeds is None:
|
| 992 |
+
check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
|
| 993 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 994 |
+
|
| 995 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 996 |
+
if input_shape[-1] > 1:
|
| 997 |
+
combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length)
|
| 998 |
+
else:
|
| 999 |
+
combined_attention_mask = _expand_mask(
|
| 1000 |
+
tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1]
|
| 1001 |
+
)
|
| 1002 |
+
|
| 1003 |
+
if attention_mask is not None:
|
| 1004 |
+
combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1])
|
| 1005 |
+
|
| 1006 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 1007 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1008 |
+
encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1])
|
| 1009 |
+
|
| 1010 |
+
# embed positions
|
| 1011 |
+
if position_ids is None:
|
| 1012 |
+
positions = self.embed_positions(input_shape, past_key_values_length)
|
| 1013 |
+
else:
|
| 1014 |
+
positions = self.embed_positions(input_shape, position_ids=position_ids)
|
| 1015 |
+
|
| 1016 |
+
hidden_states = self.layernorm_embedding(inputs_embeds) + positions
|
| 1017 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
| 1018 |
+
|
| 1019 |
+
# decoder layers
|
| 1020 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1021 |
+
all_self_attns = () if output_attentions else None
|
| 1022 |
+
all_cross_attns = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 1023 |
+
present_key_values = () if use_cache else None
|
| 1024 |
+
|
| 1025 |
+
# check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired
|
| 1026 |
+
for attn_mask_name, attn_mask in [("head_mask", head_mask), ("cross_attn_head_mask", cross_attn_head_mask)]:
|
| 1027 |
+
if attn_mask is not None:
|
| 1028 |
+
tf.debugging.assert_equal(
|
| 1029 |
+
shape_list(attn_mask)[0],
|
| 1030 |
+
len(self.layers),
|
| 1031 |
+
message=(
|
| 1032 |
+
f"The {attn_mask_name} should be specified for {len(self.layers)} layers, but it is for"
|
| 1033 |
+
f" {shape_list(attn_mask)[0]}."
|
| 1034 |
+
),
|
| 1035 |
+
)
|
| 1036 |
+
|
| 1037 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 1038 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 1039 |
+
if output_hidden_states:
|
| 1040 |
+
all_hidden_states += (hidden_states,)
|
| 1041 |
+
dropout_probability = random.uniform(0, 1)
|
| 1042 |
+
|
| 1043 |
+
if training and (dropout_probability < self.layerdrop):
|
| 1044 |
+
continue
|
| 1045 |
+
|
| 1046 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 1047 |
+
|
| 1048 |
+
hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer(
|
| 1049 |
+
hidden_states,
|
| 1050 |
+
attention_mask=combined_attention_mask,
|
| 1051 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1052 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1053 |
+
layer_head_mask=head_mask[idx] if head_mask is not None else None,
|
| 1054 |
+
cross_attn_layer_head_mask=cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
|
| 1055 |
+
past_key_value=past_key_value,
|
| 1056 |
+
)
|
| 1057 |
+
|
| 1058 |
+
if use_cache:
|
| 1059 |
+
present_key_values += (present_key_value,)
|
| 1060 |
+
|
| 1061 |
+
if output_attentions:
|
| 1062 |
+
all_self_attns += (layer_self_attn,)
|
| 1063 |
+
|
| 1064 |
+
if encoder_hidden_states is not None:
|
| 1065 |
+
all_cross_attns += (layer_cross_attn,)
|
| 1066 |
+
|
| 1067 |
+
if output_hidden_states:
|
| 1068 |
+
all_hidden_states += (hidden_states,)
|
| 1069 |
+
|
| 1070 |
+
if not return_dict:
|
| 1071 |
+
return hidden_states, present_key_values, all_hidden_states, all_self_attns, all_cross_attns
|
| 1072 |
+
else:
|
| 1073 |
+
return TFBaseModelOutputWithPastAndCrossAttentions(
|
| 1074 |
+
last_hidden_state=hidden_states,
|
| 1075 |
+
past_key_values=present_key_values,
|
| 1076 |
+
hidden_states=all_hidden_states,
|
| 1077 |
+
attentions=all_self_attns,
|
| 1078 |
+
cross_attentions=all_cross_attns,
|
| 1079 |
+
)
|
| 1080 |
+
|
| 1081 |
+
def build(self, input_shape=None):
|
| 1082 |
+
if self.built:
|
| 1083 |
+
return
|
| 1084 |
+
self.built = True
|
| 1085 |
+
if getattr(self, "embed_positions", None) is not None:
|
| 1086 |
+
with tf.name_scope(self.embed_positions.name):
|
| 1087 |
+
self.embed_positions.build(None)
|
| 1088 |
+
if getattr(self, "layernorm_embedding", None) is not None:
|
| 1089 |
+
with tf.name_scope(self.layernorm_embedding.name):
|
| 1090 |
+
self.layernorm_embedding.build([None, None, self.config.d_model])
|
| 1091 |
+
if getattr(self, "layers", None) is not None:
|
| 1092 |
+
for layer in self.layers:
|
| 1093 |
+
with tf.name_scope(layer.name):
|
| 1094 |
+
layer.build(None)
|
| 1095 |
+
|
| 1096 |
+
|
| 1097 |
+
@keras_serializable
|
| 1098 |
+
class TFBlenderbotSmallMainLayer(tf.keras.layers.Layer):
|
| 1099 |
+
config_class = BlenderbotSmallConfig
|
| 1100 |
+
|
| 1101 |
+
def __init__(self, config: BlenderbotSmallConfig, **kwargs):
|
| 1102 |
+
super().__init__(**kwargs)
|
| 1103 |
+
|
| 1104 |
+
self.config = config
|
| 1105 |
+
self.shared = tf.keras.layers.Embedding(
|
| 1106 |
+
input_dim=config.vocab_size,
|
| 1107 |
+
output_dim=config.d_model,
|
| 1108 |
+
embeddings_initializer=tf.keras.initializers.TruncatedNormal(stddev=self.config.init_std),
|
| 1109 |
+
name="model.shared",
|
| 1110 |
+
)
|
| 1111 |
+
# Additional attribute to specify the expected name scope of the layer (for loading/storing weights)
|
| 1112 |
+
self.shared.load_weight_prefix = "model.shared"
|
| 1113 |
+
|
| 1114 |
+
self.encoder = TFBlenderbotSmallEncoder(config, self.shared, name="encoder")
|
| 1115 |
+
self.decoder = TFBlenderbotSmallDecoder(config, self.shared, name="decoder")
|
| 1116 |
+
|
| 1117 |
+
def get_input_embeddings(self):
|
| 1118 |
+
return self.shared
|
| 1119 |
+
|
| 1120 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1121 |
+
self.shared = new_embeddings
|
| 1122 |
+
self.encoder.embed_tokens = self.shared
|
| 1123 |
+
self.decoder.embed_tokens = self.shared
|
| 1124 |
+
|
| 1125 |
+
@unpack_inputs
|
| 1126 |
+
def call(
|
| 1127 |
+
self,
|
| 1128 |
+
input_ids=None,
|
| 1129 |
+
attention_mask=None,
|
| 1130 |
+
decoder_input_ids=None,
|
| 1131 |
+
decoder_attention_mask=None,
|
| 1132 |
+
decoder_position_ids=None,
|
| 1133 |
+
head_mask=None,
|
| 1134 |
+
decoder_head_mask=None,
|
| 1135 |
+
cross_attn_head_mask=None,
|
| 1136 |
+
encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
|
| 1137 |
+
past_key_values=None,
|
| 1138 |
+
inputs_embeds=None,
|
| 1139 |
+
decoder_inputs_embeds=None,
|
| 1140 |
+
use_cache=None,
|
| 1141 |
+
output_attentions=None,
|
| 1142 |
+
output_hidden_states=None,
|
| 1143 |
+
return_dict=None,
|
| 1144 |
+
training=False,
|
| 1145 |
+
**kwargs,
|
| 1146 |
+
):
|
| 1147 |
+
output_hidden_states = (
|
| 1148 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1149 |
+
)
|
| 1150 |
+
|
| 1151 |
+
if encoder_outputs is None:
|
| 1152 |
+
encoder_outputs = self.encoder(
|
| 1153 |
+
input_ids=input_ids,
|
| 1154 |
+
attention_mask=attention_mask,
|
| 1155 |
+
head_mask=head_mask,
|
| 1156 |
+
inputs_embeds=inputs_embeds,
|
| 1157 |
+
output_attentions=output_attentions,
|
| 1158 |
+
output_hidden_states=output_hidden_states,
|
| 1159 |
+
return_dict=return_dict,
|
| 1160 |
+
training=training,
|
| 1161 |
+
)
|
| 1162 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True
|
| 1163 |
+
elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):
|
| 1164 |
+
encoder_outputs = TFBaseModelOutput(
|
| 1165 |
+
last_hidden_state=encoder_outputs[0],
|
| 1166 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1167 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1168 |
+
)
|
| 1169 |
+
# If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False
|
| 1170 |
+
elif not return_dict and not isinstance(encoder_outputs, tuple):
|
| 1171 |
+
encoder_outputs = encoder_outputs.to_tuple()
|
| 1172 |
+
|
| 1173 |
+
decoder_outputs = self.decoder(
|
| 1174 |
+
decoder_input_ids,
|
| 1175 |
+
attention_mask=decoder_attention_mask,
|
| 1176 |
+
position_ids=decoder_position_ids,
|
| 1177 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1178 |
+
encoder_attention_mask=attention_mask,
|
| 1179 |
+
head_mask=decoder_head_mask,
|
| 1180 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1181 |
+
past_key_values=past_key_values,
|
| 1182 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1183 |
+
use_cache=use_cache,
|
| 1184 |
+
output_attentions=output_attentions,
|
| 1185 |
+
output_hidden_states=output_hidden_states,
|
| 1186 |
+
return_dict=return_dict,
|
| 1187 |
+
training=training,
|
| 1188 |
+
)
|
| 1189 |
+
|
| 1190 |
+
if not return_dict:
|
| 1191 |
+
return decoder_outputs + encoder_outputs
|
| 1192 |
+
|
| 1193 |
+
return TFSeq2SeqModelOutput(
|
| 1194 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1195 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1196 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1197 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1198 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1199 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1200 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1201 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1202 |
+
)
|
| 1203 |
+
|
| 1204 |
+
def build(self, input_shape=None):
|
| 1205 |
+
if self.built:
|
| 1206 |
+
return
|
| 1207 |
+
self.built = True
|
| 1208 |
+
# The shared/tied weights expect to be in the model base namespace
|
| 1209 |
+
# Adding "/" to the end (not the start!) of a tf.name_scope puts it in the root namespace rather than
|
| 1210 |
+
# the current one.
|
| 1211 |
+
with tf.name_scope(self.shared.load_weight_prefix + "/" + self.shared.name + "/"):
|
| 1212 |
+
self.shared.build(None)
|
| 1213 |
+
if getattr(self, "encoder", None) is not None:
|
| 1214 |
+
with tf.name_scope(self.encoder.name):
|
| 1215 |
+
self.encoder.build(None)
|
| 1216 |
+
if getattr(self, "decoder", None) is not None:
|
| 1217 |
+
with tf.name_scope(self.decoder.name):
|
| 1218 |
+
self.decoder.build(None)
|
| 1219 |
+
|
| 1220 |
+
|
| 1221 |
+
@add_start_docstrings(
|
| 1222 |
+
"The bare BLENDERBOT_SMALL Model outputting raw hidden-states without any specific head on top.",
|
| 1223 |
+
BLENDERBOT_SMALL_START_DOCSTRING,
|
| 1224 |
+
)
|
| 1225 |
+
class TFBlenderbotSmallModel(TFBlenderbotSmallPreTrainedModel):
|
| 1226 |
+
def __init__(self, config: BlenderbotSmallConfig, *inputs, **kwargs):
|
| 1227 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1228 |
+
|
| 1229 |
+
self.model = TFBlenderbotSmallMainLayer(config, name="model")
|
| 1230 |
+
|
| 1231 |
+
def get_encoder(self):
|
| 1232 |
+
return self.model.encoder
|
| 1233 |
+
|
| 1234 |
+
def get_decoder(self):
|
| 1235 |
+
return self.model.decoder
|
| 1236 |
+
|
| 1237 |
+
@unpack_inputs
|
| 1238 |
+
@add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1239 |
+
@add_code_sample_docstrings(
|
| 1240 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1241 |
+
output_type=TFSeq2SeqModelOutput,
|
| 1242 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1243 |
+
)
|
| 1244 |
+
def call(
|
| 1245 |
+
self,
|
| 1246 |
+
input_ids: tf.Tensor | None = None,
|
| 1247 |
+
attention_mask: tf.Tensor | None = None,
|
| 1248 |
+
decoder_input_ids: tf.Tensor | None = None,
|
| 1249 |
+
decoder_attention_mask: tf.Tensor | None = None,
|
| 1250 |
+
decoder_position_ids: tf.Tensor | None = None,
|
| 1251 |
+
head_mask: tf.Tensor | None = None,
|
| 1252 |
+
decoder_head_mask: tf.Tensor | None = None,
|
| 1253 |
+
cross_attn_head_mask: tf.Tensor | None = None,
|
| 1254 |
+
encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
|
| 1255 |
+
past_key_values: List[tf.Tensor] | None = None,
|
| 1256 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 1257 |
+
decoder_inputs_embeds: tf.Tensor | None = None,
|
| 1258 |
+
use_cache: Optional[bool] = None,
|
| 1259 |
+
output_attentions: Optional[bool] = None,
|
| 1260 |
+
output_hidden_states: Optional[bool] = None,
|
| 1261 |
+
return_dict: Optional[bool] = None,
|
| 1262 |
+
training: Optional[bool] = False,
|
| 1263 |
+
**kwargs,
|
| 1264 |
+
) -> Union[Tuple[tf.Tensor], TFSeq2SeqModelOutput]:
|
| 1265 |
+
outputs = self.model(
|
| 1266 |
+
input_ids=input_ids,
|
| 1267 |
+
attention_mask=attention_mask,
|
| 1268 |
+
decoder_input_ids=decoder_input_ids,
|
| 1269 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1270 |
+
decoder_position_ids=decoder_position_ids,
|
| 1271 |
+
head_mask=head_mask,
|
| 1272 |
+
decoder_head_mask=decoder_head_mask,
|
| 1273 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1274 |
+
encoder_outputs=encoder_outputs,
|
| 1275 |
+
past_key_values=past_key_values,
|
| 1276 |
+
inputs_embeds=inputs_embeds,
|
| 1277 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1278 |
+
use_cache=use_cache,
|
| 1279 |
+
output_attentions=output_attentions,
|
| 1280 |
+
output_hidden_states=output_hidden_states,
|
| 1281 |
+
return_dict=return_dict,
|
| 1282 |
+
training=training,
|
| 1283 |
+
)
|
| 1284 |
+
|
| 1285 |
+
return outputs
|
| 1286 |
+
|
| 1287 |
+
# Copied from transformers.models.bart.modeling_tf_bart.TFBartModel.serving_output
|
| 1288 |
+
def serving_output(self, output):
|
| 1289 |
+
pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
|
| 1290 |
+
dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
|
| 1291 |
+
dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
|
| 1292 |
+
cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
|
| 1293 |
+
enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
|
| 1294 |
+
enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
|
| 1295 |
+
|
| 1296 |
+
return TFSeq2SeqModelOutput(
|
| 1297 |
+
last_hidden_state=output.last_hidden_state,
|
| 1298 |
+
past_key_values=pkv,
|
| 1299 |
+
decoder_hidden_states=dec_hs,
|
| 1300 |
+
decoder_attentions=dec_attns,
|
| 1301 |
+
cross_attentions=cross_attns,
|
| 1302 |
+
encoder_last_hidden_state=output.encoder_last_hidden_state,
|
| 1303 |
+
encoder_hidden_states=enc_hs,
|
| 1304 |
+
encoder_attentions=enc_attns,
|
| 1305 |
+
)
|
| 1306 |
+
|
| 1307 |
+
def build(self, input_shape=None):
|
| 1308 |
+
if self.built:
|
| 1309 |
+
return
|
| 1310 |
+
self.built = True
|
| 1311 |
+
if getattr(self, "model", None) is not None:
|
| 1312 |
+
with tf.name_scope(self.model.name):
|
| 1313 |
+
self.model.build(None)
|
| 1314 |
+
|
| 1315 |
+
|
| 1316 |
+
# Copied from transformers.models.bart.modeling_tf_bart.BiasLayer
|
| 1317 |
+
class BiasLayer(tf.keras.layers.Layer):
|
| 1318 |
+
"""
|
| 1319 |
+
Bias as a layer. It is used for serialization purposes: `tf.keras.Model.save_weights` stores on a per-layer basis,
|
| 1320 |
+
so all weights have to be registered in a layer.
|
| 1321 |
+
"""
|
| 1322 |
+
|
| 1323 |
+
def __init__(self, shape, initializer, trainable, name, **kwargs):
|
| 1324 |
+
super().__init__(name=name, **kwargs)
|
| 1325 |
+
# Note: the name of this variable will NOT be scoped when serialized, i.e. it will not be in the format of
|
| 1326 |
+
# "outer_layer/inner_layer/.../name:0". Instead, it will be "name:0". For further details, see:
|
| 1327 |
+
# https://github.com/huggingface/transformers/pull/18833#issuecomment-1233090214
|
| 1328 |
+
self.bias = self.add_weight(name=name, shape=shape, initializer=initializer, trainable=trainable)
|
| 1329 |
+
|
| 1330 |
+
def call(self, x):
|
| 1331 |
+
return x + self.bias
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
@add_start_docstrings(
|
| 1335 |
+
"The BLENDERBOT_SMALL Model with a language modeling head. Can be used for summarization.",
|
| 1336 |
+
BLENDERBOT_SMALL_START_DOCSTRING,
|
| 1337 |
+
)
|
| 1338 |
+
class TFBlenderbotSmallForConditionalGeneration(TFBlenderbotSmallPreTrainedModel, TFCausalLanguageModelingLoss):
|
| 1339 |
+
_keys_to_ignore_on_load_unexpected = [
|
| 1340 |
+
r"model.encoder.embed_tokens.weight",
|
| 1341 |
+
r"model.decoder.embed_tokens.weight",
|
| 1342 |
+
]
|
| 1343 |
+
|
| 1344 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1345 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1346 |
+
self.model = TFBlenderbotSmallMainLayer(config, name="model")
|
| 1347 |
+
self.use_cache = config.use_cache
|
| 1348 |
+
# final_bias_logits is registered as a buffer in pytorch, so not trainable for the sake of consistency.
|
| 1349 |
+
self.bias_layer = BiasLayer(
|
| 1350 |
+
name="final_logits_bias", shape=[1, config.vocab_size], initializer="zeros", trainable=False
|
| 1351 |
+
)
|
| 1352 |
+
|
| 1353 |
+
def get_decoder(self):
|
| 1354 |
+
return self.model.decoder
|
| 1355 |
+
|
| 1356 |
+
def get_encoder(self):
|
| 1357 |
+
return self.model.encoder
|
| 1358 |
+
|
| 1359 |
+
def get_output_embeddings(self):
|
| 1360 |
+
return self.get_input_embeddings()
|
| 1361 |
+
|
| 1362 |
+
def set_output_embeddings(self, value):
|
| 1363 |
+
self.set_input_embeddings(value)
|
| 1364 |
+
|
| 1365 |
+
def get_bias(self):
|
| 1366 |
+
return {"final_logits_bias": self.bias_layer.bias}
|
| 1367 |
+
|
| 1368 |
+
def set_bias(self, value):
|
| 1369 |
+
# Replaces the existing layers containing bias for correct (de)serialization.
|
| 1370 |
+
vocab_size = value["final_logits_bias"].shape[-1]
|
| 1371 |
+
self.bias_layer = BiasLayer(
|
| 1372 |
+
name="final_logits_bias", shape=[1, vocab_size], initializer="zeros", trainable=False
|
| 1373 |
+
)
|
| 1374 |
+
self.bias_layer.bias.assign(value["final_logits_bias"])
|
| 1375 |
+
|
| 1376 |
+
@unpack_inputs
|
| 1377 |
+
@add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING)
|
| 1378 |
+
@replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 1379 |
+
@add_end_docstrings(BLENDERBOT_SMALL_GENERATION_EXAMPLE)
|
| 1380 |
+
def call(
|
| 1381 |
+
self,
|
| 1382 |
+
input_ids: tf.Tensor | None = None,
|
| 1383 |
+
attention_mask: tf.Tensor | None = None,
|
| 1384 |
+
decoder_input_ids: tf.Tensor | None = None,
|
| 1385 |
+
decoder_attention_mask: tf.Tensor | None = None,
|
| 1386 |
+
decoder_position_ids: tf.Tensor | None = None,
|
| 1387 |
+
head_mask: tf.Tensor | None = None,
|
| 1388 |
+
decoder_head_mask: tf.Tensor | None = None,
|
| 1389 |
+
cross_attn_head_mask: tf.Tensor | None = None,
|
| 1390 |
+
encoder_outputs: Optional[TFBaseModelOutput] = None,
|
| 1391 |
+
past_key_values: List[tf.Tensor] | None = None,
|
| 1392 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 1393 |
+
decoder_inputs_embeds: tf.Tensor | None = None,
|
| 1394 |
+
use_cache: Optional[bool] = None,
|
| 1395 |
+
output_attentions: Optional[bool] = None,
|
| 1396 |
+
output_hidden_states: Optional[bool] = None,
|
| 1397 |
+
return_dict: Optional[bool] = None,
|
| 1398 |
+
labels: tf.Tensor | None = None,
|
| 1399 |
+
training: Optional[bool] = False,
|
| 1400 |
+
) -> Union[Tuple[tf.Tensor], TFSeq2SeqLMOutput]:
|
| 1401 |
+
r"""
|
| 1402 |
+
labels (`tf.tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1403 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1404 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1405 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1406 |
+
|
| 1407 |
+
Returns:
|
| 1408 |
+
|
| 1409 |
+
"""
|
| 1410 |
+
|
| 1411 |
+
if labels is not None:
|
| 1412 |
+
labels = tf.where(
|
| 1413 |
+
labels == self.config.pad_token_id,
|
| 1414 |
+
tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),
|
| 1415 |
+
labels,
|
| 1416 |
+
)
|
| 1417 |
+
use_cache = False
|
| 1418 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1419 |
+
decoder_input_ids = shift_tokens_right(
|
| 1420 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1421 |
+
)
|
| 1422 |
+
|
| 1423 |
+
outputs = self.model(
|
| 1424 |
+
input_ids,
|
| 1425 |
+
attention_mask=attention_mask,
|
| 1426 |
+
decoder_input_ids=decoder_input_ids,
|
| 1427 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1428 |
+
decoder_position_ids=decoder_position_ids,
|
| 1429 |
+
head_mask=head_mask,
|
| 1430 |
+
decoder_head_mask=decoder_head_mask,
|
| 1431 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1432 |
+
encoder_outputs=encoder_outputs,
|
| 1433 |
+
past_key_values=past_key_values,
|
| 1434 |
+
inputs_embeds=inputs_embeds,
|
| 1435 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1436 |
+
use_cache=use_cache,
|
| 1437 |
+
output_attentions=output_attentions,
|
| 1438 |
+
output_hidden_states=output_hidden_states,
|
| 1439 |
+
return_dict=return_dict,
|
| 1440 |
+
training=training,
|
| 1441 |
+
)
|
| 1442 |
+
lm_logits = tf.matmul(outputs[0], self.model.shared.weights, transpose_b=True)
|
| 1443 |
+
lm_logits = self.bias_layer(lm_logits)
|
| 1444 |
+
masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)
|
| 1445 |
+
|
| 1446 |
+
if not return_dict:
|
| 1447 |
+
output = (lm_logits,) + outputs[1:]
|
| 1448 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1449 |
+
return TFSeq2SeqLMOutput(
|
| 1450 |
+
loss=masked_lm_loss,
|
| 1451 |
+
logits=lm_logits,
|
| 1452 |
+
past_key_values=outputs.past_key_values, # index 1 of d outputs
|
| 1453 |
+
decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs
|
| 1454 |
+
decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs
|
| 1455 |
+
cross_attentions=outputs.cross_attentions, # index 4 of d outputs
|
| 1456 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs
|
| 1457 |
+
encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out
|
| 1458 |
+
encoder_attentions=outputs.encoder_attentions, # 2 of e out
|
| 1459 |
+
)
|
| 1460 |
+
|
| 1461 |
+
# Copied from transformers.models.bart.modeling_tf_bart.TFBartForConditionalGeneration.serving_output
|
| 1462 |
+
def serving_output(self, output):
|
| 1463 |
+
pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
|
| 1464 |
+
dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
|
| 1465 |
+
dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
|
| 1466 |
+
cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
|
| 1467 |
+
enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
|
| 1468 |
+
enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
|
| 1469 |
+
|
| 1470 |
+
return TFSeq2SeqLMOutput(
|
| 1471 |
+
logits=output.logits,
|
| 1472 |
+
past_key_values=pkv,
|
| 1473 |
+
decoder_hidden_states=dec_hs,
|
| 1474 |
+
decoder_attentions=dec_attns,
|
| 1475 |
+
cross_attentions=cross_attns,
|
| 1476 |
+
encoder_last_hidden_state=output.encoder_last_hidden_state,
|
| 1477 |
+
encoder_hidden_states=enc_hs,
|
| 1478 |
+
encoder_attentions=enc_attns,
|
| 1479 |
+
)
|
| 1480 |
+
|
| 1481 |
+
# Copied from transformers.models.bart.modeling_tf_bart.TFBartForConditionalGeneration.prepare_inputs_for_generation
|
| 1482 |
+
def prepare_inputs_for_generation(
|
| 1483 |
+
self,
|
| 1484 |
+
decoder_input_ids,
|
| 1485 |
+
past_key_values=None,
|
| 1486 |
+
attention_mask=None,
|
| 1487 |
+
decoder_attention_mask=None,
|
| 1488 |
+
head_mask=None,
|
| 1489 |
+
decoder_head_mask=None,
|
| 1490 |
+
cross_attn_head_mask=None,
|
| 1491 |
+
use_cache=None,
|
| 1492 |
+
encoder_outputs=None,
|
| 1493 |
+
**kwargs,
|
| 1494 |
+
):
|
| 1495 |
+
# cut decoder_input_ids if past_key_values is used
|
| 1496 |
+
if past_key_values is not None:
|
| 1497 |
+
decoder_input_ids = decoder_input_ids[:, -1:]
|
| 1498 |
+
|
| 1499 |
+
if decoder_attention_mask is not None: # xla
|
| 1500 |
+
decoder_position_ids = tf.math.cumsum(decoder_attention_mask, axis=-1, exclusive=True)[:, -1:]
|
| 1501 |
+
elif past_key_values is not None: # no xla + past_key_values
|
| 1502 |
+
decoder_position_ids = past_key_values[0][0].shape[2]
|
| 1503 |
+
else: # no xla + no past_key_values
|
| 1504 |
+
decoder_position_ids = tf.range(decoder_input_ids.shape[1])
|
| 1505 |
+
|
| 1506 |
+
return {
|
| 1507 |
+
"input_ids": None, # encoder_outputs is defined. input_ids not needed
|
| 1508 |
+
"encoder_outputs": encoder_outputs,
|
| 1509 |
+
"past_key_values": past_key_values,
|
| 1510 |
+
"decoder_input_ids": decoder_input_ids,
|
| 1511 |
+
"attention_mask": attention_mask,
|
| 1512 |
+
"decoder_attention_mask": decoder_attention_mask,
|
| 1513 |
+
"decoder_position_ids": decoder_position_ids,
|
| 1514 |
+
"head_mask": head_mask,
|
| 1515 |
+
"decoder_head_mask": decoder_head_mask,
|
| 1516 |
+
"cross_attn_head_mask": cross_attn_head_mask,
|
| 1517 |
+
"use_cache": use_cache, # change this to avoid caching (presumably for debugging)
|
| 1518 |
+
}
|
| 1519 |
+
|
| 1520 |
+
def build(self, input_shape=None):
|
| 1521 |
+
if self.built:
|
| 1522 |
+
return
|
| 1523 |
+
self.built = True
|
| 1524 |
+
if getattr(self, "model", None) is not None:
|
| 1525 |
+
with tf.name_scope(self.model.name):
|
| 1526 |
+
self.model.build(None)
|
| 1527 |
+
if getattr(self, "bias_layer", None) is not None:
|
| 1528 |
+
with tf.name_scope(self.bias_layer.name):
|
| 1529 |
+
self.bias_layer.build(None)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/tokenization_blenderbot_small.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization class for BlenderbotSmall."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
from typing import Dict, List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
import regex as re
|
| 22 |
+
|
| 23 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 24 |
+
from ...utils import logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
VOCAB_FILES_NAMES = {
|
| 31 |
+
"vocab_file": "vocab.json",
|
| 32 |
+
"merges_file": "merges.txt",
|
| 33 |
+
"tokenizer_config_file": "tokenizer_config.json",
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
| 37 |
+
"vocab_file": {
|
| 38 |
+
"facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json"
|
| 39 |
+
},
|
| 40 |
+
"merges_file": {
|
| 41 |
+
"facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt"
|
| 42 |
+
},
|
| 43 |
+
"tokenizer_config_file": {
|
| 44 |
+
"facebook/blenderbot_small-90M": (
|
| 45 |
+
"https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json"
|
| 46 |
+
)
|
| 47 |
+
},
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {"facebook/blenderbot_small-90M": 512}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_pairs(word):
|
| 54 |
+
"""
|
| 55 |
+
Return set of symbol pairs in a word.
|
| 56 |
+
|
| 57 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
| 58 |
+
"""
|
| 59 |
+
pairs = set()
|
| 60 |
+
prev_char = word[0]
|
| 61 |
+
for char in word[1:]:
|
| 62 |
+
pairs.add((prev_char, char))
|
| 63 |
+
prev_char = char
|
| 64 |
+
|
| 65 |
+
pairs = set(pairs)
|
| 66 |
+
return pairs
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class BlenderbotSmallTokenizer(PreTrainedTokenizer):
|
| 70 |
+
"""
|
| 71 |
+
Constructs a Blenderbot-90M tokenizer based on BPE (Byte-Pair-Encoding)
|
| 72 |
+
|
| 73 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 74 |
+
the superclass for more information regarding methods.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
vocab_file (`str`):
|
| 78 |
+
File containing the vocabulary.
|
| 79 |
+
merges_file (`str`):
|
| 80 |
+
Path to the merges file.
|
| 81 |
+
bos_token (`str`, *optional*, defaults to `"__start__"`):
|
| 82 |
+
The beginning of sentence token.
|
| 83 |
+
eos_token (`str`, *optional*, defaults to `"__end__"`):
|
| 84 |
+
The end of sentence token.
|
| 85 |
+
unk_token (`str`, *optional*, defaults to `"__unk__"`):
|
| 86 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 87 |
+
token instead.
|
| 88 |
+
pad_token (`str`, *optional*, defaults to `"__null__"`):
|
| 89 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 90 |
+
kwargs (*optional*):
|
| 91 |
+
Additional keyword arguments passed along to [`PreTrainedTokenizer`]
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 95 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
| 96 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
| 97 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
vocab_file,
|
| 102 |
+
merges_file,
|
| 103 |
+
bos_token="__start__",
|
| 104 |
+
eos_token="__end__",
|
| 105 |
+
unk_token="__unk__",
|
| 106 |
+
pad_token="__null__",
|
| 107 |
+
**kwargs,
|
| 108 |
+
):
|
| 109 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
| 110 |
+
self.encoder = json.load(vocab_handle)
|
| 111 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 112 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
| 113 |
+
merges = merges_handle.read().split("\n")[1:-1]
|
| 114 |
+
merges = [tuple(merge.split()) for merge in merges]
|
| 115 |
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
| 116 |
+
self.cache = {}
|
| 117 |
+
super().__init__(unk_token=unk_token, bos_token=bos_token, eos_token=eos_token, pad_token=pad_token, **kwargs)
|
| 118 |
+
|
| 119 |
+
@property
|
| 120 |
+
def vocab_size(self) -> int:
|
| 121 |
+
return len(self.encoder)
|
| 122 |
+
|
| 123 |
+
def get_vocab(self) -> Dict:
|
| 124 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 125 |
+
|
| 126 |
+
def bpe(self, token: str) -> str:
|
| 127 |
+
if token in self.cache:
|
| 128 |
+
return self.cache[token]
|
| 129 |
+
token = re.sub("([.,!?()])", r" \1", token)
|
| 130 |
+
token = re.sub("(')", r" \1 ", token)
|
| 131 |
+
token = re.sub(r"\s{2,}", " ", token)
|
| 132 |
+
if "\n" in token:
|
| 133 |
+
token = token.replace("\n", " __newln__")
|
| 134 |
+
|
| 135 |
+
tokens = token.split(" ")
|
| 136 |
+
words = []
|
| 137 |
+
for token in tokens:
|
| 138 |
+
if not len(token):
|
| 139 |
+
continue
|
| 140 |
+
|
| 141 |
+
token = token.lower()
|
| 142 |
+
word = tuple(token)
|
| 143 |
+
word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
|
| 144 |
+
pairs = get_pairs(word)
|
| 145 |
+
|
| 146 |
+
if not pairs:
|
| 147 |
+
words.append(token)
|
| 148 |
+
continue
|
| 149 |
+
|
| 150 |
+
while True:
|
| 151 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 152 |
+
if bigram not in self.bpe_ranks:
|
| 153 |
+
break
|
| 154 |
+
first, second = bigram
|
| 155 |
+
new_word = []
|
| 156 |
+
i = 0
|
| 157 |
+
|
| 158 |
+
while i < len(word):
|
| 159 |
+
try:
|
| 160 |
+
j = word.index(first, i)
|
| 161 |
+
new_word.extend(word[i:j])
|
| 162 |
+
i = j
|
| 163 |
+
except ValueError:
|
| 164 |
+
new_word.extend(word[i:])
|
| 165 |
+
break
|
| 166 |
+
|
| 167 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 168 |
+
new_word.append(first + second)
|
| 169 |
+
i += 2
|
| 170 |
+
else:
|
| 171 |
+
new_word.append(word[i])
|
| 172 |
+
i += 1
|
| 173 |
+
new_word = tuple(new_word)
|
| 174 |
+
word = new_word
|
| 175 |
+
if len(word) == 1:
|
| 176 |
+
break
|
| 177 |
+
else:
|
| 178 |
+
pairs = get_pairs(word)
|
| 179 |
+
word = "@@ ".join(word)
|
| 180 |
+
word = word[:-4]
|
| 181 |
+
|
| 182 |
+
self.cache[token] = word
|
| 183 |
+
words.append(word)
|
| 184 |
+
return " ".join(words)
|
| 185 |
+
|
| 186 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 187 |
+
"""Split a string into tokens using BPE."""
|
| 188 |
+
split_tokens = []
|
| 189 |
+
|
| 190 |
+
words = re.findall(r"\S+\n?", text)
|
| 191 |
+
|
| 192 |
+
for token in words:
|
| 193 |
+
split_tokens.extend(list(self.bpe(token).split(" ")))
|
| 194 |
+
return split_tokens
|
| 195 |
+
|
| 196 |
+
def _convert_token_to_id(self, token: str) -> int:
|
| 197 |
+
"""Converts a token to an id using the vocab."""
|
| 198 |
+
token = token.lower()
|
| 199 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 200 |
+
|
| 201 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 202 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 203 |
+
return self.decoder.get(index, self.unk_token)
|
| 204 |
+
|
| 205 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
| 206 |
+
"""Converts a sequence of tokens in a single string."""
|
| 207 |
+
out_string = " ".join(tokens).replace("@@ ", "").strip()
|
| 208 |
+
return out_string
|
| 209 |
+
|
| 210 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 211 |
+
if not os.path.isdir(save_directory):
|
| 212 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 213 |
+
return
|
| 214 |
+
vocab_file = os.path.join(
|
| 215 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 216 |
+
)
|
| 217 |
+
merge_file = os.path.join(
|
| 218 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 222 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
| 223 |
+
|
| 224 |
+
index = 0
|
| 225 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
| 226 |
+
writer.write("#version: 0.2\n")
|
| 227 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
| 228 |
+
if index != token_index:
|
| 229 |
+
logger.warning(
|
| 230 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
| 231 |
+
" Please check that the tokenizer is not corrupted!"
|
| 232 |
+
)
|
| 233 |
+
index = token_index
|
| 234 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
| 235 |
+
index += 1
|
| 236 |
+
|
| 237 |
+
return vocab_file, merge_file
|
| 238 |
+
|
| 239 |
+
@property
|
| 240 |
+
# Copied from transformers.models.blenderbot.tokenization_blenderbot.BlenderbotTokenizer.default_chat_template
|
| 241 |
+
def default_chat_template(self):
|
| 242 |
+
"""
|
| 243 |
+
A very simple chat template that just adds whitespace between messages.
|
| 244 |
+
"""
|
| 245 |
+
logger.warning_once(
|
| 246 |
+
"\nNo chat template is defined for this tokenizer - using the default template "
|
| 247 |
+
f"for the {self.__class__.__name__} class. If the default is not appropriate for "
|
| 248 |
+
"your model, please set `tokenizer.chat_template` to an appropriate template. "
|
| 249 |
+
"See https://huggingface.co/docs/transformers/main/chat_templating for more information.\n"
|
| 250 |
+
)
|
| 251 |
+
return (
|
| 252 |
+
"{% for message in messages %}"
|
| 253 |
+
"{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}"
|
| 254 |
+
"{{ message['content'] }}"
|
| 255 |
+
"{% if not loop.last %}{{ ' ' }}{% endif %}"
|
| 256 |
+
"{% endfor %}"
|
| 257 |
+
"{{ eos_token }}"
|
| 258 |
+
)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/blenderbot_small/tokenization_blenderbot_small_fast.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021, The Facebook, Inc. and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Fast tokenization class for BlenderbotSmall."""
|
| 16 |
+
from typing import List, Optional
|
| 17 |
+
|
| 18 |
+
from tokenizers import ByteLevelBPETokenizer
|
| 19 |
+
|
| 20 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 21 |
+
from ...utils import logging
|
| 22 |
+
from .tokenization_blenderbot_small import BlenderbotSmallTokenizer
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
VOCAB_FILES_NAMES = {
|
| 28 |
+
"vocab_file": "vocab.json",
|
| 29 |
+
"merges_file": "merges.txt",
|
| 30 |
+
"tokenizer_config_file": "tokenizer_config.json",
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
| 34 |
+
"vocab_file": {
|
| 35 |
+
"facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json"
|
| 36 |
+
},
|
| 37 |
+
"merges_file": {
|
| 38 |
+
"facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt"
|
| 39 |
+
},
|
| 40 |
+
"tokenizer_config_file": {
|
| 41 |
+
"facebook/blenderbot_small-90M": (
|
| 42 |
+
"https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json"
|
| 43 |
+
)
|
| 44 |
+
},
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
| 48 |
+
"facebook/blenderbot_small-90M": 512,
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class BlenderbotSmallTokenizerFast(PreTrainedTokenizerFast):
|
| 53 |
+
"""
|
| 54 |
+
Construct a "fast" BlenderbotSmall tokenizer (backed by HuggingFace's *tokenizers* library).
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
vocab_file (`str`):
|
| 58 |
+
Path to the vocabulary file.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 62 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
| 63 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
| 64 |
+
slow_tokenizer_class = BlenderbotSmallTokenizer
|
| 65 |
+
|
| 66 |
+
def __init__(
|
| 67 |
+
self,
|
| 68 |
+
vocab_file=None,
|
| 69 |
+
merges_file=None,
|
| 70 |
+
unk_token="<|endoftext|>",
|
| 71 |
+
bos_token="<|endoftext|>",
|
| 72 |
+
eos_token="<|endoftext|>",
|
| 73 |
+
add_prefix_space=False,
|
| 74 |
+
trim_offsets=True,
|
| 75 |
+
**kwargs,
|
| 76 |
+
):
|
| 77 |
+
super().__init__(
|
| 78 |
+
ByteLevelBPETokenizer(
|
| 79 |
+
vocab=vocab_file,
|
| 80 |
+
merges=merges_file,
|
| 81 |
+
add_prefix_space=add_prefix_space,
|
| 82 |
+
trim_offsets=trim_offsets,
|
| 83 |
+
),
|
| 84 |
+
bos_token=bos_token,
|
| 85 |
+
eos_token=eos_token,
|
| 86 |
+
unk_token=unk_token,
|
| 87 |
+
**kwargs,
|
| 88 |
+
)
|
| 89 |
+
self.add_prefix_space = add_prefix_space
|
| 90 |
+
|
| 91 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
| 92 |
+
output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
|
| 93 |
+
if token_ids_1 is None:
|
| 94 |
+
return output
|
| 95 |
+
|
| 96 |
+
return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
|
| 97 |
+
|
| 98 |
+
def create_token_type_ids_from_sequences(
|
| 99 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 100 |
+
) -> List[int]:
|
| 101 |
+
"""
|
| 102 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. BlenderbotSmall
|
| 103 |
+
does not make use of token type ids, therefore a list of zeros is returned.
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
token_ids_0 (`List[int]`):
|
| 107 |
+
List of IDs.
|
| 108 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 109 |
+
Optional second list of IDs for sequence pairs.
|
| 110 |
+
|
| 111 |
+
Returns:
|
| 112 |
+
`List[int]`: List of zeros.
|
| 113 |
+
"""
|
| 114 |
+
sep = [self.sep_token_id]
|
| 115 |
+
cls = [self.cls_token_id]
|
| 116 |
+
|
| 117 |
+
if token_ids_1 is None:
|
| 118 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 119 |
+
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
|
| 120 |
+
|
| 121 |
+
@property
|
| 122 |
+
# Copied from transformers.models.blenderbot.tokenization_blenderbot.BlenderbotTokenizer.default_chat_template
|
| 123 |
+
def default_chat_template(self):
|
| 124 |
+
"""
|
| 125 |
+
A very simple chat template that just adds whitespace between messages.
|
| 126 |
+
"""
|
| 127 |
+
logger.warning_once(
|
| 128 |
+
"\nNo chat template is defined for this tokenizer - using the default template "
|
| 129 |
+
f"for the {self.__class__.__name__} class. If the default is not appropriate for "
|
| 130 |
+
"your model, please set `tokenizer.chat_template` to an appropriate template. "
|
| 131 |
+
"See https://huggingface.co/docs/transformers/main/chat_templating for more information.\n"
|
| 132 |
+
)
|
| 133 |
+
return (
|
| 134 |
+
"{% for message in messages %}"
|
| 135 |
+
"{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}"
|
| 136 |
+
"{{ message['content'] }}"
|
| 137 |
+
"{% if not loop.last %}{{ ' ' }}{% endif %}"
|
| 138 |
+
"{% endfor %}"
|
| 139 |
+
"{{ eos_token }}"
|
| 140 |
+
)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/byt5/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (495 Bytes). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/byt5/__pycache__/tokenization_byt5.cpython-310.pyc
ADDED
|
Binary file (9.22 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/byt5/convert_byt5_original_tf_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The T5 authors and HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert T5 checkpoint."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
|
| 20 |
+
from transformers import T5Config, T5ForConditionalGeneration, load_tf_weights_in_t5
|
| 21 |
+
from transformers.utils import logging
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logging.set_verbosity_info()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, config_file, pytorch_dump_path):
|
| 28 |
+
# Initialise PyTorch model
|
| 29 |
+
config = T5Config.from_json_file(config_file)
|
| 30 |
+
print(f"Building PyTorch model from configuration: {config}")
|
| 31 |
+
model = T5ForConditionalGeneration(config)
|
| 32 |
+
|
| 33 |
+
# Load weights from tf checkpoint
|
| 34 |
+
load_tf_weights_in_t5(model, config, tf_checkpoint_path)
|
| 35 |
+
|
| 36 |
+
# Save pytorch-model
|
| 37 |
+
print(f"Save PyTorch model to {pytorch_dump_path}")
|
| 38 |
+
model.save_pretrained(pytorch_dump_path)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
parser = argparse.ArgumentParser()
|
| 43 |
+
# Required parameters
|
| 44 |
+
parser.add_argument(
|
| 45 |
+
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
|
| 46 |
+
)
|
| 47 |
+
parser.add_argument(
|
| 48 |
+
"--config_file",
|
| 49 |
+
default=None,
|
| 50 |
+
type=str,
|
| 51 |
+
required=True,
|
| 52 |
+
help=(
|
| 53 |
+
"The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture."
|
| 54 |
+
),
|
| 55 |
+
)
|
| 56 |
+
parser.add_argument(
|
| 57 |
+
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
|
| 58 |
+
)
|
| 59 |
+
args = parser.parse_args()
|
| 60 |
+
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__init__.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The OFA-Sys Team Authors and 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 OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_import_structure = {
|
| 20 |
+
"configuration_chinese_clip": [
|
| 21 |
+
"CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
| 22 |
+
"ChineseCLIPConfig",
|
| 23 |
+
"ChineseCLIPOnnxConfig",
|
| 24 |
+
"ChineseCLIPTextConfig",
|
| 25 |
+
"ChineseCLIPVisionConfig",
|
| 26 |
+
],
|
| 27 |
+
"processing_chinese_clip": ["ChineseCLIPProcessor"],
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
if not is_vision_available():
|
| 32 |
+
raise OptionalDependencyNotAvailable()
|
| 33 |
+
except OptionalDependencyNotAvailable:
|
| 34 |
+
pass
|
| 35 |
+
else:
|
| 36 |
+
_import_structure["feature_extraction_chinese_clip"] = ["ChineseCLIPFeatureExtractor"]
|
| 37 |
+
_import_structure["image_processing_chinese_clip"] = ["ChineseCLIPImageProcessor"]
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
if not is_torch_available():
|
| 41 |
+
raise OptionalDependencyNotAvailable()
|
| 42 |
+
except OptionalDependencyNotAvailable:
|
| 43 |
+
pass
|
| 44 |
+
else:
|
| 45 |
+
_import_structure["modeling_chinese_clip"] = [
|
| 46 |
+
"CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 47 |
+
"ChineseCLIPModel",
|
| 48 |
+
"ChineseCLIPPreTrainedModel",
|
| 49 |
+
"ChineseCLIPTextModel",
|
| 50 |
+
"ChineseCLIPVisionModel",
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
if TYPE_CHECKING:
|
| 54 |
+
from .configuration_chinese_clip import (
|
| 55 |
+
CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
| 56 |
+
ChineseCLIPConfig,
|
| 57 |
+
ChineseCLIPOnnxConfig,
|
| 58 |
+
ChineseCLIPTextConfig,
|
| 59 |
+
ChineseCLIPVisionConfig,
|
| 60 |
+
)
|
| 61 |
+
from .processing_chinese_clip import ChineseCLIPProcessor
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
if not is_vision_available():
|
| 65 |
+
raise OptionalDependencyNotAvailable()
|
| 66 |
+
except OptionalDependencyNotAvailable:
|
| 67 |
+
pass
|
| 68 |
+
else:
|
| 69 |
+
from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
if not is_torch_available():
|
| 73 |
+
raise OptionalDependencyNotAvailable()
|
| 74 |
+
except OptionalDependencyNotAvailable:
|
| 75 |
+
pass
|
| 76 |
+
else:
|
| 77 |
+
from .modeling_chinese_clip import (
|
| 78 |
+
CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 79 |
+
ChineseCLIPModel,
|
| 80 |
+
ChineseCLIPPreTrainedModel,
|
| 81 |
+
ChineseCLIPTextModel,
|
| 82 |
+
ChineseCLIPVisionModel,
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
else:
|
| 86 |
+
import sys
|
| 87 |
+
|
| 88 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/configuration_chinese_clip.cpython-310.pyc
ADDED
|
Binary file (17.9 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/convert_chinese_clip_original_pytorch_to_hf.cpython-310.pyc
ADDED
|
Binary file (4.04 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/feature_extraction_chinese_clip.cpython-310.pyc
ADDED
|
Binary file (1.06 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip.cpython-310.pyc
ADDED
|
Binary file (13.1 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/modeling_chinese_clip.cpython-310.pyc
ADDED
|
Binary file (48.4 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/__pycache__/processing_chinese_clip.cpython-310.pyc
ADDED
|
Binary file (6.12 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/configuration_chinese_clip.py
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Chinese-CLIP model configuration"""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from ...processing_utils import ProcessorMixin
|
| 24 |
+
from ...utils import TensorType
|
| 25 |
+
|
| 26 |
+
from ...configuration_utils import PretrainedConfig
|
| 27 |
+
from ...onnx import OnnxConfig
|
| 28 |
+
from ...utils import logging
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 34 |
+
"OFA-Sys/chinese-clip-vit-base-patch16": (
|
| 35 |
+
"https://huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16/resolve/main/config.json"
|
| 36 |
+
),
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class ChineseCLIPTextConfig(PretrainedConfig):
|
| 41 |
+
r"""
|
| 42 |
+
This is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used to instantiate a
|
| 43 |
+
Chinese CLIP model according to the specified arguments, defining the model architecture. Instantiating a
|
| 44 |
+
configuration with the defaults will yield a similar configuration to that of the Chinese CLIP
|
| 45 |
+
[OFA-Sys/chinese-clip-vit-base-patch16](https:
|
| 46 |
+
//huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16) architecture.
|
| 47 |
+
|
| 48 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 49 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 54 |
+
Vocabulary size of the CHINESE_CLIP model. Defines the number of different tokens that can be represented
|
| 55 |
+
by the `inputs_ids` passed when calling [`ChineseCLIPModel`].
|
| 56 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 57 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 58 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 59 |
+
Number of hidden layers in the Transformer encoder.
|
| 60 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 61 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 62 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 63 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 64 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
| 65 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 66 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 67 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 68 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 69 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 70 |
+
The dropout ratio for the attention probabilities.
|
| 71 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 72 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 73 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 74 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 75 |
+
The vocabulary size of the `token_type_ids` passed when calling [`ChineseCLIPModel`].
|
| 76 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 77 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 78 |
+
initializer_factor (`float`, *optional*, defaults to 1.0):
|
| 79 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
| 80 |
+
testing).
|
| 81 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 82 |
+
The epsilon used by the layer normalization layers.
|
| 83 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
| 84 |
+
Padding token id.
|
| 85 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 86 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 87 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 88 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 89 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 90 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 91 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 92 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 93 |
+
relevant if `config.is_decoder=True`.
|
| 94 |
+
|
| 95 |
+
Example:
|
| 96 |
+
|
| 97 |
+
```python
|
| 98 |
+
>>> from transformers import ChineseCLIPTextConfig, ChineseCLIPTextModel
|
| 99 |
+
|
| 100 |
+
>>> # Initializing a ChineseCLIPTextConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
| 101 |
+
>>> configuration = ChineseCLIPTextConfig()
|
| 102 |
+
|
| 103 |
+
>>> # Initializing a ChineseCLIPTextModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
| 104 |
+
>>> model = ChineseCLIPTextModel(configuration)
|
| 105 |
+
|
| 106 |
+
>>> # Accessing the model configuration
|
| 107 |
+
>>> configuration = model.config
|
| 108 |
+
```"""
|
| 109 |
+
|
| 110 |
+
model_type = "chinese_clip_text_model"
|
| 111 |
+
|
| 112 |
+
def __init__(
|
| 113 |
+
self,
|
| 114 |
+
vocab_size=30522,
|
| 115 |
+
hidden_size=768,
|
| 116 |
+
num_hidden_layers=12,
|
| 117 |
+
num_attention_heads=12,
|
| 118 |
+
intermediate_size=3072,
|
| 119 |
+
hidden_act="gelu",
|
| 120 |
+
hidden_dropout_prob=0.1,
|
| 121 |
+
attention_probs_dropout_prob=0.1,
|
| 122 |
+
max_position_embeddings=512,
|
| 123 |
+
type_vocab_size=2,
|
| 124 |
+
initializer_range=0.02,
|
| 125 |
+
initializer_factor=1.0,
|
| 126 |
+
layer_norm_eps=1e-12,
|
| 127 |
+
pad_token_id=0,
|
| 128 |
+
position_embedding_type="absolute",
|
| 129 |
+
use_cache=True,
|
| 130 |
+
**kwargs,
|
| 131 |
+
):
|
| 132 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
| 133 |
+
|
| 134 |
+
self.vocab_size = vocab_size
|
| 135 |
+
self.hidden_size = hidden_size
|
| 136 |
+
self.num_hidden_layers = num_hidden_layers
|
| 137 |
+
self.num_attention_heads = num_attention_heads
|
| 138 |
+
self.hidden_act = hidden_act
|
| 139 |
+
self.intermediate_size = intermediate_size
|
| 140 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 141 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 142 |
+
self.max_position_embeddings = max_position_embeddings
|
| 143 |
+
self.type_vocab_size = type_vocab_size
|
| 144 |
+
self.initializer_range = initializer_range
|
| 145 |
+
self.initializer_factor = initializer_factor
|
| 146 |
+
self.layer_norm_eps = layer_norm_eps
|
| 147 |
+
self.position_embedding_type = position_embedding_type
|
| 148 |
+
self.use_cache = use_cache
|
| 149 |
+
|
| 150 |
+
@classmethod
|
| 151 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 152 |
+
cls._set_token_in_kwargs(kwargs)
|
| 153 |
+
|
| 154 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 155 |
+
|
| 156 |
+
# get the vision config dict if we are loading from ChineseCLIPConfig
|
| 157 |
+
if config_dict.get("model_type") == "chinese_clip":
|
| 158 |
+
config_dict = config_dict["text_config"]
|
| 159 |
+
|
| 160 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 161 |
+
logger.warning(
|
| 162 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 163 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class ChineseCLIPVisionConfig(PretrainedConfig):
|
| 170 |
+
r"""
|
| 171 |
+
This is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used to instantiate an
|
| 172 |
+
ChineseCLIP model according to the specified arguments, defining the model architecture. Instantiating a
|
| 173 |
+
configuration with the defaults will yield a similar configuration to that of the ChineseCLIP
|
| 174 |
+
[OFA-Sys/chinese-clip-vit-base-patch16](https:
|
| 175 |
+
//huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16) architecture.
|
| 176 |
+
|
| 177 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 178 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
Args:
|
| 182 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 183 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 184 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 185 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 186 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
| 187 |
+
Dimentionality of text and vision projection layers.
|
| 188 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 189 |
+
Number of hidden layers in the Transformer encoder.
|
| 190 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 191 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 192 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 193 |
+
The number of input channels.
|
| 194 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 195 |
+
The size (resolution) of each image.
|
| 196 |
+
patch_size (`int`, *optional*, defaults to 32):
|
| 197 |
+
The size (resolution) of each patch.
|
| 198 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
| 199 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 200 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
|
| 201 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 202 |
+
The epsilon used by the layer normalization layers.
|
| 203 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 204 |
+
The dropout ratio for the attention probabilities.
|
| 205 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 206 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 207 |
+
initializer_factor (`float`, *optional*, defaults to 1.0):
|
| 208 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
| 209 |
+
testing).
|
| 210 |
+
Example:
|
| 211 |
+
```python
|
| 212 |
+
>>> from transformers import ChineseCLIPVisionConfig, ChineseCLIPVisionModel
|
| 213 |
+
|
| 214 |
+
>>> # Initializing a ChineseCLIPVisionConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
| 215 |
+
>>> configuration = ChineseCLIPVisionConfig()
|
| 216 |
+
|
| 217 |
+
>>> # Initializing a ChineseCLIPVisionModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
| 218 |
+
>>> model = ChineseCLIPVisionModel(configuration)
|
| 219 |
+
|
| 220 |
+
>>> # Accessing the model configuration
|
| 221 |
+
>>> configuration = model.config
|
| 222 |
+
```"""
|
| 223 |
+
|
| 224 |
+
model_type = "chinese_clip_vision_model"
|
| 225 |
+
|
| 226 |
+
def __init__(
|
| 227 |
+
self,
|
| 228 |
+
hidden_size=768,
|
| 229 |
+
intermediate_size=3072,
|
| 230 |
+
projection_dim=512,
|
| 231 |
+
num_hidden_layers=12,
|
| 232 |
+
num_attention_heads=12,
|
| 233 |
+
num_channels=3,
|
| 234 |
+
image_size=224,
|
| 235 |
+
patch_size=32,
|
| 236 |
+
hidden_act="quick_gelu",
|
| 237 |
+
layer_norm_eps=1e-5,
|
| 238 |
+
attention_dropout=0.0,
|
| 239 |
+
initializer_range=0.02,
|
| 240 |
+
initializer_factor=1.0,
|
| 241 |
+
**kwargs,
|
| 242 |
+
):
|
| 243 |
+
super().__init__(**kwargs)
|
| 244 |
+
|
| 245 |
+
self.hidden_size = hidden_size
|
| 246 |
+
self.intermediate_size = intermediate_size
|
| 247 |
+
self.projection_dim = projection_dim
|
| 248 |
+
self.num_hidden_layers = num_hidden_layers
|
| 249 |
+
self.num_attention_heads = num_attention_heads
|
| 250 |
+
self.num_channels = num_channels
|
| 251 |
+
self.patch_size = patch_size
|
| 252 |
+
self.image_size = image_size
|
| 253 |
+
self.initializer_range = initializer_range
|
| 254 |
+
self.initializer_factor = initializer_factor
|
| 255 |
+
self.attention_dropout = attention_dropout
|
| 256 |
+
self.layer_norm_eps = layer_norm_eps
|
| 257 |
+
self.hidden_act = hidden_act
|
| 258 |
+
|
| 259 |
+
@classmethod
|
| 260 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 261 |
+
cls._set_token_in_kwargs(kwargs)
|
| 262 |
+
|
| 263 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 264 |
+
|
| 265 |
+
# get the vision config dict if we are loading from ChineseCLIPConfig
|
| 266 |
+
if config_dict.get("model_type") == "chinese_clip":
|
| 267 |
+
config_dict = config_dict["vision_config"]
|
| 268 |
+
|
| 269 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 270 |
+
logger.warning(
|
| 271 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 272 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class ChineseCLIPConfig(PretrainedConfig):
|
| 279 |
+
r"""
|
| 280 |
+
[`ChineseCLIPConfig`] is the configuration class to store the configuration of a [`ChineseCLIPModel`]. It is used
|
| 281 |
+
to instantiate Chinese-CLIP model according to the specified arguments, defining the text model and vision model
|
| 282 |
+
configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the
|
| 283 |
+
Chinese-CLIP [OFA-Sys/chinese-clip-vit-base-patch16](https://huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16)
|
| 284 |
+
architecture.
|
| 285 |
+
|
| 286 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 287 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 288 |
+
|
| 289 |
+
Args:
|
| 290 |
+
text_config (`dict`, *optional*):
|
| 291 |
+
Dictionary of configuration options used to initialize [`ChineseCLIPTextConfig`].
|
| 292 |
+
vision_config (`dict`, *optional*):
|
| 293 |
+
Dictionary of configuration options used to initialize [`ChineseCLIPVisionConfig`].
|
| 294 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
| 295 |
+
Dimentionality of text and vision projection layers.
|
| 296 |
+
logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
|
| 297 |
+
The inital value of the *logit_scale* paramter. Default is used as per the original ChineseCLIP
|
| 298 |
+
implementation.
|
| 299 |
+
kwargs (*optional*):
|
| 300 |
+
Dictionary of keyword arguments.
|
| 301 |
+
|
| 302 |
+
Example:
|
| 303 |
+
|
| 304 |
+
```python
|
| 305 |
+
>>> from transformers import ChineseCLIPConfig, ChineseCLIPModel
|
| 306 |
+
|
| 307 |
+
>>> # Initializing a ChineseCLIPConfig with OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
| 308 |
+
>>> configuration = ChineseCLIPConfig()
|
| 309 |
+
|
| 310 |
+
>>> # Initializing a ChineseCLIPModel (with random weights) from the OFA-Sys/chinese-clip-vit-base-patch16 style configuration
|
| 311 |
+
>>> model = ChineseCLIPModel(configuration)
|
| 312 |
+
|
| 313 |
+
>>> # Accessing the model configuration
|
| 314 |
+
>>> configuration = model.config
|
| 315 |
+
|
| 316 |
+
>>> # We can also initialize a ChineseCLIPConfig from a ChineseCLIPTextConfig and a ChineseCLIPVisionConfig
|
| 317 |
+
|
| 318 |
+
>>> # Initializing a ChineseCLIPTextConfig and ChineseCLIPVisionConfig configuration
|
| 319 |
+
>>> config_text = ChineseCLIPTextConfig()
|
| 320 |
+
>>> config_vision = ChineseCLIPVisionConfig()
|
| 321 |
+
|
| 322 |
+
>>> config = ChineseCLIPConfig.from_text_vision_configs(config_text, config_vision)
|
| 323 |
+
```"""
|
| 324 |
+
|
| 325 |
+
model_type = "chinese_clip"
|
| 326 |
+
|
| 327 |
+
def __init__(
|
| 328 |
+
self, text_config=None, vision_config=None, projection_dim=512, logit_scale_init_value=2.6592, **kwargs
|
| 329 |
+
):
|
| 330 |
+
# If `_config_dict` exist, we use them for the backward compatibility.
|
| 331 |
+
# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
|
| 332 |
+
# of confusion!).
|
| 333 |
+
text_config_dict = kwargs.pop("text_config_dict", None)
|
| 334 |
+
vision_config_dict = kwargs.pop("vision_config_dict", None)
|
| 335 |
+
|
| 336 |
+
super().__init__(**kwargs)
|
| 337 |
+
|
| 338 |
+
# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
|
| 339 |
+
# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
|
| 340 |
+
# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
|
| 341 |
+
if text_config_dict is not None:
|
| 342 |
+
if text_config is None:
|
| 343 |
+
text_config = {}
|
| 344 |
+
|
| 345 |
+
# This is the complete result when using `text_config_dict`.
|
| 346 |
+
_text_config_dict = ChineseCLIPTextConfig(**text_config_dict).to_dict()
|
| 347 |
+
|
| 348 |
+
# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
|
| 349 |
+
for key, value in _text_config_dict.items():
|
| 350 |
+
if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
|
| 351 |
+
# If specified in `text_config_dict`
|
| 352 |
+
if key in text_config_dict:
|
| 353 |
+
message = (
|
| 354 |
+
f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
|
| 355 |
+
f'The value `text_config_dict["{key}"]` will be used instead.'
|
| 356 |
+
)
|
| 357 |
+
# If inferred from default argument values (just to be super careful)
|
| 358 |
+
else:
|
| 359 |
+
message = (
|
| 360 |
+
f"`text_config_dict` is provided which will be used to initialize `ChineseCLIPTextConfig`. "
|
| 361 |
+
f'The value `text_config["{key}"]` will be overriden.'
|
| 362 |
+
)
|
| 363 |
+
logger.info(message)
|
| 364 |
+
|
| 365 |
+
# Update all values in `text_config` with the ones in `_text_config_dict`.
|
| 366 |
+
text_config.update(_text_config_dict)
|
| 367 |
+
|
| 368 |
+
if vision_config_dict is not None:
|
| 369 |
+
if vision_config is None:
|
| 370 |
+
vision_config = {}
|
| 371 |
+
|
| 372 |
+
# This is the complete result when using `vision_config_dict`.
|
| 373 |
+
_vision_config_dict = ChineseCLIPVisionConfig(**vision_config_dict).to_dict()
|
| 374 |
+
# convert keys to string instead of integer
|
| 375 |
+
if "id2label" in _vision_config_dict:
|
| 376 |
+
_vision_config_dict["id2label"] = {
|
| 377 |
+
str(key): value for key, value in _vision_config_dict["id2label"].items()
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
|
| 381 |
+
for key, value in _vision_config_dict.items():
|
| 382 |
+
if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
|
| 383 |
+
# If specified in `vision_config_dict`
|
| 384 |
+
if key in vision_config_dict:
|
| 385 |
+
message = (
|
| 386 |
+
f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
|
| 387 |
+
f'values. The value `vision_config_dict["{key}"]` will be used instead.'
|
| 388 |
+
)
|
| 389 |
+
# If inferred from default argument values (just to be super careful)
|
| 390 |
+
else:
|
| 391 |
+
message = (
|
| 392 |
+
f"`vision_config_dict` is provided which will be used to initialize "
|
| 393 |
+
f'`ChineseCLIPVisionConfig`. The value `vision_config["{key}"]` will be overriden.'
|
| 394 |
+
)
|
| 395 |
+
logger.info(message)
|
| 396 |
+
|
| 397 |
+
# Update all values in `vision_config` with the ones in `_vision_config_dict`.
|
| 398 |
+
vision_config.update(_vision_config_dict)
|
| 399 |
+
|
| 400 |
+
if text_config is None:
|
| 401 |
+
text_config = {}
|
| 402 |
+
logger.info("`text_config` is `None`. Initializing the `ChineseCLIPTextConfig` with default values.")
|
| 403 |
+
|
| 404 |
+
if vision_config is None:
|
| 405 |
+
vision_config = {}
|
| 406 |
+
logger.info("`vision_config` is `None`. initializing the `ChineseCLIPVisionConfig` with default values.")
|
| 407 |
+
|
| 408 |
+
self.text_config = ChineseCLIPTextConfig(**text_config)
|
| 409 |
+
self.vision_config = ChineseCLIPVisionConfig(**vision_config)
|
| 410 |
+
|
| 411 |
+
self.projection_dim = projection_dim
|
| 412 |
+
self.logit_scale_init_value = logit_scale_init_value
|
| 413 |
+
self.initializer_factor = 1.0
|
| 414 |
+
self.initializer_range = 0.02
|
| 415 |
+
|
| 416 |
+
@classmethod
|
| 417 |
+
def from_text_vision_configs(
|
| 418 |
+
cls, text_config: ChineseCLIPTextConfig, vision_config: ChineseCLIPVisionConfig, **kwargs
|
| 419 |
+
):
|
| 420 |
+
r"""
|
| 421 |
+
Instantiate a [`ChineseCLIPConfig`] (or a derived class) from Chinese-CLIP text model configuration and
|
| 422 |
+
Chinese-CLIP vision model configuration. Returns:
|
| 423 |
+
[`ChineseCLIPConfig`]: An instance of a configuration object
|
| 424 |
+
"""
|
| 425 |
+
|
| 426 |
+
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
class ChineseCLIPOnnxConfig(OnnxConfig):
|
| 430 |
+
@property
|
| 431 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 432 |
+
return OrderedDict(
|
| 433 |
+
[
|
| 434 |
+
("input_ids", {0: "batch", 1: "sequence"}),
|
| 435 |
+
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
|
| 436 |
+
("attention_mask", {0: "batch", 1: "sequence"}),
|
| 437 |
+
]
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
@property
|
| 441 |
+
def outputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 442 |
+
return OrderedDict(
|
| 443 |
+
[
|
| 444 |
+
("logits_per_image", {0: "batch"}),
|
| 445 |
+
("logits_per_text", {0: "batch"}),
|
| 446 |
+
("text_embeds", {0: "batch"}),
|
| 447 |
+
("image_embeds", {0: "batch"}),
|
| 448 |
+
]
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
@property
|
| 452 |
+
def atol_for_validation(self) -> float:
|
| 453 |
+
return 1e-4
|
| 454 |
+
|
| 455 |
+
def generate_dummy_inputs(
|
| 456 |
+
self,
|
| 457 |
+
processor: "ProcessorMixin",
|
| 458 |
+
batch_size: int = -1,
|
| 459 |
+
seq_length: int = -1,
|
| 460 |
+
framework: Optional["TensorType"] = None,
|
| 461 |
+
) -> Mapping[str, Any]:
|
| 462 |
+
text_input_dict = super().generate_dummy_inputs(
|
| 463 |
+
processor.tokenizer, batch_size=batch_size, seq_length=seq_length, framework=framework
|
| 464 |
+
)
|
| 465 |
+
image_input_dict = super().generate_dummy_inputs(
|
| 466 |
+
processor.image_processor, batch_size=batch_size, framework=framework
|
| 467 |
+
)
|
| 468 |
+
return {**text_input_dict, **image_input_dict}
|
| 469 |
+
|
| 470 |
+
@property
|
| 471 |
+
def default_onnx_opset(self) -> int:
|
| 472 |
+
return 14
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/image_processing_chinese_clip.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Image processor class for Chinese-CLIP."""
|
| 16 |
+
|
| 17 |
+
from typing import Dict, List, Optional, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 22 |
+
from ...image_transforms import (
|
| 23 |
+
convert_to_rgb,
|
| 24 |
+
get_resize_output_image_size,
|
| 25 |
+
resize,
|
| 26 |
+
to_channel_dimension_format,
|
| 27 |
+
)
|
| 28 |
+
from ...image_utils import (
|
| 29 |
+
OPENAI_CLIP_MEAN,
|
| 30 |
+
OPENAI_CLIP_STD,
|
| 31 |
+
ChannelDimension,
|
| 32 |
+
ImageInput,
|
| 33 |
+
PILImageResampling,
|
| 34 |
+
infer_channel_dimension_format,
|
| 35 |
+
is_scaled_image,
|
| 36 |
+
make_list_of_images,
|
| 37 |
+
to_numpy_array,
|
| 38 |
+
valid_images,
|
| 39 |
+
)
|
| 40 |
+
from ...utils import TensorType, is_vision_available, logging
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
logger = logging.get_logger(__name__)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if is_vision_available():
|
| 47 |
+
import PIL
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class ChineseCLIPImageProcessor(BaseImageProcessor):
|
| 51 |
+
r"""
|
| 52 |
+
Constructs a Chinese-CLIP image processor.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 56 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
|
| 57 |
+
`do_resize` in the `preprocess` method.
|
| 58 |
+
size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
|
| 59 |
+
Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
|
| 60 |
+
the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
|
| 61 |
+
method.
|
| 62 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
|
| 63 |
+
Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
|
| 64 |
+
do_center_crop (`bool`, *optional*, defaults to `True`):
|
| 65 |
+
Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
|
| 66 |
+
`preprocess` method.
|
| 67 |
+
crop_size (`Dict[str, int]` *optional*, defaults to 224):
|
| 68 |
+
Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
|
| 69 |
+
method.
|
| 70 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 71 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
|
| 72 |
+
the `preprocess` method.
|
| 73 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 74 |
+
Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
|
| 75 |
+
method.
|
| 76 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 77 |
+
Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
|
| 78 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
| 79 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 80 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 81 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
| 82 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 83 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 84 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 85 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
| 86 |
+
Whether to convert the image to RGB.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
model_input_names = ["pixel_values"]
|
| 90 |
+
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
do_resize: bool = True,
|
| 94 |
+
size: Dict[str, int] = None,
|
| 95 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 96 |
+
do_center_crop: bool = True,
|
| 97 |
+
crop_size: Dict[str, int] = None,
|
| 98 |
+
do_rescale: bool = True,
|
| 99 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 100 |
+
do_normalize: bool = True,
|
| 101 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 102 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 103 |
+
do_convert_rgb: bool = True,
|
| 104 |
+
**kwargs,
|
| 105 |
+
) -> None:
|
| 106 |
+
super().__init__(**kwargs)
|
| 107 |
+
size = size if size is not None else {"shortest_edge": 224}
|
| 108 |
+
size = get_size_dict(size, default_to_square=False)
|
| 109 |
+
crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
|
| 110 |
+
crop_size = get_size_dict(crop_size)
|
| 111 |
+
|
| 112 |
+
self.do_resize = do_resize
|
| 113 |
+
self.size = size
|
| 114 |
+
self.resample = resample
|
| 115 |
+
self.do_center_crop = do_center_crop
|
| 116 |
+
self.crop_size = crop_size
|
| 117 |
+
self.do_rescale = do_rescale
|
| 118 |
+
self.rescale_factor = rescale_factor
|
| 119 |
+
self.do_normalize = do_normalize
|
| 120 |
+
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
|
| 121 |
+
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
|
| 122 |
+
self.do_convert_rgb = do_convert_rgb
|
| 123 |
+
|
| 124 |
+
def resize(
|
| 125 |
+
self,
|
| 126 |
+
image: np.ndarray,
|
| 127 |
+
size: Dict[str, int],
|
| 128 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 129 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 130 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 131 |
+
**kwargs,
|
| 132 |
+
) -> np.ndarray:
|
| 133 |
+
"""
|
| 134 |
+
Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
|
| 135 |
+
resized to keep the input aspect ratio.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
image (`np.ndarray`):
|
| 139 |
+
Image to resize.
|
| 140 |
+
size (`Dict[str, int]`):
|
| 141 |
+
Size of the output image.
|
| 142 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 143 |
+
Resampling filter to use when resiizing the image.
|
| 144 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 145 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 146 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 147 |
+
The channel dimension format of the input image. If not provided, it will be inferred from the input
|
| 148 |
+
image.
|
| 149 |
+
"""
|
| 150 |
+
size = get_size_dict(size, default_to_square=False)
|
| 151 |
+
output_size = get_resize_output_image_size(
|
| 152 |
+
image, size=(size["height"], size["width"]), default_to_square=False, input_data_format=input_data_format
|
| 153 |
+
)
|
| 154 |
+
return resize(
|
| 155 |
+
image,
|
| 156 |
+
size=output_size,
|
| 157 |
+
resample=resample,
|
| 158 |
+
data_format=data_format,
|
| 159 |
+
input_data_format=input_data_format,
|
| 160 |
+
**kwargs,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
def preprocess(
|
| 164 |
+
self,
|
| 165 |
+
images: ImageInput,
|
| 166 |
+
do_resize: bool = None,
|
| 167 |
+
size: Dict[str, int] = None,
|
| 168 |
+
resample: PILImageResampling = None,
|
| 169 |
+
do_center_crop: bool = None,
|
| 170 |
+
crop_size: int = None,
|
| 171 |
+
do_rescale: bool = None,
|
| 172 |
+
rescale_factor: float = None,
|
| 173 |
+
do_normalize: bool = None,
|
| 174 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 175 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 176 |
+
do_convert_rgb: bool = None,
|
| 177 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 178 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 179 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 180 |
+
**kwargs,
|
| 181 |
+
) -> PIL.Image.Image:
|
| 182 |
+
"""
|
| 183 |
+
Preprocess an image or batch of images.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
images (`ImageInput`):
|
| 187 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 188 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 189 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 190 |
+
Whether to resize the image.
|
| 191 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
| 192 |
+
Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
|
| 193 |
+
the longest edge resized to keep the input aspect ratio.
|
| 194 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 195 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 196 |
+
has an effect if `do_resize` is set to `True`.
|
| 197 |
+
do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
|
| 198 |
+
Whether to center crop the image.
|
| 199 |
+
crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
|
| 200 |
+
Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
|
| 201 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 202 |
+
Whether to rescale the image.
|
| 203 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 204 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 205 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 206 |
+
Whether to normalize the image.
|
| 207 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 208 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 209 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 210 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
| 211 |
+
`True`.
|
| 212 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 213 |
+
Whether to convert the image to RGB.
|
| 214 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 215 |
+
The type of tensors to return. Can be one of:
|
| 216 |
+
- Unset: Return a list of `np.ndarray`.
|
| 217 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 218 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 219 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 220 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 221 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 222 |
+
The channel dimension format for the output image. Can be one of:
|
| 223 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 224 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 225 |
+
- Unset: Use the channel dimension format of the input image.
|
| 226 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 227 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 228 |
+
from the input image. Can be one of:
|
| 229 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 230 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 231 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 232 |
+
"""
|
| 233 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 234 |
+
size = size if size is not None else self.size
|
| 235 |
+
size = get_size_dict(size, default_to_square=False)
|
| 236 |
+
resample = resample if resample is not None else self.resample
|
| 237 |
+
do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
|
| 238 |
+
crop_size = crop_size if crop_size is not None else self.crop_size
|
| 239 |
+
crop_size = get_size_dict(crop_size)
|
| 240 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 241 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 242 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 243 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 244 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 245 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 246 |
+
|
| 247 |
+
images = make_list_of_images(images)
|
| 248 |
+
|
| 249 |
+
if not valid_images(images):
|
| 250 |
+
raise ValueError(
|
| 251 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 252 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
if do_resize and size is None:
|
| 256 |
+
raise ValueError("Size must be specified if do_resize is True.")
|
| 257 |
+
|
| 258 |
+
if do_center_crop and crop_size is None:
|
| 259 |
+
raise ValueError("Crop size must be specified if do_center_crop is True.")
|
| 260 |
+
|
| 261 |
+
if do_rescale and rescale_factor is None:
|
| 262 |
+
raise ValueError("Rescale factor must be specified if do_rescale is True.")
|
| 263 |
+
|
| 264 |
+
if do_normalize and (image_mean is None or image_std is None):
|
| 265 |
+
raise ValueError("Image mean and std must be specified if do_normalize is True.")
|
| 266 |
+
|
| 267 |
+
# PIL RGBA images are converted to RGB
|
| 268 |
+
if do_convert_rgb:
|
| 269 |
+
images = [convert_to_rgb(image) for image in images]
|
| 270 |
+
|
| 271 |
+
# All transformations expect numpy arrays.
|
| 272 |
+
images = [to_numpy_array(image) for image in images]
|
| 273 |
+
|
| 274 |
+
if is_scaled_image(images[0]) and do_rescale:
|
| 275 |
+
logger.warning_once(
|
| 276 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 277 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
if input_data_format is None:
|
| 281 |
+
# We assume that all images have the same channel dimension format.
|
| 282 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 283 |
+
|
| 284 |
+
if do_resize:
|
| 285 |
+
images = [
|
| 286 |
+
self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
| 287 |
+
for image in images
|
| 288 |
+
]
|
| 289 |
+
|
| 290 |
+
if do_center_crop:
|
| 291 |
+
images = [
|
| 292 |
+
self.center_crop(image=image, size=crop_size, input_data_format=input_data_format) for image in images
|
| 293 |
+
]
|
| 294 |
+
|
| 295 |
+
if do_rescale:
|
| 296 |
+
images = [
|
| 297 |
+
self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 298 |
+
for image in images
|
| 299 |
+
]
|
| 300 |
+
|
| 301 |
+
if do_normalize:
|
| 302 |
+
images = [
|
| 303 |
+
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 304 |
+
for image in images
|
| 305 |
+
]
|
| 306 |
+
|
| 307 |
+
images = [
|
| 308 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
|
| 309 |
+
]
|
| 310 |
+
|
| 311 |
+
data = {"pixel_values": images}
|
| 312 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/modeling_chinese_clip.py
ADDED
|
@@ -0,0 +1,1564 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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coding=utf-8
|
| 2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" PyTorch Chinese-CLIP model."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import Any, List, Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.utils.checkpoint
|
| 24 |
+
from torch import nn
|
| 25 |
+
|
| 26 |
+
from ...activations import ACT2FN
|
| 27 |
+
from ...modeling_outputs import (
|
| 28 |
+
BaseModelOutput,
|
| 29 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 30 |
+
BaseModelOutputWithPooling,
|
| 31 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 32 |
+
)
|
| 33 |
+
from ...modeling_utils import PreTrainedModel
|
| 34 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 35 |
+
from ...utils import (
|
| 36 |
+
ModelOutput,
|
| 37 |
+
add_code_sample_docstrings,
|
| 38 |
+
add_start_docstrings,
|
| 39 |
+
add_start_docstrings_to_model_forward,
|
| 40 |
+
logging,
|
| 41 |
+
replace_return_docstrings,
|
| 42 |
+
)
|
| 43 |
+
from .configuration_chinese_clip import ChineseCLIPConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
_CHECKPOINT_FOR_DOC = "OFA-Sys/chinese-clip-vit-base-patch16"
|
| 49 |
+
_CONFIG_FOR_DOC = "ChineseCLIPConfig"
|
| 50 |
+
|
| 51 |
+
CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 52 |
+
"OFA-Sys/chinese-clip-vit-base-patch16",
|
| 53 |
+
# See all Chinese-CLIP models at https://huggingface.co/models?filter=chinese_clip
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
|
| 58 |
+
# Copied from transformers.models.clip.modeling_clip.contrastive_loss
|
| 59 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
| 60 |
+
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def chinese_clip_loss(similarity: torch.Tensor) -> torch.Tensor:
|
| 64 |
+
caption_loss = contrastive_loss(similarity)
|
| 65 |
+
image_loss = contrastive_loss(similarity.t())
|
| 66 |
+
return (caption_loss + image_loss) / 2.0
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@dataclass
|
| 70 |
+
class ChineseCLIPOutput(ModelOutput):
|
| 71 |
+
"""
|
| 72 |
+
Args:
|
| 73 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 74 |
+
Contrastive loss for image-text similarity.
|
| 75 |
+
logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
| 76 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
| 77 |
+
similarity scores.
|
| 78 |
+
logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
| 79 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
| 80 |
+
similarity scores.
|
| 81 |
+
text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 82 |
+
The text embeddings obtained by applying the projection layer to the pooled output of
|
| 83 |
+
[`ChineseCLIPTextModel`].
|
| 84 |
+
image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 85 |
+
The image embeddings obtained by applying the projection layer to the pooled output of
|
| 86 |
+
[`ChineseCLIPVisionModel`].
|
| 87 |
+
text_model_output(`BaseModelOutputWithPoolingAndCrossAttentions`):
|
| 88 |
+
The output of the [`ChineseCLIPTextModel`].
|
| 89 |
+
vision_model_output(`BaseModelOutputWithPoolingAndCrossAttentions`):
|
| 90 |
+
The output of the [`ChineseCLIPVisionModel`].
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
loss: Optional[torch.FloatTensor] = None
|
| 94 |
+
logits_per_image: torch.FloatTensor = None
|
| 95 |
+
logits_per_text: torch.FloatTensor = None
|
| 96 |
+
text_embeds: torch.FloatTensor = None
|
| 97 |
+
image_embeds: torch.FloatTensor = None
|
| 98 |
+
text_model_output: BaseModelOutputWithPoolingAndCrossAttentions = None
|
| 99 |
+
vision_model_output: BaseModelOutputWithPoolingAndCrossAttentions = None
|
| 100 |
+
|
| 101 |
+
def to_tuple(self) -> Tuple[Any]:
|
| 102 |
+
return tuple(
|
| 103 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 104 |
+
for k in self.keys()
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# Copied from transformers.models.bert.modeling_bert.BertEmbeddings with Bert->ChineseCLIPText
|
| 109 |
+
class ChineseCLIPTextEmbeddings(nn.Module):
|
| 110 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 111 |
+
|
| 112 |
+
def __init__(self, config):
|
| 113 |
+
super().__init__()
|
| 114 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 115 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 116 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 117 |
+
|
| 118 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 119 |
+
# any TensorFlow checkpoint file
|
| 120 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 121 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 122 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 123 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 124 |
+
self.register_buffer(
|
| 125 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 126 |
+
)
|
| 127 |
+
self.register_buffer(
|
| 128 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
def forward(
|
| 132 |
+
self,
|
| 133 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 134 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 135 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 136 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 137 |
+
past_key_values_length: int = 0,
|
| 138 |
+
) -> torch.Tensor:
|
| 139 |
+
if input_ids is not None:
|
| 140 |
+
input_shape = input_ids.size()
|
| 141 |
+
else:
|
| 142 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 143 |
+
|
| 144 |
+
seq_length = input_shape[1]
|
| 145 |
+
|
| 146 |
+
if position_ids is None:
|
| 147 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 148 |
+
|
| 149 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 150 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 151 |
+
# issue #5664
|
| 152 |
+
if token_type_ids is None:
|
| 153 |
+
if hasattr(self, "token_type_ids"):
|
| 154 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 155 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 156 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 157 |
+
else:
|
| 158 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 159 |
+
|
| 160 |
+
if inputs_embeds is None:
|
| 161 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 162 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 163 |
+
|
| 164 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 165 |
+
if self.position_embedding_type == "absolute":
|
| 166 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 167 |
+
embeddings += position_embeddings
|
| 168 |
+
embeddings = self.LayerNorm(embeddings)
|
| 169 |
+
embeddings = self.dropout(embeddings)
|
| 170 |
+
return embeddings
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->ChineseCLIP
|
| 174 |
+
class ChineseCLIPVisionEmbeddings(nn.Module):
|
| 175 |
+
def __init__(self, config: ChineseCLIPVisionConfig):
|
| 176 |
+
super().__init__()
|
| 177 |
+
self.config = config
|
| 178 |
+
self.embed_dim = config.hidden_size
|
| 179 |
+
self.image_size = config.image_size
|
| 180 |
+
self.patch_size = config.patch_size
|
| 181 |
+
|
| 182 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
| 183 |
+
|
| 184 |
+
self.patch_embedding = nn.Conv2d(
|
| 185 |
+
in_channels=config.num_channels,
|
| 186 |
+
out_channels=self.embed_dim,
|
| 187 |
+
kernel_size=self.patch_size,
|
| 188 |
+
stride=self.patch_size,
|
| 189 |
+
bias=False,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 193 |
+
self.num_positions = self.num_patches + 1
|
| 194 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
| 195 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
|
| 196 |
+
|
| 197 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 198 |
+
batch_size = pixel_values.shape[0]
|
| 199 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 200 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
|
| 201 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
| 202 |
+
|
| 203 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
| 204 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 205 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
| 206 |
+
return embeddings
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->ChineseCLIPText
|
| 210 |
+
class ChineseCLIPTextSelfAttention(nn.Module):
|
| 211 |
+
def __init__(self, config, position_embedding_type=None):
|
| 212 |
+
super().__init__()
|
| 213 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 214 |
+
raise ValueError(
|
| 215 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 216 |
+
f"heads ({config.num_attention_heads})"
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
self.num_attention_heads = config.num_attention_heads
|
| 220 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 221 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 222 |
+
|
| 223 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 224 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 225 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 226 |
+
|
| 227 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 228 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
| 229 |
+
config, "position_embedding_type", "absolute"
|
| 230 |
+
)
|
| 231 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 232 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 233 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 234 |
+
|
| 235 |
+
self.is_decoder = config.is_decoder
|
| 236 |
+
|
| 237 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 238 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 239 |
+
x = x.view(new_x_shape)
|
| 240 |
+
return x.permute(0, 2, 1, 3)
|
| 241 |
+
|
| 242 |
+
def forward(
|
| 243 |
+
self,
|
| 244 |
+
hidden_states: torch.Tensor,
|
| 245 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 246 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 247 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 248 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 249 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 250 |
+
output_attentions: Optional[bool] = False,
|
| 251 |
+
) -> Tuple[torch.Tensor]:
|
| 252 |
+
mixed_query_layer = self.query(hidden_states)
|
| 253 |
+
|
| 254 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 255 |
+
# and values come from an encoder; the attention mask needs to be
|
| 256 |
+
# such that the encoder's padding tokens are not attended to.
|
| 257 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 258 |
+
|
| 259 |
+
if is_cross_attention and past_key_value is not None:
|
| 260 |
+
# reuse k,v, cross_attentions
|
| 261 |
+
key_layer = past_key_value[0]
|
| 262 |
+
value_layer = past_key_value[1]
|
| 263 |
+
attention_mask = encoder_attention_mask
|
| 264 |
+
elif is_cross_attention:
|
| 265 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 266 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 267 |
+
attention_mask = encoder_attention_mask
|
| 268 |
+
elif past_key_value is not None:
|
| 269 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 270 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 271 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
| 272 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
| 273 |
+
else:
|
| 274 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 275 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 276 |
+
|
| 277 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 278 |
+
|
| 279 |
+
use_cache = past_key_value is not None
|
| 280 |
+
if self.is_decoder:
|
| 281 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 282 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 283 |
+
# key/value_states (first "if" case)
|
| 284 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 285 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 286 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 287 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 288 |
+
past_key_value = (key_layer, value_layer)
|
| 289 |
+
|
| 290 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 291 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 292 |
+
|
| 293 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 294 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
| 295 |
+
if use_cache:
|
| 296 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
| 297 |
+
-1, 1
|
| 298 |
+
)
|
| 299 |
+
else:
|
| 300 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 301 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 302 |
+
distance = position_ids_l - position_ids_r
|
| 303 |
+
|
| 304 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 305 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 306 |
+
|
| 307 |
+
if self.position_embedding_type == "relative_key":
|
| 308 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 309 |
+
attention_scores = attention_scores + relative_position_scores
|
| 310 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 311 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 312 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 313 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 314 |
+
|
| 315 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 316 |
+
if attention_mask is not None:
|
| 317 |
+
# Apply the attention mask is (precomputed for all layers in ChineseCLIPTextModel forward() function)
|
| 318 |
+
attention_scores = attention_scores + attention_mask
|
| 319 |
+
|
| 320 |
+
# Normalize the attention scores to probabilities.
|
| 321 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 322 |
+
|
| 323 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 324 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 325 |
+
attention_probs = self.dropout(attention_probs)
|
| 326 |
+
|
| 327 |
+
# Mask heads if we want to
|
| 328 |
+
if head_mask is not None:
|
| 329 |
+
attention_probs = attention_probs * head_mask
|
| 330 |
+
|
| 331 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 332 |
+
|
| 333 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 334 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 335 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 336 |
+
|
| 337 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 338 |
+
|
| 339 |
+
if self.is_decoder:
|
| 340 |
+
outputs = outputs + (past_key_value,)
|
| 341 |
+
return outputs
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->ChineseCLIPText
|
| 345 |
+
class ChineseCLIPTextSelfOutput(nn.Module):
|
| 346 |
+
def __init__(self, config):
|
| 347 |
+
super().__init__()
|
| 348 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 349 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 350 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 351 |
+
|
| 352 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 353 |
+
hidden_states = self.dense(hidden_states)
|
| 354 |
+
hidden_states = self.dropout(hidden_states)
|
| 355 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 356 |
+
return hidden_states
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->ChineseCLIPText
|
| 360 |
+
class ChineseCLIPTextAttention(nn.Module):
|
| 361 |
+
def __init__(self, config, position_embedding_type=None):
|
| 362 |
+
super().__init__()
|
| 363 |
+
self.self = ChineseCLIPTextSelfAttention(config, position_embedding_type=position_embedding_type)
|
| 364 |
+
self.output = ChineseCLIPTextSelfOutput(config)
|
| 365 |
+
self.pruned_heads = set()
|
| 366 |
+
|
| 367 |
+
def prune_heads(self, heads):
|
| 368 |
+
if len(heads) == 0:
|
| 369 |
+
return
|
| 370 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 371 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
# Prune linear layers
|
| 375 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 376 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 377 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 378 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 379 |
+
|
| 380 |
+
# Update hyper params and store pruned heads
|
| 381 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 382 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 383 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 384 |
+
|
| 385 |
+
def forward(
|
| 386 |
+
self,
|
| 387 |
+
hidden_states: torch.Tensor,
|
| 388 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 389 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 390 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 391 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 392 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 393 |
+
output_attentions: Optional[bool] = False,
|
| 394 |
+
) -> Tuple[torch.Tensor]:
|
| 395 |
+
self_outputs = self.self(
|
| 396 |
+
hidden_states,
|
| 397 |
+
attention_mask,
|
| 398 |
+
head_mask,
|
| 399 |
+
encoder_hidden_states,
|
| 400 |
+
encoder_attention_mask,
|
| 401 |
+
past_key_value,
|
| 402 |
+
output_attentions,
|
| 403 |
+
)
|
| 404 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 405 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 406 |
+
return outputs
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
class ChineseCLIPVisionAttention(nn.Module):
|
| 410 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 411 |
+
|
| 412 |
+
def __init__(self, config):
|
| 413 |
+
super().__init__()
|
| 414 |
+
self.config = config
|
| 415 |
+
self.embed_dim = config.hidden_size
|
| 416 |
+
self.num_heads = config.num_attention_heads
|
| 417 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 418 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 419 |
+
raise ValueError(
|
| 420 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 421 |
+
f" {self.num_heads})."
|
| 422 |
+
)
|
| 423 |
+
self.scale = self.head_dim**-0.5
|
| 424 |
+
self.dropout = config.attention_dropout
|
| 425 |
+
|
| 426 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 427 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 428 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 429 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 430 |
+
|
| 431 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 432 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 433 |
+
|
| 434 |
+
def forward(
|
| 435 |
+
self,
|
| 436 |
+
hidden_states: torch.Tensor,
|
| 437 |
+
output_attentions: Optional[bool] = False,
|
| 438 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 439 |
+
"""Input shape: Batch x Time x Channel"""
|
| 440 |
+
|
| 441 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
| 442 |
+
|
| 443 |
+
# get query proj
|
| 444 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
| 445 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 446 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 447 |
+
|
| 448 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 449 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 450 |
+
key_states = key_states.view(*proj_shape)
|
| 451 |
+
value_states = value_states.view(*proj_shape)
|
| 452 |
+
|
| 453 |
+
src_len = key_states.size(1)
|
| 454 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 455 |
+
|
| 456 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 457 |
+
raise ValueError(
|
| 458 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 459 |
+
f" {attn_weights.size()}"
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 463 |
+
|
| 464 |
+
if output_attentions:
|
| 465 |
+
# this operation is a bit akward, but it's required to
|
| 466 |
+
# make sure that attn_weights keeps its gradient.
|
| 467 |
+
# In order to do so, attn_weights have to reshaped
|
| 468 |
+
# twice and have to be reused in the following
|
| 469 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 470 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 471 |
+
else:
|
| 472 |
+
attn_weights_reshaped = None
|
| 473 |
+
|
| 474 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 475 |
+
|
| 476 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 477 |
+
|
| 478 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 479 |
+
raise ValueError(
|
| 480 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 481 |
+
f" {attn_output.size()}"
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 485 |
+
attn_output = attn_output.transpose(1, 2)
|
| 486 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
| 487 |
+
|
| 488 |
+
attn_output = self.out_proj(attn_output)
|
| 489 |
+
|
| 490 |
+
return attn_output, attn_weights_reshaped
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->ChineseCLIPText
|
| 494 |
+
class ChineseCLIPTextIntermediate(nn.Module):
|
| 495 |
+
def __init__(self, config):
|
| 496 |
+
super().__init__()
|
| 497 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 498 |
+
if isinstance(config.hidden_act, str):
|
| 499 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 500 |
+
else:
|
| 501 |
+
self.intermediate_act_fn = config.hidden_act
|
| 502 |
+
|
| 503 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 504 |
+
hidden_states = self.dense(hidden_states)
|
| 505 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 506 |
+
return hidden_states
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->ChineseCLIPText
|
| 510 |
+
class ChineseCLIPTextOutput(nn.Module):
|
| 511 |
+
def __init__(self, config):
|
| 512 |
+
super().__init__()
|
| 513 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 514 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 515 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 516 |
+
|
| 517 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 518 |
+
hidden_states = self.dense(hidden_states)
|
| 519 |
+
hidden_states = self.dropout(hidden_states)
|
| 520 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 521 |
+
return hidden_states
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->ChineseCLIPVision
|
| 525 |
+
class ChineseCLIPVisionMLP(nn.Module):
|
| 526 |
+
def __init__(self, config):
|
| 527 |
+
super().__init__()
|
| 528 |
+
self.config = config
|
| 529 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 530 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 531 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 532 |
+
|
| 533 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 534 |
+
hidden_states = self.fc1(hidden_states)
|
| 535 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 536 |
+
hidden_states = self.fc2(hidden_states)
|
| 537 |
+
return hidden_states
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
# Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->ChineseCLIPText
|
| 541 |
+
class ChineseCLIPTextLayer(nn.Module):
|
| 542 |
+
def __init__(self, config):
|
| 543 |
+
super().__init__()
|
| 544 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 545 |
+
self.seq_len_dim = 1
|
| 546 |
+
self.attention = ChineseCLIPTextAttention(config)
|
| 547 |
+
self.is_decoder = config.is_decoder
|
| 548 |
+
self.add_cross_attention = config.add_cross_attention
|
| 549 |
+
if self.add_cross_attention:
|
| 550 |
+
if not self.is_decoder:
|
| 551 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 552 |
+
self.crossattention = ChineseCLIPTextAttention(config, position_embedding_type="absolute")
|
| 553 |
+
self.intermediate = ChineseCLIPTextIntermediate(config)
|
| 554 |
+
self.output = ChineseCLIPTextOutput(config)
|
| 555 |
+
|
| 556 |
+
def forward(
|
| 557 |
+
self,
|
| 558 |
+
hidden_states: torch.Tensor,
|
| 559 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 560 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 561 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 562 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 563 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 564 |
+
output_attentions: Optional[bool] = False,
|
| 565 |
+
) -> Tuple[torch.Tensor]:
|
| 566 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 567 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 568 |
+
self_attention_outputs = self.attention(
|
| 569 |
+
hidden_states,
|
| 570 |
+
attention_mask,
|
| 571 |
+
head_mask,
|
| 572 |
+
output_attentions=output_attentions,
|
| 573 |
+
past_key_value=self_attn_past_key_value,
|
| 574 |
+
)
|
| 575 |
+
attention_output = self_attention_outputs[0]
|
| 576 |
+
|
| 577 |
+
# if decoder, the last output is tuple of self-attn cache
|
| 578 |
+
if self.is_decoder:
|
| 579 |
+
outputs = self_attention_outputs[1:-1]
|
| 580 |
+
present_key_value = self_attention_outputs[-1]
|
| 581 |
+
else:
|
| 582 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 583 |
+
|
| 584 |
+
cross_attn_present_key_value = None
|
| 585 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 586 |
+
if not hasattr(self, "crossattention"):
|
| 587 |
+
raise ValueError(
|
| 588 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 589 |
+
" by setting `config.add_cross_attention=True`"
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
| 593 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 594 |
+
cross_attention_outputs = self.crossattention(
|
| 595 |
+
attention_output,
|
| 596 |
+
attention_mask,
|
| 597 |
+
head_mask,
|
| 598 |
+
encoder_hidden_states,
|
| 599 |
+
encoder_attention_mask,
|
| 600 |
+
cross_attn_past_key_value,
|
| 601 |
+
output_attentions,
|
| 602 |
+
)
|
| 603 |
+
attention_output = cross_attention_outputs[0]
|
| 604 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 605 |
+
|
| 606 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
| 607 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
| 608 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 609 |
+
|
| 610 |
+
layer_output = apply_chunking_to_forward(
|
| 611 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 612 |
+
)
|
| 613 |
+
outputs = (layer_output,) + outputs
|
| 614 |
+
|
| 615 |
+
# if decoder, return the attn key/values as the last output
|
| 616 |
+
if self.is_decoder:
|
| 617 |
+
outputs = outputs + (present_key_value,)
|
| 618 |
+
|
| 619 |
+
return outputs
|
| 620 |
+
|
| 621 |
+
def feed_forward_chunk(self, attention_output):
|
| 622 |
+
intermediate_output = self.intermediate(attention_output)
|
| 623 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 624 |
+
return layer_output
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
class ChineseCLIPVisionLayer(nn.Module):
|
| 628 |
+
def __init__(self, config: ChineseCLIPConfig):
|
| 629 |
+
super().__init__()
|
| 630 |
+
self.embed_dim = config.hidden_size
|
| 631 |
+
self.self_attn = ChineseCLIPVisionAttention(config)
|
| 632 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 633 |
+
self.mlp = ChineseCLIPVisionMLP(config)
|
| 634 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 635 |
+
|
| 636 |
+
def forward(
|
| 637 |
+
self,
|
| 638 |
+
hidden_states: torch.Tensor,
|
| 639 |
+
output_attentions: Optional[bool] = False,
|
| 640 |
+
) -> Tuple[torch.FloatTensor]:
|
| 641 |
+
"""
|
| 642 |
+
Args:
|
| 643 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 644 |
+
output_attentions (`bool`, *optional*):
|
| 645 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 646 |
+
returned tensors for more detail.
|
| 647 |
+
"""
|
| 648 |
+
residual = hidden_states
|
| 649 |
+
|
| 650 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 651 |
+
hidden_states, attn_weights = self.self_attn(
|
| 652 |
+
hidden_states=hidden_states,
|
| 653 |
+
output_attentions=output_attentions,
|
| 654 |
+
)
|
| 655 |
+
hidden_states = residual + hidden_states
|
| 656 |
+
|
| 657 |
+
residual = hidden_states
|
| 658 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 659 |
+
hidden_states = self.mlp(hidden_states)
|
| 660 |
+
hidden_states = residual + hidden_states
|
| 661 |
+
|
| 662 |
+
outputs = (hidden_states,)
|
| 663 |
+
|
| 664 |
+
if output_attentions:
|
| 665 |
+
outputs += (attn_weights,)
|
| 666 |
+
|
| 667 |
+
return outputs
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->ChineseCLIPText
|
| 671 |
+
class ChineseCLIPTextPooler(nn.Module):
|
| 672 |
+
def __init__(self, config):
|
| 673 |
+
super().__init__()
|
| 674 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 675 |
+
self.activation = nn.Tanh()
|
| 676 |
+
|
| 677 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 678 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 679 |
+
# to the first token.
|
| 680 |
+
first_token_tensor = hidden_states[:, 0]
|
| 681 |
+
pooled_output = self.dense(first_token_tensor)
|
| 682 |
+
pooled_output = self.activation(pooled_output)
|
| 683 |
+
return pooled_output
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
class ChineseCLIPPreTrainedModel(PreTrainedModel):
|
| 687 |
+
"""
|
| 688 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 689 |
+
models.
|
| 690 |
+
"""
|
| 691 |
+
|
| 692 |
+
config_class = ChineseCLIPConfig
|
| 693 |
+
base_model_prefix = "chinese_clip"
|
| 694 |
+
supports_gradient_checkpointing = True
|
| 695 |
+
|
| 696 |
+
def _init_weights(self, module):
|
| 697 |
+
"""Initialize the weights"""
|
| 698 |
+
factor = self.config.initializer_factor
|
| 699 |
+
if isinstance(module, ChineseCLIPVisionEmbeddings):
|
| 700 |
+
factor = self.config.initializer_factor
|
| 701 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
| 702 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
| 703 |
+
nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
|
| 704 |
+
elif isinstance(module, ChineseCLIPTextEmbeddings):
|
| 705 |
+
nn.init.normal_(module.word_embeddings.weight, mean=0.0, std=self.config.initializer_range)
|
| 706 |
+
nn.init.normal_(module.position_embeddings.weight, mean=0.0, std=self.config.initializer_range)
|
| 707 |
+
nn.init.normal_(module.token_type_embeddings.weight, mean=0.0, std=self.config.initializer_range)
|
| 708 |
+
for embedding in [module.word_embeddings, module.position_embeddings, module.token_type_embeddings]:
|
| 709 |
+
if embedding.padding_idx is not None:
|
| 710 |
+
embedding.weight.data[embedding.padding_idx].zero_()
|
| 711 |
+
elif isinstance(module, ChineseCLIPVisionAttention):
|
| 712 |
+
factor = self.config.initializer_factor
|
| 713 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 714 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
| 715 |
+
nn.init.normal_(module.q_proj.weight, std=in_proj_std)
|
| 716 |
+
nn.init.normal_(module.k_proj.weight, std=in_proj_std)
|
| 717 |
+
nn.init.normal_(module.v_proj.weight, std=in_proj_std)
|
| 718 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
| 719 |
+
elif isinstance(module, ChineseCLIPVisionMLP):
|
| 720 |
+
factor = self.config.initializer_factor
|
| 721 |
+
in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 722 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
| 723 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
| 724 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
| 725 |
+
elif isinstance(module, ChineseCLIPModel):
|
| 726 |
+
nn.init.normal_(
|
| 727 |
+
module.text_projection.weight,
|
| 728 |
+
std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
|
| 729 |
+
)
|
| 730 |
+
nn.init.normal_(
|
| 731 |
+
module.visual_projection.weight,
|
| 732 |
+
std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
if isinstance(module, nn.LayerNorm):
|
| 736 |
+
module.bias.data.zero_()
|
| 737 |
+
module.weight.data.fill_(1.0)
|
| 738 |
+
if isinstance(module, nn.Linear):
|
| 739 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 740 |
+
if module.bias is not None:
|
| 741 |
+
module.bias.data.zero_()
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
CHINESE_CLIP_START_DOCSTRING = r"""
|
| 745 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 746 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 747 |
+
behavior.
|
| 748 |
+
|
| 749 |
+
Parameters:
|
| 750 |
+
config ([`ChineseCLIPConfig`]): Model configuration class with all the parameters of the model.
|
| 751 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 752 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 753 |
+
"""
|
| 754 |
+
|
| 755 |
+
CHINESE_CLIP_TEXT_INPUTS_DOCSTRING = r"""
|
| 756 |
+
Args:
|
| 757 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 758 |
+
Indices of input sequence tokens in the vocabulary.
|
| 759 |
+
|
| 760 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 761 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 762 |
+
|
| 763 |
+
[What are input IDs?](../glossary#input-ids)
|
| 764 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 765 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 766 |
+
|
| 767 |
+
- 1 for tokens that are **not masked**,
|
| 768 |
+
- 0 for tokens that are **masked**.
|
| 769 |
+
|
| 770 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 771 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 772 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 773 |
+
1]`:
|
| 774 |
+
|
| 775 |
+
- 0 corresponds to a *sentence A* token,
|
| 776 |
+
- 1 corresponds to a *sentence B* token.
|
| 777 |
+
|
| 778 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 779 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 780 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 781 |
+
config.max_position_embeddings - 1]`.
|
| 782 |
+
|
| 783 |
+
[What are position IDs?](../glossary#position-ids)
|
| 784 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 785 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 786 |
+
|
| 787 |
+
- 1 indicates the head is **not masked**,
|
| 788 |
+
- 0 indicates the head is **masked**.
|
| 789 |
+
|
| 790 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 791 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 792 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 793 |
+
model's internal embedding lookup matrix.
|
| 794 |
+
output_attentions (`bool`, *optional*):
|
| 795 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 796 |
+
tensors for more detail.
|
| 797 |
+
output_hidden_states (`bool`, *optional*):
|
| 798 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 799 |
+
more detail.
|
| 800 |
+
return_dict (`bool`, *optional*):
|
| 801 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 802 |
+
"""
|
| 803 |
+
|
| 804 |
+
CHINESE_CLIP_VISION_INPUTS_DOCSTRING = r"""
|
| 805 |
+
Args:
|
| 806 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 807 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 808 |
+
[`AutoImageProcessor`]. See [`ChineseCLIPImageProcessor.__call__`] for details.
|
| 809 |
+
output_attentions (`bool`, *optional*):
|
| 810 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 811 |
+
tensors for more detail.
|
| 812 |
+
output_hidden_states (`bool`, *optional*):
|
| 813 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 814 |
+
more detail.
|
| 815 |
+
return_dict (`bool`, *optional*):
|
| 816 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 817 |
+
"""
|
| 818 |
+
|
| 819 |
+
CHINESE_CLIP_INPUTS_DOCSTRING = r"""
|
| 820 |
+
Args:
|
| 821 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 822 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 823 |
+
it.
|
| 824 |
+
|
| 825 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 826 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 827 |
+
|
| 828 |
+
[What are input IDs?](../glossary#input-ids)
|
| 829 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 830 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 831 |
+
|
| 832 |
+
- 1 for tokens that are **not masked**,
|
| 833 |
+
- 0 for tokens that are **masked**.
|
| 834 |
+
|
| 835 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 836 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 837 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 838 |
+
1]`:
|
| 839 |
+
|
| 840 |
+
- 0 corresponds to a *sentence A* token,
|
| 841 |
+
- 1 corresponds to a *sentence B* token.
|
| 842 |
+
|
| 843 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 844 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 845 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 846 |
+
config.max_position_embeddings - 1]`.
|
| 847 |
+
|
| 848 |
+
[What are position IDs?](../glossary#position-ids)
|
| 849 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 850 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 851 |
+
[`AutoImageProcessor`]. See [`ChineseCLIPImageProcessor.__call__`] for details.
|
| 852 |
+
return_loss (`bool`, *optional*):
|
| 853 |
+
Whether or not to return the contrastive loss.
|
| 854 |
+
output_attentions (`bool`, *optional*):
|
| 855 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 856 |
+
tensors for more detail.
|
| 857 |
+
output_hidden_states (`bool`, *optional*):
|
| 858 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 859 |
+
more detail.
|
| 860 |
+
return_dict (`bool`, *optional*):
|
| 861 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 862 |
+
"""
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
# Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->ChineseCLIPText
|
| 866 |
+
class ChineseCLIPTextEncoder(nn.Module):
|
| 867 |
+
def __init__(self, config):
|
| 868 |
+
super().__init__()
|
| 869 |
+
self.config = config
|
| 870 |
+
self.layer = nn.ModuleList([ChineseCLIPTextLayer(config) for _ in range(config.num_hidden_layers)])
|
| 871 |
+
self.gradient_checkpointing = False
|
| 872 |
+
|
| 873 |
+
def forward(
|
| 874 |
+
self,
|
| 875 |
+
hidden_states: torch.Tensor,
|
| 876 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 877 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 878 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 879 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 880 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 881 |
+
use_cache: Optional[bool] = None,
|
| 882 |
+
output_attentions: Optional[bool] = False,
|
| 883 |
+
output_hidden_states: Optional[bool] = False,
|
| 884 |
+
return_dict: Optional[bool] = True,
|
| 885 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
| 886 |
+
all_hidden_states = () if output_hidden_states else None
|
| 887 |
+
all_self_attentions = () if output_attentions else None
|
| 888 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 889 |
+
|
| 890 |
+
if self.gradient_checkpointing and self.training:
|
| 891 |
+
if use_cache:
|
| 892 |
+
logger.warning_once(
|
| 893 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 894 |
+
)
|
| 895 |
+
use_cache = False
|
| 896 |
+
|
| 897 |
+
next_decoder_cache = () if use_cache else None
|
| 898 |
+
for i, layer_module in enumerate(self.layer):
|
| 899 |
+
if output_hidden_states:
|
| 900 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 901 |
+
|
| 902 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 903 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 904 |
+
|
| 905 |
+
if self.gradient_checkpointing and self.training:
|
| 906 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 907 |
+
layer_module.__call__,
|
| 908 |
+
hidden_states,
|
| 909 |
+
attention_mask,
|
| 910 |
+
layer_head_mask,
|
| 911 |
+
encoder_hidden_states,
|
| 912 |
+
encoder_attention_mask,
|
| 913 |
+
past_key_value,
|
| 914 |
+
output_attentions,
|
| 915 |
+
)
|
| 916 |
+
else:
|
| 917 |
+
layer_outputs = layer_module(
|
| 918 |
+
hidden_states,
|
| 919 |
+
attention_mask,
|
| 920 |
+
layer_head_mask,
|
| 921 |
+
encoder_hidden_states,
|
| 922 |
+
encoder_attention_mask,
|
| 923 |
+
past_key_value,
|
| 924 |
+
output_attentions,
|
| 925 |
+
)
|
| 926 |
+
|
| 927 |
+
hidden_states = layer_outputs[0]
|
| 928 |
+
if use_cache:
|
| 929 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 930 |
+
if output_attentions:
|
| 931 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 932 |
+
if self.config.add_cross_attention:
|
| 933 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 934 |
+
|
| 935 |
+
if output_hidden_states:
|
| 936 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 937 |
+
|
| 938 |
+
if not return_dict:
|
| 939 |
+
return tuple(
|
| 940 |
+
v
|
| 941 |
+
for v in [
|
| 942 |
+
hidden_states,
|
| 943 |
+
next_decoder_cache,
|
| 944 |
+
all_hidden_states,
|
| 945 |
+
all_self_attentions,
|
| 946 |
+
all_cross_attentions,
|
| 947 |
+
]
|
| 948 |
+
if v is not None
|
| 949 |
+
)
|
| 950 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 951 |
+
last_hidden_state=hidden_states,
|
| 952 |
+
past_key_values=next_decoder_cache,
|
| 953 |
+
hidden_states=all_hidden_states,
|
| 954 |
+
attentions=all_self_attentions,
|
| 955 |
+
cross_attentions=all_cross_attentions,
|
| 956 |
+
)
|
| 957 |
+
|
| 958 |
+
|
| 959 |
+
class ChineseCLIPVisionEncoder(nn.Module):
|
| 960 |
+
"""
|
| 961 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 962 |
+
[`ChineseCLIPVisionEncoderLayer`].
|
| 963 |
+
|
| 964 |
+
Args:
|
| 965 |
+
config: ChineseCLIPConfig
|
| 966 |
+
"""
|
| 967 |
+
|
| 968 |
+
def __init__(self, config: ChineseCLIPConfig):
|
| 969 |
+
super().__init__()
|
| 970 |
+
self.config = config
|
| 971 |
+
self.layers = nn.ModuleList([ChineseCLIPVisionLayer(config) for _ in range(config.num_hidden_layers)])
|
| 972 |
+
self.gradient_checkpointing = False
|
| 973 |
+
|
| 974 |
+
def forward(
|
| 975 |
+
self,
|
| 976 |
+
inputs_embeds,
|
| 977 |
+
output_attentions: Optional[bool] = None,
|
| 978 |
+
output_hidden_states: Optional[bool] = None,
|
| 979 |
+
return_dict: Optional[bool] = None,
|
| 980 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 981 |
+
r"""
|
| 982 |
+
Args:
|
| 983 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 984 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 985 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 986 |
+
than the model's internal embedding lookup matrix.
|
| 987 |
+
output_attentions (`bool`, *optional*):
|
| 988 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 989 |
+
returned tensors for more detail.
|
| 990 |
+
output_hidden_states (`bool`, *optional*):
|
| 991 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 992 |
+
for more detail.
|
| 993 |
+
return_dict (`bool`, *optional*):
|
| 994 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 995 |
+
"""
|
| 996 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 997 |
+
output_hidden_states = (
|
| 998 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 999 |
+
)
|
| 1000 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1001 |
+
|
| 1002 |
+
encoder_states = () if output_hidden_states else None
|
| 1003 |
+
all_attentions = () if output_attentions else None
|
| 1004 |
+
|
| 1005 |
+
hidden_states = inputs_embeds
|
| 1006 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 1007 |
+
if output_hidden_states:
|
| 1008 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 1009 |
+
if self.gradient_checkpointing and self.training:
|
| 1010 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 1011 |
+
encoder_layer.__call__,
|
| 1012 |
+
hidden_states,
|
| 1013 |
+
output_attentions,
|
| 1014 |
+
)
|
| 1015 |
+
else:
|
| 1016 |
+
layer_outputs = encoder_layer(
|
| 1017 |
+
hidden_states,
|
| 1018 |
+
output_attentions=output_attentions,
|
| 1019 |
+
)
|
| 1020 |
+
|
| 1021 |
+
hidden_states = layer_outputs[0]
|
| 1022 |
+
|
| 1023 |
+
if output_attentions:
|
| 1024 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 1025 |
+
|
| 1026 |
+
if output_hidden_states:
|
| 1027 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 1028 |
+
|
| 1029 |
+
if not return_dict:
|
| 1030 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 1031 |
+
return BaseModelOutput(
|
| 1032 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 1033 |
+
)
|
| 1034 |
+
|
| 1035 |
+
|
| 1036 |
+
class ChineseCLIPVisionTransformer(nn.Module):
|
| 1037 |
+
def __init__(self, config: ChineseCLIPVisionConfig):
|
| 1038 |
+
super().__init__()
|
| 1039 |
+
self.config = config
|
| 1040 |
+
embed_dim = config.hidden_size
|
| 1041 |
+
|
| 1042 |
+
self.embeddings = ChineseCLIPVisionEmbeddings(config)
|
| 1043 |
+
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 1044 |
+
self.encoder = ChineseCLIPVisionEncoder(config)
|
| 1045 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 1046 |
+
|
| 1047 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_VISION_INPUTS_DOCSTRING)
|
| 1048 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=ChineseCLIPVisionConfig)
|
| 1049 |
+
def forward(
|
| 1050 |
+
self,
|
| 1051 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1052 |
+
output_attentions: Optional[bool] = None,
|
| 1053 |
+
output_hidden_states: Optional[bool] = None,
|
| 1054 |
+
return_dict: Optional[bool] = None,
|
| 1055 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 1056 |
+
r"""
|
| 1057 |
+
Returns:
|
| 1058 |
+
"""
|
| 1059 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1060 |
+
output_hidden_states = (
|
| 1061 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1062 |
+
)
|
| 1063 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1064 |
+
|
| 1065 |
+
if pixel_values is None:
|
| 1066 |
+
raise ValueError("You have to specify pixel_values")
|
| 1067 |
+
|
| 1068 |
+
hidden_states = self.embeddings(pixel_values)
|
| 1069 |
+
hidden_states = self.pre_layrnorm(hidden_states)
|
| 1070 |
+
|
| 1071 |
+
encoder_outputs = self.encoder(
|
| 1072 |
+
inputs_embeds=hidden_states,
|
| 1073 |
+
output_attentions=output_attentions,
|
| 1074 |
+
output_hidden_states=output_hidden_states,
|
| 1075 |
+
return_dict=return_dict,
|
| 1076 |
+
)
|
| 1077 |
+
|
| 1078 |
+
last_hidden_state = encoder_outputs[0]
|
| 1079 |
+
pooled_output = last_hidden_state[:, 0, :]
|
| 1080 |
+
pooled_output = self.post_layernorm(pooled_output)
|
| 1081 |
+
|
| 1082 |
+
if not return_dict:
|
| 1083 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 1084 |
+
|
| 1085 |
+
return BaseModelOutputWithPooling(
|
| 1086 |
+
last_hidden_state=last_hidden_state,
|
| 1087 |
+
pooler_output=pooled_output,
|
| 1088 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1089 |
+
attentions=encoder_outputs.attentions,
|
| 1090 |
+
)
|
| 1091 |
+
|
| 1092 |
+
|
| 1093 |
+
@add_start_docstrings(
|
| 1094 |
+
"The text model from CHINESE_CLIP without any head or projection on top.",
|
| 1095 |
+
CHINESE_CLIP_START_DOCSTRING,
|
| 1096 |
+
)
|
| 1097 |
+
class ChineseCLIPTextModel(ChineseCLIPPreTrainedModel):
|
| 1098 |
+
"""
|
| 1099 |
+
|
| 1100 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 1101 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
| 1102 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
| 1103 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
| 1104 |
+
|
| 1105 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
| 1106 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
| 1107 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
| 1108 |
+
"""
|
| 1109 |
+
|
| 1110 |
+
config_class = ChineseCLIPTextConfig
|
| 1111 |
+
|
| 1112 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 1113 |
+
super().__init__(config)
|
| 1114 |
+
self.config = config
|
| 1115 |
+
|
| 1116 |
+
self.embeddings = ChineseCLIPTextEmbeddings(config)
|
| 1117 |
+
self.encoder = ChineseCLIPTextEncoder(config)
|
| 1118 |
+
|
| 1119 |
+
self.pooler = ChineseCLIPTextPooler(config) if add_pooling_layer else None
|
| 1120 |
+
|
| 1121 |
+
# Initialize weights and apply final processing
|
| 1122 |
+
self.post_init()
|
| 1123 |
+
|
| 1124 |
+
def get_input_embeddings(self):
|
| 1125 |
+
return self.embeddings.word_embeddings
|
| 1126 |
+
|
| 1127 |
+
def set_input_embeddings(self, value):
|
| 1128 |
+
self.embeddings.word_embeddings = value
|
| 1129 |
+
|
| 1130 |
+
def _prune_heads(self, heads_to_prune):
|
| 1131 |
+
"""
|
| 1132 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 1133 |
+
class PreTrainedModel
|
| 1134 |
+
"""
|
| 1135 |
+
for layer, heads in heads_to_prune.items():
|
| 1136 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 1137 |
+
|
| 1138 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1139 |
+
@add_code_sample_docstrings(
|
| 1140 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1141 |
+
output_type=BaseModelOutputWithPoolingAndCrossAttentions,
|
| 1142 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1143 |
+
)
|
| 1144 |
+
def forward(
|
| 1145 |
+
self,
|
| 1146 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1147 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1148 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1149 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1150 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1151 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1152 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1153 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1154 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1155 |
+
use_cache: Optional[bool] = None,
|
| 1156 |
+
output_attentions: Optional[bool] = None,
|
| 1157 |
+
output_hidden_states: Optional[bool] = None,
|
| 1158 |
+
return_dict: Optional[bool] = None,
|
| 1159 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
| 1160 |
+
r"""
|
| 1161 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1162 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 1163 |
+
the model is configured as a decoder.
|
| 1164 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1165 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 1166 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1167 |
+
|
| 1168 |
+
- 1 for tokens that are **not masked**,
|
| 1169 |
+
- 0 for tokens that are **masked**.
|
| 1170 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
| 1171 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 1172 |
+
|
| 1173 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 1174 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 1175 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1176 |
+
use_cache (`bool`, *optional*):
|
| 1177 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 1178 |
+
`past_key_values`).
|
| 1179 |
+
"""
|
| 1180 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1181 |
+
output_hidden_states = (
|
| 1182 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1183 |
+
)
|
| 1184 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1185 |
+
|
| 1186 |
+
if self.config.is_decoder:
|
| 1187 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1188 |
+
else:
|
| 1189 |
+
use_cache = False
|
| 1190 |
+
|
| 1191 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1192 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 1193 |
+
elif input_ids is not None:
|
| 1194 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 1195 |
+
input_shape = input_ids.size()
|
| 1196 |
+
elif inputs_embeds is not None:
|
| 1197 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1198 |
+
else:
|
| 1199 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1200 |
+
|
| 1201 |
+
batch_size, seq_length = input_shape
|
| 1202 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 1203 |
+
|
| 1204 |
+
# past_key_values_length
|
| 1205 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 1206 |
+
|
| 1207 |
+
if attention_mask is None:
|
| 1208 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
| 1209 |
+
|
| 1210 |
+
if token_type_ids is None:
|
| 1211 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 1212 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 1213 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 1214 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 1215 |
+
else:
|
| 1216 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 1217 |
+
|
| 1218 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 1219 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 1220 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 1221 |
+
|
| 1222 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
| 1223 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 1224 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
| 1225 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
| 1226 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
| 1227 |
+
if encoder_attention_mask is None:
|
| 1228 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
| 1229 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
| 1230 |
+
else:
|
| 1231 |
+
encoder_extended_attention_mask = None
|
| 1232 |
+
|
| 1233 |
+
# Prepare head mask if needed
|
| 1234 |
+
# 1.0 in head_mask indicate we keep the head
|
| 1235 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 1236 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 1237 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 1238 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 1239 |
+
|
| 1240 |
+
embedding_output = self.embeddings(
|
| 1241 |
+
input_ids=input_ids,
|
| 1242 |
+
position_ids=position_ids,
|
| 1243 |
+
token_type_ids=token_type_ids,
|
| 1244 |
+
inputs_embeds=inputs_embeds,
|
| 1245 |
+
past_key_values_length=past_key_values_length,
|
| 1246 |
+
)
|
| 1247 |
+
encoder_outputs = self.encoder(
|
| 1248 |
+
embedding_output,
|
| 1249 |
+
attention_mask=extended_attention_mask,
|
| 1250 |
+
head_mask=head_mask,
|
| 1251 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1252 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 1253 |
+
past_key_values=past_key_values,
|
| 1254 |
+
use_cache=use_cache,
|
| 1255 |
+
output_attentions=output_attentions,
|
| 1256 |
+
output_hidden_states=output_hidden_states,
|
| 1257 |
+
return_dict=return_dict,
|
| 1258 |
+
)
|
| 1259 |
+
sequence_output = encoder_outputs[0]
|
| 1260 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 1261 |
+
|
| 1262 |
+
if not return_dict:
|
| 1263 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 1264 |
+
|
| 1265 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
| 1266 |
+
last_hidden_state=sequence_output,
|
| 1267 |
+
pooler_output=pooled_output,
|
| 1268 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 1269 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1270 |
+
attentions=encoder_outputs.attentions,
|
| 1271 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 1272 |
+
)
|
| 1273 |
+
|
| 1274 |
+
|
| 1275 |
+
@add_start_docstrings(
|
| 1276 |
+
"""The vision model from CHINESE_CLIP without any head or projection on top.""",
|
| 1277 |
+
CHINESE_CLIP_START_DOCSTRING,
|
| 1278 |
+
)
|
| 1279 |
+
class ChineseCLIPVisionModel(ChineseCLIPPreTrainedModel):
|
| 1280 |
+
config_class = ChineseCLIPVisionConfig
|
| 1281 |
+
main_input_name = "pixel_values"
|
| 1282 |
+
|
| 1283 |
+
def __init__(self, config: ChineseCLIPVisionConfig):
|
| 1284 |
+
super().__init__(config)
|
| 1285 |
+
self.vision_model = ChineseCLIPVisionTransformer(config)
|
| 1286 |
+
# Initialize weights and apply final processing
|
| 1287 |
+
self.post_init()
|
| 1288 |
+
|
| 1289 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1290 |
+
return self.vision_model.embeddings.patch_embedding
|
| 1291 |
+
|
| 1292 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_VISION_INPUTS_DOCSTRING)
|
| 1293 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=ChineseCLIPVisionConfig)
|
| 1294 |
+
def forward(
|
| 1295 |
+
self,
|
| 1296 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1297 |
+
output_attentions: Optional[bool] = None,
|
| 1298 |
+
output_hidden_states: Optional[bool] = None,
|
| 1299 |
+
return_dict: Optional[bool] = None,
|
| 1300 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 1301 |
+
r"""
|
| 1302 |
+
Returns:
|
| 1303 |
+
|
| 1304 |
+
Examples:
|
| 1305 |
+
|
| 1306 |
+
```python
|
| 1307 |
+
>>> from PIL import Image
|
| 1308 |
+
>>> import requests
|
| 1309 |
+
>>> from transformers import CLIPProcessor, ChineseCLIPVisionModel
|
| 1310 |
+
|
| 1311 |
+
>>> model = ChineseCLIPVisionModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1312 |
+
>>> processor = CLIPProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1313 |
+
|
| 1314 |
+
>>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg"
|
| 1315 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1316 |
+
|
| 1317 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1318 |
+
|
| 1319 |
+
>>> outputs = model(**inputs)
|
| 1320 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 1321 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
| 1322 |
+
```"""
|
| 1323 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1324 |
+
|
| 1325 |
+
return self.vision_model(
|
| 1326 |
+
pixel_values=pixel_values,
|
| 1327 |
+
output_attentions=output_attentions,
|
| 1328 |
+
output_hidden_states=output_hidden_states,
|
| 1329 |
+
return_dict=return_dict,
|
| 1330 |
+
)
|
| 1331 |
+
|
| 1332 |
+
|
| 1333 |
+
@add_start_docstrings(CHINESE_CLIP_START_DOCSTRING)
|
| 1334 |
+
class ChineseCLIPModel(ChineseCLIPPreTrainedModel):
|
| 1335 |
+
config_class = ChineseCLIPConfig
|
| 1336 |
+
|
| 1337 |
+
def __init__(self, config: ChineseCLIPConfig):
|
| 1338 |
+
super().__init__(config)
|
| 1339 |
+
|
| 1340 |
+
if not isinstance(config.text_config, ChineseCLIPTextConfig):
|
| 1341 |
+
raise ValueError(
|
| 1342 |
+
"config.text_config is expected to be of type ChineseCLIPTextConfig but is of type"
|
| 1343 |
+
f" {type(config.text_config)}."
|
| 1344 |
+
)
|
| 1345 |
+
|
| 1346 |
+
if not isinstance(config.vision_config, ChineseCLIPVisionConfig):
|
| 1347 |
+
raise ValueError(
|
| 1348 |
+
"config.vision_config is expected to be of type ChineseCLIPVisionConfig but is of type"
|
| 1349 |
+
f" {type(config.vision_config)}."
|
| 1350 |
+
)
|
| 1351 |
+
|
| 1352 |
+
text_config = config.text_config
|
| 1353 |
+
vision_config = config.vision_config
|
| 1354 |
+
|
| 1355 |
+
self.projection_dim = config.projection_dim
|
| 1356 |
+
self.text_embed_dim = text_config.hidden_size
|
| 1357 |
+
self.vision_embed_dim = vision_config.hidden_size
|
| 1358 |
+
|
| 1359 |
+
self.text_model = ChineseCLIPTextModel(text_config, add_pooling_layer=False)
|
| 1360 |
+
self.vision_model = ChineseCLIPVisionTransformer(vision_config)
|
| 1361 |
+
|
| 1362 |
+
self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
|
| 1363 |
+
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
|
| 1364 |
+
self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
|
| 1365 |
+
|
| 1366 |
+
# Initialize weights and apply final processing
|
| 1367 |
+
self.post_init()
|
| 1368 |
+
|
| 1369 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_TEXT_INPUTS_DOCSTRING)
|
| 1370 |
+
def get_text_features(
|
| 1371 |
+
self,
|
| 1372 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1373 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1374 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1375 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1376 |
+
output_attentions: Optional[bool] = None,
|
| 1377 |
+
output_hidden_states: Optional[bool] = None,
|
| 1378 |
+
return_dict: Optional[bool] = None,
|
| 1379 |
+
) -> torch.FloatTensor:
|
| 1380 |
+
r"""
|
| 1381 |
+
Returns:
|
| 1382 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
| 1383 |
+
applying the projection layer to the final [CLS] hidden state of Text-Transformer.
|
| 1384 |
+
|
| 1385 |
+
Examples:
|
| 1386 |
+
|
| 1387 |
+
```python
|
| 1388 |
+
>>> from transformers import AutoTokenizer, ChineseCLIPModel
|
| 1389 |
+
|
| 1390 |
+
>>> model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1391 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1392 |
+
|
| 1393 |
+
>>> inputs = tokenizer(["杰尼龟", "妙蛙种子", "小火龙", "皮卡丘"], padding=True, return_tensors="pt")
|
| 1394 |
+
>>> text_features = model.get_text_features(**inputs)
|
| 1395 |
+
>>> text_features = text_features / text_features.norm(p=2, dim=-1, keepdim=True)
|
| 1396 |
+
```"""
|
| 1397 |
+
# Use CHINESE_CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1398 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1399 |
+
output_hidden_states = (
|
| 1400 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1401 |
+
)
|
| 1402 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1403 |
+
|
| 1404 |
+
text_outputs = self.text_model(
|
| 1405 |
+
input_ids=input_ids,
|
| 1406 |
+
attention_mask=attention_mask,
|
| 1407 |
+
token_type_ids=token_type_ids,
|
| 1408 |
+
position_ids=position_ids,
|
| 1409 |
+
output_attentions=output_attentions,
|
| 1410 |
+
output_hidden_states=output_hidden_states,
|
| 1411 |
+
return_dict=return_dict,
|
| 1412 |
+
)
|
| 1413 |
+
|
| 1414 |
+
pooled_output = text_outputs[0][:, 0, :]
|
| 1415 |
+
text_features = self.text_projection(pooled_output)
|
| 1416 |
+
|
| 1417 |
+
return text_features
|
| 1418 |
+
|
| 1419 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_VISION_INPUTS_DOCSTRING)
|
| 1420 |
+
def get_image_features(
|
| 1421 |
+
self,
|
| 1422 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1423 |
+
output_attentions: Optional[bool] = None,
|
| 1424 |
+
output_hidden_states: Optional[bool] = None,
|
| 1425 |
+
return_dict: Optional[bool] = None,
|
| 1426 |
+
) -> torch.FloatTensor:
|
| 1427 |
+
r"""
|
| 1428 |
+
Returns:
|
| 1429 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
| 1430 |
+
applying the projection layer to the final [CLS] hidden state of Vision-Transformer.
|
| 1431 |
+
|
| 1432 |
+
Examples:
|
| 1433 |
+
|
| 1434 |
+
```python
|
| 1435 |
+
>>> from PIL import Image
|
| 1436 |
+
>>> import requests
|
| 1437 |
+
>>> from transformers import AutoProcessor, ChineseCLIPModel
|
| 1438 |
+
|
| 1439 |
+
>>> model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1440 |
+
>>> processor = AutoProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1441 |
+
|
| 1442 |
+
>>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg"
|
| 1443 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1444 |
+
|
| 1445 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1446 |
+
|
| 1447 |
+
>>> image_features = model.get_image_features(**inputs)
|
| 1448 |
+
>>> image_features = image_features / image_features.norm(p=2, dim=-1, keepdim=True)
|
| 1449 |
+
```"""
|
| 1450 |
+
# Use CHINESE_CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1451 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1452 |
+
output_hidden_states = (
|
| 1453 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1454 |
+
)
|
| 1455 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1456 |
+
|
| 1457 |
+
vision_outputs = self.vision_model(
|
| 1458 |
+
pixel_values=pixel_values,
|
| 1459 |
+
output_attentions=output_attentions,
|
| 1460 |
+
output_hidden_states=output_hidden_states,
|
| 1461 |
+
return_dict=return_dict,
|
| 1462 |
+
)
|
| 1463 |
+
|
| 1464 |
+
pooled_output = vision_outputs[1] # pooled_output
|
| 1465 |
+
image_features = self.visual_projection(pooled_output)
|
| 1466 |
+
|
| 1467 |
+
return image_features
|
| 1468 |
+
|
| 1469 |
+
@add_start_docstrings_to_model_forward(CHINESE_CLIP_INPUTS_DOCSTRING)
|
| 1470 |
+
@replace_return_docstrings(output_type=ChineseCLIPOutput, config_class=ChineseCLIPConfig)
|
| 1471 |
+
def forward(
|
| 1472 |
+
self,
|
| 1473 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1474 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1475 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1476 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1477 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1478 |
+
return_loss: Optional[bool] = None,
|
| 1479 |
+
output_attentions: Optional[bool] = None,
|
| 1480 |
+
output_hidden_states: Optional[bool] = None,
|
| 1481 |
+
return_dict: Optional[bool] = None,
|
| 1482 |
+
) -> Union[Tuple, ChineseCLIPOutput]:
|
| 1483 |
+
r"""
|
| 1484 |
+
Returns:
|
| 1485 |
+
|
| 1486 |
+
Examples:
|
| 1487 |
+
|
| 1488 |
+
```python
|
| 1489 |
+
>>> from PIL import Image
|
| 1490 |
+
>>> import requests
|
| 1491 |
+
>>> from transformers import AutoProcessor, ChineseCLIPModel
|
| 1492 |
+
|
| 1493 |
+
>>> model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1494 |
+
>>> processor = AutoProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
|
| 1495 |
+
|
| 1496 |
+
>>> url = "https://clip-cn-beijing.oss-cn-beijing.aliyuncs.com/pokemon.jpeg"
|
| 1497 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1498 |
+
|
| 1499 |
+
>>> inputs = processor(text=["杰尼龟", "妙蛙种子", "小火龙", "皮卡丘"], images=image, return_tensors="pt", padding=True)
|
| 1500 |
+
|
| 1501 |
+
>>> outputs = model(**inputs)
|
| 1502 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
| 1503 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
| 1504 |
+
```"""
|
| 1505 |
+
# Use CHINESE_CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1506 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1507 |
+
output_hidden_states = (
|
| 1508 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1509 |
+
)
|
| 1510 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1511 |
+
|
| 1512 |
+
vision_outputs = self.vision_model(
|
| 1513 |
+
pixel_values=pixel_values,
|
| 1514 |
+
output_attentions=output_attentions,
|
| 1515 |
+
output_hidden_states=output_hidden_states,
|
| 1516 |
+
return_dict=return_dict,
|
| 1517 |
+
)
|
| 1518 |
+
|
| 1519 |
+
text_outputs = self.text_model(
|
| 1520 |
+
input_ids=input_ids,
|
| 1521 |
+
attention_mask=attention_mask,
|
| 1522 |
+
token_type_ids=token_type_ids,
|
| 1523 |
+
position_ids=position_ids,
|
| 1524 |
+
output_attentions=output_attentions,
|
| 1525 |
+
output_hidden_states=output_hidden_states,
|
| 1526 |
+
return_dict=return_dict,
|
| 1527 |
+
)
|
| 1528 |
+
|
| 1529 |
+
image_embeds = vision_outputs[1]
|
| 1530 |
+
image_embeds = self.visual_projection(image_embeds)
|
| 1531 |
+
|
| 1532 |
+
text_embeds = text_outputs[0][:, 0, :]
|
| 1533 |
+
text_embeds = self.text_projection(text_embeds)
|
| 1534 |
+
|
| 1535 |
+
# normalized features
|
| 1536 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1537 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1538 |
+
|
| 1539 |
+
# cosine similarity as logits
|
| 1540 |
+
logit_scale = self.logit_scale.exp()
|
| 1541 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
|
| 1542 |
+
logits_per_image = logits_per_text.t()
|
| 1543 |
+
|
| 1544 |
+
loss = None
|
| 1545 |
+
if return_loss:
|
| 1546 |
+
loss = chinese_clip_loss(logits_per_text)
|
| 1547 |
+
|
| 1548 |
+
if not return_dict:
|
| 1549 |
+
# fix the None pooled_output of text_outputs to conform with dict_output
|
| 1550 |
+
pooled_output = text_outputs[1]
|
| 1551 |
+
if pooled_output is None:
|
| 1552 |
+
text_outputs = (text_outputs[0],) + text_outputs[2:]
|
| 1553 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
| 1554 |
+
return ((loss,) + output) if loss is not None else output
|
| 1555 |
+
|
| 1556 |
+
return ChineseCLIPOutput(
|
| 1557 |
+
loss=loss,
|
| 1558 |
+
logits_per_image=logits_per_image,
|
| 1559 |
+
logits_per_text=logits_per_text,
|
| 1560 |
+
text_embeds=text_embeds,
|
| 1561 |
+
image_embeds=image_embeds,
|
| 1562 |
+
text_model_output=text_outputs,
|
| 1563 |
+
vision_model_output=vision_outputs,
|
| 1564 |
+
)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/chinese_clip/processing_chinese_clip.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The OFA-Sys Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Image/Text processor class for Chinese-CLIP
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import warnings
|
| 20 |
+
|
| 21 |
+
from ...processing_utils import ProcessorMixin
|
| 22 |
+
from ...tokenization_utils_base import BatchEncoding
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ChineseCLIPProcessor(ProcessorMixin):
|
| 26 |
+
r"""
|
| 27 |
+
Constructs a Chinese-CLIP processor which wraps a Chinese-CLIP image processor and a Chinese-CLIP tokenizer into a
|
| 28 |
+
single processor.
|
| 29 |
+
|
| 30 |
+
[`ChineseCLIPProcessor`] offers all the functionalities of [`ChineseCLIPImageProcessor`] and [`BertTokenizerFast`].
|
| 31 |
+
See the [`~ChineseCLIPProcessor.__call__`] and [`~ChineseCLIPProcessor.decode`] for more information.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
image_processor ([`ChineseCLIPImageProcessor`], *optional*):
|
| 35 |
+
The image processor is a required input.
|
| 36 |
+
tokenizer ([`BertTokenizerFast`], *optional*):
|
| 37 |
+
The tokenizer is a required input.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
attributes = ["image_processor", "tokenizer"]
|
| 41 |
+
image_processor_class = "ChineseCLIPImageProcessor"
|
| 42 |
+
tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
|
| 43 |
+
|
| 44 |
+
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
|
| 45 |
+
feature_extractor = None
|
| 46 |
+
if "feature_extractor" in kwargs:
|
| 47 |
+
warnings.warn(
|
| 48 |
+
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
|
| 49 |
+
" instead.",
|
| 50 |
+
FutureWarning,
|
| 51 |
+
)
|
| 52 |
+
feature_extractor = kwargs.pop("feature_extractor")
|
| 53 |
+
|
| 54 |
+
image_processor = image_processor if image_processor is not None else feature_extractor
|
| 55 |
+
if image_processor is None:
|
| 56 |
+
raise ValueError("You need to specify an `image_processor`.")
|
| 57 |
+
if tokenizer is None:
|
| 58 |
+
raise ValueError("You need to specify a `tokenizer`.")
|
| 59 |
+
|
| 60 |
+
super().__init__(image_processor, tokenizer)
|
| 61 |
+
self.current_processor = self.image_processor
|
| 62 |
+
|
| 63 |
+
def __call__(self, text=None, images=None, return_tensors=None, **kwargs):
|
| 64 |
+
"""
|
| 65 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
| 66 |
+
and `kwargs` arguments to BertTokenizerFast's [`~BertTokenizerFast.__call__`] if `text` is not `None` to encode
|
| 67 |
+
the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
|
| 68 |
+
CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
|
| 69 |
+
of the above two methods for more information.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
| 73 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 74 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 75 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 76 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
| 77 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 78 |
+
tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
|
| 79 |
+
number of channels, H and W are image height and width.
|
| 80 |
+
|
| 81 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 82 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 83 |
+
|
| 84 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 85 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 86 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 87 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 88 |
+
|
| 89 |
+
Returns:
|
| 90 |
+
[`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
|
| 91 |
+
|
| 92 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 93 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 94 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 95 |
+
`None`).
|
| 96 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
if text is None and images is None:
|
| 100 |
+
raise ValueError("You have to specify either text or images. Both cannot be none.")
|
| 101 |
+
|
| 102 |
+
if text is not None:
|
| 103 |
+
encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)
|
| 104 |
+
|
| 105 |
+
if images is not None:
|
| 106 |
+
image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs)
|
| 107 |
+
|
| 108 |
+
if text is not None and images is not None:
|
| 109 |
+
encoding["pixel_values"] = image_features.pixel_values
|
| 110 |
+
return encoding
|
| 111 |
+
elif text is not None:
|
| 112 |
+
return encoding
|
| 113 |
+
else:
|
| 114 |
+
return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
|
| 115 |
+
|
| 116 |
+
def batch_decode(self, *args, **kwargs):
|
| 117 |
+
"""
|
| 118 |
+
This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 119 |
+
refer to the docstring of this method for more information.
|
| 120 |
+
"""
|
| 121 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 122 |
+
|
| 123 |
+
def decode(self, *args, **kwargs):
|
| 124 |
+
"""
|
| 125 |
+
This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
| 126 |
+
the docstring of this method for more information.
|
| 127 |
+
"""
|
| 128 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 129 |
+
|
| 130 |
+
@property
|
| 131 |
+
def model_input_names(self):
|
| 132 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 133 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 134 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
| 135 |
+
|
| 136 |
+
@property
|
| 137 |
+
def feature_extractor_class(self):
|
| 138 |
+
warnings.warn(
|
| 139 |
+
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
|
| 140 |
+
FutureWarning,
|
| 141 |
+
)
|
| 142 |
+
return self.image_processor_class
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__pycache__/configuration_efficientformer.cpython-310.pyc
ADDED
|
Binary file (7.02 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/__pycache__/modeling_efficientformer.cpython-310.pyc
ADDED
|
Binary file (27.9 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/efficientformer/configuration_efficientformer.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
""" EfficientFormer model configuration"""
|
| 16 |
+
|
| 17 |
+
from typing import List
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PretrainedConfig
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 26 |
+
"snap-research/efficientformer-l1-300": (
|
| 27 |
+
"https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json"
|
| 28 |
+
),
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class EfficientFormerConfig(PretrainedConfig):
|
| 33 |
+
r"""
|
| 34 |
+
This is the configuration class to store the configuration of an [`EfficientFormerModel`]. It is used to
|
| 35 |
+
instantiate an EfficientFormer model according to the specified arguments, defining the model architecture.
|
| 36 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the EfficientFormer
|
| 37 |
+
[snap-research/efficientformer-l1](https://huggingface.co/snap-research/efficientformer-l1) architecture.
|
| 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 |
+
depths (`List(int)`, *optional*, defaults to `[3, 2, 6, 4]`)
|
| 44 |
+
Depth of each stage.
|
| 45 |
+
hidden_sizes (`List(int)`, *optional*, defaults to `[48, 96, 224, 448]`)
|
| 46 |
+
Dimensionality of each stage.
|
| 47 |
+
downsamples (`List(bool)`, *optional*, defaults to `[True, True, True, True]`)
|
| 48 |
+
Whether or not to downsample inputs between two stages.
|
| 49 |
+
dim (`int`, *optional*, defaults to 448):
|
| 50 |
+
Number of channels in Meta3D layers
|
| 51 |
+
key_dim (`int`, *optional*, defaults to 32):
|
| 52 |
+
The size of the key in meta3D block.
|
| 53 |
+
attention_ratio (`int`, *optional*, defaults to 4):
|
| 54 |
+
Ratio of the dimension of the query and value to the dimension of the key in MSHA block
|
| 55 |
+
resolution (`int`, *optional*, defaults to 7)
|
| 56 |
+
Size of each patch
|
| 57 |
+
num_hidden_layers (`int`, *optional*, defaults to 5):
|
| 58 |
+
Number of hidden layers in the Transformer encoder.
|
| 59 |
+
num_attention_heads (`int`, *optional*, defaults to 8):
|
| 60 |
+
Number of attention heads for each attention layer in the 3D MetaBlock.
|
| 61 |
+
mlp_expansion_ratio (`int`, *optional*, defaults to 4):
|
| 62 |
+
Ratio of size of the hidden dimensionality of an MLP to the dimensionality of its input.
|
| 63 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 64 |
+
The dropout probability for all fully connected layers in the embeddings and encoder.
|
| 65 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 66 |
+
The size (resolution) of each patch.
|
| 67 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 68 |
+
The number of input channels.
|
| 69 |
+
pool_size (`int`, *optional*, defaults to 3):
|
| 70 |
+
Kernel size of pooling layers.
|
| 71 |
+
downsample_patch_size (`int`, *optional*, defaults to 3):
|
| 72 |
+
The size of patches in downsampling layers.
|
| 73 |
+
downsample_stride (`int`, *optional*, defaults to 2):
|
| 74 |
+
The stride of convolution kernels in downsampling layers.
|
| 75 |
+
downsample_pad (`int`, *optional*, defaults to 1):
|
| 76 |
+
Padding in downsampling layers.
|
| 77 |
+
drop_path_rate (`int`, *optional*, defaults to 0):
|
| 78 |
+
Rate at which to increase dropout probability in DropPath.
|
| 79 |
+
num_meta3d_blocks (`int`, *optional*, defaults to 1):
|
| 80 |
+
The number of 3D MetaBlocks in the last stage.
|
| 81 |
+
distillation (`bool`, *optional*, defaults to `True`):
|
| 82 |
+
Whether to add a distillation head.
|
| 83 |
+
use_layer_scale (`bool`, *optional*, defaults to `True`):
|
| 84 |
+
Whether to scale outputs from token mixers.
|
| 85 |
+
layer_scale_init_value (`float`, *optional*, defaults to 1e-5):
|
| 86 |
+
Factor by which outputs from token mixers are scaled.
|
| 87 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 88 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 89 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 90 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 91 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 92 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 93 |
+
The epsilon used by the layer normalization layers.
|
| 94 |
+
image_size (`int`, *optional*, defaults to `224`):
|
| 95 |
+
The size (resolution) of each image.
|
| 96 |
+
|
| 97 |
+
Example:
|
| 98 |
+
|
| 99 |
+
```python
|
| 100 |
+
>>> from transformers import EfficientFormerConfig, EfficientFormerModel
|
| 101 |
+
|
| 102 |
+
>>> # Initializing a EfficientFormer efficientformer-l1 style configuration
|
| 103 |
+
>>> configuration = EfficientFormerConfig()
|
| 104 |
+
|
| 105 |
+
>>> # Initializing a EfficientFormerModel (with random weights) from the efficientformer-l3 style configuration
|
| 106 |
+
>>> model = EfficientFormerModel(configuration)
|
| 107 |
+
|
| 108 |
+
>>> # Accessing the model configuration
|
| 109 |
+
>>> configuration = model.config
|
| 110 |
+
```"""
|
| 111 |
+
|
| 112 |
+
model_type = "efficientformer"
|
| 113 |
+
|
| 114 |
+
def __init__(
|
| 115 |
+
self,
|
| 116 |
+
depths: List[int] = [3, 2, 6, 4],
|
| 117 |
+
hidden_sizes: List[int] = [48, 96, 224, 448],
|
| 118 |
+
downsamples: List[bool] = [True, True, True, True],
|
| 119 |
+
dim: int = 448,
|
| 120 |
+
key_dim: int = 32,
|
| 121 |
+
attention_ratio: int = 4,
|
| 122 |
+
resolution: int = 7,
|
| 123 |
+
num_hidden_layers: int = 5,
|
| 124 |
+
num_attention_heads: int = 8,
|
| 125 |
+
mlp_expansion_ratio: int = 4,
|
| 126 |
+
hidden_dropout_prob: float = 0.0,
|
| 127 |
+
patch_size: int = 16,
|
| 128 |
+
num_channels: int = 3,
|
| 129 |
+
pool_size: int = 3,
|
| 130 |
+
downsample_patch_size: int = 3,
|
| 131 |
+
downsample_stride: int = 2,
|
| 132 |
+
downsample_pad: int = 1,
|
| 133 |
+
drop_path_rate: float = 0.0,
|
| 134 |
+
num_meta3d_blocks: int = 1,
|
| 135 |
+
distillation: bool = True,
|
| 136 |
+
use_layer_scale: bool = True,
|
| 137 |
+
layer_scale_init_value: float = 1e-5,
|
| 138 |
+
hidden_act: str = "gelu",
|
| 139 |
+
initializer_range: float = 0.02,
|
| 140 |
+
layer_norm_eps: float = 1e-12,
|
| 141 |
+
image_size: int = 224,
|
| 142 |
+
batch_norm_eps: float = 1e-05,
|
| 143 |
+
**kwargs,
|
| 144 |
+
) -> None:
|
| 145 |
+
super().__init__(**kwargs)
|
| 146 |
+
|
| 147 |
+
self.hidden_act = hidden_act
|
| 148 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 149 |
+
self.hidden_sizes = hidden_sizes
|
| 150 |
+
self.num_hidden_layers = num_hidden_layers
|
| 151 |
+
self.num_attention_heads = num_attention_heads
|
| 152 |
+
self.initializer_range = initializer_range
|
| 153 |
+
self.layer_norm_eps = layer_norm_eps
|
| 154 |
+
self.patch_size = patch_size
|
| 155 |
+
self.num_channels = num_channels
|
| 156 |
+
self.depths = depths
|
| 157 |
+
self.mlp_expansion_ratio = mlp_expansion_ratio
|
| 158 |
+
self.downsamples = downsamples
|
| 159 |
+
self.dim = dim
|
| 160 |
+
self.key_dim = key_dim
|
| 161 |
+
self.attention_ratio = attention_ratio
|
| 162 |
+
self.resolution = resolution
|
| 163 |
+
self.pool_size = pool_size
|
| 164 |
+
self.downsample_patch_size = downsample_patch_size
|
| 165 |
+
self.downsample_stride = downsample_stride
|
| 166 |
+
self.downsample_pad = downsample_pad
|
| 167 |
+
self.drop_path_rate = drop_path_rate
|
| 168 |
+
self.num_meta3d_blocks = num_meta3d_blocks
|
| 169 |
+
self.distillation = distillation
|
| 170 |
+
self.use_layer_scale = use_layer_scale
|
| 171 |
+
self.layer_scale_init_value = layer_scale_init_value
|
| 172 |
+
self.image_size = image_size
|
| 173 |
+
self.batch_norm_eps = batch_norm_eps
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_import_structure = {
|
| 20 |
+
"configuration_graphormer": ["GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "GraphormerConfig"],
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
if not is_torch_available():
|
| 25 |
+
raise OptionalDependencyNotAvailable()
|
| 26 |
+
except OptionalDependencyNotAvailable:
|
| 27 |
+
pass
|
| 28 |
+
else:
|
| 29 |
+
_import_structure["modeling_graphormer"] = [
|
| 30 |
+
"GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 31 |
+
"GraphormerForGraphClassification",
|
| 32 |
+
"GraphormerModel",
|
| 33 |
+
"GraphormerPreTrainedModel",
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if TYPE_CHECKING:
|
| 38 |
+
from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
if not is_torch_available():
|
| 42 |
+
raise OptionalDependencyNotAvailable()
|
| 43 |
+
except OptionalDependencyNotAvailable:
|
| 44 |
+
pass
|
| 45 |
+
else:
|
| 46 |
+
from .modeling_graphormer import (
|
| 47 |
+
GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 48 |
+
GraphormerForGraphClassification,
|
| 49 |
+
GraphormerModel,
|
| 50 |
+
GraphormerPreTrainedModel,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
else:
|
| 55 |
+
import sys
|
| 56 |
+
|
| 57 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (985 Bytes). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/collating_graphormer.cpython-310.pyc
ADDED
|
Binary file (4.74 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/configuration_graphormer.cpython-310.pyc
ADDED
|
Binary file (9.19 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/algos_graphormer.pyx
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation and HuggingFace
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
import cython
|
| 5 |
+
|
| 6 |
+
cimport numpy
|
| 7 |
+
from cython.parallel cimport parallel, prange
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Reduce this number if matrices are too big for large graphs
|
| 13 |
+
UNREACHABLE_NODE_DISTANCE = 510
|
| 14 |
+
|
| 15 |
+
def floyd_warshall(adjacency_matrix):
|
| 16 |
+
"""
|
| 17 |
+
Applies the Floyd-Warshall algorithm to the adjacency matrix, to compute the
|
| 18 |
+
shortest paths distance between all nodes, up to UNREACHABLE_NODE_DISTANCE.
|
| 19 |
+
"""
|
| 20 |
+
(nrows, ncols) = adjacency_matrix.shape
|
| 21 |
+
assert nrows == ncols
|
| 22 |
+
cdef unsigned int n = nrows
|
| 23 |
+
|
| 24 |
+
adj_mat_copy = adjacency_matrix.astype(np.int32, order='C', casting='safe', copy=True)
|
| 25 |
+
assert adj_mat_copy.flags['C_CONTIGUOUS']
|
| 26 |
+
cdef numpy.ndarray[numpy.int32_t, ndim=2, mode='c'] M = adj_mat_copy
|
| 27 |
+
cdef numpy.ndarray[numpy.int32_t, ndim=2, mode='c'] path = -1 * np.ones([n, n], dtype=np.int32)
|
| 28 |
+
|
| 29 |
+
cdef unsigned int i, j, k
|
| 30 |
+
cdef numpy.int32_t M_ij, M_ik, cost_ikkj
|
| 31 |
+
cdef numpy.int32_t* M_ptr = &M[0,0]
|
| 32 |
+
cdef numpy.int32_t* M_i_ptr
|
| 33 |
+
cdef numpy.int32_t* M_k_ptr
|
| 34 |
+
|
| 35 |
+
# set unreachable nodes distance to UNREACHABLE_NODE_DISTANCE
|
| 36 |
+
for i in range(n):
|
| 37 |
+
for j in range(n):
|
| 38 |
+
if i == j:
|
| 39 |
+
M[i][j] = 0
|
| 40 |
+
elif M[i][j] == 0:
|
| 41 |
+
M[i][j] = UNREACHABLE_NODE_DISTANCE
|
| 42 |
+
|
| 43 |
+
# floyed algo
|
| 44 |
+
for k in range(n):
|
| 45 |
+
M_k_ptr = M_ptr + n*k
|
| 46 |
+
for i in range(n):
|
| 47 |
+
M_i_ptr = M_ptr + n*i
|
| 48 |
+
M_ik = M_i_ptr[k]
|
| 49 |
+
for j in range(n):
|
| 50 |
+
cost_ikkj = M_ik + M_k_ptr[j]
|
| 51 |
+
M_ij = M_i_ptr[j]
|
| 52 |
+
if M_ij > cost_ikkj:
|
| 53 |
+
M_i_ptr[j] = cost_ikkj
|
| 54 |
+
path[i][j] = k
|
| 55 |
+
|
| 56 |
+
# set unreachable path to UNREACHABLE_NODE_DISTANCE
|
| 57 |
+
for i in range(n):
|
| 58 |
+
for j in range(n):
|
| 59 |
+
if M[i][j] >= UNREACHABLE_NODE_DISTANCE:
|
| 60 |
+
path[i][j] = UNREACHABLE_NODE_DISTANCE
|
| 61 |
+
M[i][j] = UNREACHABLE_NODE_DISTANCE
|
| 62 |
+
|
| 63 |
+
return M, path
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_all_edges(path, i, j):
|
| 67 |
+
"""
|
| 68 |
+
Recursive function to compute all possible paths between two nodes from the graph adjacency matrix.
|
| 69 |
+
"""
|
| 70 |
+
cdef int k = path[i][j]
|
| 71 |
+
if k == -1:
|
| 72 |
+
return []
|
| 73 |
+
else:
|
| 74 |
+
return get_all_edges(path, i, k) + [k] + get_all_edges(path, k, j)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def gen_edge_input(max_dist, path, edge_feat):
|
| 78 |
+
"""
|
| 79 |
+
Generates the full edge feature and adjacency matrix.
|
| 80 |
+
Shape: num_nodes * num_nodes * max_distance_between_nodes * num_edge_features
|
| 81 |
+
Dim 1 is the input node, dim 2 the output node of the edge, dim 3 the depth of the edge, dim 4 the feature
|
| 82 |
+
"""
|
| 83 |
+
(nrows, ncols) = path.shape
|
| 84 |
+
assert nrows == ncols
|
| 85 |
+
cdef unsigned int n = nrows
|
| 86 |
+
cdef unsigned int max_dist_copy = max_dist
|
| 87 |
+
|
| 88 |
+
path_copy = path.astype(long, order='C', casting='safe', copy=True)
|
| 89 |
+
edge_feat_copy = edge_feat.astype(long, order='C', casting='safe', copy=True)
|
| 90 |
+
assert path_copy.flags['C_CONTIGUOUS']
|
| 91 |
+
assert edge_feat_copy.flags['C_CONTIGUOUS']
|
| 92 |
+
|
| 93 |
+
cdef numpy.ndarray[numpy.int32_t, ndim=4, mode='c'] edge_fea_all = -1 * np.ones([n, n, max_dist_copy, edge_feat.shape[-1]], dtype=np.int32)
|
| 94 |
+
cdef unsigned int i, j, k, num_path, cur
|
| 95 |
+
|
| 96 |
+
for i in range(n):
|
| 97 |
+
for j in range(n):
|
| 98 |
+
if i == j:
|
| 99 |
+
continue
|
| 100 |
+
if path_copy[i][j] == UNREACHABLE_NODE_DISTANCE:
|
| 101 |
+
continue
|
| 102 |
+
path = [i] + get_all_edges(path_copy, i, j) + [j]
|
| 103 |
+
num_path = len(path) - 1
|
| 104 |
+
for k in range(num_path):
|
| 105 |
+
edge_fea_all[i, j, k, :] = edge_feat_copy[path[k], path[k+1], :]
|
| 106 |
+
|
| 107 |
+
return edge_fea_all
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/collating_graphormer.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation and HuggingFace
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from typing import Any, Dict, List, Mapping
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
from ...utils import is_cython_available, requires_backends
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
if is_cython_available():
|
| 13 |
+
import pyximport
|
| 14 |
+
|
| 15 |
+
pyximport.install(setup_args={"include_dirs": np.get_include()})
|
| 16 |
+
from . import algos_graphormer # noqa E402
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def convert_to_single_emb(x, offset: int = 512):
|
| 20 |
+
feature_num = x.shape[1] if len(x.shape) > 1 else 1
|
| 21 |
+
feature_offset = 1 + np.arange(0, feature_num * offset, offset, dtype=np.int64)
|
| 22 |
+
x = x + feature_offset
|
| 23 |
+
return x
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def preprocess_item(item, keep_features=True):
|
| 27 |
+
requires_backends(preprocess_item, ["cython"])
|
| 28 |
+
|
| 29 |
+
if keep_features and "edge_attr" in item.keys(): # edge_attr
|
| 30 |
+
edge_attr = np.asarray(item["edge_attr"], dtype=np.int64)
|
| 31 |
+
else:
|
| 32 |
+
edge_attr = np.ones((len(item["edge_index"][0]), 1), dtype=np.int64) # same embedding for all
|
| 33 |
+
|
| 34 |
+
if keep_features and "node_feat" in item.keys(): # input_nodes
|
| 35 |
+
node_feature = np.asarray(item["node_feat"], dtype=np.int64)
|
| 36 |
+
else:
|
| 37 |
+
node_feature = np.ones((item["num_nodes"], 1), dtype=np.int64) # same embedding for all
|
| 38 |
+
|
| 39 |
+
edge_index = np.asarray(item["edge_index"], dtype=np.int64)
|
| 40 |
+
|
| 41 |
+
input_nodes = convert_to_single_emb(node_feature) + 1
|
| 42 |
+
num_nodes = item["num_nodes"]
|
| 43 |
+
|
| 44 |
+
if len(edge_attr.shape) == 1:
|
| 45 |
+
edge_attr = edge_attr[:, None]
|
| 46 |
+
attn_edge_type = np.zeros([num_nodes, num_nodes, edge_attr.shape[-1]], dtype=np.int64)
|
| 47 |
+
attn_edge_type[edge_index[0], edge_index[1]] = convert_to_single_emb(edge_attr) + 1
|
| 48 |
+
|
| 49 |
+
# node adj matrix [num_nodes, num_nodes] bool
|
| 50 |
+
adj = np.zeros([num_nodes, num_nodes], dtype=bool)
|
| 51 |
+
adj[edge_index[0], edge_index[1]] = True
|
| 52 |
+
|
| 53 |
+
shortest_path_result, path = algos_graphormer.floyd_warshall(adj)
|
| 54 |
+
max_dist = np.amax(shortest_path_result)
|
| 55 |
+
|
| 56 |
+
input_edges = algos_graphormer.gen_edge_input(max_dist, path, attn_edge_type)
|
| 57 |
+
attn_bias = np.zeros([num_nodes + 1, num_nodes + 1], dtype=np.single) # with graph token
|
| 58 |
+
|
| 59 |
+
# combine
|
| 60 |
+
item["input_nodes"] = input_nodes + 1 # we shift all indices by one for padding
|
| 61 |
+
item["attn_bias"] = attn_bias
|
| 62 |
+
item["attn_edge_type"] = attn_edge_type
|
| 63 |
+
item["spatial_pos"] = shortest_path_result.astype(np.int64) + 1 # we shift all indices by one for padding
|
| 64 |
+
item["in_degree"] = np.sum(adj, axis=1).reshape(-1) + 1 # we shift all indices by one for padding
|
| 65 |
+
item["out_degree"] = item["in_degree"] # for undirected graph
|
| 66 |
+
item["input_edges"] = input_edges + 1 # we shift all indices by one for padding
|
| 67 |
+
if "labels" not in item:
|
| 68 |
+
item["labels"] = item["y"]
|
| 69 |
+
|
| 70 |
+
return item
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class GraphormerDataCollator:
|
| 74 |
+
def __init__(self, spatial_pos_max=20, on_the_fly_processing=False):
|
| 75 |
+
if not is_cython_available():
|
| 76 |
+
raise ImportError("Graphormer preprocessing needs Cython (pyximport)")
|
| 77 |
+
|
| 78 |
+
self.spatial_pos_max = spatial_pos_max
|
| 79 |
+
self.on_the_fly_processing = on_the_fly_processing
|
| 80 |
+
|
| 81 |
+
def __call__(self, features: List[dict]) -> Dict[str, Any]:
|
| 82 |
+
if self.on_the_fly_processing:
|
| 83 |
+
features = [preprocess_item(i) for i in features]
|
| 84 |
+
|
| 85 |
+
if not isinstance(features[0], Mapping):
|
| 86 |
+
features = [vars(f) for f in features]
|
| 87 |
+
batch = {}
|
| 88 |
+
|
| 89 |
+
max_node_num = max(len(i["input_nodes"]) for i in features)
|
| 90 |
+
node_feat_size = len(features[0]["input_nodes"][0])
|
| 91 |
+
edge_feat_size = len(features[0]["attn_edge_type"][0][0])
|
| 92 |
+
max_dist = max(len(i["input_edges"][0][0]) for i in features)
|
| 93 |
+
edge_input_size = len(features[0]["input_edges"][0][0][0])
|
| 94 |
+
batch_size = len(features)
|
| 95 |
+
|
| 96 |
+
batch["attn_bias"] = torch.zeros(batch_size, max_node_num + 1, max_node_num + 1, dtype=torch.float)
|
| 97 |
+
batch["attn_edge_type"] = torch.zeros(batch_size, max_node_num, max_node_num, edge_feat_size, dtype=torch.long)
|
| 98 |
+
batch["spatial_pos"] = torch.zeros(batch_size, max_node_num, max_node_num, dtype=torch.long)
|
| 99 |
+
batch["in_degree"] = torch.zeros(batch_size, max_node_num, dtype=torch.long)
|
| 100 |
+
batch["input_nodes"] = torch.zeros(batch_size, max_node_num, node_feat_size, dtype=torch.long)
|
| 101 |
+
batch["input_edges"] = torch.zeros(
|
| 102 |
+
batch_size, max_node_num, max_node_num, max_dist, edge_input_size, dtype=torch.long
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
for ix, f in enumerate(features):
|
| 106 |
+
for k in ["attn_bias", "attn_edge_type", "spatial_pos", "in_degree", "input_nodes", "input_edges"]:
|
| 107 |
+
f[k] = torch.tensor(f[k])
|
| 108 |
+
|
| 109 |
+
if len(f["attn_bias"][1:, 1:][f["spatial_pos"] >= self.spatial_pos_max]) > 0:
|
| 110 |
+
f["attn_bias"][1:, 1:][f["spatial_pos"] >= self.spatial_pos_max] = float("-inf")
|
| 111 |
+
|
| 112 |
+
batch["attn_bias"][ix, : f["attn_bias"].shape[0], : f["attn_bias"].shape[1]] = f["attn_bias"]
|
| 113 |
+
batch["attn_edge_type"][ix, : f["attn_edge_type"].shape[0], : f["attn_edge_type"].shape[1], :] = f[
|
| 114 |
+
"attn_edge_type"
|
| 115 |
+
]
|
| 116 |
+
batch["spatial_pos"][ix, : f["spatial_pos"].shape[0], : f["spatial_pos"].shape[1]] = f["spatial_pos"]
|
| 117 |
+
batch["in_degree"][ix, : f["in_degree"].shape[0]] = f["in_degree"]
|
| 118 |
+
batch["input_nodes"][ix, : f["input_nodes"].shape[0], :] = f["input_nodes"]
|
| 119 |
+
batch["input_edges"][
|
| 120 |
+
ix, : f["input_edges"].shape[0], : f["input_edges"].shape[1], : f["input_edges"].shape[2], :
|
| 121 |
+
] = f["input_edges"]
|
| 122 |
+
|
| 123 |
+
batch["out_degree"] = batch["in_degree"]
|
| 124 |
+
|
| 125 |
+
sample = features[0]["labels"]
|
| 126 |
+
if len(sample) == 1: # one task
|
| 127 |
+
if isinstance(sample[0], float): # regression
|
| 128 |
+
batch["labels"] = torch.from_numpy(np.concatenate([i["labels"] for i in features]))
|
| 129 |
+
else: # binary classification
|
| 130 |
+
batch["labels"] = torch.from_numpy(np.concatenate([i["labels"] for i in features]))
|
| 131 |
+
else: # multi task classification, left to float to keep the NaNs
|
| 132 |
+
batch["labels"] = torch.from_numpy(np.stack([i["labels"] for i in features], axis=0))
|
| 133 |
+
|
| 134 |
+
return batch
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/graphormer/configuration_graphormer.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 Microsoft, clefourrier 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 |
+
""" Graphormer model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 24 |
+
# pcqm4mv1 now deprecated
|
| 25 |
+
"graphormer-base": "https://huggingface.co/clefourrier/graphormer-base-pcqm4mv2/resolve/main/config.json",
|
| 26 |
+
# See all Graphormer models at https://huggingface.co/models?filter=graphormer
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class GraphormerConfig(PretrainedConfig):
|
| 31 |
+
r"""
|
| 32 |
+
This is the configuration class to store the configuration of a [`~GraphormerModel`]. It is used to instantiate an
|
| 33 |
+
Graphormer model according to the specified arguments, defining the model architecture. Instantiating a
|
| 34 |
+
configuration with the defaults will yield a similar configuration to that of the Graphormer
|
| 35 |
+
[graphormer-base-pcqm4mv1](https://huggingface.co/graphormer-base-pcqm4mv1) architecture.
|
| 36 |
+
|
| 37 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 38 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
num_classes (`int`, *optional*, defaults to 1):
|
| 43 |
+
Number of target classes or labels, set to n for binary classification of n tasks.
|
| 44 |
+
num_atoms (`int`, *optional*, defaults to 512*9):
|
| 45 |
+
Number of node types in the graphs.
|
| 46 |
+
num_edges (`int`, *optional*, defaults to 512*3):
|
| 47 |
+
Number of edges types in the graph.
|
| 48 |
+
num_in_degree (`int`, *optional*, defaults to 512):
|
| 49 |
+
Number of in degrees types in the input graphs.
|
| 50 |
+
num_out_degree (`int`, *optional*, defaults to 512):
|
| 51 |
+
Number of out degrees types in the input graphs.
|
| 52 |
+
num_edge_dis (`int`, *optional*, defaults to 128):
|
| 53 |
+
Number of edge dis in the input graphs.
|
| 54 |
+
multi_hop_max_dist (`int`, *optional*, defaults to 20):
|
| 55 |
+
Maximum distance of multi hop edges between two nodes.
|
| 56 |
+
spatial_pos_max (`int`, *optional*, defaults to 1024):
|
| 57 |
+
Maximum distance between nodes in the graph attention bias matrices, used during preprocessing and
|
| 58 |
+
collation.
|
| 59 |
+
edge_type (`str`, *optional*, defaults to multihop):
|
| 60 |
+
Type of edge relation chosen.
|
| 61 |
+
max_nodes (`int`, *optional*, defaults to 512):
|
| 62 |
+
Maximum number of nodes which can be parsed for the input graphs.
|
| 63 |
+
share_input_output_embed (`bool`, *optional*, defaults to `False`):
|
| 64 |
+
Shares the embedding layer between encoder and decoder - careful, True is not implemented.
|
| 65 |
+
num_layers (`int`, *optional*, defaults to 12):
|
| 66 |
+
Number of layers.
|
| 67 |
+
embedding_dim (`int`, *optional*, defaults to 768):
|
| 68 |
+
Dimension of the embedding layer in encoder.
|
| 69 |
+
ffn_embedding_dim (`int`, *optional*, defaults to 768):
|
| 70 |
+
Dimension of the "intermediate" (often named feed-forward) layer in encoder.
|
| 71 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 72 |
+
Number of attention heads in the encoder.
|
| 73 |
+
self_attention (`bool`, *optional*, defaults to `True`):
|
| 74 |
+
Model is self attentive (False not implemented).
|
| 75 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 76 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 77 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 78 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 79 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 80 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 81 |
+
The dropout probability for the attention weights.
|
| 82 |
+
activation_dropout (`float`, *optional*, defaults to 0.1):
|
| 83 |
+
The dropout probability for the activation of the linear transformer layer.
|
| 84 |
+
layerdrop (`float`, *optional*, defaults to 0.0):
|
| 85 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 86 |
+
for more details.
|
| 87 |
+
bias (`bool`, *optional*, defaults to `True`):
|
| 88 |
+
Uses bias in the attention module - unsupported at the moment.
|
| 89 |
+
embed_scale(`float`, *optional*, defaults to None):
|
| 90 |
+
Scaling factor for the node embeddings.
|
| 91 |
+
num_trans_layers_to_freeze (`int`, *optional*, defaults to 0):
|
| 92 |
+
Number of transformer layers to freeze.
|
| 93 |
+
encoder_normalize_before (`bool`, *optional*, defaults to `False`):
|
| 94 |
+
Normalize features before encoding the graph.
|
| 95 |
+
pre_layernorm (`bool`, *optional*, defaults to `False`):
|
| 96 |
+
Apply layernorm before self attention and the feed forward network. Without this, post layernorm will be
|
| 97 |
+
used.
|
| 98 |
+
apply_graphormer_init (`bool`, *optional*, defaults to `False`):
|
| 99 |
+
Apply a custom graphormer initialisation to the model before training.
|
| 100 |
+
freeze_embeddings (`bool`, *optional*, defaults to `False`):
|
| 101 |
+
Freeze the embedding layer, or train it along the model.
|
| 102 |
+
encoder_normalize_before (`bool`, *optional*, defaults to `False`):
|
| 103 |
+
Apply the layer norm before each encoder block.
|
| 104 |
+
q_noise (`float`, *optional*, defaults to 0.0):
|
| 105 |
+
Amount of quantization noise (see "Training with Quantization Noise for Extreme Model Compression"). (For
|
| 106 |
+
more detail, see fairseq's documentation on quant_noise).
|
| 107 |
+
qn_block_size (`int`, *optional*, defaults to 8):
|
| 108 |
+
Size of the blocks for subsequent quantization with iPQ (see q_noise).
|
| 109 |
+
kdim (`int`, *optional*, defaults to None):
|
| 110 |
+
Dimension of the key in the attention, if different from the other values.
|
| 111 |
+
vdim (`int`, *optional*, defaults to None):
|
| 112 |
+
Dimension of the value in the attention, if different from the other values.
|
| 113 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 114 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
| 115 |
+
traceable (`bool`, *optional*, defaults to `False`):
|
| 116 |
+
Changes return value of the encoder's inner_state to stacked tensors.
|
| 117 |
+
|
| 118 |
+
Example:
|
| 119 |
+
```python
|
| 120 |
+
>>> from transformers import GraphormerForGraphClassification, GraphormerConfig
|
| 121 |
+
|
| 122 |
+
>>> # Initializing a Graphormer graphormer-base-pcqm4mv2 style configuration
|
| 123 |
+
>>> configuration = GraphormerConfig()
|
| 124 |
+
|
| 125 |
+
>>> # Initializing a model from the graphormer-base-pcqm4mv1 style configuration
|
| 126 |
+
>>> model = GraphormerForGraphClassification(configuration)
|
| 127 |
+
|
| 128 |
+
>>> # Accessing the model configuration
|
| 129 |
+
>>> configuration = model.config
|
| 130 |
+
```
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
model_type = "graphormer"
|
| 134 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 135 |
+
|
| 136 |
+
def __init__(
|
| 137 |
+
self,
|
| 138 |
+
num_classes: int = 1,
|
| 139 |
+
num_atoms: int = 512 * 9,
|
| 140 |
+
num_edges: int = 512 * 3,
|
| 141 |
+
num_in_degree: int = 512,
|
| 142 |
+
num_out_degree: int = 512,
|
| 143 |
+
num_spatial: int = 512,
|
| 144 |
+
num_edge_dis: int = 128,
|
| 145 |
+
multi_hop_max_dist: int = 5, # sometimes is 20
|
| 146 |
+
spatial_pos_max: int = 1024,
|
| 147 |
+
edge_type: str = "multi_hop",
|
| 148 |
+
max_nodes: int = 512,
|
| 149 |
+
share_input_output_embed: bool = False,
|
| 150 |
+
num_hidden_layers: int = 12,
|
| 151 |
+
embedding_dim: int = 768,
|
| 152 |
+
ffn_embedding_dim: int = 768,
|
| 153 |
+
num_attention_heads: int = 32,
|
| 154 |
+
dropout: float = 0.1,
|
| 155 |
+
attention_dropout: float = 0.1,
|
| 156 |
+
activation_dropout: float = 0.1,
|
| 157 |
+
layerdrop: float = 0.0,
|
| 158 |
+
encoder_normalize_before: bool = False,
|
| 159 |
+
pre_layernorm: bool = False,
|
| 160 |
+
apply_graphormer_init: bool = False,
|
| 161 |
+
activation_fn: str = "gelu",
|
| 162 |
+
embed_scale: float = None,
|
| 163 |
+
freeze_embeddings: bool = False,
|
| 164 |
+
num_trans_layers_to_freeze: int = 0,
|
| 165 |
+
traceable: bool = False,
|
| 166 |
+
q_noise: float = 0.0,
|
| 167 |
+
qn_block_size: int = 8,
|
| 168 |
+
kdim: int = None,
|
| 169 |
+
vdim: int = None,
|
| 170 |
+
bias: bool = True,
|
| 171 |
+
self_attention: bool = True,
|
| 172 |
+
pad_token_id=0,
|
| 173 |
+
bos_token_id=1,
|
| 174 |
+
eos_token_id=2,
|
| 175 |
+
**kwargs,
|
| 176 |
+
):
|
| 177 |
+
self.num_classes = num_classes
|
| 178 |
+
self.num_atoms = num_atoms
|
| 179 |
+
self.num_in_degree = num_in_degree
|
| 180 |
+
self.num_out_degree = num_out_degree
|
| 181 |
+
self.num_edges = num_edges
|
| 182 |
+
self.num_spatial = num_spatial
|
| 183 |
+
self.num_edge_dis = num_edge_dis
|
| 184 |
+
self.edge_type = edge_type
|
| 185 |
+
self.multi_hop_max_dist = multi_hop_max_dist
|
| 186 |
+
self.spatial_pos_max = spatial_pos_max
|
| 187 |
+
self.max_nodes = max_nodes
|
| 188 |
+
self.num_hidden_layers = num_hidden_layers
|
| 189 |
+
self.embedding_dim = embedding_dim
|
| 190 |
+
self.hidden_size = embedding_dim
|
| 191 |
+
self.ffn_embedding_dim = ffn_embedding_dim
|
| 192 |
+
self.num_attention_heads = num_attention_heads
|
| 193 |
+
self.dropout = dropout
|
| 194 |
+
self.attention_dropout = attention_dropout
|
| 195 |
+
self.activation_dropout = activation_dropout
|
| 196 |
+
self.layerdrop = layerdrop
|
| 197 |
+
self.encoder_normalize_before = encoder_normalize_before
|
| 198 |
+
self.pre_layernorm = pre_layernorm
|
| 199 |
+
self.apply_graphormer_init = apply_graphormer_init
|
| 200 |
+
self.activation_fn = activation_fn
|
| 201 |
+
self.embed_scale = embed_scale
|
| 202 |
+
self.freeze_embeddings = freeze_embeddings
|
| 203 |
+
self.num_trans_layers_to_freeze = num_trans_layers_to_freeze
|
| 204 |
+
self.share_input_output_embed = share_input_output_embed
|
| 205 |
+
self.traceable = traceable
|
| 206 |
+
self.q_noise = q_noise
|
| 207 |
+
self.qn_block_size = qn_block_size
|
| 208 |
+
|
| 209 |
+
# These parameters are here for future extensions
|
| 210 |
+
# atm, the model only supports self attention
|
| 211 |
+
self.kdim = kdim
|
| 212 |
+
self.vdim = vdim
|
| 213 |
+
self.self_attention = self_attention
|
| 214 |
+
self.bias = bias
|
| 215 |
+
|
| 216 |
+
super().__init__(
|
| 217 |
+
pad_token_id=pad_token_id,
|
| 218 |
+
bos_token_id=bos_token_id,
|
| 219 |
+
eos_token_id=eos_token_id,
|
| 220 |
+
**kwargs,
|
| 221 |
+
)
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/roc_bert/__pycache__/configuration_roc_bert.cpython-310.pyc
ADDED
|
Binary file (7.61 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/vitmatte/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.14 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/vitmatte/__pycache__/configuration_vitmatte.cpython-310.pyc
ADDED
|
Binary file (4.23 kB). View file
|
|
|
evalkit_cambrian/lib/python3.10/site-packages/transformers/models/vitmatte/__pycache__/convert_vitmatte_to_hf.cpython-310.pyc
ADDED
|
Binary file (4.65 kB). View file
|
|
|