Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- deepseek/lib/python3.10/site-packages/tzdata/zoneinfo/America/Grand_Turk +0 -0
- deepseek/lib/python3.10/site-packages/tzdata/zoneinfo/America/Martinique +0 -0
- deepseek/lib/python3.10/site-packages/tzdata/zoneinfo/America/Montevideo +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/generation/__pycache__/tf_utils.cpython-310.pyc +3 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/generation/__pycache__/utils.cpython-310.pyc +3 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/__init__.py +103 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/configuration_bloom.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/convert_bloom_original_checkpoint_to_pytorch.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/modeling_flax_bloom.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/tokenization_bloom_fast.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/configuration_bloom.py +242 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/convert_bloom_original_checkpoint_to_pytorch.py +255 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/modeling_bloom.py +1297 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/modeling_flax_bloom.py +734 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/tokenization_bloom_fast.py +177 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__init__.py +75 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/configuration_deformable_detr.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/convert_deformable_detr_to_pytorch.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/feature_extraction_deformable_detr.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/load_custom.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/modeling_deformable_detr.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/configuration_deformable_detr.py +262 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/convert_deformable_detr_to_pytorch.py +237 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/feature_extraction_deformable_detr.py +33 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/image_processing_deformable_detr.py +1449 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/load_custom.py +49 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/modeling_deformable_detr.py +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/flava/__pycache__/configuration_flava.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/__init__.py +60 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/__pycache__/configuration_m2m_100.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/__pycache__/convert_m2m100_original_checkpoint_to_pytorch.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/__pycache__/modeling_m2m_100.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/__pycache__/tokenization_m2m_100.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/configuration_m2m_100.py +283 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/convert_m2m100_original_checkpoint_to_pytorch.py +85 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/modeling_m2m_100.py +1389 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/tokenization_m2m_100.py +398 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__init__.py +88 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/configuration_mobilenet_v2.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/convert_original_tf_checkpoint_to_pytorch.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/feature_extraction_mobilenet_v2.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/image_processing_mobilenet_v2.cpython-310.pyc +0 -0
- evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/modeling_mobilenet_v2.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -1427,3 +1427,5 @@ evalkit_tf433/lib/python3.10/site-packages/idna/__pycache__/idnadata.cpython-310
|
|
| 1427 |
deepseek/lib/python3.10/site-packages/pyarrow/_parquet.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1428 |
deepseek/lib/python3.10/site-packages/ray/_private/runtime_env/agent/thirdparty_files/idna/__pycache__/uts46data.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1429 |
evalkit_cambrian/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cuda117.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 1427 |
deepseek/lib/python3.10/site-packages/pyarrow/_parquet.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1428 |
deepseek/lib/python3.10/site-packages/ray/_private/runtime_env/agent/thirdparty_files/idna/__pycache__/uts46data.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1429 |
evalkit_cambrian/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cuda117.so filter=lfs diff=lfs merge=lfs -text
|
| 1430 |
+
evalkit_tf433/lib/python3.10/site-packages/transformers/generation/__pycache__/tf_utils.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1431 |
+
evalkit_tf433/lib/python3.10/site-packages/transformers/generation/__pycache__/utils.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
deepseek/lib/python3.10/site-packages/tzdata/zoneinfo/America/Grand_Turk
ADDED
|
Binary file (853 Bytes). View file
|
|
|
deepseek/lib/python3.10/site-packages/tzdata/zoneinfo/America/Martinique
ADDED
|
Binary file (178 Bytes). View file
|
|
|
deepseek/lib/python3.10/site-packages/tzdata/zoneinfo/America/Montevideo
ADDED
|
Binary file (969 Bytes). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/generation/__pycache__/tf_utils.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ee13cb17ae23049a57e6a71231e06d84af19785e0154791586eb3bfc024a57a4
|
| 3 |
+
size 104822
|
evalkit_tf433/lib/python3.10/site-packages/transformers/generation/__pycache__/utils.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7f2593ebc56fdd14d48fef20117c7162d275d21999492f410a4fc68b3f8841c2
|
| 3 |
+
size 148587
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/__init__.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ...utils import (
|
| 18 |
+
OptionalDependencyNotAvailable,
|
| 19 |
+
_LazyModule,
|
| 20 |
+
is_flax_available,
|
| 21 |
+
is_tokenizers_available,
|
| 22 |
+
is_torch_available,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
_import_structure = {
|
| 27 |
+
"configuration_bloom": ["BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP", "BloomConfig", "BloomOnnxConfig"],
|
| 28 |
+
}
|
| 29 |
+
try:
|
| 30 |
+
if not is_tokenizers_available():
|
| 31 |
+
raise OptionalDependencyNotAvailable()
|
| 32 |
+
except OptionalDependencyNotAvailable:
|
| 33 |
+
pass
|
| 34 |
+
else:
|
| 35 |
+
_import_structure["tokenization_bloom_fast"] = ["BloomTokenizerFast"]
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
if not is_torch_available():
|
| 39 |
+
raise OptionalDependencyNotAvailable()
|
| 40 |
+
except OptionalDependencyNotAvailable:
|
| 41 |
+
pass
|
| 42 |
+
else:
|
| 43 |
+
_import_structure["modeling_bloom"] = [
|
| 44 |
+
"BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 45 |
+
"BloomForCausalLM",
|
| 46 |
+
"BloomModel",
|
| 47 |
+
"BloomPreTrainedModel",
|
| 48 |
+
"BloomForSequenceClassification",
|
| 49 |
+
"BloomForTokenClassification",
|
| 50 |
+
"BloomForQuestionAnswering",
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
if not is_flax_available():
|
| 55 |
+
raise OptionalDependencyNotAvailable()
|
| 56 |
+
except OptionalDependencyNotAvailable:
|
| 57 |
+
pass
|
| 58 |
+
else:
|
| 59 |
+
_import_structure["modeling_flax_bloom"] = [
|
| 60 |
+
"FlaxBloomForCausalLM",
|
| 61 |
+
"FlaxBloomModel",
|
| 62 |
+
"FlaxBloomPreTrainedModel",
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if TYPE_CHECKING:
|
| 67 |
+
from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
if not is_tokenizers_available():
|
| 71 |
+
raise OptionalDependencyNotAvailable()
|
| 72 |
+
except OptionalDependencyNotAvailable:
|
| 73 |
+
pass
|
| 74 |
+
else:
|
| 75 |
+
from .tokenization_bloom_fast import BloomTokenizerFast
|
| 76 |
+
|
| 77 |
+
try:
|
| 78 |
+
if not is_torch_available():
|
| 79 |
+
raise OptionalDependencyNotAvailable()
|
| 80 |
+
except OptionalDependencyNotAvailable:
|
| 81 |
+
pass
|
| 82 |
+
else:
|
| 83 |
+
from .modeling_bloom import (
|
| 84 |
+
BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 85 |
+
BloomForCausalLM,
|
| 86 |
+
BloomForQuestionAnswering,
|
| 87 |
+
BloomForSequenceClassification,
|
| 88 |
+
BloomForTokenClassification,
|
| 89 |
+
BloomModel,
|
| 90 |
+
BloomPreTrainedModel,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
if not is_flax_available():
|
| 95 |
+
raise OptionalDependencyNotAvailable()
|
| 96 |
+
except OptionalDependencyNotAvailable:
|
| 97 |
+
pass
|
| 98 |
+
else:
|
| 99 |
+
from .modeling_flax_bloom import FlaxBloomForCausalLM, FlaxBloomModel, FlaxBloomPreTrainedModel
|
| 100 |
+
else:
|
| 101 |
+
import sys
|
| 102 |
+
|
| 103 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.55 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/configuration_bloom.cpython-310.pyc
ADDED
|
Binary file (9.29 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/convert_bloom_original_checkpoint_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (6.26 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/modeling_flax_bloom.cpython-310.pyc
ADDED
|
Binary file (21.2 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/__pycache__/tokenization_bloom_fast.cpython-310.pyc
ADDED
|
Binary file (6.3 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/configuration_bloom.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 the Big Science Workshop and HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Bloom configuration"""
|
| 16 |
+
from collections import OrderedDict
|
| 17 |
+
from typing import TYPE_CHECKING, Any, List, Mapping, Optional
|
| 18 |
+
|
| 19 |
+
from packaging import version
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from ... import PreTrainedTokenizer, TensorType
|
| 24 |
+
|
| 25 |
+
from ...configuration_utils import PretrainedConfig
|
| 26 |
+
from ...onnx import OnnxConfigWithPast, PatchingSpec
|
| 27 |
+
from ...utils import is_torch_available, logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 33 |
+
"bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json",
|
| 34 |
+
"bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json",
|
| 35 |
+
"bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json",
|
| 36 |
+
"bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json",
|
| 37 |
+
"bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json",
|
| 38 |
+
"bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json",
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class BloomConfig(PretrainedConfig):
|
| 43 |
+
"""
|
| 44 |
+
This is the configuration class to store the configuration of a [`BloomModel`]. It is used to instantiate a Bloom
|
| 45 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 46 |
+
defaults will yield a similar configuration to the Bloom architecture
|
| 47 |
+
[bigscience/bloom](https://huggingface.co/bigscience/bloom).
|
| 48 |
+
|
| 49 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 50 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
vocab_size (`int`, *optional*, defaults to 250880):
|
| 55 |
+
Vocabulary size of the Bloom model. Defines the maximum number of different tokens that can be represented
|
| 56 |
+
by the `inputs_ids` passed when calling [`BloomModel`]. Check [this
|
| 57 |
+
discussion](https://huggingface.co/bigscience/bloom/discussions/120#633d28389addb8530b406c2a) on how the
|
| 58 |
+
`vocab_size` has been defined.
|
| 59 |
+
hidden_size (`int`, *optional*, defaults to 64):
|
| 60 |
+
Dimensionality of the embeddings and hidden states.
|
| 61 |
+
n_layer (`int`, *optional*, defaults to 2):
|
| 62 |
+
Number of hidden layers in the Transformer encoder.
|
| 63 |
+
n_head (`int`, *optional*, defaults to 8):
|
| 64 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 65 |
+
layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
|
| 66 |
+
The epsilon to use in the layer normalization layers.
|
| 67 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 68 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 69 |
+
apply_residual_connection_post_layernorm (`bool`, *optional*, defaults to `False`):
|
| 70 |
+
If enabled, use the layer norm of the hidden states as the residual in the transformer blocks
|
| 71 |
+
hidden_dropout (`float`, *optional*, defaults to 0.1):
|
| 72 |
+
Dropout rate of the dropout function on the bias dropout.
|
| 73 |
+
attention_dropout (`float`, *optional*, defaults to 0.1):
|
| 74 |
+
Dropout rate applied to the attention probs
|
| 75 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 76 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
| 77 |
+
pretraining_tp (`int`, *optional*, defaults to `1`):
|
| 78 |
+
Experimental feature. Tensor parallelism rank used during pretraining with Megatron. Please refer to [this
|
| 79 |
+
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
| 80 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
| 81 |
+
issue](https://github.com/pytorch/pytorch/issues/76232). Note also that this is enabled only when
|
| 82 |
+
`slow_but_exact=True`.
|
| 83 |
+
slow_but_exact (`bool`, *optional*, defaults to `False`):
|
| 84 |
+
Experimental feature. Whether to use slow but exact implementation of the attention mechanism. While
|
| 85 |
+
merging the TP rank tensors, due to slicing operations the results may be slightly different between the
|
| 86 |
+
model trained on Megatron and our model. Please refer to [this
|
| 87 |
+
issue](https://github.com/pytorch/pytorch/issues/76232). A solution to obtain more accurate results is to
|
| 88 |
+
enable this feature. Enabling this will hurt the computational time of the inference. Will be probably
|
| 89 |
+
resolved in the future once the main model has been fine-tuned with TP_rank=1.
|
| 90 |
+
|
| 91 |
+
Example:
|
| 92 |
+
|
| 93 |
+
```python
|
| 94 |
+
>>> from transformers import BloomConfig, BloomModel
|
| 95 |
+
|
| 96 |
+
>>> # Initializing a Bloom configuration
|
| 97 |
+
>>> configuration = BloomConfig()
|
| 98 |
+
|
| 99 |
+
>>> # Initializing a model (with random weights) from the configuration
|
| 100 |
+
>>> model = BloomModel(configuration)
|
| 101 |
+
|
| 102 |
+
>>> # Accessing the model configuration
|
| 103 |
+
>>> configuration = model.config
|
| 104 |
+
```"""
|
| 105 |
+
|
| 106 |
+
model_type = "bloom"
|
| 107 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 108 |
+
attribute_map = {
|
| 109 |
+
"num_hidden_layers": "n_layer",
|
| 110 |
+
"num_attention_heads": "n_head",
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
vocab_size=250880,
|
| 116 |
+
hidden_size=64,
|
| 117 |
+
n_layer=2,
|
| 118 |
+
n_head=8,
|
| 119 |
+
layer_norm_epsilon=1e-5,
|
| 120 |
+
initializer_range=0.02,
|
| 121 |
+
use_cache=True,
|
| 122 |
+
bos_token_id=1,
|
| 123 |
+
eos_token_id=2,
|
| 124 |
+
apply_residual_connection_post_layernorm=False,
|
| 125 |
+
hidden_dropout=0.0,
|
| 126 |
+
attention_dropout=0.0,
|
| 127 |
+
pretraining_tp=1, # TP rank used when training with megatron
|
| 128 |
+
slow_but_exact=False,
|
| 129 |
+
**kwargs,
|
| 130 |
+
):
|
| 131 |
+
self.vocab_size = vocab_size
|
| 132 |
+
# Backward compatibility with n_embed kwarg
|
| 133 |
+
n_embed = kwargs.pop("n_embed", None)
|
| 134 |
+
self.hidden_size = hidden_size if n_embed is None else n_embed
|
| 135 |
+
self.n_layer = n_layer
|
| 136 |
+
self.n_head = n_head
|
| 137 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 138 |
+
self.initializer_range = initializer_range
|
| 139 |
+
self.use_cache = use_cache
|
| 140 |
+
self.pretraining_tp = pretraining_tp
|
| 141 |
+
self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
|
| 142 |
+
self.hidden_dropout = hidden_dropout
|
| 143 |
+
self.attention_dropout = attention_dropout
|
| 144 |
+
|
| 145 |
+
self.bos_token_id = bos_token_id
|
| 146 |
+
self.eos_token_id = eos_token_id
|
| 147 |
+
self.slow_but_exact = slow_but_exact
|
| 148 |
+
|
| 149 |
+
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class BloomOnnxConfig(OnnxConfigWithPast):
|
| 153 |
+
torch_onnx_minimum_version = version.parse("1.12")
|
| 154 |
+
|
| 155 |
+
def __init__(
|
| 156 |
+
self,
|
| 157 |
+
config: PretrainedConfig,
|
| 158 |
+
task: str = "default",
|
| 159 |
+
patching_specs: List[PatchingSpec] = None,
|
| 160 |
+
use_past: bool = False,
|
| 161 |
+
):
|
| 162 |
+
super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
|
| 163 |
+
if not getattr(self._config, "pad_token_id", None):
|
| 164 |
+
# TODO: how to do that better?
|
| 165 |
+
self._config.pad_token_id = 0
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 169 |
+
common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
|
| 170 |
+
if self.use_past:
|
| 171 |
+
# BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
|
| 172 |
+
self.fill_with_past_key_values_(common_inputs, direction="inputs", inverted_values_shape=True)
|
| 173 |
+
common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
|
| 174 |
+
else:
|
| 175 |
+
common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
|
| 176 |
+
|
| 177 |
+
return common_inputs
|
| 178 |
+
|
| 179 |
+
@property
|
| 180 |
+
def num_layers(self) -> int:
|
| 181 |
+
return self._config.n_layer
|
| 182 |
+
|
| 183 |
+
@property
|
| 184 |
+
def num_attention_heads(self) -> int:
|
| 185 |
+
return self._config.n_head
|
| 186 |
+
|
| 187 |
+
@property
|
| 188 |
+
def atol_for_validation(self) -> float:
|
| 189 |
+
return 1e-3
|
| 190 |
+
|
| 191 |
+
def generate_dummy_inputs(
|
| 192 |
+
self,
|
| 193 |
+
tokenizer: "PreTrainedTokenizer",
|
| 194 |
+
batch_size: int = -1,
|
| 195 |
+
seq_length: int = -1,
|
| 196 |
+
is_pair: bool = False,
|
| 197 |
+
framework: Optional["TensorType"] = None,
|
| 198 |
+
) -> Mapping[str, Any]:
|
| 199 |
+
common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
|
| 200 |
+
tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
# We need to order the input in the way they appears in the forward()
|
| 204 |
+
ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})
|
| 205 |
+
|
| 206 |
+
# Need to add the past_keys
|
| 207 |
+
if self.use_past:
|
| 208 |
+
if not is_torch_available():
|
| 209 |
+
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
|
| 210 |
+
else:
|
| 211 |
+
import torch
|
| 212 |
+
|
| 213 |
+
batch, seqlen = common_inputs["input_ids"].shape
|
| 214 |
+
# Not using the same length for past_key_values
|
| 215 |
+
past_key_values_length = seqlen + 2
|
| 216 |
+
head_dim = self._config.hidden_size // self.num_attention_heads
|
| 217 |
+
past_key_shape = (
|
| 218 |
+
batch * self.num_attention_heads,
|
| 219 |
+
head_dim,
|
| 220 |
+
past_key_values_length,
|
| 221 |
+
)
|
| 222 |
+
past_value_shape = (
|
| 223 |
+
batch * self.num_attention_heads,
|
| 224 |
+
past_key_values_length,
|
| 225 |
+
head_dim,
|
| 226 |
+
)
|
| 227 |
+
ordered_inputs["past_key_values"] = [
|
| 228 |
+
(torch.zeros(past_key_shape), torch.zeros(past_value_shape)) for _ in range(self.num_layers)
|
| 229 |
+
]
|
| 230 |
+
|
| 231 |
+
ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
|
| 232 |
+
if self.use_past:
|
| 233 |
+
mask_dtype = ordered_inputs["attention_mask"].dtype
|
| 234 |
+
ordered_inputs["attention_mask"] = torch.cat(
|
| 235 |
+
[ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
return ordered_inputs
|
| 239 |
+
|
| 240 |
+
@property
|
| 241 |
+
def default_onnx_opset(self) -> int:
|
| 242 |
+
return 13
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/convert_bloom_original_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert BigScience BLOOM checkpoint."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import re
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
|
| 25 |
+
from transformers import BloomConfig, BloomModel
|
| 26 |
+
from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME
|
| 27 |
+
from transformers.utils import logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logging.set_verbosity_info()
|
| 31 |
+
|
| 32 |
+
WEIGHTS_TO_AVERAGE_ENDSWITH = [
|
| 33 |
+
"word_embeddings_layernorm.weight",
|
| 34 |
+
"word_embeddings_layernorm.bias",
|
| 35 |
+
"input_layernorm.weight",
|
| 36 |
+
"input_layernorm.bias",
|
| 37 |
+
"post_attention_layernorm.weight",
|
| 38 |
+
"post_attention_layernorm.bias",
|
| 39 |
+
"self_attention.dense.bias",
|
| 40 |
+
"mlp.dense_4h_to_h.bias",
|
| 41 |
+
"ln_f.weight",
|
| 42 |
+
"ln_f.bias",
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN = [
|
| 46 |
+
"mlp.dense_4h_to_h.weight",
|
| 47 |
+
"self_attention.dense.weight",
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def layer_name_mapping(key, file):
|
| 52 |
+
"""Convert Megatron-DeepSpeed TP/PP weights mapping in transformers PP only"""
|
| 53 |
+
# Handle first and last layers
|
| 54 |
+
layer_rename_map = {
|
| 55 |
+
"word_embeddings.weight": "word_embeddings.weight",
|
| 56 |
+
"word_embeddings.norm.weight": "word_embeddings_layernorm.weight",
|
| 57 |
+
"word_embeddings.norm.bias": "word_embeddings_layernorm.bias",
|
| 58 |
+
"weight": "ln_f.weight",
|
| 59 |
+
"bias": "ln_f.bias",
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
if key in layer_rename_map:
|
| 63 |
+
return layer_rename_map[key]
|
| 64 |
+
|
| 65 |
+
# Handle transformer blocks
|
| 66 |
+
layer_number = int(re.match(r".*layer_(\d*).*", file)[1])
|
| 67 |
+
layer_number -= 3
|
| 68 |
+
return f"h.{layer_number}." + key
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def get_dtype_size(dtype):
|
| 72 |
+
if dtype == torch.bool:
|
| 73 |
+
return 1 / 8
|
| 74 |
+
bit_search = re.search(r"[^\d](\d+)$", str(dtype))
|
| 75 |
+
if bit_search is None:
|
| 76 |
+
raise ValueError(f"`dtype` is not a valid dtype: {dtype}.")
|
| 77 |
+
bit_size = int(bit_search.groups()[0])
|
| 78 |
+
return bit_size // 8
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def convert_bloom_checkpoint_to_pytorch(
|
| 82 |
+
bloom_checkpoint_path, bloom_config_file, pytorch_dump_folder_path, shard_model, pretraining_tp
|
| 83 |
+
):
|
| 84 |
+
# Construct model
|
| 85 |
+
if bloom_config_file == "":
|
| 86 |
+
config = BloomConfig()
|
| 87 |
+
else:
|
| 88 |
+
config = BloomConfig.from_json_file(bloom_config_file)
|
| 89 |
+
|
| 90 |
+
if shard_model:
|
| 91 |
+
file_names = os.listdir(bloom_checkpoint_path)
|
| 92 |
+
file_names = sorted(filter(lambda s: s.startswith("layer") and "model_00" in s, file_names))
|
| 93 |
+
|
| 94 |
+
index_dict = {"weight_map": {}, "metadata": {}}
|
| 95 |
+
total_size = 0
|
| 96 |
+
|
| 97 |
+
missing_keys = None
|
| 98 |
+
|
| 99 |
+
config = BloomConfig()
|
| 100 |
+
|
| 101 |
+
for j, file in enumerate(file_names):
|
| 102 |
+
print("Processing file: {}".format(file))
|
| 103 |
+
tensors = None
|
| 104 |
+
|
| 105 |
+
for i in range(pretraining_tp):
|
| 106 |
+
# load all TP files
|
| 107 |
+
f_name = file.replace("model_00", f"model_0{i}")
|
| 108 |
+
temp = torch.load(os.path.join(bloom_checkpoint_path, f_name), map_location="cpu")
|
| 109 |
+
|
| 110 |
+
# Rename keys in the transformers names
|
| 111 |
+
keys = list(temp.keys())
|
| 112 |
+
for key in keys:
|
| 113 |
+
temp[layer_name_mapping(key, file)] = temp.pop(key)
|
| 114 |
+
|
| 115 |
+
if tensors is None:
|
| 116 |
+
tensors = temp
|
| 117 |
+
else:
|
| 118 |
+
for key in tensors.keys():
|
| 119 |
+
if any(key.endswith(end) for end in WEIGHTS_TO_AVERAGE_ENDSWITH):
|
| 120 |
+
# We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
|
| 121 |
+
tensors[key] += temp[key]
|
| 122 |
+
else:
|
| 123 |
+
# Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
|
| 124 |
+
cat_dim = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN) else 0
|
| 125 |
+
# We concatenate these weights accross TP ranks
|
| 126 |
+
tensors[key] = torch.cat([tensors[key], temp[key]], dim=cat_dim)
|
| 127 |
+
|
| 128 |
+
# Divide by the number of TP the weights we want to average
|
| 129 |
+
for key in tensors.keys():
|
| 130 |
+
if any(key.endswith(end) for end in WEIGHTS_TO_AVERAGE_ENDSWITH):
|
| 131 |
+
tensors[key] = tensors[key] / pretraining_tp
|
| 132 |
+
torch.save(
|
| 133 |
+
tensors,
|
| 134 |
+
os.path.join(
|
| 135 |
+
pytorch_dump_folder_path,
|
| 136 |
+
"pytorch_model_{}-of-{}.bin".format(str(j + 1).zfill(5), str(len(file_names)).zfill(5)),
|
| 137 |
+
),
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
for key in tensors.keys():
|
| 141 |
+
value = tensors[key]
|
| 142 |
+
total_size += value.numel() * get_dtype_size(value.dtype)
|
| 143 |
+
if key not in index_dict["weight_map"]:
|
| 144 |
+
index_dict["weight_map"][key] = "pytorch_model_{}-of-{}.bin".format(
|
| 145 |
+
str(j + 1).zfill(5), str(len(file_names)).zfill(5)
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
config = BloomConfig()
|
| 149 |
+
pytorch_config_dump_path = pytorch_dump_folder_path + "/" + CONFIG_NAME
|
| 150 |
+
index_dict["metadata"]["total_size"] = total_size
|
| 151 |
+
with open(pytorch_config_dump_path, "w", encoding="utf-8") as f:
|
| 152 |
+
f.write(config.to_json_string())
|
| 153 |
+
with open(os.path.join(pytorch_dump_folder_path, WEIGHTS_NAME + ".index.json"), "w", encoding="utf-8") as f:
|
| 154 |
+
json_config = json.dumps(index_dict, indent=2, sort_keys=True) + "\n"
|
| 155 |
+
f.write(json_config)
|
| 156 |
+
else:
|
| 157 |
+
model = BloomModel(config)
|
| 158 |
+
|
| 159 |
+
file_names = os.listdir(bloom_checkpoint_path)
|
| 160 |
+
file_names = sorted(filter(lambda s: s.startswith("layer") and "model_00" in s, file_names))
|
| 161 |
+
|
| 162 |
+
missing_keys = None
|
| 163 |
+
for i, file in enumerate(file_names):
|
| 164 |
+
tensors = None
|
| 165 |
+
for i in range(pretraining_tp):
|
| 166 |
+
# load all TP files
|
| 167 |
+
f_name = file.replace("model_00", f"model_0{i}")
|
| 168 |
+
temp = torch.load(os.path.join(bloom_checkpoint_path, f_name), map_location="cpu")
|
| 169 |
+
|
| 170 |
+
# Rename keys in the transformers names
|
| 171 |
+
keys = list(temp.keys())
|
| 172 |
+
for key in keys:
|
| 173 |
+
temp[layer_name_mapping(key, file)] = temp.pop(key)
|
| 174 |
+
|
| 175 |
+
if tensors is None:
|
| 176 |
+
tensors = temp
|
| 177 |
+
else:
|
| 178 |
+
for key in tensors.keys():
|
| 179 |
+
# We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
|
| 180 |
+
if any(key.endswith(end) for end in WEIGHTS_TO_AVERAGE_ENDSWITH):
|
| 181 |
+
tensors[key] += temp[key]
|
| 182 |
+
else:
|
| 183 |
+
# Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
|
| 184 |
+
cat_dim = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN) else 0
|
| 185 |
+
# We concatenate these weights accross TP ranks
|
| 186 |
+
tensors[key] = torch.cat([tensors[key], temp[key]], dim=cat_dim)
|
| 187 |
+
|
| 188 |
+
# Divide by the number of TP the weights we want to average
|
| 189 |
+
for key in tensors.keys():
|
| 190 |
+
if any(key.endswith(end) for end in WEIGHTS_TO_AVERAGE_ENDSWITH):
|
| 191 |
+
tensors[key] = tensors[key] / pretraining_tp
|
| 192 |
+
|
| 193 |
+
other_keys = model.load_state_dict(tensors, strict=False)
|
| 194 |
+
assert not other_keys.unexpected_keys, f"The keys {other_keys.unexpected_keys} are unexpected"
|
| 195 |
+
if missing_keys is None:
|
| 196 |
+
missing_keys = set(other_keys.missing_keys)
|
| 197 |
+
else:
|
| 198 |
+
missing_keys = missing_keys.intersection(set(other_keys.missing_keys))
|
| 199 |
+
|
| 200 |
+
assert not missing_keys, f"The keys {missing_keys} are missing"
|
| 201 |
+
|
| 202 |
+
# Save pytorch-model
|
| 203 |
+
os.makedirs(pytorch_dump_folder_path, exist_ok=True)
|
| 204 |
+
pytorch_weights_dump_path = pytorch_dump_folder_path + "/" + WEIGHTS_NAME
|
| 205 |
+
pytorch_config_dump_path = pytorch_dump_folder_path + "/" + CONFIG_NAME
|
| 206 |
+
print(f"Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}")
|
| 207 |
+
if config.torch_dtype is not None:
|
| 208 |
+
model = model.to(config.torch_dtype)
|
| 209 |
+
torch.save(model.state_dict(), pytorch_weights_dump_path)
|
| 210 |
+
print(f"Save configuration file to {pytorch_config_dump_path}")
|
| 211 |
+
with open(pytorch_config_dump_path, "w", encoding="utf-8") as f:
|
| 212 |
+
f.write(config.to_json_string())
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
if __name__ == "__main__":
|
| 216 |
+
parser = argparse.ArgumentParser()
|
| 217 |
+
# Required parameters
|
| 218 |
+
parser.add_argument(
|
| 219 |
+
"--bloom_checkpoint_path",
|
| 220 |
+
default=None,
|
| 221 |
+
type=str,
|
| 222 |
+
required=True,
|
| 223 |
+
help="Path to the Megatron-LM checkpoint path.",
|
| 224 |
+
)
|
| 225 |
+
parser.add_argument(
|
| 226 |
+
"--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
|
| 227 |
+
)
|
| 228 |
+
parser.add_argument(
|
| 229 |
+
"--bloom_config_file",
|
| 230 |
+
default="",
|
| 231 |
+
type=str,
|
| 232 |
+
help=(
|
| 233 |
+
"An optional config json file corresponding to the pre-trained model. \n"
|
| 234 |
+
"This specifies the model architecture."
|
| 235 |
+
),
|
| 236 |
+
)
|
| 237 |
+
parser.add_argument(
|
| 238 |
+
"--shard_model",
|
| 239 |
+
action="store_true",
|
| 240 |
+
help="An optional setting to shard the output model \nThis enables sharding the converted checkpoint",
|
| 241 |
+
)
|
| 242 |
+
parser.add_argument(
|
| 243 |
+
"--pretraining_tp",
|
| 244 |
+
default=4,
|
| 245 |
+
type=int,
|
| 246 |
+
help="Pretraining TP rank that has been used when training the model in Megatron-LM \n",
|
| 247 |
+
)
|
| 248 |
+
args = parser.parse_args()
|
| 249 |
+
convert_bloom_checkpoint_to_pytorch(
|
| 250 |
+
args.bloom_checkpoint_path,
|
| 251 |
+
args.bloom_config_file,
|
| 252 |
+
args.pytorch_dump_folder_path,
|
| 253 |
+
args.shard_model,
|
| 254 |
+
args.pretraining_tp,
|
| 255 |
+
)
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/modeling_bloom.py
ADDED
|
@@ -0,0 +1,1297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 HuggingFace Inc. team and BigScience workshop.
|
| 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 BLOOM model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
import warnings
|
| 19 |
+
from typing import Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
|
| 25 |
+
from torch.nn import functional as F
|
| 26 |
+
|
| 27 |
+
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
|
| 28 |
+
from ...modeling_outputs import (
|
| 29 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 30 |
+
CausalLMOutputWithCrossAttentions,
|
| 31 |
+
QuestionAnsweringModelOutput,
|
| 32 |
+
SequenceClassifierOutputWithPast,
|
| 33 |
+
TokenClassifierOutput,
|
| 34 |
+
)
|
| 35 |
+
from ...modeling_utils import PreTrainedModel
|
| 36 |
+
from ...utils import logging
|
| 37 |
+
from .configuration_bloom import BloomConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
_CHECKPOINT_FOR_DOC = "bigscience/bloom-560m"
|
| 43 |
+
_CONFIG_FOR_DOC = "BloomConfig"
|
| 44 |
+
|
| 45 |
+
BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 46 |
+
"bigscience/bigscience-small-testing",
|
| 47 |
+
"bigscience/bloom-560m",
|
| 48 |
+
"bigscience/bloom-1b1",
|
| 49 |
+
"bigscience/bloom-1b7",
|
| 50 |
+
"bigscience/bloom-3b",
|
| 51 |
+
"bigscience/bloom-7b1",
|
| 52 |
+
"bigscience/bloom",
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _make_causal_mask(
|
| 57 |
+
input_ids_shape: torch.Size, device: torch.device, past_key_values_length: int
|
| 58 |
+
) -> torch.BoolTensor:
|
| 59 |
+
"""
|
| 60 |
+
Make causal mask used for self-attention.
|
| 61 |
+
"""
|
| 62 |
+
batch_size, target_length = input_ids_shape
|
| 63 |
+
mask = torch.empty((target_length, target_length + past_key_values_length), dtype=torch.bool, device=device)
|
| 64 |
+
# ONNX doesn't support `torch.Tensor.triu` properly, thus we use this workaround
|
| 65 |
+
seq_ids = torch.arange(target_length, device=device)
|
| 66 |
+
mask[:, past_key_values_length:] = seq_ids[:, None] < seq_ids[None, :]
|
| 67 |
+
|
| 68 |
+
if past_key_values_length > 0:
|
| 69 |
+
mask[:, :past_key_values_length] = False
|
| 70 |
+
|
| 71 |
+
expanded_mask = mask[None, None, :, :].expand(batch_size, 1, target_length, target_length + past_key_values_length)
|
| 72 |
+
return expanded_mask
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _expand_mask(mask: torch.Tensor, tgt_length: int) -> torch.BoolTensor:
|
| 76 |
+
"""
|
| 77 |
+
Expands attention_mask from `[batch_size, src_length]` to `[batch_size, 1, tgt_length, src_length]`.
|
| 78 |
+
"""
|
| 79 |
+
batch_size, src_length = mask.shape
|
| 80 |
+
tgt_length = tgt_length if tgt_length is not None else src_length
|
| 81 |
+
|
| 82 |
+
expanded_mask = ~(mask[:, None, None, :].to(torch.bool))
|
| 83 |
+
return expanded_mask.expand(batch_size, 1, tgt_length, src_length)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def build_alibi_tensor(attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
|
| 87 |
+
"""
|
| 88 |
+
Link to paper: https://arxiv.org/abs/2108.12409 Alibi tensor is not causal as the original paper mentions, it
|
| 89 |
+
relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value
|
| 90 |
+
`softmax(l+a) = softmax(l)`. Based on
|
| 91 |
+
https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742
|
| 92 |
+
TODO @thomasw21 this doesn't work as nicely due to the masking strategy, and so masking varies slightly.
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
Returns tensor shaped (batch_size * num_heads, 1, max_seq_len)
|
| 96 |
+
attention_mask (`torch.Tensor`):
|
| 97 |
+
Token-wise attention mask, this should be of shape (batch_size, max_seq_len).
|
| 98 |
+
num_heads (`int`, *required*):
|
| 99 |
+
number of heads
|
| 100 |
+
dtype (`torch.dtype`, *optional*, default=`torch.bfloat16`):
|
| 101 |
+
dtype of the output tensor
|
| 102 |
+
"""
|
| 103 |
+
batch_size, seq_length = attention_mask.shape
|
| 104 |
+
closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
|
| 105 |
+
base = torch.tensor(
|
| 106 |
+
2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
|
| 107 |
+
)
|
| 108 |
+
powers = torch.arange(1, 1 + closest_power_of_2, device=attention_mask.device, dtype=torch.int32)
|
| 109 |
+
slopes = torch.pow(base, powers)
|
| 110 |
+
|
| 111 |
+
if closest_power_of_2 != num_heads:
|
| 112 |
+
extra_base = torch.tensor(
|
| 113 |
+
2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
|
| 114 |
+
)
|
| 115 |
+
num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
|
| 116 |
+
extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=attention_mask.device, dtype=torch.int32)
|
| 117 |
+
slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
|
| 118 |
+
|
| 119 |
+
# Note: alibi will added to the attention bias that will be applied to the query, key product of attention
|
| 120 |
+
# => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
|
| 121 |
+
# => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
|
| 122 |
+
# => the query_length dimension will then be broadcasted correctly
|
| 123 |
+
# This is more or less identical to T5's relative position bias:
|
| 124 |
+
# https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
|
| 125 |
+
arange_tensor = ((attention_mask.cumsum(dim=-1) - 1) * attention_mask)[:, None, :]
|
| 126 |
+
alibi = slopes[..., None] * arange_tensor
|
| 127 |
+
return alibi.reshape(batch_size * num_heads, 1, seq_length).to(dtype)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def dropout_add(x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool) -> torch.Tensor:
|
| 131 |
+
"""
|
| 132 |
+
Dropout add function
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
x (`torch.tensor`, *required*):
|
| 136 |
+
input tensor
|
| 137 |
+
residual (`torch.tensor`, *required*):
|
| 138 |
+
residual tensor
|
| 139 |
+
prob (`float`, *required*):
|
| 140 |
+
dropout probability
|
| 141 |
+
training (`bool`, *required*):
|
| 142 |
+
training mode
|
| 143 |
+
"""
|
| 144 |
+
out = F.dropout(x, p=prob, training=training)
|
| 145 |
+
out = residual + out
|
| 146 |
+
return out
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def bloom_gelu_forward(x: torch.Tensor) -> torch.Tensor:
|
| 150 |
+
"""
|
| 151 |
+
Custom bias GELU function. Adapted from Megatron-DeepSpeed code. Here we use a simple implementation (inference) to
|
| 152 |
+
make the model jitable.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
x (`torch.tensor`, *required*):
|
| 156 |
+
input hidden states
|
| 157 |
+
"""
|
| 158 |
+
return x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def bloom_gelu_back(g: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
|
| 162 |
+
"""
|
| 163 |
+
gradient of tanh approximation of gelu gradient of actual gelu is: 0.5 * (1. + torch.erf(x * 0.70710678)) +
|
| 164 |
+
0.3989423 * x * torch.exp(-0.5 * x * x)
|
| 165 |
+
|
| 166 |
+
Args:
|
| 167 |
+
g (`torch.tensor`, *required*):
|
| 168 |
+
gradient output tensor
|
| 169 |
+
x (`torch.tensor`, *required*):
|
| 170 |
+
input tensor
|
| 171 |
+
"""
|
| 172 |
+
x = x[0] # x is a tuple of 1 element, needs to unpack it first
|
| 173 |
+
tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
|
| 174 |
+
# sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
|
| 175 |
+
ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (1 + tanh_out)
|
| 176 |
+
return ff * g
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class GeLUFunction(torch.autograd.Function):
|
| 180 |
+
@staticmethod
|
| 181 |
+
def forward(ctx, input: torch.Tensor) -> torch.Tensor:
|
| 182 |
+
ctx.save_for_backward(input)
|
| 183 |
+
return bloom_gelu_forward(input)
|
| 184 |
+
|
| 185 |
+
@staticmethod
|
| 186 |
+
def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:
|
| 187 |
+
input = ctx.saved_tensors
|
| 188 |
+
tmp = bloom_gelu_back(grad_output, input)
|
| 189 |
+
return tmp
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class BloomGelu(nn.Module):
|
| 193 |
+
"""
|
| 194 |
+
BloomBiasGelu wrapper function that make use of the simple function on inference mode to make the model
|
| 195 |
+
torchscriptable and use the autograd function in training mode to get the accurate results of the gradients Partly
|
| 196 |
+
copied from Megatron-DeepSpeed code and adapted for our needs
|
| 197 |
+
|
| 198 |
+
See here why autograd functions are not torchscriptable: https://github.com/pytorch/pytorch/issues/22329
|
| 199 |
+
"""
|
| 200 |
+
|
| 201 |
+
def __init__(self):
|
| 202 |
+
super().__init__()
|
| 203 |
+
|
| 204 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 205 |
+
if self.training:
|
| 206 |
+
return GeLUFunction.apply(x)
|
| 207 |
+
else:
|
| 208 |
+
return bloom_gelu_forward(x)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class BloomAttention(nn.Module):
|
| 212 |
+
def __init__(self, config: BloomConfig):
|
| 213 |
+
super().__init__()
|
| 214 |
+
|
| 215 |
+
self.pretraining_tp = config.pretraining_tp
|
| 216 |
+
self.slow_but_exact = config.slow_but_exact
|
| 217 |
+
|
| 218 |
+
self.hidden_size = config.hidden_size
|
| 219 |
+
self.num_heads = config.n_head
|
| 220 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 221 |
+
self.split_size = self.hidden_size
|
| 222 |
+
self.hidden_dropout = config.hidden_dropout
|
| 223 |
+
|
| 224 |
+
if self.head_dim * self.num_heads != self.hidden_size:
|
| 225 |
+
raise ValueError(
|
| 226 |
+
f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
|
| 227 |
+
f" {self.num_heads})."
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
# Layer-wise attention scaling
|
| 231 |
+
self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
|
| 232 |
+
self.beta = 1.0
|
| 233 |
+
|
| 234 |
+
self.query_key_value = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=True)
|
| 235 |
+
self.dense = nn.Linear(self.hidden_size, self.hidden_size)
|
| 236 |
+
self.attention_dropout = nn.Dropout(config.attention_dropout)
|
| 237 |
+
|
| 238 |
+
def _split_heads(self, fused_qkv: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 239 |
+
"""
|
| 240 |
+
Split the last dimension into (num_heads, head_dim) without making any copies, results share same memory
|
| 241 |
+
storage as `fused_qkv`
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
fused_qkv (`torch.tensor`, *required*): [batch_size, seq_length, num_heads * 3 * head_dim]
|
| 245 |
+
|
| 246 |
+
Returns:
|
| 247 |
+
query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim]
|
| 248 |
+
value: [batch_size, seq_length, num_heads, head_dim]
|
| 249 |
+
"""
|
| 250 |
+
batch_size, seq_length, three_times_hidden_size = fused_qkv.shape
|
| 251 |
+
fused_qkv = fused_qkv.view(batch_size, seq_length, self.num_heads, 3, self.head_dim)
|
| 252 |
+
return fused_qkv[..., 0, :], fused_qkv[..., 1, :], fused_qkv[..., 2, :]
|
| 253 |
+
|
| 254 |
+
def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
|
| 255 |
+
"""
|
| 256 |
+
Merge heads together over the last dimension
|
| 257 |
+
|
| 258 |
+
Args:
|
| 259 |
+
x (`torch.tensor`, *required*): [batch_size * num_heads, seq_length, head_dim]
|
| 260 |
+
|
| 261 |
+
Returns:
|
| 262 |
+
torch.tensor: [batch_size, seq_length, num_heads * head_dim]
|
| 263 |
+
"""
|
| 264 |
+
# What we want to achieve is:
|
| 265 |
+
# batch_size * num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads * head_dim
|
| 266 |
+
batch_size_and_num_heads, seq_length, _ = x.shape
|
| 267 |
+
batch_size = batch_size_and_num_heads // self.num_heads
|
| 268 |
+
|
| 269 |
+
# First view to decompose the batch size
|
| 270 |
+
# batch_size * num_heads, seq_length, head_dim -> batch_size, num_heads, seq_length, head_dim
|
| 271 |
+
x = x.view(batch_size, self.num_heads, seq_length, self.head_dim)
|
| 272 |
+
|
| 273 |
+
# batch_size, num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads, head_dim
|
| 274 |
+
x = x.permute(0, 2, 1, 3)
|
| 275 |
+
|
| 276 |
+
# batch_size, seq_length, num_heads, head_dim -> batch_size, seq_length, num_heads * head_dim
|
| 277 |
+
return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim)
|
| 278 |
+
|
| 279 |
+
def forward(
|
| 280 |
+
self,
|
| 281 |
+
hidden_states: torch.Tensor,
|
| 282 |
+
residual: torch.Tensor,
|
| 283 |
+
alibi: torch.Tensor,
|
| 284 |
+
attention_mask: torch.Tensor,
|
| 285 |
+
layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 286 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 287 |
+
use_cache: bool = False,
|
| 288 |
+
output_attentions: bool = False,
|
| 289 |
+
):
|
| 290 |
+
fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
|
| 291 |
+
|
| 292 |
+
# 3 x [batch_size, seq_length, num_heads, head_dim]
|
| 293 |
+
(query_layer, key_layer, value_layer) = self._split_heads(fused_qkv)
|
| 294 |
+
|
| 295 |
+
batch_size, q_length, _, _ = query_layer.shape
|
| 296 |
+
|
| 297 |
+
query_layer = query_layer.transpose(1, 2).reshape(batch_size * self.num_heads, q_length, self.head_dim)
|
| 298 |
+
key_layer = key_layer.permute(0, 2, 3, 1).reshape(batch_size * self.num_heads, self.head_dim, q_length)
|
| 299 |
+
value_layer = value_layer.transpose(1, 2).reshape(batch_size * self.num_heads, q_length, self.head_dim)
|
| 300 |
+
if layer_past is not None:
|
| 301 |
+
past_key, past_value = layer_past
|
| 302 |
+
# concatenate along seq_length dimension:
|
| 303 |
+
# - key: [batch_size * self.num_heads, head_dim, kv_length]
|
| 304 |
+
# - value: [batch_size * self.num_heads, kv_length, head_dim]
|
| 305 |
+
key_layer = torch.cat((past_key, key_layer), dim=2)
|
| 306 |
+
value_layer = torch.cat((past_value, value_layer), dim=1)
|
| 307 |
+
|
| 308 |
+
_, _, kv_length = key_layer.shape
|
| 309 |
+
|
| 310 |
+
if use_cache is True:
|
| 311 |
+
present = (key_layer, value_layer)
|
| 312 |
+
else:
|
| 313 |
+
present = None
|
| 314 |
+
|
| 315 |
+
# [batch_size * num_heads, q_length, kv_length]
|
| 316 |
+
# we use `torch.Tensor.baddbmm` instead of `torch.baddbmm` as the latter isn't supported by TorchScript v1.11
|
| 317 |
+
matmul_result = alibi.baddbmm(
|
| 318 |
+
batch1=query_layer,
|
| 319 |
+
batch2=key_layer,
|
| 320 |
+
beta=self.beta,
|
| 321 |
+
alpha=self.inv_norm_factor,
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
# change view to [batch_size, num_heads, q_length, kv_length]
|
| 325 |
+
attention_scores = matmul_result.view(batch_size, self.num_heads, q_length, kv_length)
|
| 326 |
+
|
| 327 |
+
# cast attention scores to fp32, compute scaled softmax and cast back to initial dtype - [batch_size, num_heads, q_length, kv_length]
|
| 328 |
+
input_dtype = attention_scores.dtype
|
| 329 |
+
# `float16` has a minimum value of -65504.0, whereas `bfloat16` and `float32` have a minimum value of `-3.4e+38`
|
| 330 |
+
if input_dtype == torch.float16:
|
| 331 |
+
attention_scores = attention_scores.to(torch.float)
|
| 332 |
+
attn_weights = torch.masked_fill(attention_scores, attention_mask, torch.finfo(attention_scores.dtype).min)
|
| 333 |
+
attention_probs = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(input_dtype)
|
| 334 |
+
|
| 335 |
+
# [batch_size, num_heads, q_length, kv_length]
|
| 336 |
+
attention_probs = self.attention_dropout(attention_probs)
|
| 337 |
+
|
| 338 |
+
if head_mask is not None:
|
| 339 |
+
attention_probs = attention_probs * head_mask
|
| 340 |
+
|
| 341 |
+
# change view [batch_size x num_heads, q_length, kv_length]
|
| 342 |
+
attention_probs_reshaped = attention_probs.view(batch_size * self.num_heads, q_length, kv_length)
|
| 343 |
+
|
| 344 |
+
# matmul: [batch_size * num_heads, q_length, head_dim]
|
| 345 |
+
context_layer = torch.bmm(attention_probs_reshaped, value_layer)
|
| 346 |
+
|
| 347 |
+
# change view [batch_size, q_length, num_heads * head_dim]
|
| 348 |
+
context_layer = self._merge_heads(context_layer)
|
| 349 |
+
|
| 350 |
+
# aggregate results across tp ranks. See here: https://github.com/pytorch/pytorch/issues/76232
|
| 351 |
+
if self.pretraining_tp > 1 and self.slow_but_exact:
|
| 352 |
+
slices = self.hidden_size / self.pretraining_tp
|
| 353 |
+
output_tensor = torch.zeros_like(context_layer)
|
| 354 |
+
for i in range(self.pretraining_tp):
|
| 355 |
+
output_tensor = output_tensor + F.linear(
|
| 356 |
+
context_layer[:, :, int(i * slices) : int((i + 1) * slices)],
|
| 357 |
+
self.dense.weight[:, int(i * slices) : int((i + 1) * slices)],
|
| 358 |
+
)
|
| 359 |
+
else:
|
| 360 |
+
output_tensor = self.dense(context_layer)
|
| 361 |
+
|
| 362 |
+
output_tensor = dropout_add(output_tensor, residual, self.hidden_dropout, self.training)
|
| 363 |
+
|
| 364 |
+
outputs = (output_tensor, present)
|
| 365 |
+
if output_attentions:
|
| 366 |
+
outputs += (attention_probs,)
|
| 367 |
+
|
| 368 |
+
return outputs
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class BloomMLP(nn.Module):
|
| 372 |
+
def __init__(self, config: BloomConfig):
|
| 373 |
+
super().__init__()
|
| 374 |
+
hidden_size = config.hidden_size
|
| 375 |
+
|
| 376 |
+
self.pretraining_tp = config.pretraining_tp
|
| 377 |
+
self.slow_but_exact = config.slow_but_exact
|
| 378 |
+
self.dense_h_to_4h = nn.Linear(hidden_size, 4 * hidden_size)
|
| 379 |
+
self.gelu_impl = BloomGelu()
|
| 380 |
+
self.dense_4h_to_h = nn.Linear(4 * hidden_size, hidden_size)
|
| 381 |
+
self.hidden_dropout = config.hidden_dropout
|
| 382 |
+
|
| 383 |
+
def forward(self, hidden_states: torch.Tensor, residual: torch.Tensor) -> torch.Tensor:
|
| 384 |
+
hidden_states = self.gelu_impl(self.dense_h_to_4h(hidden_states))
|
| 385 |
+
|
| 386 |
+
if self.pretraining_tp > 1 and self.slow_but_exact:
|
| 387 |
+
intermediate_output = torch.zeros_like(residual)
|
| 388 |
+
slices = self.dense_4h_to_h.weight.shape[-1] / self.pretraining_tp
|
| 389 |
+
for i in range(self.pretraining_tp):
|
| 390 |
+
intermediate_output = intermediate_output + F.linear(
|
| 391 |
+
hidden_states[:, :, int(i * slices) : int((i + 1) * slices)],
|
| 392 |
+
self.dense_4h_to_h.weight[:, int(i * slices) : int((i + 1) * slices)],
|
| 393 |
+
)
|
| 394 |
+
else:
|
| 395 |
+
intermediate_output = self.dense_4h_to_h(hidden_states)
|
| 396 |
+
|
| 397 |
+
output = dropout_add(intermediate_output, residual, self.hidden_dropout, self.training)
|
| 398 |
+
|
| 399 |
+
return output
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class BloomBlock(nn.Module):
|
| 403 |
+
def __init__(self, config: BloomConfig):
|
| 404 |
+
super().__init__()
|
| 405 |
+
hidden_size = config.hidden_size
|
| 406 |
+
|
| 407 |
+
self.input_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
| 408 |
+
self.num_heads = config.n_head
|
| 409 |
+
self.self_attention = BloomAttention(config)
|
| 410 |
+
self.post_attention_layernorm = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
| 411 |
+
|
| 412 |
+
self.mlp = BloomMLP(config)
|
| 413 |
+
|
| 414 |
+
self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
|
| 415 |
+
self.hidden_dropout = config.hidden_dropout
|
| 416 |
+
|
| 417 |
+
def forward(
|
| 418 |
+
self,
|
| 419 |
+
hidden_states: torch.Tensor,
|
| 420 |
+
alibi: torch.Tensor,
|
| 421 |
+
attention_mask: torch.Tensor,
|
| 422 |
+
layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 423 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 424 |
+
use_cache: bool = False,
|
| 425 |
+
output_attentions: bool = False,
|
| 426 |
+
):
|
| 427 |
+
# hidden_states: [batch_size, seq_length, hidden_size]
|
| 428 |
+
|
| 429 |
+
# Layer norm at the beginning of the transformer layer.
|
| 430 |
+
layernorm_output = self.input_layernorm(hidden_states)
|
| 431 |
+
|
| 432 |
+
# Layer norm post the self attention.
|
| 433 |
+
if self.apply_residual_connection_post_layernorm:
|
| 434 |
+
residual = layernorm_output
|
| 435 |
+
else:
|
| 436 |
+
residual = hidden_states
|
| 437 |
+
|
| 438 |
+
# Self attention.
|
| 439 |
+
attn_outputs = self.self_attention(
|
| 440 |
+
layernorm_output,
|
| 441 |
+
residual,
|
| 442 |
+
layer_past=layer_past,
|
| 443 |
+
attention_mask=attention_mask,
|
| 444 |
+
alibi=alibi,
|
| 445 |
+
head_mask=head_mask,
|
| 446 |
+
use_cache=use_cache,
|
| 447 |
+
output_attentions=output_attentions,
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
attention_output = attn_outputs[0]
|
| 451 |
+
|
| 452 |
+
outputs = attn_outputs[1:]
|
| 453 |
+
|
| 454 |
+
layernorm_output = self.post_attention_layernorm(attention_output)
|
| 455 |
+
|
| 456 |
+
# Get residual
|
| 457 |
+
if self.apply_residual_connection_post_layernorm:
|
| 458 |
+
residual = layernorm_output
|
| 459 |
+
else:
|
| 460 |
+
residual = attention_output
|
| 461 |
+
|
| 462 |
+
# MLP.
|
| 463 |
+
output = self.mlp(layernorm_output, residual)
|
| 464 |
+
|
| 465 |
+
if use_cache:
|
| 466 |
+
outputs = (output,) + outputs
|
| 467 |
+
else:
|
| 468 |
+
outputs = (output,) + outputs[1:]
|
| 469 |
+
|
| 470 |
+
return outputs # hidden_states, present, attentions
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
class BloomPreTrainedModel(PreTrainedModel):
|
| 474 |
+
config_class = BloomConfig
|
| 475 |
+
base_model_prefix = "transformer"
|
| 476 |
+
supports_gradient_checkpointing = True
|
| 477 |
+
_no_split_modules = ["BloomBlock"]
|
| 478 |
+
_skip_keys_device_placement = "past_key_values"
|
| 479 |
+
|
| 480 |
+
def __init__(self, *inputs, **kwargs):
|
| 481 |
+
super().__init__(*inputs, **kwargs)
|
| 482 |
+
|
| 483 |
+
def _init_weights(self, module: nn.Module):
|
| 484 |
+
"""Initialize the weights."""
|
| 485 |
+
if isinstance(module, nn.Linear):
|
| 486 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 487 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 488 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 489 |
+
if module.bias is not None:
|
| 490 |
+
module.bias.data.zero_()
|
| 491 |
+
elif isinstance(module, nn.Embedding):
|
| 492 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 493 |
+
if module.padding_idx is not None:
|
| 494 |
+
module.weight.data[module.padding_idx].zero_()
|
| 495 |
+
elif isinstance(module, LayerNorm):
|
| 496 |
+
module.bias.data.zero_()
|
| 497 |
+
module.weight.data.fill_(1.0)
|
| 498 |
+
|
| 499 |
+
def _set_gradient_checkpointing(self, module: nn.Module, value: bool = False):
|
| 500 |
+
if isinstance(module, BloomModel):
|
| 501 |
+
module.gradient_checkpointing = value
|
| 502 |
+
|
| 503 |
+
@staticmethod
|
| 504 |
+
def _convert_to_standard_cache(
|
| 505 |
+
past_key_value: Tuple[Tuple[torch.Tensor, torch.Tensor]], batch_size: int
|
| 506 |
+
) -> Tuple[Tuple[torch.Tensor, torch.Tensor]]:
|
| 507 |
+
"""
|
| 508 |
+
Standardizes the format of the cache so as to match most implementations, i.e. to tuple(tuple([batch_size,
|
| 509 |
+
num_heads, ...]))
|
| 510 |
+
"""
|
| 511 |
+
batch_size_times_num_heads, head_dim, seq_length = past_key_value[0][0].shape
|
| 512 |
+
num_heads = batch_size_times_num_heads // batch_size
|
| 513 |
+
# key: [batch_size * num_heads, head_dim, seq_length] -> [batch_size, num_heads, head_dim, seq_length]
|
| 514 |
+
# value: [batch_size * num_heads, seq_length, head_dim] -> [batch_size, num_heads, seq_length, head_dim]
|
| 515 |
+
return tuple(
|
| 516 |
+
(
|
| 517 |
+
layer_past[0].view(batch_size, num_heads, head_dim, seq_length),
|
| 518 |
+
layer_past[1].view(batch_size, num_heads, seq_length, head_dim),
|
| 519 |
+
)
|
| 520 |
+
for layer_past in past_key_value
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
@staticmethod
|
| 524 |
+
def _convert_to_bloom_cache(
|
| 525 |
+
past_key_value: Tuple[Tuple[torch.Tensor, torch.Tensor]]
|
| 526 |
+
) -> Tuple[Tuple[torch.Tensor, torch.Tensor]]:
|
| 527 |
+
"""
|
| 528 |
+
Converts the cache to the format expected by Bloom, i.e. to tuple(tuple([batch_size * num_heads, ...]))
|
| 529 |
+
"""
|
| 530 |
+
batch_size, num_heads, head_dim, seq_length = past_key_value[0][0].shape
|
| 531 |
+
batch_size_times_num_heads = batch_size * num_heads
|
| 532 |
+
# key: [batch_size, num_heads, head_dim, seq_length] -> [batch_size * num_heads, head_dim, seq_length]
|
| 533 |
+
# value: [batch_size, num_heads, seq_length, head_dim] -> [batch_size * num_heads, seq_length, head_dim]
|
| 534 |
+
return tuple(
|
| 535 |
+
(
|
| 536 |
+
layer_past[0].view(batch_size_times_num_heads, head_dim, seq_length),
|
| 537 |
+
layer_past[1].view(batch_size_times_num_heads, seq_length, head_dim),
|
| 538 |
+
)
|
| 539 |
+
for layer_past in past_key_value
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
BLOOM_START_DOCSTRING = r"""
|
| 544 |
+
|
| 545 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 546 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings etc.)
|
| 547 |
+
|
| 548 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 549 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 550 |
+
and behavior.
|
| 551 |
+
|
| 552 |
+
Parameters:
|
| 553 |
+
config ([`BloomConfig`]): Model configuration class with all the parameters of the model.
|
| 554 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 555 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 556 |
+
"""
|
| 557 |
+
|
| 558 |
+
BLOOM_INPUTS_DOCSTRING = r"""
|
| 559 |
+
Args:
|
| 560 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
| 561 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0][0].shape[2]`
|
| 562 |
+
(`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.
|
| 563 |
+
|
| 564 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
| 565 |
+
`input_ids`.
|
| 566 |
+
|
| 567 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 568 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 569 |
+
|
| 570 |
+
[What are input IDs?](../glossary#input-ids)
|
| 571 |
+
past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
|
| 572 |
+
Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
|
| 573 |
+
`past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
|
| 574 |
+
their past given to this model should not be passed as `input_ids` as they have already been computed.
|
| 575 |
+
|
| 576 |
+
Each element of `past_key_values` is a tuple (past_key, past_value):
|
| 577 |
+
- past_key: [batch_size * num_heads, head_dim, kv_length]
|
| 578 |
+
- past_value: [batch_size * num_heads, kv_length, head_dim]
|
| 579 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 580 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 581 |
+
|
| 582 |
+
- 1 for tokens that are **not masked**,
|
| 583 |
+
- 0 for tokens that are **masked**.
|
| 584 |
+
|
| 585 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 586 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 587 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 588 |
+
|
| 589 |
+
- 1 indicates the head is **not masked**,
|
| 590 |
+
- 0 indicates the head is **masked**.
|
| 591 |
+
|
| 592 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 593 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 594 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 595 |
+
model's internal embedding lookup matrix.
|
| 596 |
+
|
| 597 |
+
If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
|
| 598 |
+
`past_key_values`).
|
| 599 |
+
use_cache (`bool`, *optional*):
|
| 600 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 601 |
+
`past_key_values`).
|
| 602 |
+
output_attentions (`bool`, *optional*):
|
| 603 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 604 |
+
tensors for more detail.
|
| 605 |
+
output_hidden_states (`bool`, *optional*):
|
| 606 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 607 |
+
more detail.
|
| 608 |
+
return_dict (`bool`, *optional*):
|
| 609 |
+
Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
|
| 610 |
+
"""
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
@add_start_docstrings(
|
| 614 |
+
"The bare Bloom Model transformer outputting raw hidden-states without any specific head on top.",
|
| 615 |
+
BLOOM_START_DOCSTRING,
|
| 616 |
+
)
|
| 617 |
+
class BloomModel(BloomPreTrainedModel):
|
| 618 |
+
def __init__(self, config: BloomConfig):
|
| 619 |
+
super().__init__(config)
|
| 620 |
+
|
| 621 |
+
self.embed_dim = config.hidden_size
|
| 622 |
+
self.num_heads = config.n_head
|
| 623 |
+
|
| 624 |
+
# Embedding + LN Embedding
|
| 625 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, self.embed_dim)
|
| 626 |
+
self.word_embeddings_layernorm = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
|
| 627 |
+
|
| 628 |
+
# Transformer blocks
|
| 629 |
+
self.h = nn.ModuleList([BloomBlock(config) for _ in range(config.num_hidden_layers)])
|
| 630 |
+
|
| 631 |
+
# Final Layer Norm
|
| 632 |
+
self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
|
| 633 |
+
|
| 634 |
+
self.gradient_checkpointing = False
|
| 635 |
+
|
| 636 |
+
# Initialize weights and apply final processing
|
| 637 |
+
self.post_init()
|
| 638 |
+
|
| 639 |
+
def build_alibi_tensor(self, attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
|
| 640 |
+
return build_alibi_tensor(attention_mask, num_heads, dtype)
|
| 641 |
+
|
| 642 |
+
def get_input_embeddings(self):
|
| 643 |
+
return self.word_embeddings
|
| 644 |
+
|
| 645 |
+
def _prepare_attn_mask(
|
| 646 |
+
self, attention_mask: torch.Tensor, input_shape: Tuple[int, int], past_key_values_length: int
|
| 647 |
+
) -> torch.BoolTensor:
|
| 648 |
+
# create causal mask
|
| 649 |
+
# [batch_size, seq_length] -> [batch_size, 1, tgt_length, src_length]
|
| 650 |
+
combined_attention_mask = None
|
| 651 |
+
device = attention_mask.device
|
| 652 |
+
_, src_length = input_shape
|
| 653 |
+
|
| 654 |
+
if src_length > 1:
|
| 655 |
+
combined_attention_mask = _make_causal_mask(
|
| 656 |
+
input_shape, device=device, past_key_values_length=past_key_values_length
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
# [batch_size, seq_length] -> [batch_size, 1, tgt_length, src_length]
|
| 660 |
+
expanded_attn_mask = _expand_mask(attention_mask, tgt_length=src_length)
|
| 661 |
+
combined_attention_mask = (
|
| 662 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
return combined_attention_mask
|
| 666 |
+
|
| 667 |
+
def set_input_embeddings(self, new_embeddings: torch.Tensor):
|
| 668 |
+
self.word_embeddings = new_embeddings
|
| 669 |
+
|
| 670 |
+
@add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING)
|
| 671 |
+
@add_code_sample_docstrings(
|
| 672 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 673 |
+
output_type=BaseModelOutputWithPastAndCrossAttentions,
|
| 674 |
+
config_class=_CONFIG_FOR_DOC,
|
| 675 |
+
)
|
| 676 |
+
def forward(
|
| 677 |
+
self,
|
| 678 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 679 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
| 680 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 681 |
+
head_mask: Optional[torch.LongTensor] = None,
|
| 682 |
+
inputs_embeds: Optional[torch.LongTensor] = None,
|
| 683 |
+
use_cache: Optional[bool] = None,
|
| 684 |
+
output_attentions: Optional[bool] = None,
|
| 685 |
+
output_hidden_states: Optional[bool] = None,
|
| 686 |
+
return_dict: Optional[bool] = None,
|
| 687 |
+
**deprecated_arguments,
|
| 688 |
+
) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
|
| 689 |
+
if deprecated_arguments.pop("position_ids", False) is not False:
|
| 690 |
+
# `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
|
| 691 |
+
warnings.warn(
|
| 692 |
+
"`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
|
| 693 |
+
" passing `position_ids`.",
|
| 694 |
+
FutureWarning,
|
| 695 |
+
)
|
| 696 |
+
if len(deprecated_arguments) > 0:
|
| 697 |
+
raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
|
| 698 |
+
|
| 699 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 700 |
+
output_hidden_states = (
|
| 701 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 702 |
+
)
|
| 703 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 704 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 705 |
+
|
| 706 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 707 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 708 |
+
elif input_ids is not None:
|
| 709 |
+
batch_size, seq_length = input_ids.shape
|
| 710 |
+
elif inputs_embeds is not None:
|
| 711 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
| 712 |
+
else:
|
| 713 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 714 |
+
|
| 715 |
+
if past_key_values is None:
|
| 716 |
+
past_key_values = tuple([None] * len(self.h))
|
| 717 |
+
|
| 718 |
+
# Prepare head mask if needed
|
| 719 |
+
# 1.0 in head_mask indicate we keep the head
|
| 720 |
+
# attention_probs has shape batch_size x num_heads x N x N
|
| 721 |
+
# head_mask has shape n_layer x batch x num_heads x N x N
|
| 722 |
+
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
|
| 723 |
+
|
| 724 |
+
if inputs_embeds is None:
|
| 725 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 726 |
+
|
| 727 |
+
hidden_states = self.word_embeddings_layernorm(inputs_embeds)
|
| 728 |
+
|
| 729 |
+
presents = () if use_cache else None
|
| 730 |
+
all_self_attentions = () if output_attentions else None
|
| 731 |
+
all_hidden_states = () if output_hidden_states else None
|
| 732 |
+
|
| 733 |
+
if self.gradient_checkpointing and self.training:
|
| 734 |
+
if use_cache:
|
| 735 |
+
logger.warning_once(
|
| 736 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 737 |
+
)
|
| 738 |
+
use_cache = False
|
| 739 |
+
|
| 740 |
+
# Compute alibi tensor: check build_alibi_tensor documentation
|
| 741 |
+
seq_length_with_past = seq_length
|
| 742 |
+
past_key_values_length = 0
|
| 743 |
+
if past_key_values[0] is not None:
|
| 744 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
| 745 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
| 746 |
+
if attention_mask is None:
|
| 747 |
+
attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
|
| 748 |
+
else:
|
| 749 |
+
attention_mask = attention_mask.to(hidden_states.device)
|
| 750 |
+
|
| 751 |
+
alibi = self.build_alibi_tensor(attention_mask, self.num_heads, dtype=hidden_states.dtype)
|
| 752 |
+
|
| 753 |
+
causal_mask = self._prepare_attn_mask(
|
| 754 |
+
attention_mask,
|
| 755 |
+
input_shape=(batch_size, seq_length),
|
| 756 |
+
past_key_values_length=past_key_values_length,
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
|
| 760 |
+
if output_hidden_states:
|
| 761 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 762 |
+
|
| 763 |
+
if self.gradient_checkpointing and self.training:
|
| 764 |
+
|
| 765 |
+
def create_custom_forward(module):
|
| 766 |
+
def custom_forward(*inputs):
|
| 767 |
+
# None for past_key_value
|
| 768 |
+
return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
|
| 769 |
+
|
| 770 |
+
return custom_forward
|
| 771 |
+
|
| 772 |
+
outputs = torch.utils.checkpoint.checkpoint(
|
| 773 |
+
create_custom_forward(block),
|
| 774 |
+
hidden_states,
|
| 775 |
+
alibi,
|
| 776 |
+
causal_mask,
|
| 777 |
+
layer_past,
|
| 778 |
+
head_mask[i],
|
| 779 |
+
)
|
| 780 |
+
else:
|
| 781 |
+
outputs = block(
|
| 782 |
+
hidden_states,
|
| 783 |
+
layer_past=layer_past,
|
| 784 |
+
attention_mask=causal_mask,
|
| 785 |
+
head_mask=head_mask[i],
|
| 786 |
+
use_cache=use_cache,
|
| 787 |
+
output_attentions=output_attentions,
|
| 788 |
+
alibi=alibi,
|
| 789 |
+
)
|
| 790 |
+
|
| 791 |
+
hidden_states = outputs[0]
|
| 792 |
+
if use_cache is True:
|
| 793 |
+
presents = presents + (outputs[1],)
|
| 794 |
+
|
| 795 |
+
if output_attentions:
|
| 796 |
+
all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
|
| 797 |
+
|
| 798 |
+
# Add last hidden state
|
| 799 |
+
hidden_states = self.ln_f(hidden_states)
|
| 800 |
+
|
| 801 |
+
if output_hidden_states:
|
| 802 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 803 |
+
|
| 804 |
+
if not return_dict:
|
| 805 |
+
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
|
| 806 |
+
|
| 807 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 808 |
+
last_hidden_state=hidden_states,
|
| 809 |
+
past_key_values=presents,
|
| 810 |
+
hidden_states=all_hidden_states,
|
| 811 |
+
attentions=all_self_attentions,
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
@add_start_docstrings(
|
| 816 |
+
"""
|
| 817 |
+
The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
| 818 |
+
embeddings).
|
| 819 |
+
""",
|
| 820 |
+
BLOOM_START_DOCSTRING,
|
| 821 |
+
)
|
| 822 |
+
class BloomForCausalLM(BloomPreTrainedModel):
|
| 823 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 824 |
+
|
| 825 |
+
def __init__(self, config: BloomConfig):
|
| 826 |
+
super().__init__(config)
|
| 827 |
+
self.transformer = BloomModel(config)
|
| 828 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 829 |
+
|
| 830 |
+
# Initialize weights and apply final processing
|
| 831 |
+
self.post_init()
|
| 832 |
+
|
| 833 |
+
def get_output_embeddings(self):
|
| 834 |
+
return self.lm_head
|
| 835 |
+
|
| 836 |
+
def set_output_embeddings(self, new_embeddings: torch.Tensor):
|
| 837 |
+
self.lm_head = new_embeddings
|
| 838 |
+
|
| 839 |
+
def prepare_inputs_for_generation(
|
| 840 |
+
self,
|
| 841 |
+
input_ids: torch.LongTensor,
|
| 842 |
+
past_key_values: Optional[torch.Tensor] = None,
|
| 843 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 844 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 845 |
+
**kwargs,
|
| 846 |
+
) -> dict:
|
| 847 |
+
# only last token for input_ids if past is not None
|
| 848 |
+
if past_key_values:
|
| 849 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
| 850 |
+
|
| 851 |
+
# the cache may be in the stardard format (e.g. in contrastive search), convert to bloom's format if needed
|
| 852 |
+
if past_key_values[0][0].shape[0] == input_ids.shape[0]:
|
| 853 |
+
past_key_values = self._convert_to_bloom_cache(past_key_values)
|
| 854 |
+
|
| 855 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 856 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 857 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 858 |
+
else:
|
| 859 |
+
model_inputs = {"input_ids": input_ids}
|
| 860 |
+
|
| 861 |
+
model_inputs.update(
|
| 862 |
+
{
|
| 863 |
+
"past_key_values": past_key_values,
|
| 864 |
+
"use_cache": kwargs.get("use_cache"),
|
| 865 |
+
"attention_mask": attention_mask,
|
| 866 |
+
}
|
| 867 |
+
)
|
| 868 |
+
return model_inputs
|
| 869 |
+
|
| 870 |
+
@add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING)
|
| 871 |
+
@add_code_sample_docstrings(
|
| 872 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 873 |
+
output_type=CausalLMOutputWithCrossAttentions,
|
| 874 |
+
config_class=_CONFIG_FOR_DOC,
|
| 875 |
+
)
|
| 876 |
+
def forward(
|
| 877 |
+
self,
|
| 878 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 879 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
| 880 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 881 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 882 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 883 |
+
labels: Optional[torch.Tensor] = None,
|
| 884 |
+
use_cache: Optional[bool] = None,
|
| 885 |
+
output_attentions: Optional[bool] = None,
|
| 886 |
+
output_hidden_states: Optional[bool] = None,
|
| 887 |
+
return_dict: Optional[bool] = None,
|
| 888 |
+
**deprecated_arguments,
|
| 889 |
+
) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
|
| 890 |
+
r"""
|
| 891 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 892 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
| 893 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
| 894 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
| 895 |
+
"""
|
| 896 |
+
if deprecated_arguments.pop("position_ids", False) is not False:
|
| 897 |
+
# `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
|
| 898 |
+
warnings.warn(
|
| 899 |
+
"`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
|
| 900 |
+
" passing `position_ids`.",
|
| 901 |
+
FutureWarning,
|
| 902 |
+
)
|
| 903 |
+
if len(deprecated_arguments) > 0:
|
| 904 |
+
raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
|
| 905 |
+
|
| 906 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 907 |
+
|
| 908 |
+
transformer_outputs = self.transformer(
|
| 909 |
+
input_ids,
|
| 910 |
+
past_key_values=past_key_values,
|
| 911 |
+
attention_mask=attention_mask,
|
| 912 |
+
head_mask=head_mask,
|
| 913 |
+
inputs_embeds=inputs_embeds,
|
| 914 |
+
use_cache=use_cache,
|
| 915 |
+
output_attentions=output_attentions,
|
| 916 |
+
output_hidden_states=output_hidden_states,
|
| 917 |
+
return_dict=return_dict,
|
| 918 |
+
)
|
| 919 |
+
hidden_states = transformer_outputs[0]
|
| 920 |
+
|
| 921 |
+
lm_logits = self.lm_head(hidden_states)
|
| 922 |
+
|
| 923 |
+
loss = None
|
| 924 |
+
if labels is not None:
|
| 925 |
+
# move labels to correct device to enable model parallelism
|
| 926 |
+
labels = labels.to(lm_logits.device)
|
| 927 |
+
# Shift so that tokens < n predict n
|
| 928 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
| 929 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 930 |
+
batch_size, seq_length, vocab_size = shift_logits.shape
|
| 931 |
+
# Flatten the tokens
|
| 932 |
+
loss_fct = CrossEntropyLoss()
|
| 933 |
+
loss = loss_fct(
|
| 934 |
+
shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)
|
| 935 |
+
)
|
| 936 |
+
|
| 937 |
+
if not return_dict:
|
| 938 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
| 939 |
+
return ((loss,) + output) if loss is not None else output
|
| 940 |
+
|
| 941 |
+
return CausalLMOutputWithCrossAttentions(
|
| 942 |
+
loss=loss,
|
| 943 |
+
logits=lm_logits,
|
| 944 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 945 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 946 |
+
attentions=transformer_outputs.attentions,
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
def _reorder_cache(
|
| 950 |
+
self, past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
|
| 951 |
+
) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
|
| 952 |
+
"""
|
| 953 |
+
This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
|
| 954 |
+
[`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
|
| 955 |
+
beam_idx at every generation step.
|
| 956 |
+
|
| 957 |
+
Output shares the same memory storage as `past`.
|
| 958 |
+
"""
|
| 959 |
+
standardized_past = self._convert_to_standard_cache(past, batch_size=len(beam_idx))
|
| 960 |
+
|
| 961 |
+
# Get a copy of `beam_idx` on all the devices where we need those indices.
|
| 962 |
+
device_to_beam_idx = {
|
| 963 |
+
past_state.device: beam_idx.to(past_state.device) for layer_past in past for past_state in layer_past
|
| 964 |
+
}
|
| 965 |
+
reordered_past = tuple(
|
| 966 |
+
(
|
| 967 |
+
layer_past[0].index_select(0, device_to_beam_idx[layer_past[0].device]),
|
| 968 |
+
layer_past[1].index_select(0, device_to_beam_idx[layer_past[0].device]),
|
| 969 |
+
)
|
| 970 |
+
for layer_past in standardized_past
|
| 971 |
+
)
|
| 972 |
+
return self._convert_to_bloom_cache(reordered_past)
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
@add_start_docstrings(
|
| 976 |
+
"""
|
| 977 |
+
The Bloom Model transformer with a sequence classification head on top (linear layer).
|
| 978 |
+
|
| 979 |
+
[`BloomForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 980 |
+
(e.g. GPT-1) do.
|
| 981 |
+
|
| 982 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 983 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 984 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 985 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 986 |
+
each row of the batch).
|
| 987 |
+
""",
|
| 988 |
+
BLOOM_START_DOCSTRING,
|
| 989 |
+
)
|
| 990 |
+
class BloomForSequenceClassification(BloomPreTrainedModel):
|
| 991 |
+
def __init__(self, config: BloomConfig):
|
| 992 |
+
super().__init__(config)
|
| 993 |
+
self.num_labels = config.num_labels
|
| 994 |
+
self.transformer = BloomModel(config)
|
| 995 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
|
| 996 |
+
|
| 997 |
+
# Initialize weights and apply final processing
|
| 998 |
+
self.post_init()
|
| 999 |
+
|
| 1000 |
+
@add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING)
|
| 1001 |
+
@add_code_sample_docstrings(
|
| 1002 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1003 |
+
output_type=SequenceClassifierOutputWithPast,
|
| 1004 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1005 |
+
)
|
| 1006 |
+
def forward(
|
| 1007 |
+
self,
|
| 1008 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1009 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
| 1010 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1011 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1012 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1013 |
+
labels: Optional[torch.Tensor] = None,
|
| 1014 |
+
use_cache: Optional[bool] = None,
|
| 1015 |
+
output_attentions: Optional[bool] = None,
|
| 1016 |
+
output_hidden_states: Optional[bool] = None,
|
| 1017 |
+
return_dict: Optional[bool] = None,
|
| 1018 |
+
**deprecated_arguments,
|
| 1019 |
+
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
|
| 1020 |
+
r"""
|
| 1021 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1022 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1023 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1024 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1025 |
+
"""
|
| 1026 |
+
if deprecated_arguments.pop("position_ids", False) is not False:
|
| 1027 |
+
# `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
|
| 1028 |
+
warnings.warn(
|
| 1029 |
+
"`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
|
| 1030 |
+
" passing `position_ids`.",
|
| 1031 |
+
FutureWarning,
|
| 1032 |
+
)
|
| 1033 |
+
if len(deprecated_arguments) > 0:
|
| 1034 |
+
raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
|
| 1035 |
+
|
| 1036 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1037 |
+
|
| 1038 |
+
transformer_outputs = self.transformer(
|
| 1039 |
+
input_ids,
|
| 1040 |
+
past_key_values=past_key_values,
|
| 1041 |
+
attention_mask=attention_mask,
|
| 1042 |
+
head_mask=head_mask,
|
| 1043 |
+
inputs_embeds=inputs_embeds,
|
| 1044 |
+
use_cache=use_cache,
|
| 1045 |
+
output_attentions=output_attentions,
|
| 1046 |
+
output_hidden_states=output_hidden_states,
|
| 1047 |
+
return_dict=return_dict,
|
| 1048 |
+
)
|
| 1049 |
+
|
| 1050 |
+
hidden_states = transformer_outputs[0]
|
| 1051 |
+
logits = self.score(hidden_states)
|
| 1052 |
+
|
| 1053 |
+
if input_ids is not None:
|
| 1054 |
+
batch_size = input_ids.shape[0]
|
| 1055 |
+
else:
|
| 1056 |
+
batch_size = inputs_embeds.shape[0]
|
| 1057 |
+
|
| 1058 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 1059 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 1060 |
+
if self.config.pad_token_id is None:
|
| 1061 |
+
sequence_lengths = -1
|
| 1062 |
+
else:
|
| 1063 |
+
if input_ids is not None:
|
| 1064 |
+
sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
|
| 1065 |
+
else:
|
| 1066 |
+
sequence_lengths = -1
|
| 1067 |
+
logger.warning(
|
| 1068 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
| 1069 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
| 1070 |
+
)
|
| 1071 |
+
|
| 1072 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
| 1073 |
+
|
| 1074 |
+
loss = None
|
| 1075 |
+
if labels is not None:
|
| 1076 |
+
if self.config.problem_type is None:
|
| 1077 |
+
if self.num_labels == 1:
|
| 1078 |
+
self.config.problem_type = "regression"
|
| 1079 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1080 |
+
self.config.problem_type = "single_label_classification"
|
| 1081 |
+
else:
|
| 1082 |
+
self.config.problem_type = "multi_label_classification"
|
| 1083 |
+
|
| 1084 |
+
if self.config.problem_type == "regression":
|
| 1085 |
+
loss_fct = MSELoss()
|
| 1086 |
+
if self.num_labels == 1:
|
| 1087 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
| 1088 |
+
else:
|
| 1089 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1090 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1091 |
+
loss_fct = CrossEntropyLoss()
|
| 1092 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1093 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1094 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1095 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1096 |
+
if not return_dict:
|
| 1097 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1098 |
+
return ((loss,) + output) if loss is not None else output
|
| 1099 |
+
|
| 1100 |
+
return SequenceClassifierOutputWithPast(
|
| 1101 |
+
loss=loss,
|
| 1102 |
+
logits=pooled_logits,
|
| 1103 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 1104 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1105 |
+
attentions=transformer_outputs.attentions,
|
| 1106 |
+
)
|
| 1107 |
+
|
| 1108 |
+
|
| 1109 |
+
@add_start_docstrings(
|
| 1110 |
+
"""
|
| 1111 |
+
Bloom Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1112 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1113 |
+
""",
|
| 1114 |
+
BLOOM_START_DOCSTRING,
|
| 1115 |
+
)
|
| 1116 |
+
class BloomForTokenClassification(BloomPreTrainedModel):
|
| 1117 |
+
def __init__(self, config: BloomConfig):
|
| 1118 |
+
super().__init__(config)
|
| 1119 |
+
self.num_labels = config.num_labels
|
| 1120 |
+
|
| 1121 |
+
self.transformer = BloomModel(config)
|
| 1122 |
+
if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
|
| 1123 |
+
classifier_dropout = config.classifier_dropout
|
| 1124 |
+
elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
|
| 1125 |
+
classifier_dropout = config.hidden_dropout
|
| 1126 |
+
else:
|
| 1127 |
+
classifier_dropout = 0.1
|
| 1128 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1129 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1130 |
+
|
| 1131 |
+
# Initialize weights and apply final processing
|
| 1132 |
+
self.post_init()
|
| 1133 |
+
|
| 1134 |
+
@add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING)
|
| 1135 |
+
@add_code_sample_docstrings(
|
| 1136 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1137 |
+
output_type=TokenClassifierOutput,
|
| 1138 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1139 |
+
)
|
| 1140 |
+
def forward(
|
| 1141 |
+
self,
|
| 1142 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1143 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
| 1144 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1145 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1146 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1147 |
+
labels: Optional[torch.Tensor] = None,
|
| 1148 |
+
use_cache: Optional[bool] = None,
|
| 1149 |
+
output_attentions: Optional[bool] = None,
|
| 1150 |
+
output_hidden_states: Optional[bool] = None,
|
| 1151 |
+
return_dict: Optional[bool] = None,
|
| 1152 |
+
**deprecated_arguments,
|
| 1153 |
+
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
|
| 1154 |
+
r"""
|
| 1155 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1156 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1157 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1158 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1159 |
+
"""
|
| 1160 |
+
if deprecated_arguments.pop("position_ids", False) is not False:
|
| 1161 |
+
# `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
|
| 1162 |
+
warnings.warn(
|
| 1163 |
+
"`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
|
| 1164 |
+
" passing `position_ids`.",
|
| 1165 |
+
FutureWarning,
|
| 1166 |
+
)
|
| 1167 |
+
if len(deprecated_arguments) > 0:
|
| 1168 |
+
raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
|
| 1169 |
+
|
| 1170 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1171 |
+
|
| 1172 |
+
transformer_outputs = self.transformer(
|
| 1173 |
+
input_ids,
|
| 1174 |
+
past_key_values=past_key_values,
|
| 1175 |
+
attention_mask=attention_mask,
|
| 1176 |
+
head_mask=head_mask,
|
| 1177 |
+
inputs_embeds=inputs_embeds,
|
| 1178 |
+
use_cache=use_cache,
|
| 1179 |
+
output_attentions=output_attentions,
|
| 1180 |
+
output_hidden_states=output_hidden_states,
|
| 1181 |
+
return_dict=return_dict,
|
| 1182 |
+
)
|
| 1183 |
+
|
| 1184 |
+
hidden_states = transformer_outputs[0]
|
| 1185 |
+
hidden_states = self.dropout(hidden_states)
|
| 1186 |
+
logits = self.classifier(hidden_states)
|
| 1187 |
+
|
| 1188 |
+
loss = None
|
| 1189 |
+
if labels is not None:
|
| 1190 |
+
# move labels to correct device to enable model parallelism
|
| 1191 |
+
labels = labels.to(logits.device)
|
| 1192 |
+
batch_size, seq_length = labels.shape
|
| 1193 |
+
loss_fct = CrossEntropyLoss()
|
| 1194 |
+
loss = loss_fct(
|
| 1195 |
+
logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
|
| 1196 |
+
)
|
| 1197 |
+
|
| 1198 |
+
if not return_dict:
|
| 1199 |
+
output = (logits,) + transformer_outputs[2:]
|
| 1200 |
+
return ((loss,) + output) if loss is not None else output
|
| 1201 |
+
|
| 1202 |
+
return TokenClassifierOutput(
|
| 1203 |
+
loss=loss,
|
| 1204 |
+
logits=logits,
|
| 1205 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1206 |
+
attentions=transformer_outputs.attentions,
|
| 1207 |
+
)
|
| 1208 |
+
|
| 1209 |
+
|
| 1210 |
+
@add_start_docstrings(
|
| 1211 |
+
"""
|
| 1212 |
+
The BLOOM Model transformer with a span classification head on top for extractive question-answering tasks like
|
| 1213 |
+
SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1214 |
+
""",
|
| 1215 |
+
BLOOM_START_DOCSTRING,
|
| 1216 |
+
)
|
| 1217 |
+
class BloomForQuestionAnswering(BloomPreTrainedModel):
|
| 1218 |
+
def __init__(self, config):
|
| 1219 |
+
super().__init__(config)
|
| 1220 |
+
self.transformer = BloomModel(config)
|
| 1221 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
| 1222 |
+
|
| 1223 |
+
# Initialize weights and apply final processing
|
| 1224 |
+
self.post_init()
|
| 1225 |
+
|
| 1226 |
+
@add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1227 |
+
def forward(
|
| 1228 |
+
self,
|
| 1229 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1230 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1231 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1232 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1233 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1234 |
+
start_positions: Optional[torch.LongTensor] = None,
|
| 1235 |
+
end_positions: Optional[torch.LongTensor] = None,
|
| 1236 |
+
output_attentions: Optional[bool] = None,
|
| 1237 |
+
output_hidden_states: Optional[bool] = None,
|
| 1238 |
+
return_dict: Optional[bool] = None,
|
| 1239 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
| 1240 |
+
r"""
|
| 1241 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1242 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1243 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1244 |
+
are not taken into account for computing the loss.
|
| 1245 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1246 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1247 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1248 |
+
are not taken into account for computing the loss.
|
| 1249 |
+
"""
|
| 1250 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1251 |
+
|
| 1252 |
+
outputs = self.transformer(
|
| 1253 |
+
input_ids,
|
| 1254 |
+
attention_mask=attention_mask,
|
| 1255 |
+
position_ids=position_ids,
|
| 1256 |
+
head_mask=head_mask,
|
| 1257 |
+
inputs_embeds=inputs_embeds,
|
| 1258 |
+
output_attentions=output_attentions,
|
| 1259 |
+
output_hidden_states=output_hidden_states,
|
| 1260 |
+
return_dict=return_dict,
|
| 1261 |
+
)
|
| 1262 |
+
|
| 1263 |
+
sequence_output = outputs[0]
|
| 1264 |
+
|
| 1265 |
+
logits = self.qa_outputs(sequence_output)
|
| 1266 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1267 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1268 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1269 |
+
|
| 1270 |
+
total_loss = None
|
| 1271 |
+
if start_positions is not None and end_positions is not None:
|
| 1272 |
+
# If we are on multi-GPU, split add a dimension
|
| 1273 |
+
if len(start_positions.size()) > 1:
|
| 1274 |
+
start_positions = start_positions.squeeze(-1)
|
| 1275 |
+
if len(end_positions.size()) > 1:
|
| 1276 |
+
end_positions = end_positions.squeeze(-1)
|
| 1277 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1278 |
+
ignored_index = start_logits.size(1)
|
| 1279 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1280 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1281 |
+
|
| 1282 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1283 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1284 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1285 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1286 |
+
|
| 1287 |
+
if not return_dict:
|
| 1288 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1289 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1290 |
+
|
| 1291 |
+
return QuestionAnsweringModelOutput(
|
| 1292 |
+
loss=total_loss,
|
| 1293 |
+
start_logits=start_logits,
|
| 1294 |
+
end_logits=end_logits,
|
| 1295 |
+
hidden_states=outputs.hidden_states,
|
| 1296 |
+
attentions=outputs.attentions,
|
| 1297 |
+
)
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bloom/modeling_flax_bloom.py
ADDED
|
@@ -0,0 +1,734 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 HuggingFace Inc. Team and Bigscience Workshop. 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 BLOOM model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from functools import partial
|
| 19 |
+
from typing import Optional, Tuple
|
| 20 |
+
|
| 21 |
+
import flax.linen as nn
|
| 22 |
+
import jax
|
| 23 |
+
import jax.numpy as jnp
|
| 24 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
| 25 |
+
from flax.linen import combine_masks, dot_product_attention_weights, make_causal_mask
|
| 26 |
+
from flax.linen.activation import tanh
|
| 27 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 28 |
+
from jax import lax
|
| 29 |
+
|
| 30 |
+
from ...modeling_flax_outputs import (
|
| 31 |
+
FlaxBaseModelOutput,
|
| 32 |
+
FlaxBaseModelOutputWithPastAndCrossAttentions,
|
| 33 |
+
FlaxCausalLMOutput,
|
| 34 |
+
)
|
| 35 |
+
from ...modeling_flax_utils import FlaxPreTrainedModel, append_call_sample_docstring
|
| 36 |
+
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 37 |
+
from .configuration_bloom import BloomConfig
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
_CHECKPOINT_FOR_DOC = "bigscience/bloom"
|
| 43 |
+
_CONFIG_FOR_DOC = "BloomConfig"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
BLOOM_START_DOCSTRING = r"""
|
| 47 |
+
|
| 48 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 49 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 50 |
+
etc.)
|
| 51 |
+
|
| 52 |
+
This model is also a Flax Linen
|
| 53 |
+
[flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
|
| 54 |
+
regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
|
| 55 |
+
|
| 56 |
+
Finally, this model supports inherent JAX features such as:
|
| 57 |
+
|
| 58 |
+
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
|
| 59 |
+
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
|
| 60 |
+
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
|
| 61 |
+
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
|
| 62 |
+
|
| 63 |
+
Parameters:
|
| 64 |
+
config ([`BloomConfig`]): Model configuration class with all the parameters of the model.
|
| 65 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 66 |
+
configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 67 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
| 68 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
| 69 |
+
`jax.numpy.bfloat16` (on TPUs).
|
| 70 |
+
|
| 71 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
| 72 |
+
specified all the computation will be performed with the given `dtype`.
|
| 73 |
+
|
| 74 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
| 75 |
+
parameters.**
|
| 76 |
+
|
| 77 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
| 78 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
BLOOM_INPUTS_DOCSTRING = r"""
|
| 82 |
+
Args:
|
| 83 |
+
input_ids (`numpy.ndarray` of shape `(batch_size, input_ids_length)`):
|
| 84 |
+
`input_ids_length` = `sequence_length`. Indices of input sequence tokens in the vocabulary.
|
| 85 |
+
|
| 86 |
+
Indices can be obtained using [`BloomTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 87 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 88 |
+
|
| 89 |
+
[What are input IDs?](../glossary#input-ids)
|
| 90 |
+
attention_mask (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 91 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 92 |
+
|
| 93 |
+
- 1 for tokens that are **not masked**,
|
| 94 |
+
- 0 for tokens that are **masked**.
|
| 95 |
+
|
| 96 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 97 |
+
past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
|
| 98 |
+
Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
|
| 99 |
+
auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
|
| 100 |
+
output_attentions (`bool`, *optional*):
|
| 101 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 102 |
+
tensors for more detail.
|
| 103 |
+
output_hidden_states (`bool`, *optional*):
|
| 104 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 105 |
+
more detail.
|
| 106 |
+
return_dict (`bool`, *optional*):
|
| 107 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def build_alibi_tensor(attention_mask: jnp.ndarray, num_heads: int, dtype: Optional[jnp.dtype] = jnp.float32):
|
| 112 |
+
"""
|
| 113 |
+
Flax implementation of the BLOOM Alibi tensor. BLOOM Alibi tensor is not causal as the original paper mentions, it
|
| 114 |
+
relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value
|
| 115 |
+
`softmax(l+a) = softmax(l)`. Based on
|
| 116 |
+
https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742
|
| 117 |
+
Link to paper: https://arxiv.org/abs/2108.12409
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
attention_mask (`jnp.ndarray`):
|
| 121 |
+
Token-wise attention mask, this should be of shape `(batch_size, max_seq_len)`.
|
| 122 |
+
num_heads (`int`):
|
| 123 |
+
Number of attention heads.
|
| 124 |
+
dtype (`jnp.dtype`, *optional*, defaults to `jnp.float32`):
|
| 125 |
+
The data type (dtype) of the output tensor.
|
| 126 |
+
|
| 127 |
+
Returns: Alibi tensor of shape `(batch_size * num_heads, 1, max_seq_len)`.
|
| 128 |
+
"""
|
| 129 |
+
batch_size, seq_length = attention_mask.shape
|
| 130 |
+
closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
|
| 131 |
+
base = jnp.array(2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), dtype=jnp.float32)
|
| 132 |
+
powers = jnp.arange(1, 1 + closest_power_of_2, dtype=jnp.float32)
|
| 133 |
+
slopes = jax.lax.pow(base, powers)
|
| 134 |
+
|
| 135 |
+
if closest_power_of_2 != num_heads:
|
| 136 |
+
extra_base = jnp.array(2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), dtype=jnp.float32)
|
| 137 |
+
num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
|
| 138 |
+
extra_powers = jnp.arange(1, 1 + 2 * num_remaining_heads, 2, dtype=jnp.float32)
|
| 139 |
+
slopes = jnp.cat([slopes, jax.lax.pow(extra_base, extra_powers)], axis=0)
|
| 140 |
+
|
| 141 |
+
# Note: the Alibi tensor will added to the attention bias that will be applied to the query, key product of attention
|
| 142 |
+
# therefore, Alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
|
| 143 |
+
# => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
|
| 144 |
+
# so that the query_length dimension will then be broadcast correctly.
|
| 145 |
+
# This is more or less identical to T5's relative position bias:
|
| 146 |
+
# https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
|
| 147 |
+
arange_tensor = ((attention_mask.cumsum(axis=-1) - 1) * attention_mask)[:, None, :]
|
| 148 |
+
alibi = slopes[..., None] * arange_tensor
|
| 149 |
+
alibi = jnp.expand_dims(alibi, axis=2)
|
| 150 |
+
return jnp.asarray(alibi, dtype)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class FlaxBloomAttention(nn.Module):
|
| 154 |
+
config: BloomConfig
|
| 155 |
+
dtype: jnp.dtype = jnp.float32
|
| 156 |
+
|
| 157 |
+
def setup(self):
|
| 158 |
+
self.hidden_size = self.config.hidden_size
|
| 159 |
+
self.num_heads = self.config.n_head
|
| 160 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 161 |
+
self.attention_softmax_in_fp32 = self.dtype is not jnp.float32
|
| 162 |
+
|
| 163 |
+
if self.head_dim * self.num_heads != self.hidden_size:
|
| 164 |
+
raise ValueError(
|
| 165 |
+
f"`hidden_size` must be divisible by `num_heads` (got `hidden_size`: {self.hidden_size} and "
|
| 166 |
+
f"`num_heads`: {self.num_heads})."
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
dense = partial(
|
| 170 |
+
nn.Dense,
|
| 171 |
+
dtype=self.dtype,
|
| 172 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
self.query_key_value = dense(self.hidden_size * 3)
|
| 176 |
+
self.dense = dense(self.hidden_size)
|
| 177 |
+
self.resid_dropout = nn.Dropout(rate=self.config.hidden_dropout)
|
| 178 |
+
|
| 179 |
+
def _split_heads(self, hidden_states):
|
| 180 |
+
return hidden_states.reshape(hidden_states.shape[:-1] + (self.num_heads, self.head_dim * 3))
|
| 181 |
+
|
| 182 |
+
def _merge_heads(self, hidden_states):
|
| 183 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (self.hidden_size,))
|
| 184 |
+
|
| 185 |
+
@nn.compact
|
| 186 |
+
# Copied from transformers.models.gptj.modeling_flax_gptj.FlaxGPTJAttention._concatenate_to_cache
|
| 187 |
+
def _concatenate_to_cache(self, key, value, query, attention_mask):
|
| 188 |
+
"""
|
| 189 |
+
This function takes projected key, value states from a single input token and concatenates the states to cached
|
| 190 |
+
states from previous steps. This function is slighly adapted from the official Flax repository:
|
| 191 |
+
https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
|
| 192 |
+
"""
|
| 193 |
+
# detect if we're initializing by absence of existing cache data.
|
| 194 |
+
is_initialized = self.has_variable("cache", "cached_key")
|
| 195 |
+
cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
|
| 196 |
+
cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
|
| 197 |
+
cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
|
| 198 |
+
|
| 199 |
+
if is_initialized:
|
| 200 |
+
*batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
|
| 201 |
+
# update key, value caches with our new 1d spatial slices
|
| 202 |
+
cur_index = cache_index.value
|
| 203 |
+
indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
|
| 204 |
+
key = lax.dynamic_update_slice(cached_key.value, key, indices)
|
| 205 |
+
value = lax.dynamic_update_slice(cached_value.value, value, indices)
|
| 206 |
+
cached_key.value = key
|
| 207 |
+
cached_value.value = value
|
| 208 |
+
num_updated_cache_vectors = query.shape[1]
|
| 209 |
+
cache_index.value = cache_index.value + num_updated_cache_vectors
|
| 210 |
+
# causal mask for cached decoder self-attention: our single query position should only attend to those key
|
| 211 |
+
# positions that have already been generated and cached, not the remaining zero elements.
|
| 212 |
+
pad_mask = jnp.broadcast_to(
|
| 213 |
+
jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
|
| 214 |
+
tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
|
| 215 |
+
)
|
| 216 |
+
attention_mask = combine_masks(pad_mask, attention_mask)
|
| 217 |
+
return key, value, attention_mask
|
| 218 |
+
|
| 219 |
+
def __call__(
|
| 220 |
+
self,
|
| 221 |
+
hidden_states,
|
| 222 |
+
residual,
|
| 223 |
+
alibi,
|
| 224 |
+
attention_mask=None,
|
| 225 |
+
deterministic: bool = True,
|
| 226 |
+
init_cache: bool = False,
|
| 227 |
+
output_attentions: bool = False,
|
| 228 |
+
):
|
| 229 |
+
batch_size, seq_length = hidden_states.shape[:2]
|
| 230 |
+
|
| 231 |
+
# proj q, k, v
|
| 232 |
+
fused_qkv = self.query_key_value(hidden_states)
|
| 233 |
+
fused_qkv = self._split_heads(fused_qkv)
|
| 234 |
+
query, key, value = jnp.split(fused_qkv, 3, axis=-1)
|
| 235 |
+
|
| 236 |
+
causal_attention_mask = make_causal_mask(attention_mask, dtype="bool")
|
| 237 |
+
|
| 238 |
+
# for fast decoding causal attention mask should be shifted
|
| 239 |
+
causal_attention_mask_shift = (
|
| 240 |
+
self.variables["cache"]["cache_index"] if self.has_variable("cache", "cached_key") else 0
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
# fast decoding for generate requires special attention_mask
|
| 244 |
+
if self.has_variable("cache", "cached_key"):
|
| 245 |
+
max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
|
| 246 |
+
causal_attention_mask = jax.lax.dynamic_slice(
|
| 247 |
+
causal_attention_mask,
|
| 248 |
+
(0, 0, causal_attention_mask_shift, 0),
|
| 249 |
+
(1, 1, seq_length, max_decoder_length),
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
# broadcast causal attention mask & attention mask to fit for merge
|
| 253 |
+
causal_attention_mask = jnp.broadcast_to(
|
| 254 |
+
causal_attention_mask, (batch_size,) + causal_attention_mask.shape[1:]
|
| 255 |
+
)
|
| 256 |
+
attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_attention_mask.shape)
|
| 257 |
+
attention_mask = combine_masks(attention_mask, causal_attention_mask)
|
| 258 |
+
|
| 259 |
+
dropout_rng = None
|
| 260 |
+
if not deterministic and self.config.attention_dropout > 0.0:
|
| 261 |
+
dropout_rng = self.make_rng("dropout")
|
| 262 |
+
|
| 263 |
+
# During fast autoregressive decoding, we feed one position at a time,
|
| 264 |
+
# and cache the keys and values step by step.
|
| 265 |
+
if self.has_variable("cache", "cached_key") or init_cache:
|
| 266 |
+
key, value, attention_mask = self._concatenate_to_cache(key, value, query, attention_mask)
|
| 267 |
+
|
| 268 |
+
# transform boolean mask into float mask
|
| 269 |
+
mask_value = jnp.finfo(self.dtype).min
|
| 270 |
+
attention_bias = lax.select(
|
| 271 |
+
attention_mask > 0,
|
| 272 |
+
jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
|
| 273 |
+
jnp.full(attention_mask.shape, mask_value).astype(self.dtype),
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
attention_bias = attention_bias + alibi
|
| 277 |
+
|
| 278 |
+
# Cast in fp32 if the original dtype is different from fp32
|
| 279 |
+
attention_dtype = jnp.float32 if self.attention_softmax_in_fp32 else self.dtype
|
| 280 |
+
|
| 281 |
+
attn_weights = dot_product_attention_weights(
|
| 282 |
+
query,
|
| 283 |
+
key,
|
| 284 |
+
bias=attention_bias,
|
| 285 |
+
dropout_rng=dropout_rng,
|
| 286 |
+
dropout_rate=self.config.attention_dropout,
|
| 287 |
+
deterministic=deterministic,
|
| 288 |
+
dtype=attention_dtype,
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
# Cast back in the original dtype if the native dtype is not fp32
|
| 292 |
+
if self.attention_softmax_in_fp32:
|
| 293 |
+
attn_weights = attn_weights.astype(self.dtype)
|
| 294 |
+
|
| 295 |
+
attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value)
|
| 296 |
+
attn_output = self._merge_heads(attn_output)
|
| 297 |
+
attn_output = self.dense(attn_output)
|
| 298 |
+
attn_output = self.resid_dropout(attn_output, deterministic=deterministic)
|
| 299 |
+
|
| 300 |
+
attn_output = attn_output + residual
|
| 301 |
+
|
| 302 |
+
outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
|
| 303 |
+
return outputs
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
class BloomGELU(nn.Module):
|
| 307 |
+
def setup(self):
|
| 308 |
+
self.dtype = jnp.float32
|
| 309 |
+
|
| 310 |
+
def __call__(self, x):
|
| 311 |
+
return x * 0.5 * (1.0 + tanh(0.79788456 * x * (1 + 0.044715 * x * x)))
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
class FlaxBloomMLP(nn.Module):
|
| 315 |
+
config: BloomConfig
|
| 316 |
+
dtype: jnp.dtype = jnp.float32
|
| 317 |
+
|
| 318 |
+
def setup(self):
|
| 319 |
+
hidden_size = self.config.hidden_size
|
| 320 |
+
|
| 321 |
+
kernel_init = jax.nn.initializers.normal(self.config.initializer_range)
|
| 322 |
+
|
| 323 |
+
self.dense_h_to_4h = nn.Dense(4 * hidden_size, dtype=self.dtype, kernel_init=kernel_init)
|
| 324 |
+
self.dense_4h_to_h = nn.Dense(hidden_size, dtype=self.dtype, kernel_init=kernel_init)
|
| 325 |
+
self.hidden_dropout = nn.Dropout(self.config.hidden_dropout)
|
| 326 |
+
self.act = BloomGELU()
|
| 327 |
+
|
| 328 |
+
def __call__(self, hidden_states, residual, deterministic: bool = True):
|
| 329 |
+
hidden_states = self.dense_h_to_4h(hidden_states)
|
| 330 |
+
hidden_states = self.act(hidden_states)
|
| 331 |
+
|
| 332 |
+
intermediate_output = self.dense_4h_to_h(hidden_states)
|
| 333 |
+
|
| 334 |
+
intermediate_output = intermediate_output + residual
|
| 335 |
+
hidden_states = self.hidden_dropout(intermediate_output, deterministic=deterministic)
|
| 336 |
+
|
| 337 |
+
return hidden_states
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
class FlaxBloomBlock(nn.Module):
|
| 341 |
+
config: BloomConfig
|
| 342 |
+
dtype: jnp.dtype = jnp.float32
|
| 343 |
+
|
| 344 |
+
def setup(self):
|
| 345 |
+
self.input_layernorm = nn.LayerNorm(epsilon=self.config.layer_norm_epsilon, dtype=self.dtype)
|
| 346 |
+
|
| 347 |
+
self.self_attention = FlaxBloomAttention(self.config, dtype=self.dtype)
|
| 348 |
+
self.post_attention_layernorm = nn.LayerNorm(epsilon=self.config.layer_norm_epsilon, dtype=self.dtype)
|
| 349 |
+
|
| 350 |
+
self.mlp = FlaxBloomMLP(self.config, dtype=self.dtype)
|
| 351 |
+
|
| 352 |
+
self.apply_residual_connection_post_layernorm = self.config.apply_residual_connection_post_layernorm
|
| 353 |
+
self.hidden_dropout = self.config.hidden_dropout
|
| 354 |
+
|
| 355 |
+
def __call__(
|
| 356 |
+
self,
|
| 357 |
+
hidden_states,
|
| 358 |
+
alibi,
|
| 359 |
+
attention_mask=None,
|
| 360 |
+
deterministic: bool = True,
|
| 361 |
+
init_cache: bool = False,
|
| 362 |
+
output_attentions: bool = False,
|
| 363 |
+
):
|
| 364 |
+
layernorm_output = self.input_layernorm(hidden_states)
|
| 365 |
+
|
| 366 |
+
# layer norm before saving residual if config calls for it
|
| 367 |
+
if self.apply_residual_connection_post_layernorm:
|
| 368 |
+
residual = layernorm_output
|
| 369 |
+
else:
|
| 370 |
+
residual = hidden_states
|
| 371 |
+
|
| 372 |
+
# self-attention
|
| 373 |
+
attn_outputs = self.self_attention(
|
| 374 |
+
layernorm_output,
|
| 375 |
+
residual=residual,
|
| 376 |
+
alibi=alibi,
|
| 377 |
+
attention_mask=attention_mask,
|
| 378 |
+
deterministic=deterministic,
|
| 379 |
+
init_cache=init_cache,
|
| 380 |
+
output_attentions=output_attentions,
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
attention_output = attn_outputs[0]
|
| 384 |
+
|
| 385 |
+
outputs = attn_outputs[1:]
|
| 386 |
+
|
| 387 |
+
post_layernorm = self.post_attention_layernorm(attention_output)
|
| 388 |
+
|
| 389 |
+
# set residual based on config
|
| 390 |
+
if self.apply_residual_connection_post_layernorm:
|
| 391 |
+
residual = post_layernorm
|
| 392 |
+
else:
|
| 393 |
+
residual = attention_output
|
| 394 |
+
|
| 395 |
+
output = self.mlp(post_layernorm, residual, deterministic=deterministic)
|
| 396 |
+
|
| 397 |
+
outputs = (output,) + outputs
|
| 398 |
+
|
| 399 |
+
return outputs
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class FlaxBloomPreTrainedModel(FlaxPreTrainedModel):
|
| 403 |
+
"""
|
| 404 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 405 |
+
models.
|
| 406 |
+
"""
|
| 407 |
+
|
| 408 |
+
config_class = BloomConfig
|
| 409 |
+
base_model_prefix = "transformer"
|
| 410 |
+
module_class: nn.Module = None
|
| 411 |
+
|
| 412 |
+
def __init__(
|
| 413 |
+
self,
|
| 414 |
+
config: BloomConfig,
|
| 415 |
+
input_shape: Tuple = (1, 1),
|
| 416 |
+
seed: int = 0,
|
| 417 |
+
dtype: jnp.dtype = jnp.float32,
|
| 418 |
+
_do_init: bool = True,
|
| 419 |
+
**kwargs,
|
| 420 |
+
):
|
| 421 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
| 422 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
| 423 |
+
|
| 424 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
|
| 425 |
+
# init input tensors
|
| 426 |
+
input_ids = jnp.zeros(input_shape, dtype="i4")
|
| 427 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 428 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
| 429 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
| 430 |
+
|
| 431 |
+
random_params = self.module.init(rngs, input_ids, attention_mask, return_dict=False)["params"]
|
| 432 |
+
|
| 433 |
+
if params is not None:
|
| 434 |
+
random_params = flatten_dict(unfreeze(random_params))
|
| 435 |
+
params = flatten_dict(unfreeze(params))
|
| 436 |
+
for missing_key in self._missing_keys:
|
| 437 |
+
params[missing_key] = random_params[missing_key]
|
| 438 |
+
self._missing_keys = set()
|
| 439 |
+
return freeze(unflatten_dict(params))
|
| 440 |
+
else:
|
| 441 |
+
return random_params
|
| 442 |
+
|
| 443 |
+
def init_cache(self, batch_size, max_length):
|
| 444 |
+
r"""
|
| 445 |
+
Args:
|
| 446 |
+
batch_size (`int`):
|
| 447 |
+
batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
|
| 448 |
+
max_length (`int`):
|
| 449 |
+
maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
|
| 450 |
+
cache.
|
| 451 |
+
"""
|
| 452 |
+
# init input variables to retrieve cache
|
| 453 |
+
input_ids = jnp.ones((batch_size, max_length), dtype="i4")
|
| 454 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 455 |
+
|
| 456 |
+
init_variables = self.module.init(
|
| 457 |
+
jax.random.PRNGKey(0), input_ids, attention_mask, return_dict=False, init_cache=True
|
| 458 |
+
)
|
| 459 |
+
return unfreeze(init_variables["cache"])
|
| 460 |
+
|
| 461 |
+
@add_start_docstrings_to_model_forward(BLOOM_INPUTS_DOCSTRING)
|
| 462 |
+
def __call__(
|
| 463 |
+
self,
|
| 464 |
+
input_ids,
|
| 465 |
+
attention_mask=None,
|
| 466 |
+
past_key_values: dict = None,
|
| 467 |
+
params: dict = None,
|
| 468 |
+
dropout_rng: jax.random.PRNGKey = None,
|
| 469 |
+
train: bool = False,
|
| 470 |
+
output_attentions: Optional[bool] = None,
|
| 471 |
+
output_hidden_states: Optional[bool] = None,
|
| 472 |
+
return_dict: Optional[bool] = None,
|
| 473 |
+
):
|
| 474 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 475 |
+
output_hidden_states = (
|
| 476 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 477 |
+
)
|
| 478 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 479 |
+
|
| 480 |
+
batch_size, sequence_length = input_ids.shape
|
| 481 |
+
|
| 482 |
+
if attention_mask is None:
|
| 483 |
+
attention_mask = jnp.ones((batch_size, sequence_length))
|
| 484 |
+
|
| 485 |
+
# Handle any PRNG if needed
|
| 486 |
+
rngs = {}
|
| 487 |
+
if dropout_rng is not None:
|
| 488 |
+
rngs["dropout"] = dropout_rng
|
| 489 |
+
|
| 490 |
+
inputs = {"params": params or self.params}
|
| 491 |
+
|
| 492 |
+
# If past_key_values are passed then cache is already initialized a private flag init_cache has to be passed
|
| 493 |
+
# down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be
|
| 494 |
+
# changed by FlaxBloomAttention module
|
| 495 |
+
if past_key_values:
|
| 496 |
+
inputs["cache"] = past_key_values
|
| 497 |
+
mutable = ["cache"]
|
| 498 |
+
else:
|
| 499 |
+
mutable = False
|
| 500 |
+
|
| 501 |
+
outputs = self.module.apply(
|
| 502 |
+
inputs,
|
| 503 |
+
jnp.array(input_ids, dtype="i4"),
|
| 504 |
+
jnp.array(attention_mask, dtype="i4"),
|
| 505 |
+
not train,
|
| 506 |
+
False,
|
| 507 |
+
output_attentions,
|
| 508 |
+
output_hidden_states,
|
| 509 |
+
return_dict,
|
| 510 |
+
rngs=rngs,
|
| 511 |
+
mutable=mutable,
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
# add updated cache to model output
|
| 515 |
+
if past_key_values is not None and return_dict:
|
| 516 |
+
outputs, past_key_values = outputs
|
| 517 |
+
outputs["past_key_values"] = unfreeze(past_key_values["cache"])
|
| 518 |
+
return outputs
|
| 519 |
+
elif past_key_values is not None and not return_dict:
|
| 520 |
+
outputs, past_key_values = outputs
|
| 521 |
+
outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
|
| 522 |
+
|
| 523 |
+
return outputs
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
class FlaxBloomBlockCollection(nn.Module):
|
| 527 |
+
config: BloomConfig
|
| 528 |
+
dtype: jnp.dtype = jnp.float32
|
| 529 |
+
|
| 530 |
+
def setup(self):
|
| 531 |
+
self.layers = [
|
| 532 |
+
FlaxBloomBlock(self.config, name=str(layer_number), dtype=self.dtype)
|
| 533 |
+
for layer_number in range(self.config.num_hidden_layers)
|
| 534 |
+
]
|
| 535 |
+
|
| 536 |
+
def __call__(
|
| 537 |
+
self,
|
| 538 |
+
hidden_states,
|
| 539 |
+
alibi,
|
| 540 |
+
attention_mask=None,
|
| 541 |
+
deterministic: bool = True,
|
| 542 |
+
init_cache: bool = False,
|
| 543 |
+
output_attentions: bool = False,
|
| 544 |
+
output_hidden_states: bool = False,
|
| 545 |
+
):
|
| 546 |
+
all_attentions = () if output_attentions else None
|
| 547 |
+
all_hidden_states = () if output_hidden_states else None
|
| 548 |
+
|
| 549 |
+
for layer_number in range(self.config.num_hidden_layers):
|
| 550 |
+
if output_hidden_states:
|
| 551 |
+
all_hidden_states += (hidden_states,)
|
| 552 |
+
|
| 553 |
+
layer_outputs = self.layers[layer_number](
|
| 554 |
+
hidden_states,
|
| 555 |
+
alibi=alibi,
|
| 556 |
+
attention_mask=attention_mask,
|
| 557 |
+
deterministic=deterministic,
|
| 558 |
+
init_cache=init_cache,
|
| 559 |
+
output_attentions=output_attentions,
|
| 560 |
+
)
|
| 561 |
+
hidden_states = layer_outputs[0]
|
| 562 |
+
|
| 563 |
+
if output_attentions:
|
| 564 |
+
all_attentions += (layer_outputs[1],)
|
| 565 |
+
|
| 566 |
+
# this contains possible `None` values - `FlaxBloomModule` will filter them out
|
| 567 |
+
outputs = (hidden_states, all_hidden_states, all_attentions)
|
| 568 |
+
|
| 569 |
+
return outputs
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
class FlaxBloomModule(nn.Module):
|
| 573 |
+
config: BloomConfig
|
| 574 |
+
dtype: jnp.dtype = jnp.float32
|
| 575 |
+
|
| 576 |
+
def setup(self):
|
| 577 |
+
self.embed_dim = self.config.hidden_size
|
| 578 |
+
|
| 579 |
+
# word embeddings (no positional embedding layer)
|
| 580 |
+
self.word_embeddings = nn.Embed(
|
| 581 |
+
self.config.vocab_size,
|
| 582 |
+
self.embed_dim,
|
| 583 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 584 |
+
dtype=self.dtype,
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
# post-embedding layernorm
|
| 588 |
+
self.word_embeddings_layernorm = nn.LayerNorm(epsilon=self.config.layer_norm_epsilon, dtype=self.dtype)
|
| 589 |
+
|
| 590 |
+
# transformer layers
|
| 591 |
+
self.h = FlaxBloomBlockCollection(self.config, dtype=self.dtype)
|
| 592 |
+
|
| 593 |
+
# final layernorm
|
| 594 |
+
self.ln_f = nn.LayerNorm(epsilon=self.config.layer_norm_epsilon, dtype=self.dtype)
|
| 595 |
+
|
| 596 |
+
def __call__(
|
| 597 |
+
self,
|
| 598 |
+
input_ids=None,
|
| 599 |
+
attention_mask=None,
|
| 600 |
+
deterministic=True,
|
| 601 |
+
init_cache: bool = False,
|
| 602 |
+
output_attentions: bool = False,
|
| 603 |
+
output_hidden_states: bool = False,
|
| 604 |
+
return_dict: bool = True,
|
| 605 |
+
):
|
| 606 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 607 |
+
# do post-embedding layernorm
|
| 608 |
+
hidden_states = self.word_embeddings_layernorm(inputs_embeds)
|
| 609 |
+
|
| 610 |
+
# build alibi depending on `attention_mask`
|
| 611 |
+
alibi = build_alibi_tensor(attention_mask, self.config.n_head, dtype=hidden_states.dtype)
|
| 612 |
+
|
| 613 |
+
outputs = self.h(
|
| 614 |
+
hidden_states,
|
| 615 |
+
alibi=alibi,
|
| 616 |
+
attention_mask=attention_mask,
|
| 617 |
+
deterministic=deterministic,
|
| 618 |
+
init_cache=init_cache,
|
| 619 |
+
output_hidden_states=output_hidden_states,
|
| 620 |
+
output_attentions=output_attentions,
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
hidden_states = outputs[0]
|
| 624 |
+
hidden_states = self.ln_f(hidden_states)
|
| 625 |
+
|
| 626 |
+
if output_hidden_states:
|
| 627 |
+
all_hidden_states = outputs[1] + (hidden_states,)
|
| 628 |
+
outputs = (hidden_states, all_hidden_states) + outputs[2:]
|
| 629 |
+
else:
|
| 630 |
+
outputs = (hidden_states,) + outputs[1:]
|
| 631 |
+
|
| 632 |
+
if not return_dict:
|
| 633 |
+
return tuple(v for v in [outputs[0], outputs[-1]] if v is not None)
|
| 634 |
+
|
| 635 |
+
return FlaxBaseModelOutputWithPastAndCrossAttentions(
|
| 636 |
+
last_hidden_state=hidden_states,
|
| 637 |
+
hidden_states=outputs[1],
|
| 638 |
+
attentions=outputs[-1],
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
@add_start_docstrings(
|
| 643 |
+
"The bare Bloom Model transformer outputting raw hidden-states without any specific head on top.",
|
| 644 |
+
BLOOM_START_DOCSTRING,
|
| 645 |
+
)
|
| 646 |
+
# Copied from transformers.models.gpt_neo.modeling_flax_gpt_neo.FlaxGPTNeoModel with GPTNeo->Bloom
|
| 647 |
+
class FlaxBloomModel(FlaxBloomPreTrainedModel):
|
| 648 |
+
module_class = FlaxBloomModule
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
append_call_sample_docstring(FlaxBloomModel, _CHECKPOINT_FOR_DOC, FlaxBaseModelOutput, _CONFIG_FOR_DOC)
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
class FlaxBloomForCausalLMModule(nn.Module):
|
| 655 |
+
config: BloomConfig
|
| 656 |
+
dtype: jnp.dtype = jnp.float32
|
| 657 |
+
|
| 658 |
+
def setup(self):
|
| 659 |
+
self.transformer = FlaxBloomModule(self.config, dtype=self.dtype)
|
| 660 |
+
self.lm_head = nn.Dense(
|
| 661 |
+
self.config.vocab_size,
|
| 662 |
+
use_bias=False,
|
| 663 |
+
dtype=self.dtype,
|
| 664 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 665 |
+
)
|
| 666 |
+
|
| 667 |
+
def __call__(
|
| 668 |
+
self,
|
| 669 |
+
input_ids,
|
| 670 |
+
attention_mask,
|
| 671 |
+
deterministic: bool = True,
|
| 672 |
+
init_cache: bool = False,
|
| 673 |
+
output_attentions: bool = False,
|
| 674 |
+
output_hidden_states: bool = False,
|
| 675 |
+
return_dict: bool = True,
|
| 676 |
+
):
|
| 677 |
+
outputs = self.transformer(
|
| 678 |
+
input_ids,
|
| 679 |
+
attention_mask=attention_mask,
|
| 680 |
+
deterministic=deterministic,
|
| 681 |
+
init_cache=init_cache,
|
| 682 |
+
output_attentions=output_attentions,
|
| 683 |
+
output_hidden_states=output_hidden_states,
|
| 684 |
+
return_dict=return_dict,
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
hidden_states = outputs[0]
|
| 688 |
+
|
| 689 |
+
if self.config.tie_word_embeddings:
|
| 690 |
+
shared_kernel = self.transformer.variables["params"]["word_embeddings"]["embedding"].T
|
| 691 |
+
lm_logits = self.lm_head.apply({"params": {"kernel": shared_kernel}}, hidden_states)
|
| 692 |
+
else:
|
| 693 |
+
lm_logits = self.lm_head(hidden_states)
|
| 694 |
+
|
| 695 |
+
if not return_dict:
|
| 696 |
+
return (lm_logits,) + outputs[1:]
|
| 697 |
+
|
| 698 |
+
return FlaxCausalLMOutput(logits=lm_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
@add_start_docstrings(
|
| 702 |
+
"""
|
| 703 |
+
The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
| 704 |
+
embeddings).
|
| 705 |
+
""",
|
| 706 |
+
BLOOM_START_DOCSTRING,
|
| 707 |
+
)
|
| 708 |
+
class FlaxBloomForCausalLM(FlaxBloomPreTrainedModel):
|
| 709 |
+
module_class = FlaxBloomForCausalLMModule
|
| 710 |
+
|
| 711 |
+
def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
|
| 712 |
+
# initializing the cache
|
| 713 |
+
batch_size, seq_length = input_ids.shape
|
| 714 |
+
|
| 715 |
+
past_key_values = self.init_cache(batch_size, max_length)
|
| 716 |
+
# Note that usually one would have to put 0's in the attention_mask for
|
| 717 |
+
# x > input_ids.shape[-1] and x < cache_length. But since Bloom uses a causal mask,
|
| 718 |
+
# those positions are masked anyway. Thus, we can create a single static attention_mask here,
|
| 719 |
+
# which is more efficient for compilation
|
| 720 |
+
extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
|
| 721 |
+
if attention_mask is not None:
|
| 722 |
+
extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
|
| 723 |
+
|
| 724 |
+
return {
|
| 725 |
+
"past_key_values": past_key_values,
|
| 726 |
+
"attention_mask": extended_attention_mask,
|
| 727 |
+
}
|
| 728 |
+
|
| 729 |
+
def update_inputs_for_generation(self, model_outputs, model_kwargs):
|
| 730 |
+
model_kwargs["past_key_values"] = model_outputs.past_key_values
|
| 731 |
+
return model_kwargs
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
append_call_sample_docstring(FlaxB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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization classes for Bloom."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import pickle
|
| 19 |
+
from typing import TYPE_CHECKING, List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
from ...tokenization_utils_base import BatchEncoding
|
| 22 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
from transformers.pipelines.conversational import Conversation
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
VOCAB_FILES_NAMES = {"tokenizer_file": "tokenizer.json"}
|
| 33 |
+
|
| 34 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
| 35 |
+
"tokenizer_file": {
|
| 36 |
+
"bigscience/tokenizer": "https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json",
|
| 37 |
+
"bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json",
|
| 38 |
+
"bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json",
|
| 39 |
+
"bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json",
|
| 40 |
+
"bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json",
|
| 41 |
+
"bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json",
|
| 42 |
+
"bigscience/bloom": "https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json",
|
| 43 |
+
},
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class BloomTokenizerFast(PreTrainedTokenizerFast):
|
| 48 |
+
"""
|
| 49 |
+
Construct a "fast" Bloom tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
|
| 50 |
+
Byte-Pair-Encoding.
|
| 51 |
+
|
| 52 |
+
This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
|
| 53 |
+
be encoded differently whether it is at the beginning of the sentence (without space) or not:
|
| 54 |
+
|
| 55 |
+
```python
|
| 56 |
+
>>> from transformers import BloomTokenizerFast
|
| 57 |
+
|
| 58 |
+
>>> tokenizer = BloomTokenizerFast.from_pretrained("bigscience/bloom")
|
| 59 |
+
>>> tokenizer("Hello world")["input_ids"]
|
| 60 |
+
[59414, 8876]
|
| 61 |
+
|
| 62 |
+
>>> tokenizer(" Hello world")["input_ids"]
|
| 63 |
+
[86153, 8876]
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
|
| 67 |
+
the model was not pretrained this way, it might yield a decrease in performance.
|
| 68 |
+
|
| 69 |
+
<Tip>
|
| 70 |
+
|
| 71 |
+
When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
|
| 72 |
+
|
| 73 |
+
</Tip>
|
| 74 |
+
|
| 75 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
| 76 |
+
refer to this superclass for more information regarding those methods.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
vocab_file (`str`):
|
| 80 |
+
Path to the vocabulary file.
|
| 81 |
+
merges_file (`str`):
|
| 82 |
+
Path to the merges file.
|
| 83 |
+
errors (`str`, *optional*, defaults to `"replace"`):
|
| 84 |
+
Paradigm to follow when decoding bytes to UTF-8. See
|
| 85 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
| 86 |
+
unk_token (`str`, *optional*, defaults to `<|endoftext|>`):
|
| 87 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 88 |
+
token instead.
|
| 89 |
+
bos_token (`str`, *optional*, defaults to `<|endoftext|>`):
|
| 90 |
+
The beginning of sequence token.
|
| 91 |
+
eos_token (`str`, *optional*, defaults to `<|endoftext|>`):
|
| 92 |
+
The end of sequence token.
|
| 93 |
+
add_prefix_space (`bool`, *optional*, defaults to `False`):
|
| 94 |
+
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
|
| 95 |
+
other word. (Bloom tokenizer detect beginning of words by the preceding space).
|
| 96 |
+
trim_offsets (`bool`, *optional*, defaults to `True`):
|
| 97 |
+
Whether or not the post-processing step should trim offsets to avoid including whitespaces.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 101 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
| 102 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 103 |
+
slow_tokenizer_class = None
|
| 104 |
+
# No `max_model_input_sizes` as BLOOM uses ALiBi positional embeddings
|
| 105 |
+
|
| 106 |
+
def __init__(
|
| 107 |
+
self,
|
| 108 |
+
vocab_file=None,
|
| 109 |
+
merges_file=None,
|
| 110 |
+
tokenizer_file=None,
|
| 111 |
+
unk_token="<unk>",
|
| 112 |
+
bos_token="<s>",
|
| 113 |
+
eos_token="</s>",
|
| 114 |
+
pad_token="<pad>",
|
| 115 |
+
add_prefix_space=False,
|
| 116 |
+
clean_up_tokenization_spaces=False,
|
| 117 |
+
**kwargs,
|
| 118 |
+
):
|
| 119 |
+
super().__init__(
|
| 120 |
+
vocab_file,
|
| 121 |
+
merges_file,
|
| 122 |
+
tokenizer_file=tokenizer_file,
|
| 123 |
+
unk_token=unk_token,
|
| 124 |
+
bos_token=bos_token,
|
| 125 |
+
eos_token=eos_token,
|
| 126 |
+
pad_token=pad_token,
|
| 127 |
+
add_prefix_space=add_prefix_space,
|
| 128 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 129 |
+
**kwargs,
|
| 130 |
+
)
|
| 131 |
+
# TODO @ArthurZucker this can only work one way for now, to update later-on. Tests should also properly
|
| 132 |
+
# check this as they were green before.
|
| 133 |
+
pre_tok_state = pickle.dumps(self.backend_tokenizer.pre_tokenizer)
|
| 134 |
+
decoder_state = pickle.dumps(self.backend_tokenizer.decoder)
|
| 135 |
+
|
| 136 |
+
if add_prefix_space:
|
| 137 |
+
pre_tok_state = pre_tok_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true')
|
| 138 |
+
decoder_state = decoder_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true')
|
| 139 |
+
self.backend_tokenizer.pre_tokenizer = pickle.loads(pre_tok_state)
|
| 140 |
+
self.backend_tokenizer.decoder = pickle.loads(decoder_state)
|
| 141 |
+
|
| 142 |
+
self.add_prefix_space = add_prefix_space
|
| 143 |
+
|
| 144 |
+
def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
|
| 145 |
+
is_split_into_words = kwargs.get("is_split_into_words", False)
|
| 146 |
+
if not (self.add_prefix_space or not is_split_into_words):
|
| 147 |
+
raise Exception(
|
| 148 |
+
f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"
|
| 149 |
+
" pretokenized inputs."
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
return super()._batch_encode_plus(*args, **kwargs)
|
| 153 |
+
|
| 154 |
+
def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
|
| 155 |
+
is_split_into_words = kwargs.get("is_split_into_words", False)
|
| 156 |
+
|
| 157 |
+
if not (self.add_prefix_space or not is_split_into_words):
|
| 158 |
+
raise Exception(
|
| 159 |
+
f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with"
|
| 160 |
+
" pretokenized inputs."
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
return super()._encode_plus(*args, **kwargs)
|
| 164 |
+
|
| 165 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 166 |
+
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
|
| 167 |
+
return tuple(files)
|
| 168 |
+
|
| 169 |
+
def _build_conversation_input_ids(self, conversation: "Conversation") -> List[int]:
|
| 170 |
+
"""This corresponds to DialoGPT variants of models."""
|
| 171 |
+
input_ids = []
|
| 172 |
+
for is_user, text in conversation.iter_texts():
|
| 173 |
+
input_ids.extend(self.encode(text, add_special_tokens=False) + [self.eos_token_id])
|
| 174 |
+
|
| 175 |
+
if len(input_ids) > self.model_max_length:
|
| 176 |
+
input_ids = input_ids[-self.model_max_length :]
|
| 177 |
+
return input_ids
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-310.pyc
ADDED
|
Binary file (9.83 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__init__.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_import_structure = {
|
| 21 |
+
"configuration_deformable_detr": ["DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "DeformableDetrConfig"],
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
if not is_vision_available():
|
| 26 |
+
raise OptionalDependencyNotAvailable()
|
| 27 |
+
except OptionalDependencyNotAvailable:
|
| 28 |
+
pass
|
| 29 |
+
else:
|
| 30 |
+
_import_structure["feature_extraction_deformable_detr"] = ["DeformableDetrFeatureExtractor"]
|
| 31 |
+
_import_structure["image_processing_deformable_detr"] = ["DeformableDetrImageProcessor"]
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
if not is_torch_available():
|
| 35 |
+
raise OptionalDependencyNotAvailable()
|
| 36 |
+
except OptionalDependencyNotAvailable:
|
| 37 |
+
pass
|
| 38 |
+
else:
|
| 39 |
+
_import_structure["modeling_deformable_detr"] = [
|
| 40 |
+
"DEFORMABLE_DETR_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 41 |
+
"DeformableDetrForObjectDetection",
|
| 42 |
+
"DeformableDetrModel",
|
| 43 |
+
"DeformableDetrPreTrainedModel",
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if TYPE_CHECKING:
|
| 48 |
+
from .configuration_deformable_detr import DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, DeformableDetrConfig
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
if not is_vision_available():
|
| 52 |
+
raise OptionalDependencyNotAvailable()
|
| 53 |
+
except OptionalDependencyNotAvailable:
|
| 54 |
+
pass
|
| 55 |
+
else:
|
| 56 |
+
from .feature_extraction_deformable_detr import DeformableDetrFeatureExtractor
|
| 57 |
+
from .image_processing_deformable_detr import DeformableDetrImageProcessor
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
if not is_torch_available():
|
| 61 |
+
raise OptionalDependencyNotAvailable()
|
| 62 |
+
except OptionalDependencyNotAvailable:
|
| 63 |
+
pass
|
| 64 |
+
else:
|
| 65 |
+
from .modeling_deformable_detr import (
|
| 66 |
+
DEFORMABLE_DETR_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 67 |
+
DeformableDetrForObjectDetection,
|
| 68 |
+
DeformableDetrModel,
|
| 69 |
+
DeformableDetrPreTrainedModel,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
else:
|
| 73 |
+
import sys
|
| 74 |
+
|
| 75 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.33 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/configuration_deformable_detr.cpython-310.pyc
ADDED
|
Binary file (11.6 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/convert_deformable_detr_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (6.83 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/feature_extraction_deformable_detr.cpython-310.pyc
ADDED
|
Binary file (1.08 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr.cpython-310.pyc
ADDED
|
Binary file (48.9 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/load_custom.cpython-310.pyc
ADDED
|
Binary file (1.18 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/__pycache__/modeling_deformable_detr.cpython-310.pyc
ADDED
|
Binary file (89 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/configuration_deformable_detr.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 SenseTime 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 |
+
""" Deformable DETR model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
from ..auto import CONFIG_MAPPING
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 25 |
+
"SenseTime/deformable-detr": "https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json",
|
| 26 |
+
# See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class DeformableDetrConfig(PretrainedConfig):
|
| 31 |
+
r"""
|
| 32 |
+
This is the configuration class to store the configuration of a [`DeformableDetrModel`]. It is used to instantiate
|
| 33 |
+
a Deformable DETR 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 Deformable DETR
|
| 35 |
+
[SenseTime/deformable-detr](https://huggingface.co/SenseTime/deformable-detr) 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 |
+
Args:
|
| 41 |
+
use_timm_backbone (`bool`, *optional*, defaults to `True`):
|
| 42 |
+
Whether or not to use the `timm` library for the backbone. If set to `False`, will use the [`AutoBackbone`]
|
| 43 |
+
API.
|
| 44 |
+
backbone_config (`PretrainedConfig` or `dict`, *optional*):
|
| 45 |
+
The configuration of the backbone model. Only used in case `use_timm_backbone` is set to `False` in which
|
| 46 |
+
case it will default to `ResNetConfig()`.
|
| 47 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 48 |
+
The number of input channels.
|
| 49 |
+
num_queries (`int`, *optional*, defaults to 300):
|
| 50 |
+
Number of object queries, i.e. detection slots. This is the maximal number of objects
|
| 51 |
+
[`DeformableDetrModel`] can detect in a single image. In case `two_stage` is set to `True`, we use
|
| 52 |
+
`two_stage_num_proposals` instead.
|
| 53 |
+
d_model (`int`, *optional*, defaults to 256):
|
| 54 |
+
Dimension of the layers.
|
| 55 |
+
encoder_layers (`int`, *optional*, defaults to 6):
|
| 56 |
+
Number of encoder layers.
|
| 57 |
+
decoder_layers (`int`, *optional*, defaults to 6):
|
| 58 |
+
Number of decoder layers.
|
| 59 |
+
encoder_attention_heads (`int`, *optional*, defaults to 8):
|
| 60 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 61 |
+
decoder_attention_heads (`int`, *optional*, defaults to 8):
|
| 62 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 63 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 1024):
|
| 64 |
+
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
|
| 65 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 1024):
|
| 66 |
+
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
|
| 67 |
+
activation_function (`str` or `function`, *optional*, defaults to `"relu"`):
|
| 68 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 69 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 70 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 71 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 72 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 73 |
+
The dropout ratio for the attention probabilities.
|
| 74 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 75 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 76 |
+
init_std (`float`, *optional*, defaults to 0.02):
|
| 77 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 78 |
+
init_xavier_std (`float`, *optional*, defaults to 1):
|
| 79 |
+
The scaling factor used for the Xavier initialization gain in the HM Attention map module.
|
| 80 |
+
encoder_layerdrop (`float`, *optional*, defaults to 0.0):
|
| 81 |
+
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
|
| 82 |
+
for more details.
|
| 83 |
+
auxiliary_loss (`bool`, *optional*, defaults to `False`):
|
| 84 |
+
Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
|
| 85 |
+
position_embedding_type (`str`, *optional*, defaults to `"sine"`):
|
| 86 |
+
Type of position embeddings to be used on top of the image features. One of `"sine"` or `"learned"`.
|
| 87 |
+
backbone (`str`, *optional*, defaults to `"resnet50"`):
|
| 88 |
+
Name of convolutional backbone to use in case `use_timm_backbone` = `True`. Supports any convolutional
|
| 89 |
+
backbone from the timm package. For a list of all available models, see [this
|
| 90 |
+
page](https://rwightman.github.io/pytorch-image-models/#load-a-pretrained-model).
|
| 91 |
+
use_pretrained_backbone (`bool`, *optional*, defaults to `True`):
|
| 92 |
+
Whether to use pretrained weights for the backbone. Only supported when `use_timm_backbone` = `True`.
|
| 93 |
+
dilation (`bool`, *optional*, defaults to `False`):
|
| 94 |
+
Whether to replace stride with dilation in the last convolutional block (DC5). Only supported when
|
| 95 |
+
`use_timm_backbone` = `True`.
|
| 96 |
+
class_cost (`float`, *optional*, defaults to 1):
|
| 97 |
+
Relative weight of the classification error in the Hungarian matching cost.
|
| 98 |
+
bbox_cost (`float`, *optional*, defaults to 5):
|
| 99 |
+
Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost.
|
| 100 |
+
giou_cost (`float`, *optional*, defaults to 2):
|
| 101 |
+
Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost.
|
| 102 |
+
mask_loss_coefficient (`float`, *optional*, defaults to 1):
|
| 103 |
+
Relative weight of the Focal loss in the panoptic segmentation loss.
|
| 104 |
+
dice_loss_coefficient (`float`, *optional*, defaults to 1):
|
| 105 |
+
Relative weight of the DICE/F-1 loss in the panoptic segmentation loss.
|
| 106 |
+
bbox_loss_coefficient (`float`, *optional*, defaults to 5):
|
| 107 |
+
Relative weight of the L1 bounding box loss in the object detection loss.
|
| 108 |
+
giou_loss_coefficient (`float`, *optional*, defaults to 2):
|
| 109 |
+
Relative weight of the generalized IoU loss in the object detection loss.
|
| 110 |
+
eos_coefficient (`float`, *optional*, defaults to 0.1):
|
| 111 |
+
Relative classification weight of the 'no-object' class in the object detection loss.
|
| 112 |
+
num_feature_levels (`int`, *optional*, defaults to 4):
|
| 113 |
+
The number of input feature levels.
|
| 114 |
+
encoder_n_points (`int`, *optional*, defaults to 4):
|
| 115 |
+
The number of sampled keys in each feature level for each attention head in the encoder.
|
| 116 |
+
decoder_n_points (`int`, *optional*, defaults to 4):
|
| 117 |
+
The number of sampled keys in each feature level for each attention head in the decoder.
|
| 118 |
+
two_stage (`bool`, *optional*, defaults to `False`):
|
| 119 |
+
Whether to apply a two-stage deformable DETR, where the region proposals are also generated by a variant of
|
| 120 |
+
Deformable DETR, which are further fed into the decoder for iterative bounding box refinement.
|
| 121 |
+
two_stage_num_proposals (`int`, *optional*, defaults to 300):
|
| 122 |
+
The number of region proposals to be generated, in case `two_stage` is set to `True`.
|
| 123 |
+
with_box_refine (`bool`, *optional*, defaults to `False`):
|
| 124 |
+
Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
|
| 125 |
+
based on the predictions from the previous layer.
|
| 126 |
+
focal_alpha (`float`, *optional*, defaults to 0.25):
|
| 127 |
+
Alpha parameter in the focal loss.
|
| 128 |
+
disable_custom_kernels (`bool`, *optional*, defaults to `False`):
|
| 129 |
+
Disable the use of custom CUDA and CPU kernels. This option is necessary for the ONNX export, as custom
|
| 130 |
+
kernels are not supported by PyTorch ONNX export.
|
| 131 |
+
|
| 132 |
+
Examples:
|
| 133 |
+
|
| 134 |
+
```python
|
| 135 |
+
>>> from transformers import DeformableDetrConfig, DeformableDetrModel
|
| 136 |
+
|
| 137 |
+
>>> # Initializing a Deformable DETR SenseTime/deformable-detr style configuration
|
| 138 |
+
>>> configuration = DeformableDetrConfig()
|
| 139 |
+
|
| 140 |
+
>>> # Initializing a model (with random weights) from the SenseTime/deformable-detr style configuration
|
| 141 |
+
>>> model = DeformableDetrModel(configuration)
|
| 142 |
+
|
| 143 |
+
>>> # Accessing the model configuration
|
| 144 |
+
>>> configuration = model.config
|
| 145 |
+
```"""
|
| 146 |
+
model_type = "deformable_detr"
|
| 147 |
+
attribute_map = {
|
| 148 |
+
"hidden_size": "d_model",
|
| 149 |
+
"num_attention_heads": "encoder_attention_heads",
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
def __init__(
|
| 153 |
+
self,
|
| 154 |
+
use_timm_backbone=True,
|
| 155 |
+
backbone_config=None,
|
| 156 |
+
num_channels=3,
|
| 157 |
+
num_queries=300,
|
| 158 |
+
max_position_embeddings=1024,
|
| 159 |
+
encoder_layers=6,
|
| 160 |
+
encoder_ffn_dim=1024,
|
| 161 |
+
encoder_attention_heads=8,
|
| 162 |
+
decoder_layers=6,
|
| 163 |
+
decoder_ffn_dim=1024,
|
| 164 |
+
decoder_attention_heads=8,
|
| 165 |
+
encoder_layerdrop=0.0,
|
| 166 |
+
is_encoder_decoder=True,
|
| 167 |
+
activation_function="relu",
|
| 168 |
+
d_model=256,
|
| 169 |
+
dropout=0.1,
|
| 170 |
+
attention_dropout=0.0,
|
| 171 |
+
activation_dropout=0.0,
|
| 172 |
+
init_std=0.02,
|
| 173 |
+
init_xavier_std=1.0,
|
| 174 |
+
return_intermediate=True,
|
| 175 |
+
auxiliary_loss=False,
|
| 176 |
+
position_embedding_type="sine",
|
| 177 |
+
backbone="resnet50",
|
| 178 |
+
use_pretrained_backbone=True,
|
| 179 |
+
dilation=False,
|
| 180 |
+
num_feature_levels=4,
|
| 181 |
+
encoder_n_points=4,
|
| 182 |
+
decoder_n_points=4,
|
| 183 |
+
two_stage=False,
|
| 184 |
+
two_stage_num_proposals=300,
|
| 185 |
+
with_box_refine=False,
|
| 186 |
+
class_cost=1,
|
| 187 |
+
bbox_cost=5,
|
| 188 |
+
giou_cost=2,
|
| 189 |
+
mask_loss_coefficient=1,
|
| 190 |
+
dice_loss_coefficient=1,
|
| 191 |
+
bbox_loss_coefficient=5,
|
| 192 |
+
giou_loss_coefficient=2,
|
| 193 |
+
eos_coefficient=0.1,
|
| 194 |
+
focal_alpha=0.25,
|
| 195 |
+
disable_custom_kernels=False,
|
| 196 |
+
**kwargs,
|
| 197 |
+
):
|
| 198 |
+
if backbone_config is not None and use_timm_backbone:
|
| 199 |
+
raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`.")
|
| 200 |
+
|
| 201 |
+
if not use_timm_backbone:
|
| 202 |
+
if backbone_config is None:
|
| 203 |
+
logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.")
|
| 204 |
+
backbone_config = CONFIG_MAPPING["resnet"](out_features=["stage4"])
|
| 205 |
+
elif isinstance(backbone_config, dict):
|
| 206 |
+
backbone_model_type = backbone_config.get("model_type")
|
| 207 |
+
config_class = CONFIG_MAPPING[backbone_model_type]
|
| 208 |
+
backbone_config = config_class.from_dict(backbone_config)
|
| 209 |
+
self.use_timm_backbone = use_timm_backbone
|
| 210 |
+
self.backbone_config = backbone_config
|
| 211 |
+
self.num_channels = num_channels
|
| 212 |
+
self.num_queries = num_queries
|
| 213 |
+
self.max_position_embeddings = max_position_embeddings
|
| 214 |
+
self.d_model = d_model
|
| 215 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 216 |
+
self.encoder_layers = encoder_layers
|
| 217 |
+
self.encoder_attention_heads = encoder_attention_heads
|
| 218 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 219 |
+
self.decoder_layers = decoder_layers
|
| 220 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 221 |
+
self.dropout = dropout
|
| 222 |
+
self.attention_dropout = attention_dropout
|
| 223 |
+
self.activation_dropout = activation_dropout
|
| 224 |
+
self.activation_function = activation_function
|
| 225 |
+
self.init_std = init_std
|
| 226 |
+
self.init_xavier_std = init_xavier_std
|
| 227 |
+
self.encoder_layerdrop = encoder_layerdrop
|
| 228 |
+
self.auxiliary_loss = auxiliary_loss
|
| 229 |
+
self.position_embedding_type = position_embedding_type
|
| 230 |
+
self.backbone = backbone
|
| 231 |
+
self.use_pretrained_backbone = use_pretrained_backbone
|
| 232 |
+
self.dilation = dilation
|
| 233 |
+
# deformable attributes
|
| 234 |
+
self.num_feature_levels = num_feature_levels
|
| 235 |
+
self.encoder_n_points = encoder_n_points
|
| 236 |
+
self.decoder_n_points = decoder_n_points
|
| 237 |
+
self.two_stage = two_stage
|
| 238 |
+
self.two_stage_num_proposals = two_stage_num_proposals
|
| 239 |
+
self.with_box_refine = with_box_refine
|
| 240 |
+
if two_stage is True and with_box_refine is False:
|
| 241 |
+
raise ValueError("If two_stage is True, with_box_refine must be True.")
|
| 242 |
+
# Hungarian matcher
|
| 243 |
+
self.class_cost = class_cost
|
| 244 |
+
self.bbox_cost = bbox_cost
|
| 245 |
+
self.giou_cost = giou_cost
|
| 246 |
+
# Loss coefficients
|
| 247 |
+
self.mask_loss_coefficient = mask_loss_coefficient
|
| 248 |
+
self.dice_loss_coefficient = dice_loss_coefficient
|
| 249 |
+
self.bbox_loss_coefficient = bbox_loss_coefficient
|
| 250 |
+
self.giou_loss_coefficient = giou_loss_coefficient
|
| 251 |
+
self.eos_coefficient = eos_coefficient
|
| 252 |
+
self.focal_alpha = focal_alpha
|
| 253 |
+
self.disable_custom_kernels = disable_custom_kernels
|
| 254 |
+
super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
|
| 255 |
+
|
| 256 |
+
@property
|
| 257 |
+
def num_attention_heads(self) -> int:
|
| 258 |
+
return self.encoder_attention_heads
|
| 259 |
+
|
| 260 |
+
@property
|
| 261 |
+
def hidden_size(self) -> int:
|
| 262 |
+
return self.d_model
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/convert_deformable_detr_to_pytorch.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert Deformable DETR checkpoints."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import json
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import requests
|
| 23 |
+
import torch
|
| 24 |
+
from huggingface_hub import cached_download, hf_hub_url
|
| 25 |
+
from PIL import Image
|
| 26 |
+
|
| 27 |
+
from transformers import DeformableDetrConfig, DeformableDetrForObjectDetection, DeformableDetrImageProcessor
|
| 28 |
+
from transformers.utils import logging
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logging.set_verbosity_info()
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def rename_key(orig_key):
|
| 36 |
+
if "backbone.0.body" in orig_key:
|
| 37 |
+
orig_key = orig_key.replace("backbone.0.body", "backbone.conv_encoder.model")
|
| 38 |
+
if "transformer" in orig_key:
|
| 39 |
+
orig_key = orig_key.replace("transformer.", "")
|
| 40 |
+
if "norm1" in orig_key:
|
| 41 |
+
if "encoder" in orig_key:
|
| 42 |
+
orig_key = orig_key.replace("norm1", "self_attn_layer_norm")
|
| 43 |
+
else:
|
| 44 |
+
orig_key = orig_key.replace("norm1", "encoder_attn_layer_norm")
|
| 45 |
+
if "norm2" in orig_key:
|
| 46 |
+
if "encoder" in orig_key:
|
| 47 |
+
orig_key = orig_key.replace("norm2", "final_layer_norm")
|
| 48 |
+
else:
|
| 49 |
+
orig_key = orig_key.replace("norm2", "self_attn_layer_norm")
|
| 50 |
+
if "norm3" in orig_key:
|
| 51 |
+
orig_key = orig_key.replace("norm3", "final_layer_norm")
|
| 52 |
+
if "linear1" in orig_key:
|
| 53 |
+
orig_key = orig_key.replace("linear1", "fc1")
|
| 54 |
+
if "linear2" in orig_key:
|
| 55 |
+
orig_key = orig_key.replace("linear2", "fc2")
|
| 56 |
+
if "query_embed" in orig_key:
|
| 57 |
+
orig_key = orig_key.replace("query_embed", "query_position_embeddings")
|
| 58 |
+
if "cross_attn" in orig_key:
|
| 59 |
+
orig_key = orig_key.replace("cross_attn", "encoder_attn")
|
| 60 |
+
|
| 61 |
+
return orig_key
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def read_in_q_k_v(state_dict):
|
| 65 |
+
# transformer decoder self-attention layers
|
| 66 |
+
for i in range(6):
|
| 67 |
+
# read in weights + bias of input projection layer of self-attention
|
| 68 |
+
in_proj_weight = state_dict.pop(f"decoder.layers.{i}.self_attn.in_proj_weight")
|
| 69 |
+
in_proj_bias = state_dict.pop(f"decoder.layers.{i}.self_attn.in_proj_bias")
|
| 70 |
+
# next, add query, keys and values (in that order) to the state dict
|
| 71 |
+
state_dict[f"decoder.layers.{i}.self_attn.q_proj.weight"] = in_proj_weight[:256, :]
|
| 72 |
+
state_dict[f"decoder.layers.{i}.self_attn.q_proj.bias"] = in_proj_bias[:256]
|
| 73 |
+
state_dict[f"decoder.layers.{i}.self_attn.k_proj.weight"] = in_proj_weight[256:512, :]
|
| 74 |
+
state_dict[f"decoder.layers.{i}.self_attn.k_proj.bias"] = in_proj_bias[256:512]
|
| 75 |
+
state_dict[f"decoder.layers.{i}.self_attn.v_proj.weight"] = in_proj_weight[-256:, :]
|
| 76 |
+
state_dict[f"decoder.layers.{i}.self_attn.v_proj.bias"] = in_proj_bias[-256:]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# We will verify our results on an image of cute cats
|
| 80 |
+
def prepare_img():
|
| 81 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 82 |
+
im = Image.open(requests.get(url, stream=True).raw)
|
| 83 |
+
|
| 84 |
+
return im
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@torch.no_grad()
|
| 88 |
+
def convert_deformable_detr_checkpoint(
|
| 89 |
+
checkpoint_path,
|
| 90 |
+
single_scale,
|
| 91 |
+
dilation,
|
| 92 |
+
with_box_refine,
|
| 93 |
+
two_stage,
|
| 94 |
+
pytorch_dump_folder_path,
|
| 95 |
+
push_to_hub,
|
| 96 |
+
):
|
| 97 |
+
"""
|
| 98 |
+
Copy/paste/tweak model's weights to our Deformable DETR structure.
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
# load default config
|
| 102 |
+
config = DeformableDetrConfig()
|
| 103 |
+
# set config attributes
|
| 104 |
+
if single_scale:
|
| 105 |
+
config.num_feature_levels = 1
|
| 106 |
+
config.dilation = dilation
|
| 107 |
+
config.with_box_refine = with_box_refine
|
| 108 |
+
config.two_stage = two_stage
|
| 109 |
+
# set labels
|
| 110 |
+
config.num_labels = 91
|
| 111 |
+
repo_id = "huggingface/label-files"
|
| 112 |
+
filename = "coco-detection-id2label.json"
|
| 113 |
+
id2label = json.load(open(cached_download(hf_hub_url(repo_id, filename, repo_type="dataset")), "r"))
|
| 114 |
+
id2label = {int(k): v for k, v in id2label.items()}
|
| 115 |
+
config.id2label = id2label
|
| 116 |
+
config.label2id = {v: k for k, v in id2label.items()}
|
| 117 |
+
|
| 118 |
+
# load image processor
|
| 119 |
+
image_processor = DeformableDetrImageProcessor(format="coco_detection")
|
| 120 |
+
|
| 121 |
+
# prepare image
|
| 122 |
+
img = prepare_img()
|
| 123 |
+
encoding = image_processor(images=img, return_tensors="pt")
|
| 124 |
+
pixel_values = encoding["pixel_values"]
|
| 125 |
+
|
| 126 |
+
logger.info("Converting model...")
|
| 127 |
+
|
| 128 |
+
# load original state dict
|
| 129 |
+
state_dict = torch.load(checkpoint_path, map_location="cpu")["model"]
|
| 130 |
+
# rename keys
|
| 131 |
+
for key in state_dict.copy().keys():
|
| 132 |
+
val = state_dict.pop(key)
|
| 133 |
+
state_dict[rename_key(key)] = val
|
| 134 |
+
# query, key and value matrices need special treatment
|
| 135 |
+
read_in_q_k_v(state_dict)
|
| 136 |
+
# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
|
| 137 |
+
prefix = "model."
|
| 138 |
+
for key in state_dict.copy().keys():
|
| 139 |
+
if not key.startswith("class_embed") and not key.startswith("bbox_embed"):
|
| 140 |
+
val = state_dict.pop(key)
|
| 141 |
+
state_dict[prefix + key] = val
|
| 142 |
+
# finally, create HuggingFace model and load state dict
|
| 143 |
+
model = DeformableDetrForObjectDetection(config)
|
| 144 |
+
model.load_state_dict(state_dict)
|
| 145 |
+
model.eval()
|
| 146 |
+
|
| 147 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 148 |
+
model.to(device)
|
| 149 |
+
# verify our conversion
|
| 150 |
+
outputs = model(pixel_values.to(device))
|
| 151 |
+
|
| 152 |
+
expected_logits = torch.tensor(
|
| 153 |
+
[[-9.6645, -4.3449, -5.8705], [-9.7035, -3.8504, -5.0724], [-10.5634, -5.3379, -7.5116]]
|
| 154 |
+
)
|
| 155 |
+
expected_boxes = torch.tensor([[0.8693, 0.2289, 0.2492], [0.3150, 0.5489, 0.5845], [0.5563, 0.7580, 0.8518]])
|
| 156 |
+
|
| 157 |
+
if single_scale:
|
| 158 |
+
expected_logits = torch.tensor(
|
| 159 |
+
[[-9.9051, -4.2541, -6.4852], [-9.6947, -4.0854, -6.8033], [-10.0665, -5.8470, -7.7003]]
|
| 160 |
+
)
|
| 161 |
+
expected_boxes = torch.tensor([[0.7292, 0.4991, 0.5532], [0.7959, 0.2426, 0.4236], [0.7582, 0.3518, 0.4451]])
|
| 162 |
+
|
| 163 |
+
if single_scale and dilation:
|
| 164 |
+
expected_logits = torch.tensor(
|
| 165 |
+
[[-8.9652, -4.1074, -5.6635], [-9.0596, -4.9447, -6.6075], [-10.1178, -4.5275, -6.2671]]
|
| 166 |
+
)
|
| 167 |
+
expected_boxes = torch.tensor([[0.7665, 0.4130, 0.4769], [0.8364, 0.1841, 0.3391], [0.6261, 0.3895, 0.7978]])
|
| 168 |
+
|
| 169 |
+
if with_box_refine:
|
| 170 |
+
expected_logits = torch.tensor(
|
| 171 |
+
[[-8.8895, -5.4187, -6.8153], [-8.4706, -6.1668, -7.6184], [-9.0042, -5.5359, -6.9141]]
|
| 172 |
+
)
|
| 173 |
+
expected_boxes = torch.tensor([[0.7828, 0.2208, 0.4323], [0.0892, 0.5996, 0.1319], [0.5524, 0.6389, 0.8914]])
|
| 174 |
+
|
| 175 |
+
if with_box_refine and two_stage:
|
| 176 |
+
expected_logits = torch.tensor(
|
| 177 |
+
[[-6.7108, -4.3213, -6.3777], [-8.9014, -6.1799, -6.7240], [-6.9315, -4.4735, -6.2298]]
|
| 178 |
+
)
|
| 179 |
+
expected_boxes = torch.tensor([[0.2583, 0.5499, 0.4683], [0.7652, 0.9068, 0.4882], [0.5490, 0.2763, 0.0564]])
|
| 180 |
+
|
| 181 |
+
print("Logits:", outputs.logits[0, :3, :3])
|
| 182 |
+
|
| 183 |
+
assert torch.allclose(outputs.logits[0, :3, :3], expected_logits.to(device), atol=1e-4)
|
| 184 |
+
assert torch.allclose(outputs.pred_boxes[0, :3, :3], expected_boxes.to(device), atol=1e-4)
|
| 185 |
+
|
| 186 |
+
print("Everything ok!")
|
| 187 |
+
|
| 188 |
+
# Save model and image processor
|
| 189 |
+
logger.info(f"Saving PyTorch model and image processor to {pytorch_dump_folder_path}...")
|
| 190 |
+
Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
|
| 191 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 192 |
+
image_processor.save_pretrained(pytorch_dump_folder_path)
|
| 193 |
+
|
| 194 |
+
# Push to hub
|
| 195 |
+
if push_to_hub:
|
| 196 |
+
model_name = "deformable-detr"
|
| 197 |
+
model_name += "-single-scale" if single_scale else ""
|
| 198 |
+
model_name += "-dc5" if dilation else ""
|
| 199 |
+
model_name += "-with-box-refine" if with_box_refine else ""
|
| 200 |
+
model_name += "-two-stage" if two_stage else ""
|
| 201 |
+
print("Pushing model to hub...")
|
| 202 |
+
model.push_to_hub(repo_path_or_name=model_name, organization="nielsr", commit_message="Add model")
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
if __name__ == "__main__":
|
| 206 |
+
parser = argparse.ArgumentParser()
|
| 207 |
+
|
| 208 |
+
parser.add_argument(
|
| 209 |
+
"--checkpoint_path",
|
| 210 |
+
type=str,
|
| 211 |
+
default="/home/niels/checkpoints/deformable_detr/r50_deformable_detr-checkpoint.pth",
|
| 212 |
+
help="Path to Pytorch checkpoint (.pth file) you'd like to convert.",
|
| 213 |
+
)
|
| 214 |
+
parser.add_argument("--single_scale", action="store_true", help="Whether to set config.num_features_levels = 1.")
|
| 215 |
+
parser.add_argument("--dilation", action="store_true", help="Whether to set config.dilation=True.")
|
| 216 |
+
parser.add_argument("--with_box_refine", action="store_true", help="Whether to set config.with_box_refine=True.")
|
| 217 |
+
parser.add_argument("--two_stage", action="store_true", help="Whether to set config.two_stage=True.")
|
| 218 |
+
parser.add_argument(
|
| 219 |
+
"--pytorch_dump_folder_path",
|
| 220 |
+
default=None,
|
| 221 |
+
type=str,
|
| 222 |
+
required=True,
|
| 223 |
+
help="Path to the folder to output PyTorch model.",
|
| 224 |
+
)
|
| 225 |
+
parser.add_argument(
|
| 226 |
+
"--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
|
| 227 |
+
)
|
| 228 |
+
args = parser.parse_args()
|
| 229 |
+
convert_deformable_detr_checkpoint(
|
| 230 |
+
args.checkpoint_path,
|
| 231 |
+
args.single_scale,
|
| 232 |
+
args.dilation,
|
| 233 |
+
args.with_box_refine,
|
| 234 |
+
args.two_stage,
|
| 235 |
+
args.pytorch_dump_folder_path,
|
| 236 |
+
args.push_to_hub,
|
| 237 |
+
)
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/feature_extraction_deformable_detr.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Feature extractor class for Deformable DETR."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
from .image_processing_deformable_detr import DeformableDetrImageProcessor
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class DeformableDetrFeatureExtractor(DeformableDetrImageProcessor):
|
| 27 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 28 |
+
warnings.warn(
|
| 29 |
+
"The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
|
| 30 |
+
" Please use DeformableDetrImageProcessor instead.",
|
| 31 |
+
FutureWarning,
|
| 32 |
+
)
|
| 33 |
+
super().__init__(*args, **kwargs)
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/image_processing_deformable_detr.py
ADDED
|
@@ -0,0 +1,1449 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Image processor class for Deformable DETR."""
|
| 16 |
+
|
| 17 |
+
import io
|
| 18 |
+
import pathlib
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from ...feature_extraction_utils import BatchFeature
|
| 25 |
+
from ...image_processing_utils import BaseImageProcessor, get_size_dict
|
| 26 |
+
from ...image_transforms import (
|
| 27 |
+
PaddingMode,
|
| 28 |
+
center_to_corners_format,
|
| 29 |
+
corners_to_center_format,
|
| 30 |
+
id_to_rgb,
|
| 31 |
+
pad,
|
| 32 |
+
rescale,
|
| 33 |
+
resize,
|
| 34 |
+
rgb_to_id,
|
| 35 |
+
to_channel_dimension_format,
|
| 36 |
+
)
|
| 37 |
+
from ...image_utils import (
|
| 38 |
+
IMAGENET_DEFAULT_MEAN,
|
| 39 |
+
IMAGENET_DEFAULT_STD,
|
| 40 |
+
ChannelDimension,
|
| 41 |
+
ImageInput,
|
| 42 |
+
PILImageResampling,
|
| 43 |
+
get_image_size,
|
| 44 |
+
infer_channel_dimension_format,
|
| 45 |
+
is_scaled_image,
|
| 46 |
+
make_list_of_images,
|
| 47 |
+
to_numpy_array,
|
| 48 |
+
valid_coco_detection_annotations,
|
| 49 |
+
valid_coco_panoptic_annotations,
|
| 50 |
+
valid_images,
|
| 51 |
+
)
|
| 52 |
+
from ...utils import (
|
| 53 |
+
ExplicitEnum,
|
| 54 |
+
TensorType,
|
| 55 |
+
is_flax_available,
|
| 56 |
+
is_jax_tensor,
|
| 57 |
+
is_scipy_available,
|
| 58 |
+
is_tf_available,
|
| 59 |
+
is_tf_tensor,
|
| 60 |
+
is_torch_available,
|
| 61 |
+
is_torch_tensor,
|
| 62 |
+
is_vision_available,
|
| 63 |
+
logging,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if is_torch_available():
|
| 68 |
+
import torch
|
| 69 |
+
from torch import nn
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if is_vision_available():
|
| 73 |
+
import PIL
|
| 74 |
+
|
| 75 |
+
if is_scipy_available():
|
| 76 |
+
import scipy.special
|
| 77 |
+
import scipy.stats
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 81 |
+
|
| 82 |
+
AnnotationType = Dict[str, Union[int, str, List[Dict]]]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class AnnotionFormat(ExplicitEnum):
|
| 86 |
+
COCO_DETECTION = "coco_detection"
|
| 87 |
+
COCO_PANOPTIC = "coco_panoptic"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
SUPPORTED_ANNOTATION_FORMATS = (AnnotionFormat.COCO_DETECTION, AnnotionFormat.COCO_PANOPTIC)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# Copied from transformers.models.detr.image_processing_detr.get_size_with_aspect_ratio
|
| 94 |
+
def get_size_with_aspect_ratio(image_size, size, max_size=None) -> Tuple[int, int]:
|
| 95 |
+
"""
|
| 96 |
+
Computes the output image size given the input image size and the desired output size.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
image_size (`Tuple[int, int]`):
|
| 100 |
+
The input image size.
|
| 101 |
+
size (`int`):
|
| 102 |
+
The desired output size.
|
| 103 |
+
max_size (`int`, *optional*):
|
| 104 |
+
The maximum allowed output size.
|
| 105 |
+
"""
|
| 106 |
+
height, width = image_size
|
| 107 |
+
if max_size is not None:
|
| 108 |
+
min_original_size = float(min((height, width)))
|
| 109 |
+
max_original_size = float(max((height, width)))
|
| 110 |
+
if max_original_size / min_original_size * size > max_size:
|
| 111 |
+
size = int(round(max_size * min_original_size / max_original_size))
|
| 112 |
+
|
| 113 |
+
if (height <= width and height == size) or (width <= height and width == size):
|
| 114 |
+
return height, width
|
| 115 |
+
|
| 116 |
+
if width < height:
|
| 117 |
+
ow = size
|
| 118 |
+
oh = int(size * height / width)
|
| 119 |
+
else:
|
| 120 |
+
oh = size
|
| 121 |
+
ow = int(size * width / height)
|
| 122 |
+
return (oh, ow)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# Copied from transformers.models.detr.image_processing_detr.get_resize_output_image_size
|
| 126 |
+
def get_resize_output_image_size(
|
| 127 |
+
input_image: np.ndarray,
|
| 128 |
+
size: Union[int, Tuple[int, int], List[int]],
|
| 129 |
+
max_size: Optional[int] = None,
|
| 130 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 131 |
+
) -> Tuple[int, int]:
|
| 132 |
+
"""
|
| 133 |
+
Computes the output image size given the input image size and the desired output size. If the desired output size
|
| 134 |
+
is a tuple or list, the output image size is returned as is. If the desired output size is an integer, the output
|
| 135 |
+
image size is computed by keeping the aspect ratio of the input image size.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
image_size (`Tuple[int, int]`):
|
| 139 |
+
The input image size.
|
| 140 |
+
size (`int`):
|
| 141 |
+
The desired output size.
|
| 142 |
+
max_size (`int`, *optional*):
|
| 143 |
+
The maximum allowed output size.
|
| 144 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 145 |
+
The channel dimension format of the input image. If not provided, it will be inferred from the input image.
|
| 146 |
+
"""
|
| 147 |
+
image_size = get_image_size(input_image, input_data_format)
|
| 148 |
+
if isinstance(size, (list, tuple)):
|
| 149 |
+
return size
|
| 150 |
+
|
| 151 |
+
return get_size_with_aspect_ratio(image_size, size, max_size)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
# Copied from transformers.models.detr.image_processing_detr.get_numpy_to_framework_fn
|
| 155 |
+
def get_numpy_to_framework_fn(arr) -> Callable:
|
| 156 |
+
"""
|
| 157 |
+
Returns a function that converts a numpy array to the framework of the input array.
|
| 158 |
+
|
| 159 |
+
Args:
|
| 160 |
+
arr (`np.ndarray`): The array to convert.
|
| 161 |
+
"""
|
| 162 |
+
if isinstance(arr, np.ndarray):
|
| 163 |
+
return np.array
|
| 164 |
+
if is_tf_available() and is_tf_tensor(arr):
|
| 165 |
+
import tensorflow as tf
|
| 166 |
+
|
| 167 |
+
return tf.convert_to_tensor
|
| 168 |
+
if is_torch_available() and is_torch_tensor(arr):
|
| 169 |
+
import torch
|
| 170 |
+
|
| 171 |
+
return torch.tensor
|
| 172 |
+
if is_flax_available() and is_jax_tensor(arr):
|
| 173 |
+
import jax.numpy as jnp
|
| 174 |
+
|
| 175 |
+
return jnp.array
|
| 176 |
+
raise ValueError(f"Cannot convert arrays of type {type(arr)}")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# Copied from transformers.models.detr.image_processing_detr.safe_squeeze
|
| 180 |
+
def safe_squeeze(arr: np.ndarray, axis: Optional[int] = None) -> np.ndarray:
|
| 181 |
+
"""
|
| 182 |
+
Squeezes an array, but only if the axis specified has dim 1.
|
| 183 |
+
"""
|
| 184 |
+
if axis is None:
|
| 185 |
+
return arr.squeeze()
|
| 186 |
+
|
| 187 |
+
try:
|
| 188 |
+
return arr.squeeze(axis=axis)
|
| 189 |
+
except ValueError:
|
| 190 |
+
return arr
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# Copied from transformers.models.detr.image_processing_detr.normalize_annotation
|
| 194 |
+
def normalize_annotation(annotation: Dict, image_size: Tuple[int, int]) -> Dict:
|
| 195 |
+
image_height, image_width = image_size
|
| 196 |
+
norm_annotation = {}
|
| 197 |
+
for key, value in annotation.items():
|
| 198 |
+
if key == "boxes":
|
| 199 |
+
boxes = value
|
| 200 |
+
boxes = corners_to_center_format(boxes)
|
| 201 |
+
boxes /= np.asarray([image_width, image_height, image_width, image_height], dtype=np.float32)
|
| 202 |
+
norm_annotation[key] = boxes
|
| 203 |
+
else:
|
| 204 |
+
norm_annotation[key] = value
|
| 205 |
+
return norm_annotation
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# Copied from transformers.models.detr.image_processing_detr.max_across_indices
|
| 209 |
+
def max_across_indices(values: Iterable[Any]) -> List[Any]:
|
| 210 |
+
"""
|
| 211 |
+
Return the maximum value across all indices of an iterable of values.
|
| 212 |
+
"""
|
| 213 |
+
return [max(values_i) for values_i in zip(*values)]
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
# Copied from transformers.models.detr.image_processing_detr.get_max_height_width
|
| 217 |
+
def get_max_height_width(
|
| 218 |
+
images: List[np.ndarray], input_data_format: Optional[Union[str, ChannelDimension]] = None
|
| 219 |
+
) -> List[int]:
|
| 220 |
+
"""
|
| 221 |
+
Get the maximum height and width across all images in a batch.
|
| 222 |
+
"""
|
| 223 |
+
if input_data_format is None:
|
| 224 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 225 |
+
|
| 226 |
+
if input_data_format == ChannelDimension.FIRST:
|
| 227 |
+
_, max_height, max_width = max_across_indices([img.shape for img in images])
|
| 228 |
+
elif input_data_format == ChannelDimension.LAST:
|
| 229 |
+
max_height, max_width, _ = max_across_indices([img.shape for img in images])
|
| 230 |
+
else:
|
| 231 |
+
raise ValueError(f"Invalid channel dimension format: {input_data_format}")
|
| 232 |
+
return (max_height, max_width)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# Copied from transformers.models.detr.image_processing_detr.make_pixel_mask
|
| 236 |
+
def make_pixel_mask(
|
| 237 |
+
image: np.ndarray, output_size: Tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None
|
| 238 |
+
) -> np.ndarray:
|
| 239 |
+
"""
|
| 240 |
+
Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
|
| 241 |
+
|
| 242 |
+
Args:
|
| 243 |
+
image (`np.ndarray`):
|
| 244 |
+
Image to make the pixel mask for.
|
| 245 |
+
output_size (`Tuple[int, int]`):
|
| 246 |
+
Output size of the mask.
|
| 247 |
+
"""
|
| 248 |
+
input_height, input_width = get_image_size(image, channel_dim=input_data_format)
|
| 249 |
+
mask = np.zeros(output_size, dtype=np.int64)
|
| 250 |
+
mask[:input_height, :input_width] = 1
|
| 251 |
+
return mask
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
# Copied from transformers.models.detr.image_processing_detr.convert_coco_poly_to_mask
|
| 255 |
+
def convert_coco_poly_to_mask(segmentations, height: int, width: int) -> np.ndarray:
|
| 256 |
+
"""
|
| 257 |
+
Convert a COCO polygon annotation to a mask.
|
| 258 |
+
|
| 259 |
+
Args:
|
| 260 |
+
segmentations (`List[List[float]]`):
|
| 261 |
+
List of polygons, each polygon represented by a list of x-y coordinates.
|
| 262 |
+
height (`int`):
|
| 263 |
+
Height of the mask.
|
| 264 |
+
width (`int`):
|
| 265 |
+
Width of the mask.
|
| 266 |
+
"""
|
| 267 |
+
try:
|
| 268 |
+
from pycocotools import mask as coco_mask
|
| 269 |
+
except ImportError:
|
| 270 |
+
raise ImportError("Pycocotools is not installed in your environment.")
|
| 271 |
+
|
| 272 |
+
masks = []
|
| 273 |
+
for polygons in segmentations:
|
| 274 |
+
rles = coco_mask.frPyObjects(polygons, height, width)
|
| 275 |
+
mask = coco_mask.decode(rles)
|
| 276 |
+
if len(mask.shape) < 3:
|
| 277 |
+
mask = mask[..., None]
|
| 278 |
+
mask = np.asarray(mask, dtype=np.uint8)
|
| 279 |
+
mask = np.any(mask, axis=2)
|
| 280 |
+
masks.append(mask)
|
| 281 |
+
if masks:
|
| 282 |
+
masks = np.stack(masks, axis=0)
|
| 283 |
+
else:
|
| 284 |
+
masks = np.zeros((0, height, width), dtype=np.uint8)
|
| 285 |
+
|
| 286 |
+
return masks
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
# Copied from transformers.models.detr.image_processing_detr.prepare_coco_detection_annotation with DETR->DeformableDetr
|
| 290 |
+
def prepare_coco_detection_annotation(
|
| 291 |
+
image,
|
| 292 |
+
target,
|
| 293 |
+
return_segmentation_masks: bool = False,
|
| 294 |
+
input_data_format: Optional[Union[ChannelDimension, str]] = None,
|
| 295 |
+
):
|
| 296 |
+
"""
|
| 297 |
+
Convert the target in COCO format into the format expected by DeformableDetr.
|
| 298 |
+
"""
|
| 299 |
+
image_height, image_width = get_image_size(image, channel_dim=input_data_format)
|
| 300 |
+
|
| 301 |
+
image_id = target["image_id"]
|
| 302 |
+
image_id = np.asarray([image_id], dtype=np.int64)
|
| 303 |
+
|
| 304 |
+
# Get all COCO annotations for the given image.
|
| 305 |
+
annotations = target["annotations"]
|
| 306 |
+
annotations = [obj for obj in annotations if "iscrowd" not in obj or obj["iscrowd"] == 0]
|
| 307 |
+
|
| 308 |
+
classes = [obj["category_id"] for obj in annotations]
|
| 309 |
+
classes = np.asarray(classes, dtype=np.int64)
|
| 310 |
+
|
| 311 |
+
# for conversion to coco api
|
| 312 |
+
area = np.asarray([obj["area"] for obj in annotations], dtype=np.float32)
|
| 313 |
+
iscrowd = np.asarray([obj["iscrowd"] if "iscrowd" in obj else 0 for obj in annotations], dtype=np.int64)
|
| 314 |
+
|
| 315 |
+
boxes = [obj["bbox"] for obj in annotations]
|
| 316 |
+
# guard against no boxes via resizing
|
| 317 |
+
boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
|
| 318 |
+
boxes[:, 2:] += boxes[:, :2]
|
| 319 |
+
boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
|
| 320 |
+
boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
|
| 321 |
+
|
| 322 |
+
keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
|
| 323 |
+
|
| 324 |
+
new_target = {}
|
| 325 |
+
new_target["image_id"] = image_id
|
| 326 |
+
new_target["class_labels"] = classes[keep]
|
| 327 |
+
new_target["boxes"] = boxes[keep]
|
| 328 |
+
new_target["area"] = area[keep]
|
| 329 |
+
new_target["iscrowd"] = iscrowd[keep]
|
| 330 |
+
new_target["orig_size"] = np.asarray([int(image_height), int(image_width)], dtype=np.int64)
|
| 331 |
+
|
| 332 |
+
if annotations and "keypoints" in annotations[0]:
|
| 333 |
+
keypoints = [obj["keypoints"] for obj in annotations]
|
| 334 |
+
keypoints = np.asarray(keypoints, dtype=np.float32)
|
| 335 |
+
num_keypoints = keypoints.shape[0]
|
| 336 |
+
keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
|
| 337 |
+
new_target["keypoints"] = keypoints[keep]
|
| 338 |
+
|
| 339 |
+
if return_segmentation_masks:
|
| 340 |
+
segmentation_masks = [obj["segmentation"] for obj in annotations]
|
| 341 |
+
masks = convert_coco_poly_to_mask(segmentation_masks, image_height, image_width)
|
| 342 |
+
new_target["masks"] = masks[keep]
|
| 343 |
+
|
| 344 |
+
return new_target
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
# Copied from transformers.models.detr.image_processing_detr.masks_to_boxes
|
| 348 |
+
def masks_to_boxes(masks: np.ndarray) -> np.ndarray:
|
| 349 |
+
"""
|
| 350 |
+
Compute the bounding boxes around the provided panoptic segmentation masks.
|
| 351 |
+
|
| 352 |
+
Args:
|
| 353 |
+
masks: masks in format `[number_masks, height, width]` where N is the number of masks
|
| 354 |
+
|
| 355 |
+
Returns:
|
| 356 |
+
boxes: bounding boxes in format `[number_masks, 4]` in xyxy format
|
| 357 |
+
"""
|
| 358 |
+
if masks.size == 0:
|
| 359 |
+
return np.zeros((0, 4))
|
| 360 |
+
|
| 361 |
+
h, w = masks.shape[-2:]
|
| 362 |
+
y = np.arange(0, h, dtype=np.float32)
|
| 363 |
+
x = np.arange(0, w, dtype=np.float32)
|
| 364 |
+
# see https://github.com/pytorch/pytorch/issues/50276
|
| 365 |
+
y, x = np.meshgrid(y, x, indexing="ij")
|
| 366 |
+
|
| 367 |
+
x_mask = masks * np.expand_dims(x, axis=0)
|
| 368 |
+
x_max = x_mask.reshape(x_mask.shape[0], -1).max(-1)
|
| 369 |
+
x = np.ma.array(x_mask, mask=~(np.array(masks, dtype=bool)))
|
| 370 |
+
x_min = x.filled(fill_value=1e8)
|
| 371 |
+
x_min = x_min.reshape(x_min.shape[0], -1).min(-1)
|
| 372 |
+
|
| 373 |
+
y_mask = masks * np.expand_dims(y, axis=0)
|
| 374 |
+
y_max = y_mask.reshape(x_mask.shape[0], -1).max(-1)
|
| 375 |
+
y = np.ma.array(y_mask, mask=~(np.array(masks, dtype=bool)))
|
| 376 |
+
y_min = y.filled(fill_value=1e8)
|
| 377 |
+
y_min = y_min.reshape(y_min.shape[0], -1).min(-1)
|
| 378 |
+
|
| 379 |
+
return np.stack([x_min, y_min, x_max, y_max], 1)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
# Copied from transformers.models.detr.image_processing_detr.prepare_coco_panoptic_annotation with DETR->DeformableDetr
|
| 383 |
+
def prepare_coco_panoptic_annotation(
|
| 384 |
+
image: np.ndarray,
|
| 385 |
+
target: Dict,
|
| 386 |
+
masks_path: Union[str, pathlib.Path],
|
| 387 |
+
return_masks: bool = True,
|
| 388 |
+
input_data_format: Union[ChannelDimension, str] = None,
|
| 389 |
+
) -> Dict:
|
| 390 |
+
"""
|
| 391 |
+
Prepare a coco panoptic annotation for DeformableDetr.
|
| 392 |
+
"""
|
| 393 |
+
image_height, image_width = get_image_size(image, channel_dim=input_data_format)
|
| 394 |
+
annotation_path = pathlib.Path(masks_path) / target["file_name"]
|
| 395 |
+
|
| 396 |
+
new_target = {}
|
| 397 |
+
new_target["image_id"] = np.asarray([target["image_id"] if "image_id" in target else target["id"]], dtype=np.int64)
|
| 398 |
+
new_target["size"] = np.asarray([image_height, image_width], dtype=np.int64)
|
| 399 |
+
new_target["orig_size"] = np.asarray([image_height, image_width], dtype=np.int64)
|
| 400 |
+
|
| 401 |
+
if "segments_info" in target:
|
| 402 |
+
masks = np.asarray(PIL.Image.open(annotation_path), dtype=np.uint32)
|
| 403 |
+
masks = rgb_to_id(masks)
|
| 404 |
+
|
| 405 |
+
ids = np.array([segment_info["id"] for segment_info in target["segments_info"]])
|
| 406 |
+
masks = masks == ids[:, None, None]
|
| 407 |
+
masks = masks.astype(np.uint8)
|
| 408 |
+
if return_masks:
|
| 409 |
+
new_target["masks"] = masks
|
| 410 |
+
new_target["boxes"] = masks_to_boxes(masks)
|
| 411 |
+
new_target["class_labels"] = np.array(
|
| 412 |
+
[segment_info["category_id"] for segment_info in target["segments_info"]], dtype=np.int64
|
| 413 |
+
)
|
| 414 |
+
new_target["iscrowd"] = np.asarray(
|
| 415 |
+
[segment_info["iscrowd"] for segment_info in target["segments_info"]], dtype=np.int64
|
| 416 |
+
)
|
| 417 |
+
new_target["area"] = np.asarray(
|
| 418 |
+
[segment_info["area"] for segment_info in target["segments_info"]], dtype=np.float32
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
return new_target
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
# Copied from transformers.models.detr.image_processing_detr.get_segmentation_image
|
| 425 |
+
def get_segmentation_image(
|
| 426 |
+
masks: np.ndarray, input_size: Tuple, target_size: Tuple, stuff_equiv_classes, deduplicate=False
|
| 427 |
+
):
|
| 428 |
+
h, w = input_size
|
| 429 |
+
final_h, final_w = target_size
|
| 430 |
+
|
| 431 |
+
m_id = scipy.special.softmax(masks.transpose(0, 1), -1)
|
| 432 |
+
|
| 433 |
+
if m_id.shape[-1] == 0:
|
| 434 |
+
# We didn't detect any mask :(
|
| 435 |
+
m_id = np.zeros((h, w), dtype=np.int64)
|
| 436 |
+
else:
|
| 437 |
+
m_id = m_id.argmax(-1).reshape(h, w)
|
| 438 |
+
|
| 439 |
+
if deduplicate:
|
| 440 |
+
# Merge the masks corresponding to the same stuff class
|
| 441 |
+
for equiv in stuff_equiv_classes.values():
|
| 442 |
+
for eq_id in equiv:
|
| 443 |
+
m_id[m_id == eq_id] = equiv[0]
|
| 444 |
+
|
| 445 |
+
seg_img = id_to_rgb(m_id)
|
| 446 |
+
seg_img = resize(seg_img, (final_w, final_h), resample=PILImageResampling.NEAREST)
|
| 447 |
+
return seg_img
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
# Copied from transformers.models.detr.image_processing_detr.get_mask_area
|
| 451 |
+
def get_mask_area(seg_img: np.ndarray, target_size: Tuple[int, int], n_classes: int) -> np.ndarray:
|
| 452 |
+
final_h, final_w = target_size
|
| 453 |
+
np_seg_img = seg_img.astype(np.uint8)
|
| 454 |
+
np_seg_img = np_seg_img.reshape(final_h, final_w, 3)
|
| 455 |
+
m_id = rgb_to_id(np_seg_img)
|
| 456 |
+
area = [(m_id == i).sum() for i in range(n_classes)]
|
| 457 |
+
return area
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# Copied from transformers.models.detr.image_processing_detr.score_labels_from_class_probabilities
|
| 461 |
+
def score_labels_from_class_probabilities(logits: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
|
| 462 |
+
probs = scipy.special.softmax(logits, axis=-1)
|
| 463 |
+
labels = probs.argmax(-1, keepdims=True)
|
| 464 |
+
scores = np.take_along_axis(probs, labels, axis=-1)
|
| 465 |
+
scores, labels = scores.squeeze(-1), labels.squeeze(-1)
|
| 466 |
+
return scores, labels
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
# Copied from transformers.models.detr.image_processing_detr.post_process_panoptic_sample
|
| 470 |
+
def post_process_panoptic_sample(
|
| 471 |
+
out_logits: np.ndarray,
|
| 472 |
+
masks: np.ndarray,
|
| 473 |
+
boxes: np.ndarray,
|
| 474 |
+
processed_size: Tuple[int, int],
|
| 475 |
+
target_size: Tuple[int, int],
|
| 476 |
+
is_thing_map: Dict,
|
| 477 |
+
threshold=0.85,
|
| 478 |
+
) -> Dict:
|
| 479 |
+
"""
|
| 480 |
+
Converts the output of [`DetrForSegmentation`] into panoptic segmentation predictions for a single sample.
|
| 481 |
+
|
| 482 |
+
Args:
|
| 483 |
+
out_logits (`torch.Tensor`):
|
| 484 |
+
The logits for this sample.
|
| 485 |
+
masks (`torch.Tensor`):
|
| 486 |
+
The predicted segmentation masks for this sample.
|
| 487 |
+
boxes (`torch.Tensor`):
|
| 488 |
+
The prediced bounding boxes for this sample. The boxes are in the normalized format `(center_x, center_y,
|
| 489 |
+
width, height)` and values between `[0, 1]`, relative to the size the image (disregarding padding).
|
| 490 |
+
processed_size (`Tuple[int, int]`):
|
| 491 |
+
The processed size of the image `(height, width)`, as returned by the preprocessing step i.e. the size
|
| 492 |
+
after data augmentation but before batching.
|
| 493 |
+
target_size (`Tuple[int, int]`):
|
| 494 |
+
The target size of the image, `(height, width)` corresponding to the requested final size of the
|
| 495 |
+
prediction.
|
| 496 |
+
is_thing_map (`Dict`):
|
| 497 |
+
A dictionary mapping class indices to a boolean value indicating whether the class is a thing or not.
|
| 498 |
+
threshold (`float`, *optional*, defaults to 0.85):
|
| 499 |
+
The threshold used to binarize the segmentation masks.
|
| 500 |
+
"""
|
| 501 |
+
# we filter empty queries and detection below threshold
|
| 502 |
+
scores, labels = score_labels_from_class_probabilities(out_logits)
|
| 503 |
+
keep = (labels != out_logits.shape[-1] - 1) & (scores > threshold)
|
| 504 |
+
|
| 505 |
+
cur_scores = scores[keep]
|
| 506 |
+
cur_classes = labels[keep]
|
| 507 |
+
cur_boxes = center_to_corners_format(boxes[keep])
|
| 508 |
+
|
| 509 |
+
if len(cur_boxes) != len(cur_classes):
|
| 510 |
+
raise ValueError("Not as many boxes as there are classes")
|
| 511 |
+
|
| 512 |
+
cur_masks = masks[keep]
|
| 513 |
+
cur_masks = resize(cur_masks[:, None], processed_size, resample=PILImageResampling.BILINEAR)
|
| 514 |
+
cur_masks = safe_squeeze(cur_masks, 1)
|
| 515 |
+
b, h, w = cur_masks.shape
|
| 516 |
+
|
| 517 |
+
# It may be that we have several predicted masks for the same stuff class.
|
| 518 |
+
# In the following, we track the list of masks ids for each stuff class (they are merged later on)
|
| 519 |
+
cur_masks = cur_masks.reshape(b, -1)
|
| 520 |
+
stuff_equiv_classes = defaultdict(list)
|
| 521 |
+
for k, label in enumerate(cur_classes):
|
| 522 |
+
if not is_thing_map[label]:
|
| 523 |
+
stuff_equiv_classes[label].append(k)
|
| 524 |
+
|
| 525 |
+
seg_img = get_segmentation_image(cur_masks, processed_size, target_size, stuff_equiv_classes, deduplicate=True)
|
| 526 |
+
area = get_mask_area(cur_masks, processed_size, n_classes=len(cur_scores))
|
| 527 |
+
|
| 528 |
+
# We filter out any mask that is too small
|
| 529 |
+
if cur_classes.size() > 0:
|
| 530 |
+
# We know filter empty masks as long as we find some
|
| 531 |
+
filtered_small = np.array([a <= 4 for a in area], dtype=bool)
|
| 532 |
+
while filtered_small.any():
|
| 533 |
+
cur_masks = cur_masks[~filtered_small]
|
| 534 |
+
cur_scores = cur_scores[~filtered_small]
|
| 535 |
+
cur_classes = cur_classes[~filtered_small]
|
| 536 |
+
seg_img = get_segmentation_image(cur_masks, (h, w), target_size, stuff_equiv_classes, deduplicate=True)
|
| 537 |
+
area = get_mask_area(seg_img, target_size, n_classes=len(cur_scores))
|
| 538 |
+
filtered_small = np.array([a <= 4 for a in area], dtype=bool)
|
| 539 |
+
else:
|
| 540 |
+
cur_classes = np.ones((1, 1), dtype=np.int64)
|
| 541 |
+
|
| 542 |
+
segments_info = [
|
| 543 |
+
{"id": i, "isthing": is_thing_map[cat], "category_id": int(cat), "area": a}
|
| 544 |
+
for i, (cat, a) in enumerate(zip(cur_classes, area))
|
| 545 |
+
]
|
| 546 |
+
del cur_classes
|
| 547 |
+
|
| 548 |
+
with io.BytesIO() as out:
|
| 549 |
+
PIL.Image.fromarray(seg_img).save(out, format="PNG")
|
| 550 |
+
predictions = {"png_string": out.getvalue(), "segments_info": segments_info}
|
| 551 |
+
|
| 552 |
+
return predictions
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
# Copied from transformers.models.detr.image_processing_detr.resize_annotation
|
| 556 |
+
def resize_annotation(
|
| 557 |
+
annotation: Dict[str, Any],
|
| 558 |
+
orig_size: Tuple[int, int],
|
| 559 |
+
target_size: Tuple[int, int],
|
| 560 |
+
threshold: float = 0.5,
|
| 561 |
+
resample: PILImageResampling = PILImageResampling.NEAREST,
|
| 562 |
+
):
|
| 563 |
+
"""
|
| 564 |
+
Resizes an annotation to a target size.
|
| 565 |
+
|
| 566 |
+
Args:
|
| 567 |
+
annotation (`Dict[str, Any]`):
|
| 568 |
+
The annotation dictionary.
|
| 569 |
+
orig_size (`Tuple[int, int]`):
|
| 570 |
+
The original size of the input image.
|
| 571 |
+
target_size (`Tuple[int, int]`):
|
| 572 |
+
The target size of the image, as returned by the preprocessing `resize` step.
|
| 573 |
+
threshold (`float`, *optional*, defaults to 0.5):
|
| 574 |
+
The threshold used to binarize the segmentation masks.
|
| 575 |
+
resample (`PILImageResampling`, defaults to `PILImageResampling.NEAREST`):
|
| 576 |
+
The resampling filter to use when resizing the masks.
|
| 577 |
+
"""
|
| 578 |
+
ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(target_size, orig_size))
|
| 579 |
+
ratio_height, ratio_width = ratios
|
| 580 |
+
|
| 581 |
+
new_annotation = {}
|
| 582 |
+
new_annotation["size"] = target_size
|
| 583 |
+
|
| 584 |
+
for key, value in annotation.items():
|
| 585 |
+
if key == "boxes":
|
| 586 |
+
boxes = value
|
| 587 |
+
scaled_boxes = boxes * np.asarray([ratio_width, ratio_height, ratio_width, ratio_height], dtype=np.float32)
|
| 588 |
+
new_annotation["boxes"] = scaled_boxes
|
| 589 |
+
elif key == "area":
|
| 590 |
+
area = value
|
| 591 |
+
scaled_area = area * (ratio_width * ratio_height)
|
| 592 |
+
new_annotation["area"] = scaled_area
|
| 593 |
+
elif key == "masks":
|
| 594 |
+
masks = value[:, None]
|
| 595 |
+
masks = np.array([resize(mask, target_size, resample=resample) for mask in masks])
|
| 596 |
+
masks = masks.astype(np.float32)
|
| 597 |
+
masks = masks[:, 0] > threshold
|
| 598 |
+
new_annotation["masks"] = masks
|
| 599 |
+
elif key == "size":
|
| 600 |
+
new_annotation["size"] = target_size
|
| 601 |
+
else:
|
| 602 |
+
new_annotation[key] = value
|
| 603 |
+
|
| 604 |
+
return new_annotation
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
# Copied from transformers.models.detr.image_processing_detr.binary_mask_to_rle
|
| 608 |
+
def binary_mask_to_rle(mask):
|
| 609 |
+
"""
|
| 610 |
+
Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format.
|
| 611 |
+
|
| 612 |
+
Args:
|
| 613 |
+
mask (`torch.Tensor` or `numpy.array`):
|
| 614 |
+
A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target
|
| 615 |
+
segment_id or class_id.
|
| 616 |
+
Returns:
|
| 617 |
+
`List`: Run-length encoded list of the binary mask. Refer to COCO API for more information about the RLE
|
| 618 |
+
format.
|
| 619 |
+
"""
|
| 620 |
+
if is_torch_tensor(mask):
|
| 621 |
+
mask = mask.numpy()
|
| 622 |
+
|
| 623 |
+
pixels = mask.flatten()
|
| 624 |
+
pixels = np.concatenate([[0], pixels, [0]])
|
| 625 |
+
runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
|
| 626 |
+
runs[1::2] -= runs[::2]
|
| 627 |
+
return list(runs)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
# Copied from transformers.models.detr.image_processing_detr.convert_segmentation_to_rle
|
| 631 |
+
def convert_segmentation_to_rle(segmentation):
|
| 632 |
+
"""
|
| 633 |
+
Converts given segmentation map of shape `(height, width)` to the run-length encoding (RLE) format.
|
| 634 |
+
|
| 635 |
+
Args:
|
| 636 |
+
segmentation (`torch.Tensor` or `numpy.array`):
|
| 637 |
+
A segmentation map of shape `(height, width)` where each value denotes a segment or class id.
|
| 638 |
+
Returns:
|
| 639 |
+
`List[List]`: A list of lists, where each list is the run-length encoding of a segment / class id.
|
| 640 |
+
"""
|
| 641 |
+
segment_ids = torch.unique(segmentation)
|
| 642 |
+
|
| 643 |
+
run_length_encodings = []
|
| 644 |
+
for idx in segment_ids:
|
| 645 |
+
mask = torch.where(segmentation == idx, 1, 0)
|
| 646 |
+
rle = binary_mask_to_rle(mask)
|
| 647 |
+
run_length_encodings.append(rle)
|
| 648 |
+
|
| 649 |
+
return run_length_encodings
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
# Copied from transformers.models.detr.image_processing_detr.remove_low_and_no_objects
|
| 653 |
+
def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels):
|
| 654 |
+
"""
|
| 655 |
+
Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and
|
| 656 |
+
`labels`.
|
| 657 |
+
|
| 658 |
+
Args:
|
| 659 |
+
masks (`torch.Tensor`):
|
| 660 |
+
A tensor of shape `(num_queries, height, width)`.
|
| 661 |
+
scores (`torch.Tensor`):
|
| 662 |
+
A tensor of shape `(num_queries)`.
|
| 663 |
+
labels (`torch.Tensor`):
|
| 664 |
+
A tensor of shape `(num_queries)`.
|
| 665 |
+
object_mask_threshold (`float`):
|
| 666 |
+
A number between 0 and 1 used to binarize the masks.
|
| 667 |
+
Raises:
|
| 668 |
+
`ValueError`: Raised when the first dimension doesn't match in all input tensors.
|
| 669 |
+
Returns:
|
| 670 |
+
`Tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region
|
| 671 |
+
< `object_mask_threshold`.
|
| 672 |
+
"""
|
| 673 |
+
if not (masks.shape[0] == scores.shape[0] == labels.shape[0]):
|
| 674 |
+
raise ValueError("mask, scores and labels must have the same shape!")
|
| 675 |
+
|
| 676 |
+
to_keep = labels.ne(num_labels) & (scores > object_mask_threshold)
|
| 677 |
+
|
| 678 |
+
return masks[to_keep], scores[to_keep], labels[to_keep]
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
# Copied from transformers.models.detr.image_processing_detr.check_segment_validity
|
| 682 |
+
def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8):
|
| 683 |
+
# Get the mask associated with the k class
|
| 684 |
+
mask_k = mask_labels == k
|
| 685 |
+
mask_k_area = mask_k.sum()
|
| 686 |
+
|
| 687 |
+
# Compute the area of all the stuff in query k
|
| 688 |
+
original_area = (mask_probs[k] >= mask_threshold).sum()
|
| 689 |
+
mask_exists = mask_k_area > 0 and original_area > 0
|
| 690 |
+
|
| 691 |
+
# Eliminate disconnected tiny segments
|
| 692 |
+
if mask_exists:
|
| 693 |
+
area_ratio = mask_k_area / original_area
|
| 694 |
+
if not area_ratio.item() > overlap_mask_area_threshold:
|
| 695 |
+
mask_exists = False
|
| 696 |
+
|
| 697 |
+
return mask_exists, mask_k
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
# Copied from transformers.models.detr.image_processing_detr.compute_segments
|
| 701 |
+
def compute_segments(
|
| 702 |
+
mask_probs,
|
| 703 |
+
pred_scores,
|
| 704 |
+
pred_labels,
|
| 705 |
+
mask_threshold: float = 0.5,
|
| 706 |
+
overlap_mask_area_threshold: float = 0.8,
|
| 707 |
+
label_ids_to_fuse: Optional[Set[int]] = None,
|
| 708 |
+
target_size: Tuple[int, int] = None,
|
| 709 |
+
):
|
| 710 |
+
height = mask_probs.shape[1] if target_size is None else target_size[0]
|
| 711 |
+
width = mask_probs.shape[2] if target_size is None else target_size[1]
|
| 712 |
+
|
| 713 |
+
segmentation = torch.zeros((height, width), dtype=torch.int32, device=mask_probs.device)
|
| 714 |
+
segments: List[Dict] = []
|
| 715 |
+
|
| 716 |
+
if target_size is not None:
|
| 717 |
+
mask_probs = nn.functional.interpolate(
|
| 718 |
+
mask_probs.unsqueeze(0), size=target_size, mode="bilinear", align_corners=False
|
| 719 |
+
)[0]
|
| 720 |
+
|
| 721 |
+
current_segment_id = 0
|
| 722 |
+
|
| 723 |
+
# Weigh each mask by its prediction score
|
| 724 |
+
mask_probs *= pred_scores.view(-1, 1, 1)
|
| 725 |
+
mask_labels = mask_probs.argmax(0) # [height, width]
|
| 726 |
+
|
| 727 |
+
# Keep track of instances of each class
|
| 728 |
+
stuff_memory_list: Dict[str, int] = {}
|
| 729 |
+
for k in range(pred_labels.shape[0]):
|
| 730 |
+
pred_class = pred_labels[k].item()
|
| 731 |
+
should_fuse = pred_class in label_ids_to_fuse
|
| 732 |
+
|
| 733 |
+
# Check if mask exists and large enough to be a segment
|
| 734 |
+
mask_exists, mask_k = check_segment_validity(
|
| 735 |
+
mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
if mask_exists:
|
| 739 |
+
if pred_class in stuff_memory_list:
|
| 740 |
+
current_segment_id = stuff_memory_list[pred_class]
|
| 741 |
+
else:
|
| 742 |
+
current_segment_id += 1
|
| 743 |
+
|
| 744 |
+
# Add current object segment to final segmentation map
|
| 745 |
+
segmentation[mask_k] = current_segment_id
|
| 746 |
+
segment_score = round(pred_scores[k].item(), 6)
|
| 747 |
+
segments.append(
|
| 748 |
+
{
|
| 749 |
+
"id": current_segment_id,
|
| 750 |
+
"label_id": pred_class,
|
| 751 |
+
"was_fused": should_fuse,
|
| 752 |
+
"score": segment_score,
|
| 753 |
+
}
|
| 754 |
+
)
|
| 755 |
+
if should_fuse:
|
| 756 |
+
stuff_memory_list[pred_class] = current_segment_id
|
| 757 |
+
|
| 758 |
+
return segmentation, segments
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
class DeformableDetrImageProcessor(BaseImageProcessor):
|
| 762 |
+
r"""
|
| 763 |
+
Constructs a Deformable DETR image processor.
|
| 764 |
+
|
| 765 |
+
Args:
|
| 766 |
+
format (`str`, *optional*, defaults to `"coco_detection"`):
|
| 767 |
+
Data format of the annotations. One of "coco_detection" or "coco_panoptic".
|
| 768 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 769 |
+
Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be
|
| 770 |
+
overridden by the `do_resize` parameter in the `preprocess` method.
|
| 771 |
+
size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 800, "longest_edge": 1333}`):
|
| 772 |
+
Size of the image's (height, width) dimensions after resizing. Can be overridden by the `size` parameter in
|
| 773 |
+
the `preprocess` method.
|
| 774 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
|
| 775 |
+
Resampling filter to use if resizing the image.
|
| 776 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 777 |
+
Controls whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
|
| 778 |
+
`do_rescale` parameter in the `preprocess` method.
|
| 779 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 780 |
+
Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
|
| 781 |
+
`preprocess` method.
|
| 782 |
+
do_normalize:
|
| 783 |
+
Controls whether to normalize the image. Can be overridden by the `do_normalize` parameter in the
|
| 784 |
+
`preprocess` method.
|
| 785 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN`):
|
| 786 |
+
Mean values to use when normalizing the image. Can be a single value or a list of values, one for each
|
| 787 |
+
channel. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 788 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_STD`):
|
| 789 |
+
Standard deviation values to use when normalizing the image. Can be a single value or a list of values, one
|
| 790 |
+
for each channel. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 791 |
+
do_pad (`bool`, *optional*, defaults to `True`):
|
| 792 |
+
Controls whether to pad the image to the largest image in a batch and create a pixel mask. Can be
|
| 793 |
+
overridden by the `do_pad` parameter in the `preprocess` method.
|
| 794 |
+
"""
|
| 795 |
+
|
| 796 |
+
model_input_names = ["pixel_values", "pixel_mask"]
|
| 797 |
+
|
| 798 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.__init__
|
| 799 |
+
def __init__(
|
| 800 |
+
self,
|
| 801 |
+
format: Union[str, AnnotionFormat] = AnnotionFormat.COCO_DETECTION,
|
| 802 |
+
do_resize: bool = True,
|
| 803 |
+
size: Dict[str, int] = None,
|
| 804 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 805 |
+
do_rescale: bool = True,
|
| 806 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 807 |
+
do_normalize: bool = True,
|
| 808 |
+
image_mean: Union[float, List[float]] = None,
|
| 809 |
+
image_std: Union[float, List[float]] = None,
|
| 810 |
+
do_pad: bool = True,
|
| 811 |
+
**kwargs,
|
| 812 |
+
) -> None:
|
| 813 |
+
if "pad_and_return_pixel_mask" in kwargs:
|
| 814 |
+
do_pad = kwargs.pop("pad_and_return_pixel_mask")
|
| 815 |
+
|
| 816 |
+
if "max_size" in kwargs:
|
| 817 |
+
logger.warning_once(
|
| 818 |
+
"The `max_size` parameter is deprecated and will be removed in v4.26. "
|
| 819 |
+
"Please specify in `size['longest_edge'] instead`.",
|
| 820 |
+
)
|
| 821 |
+
max_size = kwargs.pop("max_size")
|
| 822 |
+
else:
|
| 823 |
+
max_size = None if size is None else 1333
|
| 824 |
+
|
| 825 |
+
size = size if size is not None else {"shortest_edge": 800, "longest_edge": 1333}
|
| 826 |
+
size = get_size_dict(size, max_size=max_size, default_to_square=False)
|
| 827 |
+
|
| 828 |
+
super().__init__(**kwargs)
|
| 829 |
+
self.format = format
|
| 830 |
+
self.do_resize = do_resize
|
| 831 |
+
self.size = size
|
| 832 |
+
self.resample = resample
|
| 833 |
+
self.do_rescale = do_rescale
|
| 834 |
+
self.rescale_factor = rescale_factor
|
| 835 |
+
self.do_normalize = do_normalize
|
| 836 |
+
self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
|
| 837 |
+
self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
|
| 838 |
+
self.do_pad = do_pad
|
| 839 |
+
|
| 840 |
+
@classmethod
|
| 841 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.from_dict with Detr->DeformableDetr
|
| 842 |
+
def from_dict(cls, image_processor_dict: Dict[str, Any], **kwargs):
|
| 843 |
+
"""
|
| 844 |
+
Overrides the `from_dict` method from the base class to make sure parameters are updated if image processor is
|
| 845 |
+
created using from_dict and kwargs e.g. `DeformableDetrImageProcessor.from_pretrained(checkpoint, size=600,
|
| 846 |
+
max_size=800)`
|
| 847 |
+
"""
|
| 848 |
+
image_processor_dict = image_processor_dict.copy()
|
| 849 |
+
if "max_size" in kwargs:
|
| 850 |
+
image_processor_dict["max_size"] = kwargs.pop("max_size")
|
| 851 |
+
if "pad_and_return_pixel_mask" in kwargs:
|
| 852 |
+
image_processor_dict["pad_and_return_pixel_mask"] = kwargs.pop("pad_and_return_pixel_mask")
|
| 853 |
+
return super().from_dict(image_processor_dict, **kwargs)
|
| 854 |
+
|
| 855 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.prepare_annotation with DETR->DeformableDetr
|
| 856 |
+
def prepare_annotation(
|
| 857 |
+
self,
|
| 858 |
+
image: np.ndarray,
|
| 859 |
+
target: Dict,
|
| 860 |
+
format: Optional[AnnotionFormat] = None,
|
| 861 |
+
return_segmentation_masks: bool = None,
|
| 862 |
+
masks_path: Optional[Union[str, pathlib.Path]] = None,
|
| 863 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 864 |
+
) -> Dict:
|
| 865 |
+
"""
|
| 866 |
+
Prepare an annotation for feeding into DeformableDetr model.
|
| 867 |
+
"""
|
| 868 |
+
format = format if format is not None else self.format
|
| 869 |
+
|
| 870 |
+
if format == AnnotionFormat.COCO_DETECTION:
|
| 871 |
+
return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
|
| 872 |
+
target = prepare_coco_detection_annotation(
|
| 873 |
+
image, target, return_segmentation_masks, input_data_format=input_data_format
|
| 874 |
+
)
|
| 875 |
+
elif format == AnnotionFormat.COCO_PANOPTIC:
|
| 876 |
+
return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks
|
| 877 |
+
target = prepare_coco_panoptic_annotation(
|
| 878 |
+
image,
|
| 879 |
+
target,
|
| 880 |
+
masks_path=masks_path,
|
| 881 |
+
return_masks=return_segmentation_masks,
|
| 882 |
+
input_data_format=input_data_format,
|
| 883 |
+
)
|
| 884 |
+
else:
|
| 885 |
+
raise ValueError(f"Format {format} is not supported.")
|
| 886 |
+
return target
|
| 887 |
+
|
| 888 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.prepare
|
| 889 |
+
def prepare(self, image, target, return_segmentation_masks=None, masks_path=None):
|
| 890 |
+
logger.warning_once(
|
| 891 |
+
"The `prepare` method is deprecated and will be removed in a v4.33. "
|
| 892 |
+
"Please use `prepare_annotation` instead. Note: the `prepare_annotation` method "
|
| 893 |
+
"does not return the image anymore.",
|
| 894 |
+
)
|
| 895 |
+
target = self.prepare_annotation(image, target, return_segmentation_masks, masks_path, self.format)
|
| 896 |
+
return image, target
|
| 897 |
+
|
| 898 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.convert_coco_poly_to_mask
|
| 899 |
+
def convert_coco_poly_to_mask(self, *args, **kwargs):
|
| 900 |
+
logger.warning_once("The `convert_coco_poly_to_mask` method is deprecated and will be removed in v4.33. ")
|
| 901 |
+
return convert_coco_poly_to_mask(*args, **kwargs)
|
| 902 |
+
|
| 903 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.prepare_coco_detection
|
| 904 |
+
def prepare_coco_detection(self, *args, **kwargs):
|
| 905 |
+
logger.warning_once("The `prepare_coco_detection` method is deprecated and will be removed in v4.33. ")
|
| 906 |
+
return prepare_coco_detection_annotation(*args, **kwargs)
|
| 907 |
+
|
| 908 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.prepare_coco_panoptic
|
| 909 |
+
def prepare_coco_panoptic(self, *args, **kwargs):
|
| 910 |
+
logger.warning_once("The `prepare_coco_panoptic` method is deprecated and will be removed in v4.33. ")
|
| 911 |
+
return prepare_coco_panoptic_annotation(*args, **kwargs)
|
| 912 |
+
|
| 913 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.resize
|
| 914 |
+
def resize(
|
| 915 |
+
self,
|
| 916 |
+
image: np.ndarray,
|
| 917 |
+
size: Dict[str, int],
|
| 918 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
| 919 |
+
data_format: Optional[ChannelDimension] = None,
|
| 920 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 921 |
+
**kwargs,
|
| 922 |
+
) -> np.ndarray:
|
| 923 |
+
"""
|
| 924 |
+
Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
|
| 925 |
+
int, smaller edge of the image will be matched to this number.
|
| 926 |
+
|
| 927 |
+
Args:
|
| 928 |
+
image (`np.ndarray`):
|
| 929 |
+
Image to resize.
|
| 930 |
+
size (`Dict[str, int]`):
|
| 931 |
+
Dictionary containing the size to resize to. Can contain the keys `shortest_edge` and `longest_edge` or
|
| 932 |
+
`height` and `width`.
|
| 933 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
|
| 934 |
+
Resampling filter to use if resizing the image.
|
| 935 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 936 |
+
The channel dimension format for the output image. If unset, the channel dimension format of the input
|
| 937 |
+
image is used.
|
| 938 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 939 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 940 |
+
"""
|
| 941 |
+
if "max_size" in kwargs:
|
| 942 |
+
logger.warning_once(
|
| 943 |
+
"The `max_size` parameter is deprecated and will be removed in v4.26. "
|
| 944 |
+
"Please specify in `size['longest_edge'] instead`.",
|
| 945 |
+
)
|
| 946 |
+
max_size = kwargs.pop("max_size")
|
| 947 |
+
else:
|
| 948 |
+
max_size = None
|
| 949 |
+
size = get_size_dict(size, max_size=max_size, default_to_square=False)
|
| 950 |
+
if "shortest_edge" in size and "longest_edge" in size:
|
| 951 |
+
size = get_resize_output_image_size(
|
| 952 |
+
image, size["shortest_edge"], size["longest_edge"], input_data_format=input_data_format
|
| 953 |
+
)
|
| 954 |
+
elif "height" in size and "width" in size:
|
| 955 |
+
size = (size["height"], size["width"])
|
| 956 |
+
else:
|
| 957 |
+
raise ValueError(
|
| 958 |
+
"Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got"
|
| 959 |
+
f" {size.keys()}."
|
| 960 |
+
)
|
| 961 |
+
image = resize(
|
| 962 |
+
image, size=size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs
|
| 963 |
+
)
|
| 964 |
+
return image
|
| 965 |
+
|
| 966 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.resize_annotation
|
| 967 |
+
def resize_annotation(
|
| 968 |
+
self,
|
| 969 |
+
annotation,
|
| 970 |
+
orig_size,
|
| 971 |
+
size,
|
| 972 |
+
resample: PILImageResampling = PILImageResampling.NEAREST,
|
| 973 |
+
) -> Dict:
|
| 974 |
+
"""
|
| 975 |
+
Resize the annotation to match the resized image. If size is an int, smaller edge of the mask will be matched
|
| 976 |
+
to this number.
|
| 977 |
+
"""
|
| 978 |
+
return resize_annotation(annotation, orig_size=orig_size, target_size=size, resample=resample)
|
| 979 |
+
|
| 980 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.rescale
|
| 981 |
+
def rescale(
|
| 982 |
+
self,
|
| 983 |
+
image: np.ndarray,
|
| 984 |
+
rescale_factor: float,
|
| 985 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 986 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 987 |
+
) -> np.ndarray:
|
| 988 |
+
"""
|
| 989 |
+
Rescale the image by the given factor. image = image * rescale_factor.
|
| 990 |
+
|
| 991 |
+
Args:
|
| 992 |
+
image (`np.ndarray`):
|
| 993 |
+
Image to rescale.
|
| 994 |
+
rescale_factor (`float`):
|
| 995 |
+
The value to use for rescaling.
|
| 996 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 997 |
+
The channel dimension format for the output image. If unset, the channel dimension format of the input
|
| 998 |
+
image is used. Can be one of:
|
| 999 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 1000 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 1001 |
+
input_data_format (`str` or `ChannelDimension`, *optional*):
|
| 1002 |
+
The channel dimension format for the input image. If unset, is inferred from the input image. Can be
|
| 1003 |
+
one of:
|
| 1004 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 1005 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 1006 |
+
"""
|
| 1007 |
+
return rescale(image, rescale_factor, data_format=data_format, input_data_format=input_data_format)
|
| 1008 |
+
|
| 1009 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.normalize_annotation
|
| 1010 |
+
def normalize_annotation(self, annotation: Dict, image_size: Tuple[int, int]) -> Dict:
|
| 1011 |
+
"""
|
| 1012 |
+
Normalize the boxes in the annotation from `[top_left_x, top_left_y, bottom_right_x, bottom_right_y]` to
|
| 1013 |
+
`[center_x, center_y, width, height]` format.
|
| 1014 |
+
"""
|
| 1015 |
+
return normalize_annotation(annotation, image_size=image_size)
|
| 1016 |
+
|
| 1017 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor._pad_image
|
| 1018 |
+
def _pad_image(
|
| 1019 |
+
self,
|
| 1020 |
+
image: np.ndarray,
|
| 1021 |
+
output_size: Tuple[int, int],
|
| 1022 |
+
constant_values: Union[float, Iterable[float]] = 0,
|
| 1023 |
+
data_format: Optional[ChannelDimension] = None,
|
| 1024 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 1025 |
+
) -> np.ndarray:
|
| 1026 |
+
"""
|
| 1027 |
+
Pad an image with zeros to the given size.
|
| 1028 |
+
"""
|
| 1029 |
+
input_height, input_width = get_image_size(image, channel_dim=input_data_format)
|
| 1030 |
+
output_height, output_width = output_size
|
| 1031 |
+
|
| 1032 |
+
pad_bottom = output_height - input_height
|
| 1033 |
+
pad_right = output_width - input_width
|
| 1034 |
+
padding = ((0, pad_bottom), (0, pad_right))
|
| 1035 |
+
padded_image = pad(
|
| 1036 |
+
image,
|
| 1037 |
+
padding,
|
| 1038 |
+
mode=PaddingMode.CONSTANT,
|
| 1039 |
+
constant_values=constant_values,
|
| 1040 |
+
data_format=data_format,
|
| 1041 |
+
input_data_format=input_data_format,
|
| 1042 |
+
)
|
| 1043 |
+
return padded_image
|
| 1044 |
+
|
| 1045 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.pad
|
| 1046 |
+
def pad(
|
| 1047 |
+
self,
|
| 1048 |
+
images: List[np.ndarray],
|
| 1049 |
+
constant_values: Union[float, Iterable[float]] = 0,
|
| 1050 |
+
return_pixel_mask: bool = True,
|
| 1051 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 1052 |
+
data_format: Optional[ChannelDimension] = None,
|
| 1053 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 1054 |
+
) -> BatchFeature:
|
| 1055 |
+
"""
|
| 1056 |
+
Pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width
|
| 1057 |
+
in the batch and optionally returns their corresponding pixel mask.
|
| 1058 |
+
|
| 1059 |
+
Args:
|
| 1060 |
+
image (`np.ndarray`):
|
| 1061 |
+
Image to pad.
|
| 1062 |
+
constant_values (`float` or `Iterable[float]`, *optional*):
|
| 1063 |
+
The value to use for the padding if `mode` is `"constant"`.
|
| 1064 |
+
return_pixel_mask (`bool`, *optional*, defaults to `True`):
|
| 1065 |
+
Whether to return a pixel mask.
|
| 1066 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 1067 |
+
The type of tensors to return. Can be one of:
|
| 1068 |
+
- Unset: Return a list of `np.ndarray`.
|
| 1069 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 1070 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 1071 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 1072 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 1073 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 1074 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 1075 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 1076 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 1077 |
+
"""
|
| 1078 |
+
pad_size = get_max_height_width(images, input_data_format=input_data_format)
|
| 1079 |
+
|
| 1080 |
+
padded_images = [
|
| 1081 |
+
self._pad_image(
|
| 1082 |
+
image,
|
| 1083 |
+
pad_size,
|
| 1084 |
+
constant_values=constant_values,
|
| 1085 |
+
data_format=data_format,
|
| 1086 |
+
input_data_format=input_data_format,
|
| 1087 |
+
)
|
| 1088 |
+
for image in images
|
| 1089 |
+
]
|
| 1090 |
+
data = {"pixel_values": padded_images}
|
| 1091 |
+
|
| 1092 |
+
if return_pixel_mask:
|
| 1093 |
+
masks = [
|
| 1094 |
+
make_pixel_mask(image=image, output_size=pad_size, input_data_format=input_data_format)
|
| 1095 |
+
for image in images
|
| 1096 |
+
]
|
| 1097 |
+
data["pixel_mask"] = masks
|
| 1098 |
+
|
| 1099 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 1100 |
+
|
| 1101 |
+
# Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.preprocess
|
| 1102 |
+
def preprocess(
|
| 1103 |
+
self,
|
| 1104 |
+
images: ImageInput,
|
| 1105 |
+
annotations: Optional[Union[AnnotationType, List[AnnotationType]]] = None,
|
| 1106 |
+
return_segmentation_masks: bool = None,
|
| 1107 |
+
masks_path: Optional[Union[str, pathlib.Path]] = None,
|
| 1108 |
+
do_resize: Optional[bool] = None,
|
| 1109 |
+
size: Optional[Dict[str, int]] = None,
|
| 1110 |
+
resample=None, # PILImageResampling
|
| 1111 |
+
do_rescale: Optional[bool] = None,
|
| 1112 |
+
rescale_factor: Optional[Union[int, float]] = None,
|
| 1113 |
+
do_normalize: Optional[bool] = None,
|
| 1114 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 1115 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 1116 |
+
do_pad: Optional[bool] = None,
|
| 1117 |
+
format: Optional[Union[str, AnnotionFormat]] = None,
|
| 1118 |
+
return_tensors: Optional[Union[TensorType, str]] = None,
|
| 1119 |
+
data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
|
| 1120 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 1121 |
+
**kwargs,
|
| 1122 |
+
) -> BatchFeature:
|
| 1123 |
+
"""
|
| 1124 |
+
Preprocess an image or a batch of images so that it can be used by the model.
|
| 1125 |
+
|
| 1126 |
+
Args:
|
| 1127 |
+
images (`ImageInput`):
|
| 1128 |
+
Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging
|
| 1129 |
+
from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 1130 |
+
annotations (`AnnotationType` or `List[AnnotationType]`, *optional*):
|
| 1131 |
+
List of annotations associated with the image or batch of images. If annotation is for object
|
| 1132 |
+
detection, the annotations should be a dictionary with the following keys:
|
| 1133 |
+
- "image_id" (`int`): The image id.
|
| 1134 |
+
- "annotations" (`List[Dict]`): List of annotations for an image. Each annotation should be a
|
| 1135 |
+
dictionary. An image can have no annotations, in which case the list should be empty.
|
| 1136 |
+
If annotation is for segmentation, the annotations should be a dictionary with the following keys:
|
| 1137 |
+
- "image_id" (`int`): The image id.
|
| 1138 |
+
- "segments_info" (`List[Dict]`): List of segments for an image. Each segment should be a dictionary.
|
| 1139 |
+
An image can have no segments, in which case the list should be empty.
|
| 1140 |
+
- "file_name" (`str`): The file name of the image.
|
| 1141 |
+
return_segmentation_masks (`bool`, *optional*, defaults to self.return_segmentation_masks):
|
| 1142 |
+
Whether to return segmentation masks.
|
| 1143 |
+
masks_path (`str` or `pathlib.Path`, *optional*):
|
| 1144 |
+
Path to the directory containing the segmentation masks.
|
| 1145 |
+
do_resize (`bool`, *optional*, defaults to self.do_resize):
|
| 1146 |
+
Whether to resize the image.
|
| 1147 |
+
size (`Dict[str, int]`, *optional*, defaults to self.size):
|
| 1148 |
+
Size of the image after resizing.
|
| 1149 |
+
resample (`PILImageResampling`, *optional*, defaults to self.resample):
|
| 1150 |
+
Resampling filter to use when resizing the image.
|
| 1151 |
+
do_rescale (`bool`, *optional*, defaults to self.do_rescale):
|
| 1152 |
+
Whether to rescale the image.
|
| 1153 |
+
rescale_factor (`float`, *optional*, defaults to self.rescale_factor):
|
| 1154 |
+
Rescale factor to use when rescaling the image.
|
| 1155 |
+
do_normalize (`bool`, *optional*, defaults to self.do_normalize):
|
| 1156 |
+
Whether to normalize the image.
|
| 1157 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to self.image_mean):
|
| 1158 |
+
Mean to use when normalizing the image.
|
| 1159 |
+
image_std (`float` or `List[float]`, *optional*, defaults to self.image_std):
|
| 1160 |
+
Standard deviation to use when normalizing the image.
|
| 1161 |
+
do_pad (`bool`, *optional*, defaults to self.do_pad):
|
| 1162 |
+
Whether to pad the image.
|
| 1163 |
+
format (`str` or `AnnotionFormat`, *optional*, defaults to self.format):
|
| 1164 |
+
Format of the annotations.
|
| 1165 |
+
return_tensors (`str` or `TensorType`, *optional*, defaults to self.return_tensors):
|
| 1166 |
+
Type of tensors to return. If `None`, will return the list of images.
|
| 1167 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 1168 |
+
The channel dimension format for the output image. Can be one of:
|
| 1169 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 1170 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 1171 |
+
- Unset: Use the channel dimension format of the input image.
|
| 1172 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 1173 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 1174 |
+
from the input image. Can be one of:
|
| 1175 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 1176 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 1177 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 1178 |
+
"""
|
| 1179 |
+
if "pad_and_return_pixel_mask" in kwargs:
|
| 1180 |
+
logger.warning_once(
|
| 1181 |
+
"The `pad_and_return_pixel_mask` argument is deprecated and will be removed in a future version, "
|
| 1182 |
+
"use `do_pad` instead."
|
| 1183 |
+
)
|
| 1184 |
+
do_pad = kwargs.pop("pad_and_return_pixel_mask")
|
| 1185 |
+
|
| 1186 |
+
max_size = None
|
| 1187 |
+
if "max_size" in kwargs:
|
| 1188 |
+
logger.warning_once(
|
| 1189 |
+
"The `max_size` argument is deprecated and will be removed in a future version, use"
|
| 1190 |
+
" `size['longest_edge']` instead."
|
| 1191 |
+
)
|
| 1192 |
+
size = kwargs.pop("max_size")
|
| 1193 |
+
|
| 1194 |
+
do_resize = self.do_resize if do_resize is None else do_resize
|
| 1195 |
+
size = self.size if size is None else size
|
| 1196 |
+
size = get_size_dict(size=size, max_size=max_size, default_to_square=False)
|
| 1197 |
+
resample = self.resample if resample is None else resample
|
| 1198 |
+
do_rescale = self.do_rescale if do_rescale is None else do_rescale
|
| 1199 |
+
rescale_factor = self.rescale_factor if rescale_factor is None else rescale_factor
|
| 1200 |
+
do_normalize = self.do_normalize if do_normalize is None else do_normalize
|
| 1201 |
+
image_mean = self.image_mean if image_mean is None else image_mean
|
| 1202 |
+
image_std = self.image_std if image_std is None else image_std
|
| 1203 |
+
do_pad = self.do_pad if do_pad is None else do_pad
|
| 1204 |
+
format = self.format if format is None else format
|
| 1205 |
+
|
| 1206 |
+
if do_resize is not None and size is None:
|
| 1207 |
+
raise ValueError("Size and max_size must be specified if do_resize is True.")
|
| 1208 |
+
|
| 1209 |
+
if do_rescale is not None and rescale_factor is None:
|
| 1210 |
+
raise ValueError("Rescale factor must be specified if do_rescale is True.")
|
| 1211 |
+
|
| 1212 |
+
if do_normalize is not None and (image_mean is None or image_std is None):
|
| 1213 |
+
raise ValueError("Image mean and std must be specified if do_normalize is True.")
|
| 1214 |
+
|
| 1215 |
+
images = make_list_of_images(images)
|
| 1216 |
+
if annotations is not None and isinstance(annotations, dict):
|
| 1217 |
+
annotations = [annotations]
|
| 1218 |
+
|
| 1219 |
+
if annotations is not None and len(images) != len(annotations):
|
| 1220 |
+
raise ValueError(
|
| 1221 |
+
f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
|
| 1222 |
+
)
|
| 1223 |
+
|
| 1224 |
+
if not valid_images(images):
|
| 1225 |
+
raise ValueError(
|
| 1226 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 1227 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 1228 |
+
)
|
| 1229 |
+
|
| 1230 |
+
format = AnnotionFormat(format)
|
| 1231 |
+
if annotations is not None:
|
| 1232 |
+
if format == AnnotionFormat.COCO_DETECTION and not valid_coco_detection_annotations(annotations):
|
| 1233 |
+
raise ValueError(
|
| 1234 |
+
"Invalid COCO detection annotations. Annotations must a dict (single image) of list of dicts"
|
| 1235 |
+
"(batch of images) with the following keys: `image_id` and `annotations`, with the latter "
|
| 1236 |
+
"being a list of annotations in the COCO format."
|
| 1237 |
+
)
|
| 1238 |
+
elif format == AnnotionFormat.COCO_PANOPTIC and not valid_coco_panoptic_annotations(annotations):
|
| 1239 |
+
raise ValueError(
|
| 1240 |
+
"Invalid COCO panoptic annotations. Annotations must a dict (single image) of list of dicts "
|
| 1241 |
+
"(batch of images) with the following keys: `image_id`, `file_name` and `segments_info`, with "
|
| 1242 |
+
"the latter being a list of annotations in the COCO format."
|
| 1243 |
+
)
|
| 1244 |
+
elif format not in SUPPORTED_ANNOTATION_FORMATS:
|
| 1245 |
+
raise ValueError(
|
| 1246 |
+
f"Unsupported annotation format: {format} must be one of {SUPPORTED_ANNOTATION_FORMATS}"
|
| 1247 |
+
)
|
| 1248 |
+
|
| 1249 |
+
if (
|
| 1250 |
+
masks_path is not None
|
| 1251 |
+
and format == AnnotionFormat.COCO_PANOPTIC
|
| 1252 |
+
and not isinstance(masks_path, (pathlib.Path, str))
|
| 1253 |
+
):
|
| 1254 |
+
raise ValueError(
|
| 1255 |
+
"The path to the directory containing the mask PNG files should be provided as a"
|
| 1256 |
+
f" `pathlib.Path` or string object, but is {type(masks_path)} instead."
|
| 1257 |
+
)
|
| 1258 |
+
|
| 1259 |
+
# All transformations expect numpy arrays
|
| 1260 |
+
images = [to_numpy_array(image) for image in images]
|
| 1261 |
+
|
| 1262 |
+
if is_scaled_image(images[0]) and do_rescale:
|
| 1263 |
+
logger.warning_once(
|
| 1264 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 1265 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 1266 |
+
)
|
| 1267 |
+
|
| 1268 |
+
if input_data_format is None:
|
| 1269 |
+
# We assume that all images have the same channel dimension format.
|
| 1270 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 1271 |
+
|
| 1272 |
+
# prepare (COCO annotations as a list of Dict -> DETR target as a single Dict per image)
|
| 1273 |
+
if annotations is not None:
|
| 1274 |
+
prepared_images = []
|
| 1275 |
+
prepared_annotations = []
|
| 1276 |
+
for image, target in zip(images, annotations):
|
| 1277 |
+
target = self.prepare_annotation(
|
| 1278 |
+
image,
|
| 1279 |
+
target,
|
| 1280 |
+
format,
|
| 1281 |
+
return_segmentation_masks=return_segmentation_masks,
|
| 1282 |
+
masks_path=masks_path,
|
| 1283 |
+
input_data_format=input_data_format,
|
| 1284 |
+
)
|
| 1285 |
+
prepared_images.append(image)
|
| 1286 |
+
prepared_annotations.append(target)
|
| 1287 |
+
images = prepared_images
|
| 1288 |
+
annotations = prepared_annotations
|
| 1289 |
+
del prepared_images, prepared_annotations
|
| 1290 |
+
|
| 1291 |
+
# transformations
|
| 1292 |
+
if do_resize:
|
| 1293 |
+
if annotations is not None:
|
| 1294 |
+
resized_images, resized_annotations = [], []
|
| 1295 |
+
for image, target in zip(images, annotations):
|
| 1296 |
+
orig_size = get_image_size(image, input_data_format)
|
| 1297 |
+
resized_image = self.resize(
|
| 1298 |
+
image, size=size, max_size=max_size, resample=resample, input_data_format=input_data_format
|
| 1299 |
+
)
|
| 1300 |
+
resized_annotation = self.resize_annotation(
|
| 1301 |
+
target, orig_size, get_image_size(resized_image, input_data_format)
|
| 1302 |
+
)
|
| 1303 |
+
resized_images.append(resized_image)
|
| 1304 |
+
resized_annotations.append(resized_annotation)
|
| 1305 |
+
images = resized_images
|
| 1306 |
+
annotations = resized_annotations
|
| 1307 |
+
del resized_images, resized_annotations
|
| 1308 |
+
else:
|
| 1309 |
+
images = [
|
| 1310 |
+
self.resize(image, size=size, resample=resample, input_data_format=input_data_format)
|
| 1311 |
+
for image in images
|
| 1312 |
+
]
|
| 1313 |
+
|
| 1314 |
+
if do_rescale:
|
| 1315 |
+
images = [self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]
|
| 1316 |
+
|
| 1317 |
+
if do_normalize:
|
| 1318 |
+
images = [
|
| 1319 |
+
self.normalize(image, image_mean, image_std, input_data_format=input_data_format) for image in images
|
| 1320 |
+
]
|
| 1321 |
+
if annotations is not None:
|
| 1322 |
+
annotations = [
|
| 1323 |
+
self.normalize_annotation(annotation, get_image_size(image, input_data_format))
|
| 1324 |
+
for annotation, image in zip(annotations, images)
|
| 1325 |
+
]
|
| 1326 |
+
|
| 1327 |
+
if do_pad:
|
| 1328 |
+
# Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
|
| 1329 |
+
data = self.pad(
|
| 1330 |
+
images, return_pixel_mask=True, data_format=data_format, input_data_format=input_data_format
|
| 1331 |
+
)
|
| 1332 |
+
else:
|
| 1333 |
+
images = [
|
| 1334 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 1335 |
+
for image in images
|
| 1336 |
+
]
|
| 1337 |
+
data = {"pixel_values": images}
|
| 1338 |
+
|
| 1339 |
+
encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
|
| 1340 |
+
if annotations is not None:
|
| 1341 |
+
encoded_inputs["labels"] = [
|
| 1342 |
+
BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
|
| 1343 |
+
]
|
| 1344 |
+
|
| 1345 |
+
return encoded_inputs
|
| 1346 |
+
|
| 1347 |
+
# POSTPROCESSING METHODS - TODO: add support for other frameworks
|
| 1348 |
+
def post_process(self, outputs, target_sizes):
|
| 1349 |
+
"""
|
| 1350 |
+
Converts the raw output of [`DeformableDetrForObjectDetection`] into final bounding boxes in (top_left_x,
|
| 1351 |
+
top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
|
| 1352 |
+
|
| 1353 |
+
Args:
|
| 1354 |
+
outputs ([`DeformableDetrObjectDetectionOutput`]):
|
| 1355 |
+
Raw outputs of the model.
|
| 1356 |
+
target_sizes (`torch.Tensor` of shape `(batch_size, 2)`):
|
| 1357 |
+
Tensor containing the size (height, width) of each image of the batch. For evaluation, this must be the
|
| 1358 |
+
original image size (before any data augmentation). For visualization, this should be the image size
|
| 1359 |
+
after data augment, but before padding.
|
| 1360 |
+
Returns:
|
| 1361 |
+
`List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
|
| 1362 |
+
in the batch as predicted by the model.
|
| 1363 |
+
"""
|
| 1364 |
+
logger.warning_once(
|
| 1365 |
+
"`post_process` is deprecated and will be removed in v5 of Transformers, please use"
|
| 1366 |
+
" `post_process_object_detection` instead, with `threshold=0.` for equivalent results.",
|
| 1367 |
+
)
|
| 1368 |
+
|
| 1369 |
+
out_logits, out_bbox = outputs.logits, outputs.pred_boxes
|
| 1370 |
+
|
| 1371 |
+
if len(out_logits) != len(target_sizes):
|
| 1372 |
+
raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the logits")
|
| 1373 |
+
if target_sizes.shape[1] != 2:
|
| 1374 |
+
raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch")
|
| 1375 |
+
|
| 1376 |
+
prob = out_logits.sigmoid()
|
| 1377 |
+
topk_values, topk_indexes = torch.topk(prob.view(out_logits.shape[0], -1), 100, dim=1)
|
| 1378 |
+
scores = topk_values
|
| 1379 |
+
topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
|
| 1380 |
+
labels = topk_indexes % out_logits.shape[2]
|
| 1381 |
+
boxes = center_to_corners_format(out_bbox)
|
| 1382 |
+
boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
|
| 1383 |
+
|
| 1384 |
+
# and from relative [0, 1] to absolute [0, height] coordinates
|
| 1385 |
+
img_h, img_w = target_sizes.unbind(1)
|
| 1386 |
+
scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)
|
| 1387 |
+
boxes = boxes * scale_fct[:, None, :]
|
| 1388 |
+
|
| 1389 |
+
results = [{"scores": s, "labels": l, "boxes": b} for s, l, b in zip(scores, labels, boxes)]
|
| 1390 |
+
|
| 1391 |
+
return results
|
| 1392 |
+
|
| 1393 |
+
def post_process_object_detection(
|
| 1394 |
+
self, outputs, threshold: float = 0.5, target_sizes: Union[TensorType, List[Tuple]] = None, top_k: int = 100
|
| 1395 |
+
):
|
| 1396 |
+
"""
|
| 1397 |
+
Converts the raw output of [`DeformableDetrForObjectDetection`] into final bounding boxes in (top_left_x,
|
| 1398 |
+
top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
|
| 1399 |
+
|
| 1400 |
+
Args:
|
| 1401 |
+
outputs ([`DetrObjectDetectionOutput`]):
|
| 1402 |
+
Raw outputs of the model.
|
| 1403 |
+
threshold (`float`, *optional*):
|
| 1404 |
+
Score threshold to keep object detection predictions.
|
| 1405 |
+
target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*):
|
| 1406 |
+
Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size
|
| 1407 |
+
(height, width) of each image in the batch. If left to None, predictions will not be resized.
|
| 1408 |
+
top_k (`int`, *optional*, defaults to 100):
|
| 1409 |
+
Keep only top k bounding boxes before filtering by thresholding.
|
| 1410 |
+
|
| 1411 |
+
Returns:
|
| 1412 |
+
`List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
|
| 1413 |
+
in the batch as predicted by the model.
|
| 1414 |
+
"""
|
| 1415 |
+
out_logits, out_bbox = outputs.logits, outputs.pred_boxes
|
| 1416 |
+
|
| 1417 |
+
if target_sizes is not None:
|
| 1418 |
+
if len(out_logits) != len(target_sizes):
|
| 1419 |
+
raise ValueError(
|
| 1420 |
+
"Make sure that you pass in as many target sizes as the batch dimension of the logits"
|
| 1421 |
+
)
|
| 1422 |
+
|
| 1423 |
+
prob = out_logits.sigmoid()
|
| 1424 |
+
prob = prob.view(out_logits.shape[0], -1)
|
| 1425 |
+
k_value = min(top_k, prob.size(1))
|
| 1426 |
+
topk_values, topk_indexes = torch.topk(prob, k_value, dim=1)
|
| 1427 |
+
scores = topk_values
|
| 1428 |
+
topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
|
| 1429 |
+
labels = topk_indexes % out_logits.shape[2]
|
| 1430 |
+
boxes = center_to_corners_format(out_bbox)
|
| 1431 |
+
boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
|
| 1432 |
+
|
| 1433 |
+
# and from relative [0, 1] to absolute [0, height] coordinates
|
| 1434 |
+
if isinstance(target_sizes, List):
|
| 1435 |
+
img_h = torch.Tensor([i[0] for i in target_sizes])
|
| 1436 |
+
img_w = torch.Tensor([i[1] for i in target_sizes])
|
| 1437 |
+
else:
|
| 1438 |
+
img_h, img_w = target_sizes.unbind(1)
|
| 1439 |
+
scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
|
| 1440 |
+
boxes = boxes * scale_fct[:, None, :]
|
| 1441 |
+
|
| 1442 |
+
results = []
|
| 1443 |
+
for s, l, b in zip(scores, labels, boxes):
|
| 1444 |
+
score = s[s > threshold]
|
| 1445 |
+
label = l[s > threshold]
|
| 1446 |
+
box = b[s > threshold]
|
| 1447 |
+
results.append({"scores": score, "labels": label, "boxes": box})
|
| 1448 |
+
|
| 1449 |
+
return results
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/load_custom.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
""" Loading of Deformable DETR's CUDA kernels"""
|
| 16 |
+
import os
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load_cuda_kernels():
|
| 21 |
+
from torch.utils.cpp_extension import load
|
| 22 |
+
|
| 23 |
+
root = Path(__file__).resolve().parent.parent.parent / "kernels" / "deformable_detr"
|
| 24 |
+
src_files = [
|
| 25 |
+
root / filename
|
| 26 |
+
for filename in [
|
| 27 |
+
"vision.cpp",
|
| 28 |
+
os.path.join("cpu", "ms_deform_attn_cpu.cpp"),
|
| 29 |
+
os.path.join("cuda", "ms_deform_attn_cuda.cu"),
|
| 30 |
+
]
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
load(
|
| 34 |
+
"MultiScaleDeformableAttention",
|
| 35 |
+
src_files,
|
| 36 |
+
with_cuda=True,
|
| 37 |
+
extra_include_paths=[str(root)],
|
| 38 |
+
extra_cflags=["-DWITH_CUDA=1"],
|
| 39 |
+
extra_cuda_cflags=[
|
| 40 |
+
"-DCUDA_HAS_FP16=1",
|
| 41 |
+
"-D__CUDA_NO_HALF_OPERATORS__",
|
| 42 |
+
"-D__CUDA_NO_HALF_CONVERSIONS__",
|
| 43 |
+
"-D__CUDA_NO_HALF2_OPERATORS__",
|
| 44 |
+
],
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
import MultiScaleDeformableAttention as MSDA
|
| 48 |
+
|
| 49 |
+
return MSDA
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/deformable_detr/modeling_deformable_detr.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/flava/__pycache__/configuration_flava.cpython-310.pyc
ADDED
|
Binary file (25.2 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/__init__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. 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_m2m_100": ["M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP", "M2M100Config", "M2M100OnnxConfig"],
|
| 21 |
+
"tokenization_m2m_100": ["M2M100Tokenizer"],
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
if not is_torch_available():
|
| 27 |
+
raise OptionalDependencyNotAvailable()
|
| 28 |
+
except OptionalDependencyNotAvailable:
|
| 29 |
+
pass
|
| 30 |
+
else:
|
| 31 |
+
_import_structure["modeling_m2m_100"] = [
|
| 32 |
+
"M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 33 |
+
"M2M100ForConditionalGeneration",
|
| 34 |
+
"M2M100Model",
|
| 35 |
+
"M2M100PreTrainedModel",
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if TYPE_CHECKING:
|
| 40 |
+
from .configuration_m2m_100 import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, M2M100Config, M2M100OnnxConfig
|
| 41 |
+
from .tokenization_m2m_100 import M2M100Tokenizer
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
if not is_torch_available():
|
| 45 |
+
raise OptionalDependencyNotAvailable()
|
| 46 |
+
except OptionalDependencyNotAvailable:
|
| 47 |
+
pass
|
| 48 |
+
else:
|
| 49 |
+
from .modeling_m2m_100 import (
|
| 50 |
+
M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 51 |
+
M2M100ForConditionalGeneration,
|
| 52 |
+
M2M100Model,
|
| 53 |
+
M2M100PreTrainedModel,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
else:
|
| 58 |
+
import sys
|
| 59 |
+
|
| 60 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.05 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/__pycache__/configuration_m2m_100.cpython-310.pyc
ADDED
|
Binary file (9.53 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/__pycache__/convert_m2m100_original_checkpoint_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (2.38 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/__pycache__/modeling_m2m_100.cpython-310.pyc
ADDED
|
Binary file (44.3 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/__pycache__/tokenization_m2m_100.cpython-310.pyc
ADDED
|
Binary file (16.1 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/configuration_m2m_100.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 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 |
+
""" M2M100 model configuration"""
|
| 16 |
+
from collections import OrderedDict
|
| 17 |
+
from typing import Any, Mapping, Optional
|
| 18 |
+
|
| 19 |
+
from ... import PreTrainedTokenizer
|
| 20 |
+
from ...configuration_utils import PretrainedConfig
|
| 21 |
+
from ...onnx import OnnxConfig, OnnxSeq2SeqConfigWithPast
|
| 22 |
+
from ...onnx.utils import compute_effective_axis_dimension
|
| 23 |
+
from ...utils import TensorType, is_torch_available, logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 29 |
+
"facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/config.json",
|
| 30 |
+
# See all M2M100 models at https://huggingface.co/models?filter=m2m_100
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class M2M100Config(PretrainedConfig):
|
| 35 |
+
r"""
|
| 36 |
+
This is the configuration class to store the configuration of a [`M2M100Model`]. It is used to instantiate an
|
| 37 |
+
M2M100 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 38 |
+
with the defaults will yield a similar configuration to that of the M2M100
|
| 39 |
+
[facebook/m2m100_418M](https://huggingface.co/facebook/m2m100_418M) architecture.
|
| 40 |
+
|
| 41 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 42 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
vocab_size (`int`, *optional*, defaults to 50265):
|
| 47 |
+
Vocabulary size of the M2M100 model. Defines the number of different tokens that can be represented by the
|
| 48 |
+
`inputs_ids` passed when calling [`M2M100Model`] or
|
| 49 |
+
d_model (`int`, *optional*, defaults to 1024):
|
| 50 |
+
Dimensionality of the layers and the pooler layer.
|
| 51 |
+
encoder_layers (`int`, *optional*, defaults to 12):
|
| 52 |
+
Number of encoder layers.
|
| 53 |
+
decoder_layers (`int`, *optional*, defaults to 12):
|
| 54 |
+
Number of decoder layers.
|
| 55 |
+
encoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 56 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 57 |
+
decoder_attention_heads (`int`, *optional*, defaults to 16):
|
| 58 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 59 |
+
decoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 60 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
|
| 61 |
+
encoder_ffn_dim (`int`, *optional*, defaults to 4096):
|
| 62 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
|
| 63 |
+
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 64 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 65 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 66 |
+
dropout (`float`, *optional*, defaults to 0.1):
|
| 67 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 68 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 69 |
+
The dropout ratio for the attention probabilities.
|
| 70 |
+
activation_dropout (`float`, *optional*, defaults to 0.0):
|
| 71 |
+
The dropout ratio for activations inside the fully connected layer.
|
| 72 |
+
classifier_dropout (`float`, *optional*, defaults to 0.0):
|
| 73 |
+
The dropout ratio for classifier.
|
| 74 |
+
max_position_embeddings (`int`, *optional*, defaults to 1024):
|
| 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 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 86 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
| 87 |
+
|
| 88 |
+
Example:
|
| 89 |
+
|
| 90 |
+
```python
|
| 91 |
+
>>> from transformers import M2M100Config, M2M100Model
|
| 92 |
+
|
| 93 |
+
>>> # Initializing a M2M100 facebook/m2m100_418M style configuration
|
| 94 |
+
>>> configuration = M2M100Config()
|
| 95 |
+
|
| 96 |
+
>>> # Initializing a model (with random weights) from the facebook/m2m100_418M style configuration
|
| 97 |
+
>>> model = M2M100Model(configuration)
|
| 98 |
+
|
| 99 |
+
>>> # Accessing the model configuration
|
| 100 |
+
>>> configuration = model.config
|
| 101 |
+
```"""
|
| 102 |
+
model_type = "m2m_100"
|
| 103 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 104 |
+
attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
|
| 105 |
+
|
| 106 |
+
def __init__(
|
| 107 |
+
self,
|
| 108 |
+
vocab_size=128112,
|
| 109 |
+
max_position_embeddings=1024,
|
| 110 |
+
encoder_layers=12,
|
| 111 |
+
encoder_ffn_dim=4096,
|
| 112 |
+
encoder_attention_heads=16,
|
| 113 |
+
decoder_layers=12,
|
| 114 |
+
decoder_ffn_dim=4096,
|
| 115 |
+
decoder_attention_heads=16,
|
| 116 |
+
encoder_layerdrop=0.05,
|
| 117 |
+
decoder_layerdrop=0.05,
|
| 118 |
+
use_cache=True,
|
| 119 |
+
is_encoder_decoder=True,
|
| 120 |
+
activation_function="relu",
|
| 121 |
+
d_model=1024,
|
| 122 |
+
dropout=0.1,
|
| 123 |
+
attention_dropout=0.1,
|
| 124 |
+
activation_dropout=0.0,
|
| 125 |
+
init_std=0.02,
|
| 126 |
+
decoder_start_token_id=2,
|
| 127 |
+
scale_embedding=True,
|
| 128 |
+
pad_token_id=1,
|
| 129 |
+
bos_token_id=0,
|
| 130 |
+
eos_token_id=2,
|
| 131 |
+
**kwargs,
|
| 132 |
+
):
|
| 133 |
+
self.vocab_size = vocab_size
|
| 134 |
+
self.max_position_embeddings = max_position_embeddings
|
| 135 |
+
self.d_model = d_model
|
| 136 |
+
self.encoder_ffn_dim = encoder_ffn_dim
|
| 137 |
+
self.encoder_layers = encoder_layers
|
| 138 |
+
self.encoder_attention_heads = encoder_attention_heads
|
| 139 |
+
self.decoder_ffn_dim = decoder_ffn_dim
|
| 140 |
+
self.decoder_layers = decoder_layers
|
| 141 |
+
self.decoder_attention_heads = decoder_attention_heads
|
| 142 |
+
self.dropout = dropout
|
| 143 |
+
self.attention_dropout = attention_dropout
|
| 144 |
+
self.activation_dropout = activation_dropout
|
| 145 |
+
self.activation_function = activation_function
|
| 146 |
+
self.init_std = init_std
|
| 147 |
+
self.encoder_layerdrop = encoder_layerdrop
|
| 148 |
+
self.decoder_layerdrop = decoder_layerdrop
|
| 149 |
+
self.use_cache = use_cache
|
| 150 |
+
self.num_hidden_layers = encoder_layers
|
| 151 |
+
self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
|
| 152 |
+
|
| 153 |
+
super().__init__(
|
| 154 |
+
pad_token_id=pad_token_id,
|
| 155 |
+
bos_token_id=bos_token_id,
|
| 156 |
+
eos_token_id=eos_token_id,
|
| 157 |
+
is_encoder_decoder=is_encoder_decoder,
|
| 158 |
+
decoder_start_token_id=decoder_start_token_id,
|
| 159 |
+
**kwargs,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class M2M100OnnxConfig(OnnxSeq2SeqConfigWithPast):
|
| 164 |
+
@property
|
| 165 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 166 |
+
common_inputs = OrderedDict(
|
| 167 |
+
[
|
| 168 |
+
("input_ids", {0: "batch", 1: "encoder_sequence"}),
|
| 169 |
+
("attention_mask", {0: "batch", 1: "encoder_sequence"}),
|
| 170 |
+
]
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
if self.use_past:
|
| 174 |
+
common_inputs["decoder_input_ids"] = {0: "batch"}
|
| 175 |
+
common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
|
| 176 |
+
else:
|
| 177 |
+
common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
|
| 178 |
+
common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
|
| 179 |
+
|
| 180 |
+
if self.use_past:
|
| 181 |
+
self.fill_with_past_key_values_(common_inputs, direction="inputs")
|
| 182 |
+
return common_inputs
|
| 183 |
+
|
| 184 |
+
# Copied from BartOnnxConfig._generate_dummy_inputs_for_sequence_classification_and_question_answering
|
| 185 |
+
# A better name would be _generate_dummy_inputs_for_encoder_and_decoder because sequence classification and question
|
| 186 |
+
# answering are not supported for M2M100, but this name is preserved to be able to check that the copy matches what
|
| 187 |
+
# was done for BART so that it can be updated if need be.
|
| 188 |
+
def _generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 189 |
+
self,
|
| 190 |
+
tokenizer: PreTrainedTokenizer,
|
| 191 |
+
batch_size: int = -1,
|
| 192 |
+
seq_length: int = -1,
|
| 193 |
+
is_pair: bool = False,
|
| 194 |
+
framework: Optional[TensorType] = None,
|
| 195 |
+
) -> Mapping[str, Any]:
|
| 196 |
+
# Copied from OnnxConfig.generate_dummy_inputs
|
| 197 |
+
# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
|
| 198 |
+
# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
|
| 199 |
+
batch_size = compute_effective_axis_dimension(
|
| 200 |
+
batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
|
| 204 |
+
token_to_add = tokenizer.num_special_tokens_to_add(is_pair)
|
| 205 |
+
seq_length = compute_effective_axis_dimension(
|
| 206 |
+
seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# Generate dummy inputs according to compute batch and sequence
|
| 210 |
+
dummy_input = [" ".join([tokenizer.unk_token]) * seq_length] * batch_size
|
| 211 |
+
common_inputs = dict(tokenizer(dummy_input, return_tensors=framework))
|
| 212 |
+
return common_inputs
|
| 213 |
+
|
| 214 |
+
# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig._generate_dummy_inputs_for_default_and_seq2seq_lm
|
| 215 |
+
def _generate_dummy_inputs_for_default_and_seq2seq_lm(
|
| 216 |
+
self,
|
| 217 |
+
tokenizer: PreTrainedTokenizer,
|
| 218 |
+
batch_size: int = -1,
|
| 219 |
+
seq_length: int = -1,
|
| 220 |
+
is_pair: bool = False,
|
| 221 |
+
framework: Optional[TensorType] = None,
|
| 222 |
+
) -> Mapping[str, Any]:
|
| 223 |
+
encoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 224 |
+
tokenizer, batch_size, seq_length, is_pair, framework
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# Generate decoder inputs
|
| 228 |
+
decoder_seq_length = seq_length if not self.use_past else 1
|
| 229 |
+
decoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
|
| 230 |
+
tokenizer, batch_size, decoder_seq_length, is_pair, framework
|
| 231 |
+
)
|
| 232 |
+
decoder_inputs = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
|
| 233 |
+
common_inputs = dict(**encoder_inputs, **decoder_inputs)
|
| 234 |
+
|
| 235 |
+
if self.use_past:
|
| 236 |
+
if not is_torch_available():
|
| 237 |
+
raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
|
| 238 |
+
else:
|
| 239 |
+
import torch
|
| 240 |
+
batch, encoder_seq_length = common_inputs["input_ids"].shape
|
| 241 |
+
decoder_seq_length = common_inputs["decoder_input_ids"].shape[1]
|
| 242 |
+
num_encoder_attention_heads, num_decoder_attention_heads = self.num_attention_heads
|
| 243 |
+
encoder_shape = (
|
| 244 |
+
batch,
|
| 245 |
+
num_encoder_attention_heads,
|
| 246 |
+
encoder_seq_length,
|
| 247 |
+
self._config.hidden_size // num_encoder_attention_heads,
|
| 248 |
+
)
|
| 249 |
+
decoder_past_length = decoder_seq_length + 3
|
| 250 |
+
decoder_shape = (
|
| 251 |
+
batch,
|
| 252 |
+
num_decoder_attention_heads,
|
| 253 |
+
decoder_past_length,
|
| 254 |
+
self._config.hidden_size // num_decoder_attention_heads,
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
common_inputs["decoder_attention_mask"] = torch.cat(
|
| 258 |
+
[common_inputs["decoder_attention_mask"], torch.ones(batch, decoder_past_length)], dim=1
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
common_inputs["past_key_values"] = []
|
| 262 |
+
# If the number of encoder and decoder layers are present in the model configuration, both are considered
|
| 263 |
+
num_encoder_layers, num_decoder_layers = self.num_layers
|
| 264 |
+
min_num_layers = min(num_encoder_layers, num_decoder_layers)
|
| 265 |
+
max_num_layers = max(num_encoder_layers, num_decoder_layers) - min_num_layers
|
| 266 |
+
remaining_side_name = "encoder" if num_encoder_layers > num_decoder_layers else "decoder"
|
| 267 |
+
|
| 268 |
+
for _ in range(min_num_layers):
|
| 269 |
+
common_inputs["past_key_values"].append(
|
| 270 |
+
(
|
| 271 |
+
torch.zeros(decoder_shape),
|
| 272 |
+
torch.zeros(decoder_shape),
|
| 273 |
+
torch.zeros(encoder_shape),
|
| 274 |
+
torch.zeros(encoder_shape),
|
| 275 |
+
)
|
| 276 |
+
)
|
| 277 |
+
# TODO: test this.
|
| 278 |
+
shape = encoder_shape if remaining_side_name == "encoder" else decoder_shape
|
| 279 |
+
for _ in range(min_num_layers, max_num_layers):
|
| 280 |
+
common_inputs["past_key_values"].append((torch.zeros(shape), torch.zeros(shape)))
|
| 281 |
+
return common_inputs
|
| 282 |
+
|
| 283 |
+
generate_dummy_inputs = _generate_dummy_inputs_for_default_and_seq2seq_lm
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/convert_m2m100_original_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. 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 |
+
import argparse
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch import nn
|
| 19 |
+
|
| 20 |
+
from transformers import M2M100Config, M2M100ForConditionalGeneration
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def remove_ignore_keys_(state_dict):
|
| 24 |
+
ignore_keys = [
|
| 25 |
+
"encoder.version",
|
| 26 |
+
"decoder.version",
|
| 27 |
+
"model.encoder.version",
|
| 28 |
+
"model.decoder.version",
|
| 29 |
+
"decoder.output_projection.weight",
|
| 30 |
+
"_float_tensor",
|
| 31 |
+
"encoder.embed_positions._float_tensor",
|
| 32 |
+
"decoder.embed_positions._float_tensor",
|
| 33 |
+
]
|
| 34 |
+
for k in ignore_keys:
|
| 35 |
+
state_dict.pop(k, None)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def make_linear_from_emb(emb):
|
| 39 |
+
vocab_size, emb_size = emb.weight.shape
|
| 40 |
+
lin_layer = nn.Linear(vocab_size, emb_size, bias=False)
|
| 41 |
+
lin_layer.weight.data = emb.weight.data
|
| 42 |
+
return lin_layer
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def convert_fairseq_m2m100_checkpoint_from_disk(checkpoint_path):
|
| 46 |
+
m2m_100 = torch.load(checkpoint_path, map_location="cpu")
|
| 47 |
+
args = m2m_100["args"] or m2m_100["cfg"]["model"]
|
| 48 |
+
state_dict = m2m_100["model"]
|
| 49 |
+
remove_ignore_keys_(state_dict)
|
| 50 |
+
vocab_size = state_dict["encoder.embed_tokens.weight"].shape[0]
|
| 51 |
+
|
| 52 |
+
config = M2M100Config(
|
| 53 |
+
vocab_size=vocab_size,
|
| 54 |
+
max_position_embeddings=1024,
|
| 55 |
+
encoder_layers=args.encoder_layers,
|
| 56 |
+
decoder_layers=args.decoder_layers,
|
| 57 |
+
encoder_attention_heads=args.encoder_attention_heads,
|
| 58 |
+
decoder_attention_heads=args.decoder_attention_heads,
|
| 59 |
+
encoder_ffn_dim=args.encoder_ffn_embed_dim,
|
| 60 |
+
decoder_ffn_dim=args.decoder_ffn_embed_dim,
|
| 61 |
+
d_model=args.encoder_embed_dim,
|
| 62 |
+
encoder_layerdrop=args.encoder_layerdrop,
|
| 63 |
+
decoder_layerdrop=args.decoder_layerdrop,
|
| 64 |
+
dropout=args.dropout,
|
| 65 |
+
attention_dropout=args.attention_dropout,
|
| 66 |
+
activation_dropout=args.activation_dropout,
|
| 67 |
+
activation_function="relu",
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
state_dict["shared.weight"] = state_dict["decoder.embed_tokens.weight"]
|
| 71 |
+
model = M2M100ForConditionalGeneration(config)
|
| 72 |
+
model.model.load_state_dict(state_dict, strict=False)
|
| 73 |
+
model.lm_head = make_linear_from_emb(model.model.shared)
|
| 74 |
+
|
| 75 |
+
return model
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
parser = argparse.ArgumentParser()
|
| 80 |
+
# Required parameters
|
| 81 |
+
parser.add_argument("fairseq_path", type=str, help="path to a model.pt on local filesystem.")
|
| 82 |
+
parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
|
| 83 |
+
args = parser.parse_args()
|
| 84 |
+
model = convert_fairseq_m2m100_checkpoint_from_disk(args.fairseq_pathß)
|
| 85 |
+
model.save_pretrained(args.pytorch_dump_folder_path)
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/modeling_m2m_100.py
ADDED
|
@@ -0,0 +1,1389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" PyTorch M2M100 model."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
from typing import List, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import CrossEntropyLoss
|
| 24 |
+
|
| 25 |
+
from ...activations import ACT2FN
|
| 26 |
+
from ...integrations.deepspeed import is_deepspeed_zero3_enabled
|
| 27 |
+
from ...modeling_outputs import (
|
| 28 |
+
BaseModelOutput,
|
| 29 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 30 |
+
Seq2SeqLMOutput,
|
| 31 |
+
Seq2SeqModelOutput,
|
| 32 |
+
)
|
| 33 |
+
from ...modeling_utils import PreTrainedModel
|
| 34 |
+
from ...utils import (
|
| 35 |
+
add_code_sample_docstrings,
|
| 36 |
+
add_end_docstrings,
|
| 37 |
+
add_start_docstrings,
|
| 38 |
+
add_start_docstrings_to_model_forward,
|
| 39 |
+
logging,
|
| 40 |
+
replace_return_docstrings,
|
| 41 |
+
)
|
| 42 |
+
from .configuration_m2m_100 import M2M100Config
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
logger = logging.get_logger(__name__)
|
| 46 |
+
|
| 47 |
+
_CONFIG_FOR_DOC = "M2M100Config"
|
| 48 |
+
_CHECKPOINT_FOR_DOC = "facebook/m2m100_418M"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 52 |
+
"facebook/m2m100_418M",
|
| 53 |
+
# See all M2M100 models at https://huggingface.co/models?filter=m2m_100
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# Copied from transformers.models.bart.modeling_bart.shift_tokens_right
|
| 58 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 59 |
+
"""
|
| 60 |
+
Shift input ids one token to the right.
|
| 61 |
+
"""
|
| 62 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 63 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 64 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 65 |
+
|
| 66 |
+
if pad_token_id is None:
|
| 67 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 68 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 69 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 70 |
+
|
| 71 |
+
return shifted_input_ids
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
| 75 |
+
def _make_causal_mask(
|
| 76 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
| 77 |
+
):
|
| 78 |
+
"""
|
| 79 |
+
Make causal mask used for bi-directional self-attention.
|
| 80 |
+
"""
|
| 81 |
+
bsz, tgt_len = input_ids_shape
|
| 82 |
+
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
| 83 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
| 84 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
| 85 |
+
mask = mask.to(dtype)
|
| 86 |
+
|
| 87 |
+
if past_key_values_length > 0:
|
| 88 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
| 89 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
| 93 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
| 94 |
+
"""
|
| 95 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
| 96 |
+
"""
|
| 97 |
+
bsz, src_len = mask.size()
|
| 98 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
| 99 |
+
|
| 100 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
| 101 |
+
|
| 102 |
+
inverted_mask = 1.0 - expanded_mask
|
| 103 |
+
|
| 104 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
|
| 108 |
+
"""
|
| 109 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
|
| 110 |
+
are ignored. This is modified from fairseq's `utils.make_positions`.
|
| 111 |
+
"""
|
| 112 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
| 113 |
+
mask = input_ids.ne(padding_idx).int()
|
| 114 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
| 115 |
+
return incremental_indices.long() + padding_idx
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class M2M100SinusoidalPositionalEmbedding(nn.Module):
|
| 119 |
+
"""This module produces sinusoidal positional embeddings of any length."""
|
| 120 |
+
|
| 121 |
+
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 122 |
+
super().__init__()
|
| 123 |
+
self.offset = 2
|
| 124 |
+
self.embedding_dim = embedding_dim
|
| 125 |
+
self.padding_idx = padding_idx
|
| 126 |
+
self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
|
| 127 |
+
|
| 128 |
+
def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 129 |
+
emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
|
| 130 |
+
if hasattr(self, "weights"):
|
| 131 |
+
# in forward put the weights on the correct dtype and device of the param
|
| 132 |
+
emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
|
| 133 |
+
|
| 134 |
+
self.register_buffer("weights", emb_weights, persistent=False)
|
| 135 |
+
|
| 136 |
+
@staticmethod
|
| 137 |
+
def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
|
| 138 |
+
"""
|
| 139 |
+
Build sinusoidal embeddings.
|
| 140 |
+
|
| 141 |
+
This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
|
| 142 |
+
"Attention Is All You Need".
|
| 143 |
+
"""
|
| 144 |
+
half_dim = embedding_dim // 2
|
| 145 |
+
emb = math.log(10000) / (half_dim - 1)
|
| 146 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb)
|
| 147 |
+
emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0)
|
| 148 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
|
| 149 |
+
if embedding_dim % 2 == 1:
|
| 150 |
+
# zero pad
|
| 151 |
+
emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
|
| 152 |
+
if padding_idx is not None:
|
| 153 |
+
emb[padding_idx, :] = 0
|
| 154 |
+
|
| 155 |
+
return emb.to(torch.get_default_dtype())
|
| 156 |
+
|
| 157 |
+
@torch.no_grad()
|
| 158 |
+
def forward(
|
| 159 |
+
self, input_ids: torch.Tensor = None, inputs_embeds: torch.Tensor = None, past_key_values_length: int = 0
|
| 160 |
+
):
|
| 161 |
+
if input_ids is not None:
|
| 162 |
+
bsz, seq_len = input_ids.size()
|
| 163 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
| 164 |
+
position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length).to(
|
| 165 |
+
input_ids.device
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
bsz, seq_len = inputs_embeds.size()[:-1]
|
| 169 |
+
position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, past_key_values_length)
|
| 170 |
+
|
| 171 |
+
# expand embeddings if needed
|
| 172 |
+
max_pos = self.padding_idx + 1 + seq_len + past_key_values_length
|
| 173 |
+
if max_pos > self.weights.size(0):
|
| 174 |
+
self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
|
| 175 |
+
|
| 176 |
+
return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach()
|
| 177 |
+
|
| 178 |
+
def create_position_ids_from_inputs_embeds(self, inputs_embeds, past_key_values_length):
|
| 179 |
+
"""
|
| 180 |
+
We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
inputs_embeds: torch.Tensor
|
| 184 |
+
|
| 185 |
+
Returns: torch.Tensor
|
| 186 |
+
"""
|
| 187 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 188 |
+
sequence_length = input_shape[1]
|
| 189 |
+
|
| 190 |
+
position_ids = torch.arange(
|
| 191 |
+
self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
|
| 192 |
+
)
|
| 193 |
+
return position_ids.unsqueeze(0).expand(input_shape).contiguous() + past_key_values_length
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->M2M100
|
| 197 |
+
class M2M100Attention(nn.Module):
|
| 198 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 199 |
+
|
| 200 |
+
def __init__(
|
| 201 |
+
self,
|
| 202 |
+
embed_dim: int,
|
| 203 |
+
num_heads: int,
|
| 204 |
+
dropout: float = 0.0,
|
| 205 |
+
is_decoder: bool = False,
|
| 206 |
+
bias: bool = True,
|
| 207 |
+
):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.embed_dim = embed_dim
|
| 210 |
+
self.num_heads = num_heads
|
| 211 |
+
self.dropout = dropout
|
| 212 |
+
self.head_dim = embed_dim // num_heads
|
| 213 |
+
|
| 214 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 215 |
+
raise ValueError(
|
| 216 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 217 |
+
f" and `num_heads`: {num_heads})."
|
| 218 |
+
)
|
| 219 |
+
self.scaling = self.head_dim**-0.5
|
| 220 |
+
self.is_decoder = is_decoder
|
| 221 |
+
|
| 222 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 223 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 224 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 225 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 226 |
+
|
| 227 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 228 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 229 |
+
|
| 230 |
+
def forward(
|
| 231 |
+
self,
|
| 232 |
+
hidden_states: torch.Tensor,
|
| 233 |
+
key_value_states: Optional[torch.Tensor] = None,
|
| 234 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 235 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 236 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 237 |
+
output_attentions: bool = False,
|
| 238 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 239 |
+
"""Input shape: Batch x Time x Channel"""
|
| 240 |
+
|
| 241 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 242 |
+
# for the decoder
|
| 243 |
+
is_cross_attention = key_value_states is not None
|
| 244 |
+
|
| 245 |
+
bsz, tgt_len, _ = hidden_states.size()
|
| 246 |
+
|
| 247 |
+
# get query proj
|
| 248 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 249 |
+
# get key, value proj
|
| 250 |
+
# `past_key_value[0].shape[2] == key_value_states.shape[1]`
|
| 251 |
+
# is checking that the `sequence_length` of the `past_key_value` is the same as
|
| 252 |
+
# the provided `key_value_states` to support prefix tuning
|
| 253 |
+
if (
|
| 254 |
+
is_cross_attention
|
| 255 |
+
and past_key_value is not None
|
| 256 |
+
and past_key_value[0].shape[2] == key_value_states.shape[1]
|
| 257 |
+
):
|
| 258 |
+
# reuse k,v, cross_attentions
|
| 259 |
+
key_states = past_key_value[0]
|
| 260 |
+
value_states = past_key_value[1]
|
| 261 |
+
elif is_cross_attention:
|
| 262 |
+
# cross_attentions
|
| 263 |
+
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
|
| 264 |
+
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
|
| 265 |
+
elif past_key_value is not None:
|
| 266 |
+
# reuse k, v, self_attention
|
| 267 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 268 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 269 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 270 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 271 |
+
else:
|
| 272 |
+
# self_attention
|
| 273 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 274 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 275 |
+
|
| 276 |
+
if self.is_decoder:
|
| 277 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 278 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 279 |
+
# key/value_states (first "if" case)
|
| 280 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 281 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 282 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 283 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 284 |
+
past_key_value = (key_states, value_states)
|
| 285 |
+
|
| 286 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 287 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 288 |
+
key_states = key_states.reshape(*proj_shape)
|
| 289 |
+
value_states = value_states.reshape(*proj_shape)
|
| 290 |
+
|
| 291 |
+
src_len = key_states.size(1)
|
| 292 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 293 |
+
|
| 294 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 295 |
+
raise ValueError(
|
| 296 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 297 |
+
f" {attn_weights.size()}"
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
if attention_mask is not None:
|
| 301 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 302 |
+
raise ValueError(
|
| 303 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 304 |
+
)
|
| 305 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 306 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 307 |
+
|
| 308 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 309 |
+
|
| 310 |
+
if layer_head_mask is not None:
|
| 311 |
+
if layer_head_mask.size() != (self.num_heads,):
|
| 312 |
+
raise ValueError(
|
| 313 |
+
f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
|
| 314 |
+
f" {layer_head_mask.size()}"
|
| 315 |
+
)
|
| 316 |
+
attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 317 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 318 |
+
|
| 319 |
+
if output_attentions:
|
| 320 |
+
# this operation is a bit awkward, but it's required to
|
| 321 |
+
# make sure that attn_weights keeps its gradient.
|
| 322 |
+
# In order to do so, attn_weights have to be reshaped
|
| 323 |
+
# twice and have to be reused in the following
|
| 324 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 325 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 326 |
+
else:
|
| 327 |
+
attn_weights_reshaped = None
|
| 328 |
+
|
| 329 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 330 |
+
|
| 331 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 332 |
+
|
| 333 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 334 |
+
raise ValueError(
|
| 335 |
+
f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 336 |
+
f" {attn_output.size()}"
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 340 |
+
attn_output = attn_output.transpose(1, 2)
|
| 341 |
+
|
| 342 |
+
# Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
|
| 343 |
+
# partitioned across GPUs when using tensor-parallelism.
|
| 344 |
+
attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
|
| 345 |
+
|
| 346 |
+
attn_output = self.out_proj(attn_output)
|
| 347 |
+
|
| 348 |
+
return attn_output, attn_weights_reshaped, past_key_value
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
# Copied from transformers.models.mbart.modeling_mbart.MBartEncoderLayer with MBart->M2M100
|
| 352 |
+
class M2M100EncoderLayer(nn.Module):
|
| 353 |
+
def __init__(self, config: M2M100Config):
|
| 354 |
+
super().__init__()
|
| 355 |
+
self.embed_dim = config.d_model
|
| 356 |
+
self.self_attn = M2M100Attention(
|
| 357 |
+
embed_dim=self.embed_dim,
|
| 358 |
+
num_heads=config.encoder_attention_heads,
|
| 359 |
+
dropout=config.attention_dropout,
|
| 360 |
+
)
|
| 361 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 362 |
+
self.dropout = config.dropout
|
| 363 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 364 |
+
self.activation_dropout = config.activation_dropout
|
| 365 |
+
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
|
| 366 |
+
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
|
| 367 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 368 |
+
|
| 369 |
+
def forward(
|
| 370 |
+
self,
|
| 371 |
+
hidden_states: torch.Tensor,
|
| 372 |
+
attention_mask: torch.Tensor,
|
| 373 |
+
layer_head_mask: torch.Tensor,
|
| 374 |
+
output_attentions: bool = False,
|
| 375 |
+
) -> torch.Tensor:
|
| 376 |
+
"""
|
| 377 |
+
Args:
|
| 378 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 379 |
+
attention_mask (`torch.FloatTensor`): 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 |
+
output_attentions (`bool`, *optional*):
|
| 384 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 385 |
+
returned tensors for more detail.
|
| 386 |
+
"""
|
| 387 |
+
residual = hidden_states
|
| 388 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 389 |
+
hidden_states, attn_weights, _ = self.self_attn(
|
| 390 |
+
hidden_states=hidden_states,
|
| 391 |
+
attention_mask=attention_mask,
|
| 392 |
+
layer_head_mask=layer_head_mask,
|
| 393 |
+
output_attentions=output_attentions,
|
| 394 |
+
)
|
| 395 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 396 |
+
hidden_states = residual + hidden_states
|
| 397 |
+
|
| 398 |
+
residual = hidden_states
|
| 399 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 400 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 401 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 402 |
+
hidden_states = self.fc2(hidden_states)
|
| 403 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 404 |
+
hidden_states = residual + hidden_states
|
| 405 |
+
|
| 406 |
+
if hidden_states.dtype == torch.float16 and (
|
| 407 |
+
torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
|
| 408 |
+
):
|
| 409 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 410 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 411 |
+
|
| 412 |
+
outputs = (hidden_states,)
|
| 413 |
+
|
| 414 |
+
if output_attentions:
|
| 415 |
+
outputs += (attn_weights,)
|
| 416 |
+
|
| 417 |
+
return outputs
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
# Copied from transformers.models.mbart.modeling_mbart.MBartDecoderLayer with MBart->M2M100
|
| 421 |
+
class M2M100DecoderLayer(nn.Module):
|
| 422 |
+
def __init__(self, config: M2M100Config):
|
| 423 |
+
super().__init__()
|
| 424 |
+
self.embed_dim = config.d_model
|
| 425 |
+
|
| 426 |
+
self.self_attn = M2M100Attention(
|
| 427 |
+
embed_dim=self.embed_dim,
|
| 428 |
+
num_heads=config.decoder_attention_heads,
|
| 429 |
+
dropout=config.attention_dropout,
|
| 430 |
+
is_decoder=True,
|
| 431 |
+
)
|
| 432 |
+
self.dropout = config.dropout
|
| 433 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 434 |
+
self.activation_dropout = config.activation_dropout
|
| 435 |
+
|
| 436 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 437 |
+
self.encoder_attn = M2M100Attention(
|
| 438 |
+
self.embed_dim,
|
| 439 |
+
config.decoder_attention_heads,
|
| 440 |
+
dropout=config.attention_dropout,
|
| 441 |
+
is_decoder=True,
|
| 442 |
+
)
|
| 443 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 444 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 445 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 446 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 447 |
+
|
| 448 |
+
def forward(
|
| 449 |
+
self,
|
| 450 |
+
hidden_states: torch.Tensor,
|
| 451 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 452 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 453 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 454 |
+
layer_head_mask: Optional[torch.Tensor] = None,
|
| 455 |
+
cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
|
| 456 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 457 |
+
output_attentions: Optional[bool] = False,
|
| 458 |
+
use_cache: Optional[bool] = True,
|
| 459 |
+
) -> torch.Tensor:
|
| 460 |
+
"""
|
| 461 |
+
Args:
|
| 462 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 463 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 464 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 465 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 466 |
+
cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 467 |
+
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
|
| 468 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 469 |
+
layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
|
| 470 |
+
`(encoder_attention_heads,)`.
|
| 471 |
+
cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
|
| 472 |
+
size `(decoder_attention_heads,)`.
|
| 473 |
+
past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
|
| 474 |
+
output_attentions (`bool`, *optional*):
|
| 475 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 476 |
+
returned tensors for more detail.
|
| 477 |
+
"""
|
| 478 |
+
residual = hidden_states
|
| 479 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 480 |
+
|
| 481 |
+
# Self Attention
|
| 482 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 483 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 484 |
+
# add present self-attn cache to positions 1,2 of present_key_value tuple
|
| 485 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 486 |
+
hidden_states=hidden_states,
|
| 487 |
+
past_key_value=self_attn_past_key_value,
|
| 488 |
+
attention_mask=attention_mask,
|
| 489 |
+
layer_head_mask=layer_head_mask,
|
| 490 |
+
output_attentions=output_attentions,
|
| 491 |
+
)
|
| 492 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 493 |
+
hidden_states = residual + hidden_states
|
| 494 |
+
|
| 495 |
+
# Cross-Attention Block
|
| 496 |
+
cross_attn_present_key_value = None
|
| 497 |
+
cross_attn_weights = None
|
| 498 |
+
if encoder_hidden_states is not None:
|
| 499 |
+
residual = hidden_states
|
| 500 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 501 |
+
|
| 502 |
+
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
|
| 503 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 504 |
+
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
|
| 505 |
+
hidden_states=hidden_states,
|
| 506 |
+
key_value_states=encoder_hidden_states,
|
| 507 |
+
attention_mask=encoder_attention_mask,
|
| 508 |
+
layer_head_mask=cross_attn_layer_head_mask,
|
| 509 |
+
past_key_value=cross_attn_past_key_value,
|
| 510 |
+
output_attentions=output_attentions,
|
| 511 |
+
)
|
| 512 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 513 |
+
hidden_states = residual + hidden_states
|
| 514 |
+
|
| 515 |
+
# add cross-attn to positions 3,4 of present_key_value tuple
|
| 516 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 517 |
+
|
| 518 |
+
# Fully Connected
|
| 519 |
+
residual = hidden_states
|
| 520 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 521 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 522 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 523 |
+
hidden_states = self.fc2(hidden_states)
|
| 524 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 525 |
+
hidden_states = residual + hidden_states
|
| 526 |
+
|
| 527 |
+
outputs = (hidden_states,)
|
| 528 |
+
|
| 529 |
+
if output_attentions:
|
| 530 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 531 |
+
|
| 532 |
+
if use_cache:
|
| 533 |
+
outputs += (present_key_value,)
|
| 534 |
+
|
| 535 |
+
return outputs
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
class M2M100PreTrainedModel(PreTrainedModel):
|
| 539 |
+
config_class = M2M100Config
|
| 540 |
+
base_model_prefix = "model"
|
| 541 |
+
supports_gradient_checkpointing = True
|
| 542 |
+
_no_split_modules = ["M2M100Attention"]
|
| 543 |
+
|
| 544 |
+
def _init_weights(self, module):
|
| 545 |
+
std = self.config.init_std
|
| 546 |
+
if isinstance(module, nn.Linear):
|
| 547 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 548 |
+
if module.bias is not None:
|
| 549 |
+
module.bias.data.zero_()
|
| 550 |
+
elif isinstance(module, nn.Embedding):
|
| 551 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 552 |
+
if module.padding_idx is not None:
|
| 553 |
+
module.weight.data[module.padding_idx].zero_()
|
| 554 |
+
|
| 555 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 556 |
+
if isinstance(module, (M2M100Decoder, M2M100Encoder)):
|
| 557 |
+
module.gradient_checkpointing = value
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
M2M_100_START_DOCSTRING = r"""
|
| 561 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 562 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 563 |
+
etc.)
|
| 564 |
+
|
| 565 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 566 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 567 |
+
and behavior.
|
| 568 |
+
|
| 569 |
+
Parameters:
|
| 570 |
+
config ([`M2M100Config`]):
|
| 571 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 572 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 573 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 574 |
+
"""
|
| 575 |
+
|
| 576 |
+
M2M_100_GENERATION_EXAMPLE = r"""
|
| 577 |
+
Translation example:
|
| 578 |
+
|
| 579 |
+
```python
|
| 580 |
+
>>> from transformers import AutoTokenizer, M2M100ForConditionalGeneration
|
| 581 |
+
|
| 582 |
+
>>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
|
| 583 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/m2m100_418M")
|
| 584 |
+
|
| 585 |
+
>>> text_to_translate = "Life is like a box of chocolates"
|
| 586 |
+
>>> model_inputs = tokenizer(text_to_translate, return_tensors="pt")
|
| 587 |
+
|
| 588 |
+
>>> # translate to French
|
| 589 |
+
>>> gen_tokens = model.generate(**model_inputs, forced_bos_token_id=tokenizer.get_lang_id("fr"))
|
| 590 |
+
>>> print(tokenizer.batch_decode(gen_tokens, skip_special_tokens=True))
|
| 591 |
+
```
|
| 592 |
+
"""
|
| 593 |
+
|
| 594 |
+
M2M_100_INPUTS_DOCSTRING = r"""
|
| 595 |
+
Args:
|
| 596 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 597 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 598 |
+
it.
|
| 599 |
+
|
| 600 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 601 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 602 |
+
|
| 603 |
+
[What are input IDs?](../glossary#input-ids)
|
| 604 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 605 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 606 |
+
|
| 607 |
+
- 1 for tokens that are **not masked**,
|
| 608 |
+
- 0 for tokens that are **masked**.
|
| 609 |
+
|
| 610 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 611 |
+
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 612 |
+
Indices of decoder input sequence tokens in the vocabulary.
|
| 613 |
+
|
| 614 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 615 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 616 |
+
|
| 617 |
+
[What are decoder input IDs?](../glossary#decoder-input-ids)
|
| 618 |
+
|
| 619 |
+
M2M100 uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If
|
| 620 |
+
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 621 |
+
`past_key_values`).
|
| 622 |
+
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
|
| 623 |
+
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
|
| 624 |
+
be used by default.
|
| 625 |
+
head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
|
| 626 |
+
Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
|
| 627 |
+
|
| 628 |
+
- 1 indicates the head is **not masked**,
|
| 629 |
+
- 0 indicates the head is **masked**.
|
| 630 |
+
|
| 631 |
+
decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 632 |
+
Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
|
| 633 |
+
|
| 634 |
+
- 1 indicates the head is **not masked**,
|
| 635 |
+
- 0 indicates the head is **masked**.
|
| 636 |
+
|
| 637 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 638 |
+
Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
|
| 639 |
+
1]`:
|
| 640 |
+
|
| 641 |
+
- 1 indicates the head is **not masked**,
|
| 642 |
+
- 0 indicates the head is **masked**.
|
| 643 |
+
encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
|
| 644 |
+
Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
|
| 645 |
+
`last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
|
| 646 |
+
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
|
| 647 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 648 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 649 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
| 650 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 651 |
+
|
| 652 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 653 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 654 |
+
|
| 655 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 656 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 657 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape
|
| 658 |
+
`(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you
|
| 659 |
+
can choose to directly pass an embedded representation. This is useful if you want more control over how to
|
| 660 |
+
convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
|
| 661 |
+
decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
|
| 662 |
+
Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
|
| 663 |
+
representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
|
| 664 |
+
input (see `past_key_values`). This is useful if you want more control over how to convert
|
| 665 |
+
`decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
|
| 666 |
+
|
| 667 |
+
If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
|
| 668 |
+
of `inputs_embeds`.
|
| 669 |
+
use_cache (`bool`, *optional*):
|
| 670 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 671 |
+
`past_key_values`).
|
| 672 |
+
output_attentions (`bool`, *optional*):
|
| 673 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 674 |
+
tensors for more detail.
|
| 675 |
+
output_hidden_states (`bool`, *optional*):
|
| 676 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 677 |
+
more detail.
|
| 678 |
+
return_dict (`bool`, *optional*):
|
| 679 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 680 |
+
"""
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
class M2M100Encoder(M2M100PreTrainedModel):
|
| 684 |
+
"""
|
| 685 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 686 |
+
[`M2M100EncoderLayer`].
|
| 687 |
+
|
| 688 |
+
Args:
|
| 689 |
+
config: M2M100Config
|
| 690 |
+
embed_tokens (nn.Embedding): output embedding
|
| 691 |
+
"""
|
| 692 |
+
|
| 693 |
+
def __init__(self, config: M2M100Config, embed_tokens: Optional[nn.Embedding] = None):
|
| 694 |
+
super().__init__(config)
|
| 695 |
+
|
| 696 |
+
self.dropout = config.dropout
|
| 697 |
+
self.layerdrop = config.encoder_layerdrop
|
| 698 |
+
|
| 699 |
+
embed_dim = config.d_model
|
| 700 |
+
self.padding_idx = config.pad_token_id
|
| 701 |
+
self.max_source_positions = config.max_position_embeddings
|
| 702 |
+
self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
|
| 703 |
+
|
| 704 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
|
| 705 |
+
|
| 706 |
+
if embed_tokens is not None:
|
| 707 |
+
self.embed_tokens.weight = embed_tokens.weight
|
| 708 |
+
|
| 709 |
+
self.embed_positions = M2M100SinusoidalPositionalEmbedding(
|
| 710 |
+
config.max_position_embeddings,
|
| 711 |
+
embed_dim,
|
| 712 |
+
self.padding_idx,
|
| 713 |
+
)
|
| 714 |
+
self.layers = nn.ModuleList([M2M100EncoderLayer(config) for _ in range(config.encoder_layers)])
|
| 715 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 716 |
+
|
| 717 |
+
self.gradient_checkpointing = False
|
| 718 |
+
# Initialize weights and apply final processing
|
| 719 |
+
self.post_init()
|
| 720 |
+
|
| 721 |
+
def forward(
|
| 722 |
+
self,
|
| 723 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 724 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 725 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 726 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 727 |
+
output_attentions: Optional[bool] = None,
|
| 728 |
+
output_hidden_states: Optional[bool] = None,
|
| 729 |
+
return_dict: Optional[bool] = None,
|
| 730 |
+
):
|
| 731 |
+
r"""
|
| 732 |
+
Args:
|
| 733 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 734 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 735 |
+
provide it.
|
| 736 |
+
|
| 737 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 738 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 739 |
+
|
| 740 |
+
[What are input IDs?](../glossary#input-ids)
|
| 741 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 742 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 743 |
+
|
| 744 |
+
- 1 for tokens that are **not masked**,
|
| 745 |
+
- 0 for tokens that are **masked**.
|
| 746 |
+
|
| 747 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 748 |
+
head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
|
| 749 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 750 |
+
|
| 751 |
+
- 1 indicates the head is **not masked**,
|
| 752 |
+
- 0 indicates the head is **masked**.
|
| 753 |
+
|
| 754 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 755 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 756 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 757 |
+
than the model's internal embedding lookup matrix.
|
| 758 |
+
output_attentions (`bool`, *optional*):
|
| 759 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 760 |
+
returned tensors for more detail.
|
| 761 |
+
output_hidden_states (`bool`, *optional*):
|
| 762 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 763 |
+
for more detail.
|
| 764 |
+
return_dict (`bool`, *optional*):
|
| 765 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 766 |
+
"""
|
| 767 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 768 |
+
output_hidden_states = (
|
| 769 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 770 |
+
)
|
| 771 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 772 |
+
|
| 773 |
+
# retrieve input_ids and inputs_embeds
|
| 774 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 775 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 776 |
+
elif input_ids is not None:
|
| 777 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 778 |
+
input_shape = input_ids.size()
|
| 779 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 780 |
+
elif inputs_embeds is not None:
|
| 781 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 782 |
+
else:
|
| 783 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 784 |
+
|
| 785 |
+
if inputs_embeds is None:
|
| 786 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 787 |
+
|
| 788 |
+
embed_pos = self.embed_positions(input_ids, inputs_embeds)
|
| 789 |
+
embed_pos = embed_pos.to(inputs_embeds.device)
|
| 790 |
+
|
| 791 |
+
hidden_states = inputs_embeds + embed_pos
|
| 792 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 793 |
+
|
| 794 |
+
# expand attention_mask
|
| 795 |
+
if attention_mask is not None:
|
| 796 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 797 |
+
attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)
|
| 798 |
+
|
| 799 |
+
encoder_states = () if output_hidden_states else None
|
| 800 |
+
all_attentions = () if output_attentions else None
|
| 801 |
+
|
| 802 |
+
# check if head_mask has a correct number of layers specified if desired
|
| 803 |
+
if head_mask is not None:
|
| 804 |
+
if head_mask.size()[0] != len(self.layers):
|
| 805 |
+
raise ValueError(
|
| 806 |
+
f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
|
| 807 |
+
f" {head_mask.size()[0]}."
|
| 808 |
+
)
|
| 809 |
+
deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()
|
| 810 |
+
|
| 811 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 812 |
+
if output_hidden_states:
|
| 813 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 814 |
+
|
| 815 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 816 |
+
dropout_probability = torch.rand([])
|
| 817 |
+
|
| 818 |
+
skip_the_layer = True if self.training and (dropout_probability < self.layerdrop) else False
|
| 819 |
+
if not skip_the_layer or deepspeed_zero3_is_enabled:
|
| 820 |
+
# under deepspeed zero3 all gpus must run in sync
|
| 821 |
+
|
| 822 |
+
if self.gradient_checkpointing and self.training:
|
| 823 |
+
# create gradient checkpointing function
|
| 824 |
+
def create_custom_forward(module):
|
| 825 |
+
def custom_forward(*inputs):
|
| 826 |
+
return module(*inputs, output_attentions)
|
| 827 |
+
|
| 828 |
+
return custom_forward
|
| 829 |
+
|
| 830 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 831 |
+
create_custom_forward(encoder_layer),
|
| 832 |
+
hidden_states,
|
| 833 |
+
attention_mask,
|
| 834 |
+
(head_mask[idx] if head_mask is not None else None),
|
| 835 |
+
)
|
| 836 |
+
else:
|
| 837 |
+
layer_outputs = encoder_layer(
|
| 838 |
+
hidden_states,
|
| 839 |
+
attention_mask,
|
| 840 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 841 |
+
output_attentions=output_attentions,
|
| 842 |
+
)
|
| 843 |
+
|
| 844 |
+
hidden_states = layer_outputs[0]
|
| 845 |
+
|
| 846 |
+
if skip_the_layer:
|
| 847 |
+
layer_outputs = (None, None)
|
| 848 |
+
|
| 849 |
+
if output_attentions:
|
| 850 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 851 |
+
|
| 852 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 853 |
+
|
| 854 |
+
if output_hidden_states:
|
| 855 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 856 |
+
|
| 857 |
+
if not return_dict:
|
| 858 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 859 |
+
return BaseModelOutput(
|
| 860 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
class M2M100Decoder(M2M100PreTrainedModel):
|
| 865 |
+
"""
|
| 866 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`M2M100DecoderLayer`]
|
| 867 |
+
|
| 868 |
+
Args:
|
| 869 |
+
config: M2M100Config
|
| 870 |
+
embed_tokens (nn.Embedding): output embedding
|
| 871 |
+
"""
|
| 872 |
+
|
| 873 |
+
def __init__(self, config: M2M100Config, embed_tokens: Optional[nn.Embedding] = None):
|
| 874 |
+
super().__init__(config)
|
| 875 |
+
self.dropout = config.dropout
|
| 876 |
+
self.layerdrop = config.decoder_layerdrop
|
| 877 |
+
self.padding_idx = config.pad_token_id
|
| 878 |
+
self.max_target_positions = config.max_position_embeddings
|
| 879 |
+
self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 880 |
+
|
| 881 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
|
| 882 |
+
|
| 883 |
+
if embed_tokens is not None:
|
| 884 |
+
self.embed_tokens.weight = embed_tokens.weight
|
| 885 |
+
|
| 886 |
+
self.embed_positions = M2M100SinusoidalPositionalEmbedding(
|
| 887 |
+
config.max_position_embeddings,
|
| 888 |
+
config.d_model,
|
| 889 |
+
self.padding_idx,
|
| 890 |
+
)
|
| 891 |
+
self.layers = nn.ModuleList([M2M100DecoderLayer(config) for _ in range(config.decoder_layers)])
|
| 892 |
+
self.layer_norm = nn.LayerNorm(config.d_model)
|
| 893 |
+
|
| 894 |
+
self.gradient_checkpointing = False
|
| 895 |
+
# Initialize weights and apply final processing
|
| 896 |
+
self.post_init()
|
| 897 |
+
|
| 898 |
+
def forward(
|
| 899 |
+
self,
|
| 900 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 901 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 902 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 903 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 904 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 905 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 906 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 907 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 908 |
+
use_cache: Optional[bool] = None,
|
| 909 |
+
output_attentions: Optional[bool] = None,
|
| 910 |
+
output_hidden_states: Optional[bool] = None,
|
| 911 |
+
return_dict: Optional[bool] = None,
|
| 912 |
+
):
|
| 913 |
+
r"""
|
| 914 |
+
Args:
|
| 915 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 916 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
| 917 |
+
provide it.
|
| 918 |
+
|
| 919 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 920 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 921 |
+
|
| 922 |
+
[What are input IDs?](../glossary#input-ids)
|
| 923 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 924 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 925 |
+
|
| 926 |
+
- 1 for tokens that are **not masked**,
|
| 927 |
+
- 0 for tokens that are **masked**.
|
| 928 |
+
|
| 929 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 930 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 931 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 932 |
+
of the decoder.
|
| 933 |
+
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
|
| 934 |
+
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
|
| 935 |
+
selected in `[0, 1]`:
|
| 936 |
+
|
| 937 |
+
- 1 for tokens that are **not masked**,
|
| 938 |
+
- 0 for tokens that are **masked**.
|
| 939 |
+
|
| 940 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 941 |
+
head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 942 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 943 |
+
|
| 944 |
+
- 1 indicates the head is **not masked**,
|
| 945 |
+
- 0 indicates the head is **masked**.
|
| 946 |
+
|
| 947 |
+
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
|
| 948 |
+
Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
|
| 949 |
+
cross-attention on hidden heads. 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(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 955 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 956 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
|
| 957 |
+
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 958 |
+
|
| 959 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
|
| 960 |
+
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 961 |
+
|
| 962 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
|
| 963 |
+
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
|
| 964 |
+
all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of
|
| 965 |
+
shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
|
| 966 |
+
`input_ids` you can choose to directly pass an embedded representation. This is useful if you want more
|
| 967 |
+
control over how to convert `input_ids` indices into associated vectors than the model's internal
|
| 968 |
+
embedding lookup matrix.
|
| 969 |
+
output_attentions (`bool`, *optional*):
|
| 970 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 971 |
+
returned tensors for more detail.
|
| 972 |
+
output_hidden_states (`bool`, *optional*):
|
| 973 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 974 |
+
for more detail.
|
| 975 |
+
return_dict (`bool`, *optional*):
|
| 976 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 977 |
+
"""
|
| 978 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 979 |
+
output_hidden_states = (
|
| 980 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 981 |
+
)
|
| 982 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 983 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 984 |
+
|
| 985 |
+
# retrieve input_ids and inputs_embeds
|
| 986 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 987 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 988 |
+
elif input_ids is not None:
|
| 989 |
+
input_shape = input_ids.size()
|
| 990 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 991 |
+
elif inputs_embeds is not None:
|
| 992 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 993 |
+
else:
|
| 994 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 995 |
+
|
| 996 |
+
# past_key_values_length
|
| 997 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 998 |
+
|
| 999 |
+
if inputs_embeds is None:
|
| 1000 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 1001 |
+
|
| 1002 |
+
# create causal mask
|
| 1003 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1004 |
+
combined_attention_mask = None
|
| 1005 |
+
if input_shape[-1] > 1:
|
| 1006 |
+
combined_attention_mask = _make_causal_mask(
|
| 1007 |
+
input_shape,
|
| 1008 |
+
inputs_embeds.dtype,
|
| 1009 |
+
device=inputs_embeds.device,
|
| 1010 |
+
past_key_values_length=past_key_values_length,
|
| 1011 |
+
)
|
| 1012 |
+
|
| 1013 |
+
if attention_mask is not None and combined_attention_mask is not None:
|
| 1014 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1015 |
+
combined_attention_mask = combined_attention_mask + _expand_mask(
|
| 1016 |
+
attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
|
| 1017 |
+
)
|
| 1018 |
+
|
| 1019 |
+
# expand encoder attention mask
|
| 1020 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 1021 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1022 |
+
encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
|
| 1023 |
+
|
| 1024 |
+
# embed positions
|
| 1025 |
+
positions = self.embed_positions(input_ids, inputs_embeds, past_key_values_length)
|
| 1026 |
+
positions = positions.to(inputs_embeds.device)
|
| 1027 |
+
|
| 1028 |
+
hidden_states = inputs_embeds + positions
|
| 1029 |
+
|
| 1030 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 1031 |
+
|
| 1032 |
+
if self.gradient_checkpointing and self.training:
|
| 1033 |
+
if use_cache:
|
| 1034 |
+
logger.warning_once(
|
| 1035 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting" " `use_cache=False`..."
|
| 1036 |
+
)
|
| 1037 |
+
use_cache = False
|
| 1038 |
+
|
| 1039 |
+
# decoder layers
|
| 1040 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1041 |
+
all_self_attns = () if output_attentions else None
|
| 1042 |
+
all_cross_attentions = () if output_attentions else None
|
| 1043 |
+
next_decoder_cache = () if use_cache else None
|
| 1044 |
+
|
| 1045 |
+
# check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
|
| 1046 |
+
for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
|
| 1047 |
+
if attn_mask is not None:
|
| 1048 |
+
if attn_mask.size()[0] != len(self.layers):
|
| 1049 |
+
raise ValueError(
|
| 1050 |
+
f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
|
| 1051 |
+
f" {head_mask.size()[0]}."
|
| 1052 |
+
)
|
| 1053 |
+
deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()
|
| 1054 |
+
|
| 1055 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 1056 |
+
if output_hidden_states:
|
| 1057 |
+
all_hidden_states += (hidden_states,)
|
| 1058 |
+
|
| 1059 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 1060 |
+
dropout_probability = torch.rand([])
|
| 1061 |
+
|
| 1062 |
+
skip_the_layer = True if self.training and (dropout_probability < self.layerdrop) else False
|
| 1063 |
+
if not skip_the_layer or deepspeed_zero3_is_enabled:
|
| 1064 |
+
# under deepspeed zero3 all gpus must run in sync
|
| 1065 |
+
|
| 1066 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 1067 |
+
|
| 1068 |
+
if self.gradient_checkpointing and self.training:
|
| 1069 |
+
|
| 1070 |
+
def create_custom_forward(module):
|
| 1071 |
+
def custom_forward(*inputs):
|
| 1072 |
+
# None for past_key_value
|
| 1073 |
+
return module(*inputs, output_attentions, use_cache)
|
| 1074 |
+
|
| 1075 |
+
return custom_forward
|
| 1076 |
+
|
| 1077 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 1078 |
+
create_custom_forward(decoder_layer),
|
| 1079 |
+
hidden_states,
|
| 1080 |
+
combined_attention_mask,
|
| 1081 |
+
encoder_hidden_states,
|
| 1082 |
+
encoder_attention_mask,
|
| 1083 |
+
head_mask[idx] if head_mask is not None else None,
|
| 1084 |
+
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
|
| 1085 |
+
None,
|
| 1086 |
+
)
|
| 1087 |
+
else:
|
| 1088 |
+
layer_outputs = decoder_layer(
|
| 1089 |
+
hidden_states,
|
| 1090 |
+
attention_mask=combined_attention_mask,
|
| 1091 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1092 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1093 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 1094 |
+
cross_attn_layer_head_mask=(
|
| 1095 |
+
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
|
| 1096 |
+
),
|
| 1097 |
+
past_key_value=past_key_value,
|
| 1098 |
+
output_attentions=output_attentions,
|
| 1099 |
+
use_cache=use_cache,
|
| 1100 |
+
)
|
| 1101 |
+
|
| 1102 |
+
hidden_states = layer_outputs[0]
|
| 1103 |
+
|
| 1104 |
+
if skip_the_layer:
|
| 1105 |
+
continue
|
| 1106 |
+
|
| 1107 |
+
if use_cache:
|
| 1108 |
+
next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
|
| 1109 |
+
|
| 1110 |
+
if output_attentions:
|
| 1111 |
+
all_self_attns += (layer_outputs[1],)
|
| 1112 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 1113 |
+
|
| 1114 |
+
hidden_states = self.layer_norm(hidden_states)
|
| 1115 |
+
|
| 1116 |
+
# add hidden states from the last decoder layer
|
| 1117 |
+
if output_hidden_states:
|
| 1118 |
+
all_hidden_states += (hidden_states,)
|
| 1119 |
+
|
| 1120 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 1121 |
+
if not return_dict:
|
| 1122 |
+
return tuple(
|
| 1123 |
+
v
|
| 1124 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 1125 |
+
if v is not None
|
| 1126 |
+
)
|
| 1127 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 1128 |
+
last_hidden_state=hidden_states,
|
| 1129 |
+
past_key_values=next_cache,
|
| 1130 |
+
hidden_states=all_hidden_states,
|
| 1131 |
+
attentions=all_self_attns,
|
| 1132 |
+
cross_attentions=all_cross_attentions,
|
| 1133 |
+
)
|
| 1134 |
+
|
| 1135 |
+
|
| 1136 |
+
@add_start_docstrings(
|
| 1137 |
+
"The bare M2M100 Model outputting raw hidden-states without any specific head on top.",
|
| 1138 |
+
M2M_100_START_DOCSTRING,
|
| 1139 |
+
)
|
| 1140 |
+
class M2M100Model(M2M100PreTrainedModel):
|
| 1141 |
+
_tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
|
| 1142 |
+
|
| 1143 |
+
def __init__(self, config: M2M100Config):
|
| 1144 |
+
super().__init__(config)
|
| 1145 |
+
|
| 1146 |
+
padding_idx, vocab_size = config.pad_token_id, config.vocab_size
|
| 1147 |
+
self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
|
| 1148 |
+
|
| 1149 |
+
self.encoder = M2M100Encoder(config, self.shared)
|
| 1150 |
+
self.decoder = M2M100Decoder(config, self.shared)
|
| 1151 |
+
|
| 1152 |
+
# Initialize weights and apply final processing
|
| 1153 |
+
self.post_init()
|
| 1154 |
+
|
| 1155 |
+
def get_input_embeddings(self):
|
| 1156 |
+
return self.shared
|
| 1157 |
+
|
| 1158 |
+
def set_input_embeddings(self, value):
|
| 1159 |
+
self.shared = value
|
| 1160 |
+
self.encoder.embed_tokens = self.shared
|
| 1161 |
+
self.decoder.embed_tokens = self.shared
|
| 1162 |
+
|
| 1163 |
+
def get_encoder(self):
|
| 1164 |
+
return self.encoder
|
| 1165 |
+
|
| 1166 |
+
def get_decoder(self):
|
| 1167 |
+
return self.decoder
|
| 1168 |
+
|
| 1169 |
+
@add_start_docstrings_to_model_forward(M2M_100_INPUTS_DOCSTRING)
|
| 1170 |
+
@add_code_sample_docstrings(
|
| 1171 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1172 |
+
output_type=Seq2SeqModelOutput,
|
| 1173 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1174 |
+
)
|
| 1175 |
+
def forward(
|
| 1176 |
+
self,
|
| 1177 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1178 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1179 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
| 1180 |
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
| 1181 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1182 |
+
decoder_head_mask: Optional[torch.Tensor] = None,
|
| 1183 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1184 |
+
encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 1185 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 1186 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1187 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1188 |
+
use_cache: Optional[bool] = None,
|
| 1189 |
+
output_attentions: Optional[bool] = None,
|
| 1190 |
+
output_hidden_states: Optional[bool] = None,
|
| 1191 |
+
return_dict: Optional[bool] = None,
|
| 1192 |
+
) -> Union[Tuple[torch.Tensor], Seq2SeqModelOutput]:
|
| 1193 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1194 |
+
output_hidden_states = (
|
| 1195 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1196 |
+
)
|
| 1197 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1198 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1199 |
+
|
| 1200 |
+
if encoder_outputs is None:
|
| 1201 |
+
encoder_outputs = self.encoder(
|
| 1202 |
+
input_ids=input_ids,
|
| 1203 |
+
attention_mask=attention_mask,
|
| 1204 |
+
head_mask=head_mask,
|
| 1205 |
+
inputs_embeds=inputs_embeds,
|
| 1206 |
+
output_attentions=output_attentions,
|
| 1207 |
+
output_hidden_states=output_hidden_states,
|
| 1208 |
+
return_dict=return_dict,
|
| 1209 |
+
)
|
| 1210 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
|
| 1211 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 1212 |
+
encoder_outputs = BaseModelOutput(
|
| 1213 |
+
last_hidden_state=encoder_outputs[0],
|
| 1214 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1215 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1216 |
+
)
|
| 1217 |
+
|
| 1218 |
+
# decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
|
| 1219 |
+
decoder_outputs = self.decoder(
|
| 1220 |
+
input_ids=decoder_input_ids,
|
| 1221 |
+
attention_mask=decoder_attention_mask,
|
| 1222 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1223 |
+
encoder_attention_mask=attention_mask,
|
| 1224 |
+
head_mask=decoder_head_mask,
|
| 1225 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1226 |
+
past_key_values=past_key_values,
|
| 1227 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1228 |
+
use_cache=use_cache,
|
| 1229 |
+
output_attentions=output_attentions,
|
| 1230 |
+
output_hidden_states=output_hidden_states,
|
| 1231 |
+
return_dict=return_dict,
|
| 1232 |
+
)
|
| 1233 |
+
|
| 1234 |
+
if not return_dict:
|
| 1235 |
+
return decoder_outputs + encoder_outputs
|
| 1236 |
+
|
| 1237 |
+
return Seq2SeqModelOutput(
|
| 1238 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1239 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1240 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1241 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1242 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1243 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1244 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1245 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1246 |
+
)
|
| 1247 |
+
|
| 1248 |
+
|
| 1249 |
+
@add_start_docstrings(
|
| 1250 |
+
"The M2M100 Model with a language modeling head. Can be used for summarization.", M2M_100_START_DOCSTRING
|
| 1251 |
+
)
|
| 1252 |
+
class M2M100ForConditionalGeneration(M2M100PreTrainedModel):
|
| 1253 |
+
base_model_prefix = "model"
|
| 1254 |
+
_tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight", "lm_head.weight"]
|
| 1255 |
+
|
| 1256 |
+
def __init__(self, config: M2M100Config):
|
| 1257 |
+
super().__init__(config)
|
| 1258 |
+
self.model = M2M100Model(config)
|
| 1259 |
+
self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
|
| 1260 |
+
|
| 1261 |
+
# Initialize weights and apply final processing
|
| 1262 |
+
self.post_init()
|
| 1263 |
+
|
| 1264 |
+
def get_encoder(self):
|
| 1265 |
+
return self.model.get_encoder()
|
| 1266 |
+
|
| 1267 |
+
def get_decoder(self):
|
| 1268 |
+
return self.model.get_decoder()
|
| 1269 |
+
|
| 1270 |
+
def get_output_embeddings(self):
|
| 1271 |
+
return self.lm_head
|
| 1272 |
+
|
| 1273 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1274 |
+
self.lm_head = new_embeddings
|
| 1275 |
+
|
| 1276 |
+
@add_start_docstrings_to_model_forward(M2M_100_INPUTS_DOCSTRING)
|
| 1277 |
+
@replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 1278 |
+
@add_end_docstrings(M2M_100_GENERATION_EXAMPLE)
|
| 1279 |
+
def forward(
|
| 1280 |
+
self,
|
| 1281 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1282 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1283 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
| 1284 |
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
| 1285 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1286 |
+
decoder_head_mask: Optional[torch.Tensor] = None,
|
| 1287 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
| 1288 |
+
encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 1289 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 1290 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1291 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1292 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1293 |
+
use_cache: Optional[bool] = None,
|
| 1294 |
+
output_attentions: Optional[bool] = None,
|
| 1295 |
+
output_hidden_states: Optional[bool] = None,
|
| 1296 |
+
return_dict: Optional[bool] = None,
|
| 1297 |
+
) -> Union[Tuple[torch.Tensor], Seq2SeqLMOutput]:
|
| 1298 |
+
r"""
|
| 1299 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1300 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1301 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1302 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1303 |
+
|
| 1304 |
+
Returns:
|
| 1305 |
+
"""
|
| 1306 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1307 |
+
|
| 1308 |
+
if labels is not None:
|
| 1309 |
+
if decoder_input_ids is None:
|
| 1310 |
+
decoder_input_ids = shift_tokens_right(
|
| 1311 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1312 |
+
)
|
| 1313 |
+
|
| 1314 |
+
outputs = self.model(
|
| 1315 |
+
input_ids,
|
| 1316 |
+
attention_mask=attention_mask,
|
| 1317 |
+
decoder_input_ids=decoder_input_ids,
|
| 1318 |
+
encoder_outputs=encoder_outputs,
|
| 1319 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1320 |
+
head_mask=head_mask,
|
| 1321 |
+
decoder_head_mask=decoder_head_mask,
|
| 1322 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1323 |
+
past_key_values=past_key_values,
|
| 1324 |
+
inputs_embeds=inputs_embeds,
|
| 1325 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1326 |
+
use_cache=use_cache,
|
| 1327 |
+
output_attentions=output_attentions,
|
| 1328 |
+
output_hidden_states=output_hidden_states,
|
| 1329 |
+
return_dict=return_dict,
|
| 1330 |
+
)
|
| 1331 |
+
lm_logits = self.lm_head(outputs[0])
|
| 1332 |
+
|
| 1333 |
+
masked_lm_loss = None
|
| 1334 |
+
if labels is not None:
|
| 1335 |
+
# move labels to the correct device to enable PP
|
| 1336 |
+
labels = labels.to(lm_logits.device)
|
| 1337 |
+
loss_fct = CrossEntropyLoss()
|
| 1338 |
+
masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1339 |
+
|
| 1340 |
+
if not return_dict:
|
| 1341 |
+
output = (lm_logits,) + outputs[1:]
|
| 1342 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1343 |
+
|
| 1344 |
+
return Seq2SeqLMOutput(
|
| 1345 |
+
loss=masked_lm_loss,
|
| 1346 |
+
logits=lm_logits,
|
| 1347 |
+
past_key_values=outputs.past_key_values,
|
| 1348 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1349 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1350 |
+
cross_attentions=outputs.cross_attentions,
|
| 1351 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1352 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1353 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1354 |
+
)
|
| 1355 |
+
|
| 1356 |
+
def prepare_inputs_for_generation(
|
| 1357 |
+
self,
|
| 1358 |
+
decoder_input_ids,
|
| 1359 |
+
past_key_values=None,
|
| 1360 |
+
attention_mask=None,
|
| 1361 |
+
head_mask=None,
|
| 1362 |
+
decoder_head_mask=None,
|
| 1363 |
+
cross_attn_head_mask=None,
|
| 1364 |
+
use_cache=None,
|
| 1365 |
+
encoder_outputs=None,
|
| 1366 |
+
**kwargs,
|
| 1367 |
+
):
|
| 1368 |
+
# cut decoder_input_ids if past is used
|
| 1369 |
+
if past_key_values is not None:
|
| 1370 |
+
decoder_input_ids = decoder_input_ids[:, -1:]
|
| 1371 |
+
|
| 1372 |
+
return {
|
| 1373 |
+
"input_ids": None, # encoder_outputs is defined. input_ids not needed
|
| 1374 |
+
"encoder_outputs": encoder_outputs,
|
| 1375 |
+
"past_key_values": past_key_values,
|
| 1376 |
+
"decoder_input_ids": decoder_input_ids,
|
| 1377 |
+
"attention_mask": attention_mask,
|
| 1378 |
+
"head_mask": head_mask,
|
| 1379 |
+
"decoder_head_mask": decoder_head_mask,
|
| 1380 |
+
"cross_attn_head_mask": cross_attn_head_mask,
|
| 1381 |
+
"use_cache": use_cache, # change this to avoid caching (presumably for debugging)
|
| 1382 |
+
}
|
| 1383 |
+
|
| 1384 |
+
@staticmethod
|
| 1385 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 1386 |
+
reordered_past = ()
|
| 1387 |
+
for layer_past in past_key_values:
|
| 1388 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
| 1389 |
+
return reordered_past
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/m2m_100/tokenization_m2m_100.py
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. 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 |
+
"""Tokenization classes for M2M100."""
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from shutil import copyfile
|
| 19 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import sentencepiece
|
| 22 |
+
|
| 23 |
+
from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer
|
| 24 |
+
from ...utils import logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
SPIECE_UNDERLINE = "▁"
|
| 30 |
+
|
| 31 |
+
VOCAB_FILES_NAMES = {
|
| 32 |
+
"vocab_file": "vocab.json",
|
| 33 |
+
"spm_file": "sentencepiece.bpe.model",
|
| 34 |
+
"tokenizer_config_file": "tokenizer_config.json",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
| 38 |
+
"vocab_file": {
|
| 39 |
+
"facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json",
|
| 40 |
+
"facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json",
|
| 41 |
+
},
|
| 42 |
+
"spm_file": {
|
| 43 |
+
"facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model",
|
| 44 |
+
"facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model",
|
| 45 |
+
},
|
| 46 |
+
"tokenizer_config_file": {
|
| 47 |
+
"facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json",
|
| 48 |
+
"facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json",
|
| 49 |
+
},
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
| 53 |
+
"facebook/m2m100_418M": 1024,
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
# fmt: off
|
| 57 |
+
FAIRSEQ_LANGUAGE_CODES = {
|
| 58 |
+
"m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"],
|
| 59 |
+
"wmt21": ['en', 'ha', 'is', 'ja', 'cs', 'ru', 'zh', 'de']
|
| 60 |
+
}
|
| 61 |
+
# fmt: on
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class M2M100Tokenizer(PreTrainedTokenizer):
|
| 65 |
+
"""
|
| 66 |
+
Construct an M2M100 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
| 67 |
+
|
| 68 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 69 |
+
this superclass for more information regarding those methods.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
vocab_file (`str`):
|
| 73 |
+
Path to the vocabulary file.
|
| 74 |
+
spm_file (`str`):
|
| 75 |
+
Path to [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
|
| 76 |
+
contains the vocabulary.
|
| 77 |
+
src_lang (`str`, *optional*):
|
| 78 |
+
A string representing the source language.
|
| 79 |
+
tgt_lang (`str`, *optional*):
|
| 80 |
+
A string representing the target language.
|
| 81 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 82 |
+
The end of sequence token.
|
| 83 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
| 84 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 85 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 86 |
+
token of a sequence built with special tokens.
|
| 87 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 88 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 89 |
+
token instead.
|
| 90 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 91 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 92 |
+
language_codes (`str`, *optional*, defaults to `"m2m100"`):
|
| 93 |
+
What language codes to use. Should be one of `"m2m100"` or `"wmt21"`.
|
| 94 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 95 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 96 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 97 |
+
to set:
|
| 98 |
+
|
| 99 |
+
- `enable_sampling`: Enable subword regularization.
|
| 100 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 101 |
+
|
| 102 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 103 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 104 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 105 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 106 |
+
|
| 107 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 108 |
+
BPE-dropout.
|
| 109 |
+
|
| 110 |
+
Examples:
|
| 111 |
+
|
| 112 |
+
```python
|
| 113 |
+
>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
|
| 114 |
+
|
| 115 |
+
>>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
|
| 116 |
+
>>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="en", tgt_lang="ro")
|
| 117 |
+
>>> src_text = " UN Chief Says There Is No Military Solution in Syria"
|
| 118 |
+
>>> tgt_text = "Şeful ONU declară că nu există o soluţie militară în Siria"
|
| 119 |
+
>>> model_inputs = tokenizer(src_text, text_target=tgt_text, return_tensors="pt")
|
| 120 |
+
>>> outputs = model(**model_inputs) # should work
|
| 121 |
+
```"""
|
| 122 |
+
|
| 123 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 124 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
| 125 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
| 126 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 127 |
+
|
| 128 |
+
prefix_tokens: List[int] = []
|
| 129 |
+
suffix_tokens: List[int] = []
|
| 130 |
+
|
| 131 |
+
def __init__(
|
| 132 |
+
self,
|
| 133 |
+
vocab_file,
|
| 134 |
+
spm_file,
|
| 135 |
+
src_lang=None,
|
| 136 |
+
tgt_lang=None,
|
| 137 |
+
bos_token="<s>",
|
| 138 |
+
eos_token="</s>",
|
| 139 |
+
sep_token="</s>",
|
| 140 |
+
pad_token="<pad>",
|
| 141 |
+
unk_token="<unk>",
|
| 142 |
+
language_codes="m2m100",
|
| 143 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
| 144 |
+
num_madeup_words=8,
|
| 145 |
+
**kwargs,
|
| 146 |
+
) -> None:
|
| 147 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 148 |
+
|
| 149 |
+
self.language_codes = language_codes
|
| 150 |
+
fairseq_language_code = FAIRSEQ_LANGUAGE_CODES[language_codes]
|
| 151 |
+
self.lang_code_to_token = {lang_code: f"__{lang_code}__" for lang_code in fairseq_language_code}
|
| 152 |
+
|
| 153 |
+
kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", [])
|
| 154 |
+
kwargs["additional_special_tokens"] += [
|
| 155 |
+
self.get_lang_token(lang_code)
|
| 156 |
+
for lang_code in fairseq_language_code
|
| 157 |
+
if self.get_lang_token(lang_code) not in kwargs["additional_special_tokens"]
|
| 158 |
+
]
|
| 159 |
+
|
| 160 |
+
super().__init__(
|
| 161 |
+
src_lang=src_lang,
|
| 162 |
+
tgt_lang=tgt_lang,
|
| 163 |
+
bos_token=bos_token,
|
| 164 |
+
eos_token=eos_token,
|
| 165 |
+
sep_token=sep_token,
|
| 166 |
+
unk_token=unk_token,
|
| 167 |
+
pad_token=pad_token,
|
| 168 |
+
language_codes=language_codes,
|
| 169 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 170 |
+
num_madeup_words=num_madeup_words,
|
| 171 |
+
**kwargs,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
self.vocab_file = vocab_file
|
| 175 |
+
self.encoder = load_json(vocab_file)
|
| 176 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 177 |
+
self.spm_file = spm_file
|
| 178 |
+
self.sp_model = load_spm(spm_file, self.sp_model_kwargs)
|
| 179 |
+
|
| 180 |
+
self.encoder_size = len(self.encoder)
|
| 181 |
+
|
| 182 |
+
self.lang_token_to_id = {
|
| 183 |
+
self.get_lang_token(lang_code): self.encoder_size + i for i, lang_code in enumerate(fairseq_language_code)
|
| 184 |
+
}
|
| 185 |
+
self.lang_code_to_id = {lang_code: self.encoder_size + i for i, lang_code in enumerate(fairseq_language_code)}
|
| 186 |
+
self.id_to_lang_token = {v: k for k, v in self.lang_token_to_id.items()}
|
| 187 |
+
|
| 188 |
+
self._src_lang = src_lang if src_lang is not None else "en"
|
| 189 |
+
self.tgt_lang = tgt_lang
|
| 190 |
+
self.cur_lang_id = self.get_lang_id(self._src_lang)
|
| 191 |
+
self.set_src_lang_special_tokens(self._src_lang)
|
| 192 |
+
|
| 193 |
+
self.num_madeup_words = num_madeup_words
|
| 194 |
+
|
| 195 |
+
@property
|
| 196 |
+
def vocab_size(self) -> int:
|
| 197 |
+
return len(self.encoder) + len(self.lang_token_to_id)
|
| 198 |
+
|
| 199 |
+
@property
|
| 200 |
+
def src_lang(self) -> str:
|
| 201 |
+
return self._src_lang
|
| 202 |
+
|
| 203 |
+
@src_lang.setter
|
| 204 |
+
def src_lang(self, new_src_lang: str) -> None:
|
| 205 |
+
self._src_lang = new_src_lang
|
| 206 |
+
self.set_src_lang_special_tokens(self._src_lang)
|
| 207 |
+
|
| 208 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 209 |
+
return self.sp_model.encode(text, out_type=str)
|
| 210 |
+
|
| 211 |
+
def _convert_token_to_id(self, token):
|
| 212 |
+
if token in self.lang_token_to_id:
|
| 213 |
+
return self.lang_token_to_id[token]
|
| 214 |
+
return self.encoder.get(token, self.encoder[self.unk_token])
|
| 215 |
+
|
| 216 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 217 |
+
"""Converts an index (integer) in a token (str) using the decoder."""
|
| 218 |
+
if index in self.id_to_lang_token:
|
| 219 |
+
return self.id_to_lang_token[index]
|
| 220 |
+
return self.decoder.get(index, self.unk_token)
|
| 221 |
+
|
| 222 |
+
def convert_tokens_to_string(self, tokens):
|
| 223 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 224 |
+
current_sub_tokens = []
|
| 225 |
+
out_string = ""
|
| 226 |
+
for token in tokens:
|
| 227 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
| 228 |
+
if token in self.all_special_tokens:
|
| 229 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
| 230 |
+
current_sub_tokens = []
|
| 231 |
+
else:
|
| 232 |
+
current_sub_tokens.append(token)
|
| 233 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
| 234 |
+
return out_string.strip()
|
| 235 |
+
|
| 236 |
+
def get_special_tokens_mask(
|
| 237 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 238 |
+
) -> List[int]:
|
| 239 |
+
"""
|
| 240 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 241 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
token_ids_0 (`List[int]`):
|
| 245 |
+
List of IDs.
|
| 246 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 247 |
+
Optional second list of IDs for sequence pairs.
|
| 248 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 249 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 250 |
+
|
| 251 |
+
Returns:
|
| 252 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 253 |
+
"""
|
| 254 |
+
|
| 255 |
+
if already_has_special_tokens:
|
| 256 |
+
return super().get_special_tokens_mask(
|
| 257 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
prefix_ones = [1] * len(self.prefix_tokens)
|
| 261 |
+
suffix_ones = [1] * len(self.suffix_tokens)
|
| 262 |
+
if token_ids_1 is None:
|
| 263 |
+
return prefix_ones + ([0] * len(token_ids_0)) + suffix_ones
|
| 264 |
+
return prefix_ones + ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones
|
| 265 |
+
|
| 266 |
+
def build_inputs_with_special_tokens(
|
| 267 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 268 |
+
) -> List[int]:
|
| 269 |
+
"""
|
| 270 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 271 |
+
adding special tokens. An MBART sequence has the following format, where `X` represents the sequence:
|
| 272 |
+
|
| 273 |
+
- `input_ids` (for encoder) `X [eos, src_lang_code]`
|
| 274 |
+
- `decoder_input_ids`: (for decoder) `X [eos, tgt_lang_code]`
|
| 275 |
+
|
| 276 |
+
BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a
|
| 277 |
+
separator.
|
| 278 |
+
|
| 279 |
+
Args:
|
| 280 |
+
token_ids_0 (`List[int]`):
|
| 281 |
+
List of IDs to which the special tokens will be added.
|
| 282 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 283 |
+
Optional second list of IDs for sequence pairs.
|
| 284 |
+
|
| 285 |
+
Returns:
|
| 286 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 287 |
+
"""
|
| 288 |
+
if token_ids_1 is None:
|
| 289 |
+
return self.prefix_tokens + token_ids_0 + self.suffix_tokens
|
| 290 |
+
# We don't expect to process pairs, but leave the pair logic for API consistency
|
| 291 |
+
return self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens
|
| 292 |
+
|
| 293 |
+
def get_vocab(self) -> Dict:
|
| 294 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 295 |
+
vocab.update(self.added_tokens_encoder)
|
| 296 |
+
return vocab
|
| 297 |
+
|
| 298 |
+
def __getstate__(self) -> Dict:
|
| 299 |
+
state = self.__dict__.copy()
|
| 300 |
+
state["sp_model"] = None
|
| 301 |
+
return state
|
| 302 |
+
|
| 303 |
+
def __setstate__(self, d: Dict) -> None:
|
| 304 |
+
self.__dict__ = d
|
| 305 |
+
|
| 306 |
+
# for backward compatibility
|
| 307 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 308 |
+
self.sp_model_kwargs = {}
|
| 309 |
+
|
| 310 |
+
self.sp_model = load_spm(self.spm_file, self.sp_model_kwargs)
|
| 311 |
+
|
| 312 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 313 |
+
save_dir = Path(save_directory)
|
| 314 |
+
if not save_dir.is_dir():
|
| 315 |
+
raise OSError(f"{save_directory} should be a directory")
|
| 316 |
+
vocab_save_path = save_dir / (
|
| 317 |
+
(filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"]
|
| 318 |
+
)
|
| 319 |
+
spm_save_path = save_dir / (
|
| 320 |
+
(filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"]
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
save_json(self.encoder, vocab_save_path)
|
| 324 |
+
|
| 325 |
+
if os.path.abspath(self.spm_file) != os.path.abspath(spm_save_path) and os.path.isfile(self.spm_file):
|
| 326 |
+
copyfile(self.spm_file, spm_save_path)
|
| 327 |
+
elif not os.path.isfile(self.spm_file):
|
| 328 |
+
with open(spm_save_path, "wb") as fi:
|
| 329 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 330 |
+
fi.write(content_spiece_model)
|
| 331 |
+
|
| 332 |
+
return (str(vocab_save_path), str(spm_save_path))
|
| 333 |
+
|
| 334 |
+
def prepare_seq2seq_batch(
|
| 335 |
+
self,
|
| 336 |
+
src_texts: List[str],
|
| 337 |
+
src_lang: str = "en",
|
| 338 |
+
tgt_texts: Optional[List[str]] = None,
|
| 339 |
+
tgt_lang: str = "ro",
|
| 340 |
+
**kwargs,
|
| 341 |
+
) -> BatchEncoding:
|
| 342 |
+
self.src_lang = src_lang
|
| 343 |
+
self.tgt_lang = tgt_lang
|
| 344 |
+
self.set_src_lang_special_tokens(self.src_lang)
|
| 345 |
+
return super().prepare_seq2seq_batch(src_texts, tgt_texts, **kwargs)
|
| 346 |
+
|
| 347 |
+
def _build_translation_inputs(self, raw_inputs, src_lang: Optional[str], tgt_lang: Optional[str], **extra_kwargs):
|
| 348 |
+
"""Used by translation pipeline, to prepare inputs for the generate function"""
|
| 349 |
+
if src_lang is None or tgt_lang is None:
|
| 350 |
+
raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model")
|
| 351 |
+
self.src_lang = src_lang
|
| 352 |
+
inputs = self(raw_inputs, add_special_tokens=True, **extra_kwargs)
|
| 353 |
+
tgt_lang_id = self.get_lang_id(tgt_lang)
|
| 354 |
+
inputs["forced_bos_token_id"] = tgt_lang_id
|
| 355 |
+
return inputs
|
| 356 |
+
|
| 357 |
+
def _switch_to_input_mode(self):
|
| 358 |
+
self.set_src_lang_special_tokens(self.src_lang)
|
| 359 |
+
|
| 360 |
+
def _switch_to_target_mode(self):
|
| 361 |
+
self.set_tgt_lang_special_tokens(self.tgt_lang)
|
| 362 |
+
|
| 363 |
+
def set_src_lang_special_tokens(self, src_lang: str) -> None:
|
| 364 |
+
"""Reset the special tokens to the source lang setting. No prefix and suffix=[eos, src_lang_code]."""
|
| 365 |
+
lang_token = self.get_lang_token(src_lang)
|
| 366 |
+
self.cur_lang_id = self.lang_token_to_id[lang_token]
|
| 367 |
+
self.prefix_tokens = [self.cur_lang_id]
|
| 368 |
+
self.suffix_tokens = [self.eos_token_id]
|
| 369 |
+
|
| 370 |
+
def set_tgt_lang_special_tokens(self, tgt_lang: str) -> None:
|
| 371 |
+
"""Reset the special tokens to the target language setting. No prefix and suffix=[eos, tgt_lang_code]."""
|
| 372 |
+
lang_token = self.get_lang_token(tgt_lang)
|
| 373 |
+
self.cur_lang_id = self.lang_token_to_id[lang_token]
|
| 374 |
+
self.prefix_tokens = [self.cur_lang_id]
|
| 375 |
+
self.suffix_tokens = [self.eos_token_id]
|
| 376 |
+
|
| 377 |
+
def get_lang_token(self, lang: str) -> str:
|
| 378 |
+
return self.lang_code_to_token[lang]
|
| 379 |
+
|
| 380 |
+
def get_lang_id(self, lang: str) -> int:
|
| 381 |
+
lang_token = self.get_lang_token(lang)
|
| 382 |
+
return self.lang_token_to_id[lang_token]
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def load_spm(path: str, sp_model_kwargs: Dict[str, Any]) -> sentencepiece.SentencePieceProcessor:
|
| 386 |
+
spm = sentencepiece.SentencePieceProcessor(**sp_model_kwargs)
|
| 387 |
+
spm.Load(str(path))
|
| 388 |
+
return spm
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def load_json(path: str) -> Union[Dict, List]:
|
| 392 |
+
with open(path, "r") as f:
|
| 393 |
+
return json.load(f)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def save_json(data, path: str) -> None:
|
| 397 |
+
with open(path, "w") as f:
|
| 398 |
+
json.dump(data, f, indent=2)
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__init__.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_import_structure = {
|
| 20 |
+
"configuration_mobilenet_v2": [
|
| 21 |
+
"MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
| 22 |
+
"MobileNetV2Config",
|
| 23 |
+
"MobileNetV2OnnxConfig",
|
| 24 |
+
],
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
if not is_vision_available():
|
| 29 |
+
raise OptionalDependencyNotAvailable()
|
| 30 |
+
except OptionalDependencyNotAvailable:
|
| 31 |
+
pass
|
| 32 |
+
else:
|
| 33 |
+
_import_structure["feature_extraction_mobilenet_v2"] = ["MobileNetV2FeatureExtractor"]
|
| 34 |
+
_import_structure["image_processing_mobilenet_v2"] = ["MobileNetV2ImageProcessor"]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
if not is_torch_available():
|
| 39 |
+
raise OptionalDependencyNotAvailable()
|
| 40 |
+
except OptionalDependencyNotAvailable:
|
| 41 |
+
pass
|
| 42 |
+
else:
|
| 43 |
+
_import_structure["modeling_mobilenet_v2"] = [
|
| 44 |
+
"MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 45 |
+
"MobileNetV2ForImageClassification",
|
| 46 |
+
"MobileNetV2ForSemanticSegmentation",
|
| 47 |
+
"MobileNetV2Model",
|
| 48 |
+
"MobileNetV2PreTrainedModel",
|
| 49 |
+
"load_tf_weights_in_mobilenet_v2",
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if TYPE_CHECKING:
|
| 54 |
+
from .configuration_mobilenet_v2 import (
|
| 55 |
+
MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
| 56 |
+
MobileNetV2Config,
|
| 57 |
+
MobileNetV2OnnxConfig,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
if not is_vision_available():
|
| 62 |
+
raise OptionalDependencyNotAvailable()
|
| 63 |
+
except OptionalDependencyNotAvailable:
|
| 64 |
+
pass
|
| 65 |
+
else:
|
| 66 |
+
from .feature_extraction_mobilenet_v2 import MobileNetV2FeatureExtractor
|
| 67 |
+
from .image_processing_mobilenet_v2 import MobileNetV2ImageProcessor
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
if not is_torch_available():
|
| 71 |
+
raise OptionalDependencyNotAvailable()
|
| 72 |
+
except OptionalDependencyNotAvailable:
|
| 73 |
+
pass
|
| 74 |
+
else:
|
| 75 |
+
from .modeling_mobilenet_v2 import (
|
| 76 |
+
MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 77 |
+
MobileNetV2ForImageClassification,
|
| 78 |
+
MobileNetV2ForSemanticSegmentation,
|
| 79 |
+
MobileNetV2Model,
|
| 80 |
+
MobileNetV2PreTrainedModel,
|
| 81 |
+
load_tf_weights_in_mobilenet_v2,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
else:
|
| 86 |
+
import sys
|
| 87 |
+
|
| 88 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.41 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/configuration_mobilenet_v2.cpython-310.pyc
ADDED
|
Binary file (6.91 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/convert_original_tf_checkpoint_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (4.89 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/feature_extraction_mobilenet_v2.cpython-310.pyc
ADDED
|
Binary file (1.05 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/image_processing_mobilenet_v2.cpython-310.pyc
ADDED
|
Binary file (14.7 kB). View file
|
|
|
evalkit_tf433/lib/python3.10/site-packages/transformers/models/mobilenet_v2/__pycache__/modeling_mobilenet_v2.cpython-310.pyc
ADDED
|
Binary file (22.1 kB). View file
|
|
|