Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/benchmark/benchmark_tf.py +298 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/benchmark/benchmark_utils.py +913 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/add_new_model.py +259 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/add_new_model_like.py +1710 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/download.py +46 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/env.py +104 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/lfs.py +226 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/run.py +110 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/serving.py +228 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/transformers_cli.py +59 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/user.py +197 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/data/test_generation_utils.py +99 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/generation/__init__.py +272 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/kernels/rwkv/wkv_op.cpp +66 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/modelcard.py +903 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/modeling_flax_pytorch_utils.py +421 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/modeling_flax_utils.py +1170 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/modeling_tf_pytorch_utils.py +578 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/__init__.py +179 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/configuration_albert.py +172 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/convert_albert_original_tf_checkpoint_to_pytorch.py +63 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/modeling_albert.py +1403 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/modeling_flax_albert.py +1119 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/modeling_tf_albert.py +1487 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/tokenization_albert.py +369 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/tokenization_albert_fast.py +242 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/align/__init__.py +73 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/align/configuration_align.py +398 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/align/convert_align_tf_to_hf.py +387 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/align/modeling_align.py +1642 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/align/processing_align.py +122 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/altclip/__init__.py +71 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/altclip/configuration_altclip.py +405 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/altclip/modeling_altclip.py +1712 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/altclip/processing_altclip.py +130 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/audio_spectrogram_transformer/__init__.py +78 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py +126 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/audio_spectrogram_transformer/convert_audio_spectrogram_transformer_original_to_pytorch.py +279 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.py +197 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py +627 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/__init__.py +359 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/auto_factory.py +670 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/configuration_auto.py +970 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/feature_extraction_auto.py +364 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/image_processing_auto.py +388 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/modeling_auto.py +1358 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/modeling_flax_auto.py +369 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/modeling_tf_auto.py +668 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/processing_auto.py +310 -0
- SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/tokenization_auto.py +767 -0
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/benchmark/benchmark_tf.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""
|
| 17 |
+
Benchmarking the library on inference and training in PyTorch.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
import random
|
| 22 |
+
import timeit
|
| 23 |
+
from functools import wraps
|
| 24 |
+
from typing import Callable, Optional
|
| 25 |
+
|
| 26 |
+
from ..configuration_utils import PretrainedConfig
|
| 27 |
+
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
|
| 28 |
+
from ..utils import is_py3nvml_available, is_tf_available, logging
|
| 29 |
+
from .benchmark_utils import (
|
| 30 |
+
Benchmark,
|
| 31 |
+
Memory,
|
| 32 |
+
MemorySummary,
|
| 33 |
+
measure_peak_memory_cpu,
|
| 34 |
+
start_memory_tracing,
|
| 35 |
+
stop_memory_tracing,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if is_tf_available():
|
| 40 |
+
import tensorflow as tf
|
| 41 |
+
from tensorflow.python.framework.errors_impl import ResourceExhaustedError
|
| 42 |
+
|
| 43 |
+
from .benchmark_args_tf import TensorFlowBenchmarkArguments
|
| 44 |
+
|
| 45 |
+
if is_py3nvml_available():
|
| 46 |
+
import py3nvml.py3nvml as nvml
|
| 47 |
+
|
| 48 |
+
logger = logging.get_logger(__name__)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def run_with_tf_optimizations(do_eager_mode: bool, use_xla: bool):
|
| 52 |
+
def run_func(func):
|
| 53 |
+
@wraps(func)
|
| 54 |
+
def run_in_eager_mode(*args, **kwargs):
|
| 55 |
+
return func(*args, **kwargs)
|
| 56 |
+
|
| 57 |
+
@wraps(func)
|
| 58 |
+
@tf.function(experimental_compile=use_xla)
|
| 59 |
+
def run_in_graph_mode(*args, **kwargs):
|
| 60 |
+
return func(*args, **kwargs)
|
| 61 |
+
|
| 62 |
+
if do_eager_mode is True:
|
| 63 |
+
assert (
|
| 64 |
+
use_xla is False
|
| 65 |
+
), "Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`."
|
| 66 |
+
return run_in_eager_mode
|
| 67 |
+
else:
|
| 68 |
+
return run_in_graph_mode
|
| 69 |
+
|
| 70 |
+
return run_func
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def random_input_ids(batch_size: int, sequence_length: int, vocab_size: int) -> ["tf.Tensor"]:
|
| 74 |
+
rng = random.Random()
|
| 75 |
+
values = [rng.randint(0, vocab_size - 1) for i in range(batch_size * sequence_length)]
|
| 76 |
+
return tf.constant(values, shape=(batch_size, sequence_length), dtype=tf.int32)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class TensorFlowBenchmark(Benchmark):
|
| 80 |
+
args: TensorFlowBenchmarkArguments
|
| 81 |
+
configs: PretrainedConfig
|
| 82 |
+
framework: str = "TensorFlow"
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def framework_version(self):
|
| 86 |
+
return tf.__version__
|
| 87 |
+
|
| 88 |
+
def _inference_speed(self, model_name: str, batch_size: int, sequence_length: int) -> float:
|
| 89 |
+
# initialize GPU on separate process
|
| 90 |
+
strategy = self.args.strategy
|
| 91 |
+
assert strategy is not None, "A device strategy has to be initialized before using TensorFlow."
|
| 92 |
+
_inference = self._prepare_inference_func(model_name, batch_size, sequence_length)
|
| 93 |
+
return self._measure_speed(_inference)
|
| 94 |
+
|
| 95 |
+
def _train_speed(self, model_name: str, batch_size: int, sequence_length: int) -> float:
|
| 96 |
+
strategy = self.args.strategy
|
| 97 |
+
assert strategy is not None, "A device strategy has to be initialized before using TensorFlow."
|
| 98 |
+
_train = self._prepare_train_func(model_name, batch_size, sequence_length)
|
| 99 |
+
return self._measure_speed(_train)
|
| 100 |
+
|
| 101 |
+
def _inference_memory(
|
| 102 |
+
self, model_name: str, batch_size: int, sequence_length: int
|
| 103 |
+
) -> [Memory, Optional[MemorySummary]]:
|
| 104 |
+
# initialize GPU on separate process
|
| 105 |
+
if self.args.is_gpu:
|
| 106 |
+
tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx], True)
|
| 107 |
+
strategy = self.args.strategy
|
| 108 |
+
assert strategy is not None, "A device strategy has to be initialized before using TensorFlow."
|
| 109 |
+
_inference = self._prepare_inference_func(model_name, batch_size, sequence_length)
|
| 110 |
+
return self._measure_memory(_inference)
|
| 111 |
+
|
| 112 |
+
def _train_memory(
|
| 113 |
+
self, model_name: str, batch_size: int, sequence_length: int
|
| 114 |
+
) -> [Memory, Optional[MemorySummary]]:
|
| 115 |
+
if self.args.is_gpu:
|
| 116 |
+
tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx], True)
|
| 117 |
+
strategy = self.args.strategy
|
| 118 |
+
assert strategy is not None, "A device strategy has to be initialized before using TensorFlow."
|
| 119 |
+
|
| 120 |
+
_train = self._prepare_train_func(model_name, batch_size, sequence_length)
|
| 121 |
+
return self._measure_memory(_train)
|
| 122 |
+
|
| 123 |
+
def _prepare_inference_func(self, model_name: str, batch_size: int, sequence_length: int) -> Callable[[], None]:
|
| 124 |
+
config = self.config_dict[model_name]
|
| 125 |
+
|
| 126 |
+
if self.args.fp16:
|
| 127 |
+
raise NotImplementedError("Mixed precision is currently not supported.")
|
| 128 |
+
|
| 129 |
+
has_model_class_in_config = (
|
| 130 |
+
hasattr(config, "architectures")
|
| 131 |
+
and isinstance(config.architectures, list)
|
| 132 |
+
and len(config.architectures) > 0
|
| 133 |
+
)
|
| 134 |
+
if not self.args.only_pretrain_model and has_model_class_in_config:
|
| 135 |
+
try:
|
| 136 |
+
model_class = "TF" + config.architectures[0] # prepend 'TF' for tensorflow model
|
| 137 |
+
transformers_module = __import__("transformers", fromlist=[model_class])
|
| 138 |
+
model_cls = getattr(transformers_module, model_class)
|
| 139 |
+
model = model_cls(config)
|
| 140 |
+
except ImportError:
|
| 141 |
+
raise ImportError(
|
| 142 |
+
f"{model_class} does not exist. If you just want to test the pretrained model, you might want to"
|
| 143 |
+
" set `--only_pretrain_model` or `args.only_pretrain_model=True`."
|
| 144 |
+
)
|
| 145 |
+
else:
|
| 146 |
+
model = TF_MODEL_MAPPING[config.__class__](config)
|
| 147 |
+
|
| 148 |
+
# encoder-decoder has vocab size saved differently
|
| 149 |
+
vocab_size = config.vocab_size if hasattr(config, "vocab_size") else config.encoder.vocab_size
|
| 150 |
+
input_ids = random_input_ids(batch_size, sequence_length, vocab_size)
|
| 151 |
+
|
| 152 |
+
@run_with_tf_optimizations(self.args.eager_mode, self.args.use_xla)
|
| 153 |
+
def encoder_decoder_forward():
|
| 154 |
+
return model(input_ids, decoder_input_ids=input_ids, training=False)
|
| 155 |
+
|
| 156 |
+
@run_with_tf_optimizations(self.args.eager_mode, self.args.use_xla)
|
| 157 |
+
def encoder_forward():
|
| 158 |
+
return model(input_ids, training=False)
|
| 159 |
+
|
| 160 |
+
_inference = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward
|
| 161 |
+
|
| 162 |
+
return _inference
|
| 163 |
+
|
| 164 |
+
def _prepare_train_func(self, model_name: str, batch_size: int, sequence_length: int) -> Callable[[], None]:
|
| 165 |
+
config = self.config_dict[model_name]
|
| 166 |
+
|
| 167 |
+
assert (
|
| 168 |
+
self.args.eager_mode is False
|
| 169 |
+
), "Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`."
|
| 170 |
+
|
| 171 |
+
if self.args.fp16:
|
| 172 |
+
raise NotImplementedError("Mixed precision is currently not supported.")
|
| 173 |
+
|
| 174 |
+
has_model_class_in_config = (
|
| 175 |
+
hasattr(config, "architectures")
|
| 176 |
+
and isinstance(config.architectures, list)
|
| 177 |
+
and len(config.architectures) > 0
|
| 178 |
+
)
|
| 179 |
+
if not self.args.only_pretrain_model and has_model_class_in_config:
|
| 180 |
+
try:
|
| 181 |
+
model_class = "TF" + config.architectures[0] # prepend 'TF' for tensorflow model
|
| 182 |
+
transformers_module = __import__("transformers", fromlist=[model_class])
|
| 183 |
+
model_cls = getattr(transformers_module, model_class)
|
| 184 |
+
model = model_cls(config)
|
| 185 |
+
except ImportError:
|
| 186 |
+
raise ImportError(
|
| 187 |
+
f"{model_class} does not exist. If you just want to test the pretrained model, you might want to"
|
| 188 |
+
" set `--only_pretrain_model` or `args.only_pretrain_model=True`."
|
| 189 |
+
)
|
| 190 |
+
else:
|
| 191 |
+
model = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](config)
|
| 192 |
+
|
| 193 |
+
# encoder-decoder has vocab size saved differently
|
| 194 |
+
vocab_size = config.vocab_size if hasattr(config, "vocab_size") else config.encoder.vocab_size
|
| 195 |
+
input_ids = random_input_ids(batch_size, sequence_length, vocab_size)
|
| 196 |
+
|
| 197 |
+
@run_with_tf_optimizations(self.args.eager_mode, self.args.use_xla)
|
| 198 |
+
def encoder_decoder_train():
|
| 199 |
+
loss = model(input_ids, decoder_input_ids=input_ids, labels=input_ids, training=True)[0]
|
| 200 |
+
gradients = tf.gradients(loss, model.trainable_variables)
|
| 201 |
+
return gradients
|
| 202 |
+
|
| 203 |
+
@run_with_tf_optimizations(self.args.eager_mode, self.args.use_xla)
|
| 204 |
+
def encoder_train():
|
| 205 |
+
loss = model(input_ids, labels=input_ids, training=True)[0]
|
| 206 |
+
gradients = tf.gradients(loss, model.trainable_variables)
|
| 207 |
+
return gradients
|
| 208 |
+
|
| 209 |
+
_train = encoder_decoder_train if config.is_encoder_decoder else encoder_train
|
| 210 |
+
|
| 211 |
+
return _train
|
| 212 |
+
|
| 213 |
+
def _measure_speed(self, func) -> float:
|
| 214 |
+
with self.args.strategy.scope():
|
| 215 |
+
try:
|
| 216 |
+
if self.args.is_tpu or self.args.use_xla:
|
| 217 |
+
# run additional 10 times to stabilize compilation for tpu
|
| 218 |
+
logger.info("Do inference on TPU. Running model 5 times to stabilize compilation")
|
| 219 |
+
timeit.repeat(func, repeat=1, number=5)
|
| 220 |
+
|
| 221 |
+
# as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
|
| 222 |
+
runtimes = timeit.repeat(
|
| 223 |
+
func,
|
| 224 |
+
repeat=self.args.repeat,
|
| 225 |
+
number=10,
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
return min(runtimes) / 10.0
|
| 229 |
+
except ResourceExhaustedError as e:
|
| 230 |
+
self.print_fn(f"Doesn't fit on GPU. {e}")
|
| 231 |
+
|
| 232 |
+
def _measure_memory(self, func: Callable[[], None]) -> [Memory, MemorySummary]:
|
| 233 |
+
logger.info(
|
| 234 |
+
"Note that TensorFlow allocates more memory than "
|
| 235 |
+
"it might need to speed up computation. "
|
| 236 |
+
"The memory reported here corresponds to the memory "
|
| 237 |
+
"reported by `nvidia-smi`, which can vary depending "
|
| 238 |
+
"on total available memory on the GPU that is used."
|
| 239 |
+
)
|
| 240 |
+
with self.args.strategy.scope():
|
| 241 |
+
try:
|
| 242 |
+
if self.args.trace_memory_line_by_line:
|
| 243 |
+
assert self.args.eager_mode, (
|
| 244 |
+
"`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory"
|
| 245 |
+
" consumption line by line."
|
| 246 |
+
)
|
| 247 |
+
trace = start_memory_tracing("transformers")
|
| 248 |
+
|
| 249 |
+
if self.args.is_tpu:
|
| 250 |
+
# tpu
|
| 251 |
+
raise NotImplementedError(
|
| 252 |
+
"Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking"
|
| 253 |
+
" with `args.memory=False`"
|
| 254 |
+
)
|
| 255 |
+
elif self.args.is_gpu:
|
| 256 |
+
# gpu
|
| 257 |
+
if not is_py3nvml_available():
|
| 258 |
+
logger.warning(
|
| 259 |
+
"py3nvml not installed, we won't log GPU memory usage. "
|
| 260 |
+
"Install py3nvml (pip install py3nvml) to log information about GPU."
|
| 261 |
+
)
|
| 262 |
+
memory = "N/A"
|
| 263 |
+
else:
|
| 264 |
+
logger.info(
|
| 265 |
+
"Measuring total GPU usage on GPU device. Make sure to not have additional processes"
|
| 266 |
+
" running on the same GPU."
|
| 267 |
+
)
|
| 268 |
+
# init nvml
|
| 269 |
+
nvml.nvmlInit()
|
| 270 |
+
func()
|
| 271 |
+
handle = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx)
|
| 272 |
+
meminfo = nvml.nvmlDeviceGetMemoryInfo(handle)
|
| 273 |
+
max_bytes_in_use = meminfo.used
|
| 274 |
+
memory = Memory(max_bytes_in_use)
|
| 275 |
+
# shutdown nvml
|
| 276 |
+
nvml.nvmlShutdown()
|
| 277 |
+
else:
|
| 278 |
+
# cpu
|
| 279 |
+
if self.args.trace_memory_line_by_line:
|
| 280 |
+
logger.info(
|
| 281 |
+
"When enabling line by line tracing, the max peak memory for CPU is inaccurate in"
|
| 282 |
+
" TensorFlow."
|
| 283 |
+
)
|
| 284 |
+
memory = None
|
| 285 |
+
else:
|
| 286 |
+
memory_bytes = measure_peak_memory_cpu(func)
|
| 287 |
+
memory = Memory(memory_bytes) if isinstance(memory_bytes, int) else memory_bytes
|
| 288 |
+
if self.args.trace_memory_line_by_line:
|
| 289 |
+
summary = stop_memory_tracing(trace)
|
| 290 |
+
if memory is None:
|
| 291 |
+
memory = summary.total
|
| 292 |
+
else:
|
| 293 |
+
summary = None
|
| 294 |
+
|
| 295 |
+
return memory, summary
|
| 296 |
+
except ResourceExhaustedError as e:
|
| 297 |
+
self.print_fn(f"Doesn't fit on GPU. {e}")
|
| 298 |
+
return "N/A", None
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/benchmark/benchmark_utils.py
ADDED
|
@@ -0,0 +1,913 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
|
| 2 |
+
|
| 3 |
+
# Copyright 2020 The HuggingFace Team and the AllenNLP authors. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""
|
| 17 |
+
Utilities for working with the local dataset cache.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import copy
|
| 21 |
+
import csv
|
| 22 |
+
import linecache
|
| 23 |
+
import os
|
| 24 |
+
import platform
|
| 25 |
+
import sys
|
| 26 |
+
import warnings
|
| 27 |
+
from abc import ABC, abstractmethod
|
| 28 |
+
from collections import defaultdict, namedtuple
|
| 29 |
+
from datetime import datetime
|
| 30 |
+
from multiprocessing import Pipe, Process, Queue
|
| 31 |
+
from multiprocessing.connection import Connection
|
| 32 |
+
from typing import Callable, Iterable, List, NamedTuple, Optional, Union
|
| 33 |
+
|
| 34 |
+
from .. import AutoConfig, PretrainedConfig
|
| 35 |
+
from .. import __version__ as version
|
| 36 |
+
from ..utils import is_psutil_available, is_py3nvml_available, is_tf_available, is_torch_available, logging
|
| 37 |
+
from .benchmark_args_utils import BenchmarkArguments
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if is_torch_available():
|
| 41 |
+
from torch.cuda import empty_cache as torch_empty_cache
|
| 42 |
+
|
| 43 |
+
if is_tf_available():
|
| 44 |
+
from tensorflow.python.eager import context as tf_context
|
| 45 |
+
|
| 46 |
+
if is_psutil_available():
|
| 47 |
+
import psutil
|
| 48 |
+
|
| 49 |
+
if is_py3nvml_available():
|
| 50 |
+
import py3nvml.py3nvml as nvml
|
| 51 |
+
|
| 52 |
+
if platform.system() == "Windows":
|
| 53 |
+
from signal import CTRL_C_EVENT as SIGKILL
|
| 54 |
+
else:
|
| 55 |
+
from signal import SIGKILL
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
_is_memory_tracing_enabled = False
|
| 62 |
+
|
| 63 |
+
BenchmarkOutput = namedtuple(
|
| 64 |
+
"BenchmarkOutput",
|
| 65 |
+
[
|
| 66 |
+
"time_inference_result",
|
| 67 |
+
"memory_inference_result",
|
| 68 |
+
"time_train_result",
|
| 69 |
+
"memory_train_result",
|
| 70 |
+
"inference_summary",
|
| 71 |
+
"train_summary",
|
| 72 |
+
],
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def separate_process_wrapper_fn(func: Callable[[], None], do_multi_processing: bool) -> Callable[[], None]:
|
| 77 |
+
"""
|
| 78 |
+
This function wraps another function into its own separated process. In order to ensure accurate memory
|
| 79 |
+
measurements it is important that the function is executed in a separate process
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
- `func`: (`callable`): function() -> ... generic function which will be executed in its own separate process
|
| 83 |
+
- `do_multi_processing`: (`bool`) Whether to run function on separate process or not
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def multi_process_func(*args, **kwargs):
|
| 87 |
+
# run function in an individual
|
| 88 |
+
# process to get correct memory
|
| 89 |
+
def wrapper_func(queue: Queue, *args):
|
| 90 |
+
try:
|
| 91 |
+
result = func(*args)
|
| 92 |
+
except Exception as e:
|
| 93 |
+
logger.error(e)
|
| 94 |
+
print(e)
|
| 95 |
+
result = "N/A"
|
| 96 |
+
queue.put(result)
|
| 97 |
+
|
| 98 |
+
queue = Queue()
|
| 99 |
+
p = Process(target=wrapper_func, args=[queue] + list(args))
|
| 100 |
+
p.start()
|
| 101 |
+
result = queue.get()
|
| 102 |
+
p.join()
|
| 103 |
+
return result
|
| 104 |
+
|
| 105 |
+
if do_multi_processing:
|
| 106 |
+
logger.info(f"Function {func} is executed in its own process...")
|
| 107 |
+
return multi_process_func
|
| 108 |
+
else:
|
| 109 |
+
return func
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def is_memory_tracing_enabled():
|
| 113 |
+
global _is_memory_tracing_enabled
|
| 114 |
+
return _is_memory_tracing_enabled
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class Frame(NamedTuple):
|
| 118 |
+
"""
|
| 119 |
+
`Frame` is a NamedTuple used to gather the current frame state. `Frame` has the following fields:
|
| 120 |
+
|
| 121 |
+
- 'filename' (string): Name of the file currently executed
|
| 122 |
+
- 'module' (string): Name of the module currently executed
|
| 123 |
+
- 'line_number' (int): Number of the line currently executed
|
| 124 |
+
- 'event' (string): Event that triggered the tracing (default will be "line")
|
| 125 |
+
- 'line_text' (string): Text of the line in the python script
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
filename: str
|
| 129 |
+
module: str
|
| 130 |
+
line_number: int
|
| 131 |
+
event: str
|
| 132 |
+
line_text: str
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class UsedMemoryState(NamedTuple):
|
| 136 |
+
"""
|
| 137 |
+
`UsedMemoryState` are named tuples with the following fields:
|
| 138 |
+
|
| 139 |
+
- 'frame': a `Frame` namedtuple (see below) storing information on the current tracing frame (current file,
|
| 140 |
+
location in current file)
|
| 141 |
+
- 'cpu_memory': CPU RSS memory state *before* executing the line
|
| 142 |
+
- 'gpu_memory': GPU used memory *before* executing the line (sum for all GPUs or for only `gpus_to_trace` if
|
| 143 |
+
provided)
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
frame: Frame
|
| 147 |
+
cpu_memory: int
|
| 148 |
+
gpu_memory: int
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class Memory(NamedTuple):
|
| 152 |
+
"""
|
| 153 |
+
`Memory` NamedTuple have a single field `bytes` and you can get a human readable str of the number of mega bytes by
|
| 154 |
+
calling `__repr__`
|
| 155 |
+
|
| 156 |
+
- `byte` (integer): number of bytes,
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
bytes: int
|
| 160 |
+
|
| 161 |
+
def __repr__(self) -> str:
|
| 162 |
+
return str(bytes_to_mega_bytes(self.bytes))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class MemoryState(NamedTuple):
|
| 166 |
+
"""
|
| 167 |
+
`MemoryState` are namedtuples listing frame + CPU/GPU memory with the following fields:
|
| 168 |
+
|
| 169 |
+
- `frame` (`Frame`): the current frame (see above)
|
| 170 |
+
- `cpu`: CPU memory consumed at during the current frame as a `Memory` named tuple
|
| 171 |
+
- `gpu`: GPU memory consumed at during the current frame as a `Memory` named tuple
|
| 172 |
+
- `cpu_gpu`: CPU + GPU memory consumed at during the current frame as a `Memory` named tuple
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
frame: Frame
|
| 176 |
+
cpu: Memory
|
| 177 |
+
gpu: Memory
|
| 178 |
+
cpu_gpu: Memory
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class MemorySummary(NamedTuple):
|
| 182 |
+
"""
|
| 183 |
+
`MemorySummary` namedtuple otherwise with the fields:
|
| 184 |
+
|
| 185 |
+
- `sequential`: a list of `MemoryState` namedtuple (see below) computed from the provided `memory_trace` by
|
| 186 |
+
subtracting the memory after executing each line from the memory before executing said line.
|
| 187 |
+
- `cumulative`: a list of `MemoryState` namedtuple (see below) with cumulative increase in memory for each line
|
| 188 |
+
obtained by summing repeated memory increase for a line if it's executed several times. The list is sorted
|
| 189 |
+
from the frame with the largest memory consumption to the frame with the smallest (can be negative if memory
|
| 190 |
+
is released)
|
| 191 |
+
- `total`: total memory increase during the full tracing as a `Memory` named tuple (see below). Line with
|
| 192 |
+
memory release (negative consumption) are ignored if `ignore_released_memory` is `True` (default).
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
sequential: List[MemoryState]
|
| 196 |
+
cumulative: List[MemoryState]
|
| 197 |
+
current: List[MemoryState]
|
| 198 |
+
total: Memory
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
MemoryTrace = List[UsedMemoryState]
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def measure_peak_memory_cpu(function: Callable[[], None], interval=0.5, device_idx=None) -> int:
|
| 205 |
+
"""
|
| 206 |
+
measures peak cpu memory consumption of a given `function` running the function for at least interval seconds and
|
| 207 |
+
at most 20 * interval seconds. This function is heavily inspired by: `memory_usage` of the package
|
| 208 |
+
`memory_profiler`:
|
| 209 |
+
https://github.com/pythonprofilers/memory_profiler/blob/895c4ac7a08020d66ae001e24067da6dcea42451/memory_profiler.py#L239
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
- `function`: (`callable`): function() -> ... function without any arguments to measure for which to measure
|
| 213 |
+
the peak memory
|
| 214 |
+
|
| 215 |
+
- `interval`: (`float`, `optional`, defaults to `0.5`) interval in second for which to measure the memory usage
|
| 216 |
+
|
| 217 |
+
- `device_idx`: (`int`, `optional`, defaults to `None`) device id for which to measure gpu usage
|
| 218 |
+
|
| 219 |
+
Returns:
|
| 220 |
+
|
| 221 |
+
- `max_memory`: (`int`) consumed memory peak in Bytes
|
| 222 |
+
"""
|
| 223 |
+
|
| 224 |
+
def get_cpu_memory(process_id: int) -> int:
|
| 225 |
+
"""
|
| 226 |
+
measures current cpu memory usage of a given `process_id`
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
- `process_id`: (`int`) process_id for which to measure memory
|
| 230 |
+
|
| 231 |
+
Returns
|
| 232 |
+
|
| 233 |
+
- `memory`: (`int`) consumed memory in Bytes
|
| 234 |
+
"""
|
| 235 |
+
process = psutil.Process(process_id)
|
| 236 |
+
try:
|
| 237 |
+
meminfo_attr = "memory_info" if hasattr(process, "memory_info") else "get_memory_info"
|
| 238 |
+
memory = getattr(process, meminfo_attr)()[0]
|
| 239 |
+
except psutil.AccessDenied:
|
| 240 |
+
raise ValueError("Error with Psutil.")
|
| 241 |
+
return memory
|
| 242 |
+
|
| 243 |
+
if not is_psutil_available():
|
| 244 |
+
logger.warning(
|
| 245 |
+
"Psutil not installed, we won't log CPU memory usage. "
|
| 246 |
+
"Install Psutil (pip install psutil) to use CPU memory tracing."
|
| 247 |
+
)
|
| 248 |
+
max_memory = "N/A"
|
| 249 |
+
else:
|
| 250 |
+
|
| 251 |
+
class MemoryMeasureProcess(Process):
|
| 252 |
+
|
| 253 |
+
"""
|
| 254 |
+
`MemoryMeasureProcess` inherits from `Process` and overwrites its `run()` method. Used to measure the
|
| 255 |
+
memory usage of a process
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
def __init__(self, process_id: int, child_connection: Connection, interval: float):
|
| 259 |
+
super().__init__()
|
| 260 |
+
self.process_id = process_id
|
| 261 |
+
self.interval = interval
|
| 262 |
+
self.connection = child_connection
|
| 263 |
+
self.num_measurements = 1
|
| 264 |
+
self.mem_usage = get_cpu_memory(self.process_id)
|
| 265 |
+
|
| 266 |
+
def run(self):
|
| 267 |
+
self.connection.send(0)
|
| 268 |
+
stop = False
|
| 269 |
+
while True:
|
| 270 |
+
self.mem_usage = max(self.mem_usage, get_cpu_memory(self.process_id))
|
| 271 |
+
self.num_measurements += 1
|
| 272 |
+
|
| 273 |
+
if stop:
|
| 274 |
+
break
|
| 275 |
+
|
| 276 |
+
stop = self.connection.poll(self.interval)
|
| 277 |
+
|
| 278 |
+
# send results to parent pipe
|
| 279 |
+
self.connection.send(self.mem_usage)
|
| 280 |
+
self.connection.send(self.num_measurements)
|
| 281 |
+
|
| 282 |
+
while True:
|
| 283 |
+
# create child, parent connection
|
| 284 |
+
child_connection, parent_connection = Pipe()
|
| 285 |
+
|
| 286 |
+
# instantiate process
|
| 287 |
+
mem_process = MemoryMeasureProcess(os.getpid(), child_connection, interval)
|
| 288 |
+
mem_process.start()
|
| 289 |
+
|
| 290 |
+
# wait until we get memory
|
| 291 |
+
parent_connection.recv()
|
| 292 |
+
|
| 293 |
+
try:
|
| 294 |
+
# execute function
|
| 295 |
+
function()
|
| 296 |
+
|
| 297 |
+
# start parent connection
|
| 298 |
+
parent_connection.send(0)
|
| 299 |
+
|
| 300 |
+
# receive memory and num measurements
|
| 301 |
+
max_memory = parent_connection.recv()
|
| 302 |
+
num_measurements = parent_connection.recv()
|
| 303 |
+
except Exception:
|
| 304 |
+
# kill process in a clean way
|
| 305 |
+
parent = psutil.Process(os.getpid())
|
| 306 |
+
for child in parent.children(recursive=True):
|
| 307 |
+
os.kill(child.pid, SIGKILL)
|
| 308 |
+
mem_process.join(0)
|
| 309 |
+
raise RuntimeError("Process killed. Error in Process")
|
| 310 |
+
|
| 311 |
+
# run process at least 20 * interval or until it finishes
|
| 312 |
+
mem_process.join(20 * interval)
|
| 313 |
+
|
| 314 |
+
if (num_measurements > 4) or (interval < 1e-6):
|
| 315 |
+
break
|
| 316 |
+
|
| 317 |
+
# reduce interval
|
| 318 |
+
interval /= 10
|
| 319 |
+
|
| 320 |
+
return max_memory
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def start_memory_tracing(
|
| 324 |
+
modules_to_trace: Optional[Union[str, Iterable[str]]] = None,
|
| 325 |
+
modules_not_to_trace: Optional[Union[str, Iterable[str]]] = None,
|
| 326 |
+
events_to_trace: str = "line",
|
| 327 |
+
gpus_to_trace: Optional[List[int]] = None,
|
| 328 |
+
) -> MemoryTrace:
|
| 329 |
+
"""
|
| 330 |
+
Setup line-by-line tracing to record rss mem (RAM) at each line of a module or sub-module. See `./benchmark.py` for
|
| 331 |
+
usage examples. Current memory consumption is returned using psutil and in particular is the RSS memory "Resident
|
| 332 |
+
Set Size” (the non-swapped physical memory the process is using). See
|
| 333 |
+
https://psutil.readthedocs.io/en/latest/#psutil.Process.memory_info
|
| 334 |
+
|
| 335 |
+
Args:
|
| 336 |
+
- `modules_to_trace`: (None, string, list/tuple of string) if None, all events are recorded if string or list
|
| 337 |
+
of strings: only events from the listed module/sub-module will be recorded (e.g. 'fairseq' or
|
| 338 |
+
'transformers.models.gpt2.modeling_gpt2')
|
| 339 |
+
- `modules_not_to_trace`: (None, string, list/tuple of string) if None, no module is avoided if string or list
|
| 340 |
+
of strings: events from the listed module/sub-module will not be recorded (e.g. 'torch')
|
| 341 |
+
- `events_to_trace`: string or list of string of events to be recorded (see official python doc for
|
| 342 |
+
`sys.settrace` for the list of events) default to line
|
| 343 |
+
- `gpus_to_trace`: (optional list, default None) list of GPUs to trace. Default to tracing all GPUs
|
| 344 |
+
|
| 345 |
+
Return:
|
| 346 |
+
|
| 347 |
+
- `memory_trace` is a list of `UsedMemoryState` for each event (default each line of the traced script).
|
| 348 |
+
|
| 349 |
+
- `UsedMemoryState` are named tuples with the following fields:
|
| 350 |
+
|
| 351 |
+
- 'frame': a `Frame` namedtuple (see below) storing information on the current tracing frame (current
|
| 352 |
+
file, location in current file)
|
| 353 |
+
- 'cpu_memory': CPU RSS memory state *before* executing the line
|
| 354 |
+
- 'gpu_memory': GPU used memory *before* executing the line (sum for all GPUs or for only
|
| 355 |
+
`gpus_to_trace` if provided)
|
| 356 |
+
|
| 357 |
+
`Frame` is a namedtuple used by `UsedMemoryState` to list the current frame state. `Frame` has the following
|
| 358 |
+
fields: - 'filename' (string): Name of the file currently executed - 'module' (string): Name of the module
|
| 359 |
+
currently executed - 'line_number' (int): Number of the line currently executed - 'event' (string): Event that
|
| 360 |
+
triggered the tracing (default will be "line") - 'line_text' (string): Text of the line in the python script
|
| 361 |
+
|
| 362 |
+
"""
|
| 363 |
+
if is_psutil_available():
|
| 364 |
+
process = psutil.Process(os.getpid())
|
| 365 |
+
else:
|
| 366 |
+
logger.warning(
|
| 367 |
+
"Psutil not installed, we won't log CPU memory usage. "
|
| 368 |
+
"Install psutil (pip install psutil) to use CPU memory tracing."
|
| 369 |
+
)
|
| 370 |
+
process = None
|
| 371 |
+
|
| 372 |
+
if is_py3nvml_available():
|
| 373 |
+
try:
|
| 374 |
+
nvml.nvmlInit()
|
| 375 |
+
devices = list(range(nvml.nvmlDeviceGetCount())) if gpus_to_trace is None else gpus_to_trace
|
| 376 |
+
nvml.nvmlShutdown()
|
| 377 |
+
except (OSError, nvml.NVMLError):
|
| 378 |
+
logger.warning("Error while initializing communication with GPU. We won't perform GPU memory tracing.")
|
| 379 |
+
log_gpu = False
|
| 380 |
+
else:
|
| 381 |
+
log_gpu = is_torch_available() or is_tf_available()
|
| 382 |
+
else:
|
| 383 |
+
logger.warning(
|
| 384 |
+
"py3nvml not installed, we won't log GPU memory usage. "
|
| 385 |
+
"Install py3nvml (pip install py3nvml) to use GPU memory tracing."
|
| 386 |
+
)
|
| 387 |
+
log_gpu = False
|
| 388 |
+
|
| 389 |
+
memory_trace = []
|
| 390 |
+
|
| 391 |
+
def traceit(frame, event, args):
|
| 392 |
+
"""
|
| 393 |
+
Tracing method executed before running each line in a module or sub-module Record memory allocated in a list
|
| 394 |
+
with debugging information
|
| 395 |
+
"""
|
| 396 |
+
global _is_memory_tracing_enabled
|
| 397 |
+
|
| 398 |
+
if not _is_memory_tracing_enabled:
|
| 399 |
+
return traceit
|
| 400 |
+
|
| 401 |
+
# Filter events
|
| 402 |
+
if events_to_trace is not None:
|
| 403 |
+
if isinstance(events_to_trace, str) and event != events_to_trace:
|
| 404 |
+
return traceit
|
| 405 |
+
elif isinstance(events_to_trace, (list, tuple)) and event not in events_to_trace:
|
| 406 |
+
return traceit
|
| 407 |
+
|
| 408 |
+
if "__name__" not in frame.f_globals:
|
| 409 |
+
return traceit
|
| 410 |
+
|
| 411 |
+
# Filter modules
|
| 412 |
+
name = frame.f_globals["__name__"]
|
| 413 |
+
if not isinstance(name, str):
|
| 414 |
+
return traceit
|
| 415 |
+
else:
|
| 416 |
+
# Filter whitelist of modules to trace
|
| 417 |
+
if modules_to_trace is not None:
|
| 418 |
+
if isinstance(modules_to_trace, str) and modules_to_trace not in name:
|
| 419 |
+
return traceit
|
| 420 |
+
elif isinstance(modules_to_trace, (list, tuple)) and all(m not in name for m in modules_to_trace):
|
| 421 |
+
return traceit
|
| 422 |
+
|
| 423 |
+
# Filter blacklist of modules not to trace
|
| 424 |
+
if modules_not_to_trace is not None:
|
| 425 |
+
if isinstance(modules_not_to_trace, str) and modules_not_to_trace in name:
|
| 426 |
+
return traceit
|
| 427 |
+
elif isinstance(modules_not_to_trace, (list, tuple)) and any(m in name for m in modules_not_to_trace):
|
| 428 |
+
return traceit
|
| 429 |
+
|
| 430 |
+
# Record current tracing state (file, location in file...)
|
| 431 |
+
lineno = frame.f_lineno
|
| 432 |
+
filename = frame.f_globals["__file__"]
|
| 433 |
+
if filename.endswith(".pyc") or filename.endswith(".pyo"):
|
| 434 |
+
filename = filename[:-1]
|
| 435 |
+
line = linecache.getline(filename, lineno).rstrip()
|
| 436 |
+
traced_state = Frame(filename, name, lineno, event, line)
|
| 437 |
+
|
| 438 |
+
# Record current memory state (rss memory) and compute difference with previous memory state
|
| 439 |
+
cpu_mem = 0
|
| 440 |
+
if process is not None:
|
| 441 |
+
mem = process.memory_info()
|
| 442 |
+
cpu_mem = mem.rss
|
| 443 |
+
|
| 444 |
+
gpu_mem = 0
|
| 445 |
+
if log_gpu:
|
| 446 |
+
# Clear GPU caches
|
| 447 |
+
if is_torch_available():
|
| 448 |
+
torch_empty_cache()
|
| 449 |
+
if is_tf_available():
|
| 450 |
+
tf_context.context()._clear_caches() # See https://github.com/tensorflow/tensorflow/issues/20218#issuecomment-416771802
|
| 451 |
+
|
| 452 |
+
# Sum used memory for all GPUs
|
| 453 |
+
nvml.nvmlInit()
|
| 454 |
+
|
| 455 |
+
for i in devices:
|
| 456 |
+
handle = nvml.nvmlDeviceGetHandleByIndex(i)
|
| 457 |
+
meminfo = nvml.nvmlDeviceGetMemoryInfo(handle)
|
| 458 |
+
gpu_mem += meminfo.used
|
| 459 |
+
|
| 460 |
+
nvml.nvmlShutdown()
|
| 461 |
+
|
| 462 |
+
mem_state = UsedMemoryState(traced_state, cpu_mem, gpu_mem)
|
| 463 |
+
memory_trace.append(mem_state)
|
| 464 |
+
|
| 465 |
+
return traceit
|
| 466 |
+
|
| 467 |
+
sys.settrace(traceit)
|
| 468 |
+
|
| 469 |
+
global _is_memory_tracing_enabled
|
| 470 |
+
_is_memory_tracing_enabled = True
|
| 471 |
+
|
| 472 |
+
return memory_trace
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def stop_memory_tracing(
|
| 476 |
+
memory_trace: Optional[MemoryTrace] = None, ignore_released_memory: bool = True
|
| 477 |
+
) -> Optional[MemorySummary]:
|
| 478 |
+
"""
|
| 479 |
+
Stop memory tracing cleanly and return a summary of the memory trace if a trace is given.
|
| 480 |
+
|
| 481 |
+
Args:
|
| 482 |
+
`memory_trace` (optional output of start_memory_tracing, default: None):
|
| 483 |
+
memory trace to convert in summary
|
| 484 |
+
`ignore_released_memory` (boolean, default: None):
|
| 485 |
+
if True we only sum memory increase to compute total memory
|
| 486 |
+
|
| 487 |
+
Return:
|
| 488 |
+
|
| 489 |
+
- None if `memory_trace` is None
|
| 490 |
+
- `MemorySummary` namedtuple otherwise with the fields:
|
| 491 |
+
|
| 492 |
+
- `sequential`: a list of `MemoryState` namedtuple (see below) computed from the provided `memory_trace` by
|
| 493 |
+
subtracting the memory after executing each line from the memory before executing said line.
|
| 494 |
+
- `cumulative`: a list of `MemoryState` namedtuple (see below) with cumulative increase in memory for each
|
| 495 |
+
line obtained by summing repeated memory increase for a line if it's executed several times. The list is
|
| 496 |
+
sorted from the frame with the largest memory consumption to the frame with the smallest (can be negative
|
| 497 |
+
if memory is released)
|
| 498 |
+
- `total`: total memory increase during the full tracing as a `Memory` named tuple (see below). Line with
|
| 499 |
+
memory release (negative consumption) are ignored if `ignore_released_memory` is `True` (default).
|
| 500 |
+
|
| 501 |
+
`Memory` named tuple have fields
|
| 502 |
+
|
| 503 |
+
- `byte` (integer): number of bytes,
|
| 504 |
+
- `string` (string): same as human readable string (ex: "3.5MB")
|
| 505 |
+
|
| 506 |
+
`Frame` are namedtuple used to list the current frame state and have the following fields:
|
| 507 |
+
|
| 508 |
+
- 'filename' (string): Name of the file currently executed
|
| 509 |
+
- 'module' (string): Name of the module currently executed
|
| 510 |
+
- 'line_number' (int): Number of the line currently executed
|
| 511 |
+
- 'event' (string): Event that triggered the tracing (default will be "line")
|
| 512 |
+
- 'line_text' (string): Text of the line in the python script
|
| 513 |
+
|
| 514 |
+
`MemoryState` are namedtuples listing frame + CPU/GPU memory with the following fields:
|
| 515 |
+
|
| 516 |
+
- `frame` (`Frame`): the current frame (see above)
|
| 517 |
+
- `cpu`: CPU memory consumed at during the current frame as a `Memory` named tuple
|
| 518 |
+
- `gpu`: GPU memory consumed at during the current frame as a `Memory` named tuple
|
| 519 |
+
- `cpu_gpu`: CPU + GPU memory consumed at during the current frame as a `Memory` named tuple
|
| 520 |
+
"""
|
| 521 |
+
global _is_memory_tracing_enabled
|
| 522 |
+
_is_memory_tracing_enabled = False
|
| 523 |
+
|
| 524 |
+
if memory_trace is not None and len(memory_trace) > 1:
|
| 525 |
+
memory_diff_trace = []
|
| 526 |
+
memory_curr_trace = []
|
| 527 |
+
|
| 528 |
+
cumulative_memory_dict = defaultdict(lambda: [0, 0, 0])
|
| 529 |
+
|
| 530 |
+
for (
|
| 531 |
+
(frame, cpu_mem, gpu_mem),
|
| 532 |
+
(next_frame, next_cpu_mem, next_gpu_mem),
|
| 533 |
+
) in zip(memory_trace[:-1], memory_trace[1:]):
|
| 534 |
+
cpu_mem_inc = next_cpu_mem - cpu_mem
|
| 535 |
+
gpu_mem_inc = next_gpu_mem - gpu_mem
|
| 536 |
+
cpu_gpu_mem_inc = cpu_mem_inc + gpu_mem_inc
|
| 537 |
+
memory_diff_trace.append(
|
| 538 |
+
MemoryState(
|
| 539 |
+
frame=frame,
|
| 540 |
+
cpu=Memory(cpu_mem_inc),
|
| 541 |
+
gpu=Memory(gpu_mem_inc),
|
| 542 |
+
cpu_gpu=Memory(cpu_gpu_mem_inc),
|
| 543 |
+
)
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
memory_curr_trace.append(
|
| 547 |
+
MemoryState(
|
| 548 |
+
frame=frame,
|
| 549 |
+
cpu=Memory(next_cpu_mem),
|
| 550 |
+
gpu=Memory(next_gpu_mem),
|
| 551 |
+
cpu_gpu=Memory(next_gpu_mem + next_cpu_mem),
|
| 552 |
+
)
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
cumulative_memory_dict[frame][0] += cpu_mem_inc
|
| 556 |
+
cumulative_memory_dict[frame][1] += gpu_mem_inc
|
| 557 |
+
cumulative_memory_dict[frame][2] += cpu_gpu_mem_inc
|
| 558 |
+
|
| 559 |
+
cumulative_memory = sorted(
|
| 560 |
+
cumulative_memory_dict.items(), key=lambda x: x[1][2], reverse=True
|
| 561 |
+
) # order by the total CPU + GPU memory increase
|
| 562 |
+
cumulative_memory = [
|
| 563 |
+
MemoryState(
|
| 564 |
+
frame=frame,
|
| 565 |
+
cpu=Memory(cpu_mem_inc),
|
| 566 |
+
gpu=Memory(gpu_mem_inc),
|
| 567 |
+
cpu_gpu=Memory(cpu_gpu_mem_inc),
|
| 568 |
+
)
|
| 569 |
+
for frame, (cpu_mem_inc, gpu_mem_inc, cpu_gpu_mem_inc) in cumulative_memory
|
| 570 |
+
]
|
| 571 |
+
|
| 572 |
+
memory_curr_trace = sorted(memory_curr_trace, key=lambda x: x.cpu_gpu.bytes, reverse=True)
|
| 573 |
+
|
| 574 |
+
if ignore_released_memory:
|
| 575 |
+
total_memory = sum(max(0, step_trace.cpu_gpu.bytes) for step_trace in memory_diff_trace)
|
| 576 |
+
else:
|
| 577 |
+
total_memory = sum(step_trace.cpu_gpu.bytes for step_trace in memory_diff_trace)
|
| 578 |
+
|
| 579 |
+
total_memory = Memory(total_memory)
|
| 580 |
+
|
| 581 |
+
return MemorySummary(
|
| 582 |
+
sequential=memory_diff_trace,
|
| 583 |
+
cumulative=cumulative_memory,
|
| 584 |
+
current=memory_curr_trace,
|
| 585 |
+
total=total_memory,
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
return None
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def bytes_to_mega_bytes(memory_amount: int) -> int:
|
| 592 |
+
"""Utility to convert a number of bytes (int) into a number of mega bytes (int)"""
|
| 593 |
+
return memory_amount >> 20
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
class Benchmark(ABC):
|
| 597 |
+
"""
|
| 598 |
+
Benchmarks is a simple but feature-complete benchmarking script to compare memory and time performance of models in
|
| 599 |
+
Transformers.
|
| 600 |
+
"""
|
| 601 |
+
|
| 602 |
+
args: BenchmarkArguments
|
| 603 |
+
configs: PretrainedConfig
|
| 604 |
+
framework: str
|
| 605 |
+
|
| 606 |
+
def __init__(self, args: BenchmarkArguments = None, configs: PretrainedConfig = None):
|
| 607 |
+
self.args = args
|
| 608 |
+
if configs is None:
|
| 609 |
+
self.config_dict = {
|
| 610 |
+
model_name: AutoConfig.from_pretrained(model_name) for model_name in self.args.model_names
|
| 611 |
+
}
|
| 612 |
+
else:
|
| 613 |
+
self.config_dict = dict(zip(self.args.model_names, configs))
|
| 614 |
+
|
| 615 |
+
warnings.warn(
|
| 616 |
+
f"The class {self.__class__} is deprecated. Hugging Face Benchmarking utils"
|
| 617 |
+
" are deprecated in general and it is advised to use external Benchmarking libraries "
|
| 618 |
+
" to benchmark Transformer models.",
|
| 619 |
+
FutureWarning,
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
if self.args.memory and os.getenv("TRANSFORMERS_USE_MULTIPROCESSING") == 0:
|
| 623 |
+
logger.warning(
|
| 624 |
+
"Memory consumption will not be measured accurately if `args.multi_process` is set to `False.` The"
|
| 625 |
+
" flag 'TRANSFORMERS_USE_MULTIPROCESSING' should only be disabled for debugging / testing."
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
self._print_fn = None
|
| 629 |
+
self._framework_version = None
|
| 630 |
+
self._environment_info = None
|
| 631 |
+
|
| 632 |
+
@property
|
| 633 |
+
def print_fn(self):
|
| 634 |
+
if self._print_fn is None:
|
| 635 |
+
if self.args.log_print:
|
| 636 |
+
|
| 637 |
+
def print_and_log(*args):
|
| 638 |
+
with open(self.args.log_filename, "a") as log_file:
|
| 639 |
+
log_file.write("".join(args) + "\n")
|
| 640 |
+
print(*args)
|
| 641 |
+
|
| 642 |
+
self._print_fn = print_and_log
|
| 643 |
+
else:
|
| 644 |
+
self._print_fn = print
|
| 645 |
+
return self._print_fn
|
| 646 |
+
|
| 647 |
+
@property
|
| 648 |
+
@abstractmethod
|
| 649 |
+
def framework_version(self):
|
| 650 |
+
pass
|
| 651 |
+
|
| 652 |
+
@abstractmethod
|
| 653 |
+
def _inference_speed(self, model_name: str, batch_size: int, sequence_length: int) -> float:
|
| 654 |
+
pass
|
| 655 |
+
|
| 656 |
+
@abstractmethod
|
| 657 |
+
def _train_speed(self, model_name: str, batch_size: int, sequence_length: int) -> float:
|
| 658 |
+
pass
|
| 659 |
+
|
| 660 |
+
@abstractmethod
|
| 661 |
+
def _inference_memory(
|
| 662 |
+
self, model_name: str, batch_size: int, sequence_length: int
|
| 663 |
+
) -> [Memory, Optional[MemorySummary]]:
|
| 664 |
+
pass
|
| 665 |
+
|
| 666 |
+
@abstractmethod
|
| 667 |
+
def _train_memory(
|
| 668 |
+
self, model_name: str, batch_size: int, sequence_length: int
|
| 669 |
+
) -> [Memory, Optional[MemorySummary]]:
|
| 670 |
+
pass
|
| 671 |
+
|
| 672 |
+
def inference_speed(self, *args, **kwargs) -> float:
|
| 673 |
+
return separate_process_wrapper_fn(self._inference_speed, self.args.do_multi_processing)(*args, **kwargs)
|
| 674 |
+
|
| 675 |
+
def train_speed(self, *args, **kwargs) -> float:
|
| 676 |
+
return separate_process_wrapper_fn(self._train_speed, self.args.do_multi_processing)(*args, **kwargs)
|
| 677 |
+
|
| 678 |
+
def inference_memory(self, *args, **kwargs) -> [Memory, Optional[MemorySummary]]:
|
| 679 |
+
return separate_process_wrapper_fn(self._inference_memory, self.args.do_multi_processing)(*args, **kwargs)
|
| 680 |
+
|
| 681 |
+
def train_memory(self, *args, **kwargs) -> [Memory, Optional[MemorySummary]]:
|
| 682 |
+
return separate_process_wrapper_fn(self._train_memory, self.args.do_multi_processing)(*args, **kwargs)
|
| 683 |
+
|
| 684 |
+
def run(self):
|
| 685 |
+
result_dict = {model_name: {} for model_name in self.args.model_names}
|
| 686 |
+
inference_result_time = copy.deepcopy(result_dict)
|
| 687 |
+
inference_result_memory = copy.deepcopy(result_dict)
|
| 688 |
+
train_result_time = copy.deepcopy(result_dict)
|
| 689 |
+
train_result_memory = copy.deepcopy(result_dict)
|
| 690 |
+
|
| 691 |
+
for c, model_name in enumerate(self.args.model_names):
|
| 692 |
+
self.print_fn(f"{c + 1} / {len(self.args.model_names)}")
|
| 693 |
+
|
| 694 |
+
model_dict = {
|
| 695 |
+
"bs": self.args.batch_sizes,
|
| 696 |
+
"ss": self.args.sequence_lengths,
|
| 697 |
+
"result": {i: {} for i in self.args.batch_sizes},
|
| 698 |
+
}
|
| 699 |
+
inference_result_time[model_name] = copy.deepcopy(model_dict)
|
| 700 |
+
inference_result_memory[model_name] = copy.deepcopy(model_dict)
|
| 701 |
+
train_result_time[model_name] = copy.deepcopy(model_dict)
|
| 702 |
+
train_result_memory[model_name] = copy.deepcopy(model_dict)
|
| 703 |
+
|
| 704 |
+
inference_summary = train_summary = None
|
| 705 |
+
|
| 706 |
+
for batch_size in self.args.batch_sizes:
|
| 707 |
+
for sequence_length in self.args.sequence_lengths:
|
| 708 |
+
if self.args.inference:
|
| 709 |
+
if self.args.memory:
|
| 710 |
+
memory, inference_summary = self.inference_memory(model_name, batch_size, sequence_length)
|
| 711 |
+
inference_result_memory[model_name]["result"][batch_size][sequence_length] = memory
|
| 712 |
+
if self.args.speed:
|
| 713 |
+
time = self.inference_speed(model_name, batch_size, sequence_length)
|
| 714 |
+
inference_result_time[model_name]["result"][batch_size][sequence_length] = time
|
| 715 |
+
|
| 716 |
+
if self.args.training:
|
| 717 |
+
if self.args.memory:
|
| 718 |
+
memory, train_summary = self.train_memory(model_name, batch_size, sequence_length)
|
| 719 |
+
train_result_memory[model_name]["result"][batch_size][sequence_length] = memory
|
| 720 |
+
if self.args.speed:
|
| 721 |
+
time = self.train_speed(model_name, batch_size, sequence_length)
|
| 722 |
+
train_result_time[model_name]["result"][batch_size][sequence_length] = time
|
| 723 |
+
|
| 724 |
+
if self.args.inference:
|
| 725 |
+
if self.args.speed:
|
| 726 |
+
self.print_fn("\n" + 20 * "=" + ("INFERENCE - SPEED - RESULT").center(40) + 20 * "=")
|
| 727 |
+
self.print_results(inference_result_time, type_label="Time in s")
|
| 728 |
+
self.save_to_csv(inference_result_time, self.args.inference_time_csv_file)
|
| 729 |
+
if self.args.is_tpu:
|
| 730 |
+
self.print_fn(
|
| 731 |
+
"TPU was used for inference. Note that the time after compilation stabilized (after ~10"
|
| 732 |
+
" inferences model.forward(..) calls) was measured."
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
if self.args.memory:
|
| 736 |
+
self.print_fn("\n" + 20 * "=" + ("INFERENCE - MEMORY - RESULT").center(40) + 20 * "=")
|
| 737 |
+
self.print_results(inference_result_memory, type_label="Memory in MB")
|
| 738 |
+
self.save_to_csv(inference_result_memory, self.args.inference_memory_csv_file)
|
| 739 |
+
|
| 740 |
+
if self.args.trace_memory_line_by_line:
|
| 741 |
+
self.print_fn("\n" + 20 * "=" + ("INFERENCE - MEMOMRY - LINE BY LINE - SUMMARY").center(40) + 20 * "=")
|
| 742 |
+
self.print_memory_trace_statistics(inference_summary)
|
| 743 |
+
|
| 744 |
+
if self.args.training:
|
| 745 |
+
if self.args.speed:
|
| 746 |
+
self.print_fn("\n" + 20 * "=" + ("TRAIN - SPEED - RESULTS").center(40) + 20 * "=")
|
| 747 |
+
self.print_results(train_result_time, "Time in s")
|
| 748 |
+
self.save_to_csv(train_result_time, self.args.train_time_csv_file)
|
| 749 |
+
if self.args.is_tpu:
|
| 750 |
+
self.print_fn(
|
| 751 |
+
"TPU was used for training. Note that the time after compilation stabilized (after ~10 train"
|
| 752 |
+
" loss=model.forward(...) + loss.backward() calls) was measured."
|
| 753 |
+
)
|
| 754 |
+
|
| 755 |
+
if self.args.memory:
|
| 756 |
+
self.print_fn("\n" + 20 * "=" + ("TRAIN - MEMORY - RESULTS").center(40) + 20 * "=")
|
| 757 |
+
self.print_results(train_result_memory, type_label="Memory in MB")
|
| 758 |
+
self.save_to_csv(train_result_memory, self.args.train_memory_csv_file)
|
| 759 |
+
|
| 760 |
+
if self.args.trace_memory_line_by_line:
|
| 761 |
+
self.print_fn("\n" + 20 * "=" + ("TRAIN - MEMOMRY - LINE BY LINE - SUMMARY").center(40) + 20 * "=")
|
| 762 |
+
self.print_memory_trace_statistics(train_summary)
|
| 763 |
+
|
| 764 |
+
if self.args.env_print:
|
| 765 |
+
self.print_fn("\n" + 20 * "=" + ("ENVIRONMENT INFORMATION").center(40) + 20 * "=")
|
| 766 |
+
self.print_fn("\n".join([f"- {prop}: {val}" for prop, val in self.environment_info.items()]) + "\n")
|
| 767 |
+
|
| 768 |
+
if self.args.save_to_csv:
|
| 769 |
+
with open(self.args.env_info_csv_file, mode="w", newline="") as csv_file:
|
| 770 |
+
writer = csv.writer(csv_file)
|
| 771 |
+
for key, value in self.environment_info.items():
|
| 772 |
+
writer.writerow([key, value])
|
| 773 |
+
|
| 774 |
+
return BenchmarkOutput(
|
| 775 |
+
inference_result_time,
|
| 776 |
+
inference_result_memory,
|
| 777 |
+
train_result_time,
|
| 778 |
+
train_result_memory,
|
| 779 |
+
inference_summary,
|
| 780 |
+
train_summary,
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
@property
|
| 784 |
+
def environment_info(self):
|
| 785 |
+
if self._environment_info is None:
|
| 786 |
+
info = {}
|
| 787 |
+
info["transformers_version"] = version
|
| 788 |
+
info["framework"] = self.framework
|
| 789 |
+
if self.framework == "PyTorch":
|
| 790 |
+
info["use_torchscript"] = self.args.torchscript
|
| 791 |
+
if self.framework == "TensorFlow":
|
| 792 |
+
info["eager_mode"] = self.args.eager_mode
|
| 793 |
+
info["use_xla"] = self.args.use_xla
|
| 794 |
+
info["framework_version"] = self.framework_version
|
| 795 |
+
info["python_version"] = platform.python_version()
|
| 796 |
+
info["system"] = platform.system()
|
| 797 |
+
info["cpu"] = platform.processor()
|
| 798 |
+
info["architecture"] = platform.architecture()[0]
|
| 799 |
+
info["date"] = datetime.date(datetime.now())
|
| 800 |
+
info["time"] = datetime.time(datetime.now())
|
| 801 |
+
info["fp16"] = self.args.fp16
|
| 802 |
+
info["use_multiprocessing"] = self.args.do_multi_processing
|
| 803 |
+
info["only_pretrain_model"] = self.args.only_pretrain_model
|
| 804 |
+
|
| 805 |
+
if is_psutil_available():
|
| 806 |
+
info["cpu_ram_mb"] = bytes_to_mega_bytes(psutil.virtual_memory().total)
|
| 807 |
+
else:
|
| 808 |
+
logger.warning(
|
| 809 |
+
"Psutil not installed, we won't log available CPU memory. "
|
| 810 |
+
"Install psutil (pip install psutil) to log available CPU memory."
|
| 811 |
+
)
|
| 812 |
+
info["cpu_ram_mb"] = "N/A"
|
| 813 |
+
|
| 814 |
+
info["use_gpu"] = self.args.is_gpu
|
| 815 |
+
if self.args.is_gpu:
|
| 816 |
+
info["num_gpus"] = 1 # TODO(PVP) Currently only single GPU is supported
|
| 817 |
+
if is_py3nvml_available():
|
| 818 |
+
nvml.nvmlInit()
|
| 819 |
+
handle = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx)
|
| 820 |
+
info["gpu"] = nvml.nvmlDeviceGetName(handle)
|
| 821 |
+
info["gpu_ram_mb"] = bytes_to_mega_bytes(nvml.nvmlDeviceGetMemoryInfo(handle).total)
|
| 822 |
+
info["gpu_power_watts"] = nvml.nvmlDeviceGetPowerManagementLimit(handle) / 1000
|
| 823 |
+
info["gpu_performance_state"] = nvml.nvmlDeviceGetPerformanceState(handle)
|
| 824 |
+
nvml.nvmlShutdown()
|
| 825 |
+
else:
|
| 826 |
+
logger.warning(
|
| 827 |
+
"py3nvml not installed, we won't log GPU memory usage. "
|
| 828 |
+
"Install py3nvml (pip install py3nvml) to log information about GPU."
|
| 829 |
+
)
|
| 830 |
+
info["gpu"] = "N/A"
|
| 831 |
+
info["gpu_ram_mb"] = "N/A"
|
| 832 |
+
info["gpu_power_watts"] = "N/A"
|
| 833 |
+
info["gpu_performance_state"] = "N/A"
|
| 834 |
+
|
| 835 |
+
info["use_tpu"] = self.args.is_tpu
|
| 836 |
+
# TODO(PVP): See if we can add more information about TPU
|
| 837 |
+
# see: https://github.com/pytorch/xla/issues/2180
|
| 838 |
+
|
| 839 |
+
self._environment_info = info
|
| 840 |
+
return self._environment_info
|
| 841 |
+
|
| 842 |
+
def print_results(self, result_dict, type_label):
|
| 843 |
+
self.print_fn(80 * "-")
|
| 844 |
+
self.print_fn(
|
| 845 |
+
"Model Name".center(30) + "Batch Size".center(15) + "Seq Length".center(15) + type_label.center(15)
|
| 846 |
+
)
|
| 847 |
+
self.print_fn(80 * "-")
|
| 848 |
+
for model_name in self.args.model_names:
|
| 849 |
+
for batch_size in result_dict[model_name]["bs"]:
|
| 850 |
+
for sequence_length in result_dict[model_name]["ss"]:
|
| 851 |
+
result = result_dict[model_name]["result"][batch_size][sequence_length]
|
| 852 |
+
if isinstance(result, float):
|
| 853 |
+
result = round(1000 * result) / 1000
|
| 854 |
+
result = "< 0.001" if result == 0.0 else str(result)
|
| 855 |
+
else:
|
| 856 |
+
result = str(result)
|
| 857 |
+
self.print_fn(
|
| 858 |
+
model_name[:30].center(30) + str(batch_size).center(15),
|
| 859 |
+
str(sequence_length).center(15),
|
| 860 |
+
result.center(15),
|
| 861 |
+
)
|
| 862 |
+
self.print_fn(80 * "-")
|
| 863 |
+
|
| 864 |
+
def print_memory_trace_statistics(self, summary: MemorySummary):
|
| 865 |
+
self.print_fn(
|
| 866 |
+
"\nLine by line memory consumption:\n"
|
| 867 |
+
+ "\n".join(
|
| 868 |
+
f"{state.frame.filename}:{state.frame.line_number}: mem {state.cpu_gpu}: {state.frame.line_text}"
|
| 869 |
+
for state in summary.sequential
|
| 870 |
+
)
|
| 871 |
+
)
|
| 872 |
+
self.print_fn(
|
| 873 |
+
"\nLines with top memory consumption:\n"
|
| 874 |
+
+ "\n".join(
|
| 875 |
+
f"=> {state.frame.filename}:{state.frame.line_number}: mem {state.cpu_gpu}: {state.frame.line_text}"
|
| 876 |
+
for state in summary.cumulative[:6]
|
| 877 |
+
)
|
| 878 |
+
)
|
| 879 |
+
self.print_fn(
|
| 880 |
+
"\nLines with lowest memory consumption:\n"
|
| 881 |
+
+ "\n".join(
|
| 882 |
+
f"=> {state.frame.filename}:{state.frame.line_number}: mem {state.cpu_gpu}: {state.frame.line_text}"
|
| 883 |
+
for state in summary.cumulative[-6:]
|
| 884 |
+
)
|
| 885 |
+
)
|
| 886 |
+
self.print_fn(f"\nTotal memory increase: {summary.total}")
|
| 887 |
+
|
| 888 |
+
def save_to_csv(self, result_dict, filename):
|
| 889 |
+
if not self.args.save_to_csv:
|
| 890 |
+
return
|
| 891 |
+
self.print_fn("Saving results to csv.")
|
| 892 |
+
with open(filename, mode="w") as csv_file:
|
| 893 |
+
assert len(self.args.model_names) > 0, f"At least 1 model should be defined, but got {self.model_names}"
|
| 894 |
+
|
| 895 |
+
fieldnames = ["model", "batch_size", "sequence_length"]
|
| 896 |
+
writer = csv.DictWriter(csv_file, fieldnames=fieldnames + ["result"])
|
| 897 |
+
writer.writeheader()
|
| 898 |
+
|
| 899 |
+
for model_name in self.args.model_names:
|
| 900 |
+
result_dict_model = result_dict[model_name]["result"]
|
| 901 |
+
for bs in result_dict_model:
|
| 902 |
+
for ss in result_dict_model[bs]:
|
| 903 |
+
result_model = result_dict_model[bs][ss]
|
| 904 |
+
writer.writerow(
|
| 905 |
+
{
|
| 906 |
+
"model": model_name,
|
| 907 |
+
"batch_size": bs,
|
| 908 |
+
"sequence_length": ss,
|
| 909 |
+
"result": ("{}" if not isinstance(result_model, float) else "{:.4f}").format(
|
| 910 |
+
result_model
|
| 911 |
+
),
|
| 912 |
+
}
|
| 913 |
+
)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/add_new_model.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import shutil
|
| 18 |
+
import warnings
|
| 19 |
+
from argparse import ArgumentParser, Namespace
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import List
|
| 22 |
+
|
| 23 |
+
from ..utils import logging
|
| 24 |
+
from . import BaseTransformersCLICommand
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
from cookiecutter.main import cookiecutter
|
| 29 |
+
|
| 30 |
+
_has_cookiecutter = True
|
| 31 |
+
except ImportError:
|
| 32 |
+
_has_cookiecutter = False
|
| 33 |
+
|
| 34 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def add_new_model_command_factory(args: Namespace):
|
| 38 |
+
return AddNewModelCommand(args.testing, args.testing_file, path=args.path)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class AddNewModelCommand(BaseTransformersCLICommand):
|
| 42 |
+
@staticmethod
|
| 43 |
+
def register_subcommand(parser: ArgumentParser):
|
| 44 |
+
add_new_model_parser = parser.add_parser("add-new-model")
|
| 45 |
+
add_new_model_parser.add_argument("--testing", action="store_true", help="If in testing mode.")
|
| 46 |
+
add_new_model_parser.add_argument("--testing_file", type=str, help="Configuration file on which to run.")
|
| 47 |
+
add_new_model_parser.add_argument(
|
| 48 |
+
"--path", type=str, help="Path to cookiecutter. Should only be used for testing purposes."
|
| 49 |
+
)
|
| 50 |
+
add_new_model_parser.set_defaults(func=add_new_model_command_factory)
|
| 51 |
+
|
| 52 |
+
def __init__(self, testing: bool, testing_file: str, path=None, *args):
|
| 53 |
+
self._testing = testing
|
| 54 |
+
self._testing_file = testing_file
|
| 55 |
+
self._path = path
|
| 56 |
+
|
| 57 |
+
def run(self):
|
| 58 |
+
warnings.warn(
|
| 59 |
+
"The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. "
|
| 60 |
+
"It is not actively maintained anymore, so might give a result that won't pass all tests and quality "
|
| 61 |
+
"checks, you should use `transformers-cli add-new-model-like` instead."
|
| 62 |
+
)
|
| 63 |
+
if not _has_cookiecutter:
|
| 64 |
+
raise ImportError(
|
| 65 |
+
"Model creation dependencies are required to use the `add_new_model` command. Install them by running "
|
| 66 |
+
"the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n"
|
| 67 |
+
)
|
| 68 |
+
# Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory
|
| 69 |
+
directories = [directory for directory in os.listdir() if "cookiecutter-template-" == directory[:22]]
|
| 70 |
+
if len(directories) > 0:
|
| 71 |
+
raise ValueError(
|
| 72 |
+
"Several directories starting with `cookiecutter-template-` in current working directory. "
|
| 73 |
+
"Please clean your directory by removing all folders starting with `cookiecutter-template-` or "
|
| 74 |
+
"change your working directory."
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
path_to_transformer_root = (
|
| 78 |
+
Path(__file__).parent.parent.parent.parent if self._path is None else Path(self._path).parent.parent
|
| 79 |
+
)
|
| 80 |
+
path_to_cookiecutter = path_to_transformer_root / "templates" / "adding_a_new_model"
|
| 81 |
+
|
| 82 |
+
# Execute cookiecutter
|
| 83 |
+
if not self._testing:
|
| 84 |
+
cookiecutter(str(path_to_cookiecutter))
|
| 85 |
+
else:
|
| 86 |
+
with open(self._testing_file, "r") as configuration_file:
|
| 87 |
+
testing_configuration = json.load(configuration_file)
|
| 88 |
+
|
| 89 |
+
cookiecutter(
|
| 90 |
+
str(path_to_cookiecutter if self._path is None else self._path),
|
| 91 |
+
no_input=True,
|
| 92 |
+
extra_context=testing_configuration,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
directory = [directory for directory in os.listdir() if "cookiecutter-template-" in directory[:22]][0]
|
| 96 |
+
|
| 97 |
+
# Retrieve configuration
|
| 98 |
+
with open(directory + "/configuration.json", "r") as configuration_file:
|
| 99 |
+
configuration = json.load(configuration_file)
|
| 100 |
+
|
| 101 |
+
lowercase_model_name = configuration["lowercase_modelname"]
|
| 102 |
+
generate_tensorflow_pytorch_and_flax = configuration["generate_tensorflow_pytorch_and_flax"]
|
| 103 |
+
os.remove(f"{directory}/configuration.json")
|
| 104 |
+
|
| 105 |
+
output_pytorch = "PyTorch" in generate_tensorflow_pytorch_and_flax
|
| 106 |
+
output_tensorflow = "TensorFlow" in generate_tensorflow_pytorch_and_flax
|
| 107 |
+
output_flax = "Flax" in generate_tensorflow_pytorch_and_flax
|
| 108 |
+
|
| 109 |
+
model_dir = f"{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}"
|
| 110 |
+
os.makedirs(model_dir, exist_ok=True)
|
| 111 |
+
os.makedirs(f"{path_to_transformer_root}/tests/models/{lowercase_model_name}", exist_ok=True)
|
| 112 |
+
|
| 113 |
+
# Tests require submodules as they have parent imports
|
| 114 |
+
with open(f"{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py", "w"):
|
| 115 |
+
pass
|
| 116 |
+
|
| 117 |
+
shutil.move(
|
| 118 |
+
f"{directory}/__init__.py",
|
| 119 |
+
f"{model_dir}/__init__.py",
|
| 120 |
+
)
|
| 121 |
+
shutil.move(
|
| 122 |
+
f"{directory}/configuration_{lowercase_model_name}.py",
|
| 123 |
+
f"{model_dir}/configuration_{lowercase_model_name}.py",
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def remove_copy_lines(path):
|
| 127 |
+
with open(path, "r") as f:
|
| 128 |
+
lines = f.readlines()
|
| 129 |
+
with open(path, "w") as f:
|
| 130 |
+
for line in lines:
|
| 131 |
+
if "# Copied from transformers." not in line:
|
| 132 |
+
f.write(line)
|
| 133 |
+
|
| 134 |
+
if output_pytorch:
|
| 135 |
+
if not self._testing:
|
| 136 |
+
remove_copy_lines(f"{directory}/modeling_{lowercase_model_name}.py")
|
| 137 |
+
|
| 138 |
+
shutil.move(
|
| 139 |
+
f"{directory}/modeling_{lowercase_model_name}.py",
|
| 140 |
+
f"{model_dir}/modeling_{lowercase_model_name}.py",
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
shutil.move(
|
| 144 |
+
f"{directory}/test_modeling_{lowercase_model_name}.py",
|
| 145 |
+
f"{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py",
|
| 146 |
+
)
|
| 147 |
+
else:
|
| 148 |
+
os.remove(f"{directory}/modeling_{lowercase_model_name}.py")
|
| 149 |
+
os.remove(f"{directory}/test_modeling_{lowercase_model_name}.py")
|
| 150 |
+
|
| 151 |
+
if output_tensorflow:
|
| 152 |
+
if not self._testing:
|
| 153 |
+
remove_copy_lines(f"{directory}/modeling_tf_{lowercase_model_name}.py")
|
| 154 |
+
|
| 155 |
+
shutil.move(
|
| 156 |
+
f"{directory}/modeling_tf_{lowercase_model_name}.py",
|
| 157 |
+
f"{model_dir}/modeling_tf_{lowercase_model_name}.py",
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
shutil.move(
|
| 161 |
+
f"{directory}/test_modeling_tf_{lowercase_model_name}.py",
|
| 162 |
+
f"{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py",
|
| 163 |
+
)
|
| 164 |
+
else:
|
| 165 |
+
os.remove(f"{directory}/modeling_tf_{lowercase_model_name}.py")
|
| 166 |
+
os.remove(f"{directory}/test_modeling_tf_{lowercase_model_name}.py")
|
| 167 |
+
|
| 168 |
+
if output_flax:
|
| 169 |
+
if not self._testing:
|
| 170 |
+
remove_copy_lines(f"{directory}/modeling_flax_{lowercase_model_name}.py")
|
| 171 |
+
|
| 172 |
+
shutil.move(
|
| 173 |
+
f"{directory}/modeling_flax_{lowercase_model_name}.py",
|
| 174 |
+
f"{model_dir}/modeling_flax_{lowercase_model_name}.py",
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
shutil.move(
|
| 178 |
+
f"{directory}/test_modeling_flax_{lowercase_model_name}.py",
|
| 179 |
+
f"{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py",
|
| 180 |
+
)
|
| 181 |
+
else:
|
| 182 |
+
os.remove(f"{directory}/modeling_flax_{lowercase_model_name}.py")
|
| 183 |
+
os.remove(f"{directory}/test_modeling_flax_{lowercase_model_name}.py")
|
| 184 |
+
|
| 185 |
+
shutil.move(
|
| 186 |
+
f"{directory}/{lowercase_model_name}.mdx",
|
| 187 |
+
f"{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.mdx",
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
shutil.move(
|
| 191 |
+
f"{directory}/tokenization_{lowercase_model_name}.py",
|
| 192 |
+
f"{model_dir}/tokenization_{lowercase_model_name}.py",
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
shutil.move(
|
| 196 |
+
f"{directory}/tokenization_fast_{lowercase_model_name}.py",
|
| 197 |
+
f"{model_dir}/tokenization_{lowercase_model_name}_fast.py",
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
from os import fdopen, remove
|
| 201 |
+
from shutil import copymode, move
|
| 202 |
+
from tempfile import mkstemp
|
| 203 |
+
|
| 204 |
+
def replace(original_file: str, line_to_copy_below: str, lines_to_copy: List[str]):
|
| 205 |
+
# Create temp file
|
| 206 |
+
fh, abs_path = mkstemp()
|
| 207 |
+
line_found = False
|
| 208 |
+
with fdopen(fh, "w") as new_file:
|
| 209 |
+
with open(original_file) as old_file:
|
| 210 |
+
for line in old_file:
|
| 211 |
+
new_file.write(line)
|
| 212 |
+
if line_to_copy_below in line:
|
| 213 |
+
line_found = True
|
| 214 |
+
for line_to_copy in lines_to_copy:
|
| 215 |
+
new_file.write(line_to_copy)
|
| 216 |
+
|
| 217 |
+
if not line_found:
|
| 218 |
+
raise ValueError(f"Line {line_to_copy_below} was not found in file.")
|
| 219 |
+
|
| 220 |
+
# Copy the file permissions from the old file to the new file
|
| 221 |
+
copymode(original_file, abs_path)
|
| 222 |
+
# Remove original file
|
| 223 |
+
remove(original_file)
|
| 224 |
+
# Move new file
|
| 225 |
+
move(abs_path, original_file)
|
| 226 |
+
|
| 227 |
+
def skip_units(line):
|
| 228 |
+
return (
|
| 229 |
+
("generating PyTorch" in line and not output_pytorch)
|
| 230 |
+
or ("generating TensorFlow" in line and not output_tensorflow)
|
| 231 |
+
or ("generating Flax" in line and not output_flax)
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
def replace_in_files(path_to_datafile):
|
| 235 |
+
with open(path_to_datafile) as datafile:
|
| 236 |
+
lines_to_copy = []
|
| 237 |
+
skip_file = False
|
| 238 |
+
skip_snippet = False
|
| 239 |
+
for line in datafile:
|
| 240 |
+
if "# To replace in: " in line and "##" not in line:
|
| 241 |
+
file_to_replace_in = line.split('"')[1]
|
| 242 |
+
skip_file = skip_units(line)
|
| 243 |
+
elif "# Below: " in line and "##" not in line:
|
| 244 |
+
line_to_copy_below = line.split('"')[1]
|
| 245 |
+
skip_snippet = skip_units(line)
|
| 246 |
+
elif "# End." in line and "##" not in line:
|
| 247 |
+
if not skip_file and not skip_snippet:
|
| 248 |
+
replace(file_to_replace_in, line_to_copy_below, lines_to_copy)
|
| 249 |
+
|
| 250 |
+
lines_to_copy = []
|
| 251 |
+
elif "# Replace with" in line and "##" not in line:
|
| 252 |
+
lines_to_copy = []
|
| 253 |
+
elif "##" not in line:
|
| 254 |
+
lines_to_copy.append(line)
|
| 255 |
+
|
| 256 |
+
remove(path_to_datafile)
|
| 257 |
+
|
| 258 |
+
replace_in_files(f"{directory}/to_replace_{lowercase_model_name}.py")
|
| 259 |
+
os.rmdir(directory)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/add_new_model_like.py
ADDED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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import difflib
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import re
|
| 19 |
+
from argparse import ArgumentParser, Namespace
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from datetime import date
|
| 22 |
+
from itertools import chain
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Any, Callable, Dict, List, Optional, Pattern, Tuple, Union
|
| 25 |
+
|
| 26 |
+
from ..models import auto as auto_module
|
| 27 |
+
from ..models.auto.configuration_auto import model_type_to_module_name
|
| 28 |
+
from ..utils import is_flax_available, is_tf_available, is_torch_available, logging
|
| 29 |
+
from . import BaseTransformersCLICommand
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
CURRENT_YEAR = date.today().year
|
| 36 |
+
TRANSFORMERS_PATH = Path(__file__).parent.parent
|
| 37 |
+
REPO_PATH = TRANSFORMERS_PATH.parent.parent
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass
|
| 41 |
+
class ModelPatterns:
|
| 42 |
+
"""
|
| 43 |
+
Holds the basic information about a new model for the add-new-model-like command.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
model_name (`str`): The model name.
|
| 47 |
+
checkpoint (`str`): The checkpoint to use for doc examples.
|
| 48 |
+
model_type (`str`, *optional*):
|
| 49 |
+
The model type, the identifier used internally in the library like `bert` or `xlm-roberta`. Will default to
|
| 50 |
+
`model_name` lowercased with spaces replaced with minuses (-).
|
| 51 |
+
model_lower_cased (`str`, *optional*):
|
| 52 |
+
The lowercased version of the model name, to use for the module name or function names. Will default to
|
| 53 |
+
`model_name` lowercased with spaces and minuses replaced with underscores.
|
| 54 |
+
model_camel_cased (`str`, *optional*):
|
| 55 |
+
The camel-cased version of the model name, to use for the class names. Will default to `model_name`
|
| 56 |
+
camel-cased (with spaces and minuses both considered as word separators.
|
| 57 |
+
model_upper_cased (`str`, *optional*):
|
| 58 |
+
The uppercased version of the model name, to use for the constant names. Will default to `model_name`
|
| 59 |
+
uppercased with spaces and minuses replaced with underscores.
|
| 60 |
+
config_class (`str`, *optional*):
|
| 61 |
+
The tokenizer class associated with this model. Will default to `"{model_camel_cased}Config"`.
|
| 62 |
+
tokenizer_class (`str`, *optional*):
|
| 63 |
+
The tokenizer class associated with this model (leave to `None` for models that don't use a tokenizer).
|
| 64 |
+
image_processor_class (`str`, *optional*):
|
| 65 |
+
The image processor class associated with this model (leave to `None` for models that don't use an image
|
| 66 |
+
processor).
|
| 67 |
+
feature_extractor_class (`str`, *optional*):
|
| 68 |
+
The feature extractor class associated with this model (leave to `None` for models that don't use a feature
|
| 69 |
+
extractor).
|
| 70 |
+
processor_class (`str`, *optional*):
|
| 71 |
+
The processor class associated with this model (leave to `None` for models that don't use a processor).
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
model_name: str
|
| 75 |
+
checkpoint: str
|
| 76 |
+
model_type: Optional[str] = None
|
| 77 |
+
model_lower_cased: Optional[str] = None
|
| 78 |
+
model_camel_cased: Optional[str] = None
|
| 79 |
+
model_upper_cased: Optional[str] = None
|
| 80 |
+
config_class: Optional[str] = None
|
| 81 |
+
tokenizer_class: Optional[str] = None
|
| 82 |
+
image_processor_class: Optional[str] = None
|
| 83 |
+
feature_extractor_class: Optional[str] = None
|
| 84 |
+
processor_class: Optional[str] = None
|
| 85 |
+
|
| 86 |
+
def __post_init__(self):
|
| 87 |
+
if self.model_type is None:
|
| 88 |
+
self.model_type = self.model_name.lower().replace(" ", "-")
|
| 89 |
+
if self.model_lower_cased is None:
|
| 90 |
+
self.model_lower_cased = self.model_name.lower().replace(" ", "_").replace("-", "_")
|
| 91 |
+
if self.model_camel_cased is None:
|
| 92 |
+
# Split the model name on - and space
|
| 93 |
+
words = self.model_name.split(" ")
|
| 94 |
+
words = list(chain(*[w.split("-") for w in words]))
|
| 95 |
+
# Make sure each word is capitalized
|
| 96 |
+
words = [w[0].upper() + w[1:] for w in words]
|
| 97 |
+
self.model_camel_cased = "".join(words)
|
| 98 |
+
if self.model_upper_cased is None:
|
| 99 |
+
self.model_upper_cased = self.model_name.upper().replace(" ", "_").replace("-", "_")
|
| 100 |
+
if self.config_class is None:
|
| 101 |
+
self.config_class = f"{self.model_camel_cased}Config"
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
ATTRIBUTE_TO_PLACEHOLDER = {
|
| 105 |
+
"config_class": "[CONFIG_CLASS]",
|
| 106 |
+
"tokenizer_class": "[TOKENIZER_CLASS]",
|
| 107 |
+
"image_processor_class": "[IMAGE_PROCESSOR_CLASS]",
|
| 108 |
+
"feature_extractor_class": "[FEATURE_EXTRACTOR_CLASS]",
|
| 109 |
+
"processor_class": "[PROCESSOR_CLASS]",
|
| 110 |
+
"checkpoint": "[CHECKPOINT]",
|
| 111 |
+
"model_type": "[MODEL_TYPE]",
|
| 112 |
+
"model_upper_cased": "[MODEL_UPPER_CASED]",
|
| 113 |
+
"model_camel_cased": "[MODEL_CAMELCASED]",
|
| 114 |
+
"model_lower_cased": "[MODEL_LOWER_CASED]",
|
| 115 |
+
"model_name": "[MODEL_NAME]",
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def is_empty_line(line: str) -> bool:
|
| 120 |
+
"""
|
| 121 |
+
Determines whether a line is empty or not.
|
| 122 |
+
"""
|
| 123 |
+
return len(line) == 0 or line.isspace()
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def find_indent(line: str) -> int:
|
| 127 |
+
"""
|
| 128 |
+
Returns the number of spaces that start a line indent.
|
| 129 |
+
"""
|
| 130 |
+
search = re.search(r"^(\s*)(?:\S|$)", line)
|
| 131 |
+
if search is None:
|
| 132 |
+
return 0
|
| 133 |
+
return len(search.groups()[0])
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def parse_module_content(content: str) -> List[str]:
|
| 137 |
+
"""
|
| 138 |
+
Parse the content of a module in the list of objects it defines.
|
| 139 |
+
|
| 140 |
+
Args:
|
| 141 |
+
content (`str`): The content to parse
|
| 142 |
+
|
| 143 |
+
Returns:
|
| 144 |
+
`List[str]`: The list of objects defined in the module.
|
| 145 |
+
"""
|
| 146 |
+
objects = []
|
| 147 |
+
current_object = []
|
| 148 |
+
lines = content.split("\n")
|
| 149 |
+
# Doc-styler takes everything between two triple quotes in docstrings, so we need a fake """ here to go with this.
|
| 150 |
+
end_markers = [")", "]", "}", '"""']
|
| 151 |
+
|
| 152 |
+
for line in lines:
|
| 153 |
+
# End of an object
|
| 154 |
+
is_valid_object = len(current_object) > 0
|
| 155 |
+
if is_valid_object and len(current_object) == 1:
|
| 156 |
+
is_valid_object = not current_object[0].startswith("# Copied from")
|
| 157 |
+
if not is_empty_line(line) and find_indent(line) == 0 and is_valid_object:
|
| 158 |
+
# Closing parts should be included in current object
|
| 159 |
+
if line in end_markers:
|
| 160 |
+
current_object.append(line)
|
| 161 |
+
objects.append("\n".join(current_object))
|
| 162 |
+
current_object = []
|
| 163 |
+
else:
|
| 164 |
+
objects.append("\n".join(current_object))
|
| 165 |
+
current_object = [line]
|
| 166 |
+
else:
|
| 167 |
+
current_object.append(line)
|
| 168 |
+
|
| 169 |
+
# Add last object
|
| 170 |
+
if len(current_object) > 0:
|
| 171 |
+
objects.append("\n".join(current_object))
|
| 172 |
+
|
| 173 |
+
return objects
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def extract_block(content: str, indent_level: int = 0) -> str:
|
| 177 |
+
"""Return the first block in `content` with the indent level `indent_level`.
|
| 178 |
+
|
| 179 |
+
The first line in `content` should be indented at `indent_level` level, otherwise an error will be thrown.
|
| 180 |
+
|
| 181 |
+
This method will immediately stop the search when a (non-empty) line with indent level less than `indent_level` is
|
| 182 |
+
encountered.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
content (`str`): The content to parse
|
| 186 |
+
indent_level (`int`, *optional*, default to 0): The indent level of the blocks to search for
|
| 187 |
+
|
| 188 |
+
Returns:
|
| 189 |
+
`str`: The first block in `content` with the indent level `indent_level`.
|
| 190 |
+
"""
|
| 191 |
+
current_object = []
|
| 192 |
+
lines = content.split("\n")
|
| 193 |
+
# Doc-styler takes everything between two triple quotes in docstrings, so we need a fake """ here to go with this.
|
| 194 |
+
end_markers = [")", "]", "}", '"""']
|
| 195 |
+
|
| 196 |
+
for idx, line in enumerate(lines):
|
| 197 |
+
if idx == 0 and indent_level > 0 and not is_empty_line(line) and find_indent(line) != indent_level:
|
| 198 |
+
raise ValueError(
|
| 199 |
+
f"When `indent_level > 0`, the first line in `content` should have indent level {indent_level}. Got "
|
| 200 |
+
f"{find_indent(line)} instead."
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
if find_indent(line) < indent_level and not is_empty_line(line):
|
| 204 |
+
break
|
| 205 |
+
|
| 206 |
+
# End of an object
|
| 207 |
+
is_valid_object = len(current_object) > 0
|
| 208 |
+
if (
|
| 209 |
+
not is_empty_line(line)
|
| 210 |
+
and not line.endswith(":")
|
| 211 |
+
and find_indent(line) == indent_level
|
| 212 |
+
and is_valid_object
|
| 213 |
+
):
|
| 214 |
+
# Closing parts should be included in current object
|
| 215 |
+
if line.lstrip() in end_markers:
|
| 216 |
+
current_object.append(line)
|
| 217 |
+
return "\n".join(current_object)
|
| 218 |
+
else:
|
| 219 |
+
current_object.append(line)
|
| 220 |
+
|
| 221 |
+
# Add last object
|
| 222 |
+
if len(current_object) > 0:
|
| 223 |
+
return "\n".join(current_object)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def add_content_to_text(
|
| 227 |
+
text: str,
|
| 228 |
+
content: str,
|
| 229 |
+
add_after: Optional[Union[str, Pattern]] = None,
|
| 230 |
+
add_before: Optional[Union[str, Pattern]] = None,
|
| 231 |
+
exact_match: bool = False,
|
| 232 |
+
) -> str:
|
| 233 |
+
"""
|
| 234 |
+
A utility to add some content inside a given text.
|
| 235 |
+
|
| 236 |
+
Args:
|
| 237 |
+
text (`str`): The text in which we want to insert some content.
|
| 238 |
+
content (`str`): The content to add.
|
| 239 |
+
add_after (`str` or `Pattern`):
|
| 240 |
+
The pattern to test on a line of `text`, the new content is added after the first instance matching it.
|
| 241 |
+
add_before (`str` or `Pattern`):
|
| 242 |
+
The pattern to test on a line of `text`, the new content is added before the first instance matching it.
|
| 243 |
+
exact_match (`bool`, *optional*, defaults to `False`):
|
| 244 |
+
A line is considered a match with `add_after` or `add_before` if it matches exactly when `exact_match=True`,
|
| 245 |
+
otherwise, if `add_after`/`add_before` is present in the line.
|
| 246 |
+
|
| 247 |
+
<Tip warning={true}>
|
| 248 |
+
|
| 249 |
+
The arguments `add_after` and `add_before` are mutually exclusive, and one exactly needs to be provided.
|
| 250 |
+
|
| 251 |
+
</Tip>
|
| 252 |
+
|
| 253 |
+
Returns:
|
| 254 |
+
`str`: The text with the new content added if a match was found.
|
| 255 |
+
"""
|
| 256 |
+
if add_after is None and add_before is None:
|
| 257 |
+
raise ValueError("You need to pass either `add_after` or `add_before`")
|
| 258 |
+
if add_after is not None and add_before is not None:
|
| 259 |
+
raise ValueError("You can't pass both `add_after` or `add_before`")
|
| 260 |
+
pattern = add_after if add_before is None else add_before
|
| 261 |
+
|
| 262 |
+
def this_is_the_line(line):
|
| 263 |
+
if isinstance(pattern, Pattern):
|
| 264 |
+
return pattern.search(line) is not None
|
| 265 |
+
elif exact_match:
|
| 266 |
+
return pattern == line
|
| 267 |
+
else:
|
| 268 |
+
return pattern in line
|
| 269 |
+
|
| 270 |
+
new_lines = []
|
| 271 |
+
for line in text.split("\n"):
|
| 272 |
+
if this_is_the_line(line):
|
| 273 |
+
if add_before is not None:
|
| 274 |
+
new_lines.append(content)
|
| 275 |
+
new_lines.append(line)
|
| 276 |
+
if add_after is not None:
|
| 277 |
+
new_lines.append(content)
|
| 278 |
+
else:
|
| 279 |
+
new_lines.append(line)
|
| 280 |
+
|
| 281 |
+
return "\n".join(new_lines)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def add_content_to_file(
|
| 285 |
+
file_name: Union[str, os.PathLike],
|
| 286 |
+
content: str,
|
| 287 |
+
add_after: Optional[Union[str, Pattern]] = None,
|
| 288 |
+
add_before: Optional[Union[str, Pattern]] = None,
|
| 289 |
+
exact_match: bool = False,
|
| 290 |
+
):
|
| 291 |
+
"""
|
| 292 |
+
A utility to add some content inside a given file.
|
| 293 |
+
|
| 294 |
+
Args:
|
| 295 |
+
file_name (`str` or `os.PathLike`): The name of the file in which we want to insert some content.
|
| 296 |
+
content (`str`): The content to add.
|
| 297 |
+
add_after (`str` or `Pattern`):
|
| 298 |
+
The pattern to test on a line of `text`, the new content is added after the first instance matching it.
|
| 299 |
+
add_before (`str` or `Pattern`):
|
| 300 |
+
The pattern to test on a line of `text`, the new content is added before the first instance matching it.
|
| 301 |
+
exact_match (`bool`, *optional*, defaults to `False`):
|
| 302 |
+
A line is considered a match with `add_after` or `add_before` if it matches exactly when `exact_match=True`,
|
| 303 |
+
otherwise, if `add_after`/`add_before` is present in the line.
|
| 304 |
+
|
| 305 |
+
<Tip warning={true}>
|
| 306 |
+
|
| 307 |
+
The arguments `add_after` and `add_before` are mutually exclusive, and one exactly needs to be provided.
|
| 308 |
+
|
| 309 |
+
</Tip>
|
| 310 |
+
"""
|
| 311 |
+
with open(file_name, "r", encoding="utf-8") as f:
|
| 312 |
+
old_content = f.read()
|
| 313 |
+
|
| 314 |
+
new_content = add_content_to_text(
|
| 315 |
+
old_content, content, add_after=add_after, add_before=add_before, exact_match=exact_match
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
with open(file_name, "w", encoding="utf-8") as f:
|
| 319 |
+
f.write(new_content)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def replace_model_patterns(
|
| 323 |
+
text: str, old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns
|
| 324 |
+
) -> Tuple[str, str]:
|
| 325 |
+
"""
|
| 326 |
+
Replace all patterns present in a given text.
|
| 327 |
+
|
| 328 |
+
Args:
|
| 329 |
+
text (`str`): The text to treat.
|
| 330 |
+
old_model_patterns (`ModelPatterns`): The patterns for the old model.
|
| 331 |
+
new_model_patterns (`ModelPatterns`): The patterns for the new model.
|
| 332 |
+
|
| 333 |
+
Returns:
|
| 334 |
+
`Tuple(str, str)`: A tuple of with the treated text and the replacement actually done in it.
|
| 335 |
+
"""
|
| 336 |
+
# The order is crucially important as we will check and replace in that order. For instance the config probably
|
| 337 |
+
# contains the camel-cased named, but will be treated before.
|
| 338 |
+
attributes_to_check = ["config_class"]
|
| 339 |
+
# Add relevant preprocessing classes
|
| 340 |
+
for attr in ["tokenizer_class", "image_processor_class", "feature_extractor_class", "processor_class"]:
|
| 341 |
+
if getattr(old_model_patterns, attr) is not None and getattr(new_model_patterns, attr) is not None:
|
| 342 |
+
attributes_to_check.append(attr)
|
| 343 |
+
|
| 344 |
+
# Special cases for checkpoint and model_type
|
| 345 |
+
if old_model_patterns.checkpoint not in [old_model_patterns.model_type, old_model_patterns.model_lower_cased]:
|
| 346 |
+
attributes_to_check.append("checkpoint")
|
| 347 |
+
if old_model_patterns.model_type != old_model_patterns.model_lower_cased:
|
| 348 |
+
attributes_to_check.append("model_type")
|
| 349 |
+
else:
|
| 350 |
+
text = re.sub(
|
| 351 |
+
rf'(\s*)model_type = "{old_model_patterns.model_type}"',
|
| 352 |
+
r'\1model_type = "[MODEL_TYPE]"',
|
| 353 |
+
text,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
# Special case when the model camel cased and upper cased names are the same for the old model (like for GPT2) but
|
| 357 |
+
# not the new one. We can't just do a replace in all the text and will need a special regex
|
| 358 |
+
if old_model_patterns.model_upper_cased == old_model_patterns.model_camel_cased:
|
| 359 |
+
old_model_value = old_model_patterns.model_upper_cased
|
| 360 |
+
if re.search(rf"{old_model_value}_[A-Z_]*[^A-Z_]", text) is not None:
|
| 361 |
+
text = re.sub(rf"{old_model_value}([A-Z_]*)([^a-zA-Z_])", r"[MODEL_UPPER_CASED]\1\2", text)
|
| 362 |
+
else:
|
| 363 |
+
attributes_to_check.append("model_upper_cased")
|
| 364 |
+
|
| 365 |
+
attributes_to_check.extend(["model_camel_cased", "model_lower_cased", "model_name"])
|
| 366 |
+
|
| 367 |
+
# Now let's replace every other attribute by their placeholder
|
| 368 |
+
for attr in attributes_to_check:
|
| 369 |
+
text = text.replace(getattr(old_model_patterns, attr), ATTRIBUTE_TO_PLACEHOLDER[attr])
|
| 370 |
+
|
| 371 |
+
# Finally we can replace the placeholder byt the new values.
|
| 372 |
+
replacements = []
|
| 373 |
+
for attr, placeholder in ATTRIBUTE_TO_PLACEHOLDER.items():
|
| 374 |
+
if placeholder in text:
|
| 375 |
+
replacements.append((getattr(old_model_patterns, attr), getattr(new_model_patterns, attr)))
|
| 376 |
+
text = text.replace(placeholder, getattr(new_model_patterns, attr))
|
| 377 |
+
|
| 378 |
+
# If we have two inconsistent replacements, we don't return anything (ex: GPT2->GPT_NEW and GPT2->GPTNew)
|
| 379 |
+
old_replacement_values = [old for old, new in replacements]
|
| 380 |
+
if len(set(old_replacement_values)) != len(old_replacement_values):
|
| 381 |
+
return text, ""
|
| 382 |
+
|
| 383 |
+
replacements = simplify_replacements(replacements)
|
| 384 |
+
replacements = [f"{old}->{new}" for old, new in replacements]
|
| 385 |
+
return text, ",".join(replacements)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def simplify_replacements(replacements):
|
| 389 |
+
"""
|
| 390 |
+
Simplify a list of replacement patterns to make sure there are no needless ones.
|
| 391 |
+
|
| 392 |
+
For instance in the sequence "Bert->BertNew, BertConfig->BertNewConfig, bert->bert_new", the replacement
|
| 393 |
+
"BertConfig->BertNewConfig" is implied by "Bert->BertNew" so not needed.
|
| 394 |
+
|
| 395 |
+
Args:
|
| 396 |
+
replacements (`List[Tuple[str, str]]`): List of patterns (old, new)
|
| 397 |
+
|
| 398 |
+
Returns:
|
| 399 |
+
`List[Tuple[str, str]]`: The list of patterns simplified.
|
| 400 |
+
"""
|
| 401 |
+
if len(replacements) <= 1:
|
| 402 |
+
# Nothing to simplify
|
| 403 |
+
return replacements
|
| 404 |
+
|
| 405 |
+
# Next let's sort replacements by length as a replacement can only "imply" another replacement if it's shorter.
|
| 406 |
+
replacements.sort(key=lambda x: len(x[0]))
|
| 407 |
+
|
| 408 |
+
idx = 0
|
| 409 |
+
while idx < len(replacements):
|
| 410 |
+
old, new = replacements[idx]
|
| 411 |
+
# Loop through all replacements after
|
| 412 |
+
j = idx + 1
|
| 413 |
+
while j < len(replacements):
|
| 414 |
+
old_2, new_2 = replacements[j]
|
| 415 |
+
# If the replacement is implied by the current one, we can drop it.
|
| 416 |
+
if old_2.replace(old, new) == new_2:
|
| 417 |
+
replacements.pop(j)
|
| 418 |
+
else:
|
| 419 |
+
j += 1
|
| 420 |
+
idx += 1
|
| 421 |
+
|
| 422 |
+
return replacements
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def get_module_from_file(module_file: Union[str, os.PathLike]) -> str:
|
| 426 |
+
"""
|
| 427 |
+
Returns the module name corresponding to a module file.
|
| 428 |
+
"""
|
| 429 |
+
full_module_path = Path(module_file).absolute()
|
| 430 |
+
module_parts = full_module_path.with_suffix("").parts
|
| 431 |
+
|
| 432 |
+
# Find the first part named transformers, starting from the end.
|
| 433 |
+
idx = len(module_parts) - 1
|
| 434 |
+
while idx >= 0 and module_parts[idx] != "transformers":
|
| 435 |
+
idx -= 1
|
| 436 |
+
if idx < 0:
|
| 437 |
+
raise ValueError(f"{module_file} is not a transformers module.")
|
| 438 |
+
|
| 439 |
+
return ".".join(module_parts[idx:])
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
SPECIAL_PATTERNS = {
|
| 443 |
+
"_CHECKPOINT_FOR_DOC =": "checkpoint",
|
| 444 |
+
"_CONFIG_FOR_DOC =": "config_class",
|
| 445 |
+
"_TOKENIZER_FOR_DOC =": "tokenizer_class",
|
| 446 |
+
"_IMAGE_PROCESSOR_FOR_DOC =": "image_processor_class",
|
| 447 |
+
"_FEAT_EXTRACTOR_FOR_DOC =": "feature_extractor_class",
|
| 448 |
+
"_PROCESSOR_FOR_DOC =": "processor_class",
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
_re_class_func = re.compile(r"^(?:class|def)\s+([^\s:\(]+)\s*(?:\(|\:)", flags=re.MULTILINE)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def remove_attributes(obj, target_attr):
|
| 456 |
+
"""Remove `target_attr` in `obj`."""
|
| 457 |
+
lines = obj.split(os.linesep)
|
| 458 |
+
|
| 459 |
+
target_idx = None
|
| 460 |
+
for idx, line in enumerate(lines):
|
| 461 |
+
# search for assignment
|
| 462 |
+
if line.lstrip().startswith(f"{target_attr} = "):
|
| 463 |
+
target_idx = idx
|
| 464 |
+
break
|
| 465 |
+
# search for function/method definition
|
| 466 |
+
elif line.lstrip().startswith(f"def {target_attr}("):
|
| 467 |
+
target_idx = idx
|
| 468 |
+
break
|
| 469 |
+
|
| 470 |
+
# target not found
|
| 471 |
+
if target_idx is None:
|
| 472 |
+
return obj
|
| 473 |
+
|
| 474 |
+
line = lines[target_idx]
|
| 475 |
+
indent_level = find_indent(line)
|
| 476 |
+
# forward pass to find the ending of the block (including empty lines)
|
| 477 |
+
parsed = extract_block("\n".join(lines[target_idx:]), indent_level)
|
| 478 |
+
num_lines = len(parsed.split("\n"))
|
| 479 |
+
for idx in range(num_lines):
|
| 480 |
+
lines[target_idx + idx] = None
|
| 481 |
+
|
| 482 |
+
# backward pass to find comments or decorator
|
| 483 |
+
for idx in range(target_idx - 1, -1, -1):
|
| 484 |
+
line = lines[idx]
|
| 485 |
+
if (line.lstrip().startswith("#") or line.lstrip().startswith("@")) and find_indent(line) == indent_level:
|
| 486 |
+
lines[idx] = None
|
| 487 |
+
else:
|
| 488 |
+
break
|
| 489 |
+
|
| 490 |
+
new_obj = os.linesep.join([x for x in lines if x is not None])
|
| 491 |
+
|
| 492 |
+
return new_obj
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def duplicate_module(
|
| 496 |
+
module_file: Union[str, os.PathLike],
|
| 497 |
+
old_model_patterns: ModelPatterns,
|
| 498 |
+
new_model_patterns: ModelPatterns,
|
| 499 |
+
dest_file: Optional[str] = None,
|
| 500 |
+
add_copied_from: bool = True,
|
| 501 |
+
attrs_to_remove: List[str] = None,
|
| 502 |
+
):
|
| 503 |
+
"""
|
| 504 |
+
Create a new module from an existing one and adapting all function and classes names from old patterns to new ones.
|
| 505 |
+
|
| 506 |
+
Args:
|
| 507 |
+
module_file (`str` or `os.PathLike`): Path to the module to duplicate.
|
| 508 |
+
old_model_patterns (`ModelPatterns`): The patterns for the old model.
|
| 509 |
+
new_model_patterns (`ModelPatterns`): The patterns for the new model.
|
| 510 |
+
dest_file (`str` or `os.PathLike`, *optional*): Path to the new module.
|
| 511 |
+
add_copied_from (`bool`, *optional*, defaults to `True`):
|
| 512 |
+
Whether or not to add `# Copied from` statements in the duplicated module.
|
| 513 |
+
"""
|
| 514 |
+
if dest_file is None:
|
| 515 |
+
dest_file = str(module_file).replace(
|
| 516 |
+
old_model_patterns.model_lower_cased, new_model_patterns.model_lower_cased
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
with open(module_file, "r", encoding="utf-8") as f:
|
| 520 |
+
content = f.read()
|
| 521 |
+
|
| 522 |
+
content = re.sub(r"# Copyright (\d+)\s", f"# Copyright {CURRENT_YEAR} ", content)
|
| 523 |
+
objects = parse_module_content(content)
|
| 524 |
+
|
| 525 |
+
# Loop and treat all objects
|
| 526 |
+
new_objects = []
|
| 527 |
+
for obj in objects:
|
| 528 |
+
# Special cases
|
| 529 |
+
if "PRETRAINED_CONFIG_ARCHIVE_MAP = {" in obj:
|
| 530 |
+
# docstyle-ignore
|
| 531 |
+
obj = (
|
| 532 |
+
f"{new_model_patterns.model_upper_cased}_PRETRAINED_CONFIG_ARCHIVE_MAP = "
|
| 533 |
+
+ "{"
|
| 534 |
+
+ f"""
|
| 535 |
+
"{new_model_patterns.checkpoint}": "https://huggingface.co/{new_model_patterns.checkpoint}/resolve/main/config.json",
|
| 536 |
+
"""
|
| 537 |
+
+ "}\n"
|
| 538 |
+
)
|
| 539 |
+
new_objects.append(obj)
|
| 540 |
+
continue
|
| 541 |
+
elif "PRETRAINED_MODEL_ARCHIVE_LIST = [" in obj:
|
| 542 |
+
if obj.startswith("TF_"):
|
| 543 |
+
prefix = "TF_"
|
| 544 |
+
elif obj.startswith("FLAX_"):
|
| 545 |
+
prefix = "FLAX_"
|
| 546 |
+
else:
|
| 547 |
+
prefix = ""
|
| 548 |
+
# docstyle-ignore
|
| 549 |
+
obj = f"""{prefix}{new_model_patterns.model_upper_cased}_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 550 |
+
"{new_model_patterns.checkpoint}",
|
| 551 |
+
# See all {new_model_patterns.model_name} models at https://huggingface.co/models?filter={new_model_patterns.model_type}
|
| 552 |
+
]
|
| 553 |
+
"""
|
| 554 |
+
new_objects.append(obj)
|
| 555 |
+
continue
|
| 556 |
+
|
| 557 |
+
special_pattern = False
|
| 558 |
+
for pattern, attr in SPECIAL_PATTERNS.items():
|
| 559 |
+
if pattern in obj:
|
| 560 |
+
obj = obj.replace(getattr(old_model_patterns, attr), getattr(new_model_patterns, attr))
|
| 561 |
+
new_objects.append(obj)
|
| 562 |
+
special_pattern = True
|
| 563 |
+
break
|
| 564 |
+
|
| 565 |
+
if special_pattern:
|
| 566 |
+
continue
|
| 567 |
+
|
| 568 |
+
# Regular classes functions
|
| 569 |
+
old_obj = obj
|
| 570 |
+
obj, replacement = replace_model_patterns(obj, old_model_patterns, new_model_patterns)
|
| 571 |
+
has_copied_from = re.search(r"^#\s+Copied from", obj, flags=re.MULTILINE) is not None
|
| 572 |
+
if add_copied_from and not has_copied_from and _re_class_func.search(obj) is not None and len(replacement) > 0:
|
| 573 |
+
# Copied from statement must be added just before the class/function definition, which may not be the
|
| 574 |
+
# first line because of decorators.
|
| 575 |
+
module_name = get_module_from_file(module_file)
|
| 576 |
+
old_object_name = _re_class_func.search(old_obj).groups()[0]
|
| 577 |
+
obj = add_content_to_text(
|
| 578 |
+
obj, f"# Copied from {module_name}.{old_object_name} with {replacement}", add_before=_re_class_func
|
| 579 |
+
)
|
| 580 |
+
# In all cases, we remove Copied from statement with indent on methods.
|
| 581 |
+
obj = re.sub("\n[ ]+# Copied from [^\n]*\n", "\n", obj)
|
| 582 |
+
|
| 583 |
+
new_objects.append(obj)
|
| 584 |
+
|
| 585 |
+
content = "\n".join(new_objects)
|
| 586 |
+
# Remove some attributes that we don't want to copy to the new file(s)
|
| 587 |
+
if attrs_to_remove is not None:
|
| 588 |
+
for attr in attrs_to_remove:
|
| 589 |
+
content = remove_attributes(content, target_attr=attr)
|
| 590 |
+
|
| 591 |
+
with open(dest_file, "w", encoding="utf-8") as f:
|
| 592 |
+
f.write(content)
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def filter_framework_files(
|
| 596 |
+
files: List[Union[str, os.PathLike]], frameworks: Optional[List[str]] = None
|
| 597 |
+
) -> List[Union[str, os.PathLike]]:
|
| 598 |
+
"""
|
| 599 |
+
Filter a list of files to only keep the ones corresponding to a list of frameworks.
|
| 600 |
+
|
| 601 |
+
Args:
|
| 602 |
+
files (`List[Union[str, os.PathLike]]`): The list of files to filter.
|
| 603 |
+
frameworks (`List[str]`, *optional*): The list of allowed frameworks.
|
| 604 |
+
|
| 605 |
+
Returns:
|
| 606 |
+
`List[Union[str, os.PathLike]]`: The list of filtered files.
|
| 607 |
+
"""
|
| 608 |
+
if frameworks is None:
|
| 609 |
+
frameworks = get_default_frameworks()
|
| 610 |
+
|
| 611 |
+
framework_to_file = {}
|
| 612 |
+
others = []
|
| 613 |
+
for f in files:
|
| 614 |
+
parts = Path(f).name.split("_")
|
| 615 |
+
if "modeling" not in parts:
|
| 616 |
+
others.append(f)
|
| 617 |
+
continue
|
| 618 |
+
if "tf" in parts:
|
| 619 |
+
framework_to_file["tf"] = f
|
| 620 |
+
elif "flax" in parts:
|
| 621 |
+
framework_to_file["flax"] = f
|
| 622 |
+
else:
|
| 623 |
+
framework_to_file["pt"] = f
|
| 624 |
+
|
| 625 |
+
return [framework_to_file[f] for f in frameworks if f in framework_to_file] + others
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
def get_model_files(model_type: str, frameworks: Optional[List[str]] = None) -> Dict[str, Union[Path, List[Path]]]:
|
| 629 |
+
"""
|
| 630 |
+
Retrieves all the files associated to a model.
|
| 631 |
+
|
| 632 |
+
Args:
|
| 633 |
+
model_type (`str`): A valid model type (like "bert" or "gpt2")
|
| 634 |
+
frameworks (`List[str]`, *optional*):
|
| 635 |
+
If passed, will only keep the model files corresponding to the passed frameworks.
|
| 636 |
+
|
| 637 |
+
Returns:
|
| 638 |
+
`Dict[str, Union[Path, List[Path]]]`: A dictionary with the following keys:
|
| 639 |
+
- **doc_file** -- The documentation file for the model.
|
| 640 |
+
- **model_files** -- All the files in the model module.
|
| 641 |
+
- **test_files** -- The test files for the model.
|
| 642 |
+
"""
|
| 643 |
+
module_name = model_type_to_module_name(model_type)
|
| 644 |
+
|
| 645 |
+
model_module = TRANSFORMERS_PATH / "models" / module_name
|
| 646 |
+
model_files = list(model_module.glob("*.py"))
|
| 647 |
+
model_files = filter_framework_files(model_files, frameworks=frameworks)
|
| 648 |
+
|
| 649 |
+
doc_file = REPO_PATH / "docs" / "source" / "en" / "model_doc" / f"{model_type}.mdx"
|
| 650 |
+
|
| 651 |
+
# Basic pattern for test files
|
| 652 |
+
test_files = [
|
| 653 |
+
f"test_modeling_{module_name}.py",
|
| 654 |
+
f"test_modeling_tf_{module_name}.py",
|
| 655 |
+
f"test_modeling_flax_{module_name}.py",
|
| 656 |
+
f"test_tokenization_{module_name}.py",
|
| 657 |
+
f"test_image_processing_{module_name}.py",
|
| 658 |
+
f"test_feature_extraction_{module_name}.py",
|
| 659 |
+
f"test_processor_{module_name}.py",
|
| 660 |
+
]
|
| 661 |
+
test_files = filter_framework_files(test_files, frameworks=frameworks)
|
| 662 |
+
# Add the test directory
|
| 663 |
+
test_files = [REPO_PATH / "tests" / "models" / module_name / f for f in test_files]
|
| 664 |
+
# Filter by existing files
|
| 665 |
+
test_files = [f for f in test_files if f.exists()]
|
| 666 |
+
|
| 667 |
+
return {"doc_file": doc_file, "model_files": model_files, "module_name": module_name, "test_files": test_files}
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
_re_checkpoint_for_doc = re.compile(r"^_CHECKPOINT_FOR_DOC\s+=\s+(\S*)\s*$", flags=re.MULTILINE)
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
def find_base_model_checkpoint(
|
| 674 |
+
model_type: str, model_files: Optional[Dict[str, Union[Path, List[Path]]]] = None
|
| 675 |
+
) -> str:
|
| 676 |
+
"""
|
| 677 |
+
Finds the model checkpoint used in the docstrings for a given model.
|
| 678 |
+
|
| 679 |
+
Args:
|
| 680 |
+
model_type (`str`): A valid model type (like "bert" or "gpt2")
|
| 681 |
+
model_files (`Dict[str, Union[Path, List[Path]]`, *optional*):
|
| 682 |
+
The files associated to `model_type`. Can be passed to speed up the function, otherwise will be computed.
|
| 683 |
+
|
| 684 |
+
Returns:
|
| 685 |
+
`str`: The checkpoint used.
|
| 686 |
+
"""
|
| 687 |
+
if model_files is None:
|
| 688 |
+
model_files = get_model_files(model_type)
|
| 689 |
+
module_files = model_files["model_files"]
|
| 690 |
+
for fname in module_files:
|
| 691 |
+
if "modeling" not in str(fname):
|
| 692 |
+
continue
|
| 693 |
+
|
| 694 |
+
with open(fname, "r", encoding="utf-8") as f:
|
| 695 |
+
content = f.read()
|
| 696 |
+
if _re_checkpoint_for_doc.search(content) is not None:
|
| 697 |
+
checkpoint = _re_checkpoint_for_doc.search(content).groups()[0]
|
| 698 |
+
# Remove quotes
|
| 699 |
+
checkpoint = checkpoint.replace('"', "")
|
| 700 |
+
checkpoint = checkpoint.replace("'", "")
|
| 701 |
+
return checkpoint
|
| 702 |
+
|
| 703 |
+
# TODO: Find some kind of fallback if there is no _CHECKPOINT_FOR_DOC in any of the modeling file.
|
| 704 |
+
return ""
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
def get_default_frameworks():
|
| 708 |
+
"""
|
| 709 |
+
Returns the list of frameworks (PyTorch, TensorFlow, Flax) that are installed in the environment.
|
| 710 |
+
"""
|
| 711 |
+
frameworks = []
|
| 712 |
+
if is_torch_available():
|
| 713 |
+
frameworks.append("pt")
|
| 714 |
+
if is_tf_available():
|
| 715 |
+
frameworks.append("tf")
|
| 716 |
+
if is_flax_available():
|
| 717 |
+
frameworks.append("flax")
|
| 718 |
+
return frameworks
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
_re_model_mapping = re.compile("MODEL_([A-Z_]*)MAPPING_NAMES")
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def retrieve_model_classes(model_type: str, frameworks: Optional[List[str]] = None) -> Dict[str, List[str]]:
|
| 725 |
+
"""
|
| 726 |
+
Retrieve the model classes associated to a given model.
|
| 727 |
+
|
| 728 |
+
Args:
|
| 729 |
+
model_type (`str`): A valid model type (like "bert" or "gpt2")
|
| 730 |
+
frameworks (`List[str]`, *optional*):
|
| 731 |
+
The frameworks to look for. Will default to `["pt", "tf", "flax"]`, passing a smaller list will restrict
|
| 732 |
+
the classes returned.
|
| 733 |
+
|
| 734 |
+
Returns:
|
| 735 |
+
`Dict[str, List[str]]`: A dictionary with one key per framework and the list of model classes associated to
|
| 736 |
+
that framework as values.
|
| 737 |
+
"""
|
| 738 |
+
if frameworks is None:
|
| 739 |
+
frameworks = get_default_frameworks()
|
| 740 |
+
|
| 741 |
+
modules = {
|
| 742 |
+
"pt": auto_module.modeling_auto if is_torch_available() else None,
|
| 743 |
+
"tf": auto_module.modeling_tf_auto if is_tf_available() else None,
|
| 744 |
+
"flax": auto_module.modeling_flax_auto if is_flax_available() else None,
|
| 745 |
+
}
|
| 746 |
+
|
| 747 |
+
model_classes = {}
|
| 748 |
+
for framework in frameworks:
|
| 749 |
+
new_model_classes = []
|
| 750 |
+
if modules[framework] is None:
|
| 751 |
+
raise ValueError(f"You selected {framework} in the frameworks, but it is not installed.")
|
| 752 |
+
model_mappings = [attr for attr in dir(modules[framework]) if _re_model_mapping.search(attr) is not None]
|
| 753 |
+
for model_mapping_name in model_mappings:
|
| 754 |
+
model_mapping = getattr(modules[framework], model_mapping_name)
|
| 755 |
+
if model_type in model_mapping:
|
| 756 |
+
new_model_classes.append(model_mapping[model_type])
|
| 757 |
+
|
| 758 |
+
if len(new_model_classes) > 0:
|
| 759 |
+
# Remove duplicates
|
| 760 |
+
model_classes[framework] = list(set(new_model_classes))
|
| 761 |
+
|
| 762 |
+
return model_classes
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
def retrieve_info_for_model(model_type, frameworks: Optional[List[str]] = None):
|
| 766 |
+
"""
|
| 767 |
+
Retrieves all the information from a given model_type.
|
| 768 |
+
|
| 769 |
+
Args:
|
| 770 |
+
model_type (`str`): A valid model type (like "bert" or "gpt2")
|
| 771 |
+
frameworks (`List[str]`, *optional*):
|
| 772 |
+
If passed, will only keep the info corresponding to the passed frameworks.
|
| 773 |
+
|
| 774 |
+
Returns:
|
| 775 |
+
`Dict`: A dictionary with the following keys:
|
| 776 |
+
- **frameworks** (`List[str]`): The list of frameworks that back this model type.
|
| 777 |
+
- **model_classes** (`Dict[str, List[str]]`): The model classes implemented for that model type.
|
| 778 |
+
- **model_files** (`Dict[str, Union[Path, List[Path]]]`): The files associated with that model type.
|
| 779 |
+
- **model_patterns** (`ModelPatterns`): The various patterns for the model.
|
| 780 |
+
"""
|
| 781 |
+
if model_type not in auto_module.MODEL_NAMES_MAPPING:
|
| 782 |
+
raise ValueError(f"{model_type} is not a valid model type.")
|
| 783 |
+
|
| 784 |
+
model_name = auto_module.MODEL_NAMES_MAPPING[model_type]
|
| 785 |
+
config_class = auto_module.configuration_auto.CONFIG_MAPPING_NAMES[model_type]
|
| 786 |
+
archive_map = auto_module.configuration_auto.CONFIG_ARCHIVE_MAP_MAPPING_NAMES.get(model_type, None)
|
| 787 |
+
if model_type in auto_module.tokenization_auto.TOKENIZER_MAPPING_NAMES:
|
| 788 |
+
tokenizer_classes = auto_module.tokenization_auto.TOKENIZER_MAPPING_NAMES[model_type]
|
| 789 |
+
tokenizer_class = tokenizer_classes[0] if tokenizer_classes[0] is not None else tokenizer_classes[1]
|
| 790 |
+
else:
|
| 791 |
+
tokenizer_class = None
|
| 792 |
+
image_processor_class = auto_module.image_processing_auto.IMAGE_PROCESSOR_MAPPING_NAMES.get(model_type, None)
|
| 793 |
+
feature_extractor_class = auto_module.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES.get(model_type, None)
|
| 794 |
+
processor_class = auto_module.processing_auto.PROCESSOR_MAPPING_NAMES.get(model_type, None)
|
| 795 |
+
|
| 796 |
+
model_files = get_model_files(model_type, frameworks=frameworks)
|
| 797 |
+
model_camel_cased = config_class.replace("Config", "")
|
| 798 |
+
|
| 799 |
+
available_frameworks = []
|
| 800 |
+
for fname in model_files["model_files"]:
|
| 801 |
+
if "modeling_tf" in str(fname):
|
| 802 |
+
available_frameworks.append("tf")
|
| 803 |
+
elif "modeling_flax" in str(fname):
|
| 804 |
+
available_frameworks.append("flax")
|
| 805 |
+
elif "modeling" in str(fname):
|
| 806 |
+
available_frameworks.append("pt")
|
| 807 |
+
|
| 808 |
+
if frameworks is None:
|
| 809 |
+
frameworks = get_default_frameworks()
|
| 810 |
+
|
| 811 |
+
frameworks = [f for f in frameworks if f in available_frameworks]
|
| 812 |
+
|
| 813 |
+
model_classes = retrieve_model_classes(model_type, frameworks=frameworks)
|
| 814 |
+
|
| 815 |
+
# Retrieve model upper-cased name from the constant name of the pretrained archive map.
|
| 816 |
+
if archive_map is None:
|
| 817 |
+
model_upper_cased = model_camel_cased.upper()
|
| 818 |
+
else:
|
| 819 |
+
parts = archive_map.split("_")
|
| 820 |
+
idx = 0
|
| 821 |
+
while idx < len(parts) and parts[idx] != "PRETRAINED":
|
| 822 |
+
idx += 1
|
| 823 |
+
if idx < len(parts):
|
| 824 |
+
model_upper_cased = "_".join(parts[:idx])
|
| 825 |
+
else:
|
| 826 |
+
model_upper_cased = model_camel_cased.upper()
|
| 827 |
+
|
| 828 |
+
model_patterns = ModelPatterns(
|
| 829 |
+
model_name,
|
| 830 |
+
checkpoint=find_base_model_checkpoint(model_type, model_files=model_files),
|
| 831 |
+
model_type=model_type,
|
| 832 |
+
model_camel_cased=model_camel_cased,
|
| 833 |
+
model_lower_cased=model_files["module_name"],
|
| 834 |
+
model_upper_cased=model_upper_cased,
|
| 835 |
+
config_class=config_class,
|
| 836 |
+
tokenizer_class=tokenizer_class,
|
| 837 |
+
image_processor_class=image_processor_class,
|
| 838 |
+
feature_extractor_class=feature_extractor_class,
|
| 839 |
+
processor_class=processor_class,
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
return {
|
| 843 |
+
"frameworks": frameworks,
|
| 844 |
+
"model_classes": model_classes,
|
| 845 |
+
"model_files": model_files,
|
| 846 |
+
"model_patterns": model_patterns,
|
| 847 |
+
}
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
def clean_frameworks_in_init(
|
| 851 |
+
init_file: Union[str, os.PathLike], frameworks: Optional[List[str]] = None, keep_processing: bool = True
|
| 852 |
+
):
|
| 853 |
+
"""
|
| 854 |
+
Removes all the import lines that don't belong to a given list of frameworks or concern tokenizers/feature
|
| 855 |
+
extractors/image processors/processors in an init.
|
| 856 |
+
|
| 857 |
+
Args:
|
| 858 |
+
init_file (`str` or `os.PathLike`): The path to the init to treat.
|
| 859 |
+
frameworks (`List[str]`, *optional*):
|
| 860 |
+
If passed, this will remove all imports that are subject to a framework not in frameworks
|
| 861 |
+
keep_processing (`bool`, *optional*, defaults to `True`):
|
| 862 |
+
Whether or not to keep the preprocessing (tokenizer, feature extractor, image processor, processor) imports
|
| 863 |
+
in the init.
|
| 864 |
+
"""
|
| 865 |
+
if frameworks is None:
|
| 866 |
+
frameworks = get_default_frameworks()
|
| 867 |
+
|
| 868 |
+
names = {"pt": "torch"}
|
| 869 |
+
to_remove = [names.get(f, f) for f in ["pt", "tf", "flax"] if f not in frameworks]
|
| 870 |
+
if not keep_processing:
|
| 871 |
+
to_remove.extend(["sentencepiece", "tokenizers", "vision"])
|
| 872 |
+
|
| 873 |
+
if len(to_remove) == 0:
|
| 874 |
+
# Nothing to do
|
| 875 |
+
return
|
| 876 |
+
|
| 877 |
+
remove_pattern = "|".join(to_remove)
|
| 878 |
+
re_conditional_imports = re.compile(rf"^\s*if not is_({remove_pattern})_available\(\):\s*$")
|
| 879 |
+
re_try = re.compile(r"\s*try:")
|
| 880 |
+
re_else = re.compile(r"\s*else:")
|
| 881 |
+
re_is_xxx_available = re.compile(rf"is_({remove_pattern})_available")
|
| 882 |
+
|
| 883 |
+
with open(init_file, "r", encoding="utf-8") as f:
|
| 884 |
+
content = f.read()
|
| 885 |
+
|
| 886 |
+
lines = content.split("\n")
|
| 887 |
+
new_lines = []
|
| 888 |
+
idx = 0
|
| 889 |
+
while idx < len(lines):
|
| 890 |
+
# Conditional imports in try-except-else blocks
|
| 891 |
+
if (re_conditional_imports.search(lines[idx]) is not None) and (re_try.search(lines[idx - 1]) is not None):
|
| 892 |
+
# Remove the preceding `try:`
|
| 893 |
+
new_lines.pop()
|
| 894 |
+
idx += 1
|
| 895 |
+
# Iterate until `else:`
|
| 896 |
+
while is_empty_line(lines[idx]) or re_else.search(lines[idx]) is None:
|
| 897 |
+
idx += 1
|
| 898 |
+
idx += 1
|
| 899 |
+
indent = find_indent(lines[idx])
|
| 900 |
+
while find_indent(lines[idx]) >= indent or is_empty_line(lines[idx]):
|
| 901 |
+
idx += 1
|
| 902 |
+
# Remove the import from utils
|
| 903 |
+
elif re_is_xxx_available.search(lines[idx]) is not None:
|
| 904 |
+
line = lines[idx]
|
| 905 |
+
for framework in to_remove:
|
| 906 |
+
line = line.replace(f", is_{framework}_available", "")
|
| 907 |
+
line = line.replace(f"is_{framework}_available, ", "")
|
| 908 |
+
line = line.replace(f"is_{framework}_available,", "")
|
| 909 |
+
line = line.replace(f"is_{framework}_available", "")
|
| 910 |
+
|
| 911 |
+
if len(line.strip()) > 0:
|
| 912 |
+
new_lines.append(line)
|
| 913 |
+
idx += 1
|
| 914 |
+
# Otherwise we keep the line, except if it's a tokenizer import and we don't want to keep it.
|
| 915 |
+
elif keep_processing or (
|
| 916 |
+
re.search(r'^\s*"(tokenization|processing|feature_extraction|image_processing)', lines[idx]) is None
|
| 917 |
+
and re.search(r"^\s*from .(tokenization|processing|feature_extraction|image_processing)", lines[idx])
|
| 918 |
+
is None
|
| 919 |
+
):
|
| 920 |
+
new_lines.append(lines[idx])
|
| 921 |
+
idx += 1
|
| 922 |
+
else:
|
| 923 |
+
idx += 1
|
| 924 |
+
|
| 925 |
+
with open(init_file, "w", encoding="utf-8") as f:
|
| 926 |
+
f.write("\n".join(new_lines))
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
def add_model_to_main_init(
|
| 930 |
+
old_model_patterns: ModelPatterns,
|
| 931 |
+
new_model_patterns: ModelPatterns,
|
| 932 |
+
frameworks: Optional[List[str]] = None,
|
| 933 |
+
with_processing: bool = True,
|
| 934 |
+
):
|
| 935 |
+
"""
|
| 936 |
+
Add a model to the main init of Transformers.
|
| 937 |
+
|
| 938 |
+
Args:
|
| 939 |
+
old_model_patterns (`ModelPatterns`): The patterns for the old model.
|
| 940 |
+
new_model_patterns (`ModelPatterns`): The patterns for the new model.
|
| 941 |
+
frameworks (`List[str]`, *optional*):
|
| 942 |
+
If specified, only the models implemented in those frameworks will be added.
|
| 943 |
+
with_processsing (`bool`, *optional*, defaults to `True`):
|
| 944 |
+
Whether the tokenizer/feature extractor/processor of the model should also be added to the init or not.
|
| 945 |
+
"""
|
| 946 |
+
with open(TRANSFORMERS_PATH / "__init__.py", "r", encoding="utf-8") as f:
|
| 947 |
+
content = f.read()
|
| 948 |
+
|
| 949 |
+
lines = content.split("\n")
|
| 950 |
+
idx = 0
|
| 951 |
+
new_lines = []
|
| 952 |
+
framework = None
|
| 953 |
+
while idx < len(lines):
|
| 954 |
+
new_framework = False
|
| 955 |
+
if not is_empty_line(lines[idx]) and find_indent(lines[idx]) == 0:
|
| 956 |
+
framework = None
|
| 957 |
+
elif lines[idx].lstrip().startswith("if not is_torch_available"):
|
| 958 |
+
framework = "pt"
|
| 959 |
+
new_framework = True
|
| 960 |
+
elif lines[idx].lstrip().startswith("if not is_tf_available"):
|
| 961 |
+
framework = "tf"
|
| 962 |
+
new_framework = True
|
| 963 |
+
elif lines[idx].lstrip().startswith("if not is_flax_available"):
|
| 964 |
+
framework = "flax"
|
| 965 |
+
new_framework = True
|
| 966 |
+
|
| 967 |
+
if new_framework:
|
| 968 |
+
# For a new framework, we need to skip until the else: block to get where the imports are.
|
| 969 |
+
while lines[idx].strip() != "else:":
|
| 970 |
+
new_lines.append(lines[idx])
|
| 971 |
+
idx += 1
|
| 972 |
+
|
| 973 |
+
# Skip if we are in a framework not wanted.
|
| 974 |
+
if framework is not None and frameworks is not None and framework not in frameworks:
|
| 975 |
+
new_lines.append(lines[idx])
|
| 976 |
+
idx += 1
|
| 977 |
+
elif re.search(rf'models.{old_model_patterns.model_lower_cased}( |")', lines[idx]) is not None:
|
| 978 |
+
block = [lines[idx]]
|
| 979 |
+
indent = find_indent(lines[idx])
|
| 980 |
+
idx += 1
|
| 981 |
+
while find_indent(lines[idx]) > indent:
|
| 982 |
+
block.append(lines[idx])
|
| 983 |
+
idx += 1
|
| 984 |
+
if lines[idx].strip() in [")", "]", "],"]:
|
| 985 |
+
block.append(lines[idx])
|
| 986 |
+
idx += 1
|
| 987 |
+
block = "\n".join(block)
|
| 988 |
+
new_lines.append(block)
|
| 989 |
+
|
| 990 |
+
add_block = True
|
| 991 |
+
if not with_processing:
|
| 992 |
+
processing_classes = [
|
| 993 |
+
old_model_patterns.tokenizer_class,
|
| 994 |
+
old_model_patterns.image_processor_class,
|
| 995 |
+
old_model_patterns.feature_extractor_class,
|
| 996 |
+
old_model_patterns.processor_class,
|
| 997 |
+
]
|
| 998 |
+
# Only keep the ones that are not None
|
| 999 |
+
processing_classes = [c for c in processing_classes if c is not None]
|
| 1000 |
+
for processing_class in processing_classes:
|
| 1001 |
+
block = block.replace(f' "{processing_class}",', "")
|
| 1002 |
+
block = block.replace(f', "{processing_class}"', "")
|
| 1003 |
+
block = block.replace(f" {processing_class},", "")
|
| 1004 |
+
block = block.replace(f", {processing_class}", "")
|
| 1005 |
+
|
| 1006 |
+
if processing_class in block:
|
| 1007 |
+
add_block = False
|
| 1008 |
+
if add_block:
|
| 1009 |
+
new_lines.append(replace_model_patterns(block, old_model_patterns, new_model_patterns)[0])
|
| 1010 |
+
else:
|
| 1011 |
+
new_lines.append(lines[idx])
|
| 1012 |
+
idx += 1
|
| 1013 |
+
|
| 1014 |
+
with open(TRANSFORMERS_PATH / "__init__.py", "w", encoding="utf-8") as f:
|
| 1015 |
+
f.write("\n".join(new_lines))
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
def insert_tokenizer_in_auto_module(old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns):
|
| 1019 |
+
"""
|
| 1020 |
+
Add a tokenizer to the relevant mappings in the auto module.
|
| 1021 |
+
|
| 1022 |
+
Args:
|
| 1023 |
+
old_model_patterns (`ModelPatterns`): The patterns for the old model.
|
| 1024 |
+
new_model_patterns (`ModelPatterns`): The patterns for the new model.
|
| 1025 |
+
"""
|
| 1026 |
+
if old_model_patterns.tokenizer_class is None or new_model_patterns.tokenizer_class is None:
|
| 1027 |
+
return
|
| 1028 |
+
|
| 1029 |
+
with open(TRANSFORMERS_PATH / "models" / "auto" / "tokenization_auto.py", "r", encoding="utf-8") as f:
|
| 1030 |
+
content = f.read()
|
| 1031 |
+
|
| 1032 |
+
lines = content.split("\n")
|
| 1033 |
+
idx = 0
|
| 1034 |
+
# First we get to the TOKENIZER_MAPPING_NAMES block.
|
| 1035 |
+
while not lines[idx].startswith(" TOKENIZER_MAPPING_NAMES = OrderedDict("):
|
| 1036 |
+
idx += 1
|
| 1037 |
+
idx += 1
|
| 1038 |
+
|
| 1039 |
+
# That block will end at this prompt:
|
| 1040 |
+
while not lines[idx].startswith("TOKENIZER_MAPPING = _LazyAutoMapping"):
|
| 1041 |
+
# Either all the tokenizer block is defined on one line, in which case, it ends with "),"
|
| 1042 |
+
if lines[idx].endswith(","):
|
| 1043 |
+
block = lines[idx]
|
| 1044 |
+
# Otherwise it takes several lines until we get to a "),"
|
| 1045 |
+
else:
|
| 1046 |
+
block = []
|
| 1047 |
+
while not lines[idx].startswith(" ),"):
|
| 1048 |
+
block.append(lines[idx])
|
| 1049 |
+
idx += 1
|
| 1050 |
+
block = "\n".join(block)
|
| 1051 |
+
idx += 1
|
| 1052 |
+
|
| 1053 |
+
# If we find the model type and tokenizer class in that block, we have the old model tokenizer block
|
| 1054 |
+
if f'"{old_model_patterns.model_type}"' in block and old_model_patterns.tokenizer_class in block:
|
| 1055 |
+
break
|
| 1056 |
+
|
| 1057 |
+
new_block = block.replace(old_model_patterns.model_type, new_model_patterns.model_type)
|
| 1058 |
+
new_block = new_block.replace(old_model_patterns.tokenizer_class, new_model_patterns.tokenizer_class)
|
| 1059 |
+
|
| 1060 |
+
new_lines = lines[:idx] + [new_block] + lines[idx:]
|
| 1061 |
+
with open(TRANSFORMERS_PATH / "models" / "auto" / "tokenization_auto.py", "w", encoding="utf-8") as f:
|
| 1062 |
+
f.write("\n".join(new_lines))
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
AUTO_CLASSES_PATTERNS = {
|
| 1066 |
+
"configuration_auto.py": [
|
| 1067 |
+
' ("{model_type}", "{model_name}"),',
|
| 1068 |
+
' ("{model_type}", "{config_class}"),',
|
| 1069 |
+
' ("{model_type}", "{pretrained_archive_map}"),',
|
| 1070 |
+
],
|
| 1071 |
+
"feature_extraction_auto.py": [' ("{model_type}", "{feature_extractor_class}"),'],
|
| 1072 |
+
"image_processing_auto.py": [' ("{model_type}", "{image_processor_class}"),'],
|
| 1073 |
+
"modeling_auto.py": [' ("{model_type}", "{any_pt_class}"),'],
|
| 1074 |
+
"modeling_tf_auto.py": [' ("{model_type}", "{any_tf_class}"),'],
|
| 1075 |
+
"modeling_flax_auto.py": [' ("{model_type}", "{any_flax_class}"),'],
|
| 1076 |
+
"processing_auto.py": [' ("{model_type}", "{processor_class}"),'],
|
| 1077 |
+
}
|
| 1078 |
+
|
| 1079 |
+
|
| 1080 |
+
def add_model_to_auto_classes(
|
| 1081 |
+
old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns, model_classes: Dict[str, List[str]]
|
| 1082 |
+
):
|
| 1083 |
+
"""
|
| 1084 |
+
Add a model to the relevant mappings in the auto module.
|
| 1085 |
+
|
| 1086 |
+
Args:
|
| 1087 |
+
old_model_patterns (`ModelPatterns`): The patterns for the old model.
|
| 1088 |
+
new_model_patterns (`ModelPatterns`): The patterns for the new model.
|
| 1089 |
+
model_classes (`Dict[str, List[str]]`): A dictionary framework to list of model classes implemented.
|
| 1090 |
+
"""
|
| 1091 |
+
for filename in AUTO_CLASSES_PATTERNS:
|
| 1092 |
+
# Extend patterns with all model classes if necessary
|
| 1093 |
+
new_patterns = []
|
| 1094 |
+
for pattern in AUTO_CLASSES_PATTERNS[filename]:
|
| 1095 |
+
if re.search("any_([a-z]*)_class", pattern) is not None:
|
| 1096 |
+
framework = re.search("any_([a-z]*)_class", pattern).groups()[0]
|
| 1097 |
+
if framework in model_classes:
|
| 1098 |
+
new_patterns.extend(
|
| 1099 |
+
[
|
| 1100 |
+
pattern.replace("{" + f"any_{framework}_class" + "}", cls)
|
| 1101 |
+
for cls in model_classes[framework]
|
| 1102 |
+
]
|
| 1103 |
+
)
|
| 1104 |
+
elif "{config_class}" in pattern:
|
| 1105 |
+
new_patterns.append(pattern.replace("{config_class}", old_model_patterns.config_class))
|
| 1106 |
+
elif "{image_processor_class}" in pattern:
|
| 1107 |
+
if (
|
| 1108 |
+
old_model_patterns.image_processor_class is not None
|
| 1109 |
+
and new_model_patterns.image_processor_class is not None
|
| 1110 |
+
):
|
| 1111 |
+
new_patterns.append(
|
| 1112 |
+
pattern.replace("{image_processor_class}", old_model_patterns.image_processor_class)
|
| 1113 |
+
)
|
| 1114 |
+
elif "{feature_extractor_class}" in pattern:
|
| 1115 |
+
if (
|
| 1116 |
+
old_model_patterns.feature_extractor_class is not None
|
| 1117 |
+
and new_model_patterns.feature_extractor_class is not None
|
| 1118 |
+
):
|
| 1119 |
+
new_patterns.append(
|
| 1120 |
+
pattern.replace("{feature_extractor_class}", old_model_patterns.feature_extractor_class)
|
| 1121 |
+
)
|
| 1122 |
+
elif "{processor_class}" in pattern:
|
| 1123 |
+
if old_model_patterns.processor_class is not None and new_model_patterns.processor_class is not None:
|
| 1124 |
+
new_patterns.append(pattern.replace("{processor_class}", old_model_patterns.processor_class))
|
| 1125 |
+
else:
|
| 1126 |
+
new_patterns.append(pattern)
|
| 1127 |
+
|
| 1128 |
+
# Loop through all patterns.
|
| 1129 |
+
for pattern in new_patterns:
|
| 1130 |
+
full_name = TRANSFORMERS_PATH / "models" / "auto" / filename
|
| 1131 |
+
old_model_line = pattern
|
| 1132 |
+
new_model_line = pattern
|
| 1133 |
+
for attr in ["model_type", "model_name"]:
|
| 1134 |
+
old_model_line = old_model_line.replace("{" + attr + "}", getattr(old_model_patterns, attr))
|
| 1135 |
+
new_model_line = new_model_line.replace("{" + attr + "}", getattr(new_model_patterns, attr))
|
| 1136 |
+
if "pretrained_archive_map" in pattern:
|
| 1137 |
+
old_model_line = old_model_line.replace(
|
| 1138 |
+
"{pretrained_archive_map}", f"{old_model_patterns.model_upper_cased}_PRETRAINED_CONFIG_ARCHIVE_MAP"
|
| 1139 |
+
)
|
| 1140 |
+
new_model_line = new_model_line.replace(
|
| 1141 |
+
"{pretrained_archive_map}", f"{new_model_patterns.model_upper_cased}_PRETRAINED_CONFIG_ARCHIVE_MAP"
|
| 1142 |
+
)
|
| 1143 |
+
|
| 1144 |
+
new_model_line = new_model_line.replace(
|
| 1145 |
+
old_model_patterns.model_camel_cased, new_model_patterns.model_camel_cased
|
| 1146 |
+
)
|
| 1147 |
+
|
| 1148 |
+
add_content_to_file(full_name, new_model_line, add_after=old_model_line)
|
| 1149 |
+
|
| 1150 |
+
# Tokenizers require special handling
|
| 1151 |
+
insert_tokenizer_in_auto_module(old_model_patterns, new_model_patterns)
|
| 1152 |
+
|
| 1153 |
+
|
| 1154 |
+
DOC_OVERVIEW_TEMPLATE = """## Overview
|
| 1155 |
+
|
| 1156 |
+
The {model_name} model was proposed in [<INSERT PAPER NAME HERE>](<INSERT PAPER LINK HERE>) by <INSERT AUTHORS HERE>.
|
| 1157 |
+
<INSERT SHORT SUMMARY HERE>
|
| 1158 |
+
|
| 1159 |
+
The abstract from the paper is the following:
|
| 1160 |
+
|
| 1161 |
+
*<INSERT PAPER ABSTRACT HERE>*
|
| 1162 |
+
|
| 1163 |
+
Tips:
|
| 1164 |
+
|
| 1165 |
+
<INSERT TIPS ABOUT MODEL HERE>
|
| 1166 |
+
|
| 1167 |
+
This model was contributed by [INSERT YOUR HF USERNAME HERE](https://huggingface.co/<INSERT YOUR HF USERNAME HERE>).
|
| 1168 |
+
The original code can be found [here](<INSERT LINK TO GITHUB REPO HERE>).
|
| 1169 |
+
|
| 1170 |
+
"""
|
| 1171 |
+
|
| 1172 |
+
|
| 1173 |
+
def duplicate_doc_file(
|
| 1174 |
+
doc_file: Union[str, os.PathLike],
|
| 1175 |
+
old_model_patterns: ModelPatterns,
|
| 1176 |
+
new_model_patterns: ModelPatterns,
|
| 1177 |
+
dest_file: Optional[Union[str, os.PathLike]] = None,
|
| 1178 |
+
frameworks: Optional[List[str]] = None,
|
| 1179 |
+
):
|
| 1180 |
+
"""
|
| 1181 |
+
Duplicate a documentation file and adapts it for a new model.
|
| 1182 |
+
|
| 1183 |
+
Args:
|
| 1184 |
+
module_file (`str` or `os.PathLike`): Path to the doc file to duplicate.
|
| 1185 |
+
old_model_patterns (`ModelPatterns`): The patterns for the old model.
|
| 1186 |
+
new_model_patterns (`ModelPatterns`): The patterns for the new model.
|
| 1187 |
+
dest_file (`str` or `os.PathLike`, *optional*): Path to the new doc file.
|
| 1188 |
+
Will default to the a file named `{new_model_patterns.model_type}.mdx` in the same folder as `module_file`.
|
| 1189 |
+
frameworks (`List[str]`, *optional*):
|
| 1190 |
+
If passed, will only keep the model classes corresponding to this list of frameworks in the new doc file.
|
| 1191 |
+
"""
|
| 1192 |
+
with open(doc_file, "r", encoding="utf-8") as f:
|
| 1193 |
+
content = f.read()
|
| 1194 |
+
|
| 1195 |
+
content = re.sub(r"<!--\s*Copyright (\d+)\s", f"<!--Copyright {CURRENT_YEAR} ", content)
|
| 1196 |
+
if frameworks is None:
|
| 1197 |
+
frameworks = get_default_frameworks()
|
| 1198 |
+
if dest_file is None:
|
| 1199 |
+
dest_file = Path(doc_file).parent / f"{new_model_patterns.model_type}.mdx"
|
| 1200 |
+
|
| 1201 |
+
# Parse the doc file in blocks. One block per section/header
|
| 1202 |
+
lines = content.split("\n")
|
| 1203 |
+
blocks = []
|
| 1204 |
+
current_block = []
|
| 1205 |
+
|
| 1206 |
+
for line in lines:
|
| 1207 |
+
if line.startswith("#"):
|
| 1208 |
+
blocks.append("\n".join(current_block))
|
| 1209 |
+
current_block = [line]
|
| 1210 |
+
else:
|
| 1211 |
+
current_block.append(line)
|
| 1212 |
+
blocks.append("\n".join(current_block))
|
| 1213 |
+
|
| 1214 |
+
new_blocks = []
|
| 1215 |
+
in_classes = False
|
| 1216 |
+
for block in blocks:
|
| 1217 |
+
# Copyright
|
| 1218 |
+
if not block.startswith("#"):
|
| 1219 |
+
new_blocks.append(block)
|
| 1220 |
+
# Main title
|
| 1221 |
+
elif re.search(r"^#\s+\S+", block) is not None:
|
| 1222 |
+
new_blocks.append(f"# {new_model_patterns.model_name}\n")
|
| 1223 |
+
# The config starts the part of the doc with the classes.
|
| 1224 |
+
elif not in_classes and old_model_patterns.config_class in block.split("\n")[0]:
|
| 1225 |
+
in_classes = True
|
| 1226 |
+
new_blocks.append(DOC_OVERVIEW_TEMPLATE.format(model_name=new_model_patterns.model_name))
|
| 1227 |
+
new_block, _ = replace_model_patterns(block, old_model_patterns, new_model_patterns)
|
| 1228 |
+
new_blocks.append(new_block)
|
| 1229 |
+
# In classes
|
| 1230 |
+
elif in_classes:
|
| 1231 |
+
in_classes = True
|
| 1232 |
+
block_title = block.split("\n")[0]
|
| 1233 |
+
block_class = re.search(r"^#+\s+(\S.*)$", block_title).groups()[0]
|
| 1234 |
+
new_block, _ = replace_model_patterns(block, old_model_patterns, new_model_patterns)
|
| 1235 |
+
|
| 1236 |
+
if "Tokenizer" in block_class:
|
| 1237 |
+
# We only add the tokenizer if necessary
|
| 1238 |
+
if old_model_patterns.tokenizer_class != new_model_patterns.tokenizer_class:
|
| 1239 |
+
new_blocks.append(new_block)
|
| 1240 |
+
elif "ImageProcessor" in block_class:
|
| 1241 |
+
# We only add the image processor if necessary
|
| 1242 |
+
if old_model_patterns.image_processor_class != new_model_patterns.image_processor_class:
|
| 1243 |
+
new_blocks.append(new_block)
|
| 1244 |
+
elif "FeatureExtractor" in block_class:
|
| 1245 |
+
# We only add the feature extractor if necessary
|
| 1246 |
+
if old_model_patterns.feature_extractor_class != new_model_patterns.feature_extractor_class:
|
| 1247 |
+
new_blocks.append(new_block)
|
| 1248 |
+
elif "Processor" in block_class:
|
| 1249 |
+
# We only add the processor if necessary
|
| 1250 |
+
if old_model_patterns.processor_class != new_model_patterns.processor_class:
|
| 1251 |
+
new_blocks.append(new_block)
|
| 1252 |
+
elif block_class.startswith("Flax"):
|
| 1253 |
+
# We only add Flax models if in the selected frameworks
|
| 1254 |
+
if "flax" in frameworks:
|
| 1255 |
+
new_blocks.append(new_block)
|
| 1256 |
+
elif block_class.startswith("TF"):
|
| 1257 |
+
# We only add TF models if in the selected frameworks
|
| 1258 |
+
if "tf" in frameworks:
|
| 1259 |
+
new_blocks.append(new_block)
|
| 1260 |
+
elif len(block_class.split(" ")) == 1:
|
| 1261 |
+
# We only add PyTorch models if in the selected frameworks
|
| 1262 |
+
if "pt" in frameworks:
|
| 1263 |
+
new_blocks.append(new_block)
|
| 1264 |
+
else:
|
| 1265 |
+
new_blocks.append(new_block)
|
| 1266 |
+
|
| 1267 |
+
with open(dest_file, "w", encoding="utf-8") as f:
|
| 1268 |
+
f.write("\n".join(new_blocks))
|
| 1269 |
+
|
| 1270 |
+
|
| 1271 |
+
def create_new_model_like(
|
| 1272 |
+
model_type: str,
|
| 1273 |
+
new_model_patterns: ModelPatterns,
|
| 1274 |
+
add_copied_from: bool = True,
|
| 1275 |
+
frameworks: Optional[List[str]] = None,
|
| 1276 |
+
old_checkpoint: Optional[str] = None,
|
| 1277 |
+
):
|
| 1278 |
+
"""
|
| 1279 |
+
Creates a new model module like a given model of the Transformers library.
|
| 1280 |
+
|
| 1281 |
+
Args:
|
| 1282 |
+
model_type (`str`): The model type to duplicate (like "bert" or "gpt2")
|
| 1283 |
+
new_model_patterns (`ModelPatterns`): The patterns for the new model.
|
| 1284 |
+
add_copied_from (`bool`, *optional*, defaults to `True`):
|
| 1285 |
+
Whether or not to add "Copied from" statements to all classes in the new model modeling files.
|
| 1286 |
+
frameworks (`List[str]`, *optional*):
|
| 1287 |
+
If passed, will limit the duplicate to the frameworks specified.
|
| 1288 |
+
old_checkpoint (`str`, *optional*):
|
| 1289 |
+
The name of the base checkpoint for the old model. Should be passed along when it can't be automatically
|
| 1290 |
+
recovered from the `model_type`.
|
| 1291 |
+
"""
|
| 1292 |
+
# Retrieve all the old model info.
|
| 1293 |
+
model_info = retrieve_info_for_model(model_type, frameworks=frameworks)
|
| 1294 |
+
model_files = model_info["model_files"]
|
| 1295 |
+
old_model_patterns = model_info["model_patterns"]
|
| 1296 |
+
if old_checkpoint is not None:
|
| 1297 |
+
old_model_patterns.checkpoint = old_checkpoint
|
| 1298 |
+
if len(old_model_patterns.checkpoint) == 0:
|
| 1299 |
+
raise ValueError(
|
| 1300 |
+
"The old model checkpoint could not be recovered from the model type. Please pass it to the "
|
| 1301 |
+
"`old_checkpoint` argument."
|
| 1302 |
+
)
|
| 1303 |
+
|
| 1304 |
+
keep_old_processing = True
|
| 1305 |
+
for processing_attr in ["image_processor_class", "feature_extractor_class", "processor_class", "tokenizer_class"]:
|
| 1306 |
+
if getattr(old_model_patterns, processing_attr) != getattr(new_model_patterns, processing_attr):
|
| 1307 |
+
keep_old_processing = False
|
| 1308 |
+
|
| 1309 |
+
model_classes = model_info["model_classes"]
|
| 1310 |
+
|
| 1311 |
+
# 1. We create the module for our new model.
|
| 1312 |
+
old_module_name = model_files["module_name"]
|
| 1313 |
+
module_folder = TRANSFORMERS_PATH / "models" / new_model_patterns.model_lower_cased
|
| 1314 |
+
os.makedirs(module_folder, exist_ok=True)
|
| 1315 |
+
|
| 1316 |
+
files_to_adapt = model_files["model_files"]
|
| 1317 |
+
if keep_old_processing:
|
| 1318 |
+
files_to_adapt = [
|
| 1319 |
+
f
|
| 1320 |
+
for f in files_to_adapt
|
| 1321 |
+
if "tokenization" not in str(f)
|
| 1322 |
+
and "processing" not in str(f)
|
| 1323 |
+
and "feature_extraction" not in str(f)
|
| 1324 |
+
and "image_processing" not in str(f)
|
| 1325 |
+
]
|
| 1326 |
+
|
| 1327 |
+
os.makedirs(module_folder, exist_ok=True)
|
| 1328 |
+
for module_file in files_to_adapt:
|
| 1329 |
+
new_module_name = module_file.name.replace(
|
| 1330 |
+
old_model_patterns.model_lower_cased, new_model_patterns.model_lower_cased
|
| 1331 |
+
)
|
| 1332 |
+
dest_file = module_folder / new_module_name
|
| 1333 |
+
duplicate_module(
|
| 1334 |
+
module_file,
|
| 1335 |
+
old_model_patterns,
|
| 1336 |
+
new_model_patterns,
|
| 1337 |
+
dest_file=dest_file,
|
| 1338 |
+
add_copied_from=add_copied_from and "modeling" in new_module_name,
|
| 1339 |
+
)
|
| 1340 |
+
|
| 1341 |
+
clean_frameworks_in_init(
|
| 1342 |
+
module_folder / "__init__.py", frameworks=frameworks, keep_processing=not keep_old_processing
|
| 1343 |
+
)
|
| 1344 |
+
|
| 1345 |
+
# 2. We add our new model to the models init and the main init
|
| 1346 |
+
add_content_to_file(
|
| 1347 |
+
TRANSFORMERS_PATH / "models" / "__init__.py",
|
| 1348 |
+
f" {new_model_patterns.model_lower_cased},",
|
| 1349 |
+
add_after=f" {old_module_name},",
|
| 1350 |
+
exact_match=True,
|
| 1351 |
+
)
|
| 1352 |
+
add_model_to_main_init(
|
| 1353 |
+
old_model_patterns, new_model_patterns, frameworks=frameworks, with_processing=not keep_old_processing
|
| 1354 |
+
)
|
| 1355 |
+
|
| 1356 |
+
# 3. Add test files
|
| 1357 |
+
files_to_adapt = model_files["test_files"]
|
| 1358 |
+
if keep_old_processing:
|
| 1359 |
+
files_to_adapt = [
|
| 1360 |
+
f
|
| 1361 |
+
for f in files_to_adapt
|
| 1362 |
+
if "tokenization" not in str(f)
|
| 1363 |
+
and "processor" not in str(f)
|
| 1364 |
+
and "feature_extraction" not in str(f)
|
| 1365 |
+
and "image_processing" not in str(f)
|
| 1366 |
+
]
|
| 1367 |
+
|
| 1368 |
+
def disable_fx_test(filename: Path) -> bool:
|
| 1369 |
+
with open(filename) as fp:
|
| 1370 |
+
content = fp.read()
|
| 1371 |
+
new_content = re.sub(r"fx_compatible\s*=\s*True", "fx_compatible = False", content)
|
| 1372 |
+
with open(filename, "w") as fp:
|
| 1373 |
+
fp.write(new_content)
|
| 1374 |
+
return content != new_content
|
| 1375 |
+
|
| 1376 |
+
disabled_fx_test = False
|
| 1377 |
+
|
| 1378 |
+
tests_folder = REPO_PATH / "tests" / "models" / new_model_patterns.model_lower_cased
|
| 1379 |
+
os.makedirs(tests_folder, exist_ok=True)
|
| 1380 |
+
with open(tests_folder / "__init__.py", "w"):
|
| 1381 |
+
pass
|
| 1382 |
+
|
| 1383 |
+
for test_file in files_to_adapt:
|
| 1384 |
+
new_test_file_name = test_file.name.replace(
|
| 1385 |
+
old_model_patterns.model_lower_cased, new_model_patterns.model_lower_cased
|
| 1386 |
+
)
|
| 1387 |
+
dest_file = test_file.parent.parent / new_model_patterns.model_lower_cased / new_test_file_name
|
| 1388 |
+
duplicate_module(
|
| 1389 |
+
test_file,
|
| 1390 |
+
old_model_patterns,
|
| 1391 |
+
new_model_patterns,
|
| 1392 |
+
dest_file=dest_file,
|
| 1393 |
+
add_copied_from=False,
|
| 1394 |
+
attrs_to_remove=["pipeline_model_mapping", "is_pipeline_test_to_skip"],
|
| 1395 |
+
)
|
| 1396 |
+
disabled_fx_test = disabled_fx_test | disable_fx_test(dest_file)
|
| 1397 |
+
|
| 1398 |
+
if disabled_fx_test:
|
| 1399 |
+
print(
|
| 1400 |
+
"The tests for symbolic tracing with torch.fx were disabled, you can add those once symbolic tracing works"
|
| 1401 |
+
" for your new model."
|
| 1402 |
+
)
|
| 1403 |
+
|
| 1404 |
+
# 4. Add model to auto classes
|
| 1405 |
+
add_model_to_auto_classes(old_model_patterns, new_model_patterns, model_classes)
|
| 1406 |
+
|
| 1407 |
+
# 5. Add doc file
|
| 1408 |
+
doc_file = REPO_PATH / "docs" / "source" / "en" / "model_doc" / f"{old_model_patterns.model_type}.mdx"
|
| 1409 |
+
duplicate_doc_file(doc_file, old_model_patterns, new_model_patterns, frameworks=frameworks)
|
| 1410 |
+
|
| 1411 |
+
# 6. Warn the user for duplicate patterns
|
| 1412 |
+
if old_model_patterns.model_type == old_model_patterns.checkpoint:
|
| 1413 |
+
print(
|
| 1414 |
+
"The model you picked has the same name for the model type and the checkpoint name "
|
| 1415 |
+
f"({old_model_patterns.model_type}). As a result, it's possible some places where the new checkpoint "
|
| 1416 |
+
f"should be, you have {new_model_patterns.model_type} instead. You should search for all instances of "
|
| 1417 |
+
f"{new_model_patterns.model_type} in the new files and check they're not badly used as checkpoints."
|
| 1418 |
+
)
|
| 1419 |
+
elif old_model_patterns.model_lower_cased == old_model_patterns.checkpoint:
|
| 1420 |
+
print(
|
| 1421 |
+
"The model you picked has the same name for the model type and the checkpoint name "
|
| 1422 |
+
f"({old_model_patterns.model_lower_cased}). As a result, it's possible some places where the new "
|
| 1423 |
+
f"checkpoint should be, you have {new_model_patterns.model_lower_cased} instead. You should search for "
|
| 1424 |
+
f"all instances of {new_model_patterns.model_lower_cased} in the new files and check they're not badly "
|
| 1425 |
+
"used as checkpoints."
|
| 1426 |
+
)
|
| 1427 |
+
if (
|
| 1428 |
+
old_model_patterns.model_type == old_model_patterns.model_lower_cased
|
| 1429 |
+
and new_model_patterns.model_type != new_model_patterns.model_lower_cased
|
| 1430 |
+
):
|
| 1431 |
+
print(
|
| 1432 |
+
"The model you picked has the same name for the model type and the lowercased model name "
|
| 1433 |
+
f"({old_model_patterns.model_lower_cased}). As a result, it's possible some places where the new "
|
| 1434 |
+
f"model type should be, you have {new_model_patterns.model_lower_cased} instead. You should search for "
|
| 1435 |
+
f"all instances of {new_model_patterns.model_lower_cased} in the new files and check they're not badly "
|
| 1436 |
+
"used as the model type."
|
| 1437 |
+
)
|
| 1438 |
+
|
| 1439 |
+
if not keep_old_processing and old_model_patterns.tokenizer_class is not None:
|
| 1440 |
+
print(
|
| 1441 |
+
"The constants at the start of the new tokenizer file created needs to be manually fixed. If your new "
|
| 1442 |
+
"model has a tokenizer fast, you will also need to manually add the converter in the "
|
| 1443 |
+
"`SLOW_TO_FAST_CONVERTERS` constant of `convert_slow_tokenizer.py`."
|
| 1444 |
+
)
|
| 1445 |
+
|
| 1446 |
+
|
| 1447 |
+
def add_new_model_like_command_factory(args: Namespace):
|
| 1448 |
+
return AddNewModelLikeCommand(config_file=args.config_file, path_to_repo=args.path_to_repo)
|
| 1449 |
+
|
| 1450 |
+
|
| 1451 |
+
class AddNewModelLikeCommand(BaseTransformersCLICommand):
|
| 1452 |
+
@staticmethod
|
| 1453 |
+
def register_subcommand(parser: ArgumentParser):
|
| 1454 |
+
add_new_model_like_parser = parser.add_parser("add-new-model-like")
|
| 1455 |
+
add_new_model_like_parser.add_argument(
|
| 1456 |
+
"--config_file", type=str, help="A file with all the information for this model creation."
|
| 1457 |
+
)
|
| 1458 |
+
add_new_model_like_parser.add_argument(
|
| 1459 |
+
"--path_to_repo", type=str, help="When not using an editable install, the path to the Transformers repo."
|
| 1460 |
+
)
|
| 1461 |
+
add_new_model_like_parser.set_defaults(func=add_new_model_like_command_factory)
|
| 1462 |
+
|
| 1463 |
+
def __init__(self, config_file=None, path_to_repo=None, *args):
|
| 1464 |
+
if config_file is not None:
|
| 1465 |
+
with open(config_file, "r", encoding="utf-8") as f:
|
| 1466 |
+
config = json.load(f)
|
| 1467 |
+
self.old_model_type = config["old_model_type"]
|
| 1468 |
+
self.model_patterns = ModelPatterns(**config["new_model_patterns"])
|
| 1469 |
+
self.add_copied_from = config.get("add_copied_from", True)
|
| 1470 |
+
self.frameworks = config.get("frameworks", get_default_frameworks())
|
| 1471 |
+
self.old_checkpoint = config.get("old_checkpoint", None)
|
| 1472 |
+
else:
|
| 1473 |
+
(
|
| 1474 |
+
self.old_model_type,
|
| 1475 |
+
self.model_patterns,
|
| 1476 |
+
self.add_copied_from,
|
| 1477 |
+
self.frameworks,
|
| 1478 |
+
self.old_checkpoint,
|
| 1479 |
+
) = get_user_input()
|
| 1480 |
+
|
| 1481 |
+
self.path_to_repo = path_to_repo
|
| 1482 |
+
|
| 1483 |
+
def run(self):
|
| 1484 |
+
if self.path_to_repo is not None:
|
| 1485 |
+
# Adapt constants
|
| 1486 |
+
global TRANSFORMERS_PATH
|
| 1487 |
+
global REPO_PATH
|
| 1488 |
+
|
| 1489 |
+
REPO_PATH = Path(self.path_to_repo)
|
| 1490 |
+
TRANSFORMERS_PATH = REPO_PATH / "src" / "transformers"
|
| 1491 |
+
|
| 1492 |
+
create_new_model_like(
|
| 1493 |
+
model_type=self.old_model_type,
|
| 1494 |
+
new_model_patterns=self.model_patterns,
|
| 1495 |
+
add_copied_from=self.add_copied_from,
|
| 1496 |
+
frameworks=self.frameworks,
|
| 1497 |
+
old_checkpoint=self.old_checkpoint,
|
| 1498 |
+
)
|
| 1499 |
+
|
| 1500 |
+
|
| 1501 |
+
def get_user_field(
|
| 1502 |
+
question: str,
|
| 1503 |
+
default_value: Optional[str] = None,
|
| 1504 |
+
is_valid_answer: Optional[Callable] = None,
|
| 1505 |
+
convert_to: Optional[Callable] = None,
|
| 1506 |
+
fallback_message: Optional[str] = None,
|
| 1507 |
+
) -> Any:
|
| 1508 |
+
"""
|
| 1509 |
+
A utility function that asks a question to the user to get an answer, potentially looping until it gets a valid
|
| 1510 |
+
answer.
|
| 1511 |
+
|
| 1512 |
+
Args:
|
| 1513 |
+
question (`str`): The question to ask the user.
|
| 1514 |
+
default_value (`str`, *optional*): A potential default value that will be used when the answer is empty.
|
| 1515 |
+
is_valid_answer (`Callable`, *optional*):
|
| 1516 |
+
If set, the question will be asked until this function returns `True` on the provided answer.
|
| 1517 |
+
convert_to (`Callable`, *optional*):
|
| 1518 |
+
If set, the answer will be passed to this function. If this function raises an error on the procided
|
| 1519 |
+
answer, the question will be asked again.
|
| 1520 |
+
fallback_message (`str`, *optional*):
|
| 1521 |
+
A message that will be displayed each time the question is asked again to the user.
|
| 1522 |
+
|
| 1523 |
+
Returns:
|
| 1524 |
+
`Any`: The answer provided by the user (or the default), passed through the potential conversion function.
|
| 1525 |
+
"""
|
| 1526 |
+
if not question.endswith(" "):
|
| 1527 |
+
question = question + " "
|
| 1528 |
+
if default_value is not None:
|
| 1529 |
+
question = f"{question} [{default_value}] "
|
| 1530 |
+
|
| 1531 |
+
valid_answer = False
|
| 1532 |
+
while not valid_answer:
|
| 1533 |
+
answer = input(question)
|
| 1534 |
+
if default_value is not None and len(answer) == 0:
|
| 1535 |
+
answer = default_value
|
| 1536 |
+
if is_valid_answer is not None:
|
| 1537 |
+
valid_answer = is_valid_answer(answer)
|
| 1538 |
+
elif convert_to is not None:
|
| 1539 |
+
try:
|
| 1540 |
+
answer = convert_to(answer)
|
| 1541 |
+
valid_answer = True
|
| 1542 |
+
except Exception:
|
| 1543 |
+
valid_answer = False
|
| 1544 |
+
else:
|
| 1545 |
+
valid_answer = True
|
| 1546 |
+
|
| 1547 |
+
if not valid_answer:
|
| 1548 |
+
print(fallback_message)
|
| 1549 |
+
|
| 1550 |
+
return answer
|
| 1551 |
+
|
| 1552 |
+
|
| 1553 |
+
def convert_to_bool(x: str) -> bool:
|
| 1554 |
+
"""
|
| 1555 |
+
Converts a string to a bool.
|
| 1556 |
+
"""
|
| 1557 |
+
if x.lower() in ["1", "y", "yes", "true"]:
|
| 1558 |
+
return True
|
| 1559 |
+
if x.lower() in ["0", "n", "no", "false"]:
|
| 1560 |
+
return False
|
| 1561 |
+
raise ValueError(f"{x} is not a value that can be converted to a bool.")
|
| 1562 |
+
|
| 1563 |
+
|
| 1564 |
+
def get_user_input():
|
| 1565 |
+
"""
|
| 1566 |
+
Ask the user for the necessary inputs to add the new model.
|
| 1567 |
+
"""
|
| 1568 |
+
model_types = list(auto_module.configuration_auto.MODEL_NAMES_MAPPING.keys())
|
| 1569 |
+
|
| 1570 |
+
# Get old model type
|
| 1571 |
+
valid_model_type = False
|
| 1572 |
+
while not valid_model_type:
|
| 1573 |
+
old_model_type = input(
|
| 1574 |
+
"What is the model you would like to duplicate? Please provide the lowercase `model_type` (e.g. roberta): "
|
| 1575 |
+
)
|
| 1576 |
+
if old_model_type in model_types:
|
| 1577 |
+
valid_model_type = True
|
| 1578 |
+
else:
|
| 1579 |
+
print(f"{old_model_type} is not a valid model type.")
|
| 1580 |
+
near_choices = difflib.get_close_matches(old_model_type, model_types)
|
| 1581 |
+
if len(near_choices) >= 1:
|
| 1582 |
+
if len(near_choices) > 1:
|
| 1583 |
+
near_choices = " or ".join(near_choices)
|
| 1584 |
+
print(f"Did you mean {near_choices}?")
|
| 1585 |
+
|
| 1586 |
+
old_model_info = retrieve_info_for_model(old_model_type)
|
| 1587 |
+
old_tokenizer_class = old_model_info["model_patterns"].tokenizer_class
|
| 1588 |
+
old_image_processor_class = old_model_info["model_patterns"].image_processor_class
|
| 1589 |
+
old_feature_extractor_class = old_model_info["model_patterns"].feature_extractor_class
|
| 1590 |
+
old_processor_class = old_model_info["model_patterns"].processor_class
|
| 1591 |
+
old_frameworks = old_model_info["frameworks"]
|
| 1592 |
+
|
| 1593 |
+
old_checkpoint = None
|
| 1594 |
+
if len(old_model_info["model_patterns"].checkpoint) == 0:
|
| 1595 |
+
old_checkpoint = get_user_field(
|
| 1596 |
+
"We couldn't find the name of the base checkpoint for that model, please enter it here."
|
| 1597 |
+
)
|
| 1598 |
+
|
| 1599 |
+
model_name = get_user_field(
|
| 1600 |
+
"What is the name (with no special casing) for your new model in the paper (e.g. RoBERTa)? "
|
| 1601 |
+
)
|
| 1602 |
+
default_patterns = ModelPatterns(model_name, model_name)
|
| 1603 |
+
|
| 1604 |
+
model_type = get_user_field(
|
| 1605 |
+
"What identifier would you like to use for the `model_type` of this model? ",
|
| 1606 |
+
default_value=default_patterns.model_type,
|
| 1607 |
+
)
|
| 1608 |
+
model_lower_cased = get_user_field(
|
| 1609 |
+
"What lowercase name would you like to use for the module (folder) of this model? ",
|
| 1610 |
+
default_value=default_patterns.model_lower_cased,
|
| 1611 |
+
)
|
| 1612 |
+
model_camel_cased = get_user_field(
|
| 1613 |
+
"What prefix (camel-cased) would you like to use for the model classes of this model (e.g. Roberta)? ",
|
| 1614 |
+
default_value=default_patterns.model_camel_cased,
|
| 1615 |
+
)
|
| 1616 |
+
model_upper_cased = get_user_field(
|
| 1617 |
+
"What prefix (upper-cased) would you like to use for the constants relative to this model? ",
|
| 1618 |
+
default_value=default_patterns.model_upper_cased,
|
| 1619 |
+
)
|
| 1620 |
+
config_class = get_user_field(
|
| 1621 |
+
"What will be the name of the config class for this model? ", default_value=f"{model_camel_cased}Config"
|
| 1622 |
+
)
|
| 1623 |
+
checkpoint = get_user_field(
|
| 1624 |
+
"Please give a checkpoint identifier (on the model Hub) for this new model (e.g. facebook/roberta-base): "
|
| 1625 |
+
)
|
| 1626 |
+
|
| 1627 |
+
old_processing_classes = [
|
| 1628 |
+
c
|
| 1629 |
+
for c in [old_image_processor_class, old_feature_extractor_class, old_tokenizer_class, old_processor_class]
|
| 1630 |
+
if c is not None
|
| 1631 |
+
]
|
| 1632 |
+
old_processing_classes = ", ".join(old_processing_classes)
|
| 1633 |
+
keep_processing = get_user_field(
|
| 1634 |
+
f"Will your new model use the same processing class as {old_model_type} ({old_processing_classes}) (yes/no)? ",
|
| 1635 |
+
convert_to=convert_to_bool,
|
| 1636 |
+
fallback_message="Please answer yes/no, y/n, true/false or 1/0. ",
|
| 1637 |
+
)
|
| 1638 |
+
if keep_processing:
|
| 1639 |
+
image_processor_class = old_image_processor_class
|
| 1640 |
+
feature_extractor_class = old_feature_extractor_class
|
| 1641 |
+
processor_class = old_processor_class
|
| 1642 |
+
tokenizer_class = old_tokenizer_class
|
| 1643 |
+
else:
|
| 1644 |
+
if old_tokenizer_class is not None:
|
| 1645 |
+
tokenizer_class = get_user_field(
|
| 1646 |
+
"What will be the name of the tokenizer class for this model? ",
|
| 1647 |
+
default_value=f"{model_camel_cased}Tokenizer",
|
| 1648 |
+
)
|
| 1649 |
+
else:
|
| 1650 |
+
tokenizer_class = None
|
| 1651 |
+
if old_image_processor_class is not None:
|
| 1652 |
+
image_processor_class = get_user_field(
|
| 1653 |
+
"What will be the name of the image processor class for this model? ",
|
| 1654 |
+
default_value=f"{model_camel_cased}ImageProcessor",
|
| 1655 |
+
)
|
| 1656 |
+
else:
|
| 1657 |
+
image_processor_class = None
|
| 1658 |
+
if old_feature_extractor_class is not None:
|
| 1659 |
+
feature_extractor_class = get_user_field(
|
| 1660 |
+
"What will be the name of the feature extractor class for this model? ",
|
| 1661 |
+
default_value=f"{model_camel_cased}FeatureExtractor",
|
| 1662 |
+
)
|
| 1663 |
+
else:
|
| 1664 |
+
feature_extractor_class = None
|
| 1665 |
+
if old_processor_class is not None:
|
| 1666 |
+
processor_class = get_user_field(
|
| 1667 |
+
"What will be the name of the processor class for this model? ",
|
| 1668 |
+
default_value=f"{model_camel_cased}Processor",
|
| 1669 |
+
)
|
| 1670 |
+
else:
|
| 1671 |
+
processor_class = None
|
| 1672 |
+
|
| 1673 |
+
model_patterns = ModelPatterns(
|
| 1674 |
+
model_name,
|
| 1675 |
+
checkpoint,
|
| 1676 |
+
model_type=model_type,
|
| 1677 |
+
model_lower_cased=model_lower_cased,
|
| 1678 |
+
model_camel_cased=model_camel_cased,
|
| 1679 |
+
model_upper_cased=model_upper_cased,
|
| 1680 |
+
config_class=config_class,
|
| 1681 |
+
tokenizer_class=tokenizer_class,
|
| 1682 |
+
image_processor_class=image_processor_class,
|
| 1683 |
+
feature_extractor_class=feature_extractor_class,
|
| 1684 |
+
processor_class=processor_class,
|
| 1685 |
+
)
|
| 1686 |
+
|
| 1687 |
+
add_copied_from = get_user_field(
|
| 1688 |
+
"Should we add # Copied from statements when creating the new modeling file (yes/no)? ",
|
| 1689 |
+
convert_to=convert_to_bool,
|
| 1690 |
+
default_value="yes",
|
| 1691 |
+
fallback_message="Please answer yes/no, y/n, true/false or 1/0.",
|
| 1692 |
+
)
|
| 1693 |
+
|
| 1694 |
+
all_frameworks = get_user_field(
|
| 1695 |
+
"Should we add a version of your new model in all the frameworks implemented by"
|
| 1696 |
+
f" {old_model_type} ({old_frameworks}) (yes/no)? ",
|
| 1697 |
+
convert_to=convert_to_bool,
|
| 1698 |
+
default_value="yes",
|
| 1699 |
+
fallback_message="Please answer yes/no, y/n, true/false or 1/0.",
|
| 1700 |
+
)
|
| 1701 |
+
if all_frameworks:
|
| 1702 |
+
frameworks = None
|
| 1703 |
+
else:
|
| 1704 |
+
frameworks = get_user_field(
|
| 1705 |
+
"Please enter the list of framworks you want (pt, tf, flax) separated by spaces",
|
| 1706 |
+
is_valid_answer=lambda x: all(p in ["pt", "tf", "flax"] for p in x.split(" ")),
|
| 1707 |
+
)
|
| 1708 |
+
frameworks = list(set(frameworks.split(" ")))
|
| 1709 |
+
|
| 1710 |
+
return (old_model_type, model_patterns, add_copied_from, frameworks, old_checkpoint)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/download.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from argparse import ArgumentParser
|
| 16 |
+
|
| 17 |
+
from . import BaseTransformersCLICommand
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def download_command_factory(args):
|
| 21 |
+
return DownloadCommand(args.model, args.cache_dir, args.force)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class DownloadCommand(BaseTransformersCLICommand):
|
| 25 |
+
@staticmethod
|
| 26 |
+
def register_subcommand(parser: ArgumentParser):
|
| 27 |
+
download_parser = parser.add_parser("download")
|
| 28 |
+
download_parser.add_argument(
|
| 29 |
+
"--cache-dir", type=str, default=None, help="Path to location to store the models"
|
| 30 |
+
)
|
| 31 |
+
download_parser.add_argument(
|
| 32 |
+
"--force", action="store_true", help="Force the model to be download even if already in cache-dir"
|
| 33 |
+
)
|
| 34 |
+
download_parser.add_argument("model", type=str, help="Name of the model to download")
|
| 35 |
+
download_parser.set_defaults(func=download_command_factory)
|
| 36 |
+
|
| 37 |
+
def __init__(self, model: str, cache: str, force: bool):
|
| 38 |
+
self._model = model
|
| 39 |
+
self._cache = cache
|
| 40 |
+
self._force = force
|
| 41 |
+
|
| 42 |
+
def run(self):
|
| 43 |
+
from ..models.auto import AutoModel, AutoTokenizer
|
| 44 |
+
|
| 45 |
+
AutoModel.from_pretrained(self._model, cache_dir=self._cache, force_download=self._force)
|
| 46 |
+
AutoTokenizer.from_pretrained(self._model, cache_dir=self._cache, force_download=self._force)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/env.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import importlib.util
|
| 16 |
+
import platform
|
| 17 |
+
from argparse import ArgumentParser
|
| 18 |
+
|
| 19 |
+
import huggingface_hub
|
| 20 |
+
|
| 21 |
+
from .. import __version__ as version
|
| 22 |
+
from ..utils import is_flax_available, is_safetensors_available, is_tf_available, is_torch_available
|
| 23 |
+
from . import BaseTransformersCLICommand
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def info_command_factory(_):
|
| 27 |
+
return EnvironmentCommand()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class EnvironmentCommand(BaseTransformersCLICommand):
|
| 31 |
+
@staticmethod
|
| 32 |
+
def register_subcommand(parser: ArgumentParser):
|
| 33 |
+
download_parser = parser.add_parser("env")
|
| 34 |
+
download_parser.set_defaults(func=info_command_factory)
|
| 35 |
+
|
| 36 |
+
def run(self):
|
| 37 |
+
safetensors_version = "not installed"
|
| 38 |
+
if is_safetensors_available():
|
| 39 |
+
import safetensors
|
| 40 |
+
|
| 41 |
+
safetensors_version = safetensors.__version__
|
| 42 |
+
elif importlib.util.find_spec("safetensors") is not None:
|
| 43 |
+
import safetensors
|
| 44 |
+
|
| 45 |
+
safetensors_version = f"{safetensors.__version__} but is ignored because of PyTorch version too old."
|
| 46 |
+
|
| 47 |
+
pt_version = "not installed"
|
| 48 |
+
pt_cuda_available = "NA"
|
| 49 |
+
if is_torch_available():
|
| 50 |
+
import torch
|
| 51 |
+
|
| 52 |
+
pt_version = torch.__version__
|
| 53 |
+
pt_cuda_available = torch.cuda.is_available()
|
| 54 |
+
|
| 55 |
+
tf_version = "not installed"
|
| 56 |
+
tf_cuda_available = "NA"
|
| 57 |
+
if is_tf_available():
|
| 58 |
+
import tensorflow as tf
|
| 59 |
+
|
| 60 |
+
tf_version = tf.__version__
|
| 61 |
+
try:
|
| 62 |
+
# deprecated in v2.1
|
| 63 |
+
tf_cuda_available = tf.test.is_gpu_available()
|
| 64 |
+
except AttributeError:
|
| 65 |
+
# returns list of devices, convert to bool
|
| 66 |
+
tf_cuda_available = bool(tf.config.list_physical_devices("GPU"))
|
| 67 |
+
|
| 68 |
+
flax_version = "not installed"
|
| 69 |
+
jax_version = "not installed"
|
| 70 |
+
jaxlib_version = "not installed"
|
| 71 |
+
jax_backend = "NA"
|
| 72 |
+
if is_flax_available():
|
| 73 |
+
import flax
|
| 74 |
+
import jax
|
| 75 |
+
import jaxlib
|
| 76 |
+
|
| 77 |
+
flax_version = flax.__version__
|
| 78 |
+
jax_version = jax.__version__
|
| 79 |
+
jaxlib_version = jaxlib.__version__
|
| 80 |
+
jax_backend = jax.lib.xla_bridge.get_backend().platform
|
| 81 |
+
|
| 82 |
+
info = {
|
| 83 |
+
"`transformers` version": version,
|
| 84 |
+
"Platform": platform.platform(),
|
| 85 |
+
"Python version": platform.python_version(),
|
| 86 |
+
"Huggingface_hub version": huggingface_hub.__version__,
|
| 87 |
+
"Safetensors version": f"{safetensors_version}",
|
| 88 |
+
"PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})",
|
| 89 |
+
"Tensorflow version (GPU?)": f"{tf_version} ({tf_cuda_available})",
|
| 90 |
+
"Flax version (CPU?/GPU?/TPU?)": f"{flax_version} ({jax_backend})",
|
| 91 |
+
"Jax version": f"{jax_version}",
|
| 92 |
+
"JaxLib version": f"{jaxlib_version}",
|
| 93 |
+
"Using GPU in script?": "<fill in>",
|
| 94 |
+
"Using distributed or parallel set-up in script?": "<fill in>",
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n")
|
| 98 |
+
print(self.format_dict(info))
|
| 99 |
+
|
| 100 |
+
return info
|
| 101 |
+
|
| 102 |
+
@staticmethod
|
| 103 |
+
def format_dict(d):
|
| 104 |
+
return "\n".join([f"- {prop}: {val}" for prop, val in d.items()]) + "\n"
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/lfs.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Implementation of a custom transfer agent for the transfer type "multipart" for git-lfs.
|
| 3 |
+
|
| 4 |
+
Inspired by: github.com/cbartz/git-lfs-swift-transfer-agent/blob/master/git_lfs_swift_transfer.py
|
| 5 |
+
|
| 6 |
+
Spec is: github.com/git-lfs/git-lfs/blob/master/docs/custom-transfers.md
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
To launch debugger while developing:
|
| 10 |
+
|
| 11 |
+
``` [lfs "customtransfer.multipart"]
|
| 12 |
+
path = /path/to/transformers/.env/bin/python args = -m debugpy --listen 5678 --wait-for-client
|
| 13 |
+
/path/to/transformers/src/transformers/commands/transformers_cli.py lfs-multipart-upload ```"""
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
import warnings
|
| 20 |
+
from argparse import ArgumentParser
|
| 21 |
+
from contextlib import AbstractContextManager
|
| 22 |
+
from typing import Dict, List, Optional
|
| 23 |
+
|
| 24 |
+
import requests
|
| 25 |
+
|
| 26 |
+
from ..utils import logging
|
| 27 |
+
from . import BaseTransformersCLICommand
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
LFS_MULTIPART_UPLOAD_COMMAND = "lfs-multipart-upload"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class LfsCommands(BaseTransformersCLICommand):
|
| 37 |
+
"""
|
| 38 |
+
Implementation of a custom transfer agent for the transfer type "multipart" for git-lfs. This lets users upload
|
| 39 |
+
large files >5GB 🔥. Spec for LFS custom transfer agent is:
|
| 40 |
+
https://github.com/git-lfs/git-lfs/blob/master/docs/custom-transfers.md
|
| 41 |
+
|
| 42 |
+
This introduces two commands to the CLI:
|
| 43 |
+
|
| 44 |
+
1. $ transformers-cli lfs-enable-largefiles
|
| 45 |
+
|
| 46 |
+
This should be executed once for each model repo that contains a model file >5GB. It's documented in the error
|
| 47 |
+
message you get if you just try to git push a 5GB file without having enabled it before.
|
| 48 |
+
|
| 49 |
+
2. $ transformers-cli lfs-multipart-upload
|
| 50 |
+
|
| 51 |
+
This command is called by lfs directly and is not meant to be called by the user.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
@staticmethod
|
| 55 |
+
def register_subcommand(parser: ArgumentParser):
|
| 56 |
+
enable_parser = parser.add_parser(
|
| 57 |
+
"lfs-enable-largefiles",
|
| 58 |
+
help=(
|
| 59 |
+
"Deprecated: use `huggingface-cli` instead. Configure your repository to enable upload of files > 5GB."
|
| 60 |
+
),
|
| 61 |
+
)
|
| 62 |
+
enable_parser.add_argument("path", type=str, help="Local path to repository you want to configure.")
|
| 63 |
+
enable_parser.set_defaults(func=lambda args: LfsEnableCommand(args))
|
| 64 |
+
|
| 65 |
+
upload_parser = parser.add_parser(
|
| 66 |
+
LFS_MULTIPART_UPLOAD_COMMAND,
|
| 67 |
+
help=(
|
| 68 |
+
"Deprecated: use `huggingface-cli` instead. "
|
| 69 |
+
"Command will get called by git-lfs, do not call it directly."
|
| 70 |
+
),
|
| 71 |
+
)
|
| 72 |
+
upload_parser.set_defaults(func=lambda args: LfsUploadCommand(args))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class LfsEnableCommand:
|
| 76 |
+
def __init__(self, args):
|
| 77 |
+
self.args = args
|
| 78 |
+
|
| 79 |
+
def run(self):
|
| 80 |
+
warnings.warn(
|
| 81 |
+
"Managing repositories through transformers-cli is deprecated. Please use `huggingface-cli` instead."
|
| 82 |
+
)
|
| 83 |
+
local_path = os.path.abspath(self.args.path)
|
| 84 |
+
if not os.path.isdir(local_path):
|
| 85 |
+
print("This does not look like a valid git repo.")
|
| 86 |
+
exit(1)
|
| 87 |
+
subprocess.run(
|
| 88 |
+
"git config lfs.customtransfer.multipart.path transformers-cli".split(), check=True, cwd=local_path
|
| 89 |
+
)
|
| 90 |
+
subprocess.run(
|
| 91 |
+
f"git config lfs.customtransfer.multipart.args {LFS_MULTIPART_UPLOAD_COMMAND}".split(),
|
| 92 |
+
check=True,
|
| 93 |
+
cwd=local_path,
|
| 94 |
+
)
|
| 95 |
+
print("Local repo set up for largefiles")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def write_msg(msg: Dict):
|
| 99 |
+
"""Write out the message in Line delimited JSON."""
|
| 100 |
+
msg = json.dumps(msg) + "\n"
|
| 101 |
+
sys.stdout.write(msg)
|
| 102 |
+
sys.stdout.flush()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def read_msg() -> Optional[Dict]:
|
| 106 |
+
"""Read Line delimited JSON from stdin."""
|
| 107 |
+
msg = json.loads(sys.stdin.readline().strip())
|
| 108 |
+
|
| 109 |
+
if "terminate" in (msg.get("type"), msg.get("event")):
|
| 110 |
+
# terminate message received
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
if msg.get("event") not in ("download", "upload"):
|
| 114 |
+
logger.critical("Received unexpected message")
|
| 115 |
+
sys.exit(1)
|
| 116 |
+
|
| 117 |
+
return msg
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class FileSlice(AbstractContextManager):
|
| 121 |
+
"""
|
| 122 |
+
File-like object that only reads a slice of a file
|
| 123 |
+
|
| 124 |
+
Inspired by stackoverflow.com/a/29838711/593036
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
def __init__(self, filepath: str, seek_from: int, read_limit: int):
|
| 128 |
+
self.filepath = filepath
|
| 129 |
+
self.seek_from = seek_from
|
| 130 |
+
self.read_limit = read_limit
|
| 131 |
+
self.n_seen = 0
|
| 132 |
+
|
| 133 |
+
def __enter__(self):
|
| 134 |
+
self.f = open(self.filepath, "rb")
|
| 135 |
+
self.f.seek(self.seek_from)
|
| 136 |
+
return self
|
| 137 |
+
|
| 138 |
+
def __len__(self):
|
| 139 |
+
total_length = os.fstat(self.f.fileno()).st_size
|
| 140 |
+
return min(self.read_limit, total_length - self.seek_from)
|
| 141 |
+
|
| 142 |
+
def read(self, n=-1):
|
| 143 |
+
if self.n_seen >= self.read_limit:
|
| 144 |
+
return b""
|
| 145 |
+
remaining_amount = self.read_limit - self.n_seen
|
| 146 |
+
data = self.f.read(remaining_amount if n < 0 else min(n, remaining_amount))
|
| 147 |
+
self.n_seen += len(data)
|
| 148 |
+
return data
|
| 149 |
+
|
| 150 |
+
def __iter__(self):
|
| 151 |
+
yield self.read(n=4 * 1024 * 1024)
|
| 152 |
+
|
| 153 |
+
def __exit__(self, *args):
|
| 154 |
+
self.f.close()
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class LfsUploadCommand:
|
| 158 |
+
def __init__(self, args):
|
| 159 |
+
self.args = args
|
| 160 |
+
|
| 161 |
+
def run(self):
|
| 162 |
+
# Immediately after invoking a custom transfer process, git-lfs
|
| 163 |
+
# sends initiation data to the process over stdin.
|
| 164 |
+
# This tells the process useful information about the configuration.
|
| 165 |
+
init_msg = json.loads(sys.stdin.readline().strip())
|
| 166 |
+
if not (init_msg.get("event") == "init" and init_msg.get("operation") == "upload"):
|
| 167 |
+
write_msg({"error": {"code": 32, "message": "Wrong lfs init operation"}})
|
| 168 |
+
sys.exit(1)
|
| 169 |
+
|
| 170 |
+
# The transfer process should use the information it needs from the
|
| 171 |
+
# initiation structure, and also perform any one-off setup tasks it
|
| 172 |
+
# needs to do. It should then respond on stdout with a simple empty
|
| 173 |
+
# confirmation structure, as follows:
|
| 174 |
+
write_msg({})
|
| 175 |
+
|
| 176 |
+
# After the initiation exchange, git-lfs will send any number of
|
| 177 |
+
# transfer requests to the stdin of the transfer process, in a serial sequence.
|
| 178 |
+
while True:
|
| 179 |
+
msg = read_msg()
|
| 180 |
+
if msg is None:
|
| 181 |
+
# When all transfers have been processed, git-lfs will send
|
| 182 |
+
# a terminate event to the stdin of the transfer process.
|
| 183 |
+
# On receiving this message the transfer process should
|
| 184 |
+
# clean up and terminate. No response is expected.
|
| 185 |
+
sys.exit(0)
|
| 186 |
+
|
| 187 |
+
oid = msg["oid"]
|
| 188 |
+
filepath = msg["path"]
|
| 189 |
+
completion_url = msg["action"]["href"]
|
| 190 |
+
header = msg["action"]["header"]
|
| 191 |
+
chunk_size = int(header.pop("chunk_size"))
|
| 192 |
+
presigned_urls: List[str] = list(header.values())
|
| 193 |
+
|
| 194 |
+
parts = []
|
| 195 |
+
for i, presigned_url in enumerate(presigned_urls):
|
| 196 |
+
with FileSlice(filepath, seek_from=i * chunk_size, read_limit=chunk_size) as data:
|
| 197 |
+
r = requests.put(presigned_url, data=data)
|
| 198 |
+
r.raise_for_status()
|
| 199 |
+
parts.append(
|
| 200 |
+
{
|
| 201 |
+
"etag": r.headers.get("etag"),
|
| 202 |
+
"partNumber": i + 1,
|
| 203 |
+
}
|
| 204 |
+
)
|
| 205 |
+
# In order to support progress reporting while data is uploading / downloading,
|
| 206 |
+
# the transfer process should post messages to stdout
|
| 207 |
+
write_msg(
|
| 208 |
+
{
|
| 209 |
+
"event": "progress",
|
| 210 |
+
"oid": oid,
|
| 211 |
+
"bytesSoFar": (i + 1) * chunk_size,
|
| 212 |
+
"bytesSinceLast": chunk_size,
|
| 213 |
+
}
|
| 214 |
+
)
|
| 215 |
+
# Not precise but that's ok.
|
| 216 |
+
|
| 217 |
+
r = requests.post(
|
| 218 |
+
completion_url,
|
| 219 |
+
json={
|
| 220 |
+
"oid": oid,
|
| 221 |
+
"parts": parts,
|
| 222 |
+
},
|
| 223 |
+
)
|
| 224 |
+
r.raise_for_status()
|
| 225 |
+
|
| 226 |
+
write_msg({"event": "complete", "oid": oid})
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/run.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from argparse import ArgumentParser
|
| 16 |
+
|
| 17 |
+
from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline
|
| 18 |
+
from ..utils import logging
|
| 19 |
+
from . import BaseTransformersCLICommand
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def try_infer_format_from_ext(path: str):
|
| 26 |
+
if not path:
|
| 27 |
+
return "pipe"
|
| 28 |
+
|
| 29 |
+
for ext in PipelineDataFormat.SUPPORTED_FORMATS:
|
| 30 |
+
if path.endswith(ext):
|
| 31 |
+
return ext
|
| 32 |
+
|
| 33 |
+
raise Exception(
|
| 34 |
+
f"Unable to determine file format from file extension {path}. "
|
| 35 |
+
f"Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def run_command_factory(args):
|
| 40 |
+
nlp = pipeline(
|
| 41 |
+
task=args.task,
|
| 42 |
+
model=args.model if args.model else None,
|
| 43 |
+
config=args.config,
|
| 44 |
+
tokenizer=args.tokenizer,
|
| 45 |
+
device=args.device,
|
| 46 |
+
)
|
| 47 |
+
format = try_infer_format_from_ext(args.input) if args.format == "infer" else args.format
|
| 48 |
+
reader = PipelineDataFormat.from_str(
|
| 49 |
+
format=format,
|
| 50 |
+
output_path=args.output,
|
| 51 |
+
input_path=args.input,
|
| 52 |
+
column=args.column if args.column else nlp.default_input_names,
|
| 53 |
+
overwrite=args.overwrite,
|
| 54 |
+
)
|
| 55 |
+
return RunCommand(nlp, reader)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class RunCommand(BaseTransformersCLICommand):
|
| 59 |
+
def __init__(self, nlp: Pipeline, reader: PipelineDataFormat):
|
| 60 |
+
self._nlp = nlp
|
| 61 |
+
self._reader = reader
|
| 62 |
+
|
| 63 |
+
@staticmethod
|
| 64 |
+
def register_subcommand(parser: ArgumentParser):
|
| 65 |
+
run_parser = parser.add_parser("run", help="Run a pipeline through the CLI")
|
| 66 |
+
run_parser.add_argument("--task", choices=get_supported_tasks(), help="Task to run")
|
| 67 |
+
run_parser.add_argument("--input", type=str, help="Path to the file to use for inference")
|
| 68 |
+
run_parser.add_argument("--output", type=str, help="Path to the file that will be used post to write results.")
|
| 69 |
+
run_parser.add_argument("--model", type=str, help="Name or path to the model to instantiate.")
|
| 70 |
+
run_parser.add_argument("--config", type=str, help="Name or path to the model's config to instantiate.")
|
| 71 |
+
run_parser.add_argument(
|
| 72 |
+
"--tokenizer", type=str, help="Name of the tokenizer to use. (default: same as the model name)"
|
| 73 |
+
)
|
| 74 |
+
run_parser.add_argument(
|
| 75 |
+
"--column",
|
| 76 |
+
type=str,
|
| 77 |
+
help="Name of the column to use as input. (For multi columns input as QA use column1,columns2)",
|
| 78 |
+
)
|
| 79 |
+
run_parser.add_argument(
|
| 80 |
+
"--format",
|
| 81 |
+
type=str,
|
| 82 |
+
default="infer",
|
| 83 |
+
choices=PipelineDataFormat.SUPPORTED_FORMATS,
|
| 84 |
+
help="Input format to read from",
|
| 85 |
+
)
|
| 86 |
+
run_parser.add_argument(
|
| 87 |
+
"--device",
|
| 88 |
+
type=int,
|
| 89 |
+
default=-1,
|
| 90 |
+
help="Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)",
|
| 91 |
+
)
|
| 92 |
+
run_parser.add_argument("--overwrite", action="store_true", help="Allow overwriting the output file.")
|
| 93 |
+
run_parser.set_defaults(func=run_command_factory)
|
| 94 |
+
|
| 95 |
+
def run(self):
|
| 96 |
+
nlp, outputs = self._nlp, []
|
| 97 |
+
|
| 98 |
+
for entry in self._reader:
|
| 99 |
+
output = nlp(**entry) if self._reader.is_multi_columns else nlp(entry)
|
| 100 |
+
if isinstance(output, dict):
|
| 101 |
+
outputs.append(output)
|
| 102 |
+
else:
|
| 103 |
+
outputs += output
|
| 104 |
+
|
| 105 |
+
# Saving data
|
| 106 |
+
if self._nlp.binary_output:
|
| 107 |
+
binary_path = self._reader.save_binary(outputs)
|
| 108 |
+
logger.warning(f"Current pipeline requires output to be in binary format, saving at {binary_path}")
|
| 109 |
+
else:
|
| 110 |
+
self._reader.save(outputs)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/serving.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from argparse import ArgumentParser, Namespace
|
| 16 |
+
from typing import Any, List, Optional
|
| 17 |
+
|
| 18 |
+
from ..pipelines import Pipeline, get_supported_tasks, pipeline
|
| 19 |
+
from ..utils import logging
|
| 20 |
+
from . import BaseTransformersCLICommand
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
from fastapi import Body, FastAPI, HTTPException
|
| 25 |
+
from fastapi.routing import APIRoute
|
| 26 |
+
from pydantic import BaseModel
|
| 27 |
+
from starlette.responses import JSONResponse
|
| 28 |
+
from uvicorn import run
|
| 29 |
+
|
| 30 |
+
_serve_dependencies_installed = True
|
| 31 |
+
except (ImportError, AttributeError):
|
| 32 |
+
BaseModel = object
|
| 33 |
+
|
| 34 |
+
def Body(*x, **y):
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
_serve_dependencies_installed = False
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger("transformers-cli/serving")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def serve_command_factory(args: Namespace):
|
| 44 |
+
"""
|
| 45 |
+
Factory function used to instantiate serving server from provided command line arguments.
|
| 46 |
+
|
| 47 |
+
Returns: ServeCommand
|
| 48 |
+
"""
|
| 49 |
+
nlp = pipeline(
|
| 50 |
+
task=args.task,
|
| 51 |
+
model=args.model if args.model else None,
|
| 52 |
+
config=args.config,
|
| 53 |
+
tokenizer=args.tokenizer,
|
| 54 |
+
device=args.device,
|
| 55 |
+
)
|
| 56 |
+
return ServeCommand(nlp, args.host, args.port, args.workers)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class ServeModelInfoResult(BaseModel):
|
| 60 |
+
"""
|
| 61 |
+
Expose model information
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
infos: dict
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class ServeTokenizeResult(BaseModel):
|
| 68 |
+
"""
|
| 69 |
+
Tokenize result model
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
tokens: List[str]
|
| 73 |
+
tokens_ids: Optional[List[int]]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class ServeDeTokenizeResult(BaseModel):
|
| 77 |
+
"""
|
| 78 |
+
DeTokenize result model
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
text: str
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class ServeForwardResult(BaseModel):
|
| 85 |
+
"""
|
| 86 |
+
Forward result model
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
output: Any
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class ServeCommand(BaseTransformersCLICommand):
|
| 93 |
+
@staticmethod
|
| 94 |
+
def register_subcommand(parser: ArgumentParser):
|
| 95 |
+
"""
|
| 96 |
+
Register this command to argparse so it's available for the transformer-cli
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
parser: Root parser to register command-specific arguments
|
| 100 |
+
"""
|
| 101 |
+
serve_parser = parser.add_parser(
|
| 102 |
+
"serve", help="CLI tool to run inference requests through REST and GraphQL endpoints."
|
| 103 |
+
)
|
| 104 |
+
serve_parser.add_argument(
|
| 105 |
+
"--task",
|
| 106 |
+
type=str,
|
| 107 |
+
choices=get_supported_tasks(),
|
| 108 |
+
help="The task to run the pipeline on",
|
| 109 |
+
)
|
| 110 |
+
serve_parser.add_argument("--host", type=str, default="localhost", help="Interface the server will listen on.")
|
| 111 |
+
serve_parser.add_argument("--port", type=int, default=8888, help="Port the serving will listen to.")
|
| 112 |
+
serve_parser.add_argument("--workers", type=int, default=1, help="Number of http workers")
|
| 113 |
+
serve_parser.add_argument("--model", type=str, help="Model's name or path to stored model.")
|
| 114 |
+
serve_parser.add_argument("--config", type=str, help="Model's config name or path to stored model.")
|
| 115 |
+
serve_parser.add_argument("--tokenizer", type=str, help="Tokenizer name to use.")
|
| 116 |
+
serve_parser.add_argument(
|
| 117 |
+
"--device",
|
| 118 |
+
type=int,
|
| 119 |
+
default=-1,
|
| 120 |
+
help="Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)",
|
| 121 |
+
)
|
| 122 |
+
serve_parser.set_defaults(func=serve_command_factory)
|
| 123 |
+
|
| 124 |
+
def __init__(self, pipeline: Pipeline, host: str, port: int, workers: int):
|
| 125 |
+
self._pipeline = pipeline
|
| 126 |
+
|
| 127 |
+
self.host = host
|
| 128 |
+
self.port = port
|
| 129 |
+
self.workers = workers
|
| 130 |
+
|
| 131 |
+
if not _serve_dependencies_installed:
|
| 132 |
+
raise RuntimeError(
|
| 133 |
+
"Using serve command requires FastAPI and uvicorn. "
|
| 134 |
+
'Please install transformers with [serving]: pip install "transformers[serving]".'
|
| 135 |
+
"Or install FastAPI and uvicorn separately."
|
| 136 |
+
)
|
| 137 |
+
else:
|
| 138 |
+
logger.info(f"Serving model over {host}:{port}")
|
| 139 |
+
self._app = FastAPI(
|
| 140 |
+
routes=[
|
| 141 |
+
APIRoute(
|
| 142 |
+
"/",
|
| 143 |
+
self.model_info,
|
| 144 |
+
response_model=ServeModelInfoResult,
|
| 145 |
+
response_class=JSONResponse,
|
| 146 |
+
methods=["GET"],
|
| 147 |
+
),
|
| 148 |
+
APIRoute(
|
| 149 |
+
"/tokenize",
|
| 150 |
+
self.tokenize,
|
| 151 |
+
response_model=ServeTokenizeResult,
|
| 152 |
+
response_class=JSONResponse,
|
| 153 |
+
methods=["POST"],
|
| 154 |
+
),
|
| 155 |
+
APIRoute(
|
| 156 |
+
"/detokenize",
|
| 157 |
+
self.detokenize,
|
| 158 |
+
response_model=ServeDeTokenizeResult,
|
| 159 |
+
response_class=JSONResponse,
|
| 160 |
+
methods=["POST"],
|
| 161 |
+
),
|
| 162 |
+
APIRoute(
|
| 163 |
+
"/forward",
|
| 164 |
+
self.forward,
|
| 165 |
+
response_model=ServeForwardResult,
|
| 166 |
+
response_class=JSONResponse,
|
| 167 |
+
methods=["POST"],
|
| 168 |
+
),
|
| 169 |
+
],
|
| 170 |
+
timeout=600,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
def run(self):
|
| 174 |
+
run(self._app, host=self.host, port=self.port, workers=self.workers)
|
| 175 |
+
|
| 176 |
+
def model_info(self):
|
| 177 |
+
return ServeModelInfoResult(infos=vars(self._pipeline.model.config))
|
| 178 |
+
|
| 179 |
+
def tokenize(self, text_input: str = Body(None, embed=True), return_ids: bool = Body(False, embed=True)):
|
| 180 |
+
"""
|
| 181 |
+
Tokenize the provided input and eventually returns corresponding tokens id: - **text_input**: String to
|
| 182 |
+
tokenize - **return_ids**: Boolean flags indicating if the tokens have to be converted to their integer
|
| 183 |
+
mapping.
|
| 184 |
+
"""
|
| 185 |
+
try:
|
| 186 |
+
tokens_txt = self._pipeline.tokenizer.tokenize(text_input)
|
| 187 |
+
|
| 188 |
+
if return_ids:
|
| 189 |
+
tokens_ids = self._pipeline.tokenizer.convert_tokens_to_ids(tokens_txt)
|
| 190 |
+
return ServeTokenizeResult(tokens=tokens_txt, tokens_ids=tokens_ids)
|
| 191 |
+
else:
|
| 192 |
+
return ServeTokenizeResult(tokens=tokens_txt)
|
| 193 |
+
|
| 194 |
+
except Exception as e:
|
| 195 |
+
raise HTTPException(status_code=500, detail={"model": "", "error": str(e)})
|
| 196 |
+
|
| 197 |
+
def detokenize(
|
| 198 |
+
self,
|
| 199 |
+
tokens_ids: List[int] = Body(None, embed=True),
|
| 200 |
+
skip_special_tokens: bool = Body(False, embed=True),
|
| 201 |
+
cleanup_tokenization_spaces: bool = Body(True, embed=True),
|
| 202 |
+
):
|
| 203 |
+
"""
|
| 204 |
+
Detokenize the provided tokens ids to readable text: - **tokens_ids**: List of tokens ids -
|
| 205 |
+
**skip_special_tokens**: Flag indicating to not try to decode special tokens - **cleanup_tokenization_spaces**:
|
| 206 |
+
Flag indicating to remove all leading/trailing spaces and intermediate ones.
|
| 207 |
+
"""
|
| 208 |
+
try:
|
| 209 |
+
decoded_str = self._pipeline.tokenizer.decode(tokens_ids, skip_special_tokens, cleanup_tokenization_spaces)
|
| 210 |
+
return ServeDeTokenizeResult(model="", text=decoded_str)
|
| 211 |
+
except Exception as e:
|
| 212 |
+
raise HTTPException(status_code=500, detail={"model": "", "error": str(e)})
|
| 213 |
+
|
| 214 |
+
async def forward(self, inputs=Body(None, embed=True)):
|
| 215 |
+
"""
|
| 216 |
+
**inputs**: **attention_mask**: **tokens_type_ids**:
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
# Check we don't have empty string
|
| 220 |
+
if len(inputs) == 0:
|
| 221 |
+
return ServeForwardResult(output=[], attention=[])
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
# Forward through the model
|
| 225 |
+
output = self._pipeline(inputs)
|
| 226 |
+
return ServeForwardResult(output=output)
|
| 227 |
+
except Exception as e:
|
| 228 |
+
raise HTTPException(500, {"error": str(e)})
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/commands/transformers_cli.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from argparse import ArgumentParser
|
| 17 |
+
|
| 18 |
+
from .add_new_model import AddNewModelCommand
|
| 19 |
+
from .add_new_model_like import AddNewModelLikeCommand
|
| 20 |
+
from .convert import ConvertCommand
|
| 21 |
+
from .download import DownloadCommand
|
| 22 |
+
from .env import EnvironmentCommand
|
| 23 |
+
from .lfs import LfsCommands
|
| 24 |
+
from .pt_to_tf import PTtoTFCommand
|
| 25 |
+
from .run import RunCommand
|
| 26 |
+
from .serving import ServeCommand
|
| 27 |
+
from .user import UserCommands
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def main():
|
| 31 |
+
parser = ArgumentParser("Transformers CLI tool", usage="transformers-cli <command> [<args>]")
|
| 32 |
+
commands_parser = parser.add_subparsers(help="transformers-cli command helpers")
|
| 33 |
+
|
| 34 |
+
# Register commands
|
| 35 |
+
ConvertCommand.register_subcommand(commands_parser)
|
| 36 |
+
DownloadCommand.register_subcommand(commands_parser)
|
| 37 |
+
EnvironmentCommand.register_subcommand(commands_parser)
|
| 38 |
+
RunCommand.register_subcommand(commands_parser)
|
| 39 |
+
ServeCommand.register_subcommand(commands_parser)
|
| 40 |
+
UserCommands.register_subcommand(commands_parser)
|
| 41 |
+
AddNewModelCommand.register_subcommand(commands_parser)
|
| 42 |
+
AddNewModelLikeCommand.register_subcommand(commands_parser)
|
| 43 |
+
LfsCommands.register_subcommand(commands_parser)
|
| 44 |
+
PTtoTFCommand.register_subcommand(commands_parser)
|
| 45 |
+
|
| 46 |
+
# Let's go
|
| 47 |
+
args = parser.parse_args()
|
| 48 |
+
|
| 49 |
+
if not hasattr(args, "func"):
|
| 50 |
+
parser.print_help()
|
| 51 |
+
exit(1)
|
| 52 |
+
|
| 53 |
+
# Run
|
| 54 |
+
service = args.func(args)
|
| 55 |
+
service.run()
|
| 56 |
+
|
| 57 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import subprocess
|
| 16 |
+
from argparse import ArgumentParser
|
| 17 |
+
from typing import List, Union
|
| 18 |
+
|
| 19 |
+
from huggingface_hub.hf_api import HfFolder, create_repo, whoami
|
| 20 |
+
from requests.exceptions import HTTPError
|
| 21 |
+
|
| 22 |
+
from . import BaseTransformersCLICommand
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class UserCommands(BaseTransformersCLICommand):
|
| 26 |
+
@staticmethod
|
| 27 |
+
def register_subcommand(parser: ArgumentParser):
|
| 28 |
+
login_parser = parser.add_parser("login", help="Log in using the same credentials as on huggingface.co")
|
| 29 |
+
login_parser.set_defaults(func=lambda args: LoginCommand(args))
|
| 30 |
+
whoami_parser = parser.add_parser("whoami", help="Find out which huggingface.co account you are logged in as.")
|
| 31 |
+
whoami_parser.set_defaults(func=lambda args: WhoamiCommand(args))
|
| 32 |
+
logout_parser = parser.add_parser("logout", help="Log out")
|
| 33 |
+
logout_parser.set_defaults(func=lambda args: LogoutCommand(args))
|
| 34 |
+
|
| 35 |
+
# new system: git-based repo system
|
| 36 |
+
repo_parser = parser.add_parser(
|
| 37 |
+
"repo",
|
| 38 |
+
help="Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos.",
|
| 39 |
+
)
|
| 40 |
+
repo_subparsers = repo_parser.add_subparsers(
|
| 41 |
+
help="Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands"
|
| 42 |
+
)
|
| 43 |
+
repo_create_parser = repo_subparsers.add_parser(
|
| 44 |
+
"create", help="Deprecated: use `huggingface-cli` instead. Create a new repo on huggingface.co"
|
| 45 |
+
)
|
| 46 |
+
repo_create_parser.add_argument(
|
| 47 |
+
"name",
|
| 48 |
+
type=str,
|
| 49 |
+
help="Name for your model's repo. Will be namespaced under your username to build the model id.",
|
| 50 |
+
)
|
| 51 |
+
repo_create_parser.add_argument("--organization", type=str, help="Optional: organization namespace.")
|
| 52 |
+
repo_create_parser.add_argument("-y", "--yes", action="store_true", help="Optional: answer Yes to the prompt")
|
| 53 |
+
repo_create_parser.set_defaults(func=lambda args: RepoCreateCommand(args))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class ANSI:
|
| 57 |
+
"""
|
| 58 |
+
Helper for en.wikipedia.org/wiki/ANSI_escape_code
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
_bold = "\u001b[1m"
|
| 62 |
+
_red = "\u001b[31m"
|
| 63 |
+
_gray = "\u001b[90m"
|
| 64 |
+
_reset = "\u001b[0m"
|
| 65 |
+
|
| 66 |
+
@classmethod
|
| 67 |
+
def bold(cls, s):
|
| 68 |
+
return f"{cls._bold}{s}{cls._reset}"
|
| 69 |
+
|
| 70 |
+
@classmethod
|
| 71 |
+
def red(cls, s):
|
| 72 |
+
return f"{cls._bold}{cls._red}{s}{cls._reset}"
|
| 73 |
+
|
| 74 |
+
@classmethod
|
| 75 |
+
def gray(cls, s):
|
| 76 |
+
return f"{cls._gray}{s}{cls._reset}"
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def tabulate(rows: List[List[Union[str, int]]], headers: List[str]) -> str:
|
| 80 |
+
"""
|
| 81 |
+
Inspired by:
|
| 82 |
+
|
| 83 |
+
- stackoverflow.com/a/8356620/593036
|
| 84 |
+
- stackoverflow.com/questions/9535954/printing-lists-as-tabular-data
|
| 85 |
+
"""
|
| 86 |
+
col_widths = [max(len(str(x)) for x in col) for col in zip(*rows, headers)]
|
| 87 |
+
row_format = ("{{:{}}} " * len(headers)).format(*col_widths)
|
| 88 |
+
lines = []
|
| 89 |
+
lines.append(row_format.format(*headers))
|
| 90 |
+
lines.append(row_format.format(*["-" * w for w in col_widths]))
|
| 91 |
+
for row in rows:
|
| 92 |
+
lines.append(row_format.format(*row))
|
| 93 |
+
return "\n".join(lines)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class BaseUserCommand:
|
| 97 |
+
def __init__(self, args):
|
| 98 |
+
self.args = args
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class LoginCommand(BaseUserCommand):
|
| 102 |
+
def run(self):
|
| 103 |
+
print(
|
| 104 |
+
ANSI.red(
|
| 105 |
+
"ERROR! `huggingface-cli login` uses an outdated login mechanism "
|
| 106 |
+
"that is not compatible with the Hugging Face Hub backend anymore. "
|
| 107 |
+
"Please use `huggingface-cli login instead."
|
| 108 |
+
)
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class WhoamiCommand(BaseUserCommand):
|
| 113 |
+
def run(self):
|
| 114 |
+
print(
|
| 115 |
+
ANSI.red(
|
| 116 |
+
"WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use "
|
| 117 |
+
"`huggingface-cli whoami` instead."
|
| 118 |
+
)
|
| 119 |
+
)
|
| 120 |
+
token = HfFolder.get_token()
|
| 121 |
+
if token is None:
|
| 122 |
+
print("Not logged in")
|
| 123 |
+
exit()
|
| 124 |
+
try:
|
| 125 |
+
user, orgs = whoami(token)
|
| 126 |
+
print(user)
|
| 127 |
+
if orgs:
|
| 128 |
+
print(ANSI.bold("orgs: "), ",".join(orgs))
|
| 129 |
+
except HTTPError as e:
|
| 130 |
+
print(e)
|
| 131 |
+
print(ANSI.red(e.response.text))
|
| 132 |
+
exit(1)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class LogoutCommand(BaseUserCommand):
|
| 136 |
+
def run(self):
|
| 137 |
+
print(
|
| 138 |
+
ANSI.red(
|
| 139 |
+
"ERROR! `transformers-cli logout` uses an outdated logout mechanism "
|
| 140 |
+
"that is not compatible with the Hugging Face Hub backend anymore. "
|
| 141 |
+
"Please use `huggingface-cli logout instead."
|
| 142 |
+
)
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class RepoCreateCommand(BaseUserCommand):
|
| 147 |
+
def run(self):
|
| 148 |
+
print(
|
| 149 |
+
ANSI.red(
|
| 150 |
+
"WARNING! Managing repositories through transformers-cli is deprecated. "
|
| 151 |
+
"Please use `huggingface-cli` instead."
|
| 152 |
+
)
|
| 153 |
+
)
|
| 154 |
+
token = HfFolder.get_token()
|
| 155 |
+
if token is None:
|
| 156 |
+
print("Not logged in")
|
| 157 |
+
exit(1)
|
| 158 |
+
try:
|
| 159 |
+
stdout = subprocess.check_output(["git", "--version"]).decode("utf-8")
|
| 160 |
+
print(ANSI.gray(stdout.strip()))
|
| 161 |
+
except FileNotFoundError:
|
| 162 |
+
print("Looks like you do not have git installed, please install.")
|
| 163 |
+
|
| 164 |
+
try:
|
| 165 |
+
stdout = subprocess.check_output(["git-lfs", "--version"]).decode("utf-8")
|
| 166 |
+
print(ANSI.gray(stdout.strip()))
|
| 167 |
+
except FileNotFoundError:
|
| 168 |
+
print(
|
| 169 |
+
ANSI.red(
|
| 170 |
+
"Looks like you do not have git-lfs installed, please install."
|
| 171 |
+
" You can install from https://git-lfs.github.com/."
|
| 172 |
+
" Then run `git lfs install` (you only have to do this once)."
|
| 173 |
+
)
|
| 174 |
+
)
|
| 175 |
+
print("")
|
| 176 |
+
|
| 177 |
+
user, _ = whoami(token)
|
| 178 |
+
namespace = self.args.organization if self.args.organization is not None else user
|
| 179 |
+
full_name = f"{namespace}/{self.args.name}"
|
| 180 |
+
print(f"You are about to create {ANSI.bold(full_name)}")
|
| 181 |
+
|
| 182 |
+
if not self.args.yes:
|
| 183 |
+
choice = input("Proceed? [Y/n] ").lower()
|
| 184 |
+
if not (choice == "" or choice == "y" or choice == "yes"):
|
| 185 |
+
print("Abort")
|
| 186 |
+
exit()
|
| 187 |
+
try:
|
| 188 |
+
url = create_repo(token, name=self.args.name, organization=self.args.organization)
|
| 189 |
+
except HTTPError as e:
|
| 190 |
+
print(e)
|
| 191 |
+
print(ANSI.red(e.response.text))
|
| 192 |
+
exit(1)
|
| 193 |
+
print("\nYour repo now lives at:")
|
| 194 |
+
print(f" {ANSI.bold(url)}")
|
| 195 |
+
print("\nYou can clone it locally with the command below, and commit/push as usual.")
|
| 196 |
+
print(f"\n git clone {url}")
|
| 197 |
+
print("")
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/data/test_generation_utils.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import random
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
import timeout_decorator
|
| 19 |
+
|
| 20 |
+
from ..testing_utils import require_torch
|
| 21 |
+
from ..utils import cached_property, is_torch_available
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if is_torch_available():
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
from ..models.marian import MarianConfig, MarianMTModel
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@require_torch
|
| 31 |
+
class GenerationUtilsTest(unittest.TestCase):
|
| 32 |
+
@cached_property
|
| 33 |
+
def config(self):
|
| 34 |
+
config = MarianConfig.from_pretrained("sshleifer/tiny-marian-en-de")
|
| 35 |
+
return config
|
| 36 |
+
|
| 37 |
+
@cached_property
|
| 38 |
+
def model(self):
|
| 39 |
+
return MarianMTModel(self.config)
|
| 40 |
+
|
| 41 |
+
def test_postprocess_next_token_scores(self):
|
| 42 |
+
config = self.config
|
| 43 |
+
model = self.model
|
| 44 |
+
# Initialize an input id tensor with batch size 8 and sequence length 12
|
| 45 |
+
input_ids = torch.arange(0, 96, 1).view((8, 12))
|
| 46 |
+
eos = config.eos_token_id
|
| 47 |
+
bad_words_ids_test_cases = [[[299]], [[23, 24], [54]], [[config.eos_token_id]], []]
|
| 48 |
+
masked_scores = [
|
| 49 |
+
[(0, 299), (1, 299), (2, 299), (3, 299), (4, 299), (5, 299), (6, 299), (7, 299)],
|
| 50 |
+
[(1, 24), (0, 54), (1, 54), (2, 54), (3, 54), (4, 54), (5, 54), (6, 54), (7, 54)],
|
| 51 |
+
[(0, eos), (1, eos), (2, eos), (3, eos), (4, eos), (5, eos), (6, eos), (7, eos)],
|
| 52 |
+
[],
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
for test_case_index, bad_words_ids in enumerate(bad_words_ids_test_cases):
|
| 56 |
+
# Initialize a scores tensor with batch size 8 and vocabulary size 300
|
| 57 |
+
scores = torch.rand((8, 300))
|
| 58 |
+
output = model.postprocess_next_token_scores(
|
| 59 |
+
scores,
|
| 60 |
+
input_ids,
|
| 61 |
+
0,
|
| 62 |
+
bad_words_ids,
|
| 63 |
+
13,
|
| 64 |
+
15,
|
| 65 |
+
config.max_length,
|
| 66 |
+
config.eos_token_id,
|
| 67 |
+
config.repetition_penalty,
|
| 68 |
+
32,
|
| 69 |
+
5,
|
| 70 |
+
)
|
| 71 |
+
for masked_score in masked_scores[test_case_index]:
|
| 72 |
+
self.assertTrue(output[masked_score[0], masked_score[1]] == -float("inf"))
|
| 73 |
+
|
| 74 |
+
@timeout_decorator.timeout(10)
|
| 75 |
+
def test_postprocess_next_token_scores_large_bad_words_list(self):
|
| 76 |
+
config = self.config
|
| 77 |
+
model = self.model
|
| 78 |
+
# Initialize an input id tensor with batch size 8 and sequence length 12
|
| 79 |
+
input_ids = torch.arange(0, 96, 1).view((8, 12))
|
| 80 |
+
|
| 81 |
+
bad_words_ids = []
|
| 82 |
+
for _ in range(100):
|
| 83 |
+
length_bad_word = random.randint(1, 4)
|
| 84 |
+
bad_words_ids.append(random.sample(range(1, 300), length_bad_word))
|
| 85 |
+
|
| 86 |
+
scores = torch.rand((8, 300))
|
| 87 |
+
_ = model.postprocess_next_token_scores(
|
| 88 |
+
scores,
|
| 89 |
+
input_ids,
|
| 90 |
+
0,
|
| 91 |
+
bad_words_ids,
|
| 92 |
+
13,
|
| 93 |
+
15,
|
| 94 |
+
config.max_length,
|
| 95 |
+
config.eos_token_id,
|
| 96 |
+
config.repetition_penalty,
|
| 97 |
+
32,
|
| 98 |
+
5,
|
| 99 |
+
)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/generation/__init__.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_flax_available, is_tf_available, is_torch_available
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_import_structure = {
|
| 21 |
+
"configuration_utils": ["GenerationConfig"],
|
| 22 |
+
"streamers": ["TextIteratorStreamer", "TextStreamer"],
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
if not is_torch_available():
|
| 27 |
+
raise OptionalDependencyNotAvailable()
|
| 28 |
+
except OptionalDependencyNotAvailable:
|
| 29 |
+
pass
|
| 30 |
+
else:
|
| 31 |
+
_import_structure["beam_constraints"] = [
|
| 32 |
+
"Constraint",
|
| 33 |
+
"ConstraintListState",
|
| 34 |
+
"DisjunctiveConstraint",
|
| 35 |
+
"PhrasalConstraint",
|
| 36 |
+
]
|
| 37 |
+
_import_structure["beam_search"] = [
|
| 38 |
+
"BeamHypotheses",
|
| 39 |
+
"BeamScorer",
|
| 40 |
+
"BeamSearchScorer",
|
| 41 |
+
"ConstrainedBeamSearchScorer",
|
| 42 |
+
]
|
| 43 |
+
_import_structure["logits_process"] = [
|
| 44 |
+
"EpsilonLogitsWarper",
|
| 45 |
+
"EtaLogitsWarper",
|
| 46 |
+
"ForcedBOSTokenLogitsProcessor",
|
| 47 |
+
"ForcedEOSTokenLogitsProcessor",
|
| 48 |
+
"HammingDiversityLogitsProcessor",
|
| 49 |
+
"InfNanRemoveLogitsProcessor",
|
| 50 |
+
"LogitsProcessor",
|
| 51 |
+
"LogitsProcessorList",
|
| 52 |
+
"LogitsWarper",
|
| 53 |
+
"MinLengthLogitsProcessor",
|
| 54 |
+
"MinNewTokensLengthLogitsProcessor",
|
| 55 |
+
"NoBadWordsLogitsProcessor",
|
| 56 |
+
"NoRepeatNGramLogitsProcessor",
|
| 57 |
+
"PrefixConstrainedLogitsProcessor",
|
| 58 |
+
"RepetitionPenaltyLogitsProcessor",
|
| 59 |
+
"EncoderRepetitionPenaltyLogitsProcessor",
|
| 60 |
+
"TemperatureLogitsWarper",
|
| 61 |
+
"TopKLogitsWarper",
|
| 62 |
+
"TopPLogitsWarper",
|
| 63 |
+
"TypicalLogitsWarper",
|
| 64 |
+
"EncoderNoRepeatNGramLogitsProcessor",
|
| 65 |
+
"ExponentialDecayLengthPenalty",
|
| 66 |
+
"LogitNormalization",
|
| 67 |
+
]
|
| 68 |
+
_import_structure["stopping_criteria"] = [
|
| 69 |
+
"MaxNewTokensCriteria",
|
| 70 |
+
"MaxLengthCriteria",
|
| 71 |
+
"MaxTimeCriteria",
|
| 72 |
+
"StoppingCriteria",
|
| 73 |
+
"StoppingCriteriaList",
|
| 74 |
+
"validate_stopping_criteria",
|
| 75 |
+
]
|
| 76 |
+
_import_structure["utils"] = [
|
| 77 |
+
"GenerationMixin",
|
| 78 |
+
"top_k_top_p_filtering",
|
| 79 |
+
"GreedySearchEncoderDecoderOutput",
|
| 80 |
+
"GreedySearchDecoderOnlyOutput",
|
| 81 |
+
"SampleEncoderDecoderOutput",
|
| 82 |
+
"SampleDecoderOnlyOutput",
|
| 83 |
+
"BeamSearchEncoderDecoderOutput",
|
| 84 |
+
"BeamSearchDecoderOnlyOutput",
|
| 85 |
+
"BeamSampleEncoderDecoderOutput",
|
| 86 |
+
"BeamSampleDecoderOnlyOutput",
|
| 87 |
+
"ContrastiveSearchEncoderDecoderOutput",
|
| 88 |
+
"ContrastiveSearchDecoderOnlyOutput",
|
| 89 |
+
]
|
| 90 |
+
|
| 91 |
+
try:
|
| 92 |
+
if not is_tf_available():
|
| 93 |
+
raise OptionalDependencyNotAvailable()
|
| 94 |
+
except OptionalDependencyNotAvailable:
|
| 95 |
+
pass
|
| 96 |
+
else:
|
| 97 |
+
_import_structure["tf_logits_process"] = [
|
| 98 |
+
"TFForcedBOSTokenLogitsProcessor",
|
| 99 |
+
"TFForcedEOSTokenLogitsProcessor",
|
| 100 |
+
"TFLogitsProcessor",
|
| 101 |
+
"TFLogitsProcessorList",
|
| 102 |
+
"TFLogitsWarper",
|
| 103 |
+
"TFMinLengthLogitsProcessor",
|
| 104 |
+
"TFNoBadWordsLogitsProcessor",
|
| 105 |
+
"TFNoRepeatNGramLogitsProcessor",
|
| 106 |
+
"TFRepetitionPenaltyLogitsProcessor",
|
| 107 |
+
"TFTemperatureLogitsWarper",
|
| 108 |
+
"TFTopKLogitsWarper",
|
| 109 |
+
"TFTopPLogitsWarper",
|
| 110 |
+
"TFForceTokensLogitsProcessor",
|
| 111 |
+
"TFSuppressTokensAtBeginLogitsProcessor",
|
| 112 |
+
"TFSuppressTokensLogitsProcessor",
|
| 113 |
+
]
|
| 114 |
+
_import_structure["tf_utils"] = [
|
| 115 |
+
"TFGenerationMixin",
|
| 116 |
+
"tf_top_k_top_p_filtering",
|
| 117 |
+
"TFGreedySearchDecoderOnlyOutput",
|
| 118 |
+
"TFGreedySearchEncoderDecoderOutput",
|
| 119 |
+
"TFSampleEncoderDecoderOutput",
|
| 120 |
+
"TFSampleDecoderOnlyOutput",
|
| 121 |
+
"TFBeamSearchEncoderDecoderOutput",
|
| 122 |
+
"TFBeamSearchDecoderOnlyOutput",
|
| 123 |
+
"TFBeamSampleEncoderDecoderOutput",
|
| 124 |
+
"TFBeamSampleDecoderOnlyOutput",
|
| 125 |
+
"TFContrastiveSearchEncoderDecoderOutput",
|
| 126 |
+
"TFContrastiveSearchDecoderOnlyOutput",
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
try:
|
| 130 |
+
if not is_flax_available():
|
| 131 |
+
raise OptionalDependencyNotAvailable()
|
| 132 |
+
except OptionalDependencyNotAvailable:
|
| 133 |
+
pass
|
| 134 |
+
else:
|
| 135 |
+
_import_structure["flax_logits_process"] = [
|
| 136 |
+
"FlaxForcedBOSTokenLogitsProcessor",
|
| 137 |
+
"FlaxForcedEOSTokenLogitsProcessor",
|
| 138 |
+
"FlaxLogitsProcessor",
|
| 139 |
+
"FlaxLogitsProcessorList",
|
| 140 |
+
"FlaxLogitsWarper",
|
| 141 |
+
"FlaxMinLengthLogitsProcessor",
|
| 142 |
+
"FlaxTemperatureLogitsWarper",
|
| 143 |
+
"FlaxTopKLogitsWarper",
|
| 144 |
+
"FlaxTopPLogitsWarper",
|
| 145 |
+
]
|
| 146 |
+
_import_structure["flax_utils"] = [
|
| 147 |
+
"FlaxGenerationMixin",
|
| 148 |
+
"FlaxGreedySearchOutput",
|
| 149 |
+
"FlaxSampleOutput",
|
| 150 |
+
"FlaxBeamSearchOutput",
|
| 151 |
+
]
|
| 152 |
+
|
| 153 |
+
if TYPE_CHECKING:
|
| 154 |
+
from .configuration_utils import GenerationConfig
|
| 155 |
+
from .streamers import TextIteratorStreamer, TextStreamer
|
| 156 |
+
|
| 157 |
+
try:
|
| 158 |
+
if not is_torch_available():
|
| 159 |
+
raise OptionalDependencyNotAvailable()
|
| 160 |
+
except OptionalDependencyNotAvailable:
|
| 161 |
+
pass
|
| 162 |
+
else:
|
| 163 |
+
from .beam_constraints import Constraint, ConstraintListState, DisjunctiveConstraint, PhrasalConstraint
|
| 164 |
+
from .beam_search import BeamHypotheses, BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
|
| 165 |
+
from .logits_process import (
|
| 166 |
+
EncoderNoRepeatNGramLogitsProcessor,
|
| 167 |
+
EncoderRepetitionPenaltyLogitsProcessor,
|
| 168 |
+
EpsilonLogitsWarper,
|
| 169 |
+
EtaLogitsWarper,
|
| 170 |
+
ExponentialDecayLengthPenalty,
|
| 171 |
+
ForcedBOSTokenLogitsProcessor,
|
| 172 |
+
ForcedEOSTokenLogitsProcessor,
|
| 173 |
+
HammingDiversityLogitsProcessor,
|
| 174 |
+
InfNanRemoveLogitsProcessor,
|
| 175 |
+
LogitNormalization,
|
| 176 |
+
LogitsProcessor,
|
| 177 |
+
LogitsProcessorList,
|
| 178 |
+
LogitsWarper,
|
| 179 |
+
MinLengthLogitsProcessor,
|
| 180 |
+
MinNewTokensLengthLogitsProcessor,
|
| 181 |
+
NoBadWordsLogitsProcessor,
|
| 182 |
+
NoRepeatNGramLogitsProcessor,
|
| 183 |
+
PrefixConstrainedLogitsProcessor,
|
| 184 |
+
RepetitionPenaltyLogitsProcessor,
|
| 185 |
+
TemperatureLogitsWarper,
|
| 186 |
+
TopKLogitsWarper,
|
| 187 |
+
TopPLogitsWarper,
|
| 188 |
+
TypicalLogitsWarper,
|
| 189 |
+
)
|
| 190 |
+
from .stopping_criteria import (
|
| 191 |
+
MaxLengthCriteria,
|
| 192 |
+
MaxNewTokensCriteria,
|
| 193 |
+
MaxTimeCriteria,
|
| 194 |
+
StoppingCriteria,
|
| 195 |
+
StoppingCriteriaList,
|
| 196 |
+
validate_stopping_criteria,
|
| 197 |
+
)
|
| 198 |
+
from .utils import (
|
| 199 |
+
BeamSampleDecoderOnlyOutput,
|
| 200 |
+
BeamSampleEncoderDecoderOutput,
|
| 201 |
+
BeamSearchDecoderOnlyOutput,
|
| 202 |
+
BeamSearchEncoderDecoderOutput,
|
| 203 |
+
ContrastiveSearchDecoderOnlyOutput,
|
| 204 |
+
ContrastiveSearchEncoderDecoderOutput,
|
| 205 |
+
GenerationMixin,
|
| 206 |
+
GreedySearchDecoderOnlyOutput,
|
| 207 |
+
GreedySearchEncoderDecoderOutput,
|
| 208 |
+
SampleDecoderOnlyOutput,
|
| 209 |
+
SampleEncoderDecoderOutput,
|
| 210 |
+
top_k_top_p_filtering,
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
try:
|
| 214 |
+
if not is_tf_available():
|
| 215 |
+
raise OptionalDependencyNotAvailable()
|
| 216 |
+
except OptionalDependencyNotAvailable:
|
| 217 |
+
pass
|
| 218 |
+
else:
|
| 219 |
+
from .tf_logits_process import (
|
| 220 |
+
TFForcedBOSTokenLogitsProcessor,
|
| 221 |
+
TFForcedEOSTokenLogitsProcessor,
|
| 222 |
+
TFForceTokensLogitsProcessor,
|
| 223 |
+
TFLogitsProcessor,
|
| 224 |
+
TFLogitsProcessorList,
|
| 225 |
+
TFLogitsWarper,
|
| 226 |
+
TFMinLengthLogitsProcessor,
|
| 227 |
+
TFNoBadWordsLogitsProcessor,
|
| 228 |
+
TFNoRepeatNGramLogitsProcessor,
|
| 229 |
+
TFRepetitionPenaltyLogitsProcessor,
|
| 230 |
+
TFSuppressTokensAtBeginLogitsProcessor,
|
| 231 |
+
TFSuppressTokensLogitsProcessor,
|
| 232 |
+
TFTemperatureLogitsWarper,
|
| 233 |
+
TFTopKLogitsWarper,
|
| 234 |
+
TFTopPLogitsWarper,
|
| 235 |
+
)
|
| 236 |
+
from .tf_utils import (
|
| 237 |
+
TFBeamSampleDecoderOnlyOutput,
|
| 238 |
+
TFBeamSampleEncoderDecoderOutput,
|
| 239 |
+
TFBeamSearchDecoderOnlyOutput,
|
| 240 |
+
TFBeamSearchEncoderDecoderOutput,
|
| 241 |
+
TFContrastiveSearchDecoderOnlyOutput,
|
| 242 |
+
TFContrastiveSearchEncoderDecoderOutput,
|
| 243 |
+
TFGenerationMixin,
|
| 244 |
+
TFGreedySearchDecoderOnlyOutput,
|
| 245 |
+
TFGreedySearchEncoderDecoderOutput,
|
| 246 |
+
TFSampleDecoderOnlyOutput,
|
| 247 |
+
TFSampleEncoderDecoderOutput,
|
| 248 |
+
tf_top_k_top_p_filtering,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
try:
|
| 252 |
+
if not is_flax_available():
|
| 253 |
+
raise OptionalDependencyNotAvailable()
|
| 254 |
+
except OptionalDependencyNotAvailable:
|
| 255 |
+
pass
|
| 256 |
+
else:
|
| 257 |
+
from .flax_logits_process import (
|
| 258 |
+
FlaxForcedBOSTokenLogitsProcessor,
|
| 259 |
+
FlaxForcedEOSTokenLogitsProcessor,
|
| 260 |
+
FlaxLogitsProcessor,
|
| 261 |
+
FlaxLogitsProcessorList,
|
| 262 |
+
FlaxLogitsWarper,
|
| 263 |
+
FlaxMinLengthLogitsProcessor,
|
| 264 |
+
FlaxTemperatureLogitsWarper,
|
| 265 |
+
FlaxTopKLogitsWarper,
|
| 266 |
+
FlaxTopPLogitsWarper,
|
| 267 |
+
)
|
| 268 |
+
from .flax_utils import FlaxBeamSearchOutput, FlaxGenerationMixin, FlaxGreedySearchOutput, FlaxSampleOutput
|
| 269 |
+
else:
|
| 270 |
+
import sys
|
| 271 |
+
|
| 272 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/kernels/rwkv/wkv_op.cpp
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <torch/extension.h>
|
| 2 |
+
#include "ATen/ATen.h"
|
| 3 |
+
typedef at::BFloat16 bf16;
|
| 4 |
+
|
| 5 |
+
void cuda_forward(int B, int T, int C, float *w, float *u, float *k, float *v, float *y);
|
| 6 |
+
void cuda_forward_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y);
|
| 7 |
+
void cuda_forward_with_state(int B, int T, int C, float *w, float *u, float *k, float *v, float *y, float *s);
|
| 8 |
+
void cuda_forward_with_state_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y, float *s);
|
| 9 |
+
void cuda_backward(int B, int T, int C, float *w, float *u, float *k, float *v, float *y, float *gy, float *gw, float *gu, float *gk, float *gv);
|
| 10 |
+
void cuda_backward_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y, bf16 *gy, bf16 *gw, bf16 *gu, bf16 *gk, bf16 *gv);
|
| 11 |
+
|
| 12 |
+
void forward(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y) {
|
| 13 |
+
const int B = k.size(0);
|
| 14 |
+
const int T = k.size(1);
|
| 15 |
+
const int C = k.size(2);
|
| 16 |
+
cuda_forward(B, T, C, w.data_ptr<float>(), u.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(), y.data_ptr<float>());
|
| 17 |
+
}
|
| 18 |
+
void forward_bf16(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y) {
|
| 19 |
+
const int B = k.size(0);
|
| 20 |
+
const int T = k.size(1);
|
| 21 |
+
const int C = k.size(2);
|
| 22 |
+
cuda_forward_bf16(B, T, C, w.data_ptr<float>(), u.data_ptr<bf16>(), k.data_ptr<bf16>(), v.data_ptr<bf16>(), y.data_ptr<bf16>());
|
| 23 |
+
}
|
| 24 |
+
void forward_with_state(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y, torch::Tensor &s) {
|
| 25 |
+
const int B = k.size(0);
|
| 26 |
+
const int T = k.size(1);
|
| 27 |
+
const int C = k.size(2);
|
| 28 |
+
cuda_forward_with_state(B, T, C, w.data_ptr<float>(), u.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(), y.data_ptr<float>(), s.data_ptr<float>());
|
| 29 |
+
}
|
| 30 |
+
void forward_with_state_bf16(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y, torch::Tensor &s) {
|
| 31 |
+
const int B = k.size(0);
|
| 32 |
+
const int T = k.size(1);
|
| 33 |
+
const int C = k.size(2);
|
| 34 |
+
cuda_forward_with_state_bf16(B, T, C, w.data_ptr<float>(), u.data_ptr<bf16>(), k.data_ptr<bf16>(), v.data_ptr<bf16>(), y.data_ptr<bf16>(), s.data_ptr<float>());
|
| 35 |
+
}
|
| 36 |
+
void backward(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y, torch::Tensor &gy, torch::Tensor &gw, torch::Tensor &gu, torch::Tensor &gk, torch::Tensor &gv) {
|
| 37 |
+
const int B = k.size(0);
|
| 38 |
+
const int T = k.size(1);
|
| 39 |
+
const int C = k.size(2);
|
| 40 |
+
cuda_backward(B, T, C, w.data_ptr<float>(), u.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(), y.data_ptr<float>(), gy.data_ptr<float>(), gw.data_ptr<float>(), gu.data_ptr<float>(), gk.data_ptr<float>(), gv.data_ptr<float>());
|
| 41 |
+
}
|
| 42 |
+
void backward_bf16(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y, torch::Tensor &gy, torch::Tensor &gw, torch::Tensor &gu, torch::Tensor &gk, torch::Tensor &gv) {
|
| 43 |
+
const int B = k.size(0);
|
| 44 |
+
const int T = k.size(1);
|
| 45 |
+
const int C = k.size(2);
|
| 46 |
+
cuda_backward_bf16(B, T, C, w.data_ptr<float>(), u.data_ptr<bf16>(), k.data_ptr<bf16>(), v.data_ptr<bf16>(), y.data_ptr<bf16>(),
|
| 47 |
+
gy.data_ptr<bf16>(), gw.data_ptr<bf16>(), gu.data_ptr<bf16>(), gk.data_ptr<bf16>(), gv.data_ptr<bf16>());
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
| 51 |
+
m.def("forward", &forward, "wkv forward");
|
| 52 |
+
m.def("forward_bf16", &forward_bf16, "wkv forward bf16");
|
| 53 |
+
m.def("forward_with_state", &forward_with_state, "wkv forward with state");
|
| 54 |
+
m.def("forward_with_state_bf16", &forward_with_state_bf16, "wkv forward with state bf16");
|
| 55 |
+
m.def("backward", &backward, "wkv backward");
|
| 56 |
+
m.def("backward_bf16", &backward_bf16, "wkv backward bf16");
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
TORCH_LIBRARY(wkv, m) {
|
| 60 |
+
m.def("forward", forward);
|
| 61 |
+
m.def("forward_bf16", forward_bf16);
|
| 62 |
+
m.def("forward_with_state", forward_with_state);
|
| 63 |
+
m.def("forward_with_state_bf16", forward_with_state_bf16);
|
| 64 |
+
m.def("backward", backward);
|
| 65 |
+
m.def("backward_bf16", backward_bf16);
|
| 66 |
+
}
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/modelcard.py
ADDED
|
@@ -0,0 +1,903 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Configuration base class and utilities."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import copy
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import warnings
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Any, Dict, List, Optional, Union
|
| 25 |
+
|
| 26 |
+
import requests
|
| 27 |
+
import yaml
|
| 28 |
+
from huggingface_hub import model_info
|
| 29 |
+
from huggingface_hub.utils import HFValidationError
|
| 30 |
+
|
| 31 |
+
from . import __version__
|
| 32 |
+
from .models.auto.modeling_auto import (
|
| 33 |
+
MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES,
|
| 34 |
+
MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,
|
| 35 |
+
MODEL_FOR_CTC_MAPPING_NAMES,
|
| 36 |
+
MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES,
|
| 37 |
+
MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES,
|
| 38 |
+
MODEL_FOR_MASKED_LM_MAPPING_NAMES,
|
| 39 |
+
MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,
|
| 40 |
+
MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES,
|
| 41 |
+
MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
|
| 42 |
+
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES,
|
| 43 |
+
MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES,
|
| 44 |
+
MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES,
|
| 45 |
+
MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,
|
| 46 |
+
MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES,
|
| 47 |
+
)
|
| 48 |
+
from .training_args import ParallelMode
|
| 49 |
+
from .utils import (
|
| 50 |
+
MODEL_CARD_NAME,
|
| 51 |
+
cached_file,
|
| 52 |
+
is_datasets_available,
|
| 53 |
+
is_offline_mode,
|
| 54 |
+
is_tf_available,
|
| 55 |
+
is_tokenizers_available,
|
| 56 |
+
is_torch_available,
|
| 57 |
+
logging,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
TASK_MAPPING = {
|
| 62 |
+
"text-generation": MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,
|
| 63 |
+
"image-classification": MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES,
|
| 64 |
+
"image-segmentation": MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES,
|
| 65 |
+
"fill-mask": MODEL_FOR_MASKED_LM_MAPPING_NAMES,
|
| 66 |
+
"object-detection": MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,
|
| 67 |
+
"question-answering": MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES,
|
| 68 |
+
"text2text-generation": MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
|
| 69 |
+
"text-classification": MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES,
|
| 70 |
+
"table-question-answering": MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES,
|
| 71 |
+
"token-classification": MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,
|
| 72 |
+
"audio-classification": MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES,
|
| 73 |
+
"automatic-speech-recognition": {**MODEL_FOR_CTC_MAPPING_NAMES, **MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES},
|
| 74 |
+
"zero-shot-image-classification": MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES,
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
logger = logging.get_logger(__name__)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class ModelCard:
|
| 81 |
+
r"""
|
| 82 |
+
Structured Model Card class. Store model card as well as methods for loading/downloading/saving model cards.
|
| 83 |
+
|
| 84 |
+
Please read the following paper for details and explanation on the sections: "Model Cards for Model Reporting" by
|
| 85 |
+
Margaret Mitchell, Simone Wu, Andrew Zaldivar, Parker Barnes, Lucy Vasserman, Ben Hutchinson, Elena Spitzer,
|
| 86 |
+
Inioluwa Deborah Raji and Timnit Gebru for the proposal behind model cards. Link: https://arxiv.org/abs/1810.03993
|
| 87 |
+
|
| 88 |
+
Note: A model card can be loaded and saved to disk.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
def __init__(self, **kwargs):
|
| 92 |
+
warnings.warn(
|
| 93 |
+
"The class `ModelCard` is deprecated and will be removed in version 5 of Transformers", FutureWarning
|
| 94 |
+
)
|
| 95 |
+
# Recommended attributes from https://arxiv.org/abs/1810.03993 (see papers)
|
| 96 |
+
self.model_details = kwargs.pop("model_details", {})
|
| 97 |
+
self.intended_use = kwargs.pop("intended_use", {})
|
| 98 |
+
self.factors = kwargs.pop("factors", {})
|
| 99 |
+
self.metrics = kwargs.pop("metrics", {})
|
| 100 |
+
self.evaluation_data = kwargs.pop("evaluation_data", {})
|
| 101 |
+
self.training_data = kwargs.pop("training_data", {})
|
| 102 |
+
self.quantitative_analyses = kwargs.pop("quantitative_analyses", {})
|
| 103 |
+
self.ethical_considerations = kwargs.pop("ethical_considerations", {})
|
| 104 |
+
self.caveats_and_recommendations = kwargs.pop("caveats_and_recommendations", {})
|
| 105 |
+
|
| 106 |
+
# Open additional attributes
|
| 107 |
+
for key, value in kwargs.items():
|
| 108 |
+
try:
|
| 109 |
+
setattr(self, key, value)
|
| 110 |
+
except AttributeError as err:
|
| 111 |
+
logger.error(f"Can't set {key} with value {value} for {self}")
|
| 112 |
+
raise err
|
| 113 |
+
|
| 114 |
+
def save_pretrained(self, save_directory_or_file):
|
| 115 |
+
"""Save a model card object to the directory or file `save_directory_or_file`."""
|
| 116 |
+
if os.path.isdir(save_directory_or_file):
|
| 117 |
+
# If we save using the predefined names, we can load using `from_pretrained`
|
| 118 |
+
output_model_card_file = os.path.join(save_directory_or_file, MODEL_CARD_NAME)
|
| 119 |
+
else:
|
| 120 |
+
output_model_card_file = save_directory_or_file
|
| 121 |
+
|
| 122 |
+
self.to_json_file(output_model_card_file)
|
| 123 |
+
logger.info(f"Model card saved in {output_model_card_file}")
|
| 124 |
+
|
| 125 |
+
@classmethod
|
| 126 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 127 |
+
r"""
|
| 128 |
+
Instantiate a [`ModelCard`] from a pre-trained model model card.
|
| 129 |
+
|
| 130 |
+
Parameters:
|
| 131 |
+
pretrained_model_name_or_path: either:
|
| 132 |
+
|
| 133 |
+
- a string, the *model id* of a pretrained model card hosted inside a model repo on huggingface.co.
|
| 134 |
+
Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
|
| 135 |
+
user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 136 |
+
- a path to a *directory* containing a model card file saved using the [`~ModelCard.save_pretrained`]
|
| 137 |
+
method, e.g.: `./my_model_directory/`.
|
| 138 |
+
- a path or url to a saved model card JSON *file*, e.g.: `./my_model_directory/modelcard.json`.
|
| 139 |
+
|
| 140 |
+
cache_dir: (*optional*) string:
|
| 141 |
+
Path to a directory in which a downloaded pre-trained model card should be cached if the standard cache
|
| 142 |
+
should not be used.
|
| 143 |
+
|
| 144 |
+
kwargs: (*optional*) dict: key/value pairs with which to update the ModelCard object after loading.
|
| 145 |
+
|
| 146 |
+
- The values in kwargs of any keys which are model card attributes will be used to override the loaded
|
| 147 |
+
values.
|
| 148 |
+
- Behavior concerning key/value pairs whose keys are *not* model card attributes is controlled by the
|
| 149 |
+
*return_unused_kwargs* keyword parameter.
|
| 150 |
+
|
| 151 |
+
proxies: (*optional*) dict, default None:
|
| 152 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128',
|
| 153 |
+
'http://hostname': 'foo.bar:4012'}. The proxies are used on each request.
|
| 154 |
+
|
| 155 |
+
return_unused_kwargs: (*optional*) bool:
|
| 156 |
+
|
| 157 |
+
- If False, then this function returns just the final model card object.
|
| 158 |
+
- If True, then this functions returns a tuple *(model card, unused_kwargs)* where *unused_kwargs* is a
|
| 159 |
+
dictionary consisting of the key/value pairs whose keys are not model card attributes: ie the part of
|
| 160 |
+
kwargs which has not been used to update *ModelCard* and is otherwise ignored.
|
| 161 |
+
|
| 162 |
+
Examples:
|
| 163 |
+
|
| 164 |
+
```python
|
| 165 |
+
# Download model card from huggingface.co and cache.
|
| 166 |
+
modelcard = ModelCard.from_pretrained("bert-base-uncased")
|
| 167 |
+
# Model card was saved using *save_pretrained('./test/saved_model/')*
|
| 168 |
+
modelcard = ModelCard.from_pretrained("./test/saved_model/")
|
| 169 |
+
modelcard = ModelCard.from_pretrained("./test/saved_model/modelcard.json")
|
| 170 |
+
modelcard = ModelCard.from_pretrained("bert-base-uncased", output_attentions=True, foo=False)
|
| 171 |
+
```"""
|
| 172 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
| 173 |
+
proxies = kwargs.pop("proxies", None)
|
| 174 |
+
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
|
| 175 |
+
from_pipeline = kwargs.pop("_from_pipeline", None)
|
| 176 |
+
|
| 177 |
+
user_agent = {"file_type": "model_card"}
|
| 178 |
+
if from_pipeline is not None:
|
| 179 |
+
user_agent["using_pipeline"] = from_pipeline
|
| 180 |
+
|
| 181 |
+
is_local = os.path.isdir(pretrained_model_name_or_path)
|
| 182 |
+
if os.path.isfile(pretrained_model_name_or_path):
|
| 183 |
+
resolved_model_card_file = pretrained_model_name_or_path
|
| 184 |
+
is_local = True
|
| 185 |
+
else:
|
| 186 |
+
try:
|
| 187 |
+
# Load from URL or cache if already cached
|
| 188 |
+
resolved_model_card_file = cached_file(
|
| 189 |
+
pretrained_model_name_or_path,
|
| 190 |
+
filename=MODEL_CARD_NAME,
|
| 191 |
+
cache_dir=cache_dir,
|
| 192 |
+
proxies=proxies,
|
| 193 |
+
user_agent=user_agent,
|
| 194 |
+
)
|
| 195 |
+
if is_local:
|
| 196 |
+
logger.info(f"loading model card file {resolved_model_card_file}")
|
| 197 |
+
else:
|
| 198 |
+
logger.info(f"loading model card file {MODEL_CARD_NAME} from cache at {resolved_model_card_file}")
|
| 199 |
+
# Load model card
|
| 200 |
+
modelcard = cls.from_json_file(resolved_model_card_file)
|
| 201 |
+
|
| 202 |
+
except (EnvironmentError, json.JSONDecodeError):
|
| 203 |
+
# We fall back on creating an empty model card
|
| 204 |
+
modelcard = cls()
|
| 205 |
+
|
| 206 |
+
# Update model card with kwargs if needed
|
| 207 |
+
to_remove = []
|
| 208 |
+
for key, value in kwargs.items():
|
| 209 |
+
if hasattr(modelcard, key):
|
| 210 |
+
setattr(modelcard, key, value)
|
| 211 |
+
to_remove.append(key)
|
| 212 |
+
for key in to_remove:
|
| 213 |
+
kwargs.pop(key, None)
|
| 214 |
+
|
| 215 |
+
logger.info(f"Model card: {modelcard}")
|
| 216 |
+
if return_unused_kwargs:
|
| 217 |
+
return modelcard, kwargs
|
| 218 |
+
else:
|
| 219 |
+
return modelcard
|
| 220 |
+
|
| 221 |
+
@classmethod
|
| 222 |
+
def from_dict(cls, json_object):
|
| 223 |
+
"""Constructs a `ModelCard` from a Python dictionary of parameters."""
|
| 224 |
+
return cls(**json_object)
|
| 225 |
+
|
| 226 |
+
@classmethod
|
| 227 |
+
def from_json_file(cls, json_file):
|
| 228 |
+
"""Constructs a `ModelCard` from a json file of parameters."""
|
| 229 |
+
with open(json_file, "r", encoding="utf-8") as reader:
|
| 230 |
+
text = reader.read()
|
| 231 |
+
dict_obj = json.loads(text)
|
| 232 |
+
return cls(**dict_obj)
|
| 233 |
+
|
| 234 |
+
def __eq__(self, other):
|
| 235 |
+
return self.__dict__ == other.__dict__
|
| 236 |
+
|
| 237 |
+
def __repr__(self):
|
| 238 |
+
return str(self.to_json_string())
|
| 239 |
+
|
| 240 |
+
def to_dict(self):
|
| 241 |
+
"""Serializes this instance to a Python dictionary."""
|
| 242 |
+
output = copy.deepcopy(self.__dict__)
|
| 243 |
+
return output
|
| 244 |
+
|
| 245 |
+
def to_json_string(self):
|
| 246 |
+
"""Serializes this instance to a JSON string."""
|
| 247 |
+
return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
|
| 248 |
+
|
| 249 |
+
def to_json_file(self, json_file_path):
|
| 250 |
+
"""Save this instance to a json file."""
|
| 251 |
+
with open(json_file_path, "w", encoding="utf-8") as writer:
|
| 252 |
+
writer.write(self.to_json_string())
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
AUTOGENERATED_TRAINER_COMMENT = """
|
| 256 |
+
<!-- This model card has been generated automatically according to the information the Trainer had access to. You
|
| 257 |
+
should probably proofread and complete it, then remove this comment. -->
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
AUTOGENERATED_KERAS_COMMENT = """
|
| 261 |
+
<!-- This model card has been generated automatically according to the information Keras had access to. You should
|
| 262 |
+
probably proofread and complete it, then remove this comment. -->
|
| 263 |
+
"""
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
TASK_TAG_TO_NAME_MAPPING = {
|
| 267 |
+
"fill-mask": "Masked Language Modeling",
|
| 268 |
+
"image-classification": "Image Classification",
|
| 269 |
+
"image-segmentation": "Image Segmentation",
|
| 270 |
+
"multiple-choice": "Multiple Choice",
|
| 271 |
+
"object-detection": "Object Detection",
|
| 272 |
+
"question-answering": "Question Answering",
|
| 273 |
+
"summarization": "Summarization",
|
| 274 |
+
"table-question-answering": "Table Question Answering",
|
| 275 |
+
"text-classification": "Text Classification",
|
| 276 |
+
"text-generation": "Causal Language Modeling",
|
| 277 |
+
"text2text-generation": "Sequence-to-sequence Language Modeling",
|
| 278 |
+
"token-classification": "Token Classification",
|
| 279 |
+
"translation": "Translation",
|
| 280 |
+
"zero-shot-classification": "Zero Shot Classification",
|
| 281 |
+
"automatic-speech-recognition": "Automatic Speech Recognition",
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
METRIC_TAGS = [
|
| 286 |
+
"accuracy",
|
| 287 |
+
"bleu",
|
| 288 |
+
"f1",
|
| 289 |
+
"matthews_correlation",
|
| 290 |
+
"pearsonr",
|
| 291 |
+
"precision",
|
| 292 |
+
"recall",
|
| 293 |
+
"rouge",
|
| 294 |
+
"sacrebleu",
|
| 295 |
+
"spearmanr",
|
| 296 |
+
"wer",
|
| 297 |
+
]
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _listify(obj):
|
| 301 |
+
if obj is None:
|
| 302 |
+
return []
|
| 303 |
+
elif isinstance(obj, str):
|
| 304 |
+
return [obj]
|
| 305 |
+
else:
|
| 306 |
+
return obj
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _insert_values_as_list(metadata, name, values):
|
| 310 |
+
if values is None:
|
| 311 |
+
return metadata
|
| 312 |
+
if isinstance(values, str):
|
| 313 |
+
values = [values]
|
| 314 |
+
values = [v for v in values if v is not None]
|
| 315 |
+
if len(values) == 0:
|
| 316 |
+
return metadata
|
| 317 |
+
metadata[name] = values
|
| 318 |
+
return metadata
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def infer_metric_tags_from_eval_results(eval_results):
|
| 322 |
+
if eval_results is None:
|
| 323 |
+
return {}
|
| 324 |
+
result = {}
|
| 325 |
+
for key in eval_results.keys():
|
| 326 |
+
if key.lower().replace(" ", "_") in METRIC_TAGS:
|
| 327 |
+
result[key.lower().replace(" ", "_")] = key
|
| 328 |
+
elif key.lower() == "rouge1":
|
| 329 |
+
result["rouge"] = key
|
| 330 |
+
return result
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _insert_value(metadata, name, value):
|
| 334 |
+
if value is None:
|
| 335 |
+
return metadata
|
| 336 |
+
metadata[name] = value
|
| 337 |
+
return metadata
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def is_hf_dataset(dataset):
|
| 341 |
+
if not is_datasets_available():
|
| 342 |
+
return False
|
| 343 |
+
|
| 344 |
+
from datasets import Dataset, IterableDataset
|
| 345 |
+
|
| 346 |
+
return isinstance(dataset, (Dataset, IterableDataset))
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def _get_mapping_values(mapping):
|
| 350 |
+
result = []
|
| 351 |
+
for v in mapping.values():
|
| 352 |
+
if isinstance(v, (tuple, list)):
|
| 353 |
+
result += list(v)
|
| 354 |
+
else:
|
| 355 |
+
result.append(v)
|
| 356 |
+
return result
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
@dataclass
|
| 360 |
+
class TrainingSummary:
|
| 361 |
+
model_name: str
|
| 362 |
+
language: Optional[Union[str, List[str]]] = None
|
| 363 |
+
license: Optional[str] = None
|
| 364 |
+
tags: Optional[Union[str, List[str]]] = None
|
| 365 |
+
finetuned_from: Optional[str] = None
|
| 366 |
+
tasks: Optional[Union[str, List[str]]] = None
|
| 367 |
+
dataset: Optional[Union[str, List[str]]] = None
|
| 368 |
+
dataset_tags: Optional[Union[str, List[str]]] = None
|
| 369 |
+
dataset_args: Optional[Union[str, List[str]]] = None
|
| 370 |
+
dataset_metadata: Optional[Dict[str, Any]] = None
|
| 371 |
+
eval_results: Optional[Dict[str, float]] = None
|
| 372 |
+
eval_lines: Optional[List[str]] = None
|
| 373 |
+
hyperparameters: Optional[Dict[str, Any]] = None
|
| 374 |
+
source: Optional[str] = "trainer"
|
| 375 |
+
|
| 376 |
+
def __post_init__(self):
|
| 377 |
+
# Infer default license from the checkpoint used, if possible.
|
| 378 |
+
if (
|
| 379 |
+
self.license is None
|
| 380 |
+
and not is_offline_mode()
|
| 381 |
+
and self.finetuned_from is not None
|
| 382 |
+
and len(self.finetuned_from) > 0
|
| 383 |
+
):
|
| 384 |
+
try:
|
| 385 |
+
info = model_info(self.finetuned_from)
|
| 386 |
+
for tag in info.tags:
|
| 387 |
+
if tag.startswith("license:"):
|
| 388 |
+
self.license = tag[8:]
|
| 389 |
+
except (requests.exceptions.HTTPError, HFValidationError):
|
| 390 |
+
pass
|
| 391 |
+
|
| 392 |
+
def create_model_index(self, metric_mapping):
|
| 393 |
+
model_index = {"name": self.model_name}
|
| 394 |
+
|
| 395 |
+
# Dataset mapping tag -> name
|
| 396 |
+
dataset_names = _listify(self.dataset)
|
| 397 |
+
dataset_tags = _listify(self.dataset_tags)
|
| 398 |
+
dataset_args = _listify(self.dataset_args)
|
| 399 |
+
dataset_metadata = _listify(self.dataset_metadata)
|
| 400 |
+
if len(dataset_args) < len(dataset_tags):
|
| 401 |
+
dataset_args = dataset_args + [None] * (len(dataset_tags) - len(dataset_args))
|
| 402 |
+
dataset_mapping = dict(zip(dataset_tags, dataset_names))
|
| 403 |
+
dataset_arg_mapping = dict(zip(dataset_tags, dataset_args))
|
| 404 |
+
dataset_metadata_mapping = dict(zip(dataset_tags, dataset_metadata))
|
| 405 |
+
|
| 406 |
+
task_mapping = {
|
| 407 |
+
task: TASK_TAG_TO_NAME_MAPPING[task] for task in _listify(self.tasks) if task in TASK_TAG_TO_NAME_MAPPING
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
model_index["results"] = []
|
| 411 |
+
|
| 412 |
+
if len(task_mapping) == 0 and len(dataset_mapping) == 0:
|
| 413 |
+
return [model_index]
|
| 414 |
+
if len(task_mapping) == 0:
|
| 415 |
+
task_mapping = {None: None}
|
| 416 |
+
if len(dataset_mapping) == 0:
|
| 417 |
+
dataset_mapping = {None: None}
|
| 418 |
+
|
| 419 |
+
# One entry per dataset and per task
|
| 420 |
+
all_possibilities = [(task_tag, ds_tag) for task_tag in task_mapping for ds_tag in dataset_mapping]
|
| 421 |
+
for task_tag, ds_tag in all_possibilities:
|
| 422 |
+
result = {}
|
| 423 |
+
if task_tag is not None:
|
| 424 |
+
result["task"] = {"name": task_mapping[task_tag], "type": task_tag}
|
| 425 |
+
|
| 426 |
+
if ds_tag is not None:
|
| 427 |
+
metadata = dataset_metadata_mapping.get(ds_tag, {})
|
| 428 |
+
result["dataset"] = {
|
| 429 |
+
"name": dataset_mapping[ds_tag],
|
| 430 |
+
"type": ds_tag,
|
| 431 |
+
**metadata,
|
| 432 |
+
}
|
| 433 |
+
if dataset_arg_mapping[ds_tag] is not None:
|
| 434 |
+
result["dataset"]["args"] = dataset_arg_mapping[ds_tag]
|
| 435 |
+
|
| 436 |
+
if len(metric_mapping) > 0:
|
| 437 |
+
result["metrics"] = []
|
| 438 |
+
for metric_tag, metric_name in metric_mapping.items():
|
| 439 |
+
result["metrics"].append(
|
| 440 |
+
{
|
| 441 |
+
"name": metric_name,
|
| 442 |
+
"type": metric_tag,
|
| 443 |
+
"value": self.eval_results[metric_name],
|
| 444 |
+
}
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
# Remove partial results to avoid the model card being rejected.
|
| 448 |
+
if "task" in result and "dataset" in result and "metrics" in result:
|
| 449 |
+
model_index["results"].append(result)
|
| 450 |
+
else:
|
| 451 |
+
logger.info(f"Dropping the following result as it does not have all the necessary fields:\n{result}")
|
| 452 |
+
|
| 453 |
+
return [model_index]
|
| 454 |
+
|
| 455 |
+
def create_metadata(self):
|
| 456 |
+
metric_mapping = infer_metric_tags_from_eval_results(self.eval_results)
|
| 457 |
+
|
| 458 |
+
metadata = {}
|
| 459 |
+
metadata = _insert_values_as_list(metadata, "language", self.language)
|
| 460 |
+
metadata = _insert_value(metadata, "license", self.license)
|
| 461 |
+
metadata = _insert_values_as_list(metadata, "tags", self.tags)
|
| 462 |
+
metadata = _insert_values_as_list(metadata, "datasets", self.dataset_tags)
|
| 463 |
+
metadata = _insert_values_as_list(metadata, "metrics", list(metric_mapping.keys()))
|
| 464 |
+
metadata["model-index"] = self.create_model_index(metric_mapping)
|
| 465 |
+
|
| 466 |
+
return metadata
|
| 467 |
+
|
| 468 |
+
def to_model_card(self):
|
| 469 |
+
model_card = ""
|
| 470 |
+
|
| 471 |
+
metadata = yaml.dump(self.create_metadata(), sort_keys=False)
|
| 472 |
+
if len(metadata) > 0:
|
| 473 |
+
model_card = f"---\n{metadata}---\n"
|
| 474 |
+
|
| 475 |
+
# Now the model card for realsies.
|
| 476 |
+
if self.source == "trainer":
|
| 477 |
+
model_card += AUTOGENERATED_TRAINER_COMMENT
|
| 478 |
+
else:
|
| 479 |
+
model_card += AUTOGENERATED_KERAS_COMMENT
|
| 480 |
+
|
| 481 |
+
model_card += f"\n# {self.model_name}\n\n"
|
| 482 |
+
|
| 483 |
+
if self.finetuned_from is None:
|
| 484 |
+
model_card += "This model was trained from scratch on "
|
| 485 |
+
else:
|
| 486 |
+
model_card += (
|
| 487 |
+
"This model is a fine-tuned version of"
|
| 488 |
+
f" [{self.finetuned_from}](https://huggingface.co/{self.finetuned_from}) on "
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
if self.dataset is None:
|
| 492 |
+
model_card += "an unknown dataset."
|
| 493 |
+
else:
|
| 494 |
+
if isinstance(self.dataset, str):
|
| 495 |
+
model_card += f"the {self.dataset} dataset."
|
| 496 |
+
elif isinstance(self.dataset, (tuple, list)) and len(self.dataset) == 1:
|
| 497 |
+
model_card += f"the {self.dataset[0]} dataset."
|
| 498 |
+
else:
|
| 499 |
+
model_card += (
|
| 500 |
+
", ".join([f"the {ds}" for ds in self.dataset[:-1]]) + f" and the {self.dataset[-1]} datasets."
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
if self.eval_results is not None:
|
| 504 |
+
model_card += "\nIt achieves the following results on the evaluation set:\n"
|
| 505 |
+
model_card += "\n".join([f"- {name}: {_maybe_round(value)}" for name, value in self.eval_results.items()])
|
| 506 |
+
model_card += "\n"
|
| 507 |
+
|
| 508 |
+
model_card += "\n## Model description\n\nMore information needed\n"
|
| 509 |
+
model_card += "\n## Intended uses & limitations\n\nMore information needed\n"
|
| 510 |
+
model_card += "\n## Training and evaluation data\n\nMore information needed\n"
|
| 511 |
+
|
| 512 |
+
model_card += "\n## Training procedure\n"
|
| 513 |
+
model_card += "\n### Training hyperparameters\n"
|
| 514 |
+
if self.hyperparameters is not None:
|
| 515 |
+
model_card += "\nThe following hyperparameters were used during training:\n"
|
| 516 |
+
model_card += "\n".join([f"- {name}: {value}" for name, value in self.hyperparameters.items()])
|
| 517 |
+
model_card += "\n"
|
| 518 |
+
else:
|
| 519 |
+
model_card += "\nMore information needed\n"
|
| 520 |
+
|
| 521 |
+
if self.eval_lines is not None:
|
| 522 |
+
model_card += "\n### Training results\n\n"
|
| 523 |
+
model_card += make_markdown_table(self.eval_lines)
|
| 524 |
+
model_card += "\n"
|
| 525 |
+
|
| 526 |
+
model_card += "\n### Framework versions\n\n"
|
| 527 |
+
model_card += f"- Transformers {__version__}\n"
|
| 528 |
+
|
| 529 |
+
if self.source == "trainer" and is_torch_available():
|
| 530 |
+
import torch
|
| 531 |
+
|
| 532 |
+
model_card += f"- Pytorch {torch.__version__}\n"
|
| 533 |
+
elif self.source == "keras" and is_tf_available():
|
| 534 |
+
import tensorflow as tf
|
| 535 |
+
|
| 536 |
+
model_card += f"- TensorFlow {tf.__version__}\n"
|
| 537 |
+
if is_datasets_available():
|
| 538 |
+
import datasets
|
| 539 |
+
|
| 540 |
+
model_card += f"- Datasets {datasets.__version__}\n"
|
| 541 |
+
if is_tokenizers_available():
|
| 542 |
+
import tokenizers
|
| 543 |
+
|
| 544 |
+
model_card += f"- Tokenizers {tokenizers.__version__}\n"
|
| 545 |
+
|
| 546 |
+
return model_card
|
| 547 |
+
|
| 548 |
+
@classmethod
|
| 549 |
+
def from_trainer(
|
| 550 |
+
cls,
|
| 551 |
+
trainer,
|
| 552 |
+
language=None,
|
| 553 |
+
license=None,
|
| 554 |
+
tags=None,
|
| 555 |
+
model_name=None,
|
| 556 |
+
finetuned_from=None,
|
| 557 |
+
tasks=None,
|
| 558 |
+
dataset_tags=None,
|
| 559 |
+
dataset_metadata=None,
|
| 560 |
+
dataset=None,
|
| 561 |
+
dataset_args=None,
|
| 562 |
+
):
|
| 563 |
+
# Infer default from dataset
|
| 564 |
+
one_dataset = trainer.eval_dataset if trainer.eval_dataset is not None else trainer.train_dataset
|
| 565 |
+
if is_hf_dataset(one_dataset) and (dataset_tags is None or dataset_args is None or dataset_metadata is None):
|
| 566 |
+
default_tag = one_dataset.builder_name
|
| 567 |
+
# Those are not real datasets from the Hub so we exclude them.
|
| 568 |
+
if default_tag not in ["csv", "json", "pandas", "parquet", "text"]:
|
| 569 |
+
if dataset_metadata is None:
|
| 570 |
+
dataset_metadata = [{"config": one_dataset.config_name, "split": str(one_dataset.split)}]
|
| 571 |
+
if dataset_tags is None:
|
| 572 |
+
dataset_tags = [default_tag]
|
| 573 |
+
if dataset_args is None:
|
| 574 |
+
dataset_args = [one_dataset.config_name]
|
| 575 |
+
|
| 576 |
+
if dataset is None and dataset_tags is not None:
|
| 577 |
+
dataset = dataset_tags
|
| 578 |
+
|
| 579 |
+
# Infer default finetuned_from
|
| 580 |
+
if (
|
| 581 |
+
finetuned_from is None
|
| 582 |
+
and hasattr(trainer.model.config, "_name_or_path")
|
| 583 |
+
and not os.path.isdir(trainer.model.config._name_or_path)
|
| 584 |
+
):
|
| 585 |
+
finetuned_from = trainer.model.config._name_or_path
|
| 586 |
+
|
| 587 |
+
# Infer default task tag:
|
| 588 |
+
if tasks is None:
|
| 589 |
+
model_class_name = trainer.model.__class__.__name__
|
| 590 |
+
for task, mapping in TASK_MAPPING.items():
|
| 591 |
+
if model_class_name in _get_mapping_values(mapping):
|
| 592 |
+
tasks = task
|
| 593 |
+
|
| 594 |
+
if model_name is None:
|
| 595 |
+
model_name = Path(trainer.args.output_dir).name
|
| 596 |
+
if len(model_name) == 0:
|
| 597 |
+
model_name = finetuned_from
|
| 598 |
+
|
| 599 |
+
# Add `generated_from_trainer` to the tags
|
| 600 |
+
if tags is None:
|
| 601 |
+
tags = ["generated_from_trainer"]
|
| 602 |
+
elif isinstance(tags, str) and tags != "generated_from_trainer":
|
| 603 |
+
tags = [tags, "generated_from_trainer"]
|
| 604 |
+
elif "generated_from_trainer" not in tags:
|
| 605 |
+
tags.append("generated_from_trainer")
|
| 606 |
+
|
| 607 |
+
_, eval_lines, eval_results = parse_log_history(trainer.state.log_history)
|
| 608 |
+
hyperparameters = extract_hyperparameters_from_trainer(trainer)
|
| 609 |
+
|
| 610 |
+
return cls(
|
| 611 |
+
language=language,
|
| 612 |
+
license=license,
|
| 613 |
+
tags=tags,
|
| 614 |
+
model_name=model_name,
|
| 615 |
+
finetuned_from=finetuned_from,
|
| 616 |
+
tasks=tasks,
|
| 617 |
+
dataset=dataset,
|
| 618 |
+
dataset_tags=dataset_tags,
|
| 619 |
+
dataset_args=dataset_args,
|
| 620 |
+
dataset_metadata=dataset_metadata,
|
| 621 |
+
eval_results=eval_results,
|
| 622 |
+
eval_lines=eval_lines,
|
| 623 |
+
hyperparameters=hyperparameters,
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
@classmethod
|
| 627 |
+
def from_keras(
|
| 628 |
+
cls,
|
| 629 |
+
model,
|
| 630 |
+
model_name,
|
| 631 |
+
keras_history=None,
|
| 632 |
+
language=None,
|
| 633 |
+
license=None,
|
| 634 |
+
tags=None,
|
| 635 |
+
finetuned_from=None,
|
| 636 |
+
tasks=None,
|
| 637 |
+
dataset_tags=None,
|
| 638 |
+
dataset=None,
|
| 639 |
+
dataset_args=None,
|
| 640 |
+
):
|
| 641 |
+
# Infer default from dataset
|
| 642 |
+
if dataset is not None:
|
| 643 |
+
if is_hf_dataset(dataset) and (dataset_tags is None or dataset_args is None):
|
| 644 |
+
default_tag = dataset.builder_name
|
| 645 |
+
# Those are not real datasets from the Hub so we exclude them.
|
| 646 |
+
if default_tag not in ["csv", "json", "pandas", "parquet", "text"]:
|
| 647 |
+
if dataset_tags is None:
|
| 648 |
+
dataset_tags = [default_tag]
|
| 649 |
+
if dataset_args is None:
|
| 650 |
+
dataset_args = [dataset.config_name]
|
| 651 |
+
|
| 652 |
+
if dataset is None and dataset_tags is not None:
|
| 653 |
+
dataset = dataset_tags
|
| 654 |
+
|
| 655 |
+
# Infer default finetuned_from
|
| 656 |
+
if (
|
| 657 |
+
finetuned_from is None
|
| 658 |
+
and hasattr(model.config, "_name_or_path")
|
| 659 |
+
and not os.path.isdir(model.config._name_or_path)
|
| 660 |
+
):
|
| 661 |
+
finetuned_from = model.config._name_or_path
|
| 662 |
+
|
| 663 |
+
# Infer default task tag:
|
| 664 |
+
if tasks is None:
|
| 665 |
+
model_class_name = model.__class__.__name__
|
| 666 |
+
for task, mapping in TASK_MAPPING.items():
|
| 667 |
+
if model_class_name in _get_mapping_values(mapping):
|
| 668 |
+
tasks = task
|
| 669 |
+
|
| 670 |
+
# Add `generated_from_keras_callback` to the tags
|
| 671 |
+
if tags is None:
|
| 672 |
+
tags = ["generated_from_keras_callback"]
|
| 673 |
+
elif isinstance(tags, str) and tags != "generated_from_keras_callback":
|
| 674 |
+
tags = [tags, "generated_from_keras_callback"]
|
| 675 |
+
elif "generated_from_keras_callback" not in tags:
|
| 676 |
+
tags.append("generated_from_keras_callback")
|
| 677 |
+
|
| 678 |
+
if keras_history is not None:
|
| 679 |
+
_, eval_lines, eval_results = parse_keras_history(keras_history)
|
| 680 |
+
else:
|
| 681 |
+
eval_lines = []
|
| 682 |
+
eval_results = {}
|
| 683 |
+
hyperparameters = extract_hyperparameters_from_keras(model)
|
| 684 |
+
|
| 685 |
+
return cls(
|
| 686 |
+
language=language,
|
| 687 |
+
license=license,
|
| 688 |
+
tags=tags,
|
| 689 |
+
model_name=model_name,
|
| 690 |
+
finetuned_from=finetuned_from,
|
| 691 |
+
tasks=tasks,
|
| 692 |
+
dataset_tags=dataset_tags,
|
| 693 |
+
dataset=dataset,
|
| 694 |
+
dataset_args=dataset_args,
|
| 695 |
+
eval_results=eval_results,
|
| 696 |
+
eval_lines=eval_lines,
|
| 697 |
+
hyperparameters=hyperparameters,
|
| 698 |
+
source="keras",
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
def parse_keras_history(logs):
|
| 703 |
+
"""
|
| 704 |
+
Parse the `logs` of either a `tf.keras.History` object returned by `model.fit()` or an accumulated logs `dict`
|
| 705 |
+
passed to the `PushToHubCallback`. Returns lines and logs compatible with those returned by `parse_log_history`.
|
| 706 |
+
"""
|
| 707 |
+
if hasattr(logs, "history"):
|
| 708 |
+
# This looks like a `History` object
|
| 709 |
+
if not hasattr(logs, "epoch"):
|
| 710 |
+
# This history looks empty, return empty results
|
| 711 |
+
return None, [], {}
|
| 712 |
+
logs.history["epoch"] = logs.epoch
|
| 713 |
+
logs = logs.history
|
| 714 |
+
else:
|
| 715 |
+
# Training logs is a list of dicts, let's invert it to a dict of lists to match a History object
|
| 716 |
+
logs = {log_key: [single_dict[log_key] for single_dict in logs] for log_key in logs[0]}
|
| 717 |
+
|
| 718 |
+
lines = []
|
| 719 |
+
for i in range(len(logs["epoch"])):
|
| 720 |
+
epoch_dict = {log_key: log_value_list[i] for log_key, log_value_list in logs.items()}
|
| 721 |
+
values = {}
|
| 722 |
+
for k, v in epoch_dict.items():
|
| 723 |
+
if k.startswith("val_"):
|
| 724 |
+
k = "validation_" + k[4:]
|
| 725 |
+
elif k != "epoch":
|
| 726 |
+
k = "train_" + k
|
| 727 |
+
splits = k.split("_")
|
| 728 |
+
name = " ".join([part.capitalize() for part in splits])
|
| 729 |
+
values[name] = v
|
| 730 |
+
lines.append(values)
|
| 731 |
+
|
| 732 |
+
eval_results = lines[-1]
|
| 733 |
+
|
| 734 |
+
return logs, lines, eval_results
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
def parse_log_history(log_history):
|
| 738 |
+
"""
|
| 739 |
+
Parse the `log_history` of a Trainer to get the intermediate and final evaluation results.
|
| 740 |
+
"""
|
| 741 |
+
idx = 0
|
| 742 |
+
while idx < len(log_history) and "train_runtime" not in log_history[idx]:
|
| 743 |
+
idx += 1
|
| 744 |
+
|
| 745 |
+
# If there are no training logs
|
| 746 |
+
if idx == len(log_history):
|
| 747 |
+
idx -= 1
|
| 748 |
+
while idx >= 0 and "eval_loss" not in log_history[idx]:
|
| 749 |
+
idx -= 1
|
| 750 |
+
|
| 751 |
+
if idx >= 0:
|
| 752 |
+
return None, None, log_history[idx]
|
| 753 |
+
else:
|
| 754 |
+
return None, None, None
|
| 755 |
+
|
| 756 |
+
# From now one we can assume we have training logs:
|
| 757 |
+
train_log = log_history[idx]
|
| 758 |
+
lines = []
|
| 759 |
+
training_loss = "No log"
|
| 760 |
+
for i in range(idx):
|
| 761 |
+
if "loss" in log_history[i]:
|
| 762 |
+
training_loss = log_history[i]["loss"]
|
| 763 |
+
if "eval_loss" in log_history[i]:
|
| 764 |
+
metrics = log_history[i].copy()
|
| 765 |
+
_ = metrics.pop("total_flos", None)
|
| 766 |
+
epoch = metrics.pop("epoch", None)
|
| 767 |
+
step = metrics.pop("step", None)
|
| 768 |
+
_ = metrics.pop("eval_runtime", None)
|
| 769 |
+
_ = metrics.pop("eval_samples_per_second", None)
|
| 770 |
+
_ = metrics.pop("eval_steps_per_second", None)
|
| 771 |
+
_ = metrics.pop("eval_jit_compilation_time", None)
|
| 772 |
+
values = {"Training Loss": training_loss, "Epoch": epoch, "Step": step}
|
| 773 |
+
for k, v in metrics.items():
|
| 774 |
+
if k == "eval_loss":
|
| 775 |
+
values["Validation Loss"] = v
|
| 776 |
+
else:
|
| 777 |
+
splits = k.split("_")
|
| 778 |
+
name = " ".join([part.capitalize() for part in splits[1:]])
|
| 779 |
+
values[name] = v
|
| 780 |
+
lines.append(values)
|
| 781 |
+
|
| 782 |
+
idx = len(log_history) - 1
|
| 783 |
+
while idx >= 0 and "eval_loss" not in log_history[idx]:
|
| 784 |
+
idx -= 1
|
| 785 |
+
|
| 786 |
+
if idx > 0:
|
| 787 |
+
eval_results = {}
|
| 788 |
+
for key, value in log_history[idx].items():
|
| 789 |
+
if key.startswith("eval_"):
|
| 790 |
+
key = key[5:]
|
| 791 |
+
if key not in ["runtime", "samples_per_second", "steps_per_second", "epoch", "step"]:
|
| 792 |
+
camel_cased_key = " ".join([part.capitalize() for part in key.split("_")])
|
| 793 |
+
eval_results[camel_cased_key] = value
|
| 794 |
+
return train_log, lines, eval_results
|
| 795 |
+
else:
|
| 796 |
+
return train_log, lines, None
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
def extract_hyperparameters_from_keras(model):
|
| 800 |
+
import tensorflow as tf
|
| 801 |
+
|
| 802 |
+
hyperparameters = {}
|
| 803 |
+
if hasattr(model, "optimizer") and model.optimizer is not None:
|
| 804 |
+
hyperparameters["optimizer"] = model.optimizer.get_config()
|
| 805 |
+
else:
|
| 806 |
+
hyperparameters["optimizer"] = None
|
| 807 |
+
hyperparameters["training_precision"] = tf.keras.mixed_precision.global_policy().name
|
| 808 |
+
|
| 809 |
+
return hyperparameters
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
def _maybe_round(v, decimals=4):
|
| 813 |
+
if isinstance(v, float) and len(str(v).split(".")) > 1 and len(str(v).split(".")[1]) > decimals:
|
| 814 |
+
return f"{v:.{decimals}f}"
|
| 815 |
+
return str(v)
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def _regular_table_line(values, col_widths):
|
| 819 |
+
values_with_space = [f"| {v}" + " " * (w - len(v) + 1) for v, w in zip(values, col_widths)]
|
| 820 |
+
return "".join(values_with_space) + "|\n"
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
def _second_table_line(col_widths):
|
| 824 |
+
values = ["|:" + "-" * w + ":" for w in col_widths]
|
| 825 |
+
return "".join(values) + "|\n"
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
def make_markdown_table(lines):
|
| 829 |
+
"""
|
| 830 |
+
Create a nice Markdown table from the results in `lines`.
|
| 831 |
+
"""
|
| 832 |
+
if lines is None or len(lines) == 0:
|
| 833 |
+
return ""
|
| 834 |
+
col_widths = {key: len(str(key)) for key in lines[0].keys()}
|
| 835 |
+
for line in lines:
|
| 836 |
+
for key, value in line.items():
|
| 837 |
+
if col_widths[key] < len(_maybe_round(value)):
|
| 838 |
+
col_widths[key] = len(_maybe_round(value))
|
| 839 |
+
|
| 840 |
+
table = _regular_table_line(list(lines[0].keys()), list(col_widths.values()))
|
| 841 |
+
table += _second_table_line(list(col_widths.values()))
|
| 842 |
+
for line in lines:
|
| 843 |
+
table += _regular_table_line([_maybe_round(v) for v in line.values()], list(col_widths.values()))
|
| 844 |
+
return table
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
_TRAINING_ARGS_KEYS = [
|
| 848 |
+
"learning_rate",
|
| 849 |
+
"train_batch_size",
|
| 850 |
+
"eval_batch_size",
|
| 851 |
+
"seed",
|
| 852 |
+
]
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def extract_hyperparameters_from_trainer(trainer):
|
| 856 |
+
hyperparameters = {k: getattr(trainer.args, k) for k in _TRAINING_ARGS_KEYS}
|
| 857 |
+
|
| 858 |
+
if trainer.args.parallel_mode not in [ParallelMode.NOT_PARALLEL, ParallelMode.NOT_DISTRIBUTED]:
|
| 859 |
+
hyperparameters["distributed_type"] = (
|
| 860 |
+
"multi-GPU" if trainer.args.parallel_mode == ParallelMode.DISTRIBUTED else trainer.args.parallel_mode.value
|
| 861 |
+
)
|
| 862 |
+
if trainer.args.world_size > 1:
|
| 863 |
+
hyperparameters["num_devices"] = trainer.args.world_size
|
| 864 |
+
if trainer.args.gradient_accumulation_steps > 1:
|
| 865 |
+
hyperparameters["gradient_accumulation_steps"] = trainer.args.gradient_accumulation_steps
|
| 866 |
+
|
| 867 |
+
total_train_batch_size = (
|
| 868 |
+
trainer.args.train_batch_size * trainer.args.world_size * trainer.args.gradient_accumulation_steps
|
| 869 |
+
)
|
| 870 |
+
if total_train_batch_size != hyperparameters["train_batch_size"]:
|
| 871 |
+
hyperparameters["total_train_batch_size"] = total_train_batch_size
|
| 872 |
+
total_eval_batch_size = trainer.args.eval_batch_size * trainer.args.world_size
|
| 873 |
+
if total_eval_batch_size != hyperparameters["eval_batch_size"]:
|
| 874 |
+
hyperparameters["total_eval_batch_size"] = total_eval_batch_size
|
| 875 |
+
|
| 876 |
+
if trainer.args.adafactor:
|
| 877 |
+
hyperparameters["optimizer"] = "Adafactor"
|
| 878 |
+
else:
|
| 879 |
+
hyperparameters["optimizer"] = (
|
| 880 |
+
f"Adam with betas=({trainer.args.adam_beta1},{trainer.args.adam_beta2}) and"
|
| 881 |
+
f" epsilon={trainer.args.adam_epsilon}"
|
| 882 |
+
)
|
| 883 |
+
|
| 884 |
+
hyperparameters["lr_scheduler_type"] = trainer.args.lr_scheduler_type.value
|
| 885 |
+
if trainer.args.warmup_ratio != 0.0:
|
| 886 |
+
hyperparameters["lr_scheduler_warmup_ratio"] = trainer.args.warmup_ratio
|
| 887 |
+
if trainer.args.warmup_steps != 0.0:
|
| 888 |
+
hyperparameters["lr_scheduler_warmup_steps"] = trainer.args.warmup_steps
|
| 889 |
+
if trainer.args.max_steps != -1:
|
| 890 |
+
hyperparameters["training_steps"] = trainer.args.max_steps
|
| 891 |
+
else:
|
| 892 |
+
hyperparameters["num_epochs"] = trainer.args.num_train_epochs
|
| 893 |
+
|
| 894 |
+
if trainer.args.fp16:
|
| 895 |
+
if trainer.use_cuda_amp:
|
| 896 |
+
hyperparameters["mixed_precision_training"] = "Native AMP"
|
| 897 |
+
elif trainer.use_apex:
|
| 898 |
+
hyperparameters["mixed_precision_training"] = f"Apex, opt level {trainer.args.fp16_opt_level}"
|
| 899 |
+
|
| 900 |
+
if trainer.args.label_smoothing_factor != 0.0:
|
| 901 |
+
hyperparameters["label_smoothing_factor"] = trainer.args.label_smoothing_factor
|
| 902 |
+
|
| 903 |
+
return hyperparameters
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/modeling_flax_pytorch_utils.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" PyTorch - Flax general utilities."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
from pickle import UnpicklingError
|
| 20 |
+
from typing import Dict, Tuple
|
| 21 |
+
|
| 22 |
+
import jax
|
| 23 |
+
import jax.numpy as jnp
|
| 24 |
+
import numpy as np
|
| 25 |
+
from flax.serialization import from_bytes
|
| 26 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 27 |
+
|
| 28 |
+
import transformers
|
| 29 |
+
|
| 30 |
+
from .utils import logging
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
#####################
|
| 37 |
+
# PyTorch => Flax #
|
| 38 |
+
#####################
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def load_pytorch_checkpoint_in_flax_state_dict(
|
| 42 |
+
flax_model, pytorch_checkpoint_path, is_sharded, allow_missing_keys=False
|
| 43 |
+
):
|
| 44 |
+
"""Load pytorch checkpoints in a flax model"""
|
| 45 |
+
try:
|
| 46 |
+
import torch # noqa: F401
|
| 47 |
+
except ImportError:
|
| 48 |
+
logger.error(
|
| 49 |
+
"Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see"
|
| 50 |
+
" https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation"
|
| 51 |
+
" instructions."
|
| 52 |
+
)
|
| 53 |
+
raise
|
| 54 |
+
|
| 55 |
+
if not is_sharded:
|
| 56 |
+
pt_path = os.path.abspath(pytorch_checkpoint_path)
|
| 57 |
+
logger.info(f"Loading PyTorch weights from {pt_path}")
|
| 58 |
+
|
| 59 |
+
pt_state_dict = torch.load(pt_path, map_location="cpu")
|
| 60 |
+
logger.info(f"PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values()):,} parameters.")
|
| 61 |
+
|
| 62 |
+
flax_state_dict = convert_pytorch_state_dict_to_flax(pt_state_dict, flax_model)
|
| 63 |
+
else:
|
| 64 |
+
# model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files
|
| 65 |
+
flax_state_dict = convert_pytorch_sharded_state_dict_to_flax(pytorch_checkpoint_path, flax_model)
|
| 66 |
+
return flax_state_dict
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def rename_key_and_reshape_tensor(
|
| 70 |
+
pt_tuple_key: Tuple[str],
|
| 71 |
+
pt_tensor: np.ndarray,
|
| 72 |
+
random_flax_state_dict: Dict[str, jnp.ndarray],
|
| 73 |
+
model_prefix: str,
|
| 74 |
+
) -> (Tuple[str], np.ndarray):
|
| 75 |
+
"""Rename PT weight names to corresponding Flax weight names and reshape tensor if necessary"""
|
| 76 |
+
|
| 77 |
+
def is_key_or_prefix_key_in_dict(key: Tuple[str]) -> bool:
|
| 78 |
+
"""Checks if `key` of `(prefix,) + key` is in random_flax_state_dict"""
|
| 79 |
+
return len(set(random_flax_state_dict) & {key, (model_prefix,) + key}) > 0
|
| 80 |
+
|
| 81 |
+
# layer norm
|
| 82 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
|
| 83 |
+
if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(renamed_pt_tuple_key):
|
| 84 |
+
return renamed_pt_tuple_key, pt_tensor
|
| 85 |
+
|
| 86 |
+
# batch norm layer mean
|
| 87 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("mean",)
|
| 88 |
+
if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(pt_tuple_key):
|
| 89 |
+
return renamed_pt_tuple_key, pt_tensor
|
| 90 |
+
|
| 91 |
+
# batch norm layer var
|
| 92 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("var",)
|
| 93 |
+
if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(pt_tuple_key):
|
| 94 |
+
return renamed_pt_tuple_key, pt_tensor
|
| 95 |
+
|
| 96 |
+
# embedding
|
| 97 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("embedding",)
|
| 98 |
+
if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(renamed_pt_tuple_key):
|
| 99 |
+
return renamed_pt_tuple_key, pt_tensor
|
| 100 |
+
|
| 101 |
+
# conv layer
|
| 102 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("kernel",)
|
| 103 |
+
if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(pt_tuple_key):
|
| 104 |
+
pt_tensor = pt_tensor.transpose(2, 3, 1, 0)
|
| 105 |
+
return renamed_pt_tuple_key, pt_tensor
|
| 106 |
+
|
| 107 |
+
# linear layer
|
| 108 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("kernel",)
|
| 109 |
+
if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(pt_tuple_key):
|
| 110 |
+
pt_tensor = pt_tensor.T
|
| 111 |
+
return renamed_pt_tuple_key, pt_tensor
|
| 112 |
+
|
| 113 |
+
# old PyTorch layer norm weight
|
| 114 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("weight",)
|
| 115 |
+
if pt_tuple_key[-1] == "gamma":
|
| 116 |
+
return renamed_pt_tuple_key, pt_tensor
|
| 117 |
+
|
| 118 |
+
# old PyTorch layer norm bias
|
| 119 |
+
renamed_pt_tuple_key = pt_tuple_key[:-1] + ("bias",)
|
| 120 |
+
if pt_tuple_key[-1] == "beta":
|
| 121 |
+
return renamed_pt_tuple_key, pt_tensor
|
| 122 |
+
|
| 123 |
+
return pt_tuple_key, pt_tensor
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def convert_pytorch_state_dict_to_flax(pt_state_dict, flax_model):
|
| 127 |
+
# convert pytorch tensor to numpy
|
| 128 |
+
pt_state_dict = {k: v.numpy() for k, v in pt_state_dict.items()}
|
| 129 |
+
|
| 130 |
+
model_prefix = flax_model.base_model_prefix
|
| 131 |
+
|
| 132 |
+
# use params dict if the model contains batch norm layers
|
| 133 |
+
if "params" in flax_model.params:
|
| 134 |
+
flax_model_params = flax_model.params["params"]
|
| 135 |
+
else:
|
| 136 |
+
flax_model_params = flax_model.params
|
| 137 |
+
random_flax_state_dict = flatten_dict(flax_model_params)
|
| 138 |
+
|
| 139 |
+
# add batch_stats keys,values to dict
|
| 140 |
+
if "batch_stats" in flax_model.params:
|
| 141 |
+
flax_batch_stats = flatten_dict(flax_model.params["batch_stats"])
|
| 142 |
+
random_flax_state_dict.update(flax_batch_stats)
|
| 143 |
+
|
| 144 |
+
flax_state_dict = {}
|
| 145 |
+
|
| 146 |
+
load_model_with_head_into_base_model = (model_prefix not in flax_model_params) and (
|
| 147 |
+
model_prefix in {k.split(".")[0] for k in pt_state_dict.keys()}
|
| 148 |
+
)
|
| 149 |
+
load_base_model_into_model_with_head = (model_prefix in flax_model_params) and (
|
| 150 |
+
model_prefix not in {k.split(".")[0] for k in pt_state_dict.keys()}
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Need to change some parameters name to match Flax names
|
| 154 |
+
for pt_key, pt_tensor in pt_state_dict.items():
|
| 155 |
+
pt_tuple_key = tuple(pt_key.split("."))
|
| 156 |
+
|
| 157 |
+
# remove base model prefix if necessary
|
| 158 |
+
has_base_model_prefix = pt_tuple_key[0] == model_prefix
|
| 159 |
+
if load_model_with_head_into_base_model and has_base_model_prefix:
|
| 160 |
+
pt_tuple_key = pt_tuple_key[1:]
|
| 161 |
+
|
| 162 |
+
# Correctly rename weight parameters
|
| 163 |
+
flax_key, flax_tensor = rename_key_and_reshape_tensor(
|
| 164 |
+
pt_tuple_key, pt_tensor, random_flax_state_dict, model_prefix
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# add model prefix if necessary
|
| 168 |
+
require_base_model_prefix = (model_prefix,) + flax_key in random_flax_state_dict
|
| 169 |
+
if load_base_model_into_model_with_head and require_base_model_prefix:
|
| 170 |
+
flax_key = (model_prefix,) + flax_key
|
| 171 |
+
|
| 172 |
+
if flax_key in random_flax_state_dict:
|
| 173 |
+
if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
|
| 174 |
+
raise ValueError(
|
| 175 |
+
f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape "
|
| 176 |
+
f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# add batch stats if the model contains batchnorm layers
|
| 180 |
+
if "batch_stats" in flax_model.params:
|
| 181 |
+
if "mean" in flax_key[-1] or "var" in flax_key[-1]:
|
| 182 |
+
flax_state_dict[("batch_stats",) + flax_key] = jnp.asarray(flax_tensor)
|
| 183 |
+
continue
|
| 184 |
+
# remove num_batches_tracked key
|
| 185 |
+
if "num_batches_tracked" in flax_key[-1]:
|
| 186 |
+
flax_state_dict.pop(flax_key, None)
|
| 187 |
+
continue
|
| 188 |
+
|
| 189 |
+
# also add unexpected weight so that warning is thrown
|
| 190 |
+
flax_state_dict[("params",) + flax_key] = jnp.asarray(flax_tensor)
|
| 191 |
+
|
| 192 |
+
else:
|
| 193 |
+
# also add unexpected weight so that warning is thrown
|
| 194 |
+
flax_state_dict[flax_key] = jnp.asarray(flax_tensor)
|
| 195 |
+
|
| 196 |
+
return unflatten_dict(flax_state_dict)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
############################
|
| 200 |
+
# Sharded Pytorch => Flax #
|
| 201 |
+
############################
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def convert_pytorch_sharded_state_dict_to_flax(shard_filenames, flax_model):
|
| 205 |
+
import torch
|
| 206 |
+
|
| 207 |
+
# Load the index
|
| 208 |
+
flax_state_dict = {}
|
| 209 |
+
for shard_file in shard_filenames:
|
| 210 |
+
# load using msgpack utils
|
| 211 |
+
pt_state_dict = torch.load(shard_file)
|
| 212 |
+
pt_state_dict = {k: v.numpy() for k, v in pt_state_dict.items()}
|
| 213 |
+
|
| 214 |
+
model_prefix = flax_model.base_model_prefix
|
| 215 |
+
|
| 216 |
+
# use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict
|
| 217 |
+
if "batch_stats" in flax_model.params:
|
| 218 |
+
flax_model_params = flax_model.params["params"]
|
| 219 |
+
|
| 220 |
+
random_flax_state_dict = flatten_dict(flax_model_params)
|
| 221 |
+
random_flax_state_dict.update(flatten_dict(flax_model.params["batch_stats"]))
|
| 222 |
+
else:
|
| 223 |
+
flax_model_params = flax_model.params
|
| 224 |
+
random_flax_state_dict = flatten_dict(flax_model_params)
|
| 225 |
+
|
| 226 |
+
load_model_with_head_into_base_model = (model_prefix not in flax_model_params) and (
|
| 227 |
+
model_prefix in {k.split(".")[0] for k in pt_state_dict.keys()}
|
| 228 |
+
)
|
| 229 |
+
load_base_model_into_model_with_head = (model_prefix in flax_model_params) and (
|
| 230 |
+
model_prefix not in {k.split(".")[0] for k in pt_state_dict.keys()}
|
| 231 |
+
)
|
| 232 |
+
# Need to change some parameters name to match Flax names
|
| 233 |
+
for pt_key, pt_tensor in pt_state_dict.items():
|
| 234 |
+
pt_tuple_key = tuple(pt_key.split("."))
|
| 235 |
+
|
| 236 |
+
# remove base model prefix if necessary
|
| 237 |
+
has_base_model_prefix = pt_tuple_key[0] == model_prefix
|
| 238 |
+
if load_model_with_head_into_base_model and has_base_model_prefix:
|
| 239 |
+
pt_tuple_key = pt_tuple_key[1:]
|
| 240 |
+
|
| 241 |
+
# Correctly rename weight parameters
|
| 242 |
+
flax_key, flax_tensor = rename_key_and_reshape_tensor(
|
| 243 |
+
pt_tuple_key, pt_tensor, random_flax_state_dict, model_prefix
|
| 244 |
+
)
|
| 245 |
+
# add model prefix if necessary
|
| 246 |
+
require_base_model_prefix = (model_prefix,) + flax_key in random_flax_state_dict
|
| 247 |
+
if load_base_model_into_model_with_head and require_base_model_prefix:
|
| 248 |
+
flax_key = (model_prefix,) + flax_key
|
| 249 |
+
|
| 250 |
+
if flax_key in random_flax_state_dict:
|
| 251 |
+
if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
|
| 252 |
+
raise ValueError(
|
| 253 |
+
f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape "
|
| 254 |
+
f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
# add batch stats if the model contains batchnorm layers
|
| 258 |
+
if "batch_stats" in flax_model.params:
|
| 259 |
+
if "mean" in flax_key[-1]:
|
| 260 |
+
flax_state_dict[("batch_stats",) + flax_key] = jnp.asarray(flax_tensor)
|
| 261 |
+
continue
|
| 262 |
+
if "var" in flax_key[-1]:
|
| 263 |
+
flax_state_dict[("batch_stats",) + flax_key] = jnp.asarray(flax_tensor)
|
| 264 |
+
continue
|
| 265 |
+
# remove num_batches_tracked key
|
| 266 |
+
if "num_batches_tracked" in flax_key[-1]:
|
| 267 |
+
flax_state_dict.pop(flax_key, None)
|
| 268 |
+
continue
|
| 269 |
+
|
| 270 |
+
# also add unexpected weight so that warning is thrown
|
| 271 |
+
flax_state_dict[("params",) + flax_key] = jnp.asarray(flax_tensor)
|
| 272 |
+
|
| 273 |
+
else:
|
| 274 |
+
# also add unexpected weight so that warning is thrown
|
| 275 |
+
flax_state_dict[flax_key] = jnp.asarray(flax_tensor)
|
| 276 |
+
return unflatten_dict(flax_state_dict)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
#####################
|
| 280 |
+
# Flax => PyTorch #
|
| 281 |
+
#####################
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def load_flax_checkpoint_in_pytorch_model(model, flax_checkpoint_path):
|
| 285 |
+
"""Load flax checkpoints in a PyTorch model"""
|
| 286 |
+
flax_checkpoint_path = os.path.abspath(flax_checkpoint_path)
|
| 287 |
+
logger.info(f"Loading Flax weights from {flax_checkpoint_path}")
|
| 288 |
+
|
| 289 |
+
# import correct flax class
|
| 290 |
+
flax_cls = getattr(transformers, "Flax" + model.__class__.__name__)
|
| 291 |
+
|
| 292 |
+
# load flax weight dict
|
| 293 |
+
with open(flax_checkpoint_path, "rb") as state_f:
|
| 294 |
+
try:
|
| 295 |
+
flax_state_dict = from_bytes(flax_cls, state_f.read())
|
| 296 |
+
except UnpicklingError:
|
| 297 |
+
raise EnvironmentError(f"Unable to convert {flax_checkpoint_path} to Flax deserializable object. ")
|
| 298 |
+
|
| 299 |
+
return load_flax_weights_in_pytorch_model(model, flax_state_dict)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def load_flax_weights_in_pytorch_model(pt_model, flax_state):
|
| 303 |
+
"""Load flax checkpoints in a PyTorch model"""
|
| 304 |
+
|
| 305 |
+
try:
|
| 306 |
+
import torch # noqa: F401
|
| 307 |
+
except ImportError:
|
| 308 |
+
logger.error(
|
| 309 |
+
"Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see"
|
| 310 |
+
" https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation"
|
| 311 |
+
" instructions."
|
| 312 |
+
)
|
| 313 |
+
raise
|
| 314 |
+
|
| 315 |
+
# check if we have bf16 weights
|
| 316 |
+
is_type_bf16 = flatten_dict(jax.tree_util.tree_map(lambda x: x.dtype == jnp.bfloat16, flax_state)).values()
|
| 317 |
+
if any(is_type_bf16):
|
| 318 |
+
# convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16
|
| 319 |
+
# and bf16 is not fully supported in PT yet.
|
| 320 |
+
logger.warning(
|
| 321 |
+
"Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` "
|
| 322 |
+
"before loading those in PyTorch model."
|
| 323 |
+
)
|
| 324 |
+
flax_state = jax.tree_util.tree_map(
|
| 325 |
+
lambda params: params.astype(np.float32) if params.dtype == jnp.bfloat16 else params, flax_state
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
flax_state_dict = flatten_dict(flax_state)
|
| 329 |
+
pt_model_dict = pt_model.state_dict()
|
| 330 |
+
|
| 331 |
+
load_model_with_head_into_base_model = (pt_model.base_model_prefix in flax_state) and (
|
| 332 |
+
pt_model.base_model_prefix not in {k.split(".")[0] for k in pt_model_dict.keys()}
|
| 333 |
+
)
|
| 334 |
+
load_base_model_into_model_with_head = (pt_model.base_model_prefix not in flax_state) and (
|
| 335 |
+
pt_model.base_model_prefix in {k.split(".")[0] for k in pt_model_dict.keys()}
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
# keep track of unexpected & missing keys
|
| 339 |
+
unexpected_keys = []
|
| 340 |
+
missing_keys = set(pt_model_dict.keys())
|
| 341 |
+
|
| 342 |
+
for flax_key_tuple, flax_tensor in flax_state_dict.items():
|
| 343 |
+
has_base_model_prefix = flax_key_tuple[0] == pt_model.base_model_prefix
|
| 344 |
+
require_base_model_prefix = ".".join((pt_model.base_model_prefix,) + flax_key_tuple) in pt_model_dict
|
| 345 |
+
|
| 346 |
+
# adapt flax_key to prepare for loading from/to base model only
|
| 347 |
+
if load_model_with_head_into_base_model and has_base_model_prefix:
|
| 348 |
+
flax_key_tuple = flax_key_tuple[1:]
|
| 349 |
+
elif load_base_model_into_model_with_head and require_base_model_prefix:
|
| 350 |
+
flax_key_tuple = (pt_model.base_model_prefix,) + flax_key_tuple
|
| 351 |
+
|
| 352 |
+
# rename flax weights to PyTorch format
|
| 353 |
+
if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(flax_key_tuple) not in pt_model_dict:
|
| 354 |
+
# conv layer
|
| 355 |
+
flax_key_tuple = flax_key_tuple[:-1] + ("weight",)
|
| 356 |
+
flax_tensor = jnp.transpose(flax_tensor, (3, 2, 0, 1))
|
| 357 |
+
elif flax_key_tuple[-1] == "kernel" and ".".join(flax_key_tuple) not in pt_model_dict:
|
| 358 |
+
# linear layer
|
| 359 |
+
flax_key_tuple = flax_key_tuple[:-1] + ("weight",)
|
| 360 |
+
flax_tensor = flax_tensor.T
|
| 361 |
+
elif flax_key_tuple[-1] in ["scale", "embedding"]:
|
| 362 |
+
flax_key_tuple = flax_key_tuple[:-1] + ("weight",)
|
| 363 |
+
|
| 364 |
+
# adding batch stats from flax batch norm to pt
|
| 365 |
+
elif "mean" in flax_key_tuple[-1]:
|
| 366 |
+
flax_key_tuple = flax_key_tuple[:-1] + ("running_mean",)
|
| 367 |
+
elif "var" in flax_key_tuple[-1]:
|
| 368 |
+
flax_key_tuple = flax_key_tuple[:-1] + ("running_var",)
|
| 369 |
+
|
| 370 |
+
if "batch_stats" in flax_state:
|
| 371 |
+
flax_key = ".".join(flax_key_tuple[1:]) # Remove the params/batch_stats header
|
| 372 |
+
else:
|
| 373 |
+
flax_key = ".".join(flax_key_tuple)
|
| 374 |
+
|
| 375 |
+
if flax_key in pt_model_dict:
|
| 376 |
+
if flax_tensor.shape != pt_model_dict[flax_key].shape:
|
| 377 |
+
raise ValueError(
|
| 378 |
+
f"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected "
|
| 379 |
+
f"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}."
|
| 380 |
+
)
|
| 381 |
+
else:
|
| 382 |
+
# add weight to pytorch dict
|
| 383 |
+
flax_tensor = np.asarray(flax_tensor) if not isinstance(flax_tensor, np.ndarray) else flax_tensor
|
| 384 |
+
pt_model_dict[flax_key] = torch.from_numpy(flax_tensor)
|
| 385 |
+
# remove from missing keys
|
| 386 |
+
missing_keys.remove(flax_key)
|
| 387 |
+
else:
|
| 388 |
+
# weight is not expected by PyTorch model
|
| 389 |
+
unexpected_keys.append(flax_key)
|
| 390 |
+
|
| 391 |
+
pt_model.load_state_dict(pt_model_dict)
|
| 392 |
+
|
| 393 |
+
# re-transform missing_keys to list
|
| 394 |
+
missing_keys = list(missing_keys)
|
| 395 |
+
|
| 396 |
+
if len(unexpected_keys) > 0:
|
| 397 |
+
logger.warning(
|
| 398 |
+
"Some weights of the Flax model were not used when initializing the PyTorch model"
|
| 399 |
+
f" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing"
|
| 400 |
+
f" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture"
|
| 401 |
+
" (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This"
|
| 402 |
+
f" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect"
|
| 403 |
+
" to be exactly identical (e.g. initializing a BertForSequenceClassification model from a"
|
| 404 |
+
" FlaxBertForSequenceClassification model)."
|
| 405 |
+
)
|
| 406 |
+
else:
|
| 407 |
+
logger.warning(f"All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n")
|
| 408 |
+
if len(missing_keys) > 0:
|
| 409 |
+
logger.warning(
|
| 410 |
+
f"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly"
|
| 411 |
+
f" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to"
|
| 412 |
+
" use it for predictions and inference."
|
| 413 |
+
)
|
| 414 |
+
else:
|
| 415 |
+
logger.warning(
|
| 416 |
+
f"All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n"
|
| 417 |
+
"If your task is similar to the task the model of the checkpoint was trained on, "
|
| 418 |
+
f"you can already use {pt_model.__class__.__name__} for predictions without further training."
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
return pt_model
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/modeling_flax_utils.py
ADDED
|
@@ -0,0 +1,1170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Google Flax Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import gc
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import re
|
| 21 |
+
from functools import partial
|
| 22 |
+
from pickle import UnpicklingError
|
| 23 |
+
from typing import Any, Dict, Set, Tuple, Union
|
| 24 |
+
|
| 25 |
+
import flax.linen as nn
|
| 26 |
+
import jax
|
| 27 |
+
import jax.numpy as jnp
|
| 28 |
+
import msgpack.exceptions
|
| 29 |
+
from flax.core.frozen_dict import FrozenDict, unfreeze
|
| 30 |
+
from flax.serialization import from_bytes, to_bytes
|
| 31 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 32 |
+
from jax.random import PRNGKey
|
| 33 |
+
|
| 34 |
+
from .configuration_utils import PretrainedConfig
|
| 35 |
+
from .dynamic_module_utils import custom_object_save
|
| 36 |
+
from .generation import FlaxGenerationMixin, GenerationConfig
|
| 37 |
+
from .modeling_flax_pytorch_utils import load_pytorch_checkpoint_in_flax_state_dict
|
| 38 |
+
from .utils import (
|
| 39 |
+
FLAX_WEIGHTS_INDEX_NAME,
|
| 40 |
+
FLAX_WEIGHTS_NAME,
|
| 41 |
+
WEIGHTS_INDEX_NAME,
|
| 42 |
+
WEIGHTS_NAME,
|
| 43 |
+
PushToHubMixin,
|
| 44 |
+
add_code_sample_docstrings,
|
| 45 |
+
add_start_docstrings_to_model_forward,
|
| 46 |
+
cached_file,
|
| 47 |
+
copy_func,
|
| 48 |
+
download_url,
|
| 49 |
+
has_file,
|
| 50 |
+
is_offline_mode,
|
| 51 |
+
is_remote_url,
|
| 52 |
+
logging,
|
| 53 |
+
replace_return_docstrings,
|
| 54 |
+
)
|
| 55 |
+
from .utils.hub import convert_file_size_to_int, get_checkpoint_shard_files
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
logger = logging.get_logger(__name__)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def quick_gelu(x):
|
| 62 |
+
return x * jax.nn.sigmoid(1.702 * x)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
ACT2FN = {
|
| 66 |
+
"gelu": partial(nn.gelu, approximate=False),
|
| 67 |
+
"relu": nn.relu,
|
| 68 |
+
"silu": nn.swish,
|
| 69 |
+
"swish": nn.swish,
|
| 70 |
+
"gelu_new": partial(nn.gelu, approximate=True),
|
| 71 |
+
"quick_gelu": quick_gelu,
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def dtype_byte_size(dtype):
|
| 76 |
+
"""
|
| 77 |
+
Returns the size (in bytes) occupied by one parameter of type `dtype`. Example:
|
| 78 |
+
```py
|
| 79 |
+
>>> dtype_byte_size(np.float32)
|
| 80 |
+
4
|
| 81 |
+
```
|
| 82 |
+
"""
|
| 83 |
+
if dtype == bool:
|
| 84 |
+
return 1 / 8
|
| 85 |
+
bit_search = re.search(r"[^\d](\d+)$", dtype.name)
|
| 86 |
+
if bit_search is None:
|
| 87 |
+
raise ValueError(f"`dtype` is not a valid dtype: {dtype}.")
|
| 88 |
+
bit_size = int(bit_search.groups()[0])
|
| 89 |
+
return bit_size // 8
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def flax_shard_checkpoint(params, max_shard_size="10GB"):
|
| 93 |
+
"""
|
| 94 |
+
Splits a model state dictionary in sub-checkpoints so that the final size of each sub-checkpoint does not exceed a
|
| 95 |
+
given size. The sub-checkpoints are determined by iterating through the `state_dict` in the order of its keys, so
|
| 96 |
+
there is no optimization made to make each sub-checkpoint as close as possible to the maximum size passed. For
|
| 97 |
+
example, if the limit is 10GB and we have weights of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as
|
| 98 |
+
[6GB], [6+2GB], [6+2+2GB] and not [6+2+2GB], [6+2GB], [6GB].
|
| 99 |
+
|
| 100 |
+
<Tip warning={true}>
|
| 101 |
+
|
| 102 |
+
If one of the model's weight is bigger that `max_shard_size`, it will end up in its own sub-checkpoint which will
|
| 103 |
+
have a size greater than `max_shard_size`.
|
| 104 |
+
|
| 105 |
+
</Tip>
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
params (`Union[Dict, FrozenDict]`): A `PyTree` of model parameters.
|
| 109 |
+
max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`):
|
| 110 |
+
The maximum size of each sub-checkpoint. If expressed as a string, needs to be digits followed by a unit
|
| 111 |
+
(like `"5MB"`).
|
| 112 |
+
"""
|
| 113 |
+
max_shard_size = convert_file_size_to_int(max_shard_size)
|
| 114 |
+
|
| 115 |
+
sharded_state_dicts = []
|
| 116 |
+
current_block = {}
|
| 117 |
+
current_block_size = 0
|
| 118 |
+
total_size = 0
|
| 119 |
+
|
| 120 |
+
# flatten the weights to chunk
|
| 121 |
+
weights = flatten_dict(params, sep="/")
|
| 122 |
+
for item in weights:
|
| 123 |
+
weight_size = weights[item].size * dtype_byte_size(weights[item].dtype)
|
| 124 |
+
|
| 125 |
+
# If this weight is going to tip up over the maximal size, we split.
|
| 126 |
+
if current_block_size + weight_size > max_shard_size:
|
| 127 |
+
sharded_state_dicts.append(current_block)
|
| 128 |
+
current_block = {}
|
| 129 |
+
current_block_size = 0
|
| 130 |
+
|
| 131 |
+
current_block[item] = weights[item]
|
| 132 |
+
current_block_size += weight_size
|
| 133 |
+
total_size += weight_size
|
| 134 |
+
|
| 135 |
+
# Add the last block
|
| 136 |
+
sharded_state_dicts.append(current_block)
|
| 137 |
+
|
| 138 |
+
# If we only have one shard, we return it
|
| 139 |
+
if len(sharded_state_dicts) == 1:
|
| 140 |
+
return {FLAX_WEIGHTS_NAME: sharded_state_dicts[0]}, None
|
| 141 |
+
|
| 142 |
+
# Otherwise, let's build the index
|
| 143 |
+
weight_map = {}
|
| 144 |
+
shards = {}
|
| 145 |
+
for idx, shard in enumerate(sharded_state_dicts):
|
| 146 |
+
shard_file = FLAX_WEIGHTS_NAME.replace(".msgpack", f"-{idx+1:05d}-of-{len(sharded_state_dicts):05d}.msgpack")
|
| 147 |
+
shards[shard_file] = shard
|
| 148 |
+
for weight_name in shard.keys():
|
| 149 |
+
weight_map[weight_name] = shard_file
|
| 150 |
+
|
| 151 |
+
# Add the metadata
|
| 152 |
+
metadata = {"total_size": total_size}
|
| 153 |
+
index = {"metadata": metadata, "weight_map": weight_map}
|
| 154 |
+
return shards, index
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class FlaxPreTrainedModel(PushToHubMixin, FlaxGenerationMixin):
|
| 158 |
+
r"""
|
| 159 |
+
Base class for all models.
|
| 160 |
+
|
| 161 |
+
[`FlaxPreTrainedModel`] takes care of storing the configuration of the models and handles methods for loading,
|
| 162 |
+
downloading and saving models.
|
| 163 |
+
|
| 164 |
+
Class attributes (overridden by derived classes):
|
| 165 |
+
|
| 166 |
+
- **config_class** ([`PretrainedConfig`]) -- A subclass of [`PretrainedConfig`] to use as configuration class
|
| 167 |
+
for this model architecture.
|
| 168 |
+
- **base_model_prefix** (`str`) -- A string indicating the attribute associated to the base model in derived
|
| 169 |
+
classes of the same architecture adding modules on top of the base model.
|
| 170 |
+
- **main_input_name** (`str`) -- The name of the principal input to the model (often `input_ids` for NLP
|
| 171 |
+
models, `pixel_values` for vision models and `input_values` for speech models).
|
| 172 |
+
"""
|
| 173 |
+
config_class = None
|
| 174 |
+
base_model_prefix = ""
|
| 175 |
+
main_input_name = "input_ids"
|
| 176 |
+
_auto_class = None
|
| 177 |
+
_missing_keys = set()
|
| 178 |
+
|
| 179 |
+
def __init__(
|
| 180 |
+
self,
|
| 181 |
+
config: PretrainedConfig,
|
| 182 |
+
module: nn.Module,
|
| 183 |
+
input_shape: Tuple = (1, 1),
|
| 184 |
+
seed: int = 0,
|
| 185 |
+
dtype: jnp.dtype = jnp.float32,
|
| 186 |
+
_do_init: bool = True,
|
| 187 |
+
):
|
| 188 |
+
if config is None:
|
| 189 |
+
raise ValueError("config cannot be None")
|
| 190 |
+
|
| 191 |
+
if module is None:
|
| 192 |
+
raise ValueError("module cannot be None")
|
| 193 |
+
|
| 194 |
+
# Those are private to be exposed as typed property on derived classes.
|
| 195 |
+
self._config = config
|
| 196 |
+
self._module = module
|
| 197 |
+
|
| 198 |
+
# Those are public as their type is generic to every derived classes.
|
| 199 |
+
self.key = PRNGKey(seed)
|
| 200 |
+
self.dtype = dtype
|
| 201 |
+
self.input_shape = input_shape
|
| 202 |
+
self.generation_config = GenerationConfig.from_model_config(config) if self.can_generate() else None
|
| 203 |
+
|
| 204 |
+
# To check if the model was intialized automatically.
|
| 205 |
+
self._is_initialized = _do_init
|
| 206 |
+
|
| 207 |
+
if _do_init:
|
| 208 |
+
# randomly initialized parameters
|
| 209 |
+
random_params = self.init_weights(self.key, input_shape)
|
| 210 |
+
params_shape_tree = jax.eval_shape(lambda params: params, random_params)
|
| 211 |
+
else:
|
| 212 |
+
init_fn = partial(self.init_weights, input_shape=input_shape)
|
| 213 |
+
params_shape_tree = jax.eval_shape(init_fn, self.key)
|
| 214 |
+
|
| 215 |
+
logger.info(
|
| 216 |
+
"Model weights are not initialized as `_do_init` is set to `False`. "
|
| 217 |
+
f"Make sure to call `{self.__class__.__name__}.init_weights` manually to initialize the weights."
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
# get the shape of the parameters
|
| 221 |
+
self._params_shape_tree = params_shape_tree
|
| 222 |
+
|
| 223 |
+
# save required_params as set
|
| 224 |
+
self._required_params = set(flatten_dict(unfreeze(params_shape_tree)).keys())
|
| 225 |
+
|
| 226 |
+
# initialize the parameters
|
| 227 |
+
if _do_init:
|
| 228 |
+
self.params = random_params
|
| 229 |
+
|
| 230 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> Dict:
|
| 231 |
+
raise NotImplementedError(f"init method has to be implemented for {self}")
|
| 232 |
+
|
| 233 |
+
def enable_gradient_checkpointing(self):
|
| 234 |
+
raise NotImplementedError(f"gradient checkpointing method has to be implemented for {self}")
|
| 235 |
+
|
| 236 |
+
@classmethod
|
| 237 |
+
def _from_config(cls, config, **kwargs):
|
| 238 |
+
"""
|
| 239 |
+
All context managers that the model should be initialized under go here.
|
| 240 |
+
"""
|
| 241 |
+
return cls(config, **kwargs)
|
| 242 |
+
|
| 243 |
+
@property
|
| 244 |
+
def framework(self) -> str:
|
| 245 |
+
"""
|
| 246 |
+
:str: Identifies that this is a Flax model.
|
| 247 |
+
"""
|
| 248 |
+
return "flax"
|
| 249 |
+
|
| 250 |
+
@property
|
| 251 |
+
def config(self) -> PretrainedConfig:
|
| 252 |
+
return self._config
|
| 253 |
+
|
| 254 |
+
@property
|
| 255 |
+
def module(self) -> nn.Module:
|
| 256 |
+
return self._module
|
| 257 |
+
|
| 258 |
+
@property
|
| 259 |
+
def params(self) -> Union[Dict, FrozenDict]:
|
| 260 |
+
if not self._is_initialized:
|
| 261 |
+
raise ValueError(
|
| 262 |
+
"`params` cannot be accessed from model when the model is created with `_do_init=False`. "
|
| 263 |
+
"You must call `init_weights` manually and store the params outside of the model and "
|
| 264 |
+
"pass it explicitly where needed."
|
| 265 |
+
)
|
| 266 |
+
return self._params
|
| 267 |
+
|
| 268 |
+
@property
|
| 269 |
+
def required_params(self) -> Set:
|
| 270 |
+
return self._required_params
|
| 271 |
+
|
| 272 |
+
@property
|
| 273 |
+
def params_shape_tree(self) -> Dict:
|
| 274 |
+
return self._params_shape_tree
|
| 275 |
+
|
| 276 |
+
@params.setter
|
| 277 |
+
def params(self, params: Union[Dict, FrozenDict]):
|
| 278 |
+
# don't set params if the model is not initialized
|
| 279 |
+
if not self._is_initialized:
|
| 280 |
+
raise ValueError(
|
| 281 |
+
"`params` cannot be set from model when the model is created with `_do_init=False`. "
|
| 282 |
+
"You store the params outside of the model."
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
if isinstance(params, FrozenDict):
|
| 286 |
+
params = unfreeze(params)
|
| 287 |
+
param_keys = set(flatten_dict(params).keys())
|
| 288 |
+
if len(self.required_params - param_keys) > 0:
|
| 289 |
+
raise ValueError(
|
| 290 |
+
"Some parameters are missing. Make sure that `params` include the following "
|
| 291 |
+
f"parameters {self.required_params - param_keys}"
|
| 292 |
+
)
|
| 293 |
+
self._params = params
|
| 294 |
+
|
| 295 |
+
def _cast_floating_to(self, params: Union[Dict, FrozenDict], dtype: jnp.dtype, mask: Any = None) -> Any:
|
| 296 |
+
"""
|
| 297 |
+
Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`.
|
| 298 |
+
"""
|
| 299 |
+
|
| 300 |
+
# taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e6583b192/jmp/_src/policy.py#L27
|
| 301 |
+
def conditional_cast(param):
|
| 302 |
+
if isinstance(param, jnp.ndarray) and jnp.issubdtype(param.dtype, jnp.floating):
|
| 303 |
+
param = param.astype(dtype)
|
| 304 |
+
return param
|
| 305 |
+
|
| 306 |
+
if mask is None:
|
| 307 |
+
return jax.tree_util.tree_map(conditional_cast, params)
|
| 308 |
+
|
| 309 |
+
flat_params = flatten_dict(params)
|
| 310 |
+
flat_mask, _ = jax.tree_util.tree_flatten(mask)
|
| 311 |
+
|
| 312 |
+
for masked, key in zip(flat_mask, flat_params.keys()):
|
| 313 |
+
if masked:
|
| 314 |
+
param = flat_params[key]
|
| 315 |
+
flat_params[key] = conditional_cast(param)
|
| 316 |
+
|
| 317 |
+
return unflatten_dict(flat_params)
|
| 318 |
+
|
| 319 |
+
def to_bf16(self, params: Union[Dict, FrozenDict], mask: Any = None):
|
| 320 |
+
r"""
|
| 321 |
+
Cast the floating-point `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast
|
| 322 |
+
the `params` in place.
|
| 323 |
+
|
| 324 |
+
This method can be used on TPU to explicitly convert the model parameters to bfloat16 precision to do full
|
| 325 |
+
half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed.
|
| 326 |
+
|
| 327 |
+
Arguments:
|
| 328 |
+
params (`Union[Dict, FrozenDict]`):
|
| 329 |
+
A `PyTree` of model parameters.
|
| 330 |
+
mask (`Union[Dict, FrozenDict]`):
|
| 331 |
+
A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params
|
| 332 |
+
you want to cast, and should be `False` for those you want to skip.
|
| 333 |
+
|
| 334 |
+
Examples:
|
| 335 |
+
|
| 336 |
+
```python
|
| 337 |
+
>>> from transformers import FlaxBertModel
|
| 338 |
+
|
| 339 |
+
>>> # load model
|
| 340 |
+
>>> model = FlaxBertModel.from_pretrained("bert-base-cased")
|
| 341 |
+
>>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision
|
| 342 |
+
>>> model.params = model.to_bf16(model.params)
|
| 343 |
+
>>> # If you want don't want to cast certain parameters (for example layer norm bias and scale)
|
| 344 |
+
>>> # then pass the mask as follows
|
| 345 |
+
>>> from flax import traverse_util
|
| 346 |
+
|
| 347 |
+
>>> model = FlaxBertModel.from_pretrained("bert-base-cased")
|
| 348 |
+
>>> flat_params = traverse_util.flatten_dict(model.params)
|
| 349 |
+
>>> mask = {
|
| 350 |
+
... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
|
| 351 |
+
... for path in flat_params
|
| 352 |
+
... }
|
| 353 |
+
>>> mask = traverse_util.unflatten_dict(mask)
|
| 354 |
+
>>> model.params = model.to_bf16(model.params, mask)
|
| 355 |
+
```"""
|
| 356 |
+
return self._cast_floating_to(params, jnp.bfloat16, mask)
|
| 357 |
+
|
| 358 |
+
def to_fp32(self, params: Union[Dict, FrozenDict], mask: Any = None):
|
| 359 |
+
r"""
|
| 360 |
+
Cast the floating-point `parmas` to `jax.numpy.float32`. This method can be used to explicitly convert the
|
| 361 |
+
model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place.
|
| 362 |
+
|
| 363 |
+
Arguments:
|
| 364 |
+
params (`Union[Dict, FrozenDict]`):
|
| 365 |
+
A `PyTree` of model parameters.
|
| 366 |
+
mask (`Union[Dict, FrozenDict]`):
|
| 367 |
+
A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params
|
| 368 |
+
you want to cast, and should be `False` for those you want to skip
|
| 369 |
+
|
| 370 |
+
Examples:
|
| 371 |
+
|
| 372 |
+
```python
|
| 373 |
+
>>> from transformers import FlaxBertModel
|
| 374 |
+
|
| 375 |
+
>>> # Download model and configuration from huggingface.co
|
| 376 |
+
>>> model = FlaxBertModel.from_pretrained("bert-base-cased")
|
| 377 |
+
>>> # By default, the model params will be in fp32, to illustrate the use of this method,
|
| 378 |
+
>>> # we'll first cast to fp16 and back to fp32
|
| 379 |
+
>>> model.params = model.to_f16(model.params)
|
| 380 |
+
>>> # now cast back to fp32
|
| 381 |
+
>>> model.params = model.to_fp32(model.params)
|
| 382 |
+
```"""
|
| 383 |
+
return self._cast_floating_to(params, jnp.float32, mask)
|
| 384 |
+
|
| 385 |
+
def to_fp16(self, params: Union[Dict, FrozenDict], mask: Any = None):
|
| 386 |
+
r"""
|
| 387 |
+
Cast the floating-point `parmas` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the
|
| 388 |
+
`params` in place.
|
| 389 |
+
|
| 390 |
+
This method can be used on GPU to explicitly convert the model parameters to float16 precision to do full
|
| 391 |
+
half-precision training or to save weights in float16 for inference in order to save memory and improve speed.
|
| 392 |
+
|
| 393 |
+
Arguments:
|
| 394 |
+
params (`Union[Dict, FrozenDict]`):
|
| 395 |
+
A `PyTree` of model parameters.
|
| 396 |
+
mask (`Union[Dict, FrozenDict]`):
|
| 397 |
+
A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params
|
| 398 |
+
you want to cast, and should be `False` for those you want to skip
|
| 399 |
+
|
| 400 |
+
Examples:
|
| 401 |
+
|
| 402 |
+
```python
|
| 403 |
+
>>> from transformers import FlaxBertModel
|
| 404 |
+
|
| 405 |
+
>>> # load model
|
| 406 |
+
>>> model = FlaxBertModel.from_pretrained("bert-base-cased")
|
| 407 |
+
>>> # By default, the model params will be in fp32, to cast these to float16
|
| 408 |
+
>>> model.params = model.to_fp16(model.params)
|
| 409 |
+
>>> # If you want don't want to cast certain parameters (for example layer norm bias and scale)
|
| 410 |
+
>>> # then pass the mask as follows
|
| 411 |
+
>>> from flax import traverse_util
|
| 412 |
+
|
| 413 |
+
>>> model = FlaxBertModel.from_pretrained("bert-base-cased")
|
| 414 |
+
>>> flat_params = traverse_util.flatten_dict(model.params)
|
| 415 |
+
>>> mask = {
|
| 416 |
+
... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
|
| 417 |
+
... for path in flat_params
|
| 418 |
+
... }
|
| 419 |
+
>>> mask = traverse_util.unflatten_dict(mask)
|
| 420 |
+
>>> model.params = model.to_fp16(model.params, mask)
|
| 421 |
+
```"""
|
| 422 |
+
return self._cast_floating_to(params, jnp.float16, mask)
|
| 423 |
+
|
| 424 |
+
@classmethod
|
| 425 |
+
def load_flax_sharded_weights(cls, shard_files):
|
| 426 |
+
"""
|
| 427 |
+
This is the same as [`flax.serialization.from_bytes`]
|
| 428 |
+
(https:lax.readthedocs.io/en/latest/_modules/flax/serialization.html#from_bytes) but for a sharded checkpoint.
|
| 429 |
+
|
| 430 |
+
This load is performed efficiently: each checkpoint shard is loaded one by one in RAM and deleted after being
|
| 431 |
+
loaded in the model.
|
| 432 |
+
|
| 433 |
+
Args:
|
| 434 |
+
shard_files (`List[str]`:
|
| 435 |
+
The list of shard files to load.
|
| 436 |
+
|
| 437 |
+
Returns:
|
| 438 |
+
`Dict`: A nested dictionary of the model parameters, in the expected format for flax models : `{'model':
|
| 439 |
+
{'params': {'...'}}}`.
|
| 440 |
+
"""
|
| 441 |
+
|
| 442 |
+
# Load the index
|
| 443 |
+
state_sharded_dict = {}
|
| 444 |
+
|
| 445 |
+
for shard_file in shard_files:
|
| 446 |
+
# load using msgpack utils
|
| 447 |
+
try:
|
| 448 |
+
with open(shard_file, "rb") as state_f:
|
| 449 |
+
state = from_bytes(cls, state_f.read())
|
| 450 |
+
except (UnpicklingError, msgpack.exceptions.ExtraData) as e:
|
| 451 |
+
with open(shard_file) as f:
|
| 452 |
+
if f.read().startswith("version"):
|
| 453 |
+
raise OSError(
|
| 454 |
+
"You seem to have cloned a repository without having git-lfs installed. Please"
|
| 455 |
+
" install git-lfs and run `git lfs install` followed by `git lfs pull` in the"
|
| 456 |
+
" folder you cloned."
|
| 457 |
+
)
|
| 458 |
+
else:
|
| 459 |
+
raise ValueError from e
|
| 460 |
+
except (UnicodeDecodeError, ValueError):
|
| 461 |
+
raise EnvironmentError(f"Unable to convert {shard_file} to Flax deserializable object. ")
|
| 462 |
+
|
| 463 |
+
state = flatten_dict(state, sep="/")
|
| 464 |
+
state_sharded_dict.update(state)
|
| 465 |
+
del state
|
| 466 |
+
gc.collect()
|
| 467 |
+
|
| 468 |
+
# the state dict is unflattened to the match the format of model.params
|
| 469 |
+
return unflatten_dict(state_sharded_dict, sep="/")
|
| 470 |
+
|
| 471 |
+
def can_generate(self) -> bool:
|
| 472 |
+
"""
|
| 473 |
+
Returns whether this model can generate sequences with `.generate()`. Returns:
|
| 474 |
+
`bool`: Whether this model can generate sequences with `.generate()`.
|
| 475 |
+
"""
|
| 476 |
+
# Detects whether `prepare_inputs_for_generation` has been overwritten, which is a requirement for generation
|
| 477 |
+
if "GenerationMixin" in str(self.prepare_inputs_for_generation):
|
| 478 |
+
return False
|
| 479 |
+
return True
|
| 480 |
+
|
| 481 |
+
@classmethod
|
| 482 |
+
def from_pretrained(
|
| 483 |
+
cls,
|
| 484 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
| 485 |
+
dtype: jnp.dtype = jnp.float32,
|
| 486 |
+
*model_args,
|
| 487 |
+
**kwargs,
|
| 488 |
+
):
|
| 489 |
+
r"""
|
| 490 |
+
Instantiate a pretrained flax model from a pre-trained model configuration.
|
| 491 |
+
|
| 492 |
+
The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come
|
| 493 |
+
pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning
|
| 494 |
+
task.
|
| 495 |
+
|
| 496 |
+
The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those
|
| 497 |
+
weights are discarded.
|
| 498 |
+
|
| 499 |
+
Parameters:
|
| 500 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 501 |
+
Can be either:
|
| 502 |
+
|
| 503 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
| 504 |
+
Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
|
| 505 |
+
user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 506 |
+
- A path to a *directory* containing model weights saved using
|
| 507 |
+
[`~FlaxPreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
|
| 508 |
+
- A path or url to a *pt index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In this case,
|
| 509 |
+
`from_pt` should be set to `True`.
|
| 510 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
| 511 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
| 512 |
+
`jax.numpy.bfloat16` (on TPUs).
|
| 513 |
+
|
| 514 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
| 515 |
+
specified all the computation will be performed with the given `dtype`.
|
| 516 |
+
|
| 517 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
| 518 |
+
parameters.**
|
| 519 |
+
|
| 520 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
| 521 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
| 522 |
+
model_args (sequence of positional arguments, *optional*):
|
| 523 |
+
All remaining positional arguments will be passed to the underlying model's `__init__` method.
|
| 524 |
+
config (`Union[PretrainedConfig, str, os.PathLike]`, *optional*):
|
| 525 |
+
Can be either:
|
| 526 |
+
|
| 527 |
+
- an instance of a class derived from [`PretrainedConfig`],
|
| 528 |
+
- a string or path valid as input to [`~PretrainedConfig.from_pretrained`].
|
| 529 |
+
|
| 530 |
+
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
|
| 531 |
+
be automatically loaded when:
|
| 532 |
+
|
| 533 |
+
- The model is a model provided by the library (loaded with the *model id* string of a pretrained
|
| 534 |
+
model).
|
| 535 |
+
- The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
|
| 536 |
+
save directory.
|
| 537 |
+
- The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
|
| 538 |
+
configuration JSON file named *config.json* is found in the directory.
|
| 539 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 540 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 541 |
+
standard cache should not be used.
|
| 542 |
+
from_pt (`bool`, *optional*, defaults to `False`):
|
| 543 |
+
Load the model weights from a PyTorch checkpoint save file (see docstring of
|
| 544 |
+
`pretrained_model_name_or_path` argument).
|
| 545 |
+
ignore_mismatched_sizes (`bool`, *optional*, defaults to `False`):
|
| 546 |
+
Whether or not to raise an error if some of the weights from the checkpoint do not have the same size
|
| 547 |
+
as the weights of the model (if for instance, you are instantiating a model with 10 labels from a
|
| 548 |
+
checkpoint with 3 labels).
|
| 549 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 550 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 551 |
+
cached versions if they exist.
|
| 552 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 553 |
+
Whether or not to delete incompletely received files. Will attempt to resume the download if such a
|
| 554 |
+
file exists.
|
| 555 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 556 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 557 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 558 |
+
local_files_only(`bool`, *optional*, defaults to `False`):
|
| 559 |
+
Whether or not to only look at local files (i.e., do not try to download the model).
|
| 560 |
+
use_auth_token (`str` or `bool`, *optional*):
|
| 561 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
|
| 562 |
+
the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 563 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 564 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 565 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 566 |
+
identifier allowed by git.
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
<Tip>
|
| 570 |
+
|
| 571 |
+
To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>".
|
| 572 |
+
|
| 573 |
+
</Tip>
|
| 574 |
+
|
| 575 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
| 576 |
+
In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
|
| 577 |
+
specify the folder name here.
|
| 578 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
| 579 |
+
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
|
| 580 |
+
`output_attentions=True`). Behaves differently depending on whether a `config` is provided or
|
| 581 |
+
automatically loaded:
|
| 582 |
+
|
| 583 |
+
- If a configuration is provided with `config`, `**kwargs` will be directly passed to the
|
| 584 |
+
underlying model's `__init__` method (we assume all relevant updates to the configuration have
|
| 585 |
+
already been done)
|
| 586 |
+
- If a configuration is not provided, `kwargs` will be first passed to the configuration class
|
| 587 |
+
initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
|
| 588 |
+
corresponds to a configuration attribute will be used to override said attribute with the
|
| 589 |
+
supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
|
| 590 |
+
will be passed to the underlying model's `__init__` function.
|
| 591 |
+
|
| 592 |
+
Examples:
|
| 593 |
+
|
| 594 |
+
```python
|
| 595 |
+
>>> from transformers import BertConfig, FlaxBertModel
|
| 596 |
+
|
| 597 |
+
>>> # Download model and configuration from huggingface.co and cache.
|
| 598 |
+
>>> model = FlaxBertModel.from_pretrained("bert-base-cased")
|
| 599 |
+
>>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).
|
| 600 |
+
>>> model = FlaxBertModel.from_pretrained("./test/saved_model/")
|
| 601 |
+
>>> # Loading from a PyTorch checkpoint file instead of a PyTorch model (slower, for example purposes, not runnable).
|
| 602 |
+
>>> config = BertConfig.from_json_file("./pt_model/config.json")
|
| 603 |
+
>>> model = FlaxBertModel.from_pretrained("./pt_model/pytorch_model.bin", from_pt=True, config=config)
|
| 604 |
+
```"""
|
| 605 |
+
config = kwargs.pop("config", None)
|
| 606 |
+
cache_dir = kwargs.pop("cache_dir", None)
|
| 607 |
+
from_pt = kwargs.pop("from_pt", False)
|
| 608 |
+
ignore_mismatched_sizes = kwargs.pop("ignore_mismatched_sizes", False)
|
| 609 |
+
force_download = kwargs.pop("force_download", False)
|
| 610 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 611 |
+
proxies = kwargs.pop("proxies", None)
|
| 612 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
| 613 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 614 |
+
revision = kwargs.pop("revision", None)
|
| 615 |
+
trust_remote_code = kwargs.pop("trust_remote_code", None)
|
| 616 |
+
from_pipeline = kwargs.pop("_from_pipeline", None)
|
| 617 |
+
from_auto_class = kwargs.pop("_from_auto", False)
|
| 618 |
+
_do_init = kwargs.pop("_do_init", True)
|
| 619 |
+
subfolder = kwargs.pop("subfolder", "")
|
| 620 |
+
commit_hash = kwargs.pop("_commit_hash", None)
|
| 621 |
+
|
| 622 |
+
if trust_remote_code is True:
|
| 623 |
+
logger.warning(
|
| 624 |
+
"The argument `trust_remote_code` is to be used with Auto classes. It has no effect here and is"
|
| 625 |
+
" ignored."
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
user_agent = {"file_type": "model", "framework": "flax", "from_auto_class": from_auto_class}
|
| 629 |
+
if from_pipeline is not None:
|
| 630 |
+
user_agent["using_pipeline"] = from_pipeline
|
| 631 |
+
|
| 632 |
+
if is_offline_mode() and not local_files_only:
|
| 633 |
+
logger.info("Offline mode: forcing local_files_only=True")
|
| 634 |
+
local_files_only = True
|
| 635 |
+
|
| 636 |
+
# Load config if we don't provide a configuration
|
| 637 |
+
if not isinstance(config, PretrainedConfig):
|
| 638 |
+
config_path = config if config is not None else pretrained_model_name_or_path
|
| 639 |
+
config, model_kwargs = cls.config_class.from_pretrained(
|
| 640 |
+
config_path,
|
| 641 |
+
cache_dir=cache_dir,
|
| 642 |
+
return_unused_kwargs=True,
|
| 643 |
+
force_download=force_download,
|
| 644 |
+
resume_download=resume_download,
|
| 645 |
+
proxies=proxies,
|
| 646 |
+
local_files_only=local_files_only,
|
| 647 |
+
use_auth_token=use_auth_token,
|
| 648 |
+
revision=revision,
|
| 649 |
+
subfolder=subfolder,
|
| 650 |
+
_from_auto=from_auto_class,
|
| 651 |
+
_from_pipeline=from_pipeline,
|
| 652 |
+
_commit_hash=commit_hash,
|
| 653 |
+
**kwargs,
|
| 654 |
+
)
|
| 655 |
+
else:
|
| 656 |
+
model_kwargs = kwargs.copy()
|
| 657 |
+
|
| 658 |
+
if commit_hash is None:
|
| 659 |
+
commit_hash = getattr(config, "_commit_hash", None)
|
| 660 |
+
|
| 661 |
+
# Add the dtype to model_kwargs
|
| 662 |
+
model_kwargs["dtype"] = dtype
|
| 663 |
+
|
| 664 |
+
# This variable will flag if we're loading a sharded checkpoint. In this case the archive file is just the
|
| 665 |
+
# index of the files.
|
| 666 |
+
is_sharded = False
|
| 667 |
+
|
| 668 |
+
# Load model
|
| 669 |
+
if pretrained_model_name_or_path is not None:
|
| 670 |
+
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
|
| 671 |
+
is_local = os.path.isdir(pretrained_model_name_or_path)
|
| 672 |
+
if os.path.isdir(pretrained_model_name_or_path):
|
| 673 |
+
if from_pt and os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_NAME)):
|
| 674 |
+
# Load from a PyTorch checkpoint
|
| 675 |
+
archive_file = os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_NAME)
|
| 676 |
+
elif from_pt and os.path.isfile(
|
| 677 |
+
os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_INDEX_NAME)
|
| 678 |
+
):
|
| 679 |
+
# Load from a sharded pytorch checkpoint
|
| 680 |
+
archive_file = os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_INDEX_NAME)
|
| 681 |
+
is_sharded = True
|
| 682 |
+
elif os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_NAME)):
|
| 683 |
+
# Load from a Flax checkpoint
|
| 684 |
+
archive_file = os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_NAME)
|
| 685 |
+
elif os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_INDEX_NAME)):
|
| 686 |
+
# Load from a sharded Flax checkpoint
|
| 687 |
+
archive_file = os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_INDEX_NAME)
|
| 688 |
+
is_sharded = True
|
| 689 |
+
# At this stage we don't have a weight file so we will raise an error.
|
| 690 |
+
elif os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_NAME)):
|
| 691 |
+
raise EnvironmentError(
|
| 692 |
+
f"Error no file named {FLAX_WEIGHTS_NAME} found in directory {pretrained_model_name_or_path} "
|
| 693 |
+
"but there is a file for PyTorch weights. Use `from_pt=True` to load this model from those "
|
| 694 |
+
"weights."
|
| 695 |
+
)
|
| 696 |
+
else:
|
| 697 |
+
raise EnvironmentError(
|
| 698 |
+
f"Error no file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory "
|
| 699 |
+
f"{pretrained_model_name_or_path}."
|
| 700 |
+
)
|
| 701 |
+
elif os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)):
|
| 702 |
+
archive_file = pretrained_model_name_or_path
|
| 703 |
+
is_local = True
|
| 704 |
+
elif is_remote_url(pretrained_model_name_or_path):
|
| 705 |
+
filename = pretrained_model_name_or_path
|
| 706 |
+
resolved_archive_file = download_url(pretrained_model_name_or_path)
|
| 707 |
+
else:
|
| 708 |
+
filename = WEIGHTS_NAME if from_pt else FLAX_WEIGHTS_NAME
|
| 709 |
+
try:
|
| 710 |
+
# Load from URL or cache if already cached
|
| 711 |
+
cached_file_kwargs = {
|
| 712 |
+
"cache_dir": cache_dir,
|
| 713 |
+
"force_download": force_download,
|
| 714 |
+
"proxies": proxies,
|
| 715 |
+
"resume_download": resume_download,
|
| 716 |
+
"local_files_only": local_files_only,
|
| 717 |
+
"use_auth_token": use_auth_token,
|
| 718 |
+
"user_agent": user_agent,
|
| 719 |
+
"revision": revision,
|
| 720 |
+
"subfolder": subfolder,
|
| 721 |
+
"_raise_exceptions_for_missing_entries": False,
|
| 722 |
+
"_commit_hash": commit_hash,
|
| 723 |
+
}
|
| 724 |
+
resolved_archive_file = cached_file(pretrained_model_name_or_path, filename, **cached_file_kwargs)
|
| 725 |
+
|
| 726 |
+
# Since we set _raise_exceptions_for_missing_entries=False, we don't get an expection but a None
|
| 727 |
+
# result when internet is up, the repo and revision exist, but the file does not.
|
| 728 |
+
if resolved_archive_file is None and filename == FLAX_WEIGHTS_NAME:
|
| 729 |
+
# Maybe the checkpoint is sharded, we try to grab the index name in this case.
|
| 730 |
+
resolved_archive_file = cached_file(
|
| 731 |
+
pretrained_model_name_or_path, FLAX_WEIGHTS_INDEX_NAME, **cached_file_kwargs
|
| 732 |
+
)
|
| 733 |
+
if resolved_archive_file is not None:
|
| 734 |
+
is_sharded = True
|
| 735 |
+
# Maybe the checkpoint is pytorch sharded, we try to grab the pytorch index name in this case.
|
| 736 |
+
elif resolved_archive_file is None and from_pt:
|
| 737 |
+
resolved_archive_file = cached_file(
|
| 738 |
+
pretrained_model_name_or_path, WEIGHTS_INDEX_NAME, **cached_file_kwargs
|
| 739 |
+
)
|
| 740 |
+
if resolved_archive_file is not None:
|
| 741 |
+
is_sharded = True
|
| 742 |
+
if resolved_archive_file is None:
|
| 743 |
+
# Otherwise, maybe there is a TF or Flax model file. We try those to give a helpful error
|
| 744 |
+
# message.
|
| 745 |
+
has_file_kwargs = {
|
| 746 |
+
"revision": revision,
|
| 747 |
+
"proxies": proxies,
|
| 748 |
+
"use_auth_token": use_auth_token,
|
| 749 |
+
}
|
| 750 |
+
if has_file(pretrained_model_name_or_path, WEIGHTS_NAME, **has_file_kwargs):
|
| 751 |
+
raise EnvironmentError(
|
| 752 |
+
f"{pretrained_model_name_or_path} does not appear to have a file named"
|
| 753 |
+
f" {FLAX_WEIGHTS_NAME} but there is a file for PyTorch weights. Use `from_pt=True` to"
|
| 754 |
+
" load this model from those weights."
|
| 755 |
+
)
|
| 756 |
+
elif has_file(pretrained_model_name_or_path, WEIGHTS_INDEX_NAME, **has_file_kwargs):
|
| 757 |
+
raise EnvironmentError(
|
| 758 |
+
f"{pretrained_model_name_or_path} does not appear to have a file named"
|
| 759 |
+
f" {FLAX_WEIGHTS_INDEX_NAME} but there is a sharded file for PyTorch weights. Use"
|
| 760 |
+
" `from_pt=True` to load this model from those weights."
|
| 761 |
+
)
|
| 762 |
+
else:
|
| 763 |
+
raise EnvironmentError(
|
| 764 |
+
f"{pretrained_model_name_or_path} does not appear to have a file named"
|
| 765 |
+
f" {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}."
|
| 766 |
+
)
|
| 767 |
+
except EnvironmentError:
|
| 768 |
+
# Raise any environment error raise by `cached_file`. It will have a helpful error message adapted
|
| 769 |
+
# to the original exception.
|
| 770 |
+
raise
|
| 771 |
+
except Exception:
|
| 772 |
+
# For any other exception, we throw a generic error.
|
| 773 |
+
raise EnvironmentError(
|
| 774 |
+
f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it"
|
| 775 |
+
" from 'https://huggingface.co/models', make sure you don't have a local directory with the"
|
| 776 |
+
f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
|
| 777 |
+
f" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}."
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
if is_local:
|
| 781 |
+
logger.info(f"loading weights file {archive_file}")
|
| 782 |
+
resolved_archive_file = archive_file
|
| 783 |
+
else:
|
| 784 |
+
logger.info(f"loading weights file {filename} from cache at {resolved_archive_file}")
|
| 785 |
+
else:
|
| 786 |
+
resolved_archive_file = None
|
| 787 |
+
|
| 788 |
+
# We'll need to download and cache each checkpoint shard if the checkpoint is sharded.
|
| 789 |
+
if is_sharded:
|
| 790 |
+
# resolved_archive_file becomes a list of files that point to the different checkpoint shards in this case.
|
| 791 |
+
resolved_archive_file, _ = get_checkpoint_shard_files(
|
| 792 |
+
pretrained_model_name_or_path,
|
| 793 |
+
resolved_archive_file,
|
| 794 |
+
cache_dir=cache_dir,
|
| 795 |
+
force_download=force_download,
|
| 796 |
+
proxies=proxies,
|
| 797 |
+
resume_download=resume_download,
|
| 798 |
+
local_files_only=local_files_only,
|
| 799 |
+
use_auth_token=use_auth_token,
|
| 800 |
+
user_agent=user_agent,
|
| 801 |
+
revision=revision,
|
| 802 |
+
subfolder=subfolder,
|
| 803 |
+
_commit_hash=commit_hash,
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
# init random models
|
| 807 |
+
model = cls(config, *model_args, _do_init=_do_init, **model_kwargs)
|
| 808 |
+
|
| 809 |
+
if from_pt:
|
| 810 |
+
state = load_pytorch_checkpoint_in_flax_state_dict(model, resolved_archive_file, is_sharded)
|
| 811 |
+
else:
|
| 812 |
+
if is_sharded:
|
| 813 |
+
state = cls.load_flax_sharded_weights(resolved_archive_file)
|
| 814 |
+
else:
|
| 815 |
+
try:
|
| 816 |
+
with open(resolved_archive_file, "rb") as state_f:
|
| 817 |
+
state = from_bytes(cls, state_f.read())
|
| 818 |
+
except (UnpicklingError, msgpack.exceptions.ExtraData) as e:
|
| 819 |
+
try:
|
| 820 |
+
with open(resolved_archive_file) as f:
|
| 821 |
+
if f.read().startswith("version"):
|
| 822 |
+
raise OSError(
|
| 823 |
+
"You seem to have cloned a repository without having git-lfs installed. Please"
|
| 824 |
+
" install git-lfs and run `git lfs install` followed by `git lfs pull` in the"
|
| 825 |
+
" folder you cloned."
|
| 826 |
+
)
|
| 827 |
+
else:
|
| 828 |
+
raise ValueError from e
|
| 829 |
+
except (UnicodeDecodeError, ValueError):
|
| 830 |
+
raise EnvironmentError(f"Unable to convert {archive_file} to Flax deserializable object. ")
|
| 831 |
+
# make sure all arrays are stored as jnp.arrays
|
| 832 |
+
# NOTE: This is to prevent a bug this will be fixed in Flax >= v0.3.4:
|
| 833 |
+
# https://github.com/google/flax/issues/1261
|
| 834 |
+
if _do_init:
|
| 835 |
+
state = jax.tree_util.tree_map(jnp.array, state)
|
| 836 |
+
else:
|
| 837 |
+
# keep the params on CPU if we don't want to initialize
|
| 838 |
+
state = jax.tree_util.tree_map(lambda x: jax.device_put(x, jax.devices("cpu")[0]), state)
|
| 839 |
+
|
| 840 |
+
if "batch_stats" in state: # if flax model contains batch norm layers
|
| 841 |
+
# if model is base model only use model_prefix key
|
| 842 |
+
if (
|
| 843 |
+
cls.base_model_prefix not in dict(model.params_shape_tree["params"])
|
| 844 |
+
and cls.base_model_prefix in state["params"]
|
| 845 |
+
):
|
| 846 |
+
state["params"] = state["params"][cls.base_model_prefix]
|
| 847 |
+
state["batch_stats"] = state["batch_stats"][cls.base_model_prefix]
|
| 848 |
+
|
| 849 |
+
# if model is head model and we are loading weights from base model
|
| 850 |
+
# we initialize new params dict with base_model_prefix
|
| 851 |
+
if (
|
| 852 |
+
cls.base_model_prefix in dict(model.params_shape_tree["params"])
|
| 853 |
+
and cls.base_model_prefix not in state["params"]
|
| 854 |
+
):
|
| 855 |
+
state = {
|
| 856 |
+
"params": {cls.base_model_prefix: state["params"]},
|
| 857 |
+
"batch_stats": {cls.base_model_prefix: state["batch_stats"]},
|
| 858 |
+
}
|
| 859 |
+
|
| 860 |
+
else:
|
| 861 |
+
# if model is base model only use model_prefix key
|
| 862 |
+
if cls.base_model_prefix not in dict(model.params_shape_tree) and cls.base_model_prefix in state:
|
| 863 |
+
state = state[cls.base_model_prefix]
|
| 864 |
+
|
| 865 |
+
# if model is head model and we are loading weights from base model
|
| 866 |
+
# we initialize new params dict with base_model_prefix
|
| 867 |
+
if cls.base_model_prefix in dict(model.params_shape_tree) and cls.base_model_prefix not in state:
|
| 868 |
+
state = {cls.base_model_prefix: state}
|
| 869 |
+
|
| 870 |
+
# flatten dicts
|
| 871 |
+
state = flatten_dict(state)
|
| 872 |
+
|
| 873 |
+
random_state = flatten_dict(unfreeze(model.params if _do_init else model.params_shape_tree))
|
| 874 |
+
|
| 875 |
+
missing_keys = model.required_params - set(state.keys())
|
| 876 |
+
unexpected_keys = set(state.keys()) - model.required_params
|
| 877 |
+
|
| 878 |
+
# Disabling warning when porting pytorch weights to flax, flax does not uses num_batches_tracked
|
| 879 |
+
for unexpected_key in unexpected_keys.copy():
|
| 880 |
+
if "num_batches_tracked" in unexpected_key[-1]:
|
| 881 |
+
unexpected_keys.remove(unexpected_key)
|
| 882 |
+
|
| 883 |
+
if missing_keys and not _do_init:
|
| 884 |
+
logger.warning(
|
| 885 |
+
f"The checkpoint {pretrained_model_name_or_path} is missing required keys: {missing_keys}. "
|
| 886 |
+
"Make sure to call model.init_weights to initialize the missing weights."
|
| 887 |
+
)
|
| 888 |
+
cls._missing_keys = missing_keys
|
| 889 |
+
|
| 890 |
+
# Mistmatched keys contains tuples key/shape1/shape2 of weights in the checkpoint that have a shape not
|
| 891 |
+
# matching the weights in the model.
|
| 892 |
+
mismatched_keys = []
|
| 893 |
+
for key in state.keys():
|
| 894 |
+
if key in random_state and state[key].shape != random_state[key].shape:
|
| 895 |
+
if ignore_mismatched_sizes:
|
| 896 |
+
mismatched_keys.append((key, state[key].shape, random_state[key].shape))
|
| 897 |
+
state[key] = random_state[key]
|
| 898 |
+
else:
|
| 899 |
+
raise ValueError(
|
| 900 |
+
f"Trying to load the pretrained weight for {key} failed: checkpoint has shape "
|
| 901 |
+
f"{state[key].shape} which is incompatible with the model shape {random_state[key].shape}. "
|
| 902 |
+
"Using `ignore_mismatched_sizes=True` if you really want to load this checkpoint inside this "
|
| 903 |
+
"model."
|
| 904 |
+
)
|
| 905 |
+
|
| 906 |
+
# add missing keys as random parameters if we are initializing
|
| 907 |
+
if missing_keys and _do_init:
|
| 908 |
+
for missing_key in missing_keys:
|
| 909 |
+
state[missing_key] = random_state[missing_key]
|
| 910 |
+
|
| 911 |
+
# remove unexpected keys to not be saved again
|
| 912 |
+
for unexpected_key in unexpected_keys:
|
| 913 |
+
del state[unexpected_key]
|
| 914 |
+
|
| 915 |
+
if len(unexpected_keys) > 0:
|
| 916 |
+
logger.warning(
|
| 917 |
+
f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when"
|
| 918 |
+
f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
|
| 919 |
+
f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or"
|
| 920 |
+
" with another architecture (e.g. initializing a BertForSequenceClassification model from a"
|
| 921 |
+
" BertForPreTraining model).\n- This IS NOT expected if you are initializing"
|
| 922 |
+
f" {model.__class__.__name__} from the checkpoint of a model that you expect to be exactly identical"
|
| 923 |
+
" (initializing a BertForSequenceClassification model from a BertForSequenceClassification model)."
|
| 924 |
+
)
|
| 925 |
+
else:
|
| 926 |
+
logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")
|
| 927 |
+
|
| 928 |
+
if len(missing_keys) > 0:
|
| 929 |
+
logger.warning(
|
| 930 |
+
f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
|
| 931 |
+
f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"
|
| 932 |
+
" TRAIN this model on a down-stream task to be able to use it for predictions and inference."
|
| 933 |
+
)
|
| 934 |
+
elif len(mismatched_keys) == 0:
|
| 935 |
+
logger.info(
|
| 936 |
+
f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"
|
| 937 |
+
f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the checkpoint"
|
| 938 |
+
f" was trained on, you can already use {model.__class__.__name__} for predictions without further"
|
| 939 |
+
" training."
|
| 940 |
+
)
|
| 941 |
+
if len(mismatched_keys) > 0:
|
| 942 |
+
mismatched_warning = "\n".join(
|
| 943 |
+
[
|
| 944 |
+
f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated"
|
| 945 |
+
for key, shape1, shape2 in mismatched_keys
|
| 946 |
+
]
|
| 947 |
+
)
|
| 948 |
+
logger.warning(
|
| 949 |
+
f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
|
| 950 |
+
f" {pretrained_model_name_or_path} and are newly initialized because the shapes did not"
|
| 951 |
+
f" match:\n{mismatched_warning}\nYou should probably TRAIN this model on a down-stream task to be able"
|
| 952 |
+
" to use it for predictions and inference."
|
| 953 |
+
)
|
| 954 |
+
|
| 955 |
+
# dictionary of key: dtypes for the model params
|
| 956 |
+
param_dtypes = jax.tree_util.tree_map(lambda x: x.dtype, state)
|
| 957 |
+
# extract keys of parameters not in jnp.float32
|
| 958 |
+
fp16_params = [k for k in param_dtypes if param_dtypes[k] == jnp.float16]
|
| 959 |
+
bf16_params = [k for k in param_dtypes if param_dtypes[k] == jnp.bfloat16]
|
| 960 |
+
|
| 961 |
+
# raise a warning if any of the parameters are not in jnp.float32
|
| 962 |
+
if len(fp16_params) > 0:
|
| 963 |
+
logger.warning(
|
| 964 |
+
f"Some of the weights of {model.__class__.__name__} were initialized in float16 precision from "
|
| 965 |
+
f"the model checkpoint at {pretrained_model_name_or_path}:\n{fp16_params}\n"
|
| 966 |
+
"You should probably UPCAST the model weights to float32 if this was not intended. "
|
| 967 |
+
"See [`~FlaxPreTrainedModel.to_fp32`] for further information on how to do this."
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
if len(bf16_params) > 0:
|
| 971 |
+
logger.warning(
|
| 972 |
+
f"Some of the weights of {model.__class__.__name__} were initialized in bfloat16 precision from "
|
| 973 |
+
f"the model checkpoint at {pretrained_model_name_or_path}:\n{bf16_params}\n"
|
| 974 |
+
"You should probably UPCAST the model weights to float32 if this was not intended. "
|
| 975 |
+
"See [`~FlaxPreTrainedModel.to_fp32`] for further information on how to do this."
|
| 976 |
+
)
|
| 977 |
+
|
| 978 |
+
# If it is a model with generation capabilities, attempt to load the generation config
|
| 979 |
+
if model.can_generate():
|
| 980 |
+
try:
|
| 981 |
+
model.generation_config = GenerationConfig.from_pretrained(
|
| 982 |
+
pretrained_model_name_or_path,
|
| 983 |
+
cache_dir=cache_dir,
|
| 984 |
+
force_download=force_download,
|
| 985 |
+
resume_download=resume_download,
|
| 986 |
+
proxies=proxies,
|
| 987 |
+
local_files_only=local_files_only,
|
| 988 |
+
use_auth_token=use_auth_token,
|
| 989 |
+
revision=revision,
|
| 990 |
+
subfolder=subfolder,
|
| 991 |
+
_from_auto=from_auto_class,
|
| 992 |
+
_from_pipeline=from_pipeline,
|
| 993 |
+
**kwargs,
|
| 994 |
+
)
|
| 995 |
+
except OSError:
|
| 996 |
+
logger.info(
|
| 997 |
+
"Generation config file not found, using a generation config created from the model config."
|
| 998 |
+
)
|
| 999 |
+
pass
|
| 1000 |
+
|
| 1001 |
+
if _do_init:
|
| 1002 |
+
# set correct parameters
|
| 1003 |
+
model.params = unflatten_dict(state)
|
| 1004 |
+
return model
|
| 1005 |
+
else:
|
| 1006 |
+
return model, unflatten_dict(state)
|
| 1007 |
+
|
| 1008 |
+
def save_pretrained(
|
| 1009 |
+
self, save_directory: Union[str, os.PathLike], params=None, push_to_hub=False, max_shard_size="10GB", **kwargs
|
| 1010 |
+
):
|
| 1011 |
+
"""
|
| 1012 |
+
Save a model and its configuration file to a directory, so that it can be re-loaded using the
|
| 1013 |
+
`[`~FlaxPreTrainedModel.from_pretrained`]` class method
|
| 1014 |
+
|
| 1015 |
+
Arguments:
|
| 1016 |
+
save_directory (`str` or `os.PathLike`):
|
| 1017 |
+
Directory to which to save. Will be created if it doesn't exist.
|
| 1018 |
+
push_to_hub (`bool`, *optional*, defaults to `False`):
|
| 1019 |
+
Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
|
| 1020 |
+
repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
|
| 1021 |
+
namespace).
|
| 1022 |
+
max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`):
|
| 1023 |
+
The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
|
| 1024 |
+
lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).
|
| 1025 |
+
|
| 1026 |
+
<Tip warning={true}>
|
| 1027 |
+
|
| 1028 |
+
If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard
|
| 1029 |
+
which will be bigger than `max_shard_size`.
|
| 1030 |
+
|
| 1031 |
+
</Tip>
|
| 1032 |
+
|
| 1033 |
+
kwargs:
|
| 1034 |
+
Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
|
| 1035 |
+
"""
|
| 1036 |
+
if os.path.isfile(save_directory):
|
| 1037 |
+
logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
|
| 1038 |
+
return
|
| 1039 |
+
|
| 1040 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 1041 |
+
|
| 1042 |
+
if push_to_hub:
|
| 1043 |
+
commit_message = kwargs.pop("commit_message", None)
|
| 1044 |
+
repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
|
| 1045 |
+
repo_id = self._create_repo(repo_id, **kwargs)
|
| 1046 |
+
files_timestamps = self._get_files_timestamps(save_directory)
|
| 1047 |
+
|
| 1048 |
+
# get abs dir
|
| 1049 |
+
save_directory = os.path.abspath(save_directory)
|
| 1050 |
+
# save config as well
|
| 1051 |
+
self.config.architectures = [self.__class__.__name__[4:]]
|
| 1052 |
+
|
| 1053 |
+
# If we have a custom model, we copy the file defining it in the folder and set the attributes so it can be
|
| 1054 |
+
# loaded from the Hub.
|
| 1055 |
+
if self._auto_class is not None:
|
| 1056 |
+
custom_object_save(self, save_directory, config=self.config)
|
| 1057 |
+
|
| 1058 |
+
self.config.save_pretrained(save_directory)
|
| 1059 |
+
if self.can_generate():
|
| 1060 |
+
self.generation_config.save_pretrained(save_directory)
|
| 1061 |
+
|
| 1062 |
+
# save model
|
| 1063 |
+
output_model_file = os.path.join(save_directory, FLAX_WEIGHTS_NAME)
|
| 1064 |
+
|
| 1065 |
+
shards, index = flax_shard_checkpoint(params if params is not None else self.params, max_shard_size)
|
| 1066 |
+
# Clean the folder from a previous save
|
| 1067 |
+
for filename in os.listdir(save_directory):
|
| 1068 |
+
full_filename = os.path.join(save_directory, filename)
|
| 1069 |
+
if (
|
| 1070 |
+
filename.startswith(FLAX_WEIGHTS_NAME[:-4])
|
| 1071 |
+
and os.path.isfile(full_filename)
|
| 1072 |
+
and filename not in shards.keys()
|
| 1073 |
+
):
|
| 1074 |
+
os.remove(full_filename)
|
| 1075 |
+
|
| 1076 |
+
if index is None:
|
| 1077 |
+
with open(output_model_file, "wb") as f:
|
| 1078 |
+
params = params if params is not None else self.params
|
| 1079 |
+
model_bytes = to_bytes(params)
|
| 1080 |
+
f.write(model_bytes)
|
| 1081 |
+
|
| 1082 |
+
else:
|
| 1083 |
+
save_index_file = os.path.join(save_directory, FLAX_WEIGHTS_INDEX_NAME)
|
| 1084 |
+
# Save the index as well
|
| 1085 |
+
with open(save_index_file, "w", encoding="utf-8") as f:
|
| 1086 |
+
content = json.dumps(index, indent=2, sort_keys=True) + "\n"
|
| 1087 |
+
f.write(content)
|
| 1088 |
+
logger.info(
|
| 1089 |
+
f"The model is bigger than the maximum size per checkpoint ({max_shard_size}) and is going to be "
|
| 1090 |
+
f"split in {len(shards)} checkpoint shards. You can find where each parameters has been saved in the "
|
| 1091 |
+
f"index located at {save_index_file}."
|
| 1092 |
+
)
|
| 1093 |
+
for shard_file, shard in shards.items():
|
| 1094 |
+
# the shard item are unflattened, to save them we need to flatten them again
|
| 1095 |
+
with open(os.path.join(save_directory, shard_file), mode="wb") as f:
|
| 1096 |
+
params = unflatten_dict(shard, sep="/")
|
| 1097 |
+
shard_bytes = to_bytes(params)
|
| 1098 |
+
f.write(shard_bytes)
|
| 1099 |
+
|
| 1100 |
+
logger.info(f"Model weights saved in {output_model_file}")
|
| 1101 |
+
|
| 1102 |
+
if push_to_hub:
|
| 1103 |
+
self._upload_modified_files(
|
| 1104 |
+
save_directory,
|
| 1105 |
+
repo_id,
|
| 1106 |
+
files_timestamps,
|
| 1107 |
+
commit_message=commit_message,
|
| 1108 |
+
token=kwargs.get("use_auth_token"),
|
| 1109 |
+
)
|
| 1110 |
+
|
| 1111 |
+
@classmethod
|
| 1112 |
+
def register_for_auto_class(cls, auto_class="FlaxAutoModel"):
|
| 1113 |
+
"""
|
| 1114 |
+
Register this class with a given auto class. This should only be used for custom models as the ones in the
|
| 1115 |
+
library are already mapped with an auto class.
|
| 1116 |
+
|
| 1117 |
+
<Tip warning={true}>
|
| 1118 |
+
|
| 1119 |
+
This API is experimental and may have some slight breaking changes in the next releases.
|
| 1120 |
+
|
| 1121 |
+
</Tip>
|
| 1122 |
+
|
| 1123 |
+
Args:
|
| 1124 |
+
auto_class (`str` or `type`, *optional*, defaults to `"FlaxAutoModel"`):
|
| 1125 |
+
The auto class to register this new model with.
|
| 1126 |
+
"""
|
| 1127 |
+
if not isinstance(auto_class, str):
|
| 1128 |
+
auto_class = auto_class.__name__
|
| 1129 |
+
|
| 1130 |
+
import transformers.models.auto as auto_module
|
| 1131 |
+
|
| 1132 |
+
if not hasattr(auto_module, auto_class):
|
| 1133 |
+
raise ValueError(f"{auto_class} is not a valid auto class.")
|
| 1134 |
+
|
| 1135 |
+
cls._auto_class = auto_class
|
| 1136 |
+
|
| 1137 |
+
|
| 1138 |
+
# To update the docstring, we need to copy the method, otherwise we change the original docstring.
|
| 1139 |
+
FlaxPreTrainedModel.push_to_hub = copy_func(FlaxPreTrainedModel.push_to_hub)
|
| 1140 |
+
if FlaxPreTrainedModel.push_to_hub.__doc__ is not None:
|
| 1141 |
+
FlaxPreTrainedModel.push_to_hub.__doc__ = FlaxPreTrainedModel.push_to_hub.__doc__.format(
|
| 1142 |
+
object="model", object_class="FlaxAutoModel", object_files="model checkpoint"
|
| 1143 |
+
)
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
def overwrite_call_docstring(model_class, docstring):
|
| 1147 |
+
# copy __call__ function to be sure docstring is changed only for this function
|
| 1148 |
+
model_class.__call__ = copy_func(model_class.__call__)
|
| 1149 |
+
# delete existing docstring
|
| 1150 |
+
model_class.__call__.__doc__ = None
|
| 1151 |
+
# set correct docstring
|
| 1152 |
+
model_class.__call__ = add_start_docstrings_to_model_forward(docstring)(model_class.__call__)
|
| 1153 |
+
|
| 1154 |
+
|
| 1155 |
+
def append_call_sample_docstring(model_class, checkpoint, output_type, config_class, mask=None):
|
| 1156 |
+
model_class.__call__ = copy_func(model_class.__call__)
|
| 1157 |
+
model_class.__call__ = add_code_sample_docstrings(
|
| 1158 |
+
checkpoint=checkpoint,
|
| 1159 |
+
output_type=output_type,
|
| 1160 |
+
config_class=config_class,
|
| 1161 |
+
model_cls=model_class.__name__,
|
| 1162 |
+
)(model_class.__call__)
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
def append_replace_return_docstrings(model_class, output_type, config_class):
|
| 1166 |
+
model_class.__call__ = copy_func(model_class.__call__)
|
| 1167 |
+
model_class.__call__ = replace_return_docstrings(
|
| 1168 |
+
output_type=output_type,
|
| 1169 |
+
config_class=config_class,
|
| 1170 |
+
)(model_class.__call__)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/modeling_tf_pytorch_utils.py
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
""" PyTorch - TF 2.0 general utilities."""
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
import re
|
| 21 |
+
|
| 22 |
+
import numpy
|
| 23 |
+
|
| 24 |
+
from .utils import ExplicitEnum, expand_dims, is_numpy_array, is_torch_tensor, logging, reshape, squeeze, tensor_size
|
| 25 |
+
from .utils import transpose as transpose_func
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class TransposeType(ExplicitEnum):
|
| 32 |
+
"""
|
| 33 |
+
Possible ...
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
NO = "no"
|
| 37 |
+
SIMPLE = "simple"
|
| 38 |
+
CONV1D = "conv1d"
|
| 39 |
+
CONV2D = "conv2d"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def convert_tf_weight_name_to_pt_weight_name(
|
| 43 |
+
tf_name, start_prefix_to_remove="", tf_weight_shape=None, name_scope=None
|
| 44 |
+
):
|
| 45 |
+
"""
|
| 46 |
+
Convert a TF 2.0 model variable name in a pytorch model weight name.
|
| 47 |
+
|
| 48 |
+
Conventions for TF2.0 scopes -> PyTorch attribute names conversions:
|
| 49 |
+
|
| 50 |
+
- '$1___$2' is replaced by $2 (can be used to duplicate or remove layers in TF2.0 vs PyTorch)
|
| 51 |
+
- '_._' is replaced by a new level separation (can be used to convert TF2.0 lists in PyTorch nn.ModulesList)
|
| 52 |
+
|
| 53 |
+
return tuple with:
|
| 54 |
+
|
| 55 |
+
- pytorch model weight name
|
| 56 |
+
- transpose: `TransposeType` member indicating whether and how TF2.0 and PyTorch weights matrices should be
|
| 57 |
+
transposed with regards to each other
|
| 58 |
+
"""
|
| 59 |
+
if name_scope is not None:
|
| 60 |
+
if not tf_name.startswith(name_scope):
|
| 61 |
+
raise ValueError(
|
| 62 |
+
f"Weight name {tf_name} does not start with name_scope {name_scope}. This is an internal error "
|
| 63 |
+
"in Transformers, so (unless you were doing something really evil) please open an issue to report it!"
|
| 64 |
+
)
|
| 65 |
+
tf_name = tf_name[len(name_scope) :]
|
| 66 |
+
tf_name = tf_name.lstrip("/")
|
| 67 |
+
tf_name = tf_name.replace(":0", "") # device ids
|
| 68 |
+
tf_name = re.sub(
|
| 69 |
+
r"/[^/]*___([^/]*)/", r"/\1/", tf_name
|
| 70 |
+
) # '$1___$2' is replaced by $2 (can be used to duplicate or remove layers in TF2.0 vs PyTorch)
|
| 71 |
+
tf_name = tf_name.replace(
|
| 72 |
+
"_._", "/"
|
| 73 |
+
) # '_._' is replaced by a level separation (can be used to convert TF2.0 lists in PyTorch nn.ModulesList)
|
| 74 |
+
tf_name = re.sub(r"//+", "/", tf_name) # Remove empty levels at the end
|
| 75 |
+
tf_name = tf_name.split("/") # Convert from TF2.0 '/' separators to PyTorch '.' separators
|
| 76 |
+
# Some weights have a single name without "/" such as final_logits_bias in BART
|
| 77 |
+
if len(tf_name) > 1:
|
| 78 |
+
tf_name = tf_name[1:] # Remove level zero
|
| 79 |
+
|
| 80 |
+
tf_weight_shape = list(tf_weight_shape)
|
| 81 |
+
|
| 82 |
+
# When should we transpose the weights
|
| 83 |
+
if tf_name[-1] == "kernel" and tf_weight_shape is not None and len(tf_weight_shape) == 4:
|
| 84 |
+
transpose = TransposeType.CONV2D
|
| 85 |
+
elif tf_name[-1] == "kernel" and tf_weight_shape is not None and len(tf_weight_shape) == 3:
|
| 86 |
+
transpose = TransposeType.CONV1D
|
| 87 |
+
elif bool(
|
| 88 |
+
tf_name[-1] in ["kernel", "pointwise_kernel", "depthwise_kernel"]
|
| 89 |
+
or "emb_projs" in tf_name
|
| 90 |
+
or "out_projs" in tf_name
|
| 91 |
+
):
|
| 92 |
+
transpose = TransposeType.SIMPLE
|
| 93 |
+
else:
|
| 94 |
+
transpose = TransposeType.NO
|
| 95 |
+
|
| 96 |
+
# Convert standard TF2.0 names in PyTorch names
|
| 97 |
+
if tf_name[-1] == "kernel" or tf_name[-1] == "embeddings" or tf_name[-1] == "gamma":
|
| 98 |
+
tf_name[-1] = "weight"
|
| 99 |
+
if tf_name[-1] == "beta":
|
| 100 |
+
tf_name[-1] = "bias"
|
| 101 |
+
|
| 102 |
+
# The SeparableConv1D TF layer contains two weights that are translated to PyTorch Conv1D here
|
| 103 |
+
if tf_name[-1] == "pointwise_kernel" or tf_name[-1] == "depthwise_kernel":
|
| 104 |
+
tf_name[-1] = tf_name[-1].replace("_kernel", ".weight")
|
| 105 |
+
|
| 106 |
+
# Remove prefix if needed
|
| 107 |
+
tf_name = ".".join(tf_name)
|
| 108 |
+
if start_prefix_to_remove:
|
| 109 |
+
tf_name = tf_name.replace(start_prefix_to_remove, "", 1)
|
| 110 |
+
|
| 111 |
+
return tf_name, transpose
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def apply_transpose(transpose: TransposeType, weight, match_shape=None, pt_to_tf=True):
|
| 115 |
+
"""
|
| 116 |
+
Apply a transpose to some weight then tries to reshape the weight to the same shape as a given shape, all in a
|
| 117 |
+
framework agnostic way.
|
| 118 |
+
"""
|
| 119 |
+
if transpose is TransposeType.CONV2D:
|
| 120 |
+
# Conv2D weight:
|
| 121 |
+
# PT: (num_out_channel, num_in_channel, kernel[0], kernel[1])
|
| 122 |
+
# -> TF: (kernel[0], kernel[1], num_in_channel, num_out_channel)
|
| 123 |
+
axes = (2, 3, 1, 0) if pt_to_tf else (3, 2, 0, 1)
|
| 124 |
+
weight = transpose_func(weight, axes=axes)
|
| 125 |
+
elif transpose is TransposeType.CONV1D:
|
| 126 |
+
# Conv1D weight:
|
| 127 |
+
# PT: (num_out_channel, num_in_channel, kernel)
|
| 128 |
+
# -> TF: (kernel, num_in_channel, num_out_channel)
|
| 129 |
+
weight = transpose_func(weight, axes=(2, 1, 0))
|
| 130 |
+
elif transpose is TransposeType.SIMPLE:
|
| 131 |
+
weight = transpose_func(weight)
|
| 132 |
+
|
| 133 |
+
if match_shape is None:
|
| 134 |
+
return weight
|
| 135 |
+
|
| 136 |
+
if len(match_shape) < len(weight.shape):
|
| 137 |
+
weight = squeeze(weight)
|
| 138 |
+
elif len(match_shape) > len(weight.shape):
|
| 139 |
+
weight = expand_dims(weight, axis=0)
|
| 140 |
+
|
| 141 |
+
if list(match_shape) != list(weight.shape):
|
| 142 |
+
try:
|
| 143 |
+
weight = reshape(weight, match_shape)
|
| 144 |
+
except AssertionError as e:
|
| 145 |
+
e.args += (match_shape, match_shape)
|
| 146 |
+
raise e
|
| 147 |
+
|
| 148 |
+
return weight
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
#####################
|
| 152 |
+
# PyTorch => TF 2.0 #
|
| 153 |
+
#####################
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def load_pytorch_checkpoint_in_tf2_model(
|
| 157 |
+
tf_model,
|
| 158 |
+
pytorch_checkpoint_path,
|
| 159 |
+
tf_inputs=None,
|
| 160 |
+
allow_missing_keys=False,
|
| 161 |
+
output_loading_info=False,
|
| 162 |
+
_prefix=None,
|
| 163 |
+
tf_to_pt_weight_rename=None,
|
| 164 |
+
):
|
| 165 |
+
"""Load pytorch checkpoints in a TF 2.0 model"""
|
| 166 |
+
try:
|
| 167 |
+
import tensorflow as tf # noqa: F401
|
| 168 |
+
import torch # noqa: F401
|
| 169 |
+
except ImportError:
|
| 170 |
+
logger.error(
|
| 171 |
+
"Loading a PyTorch model in TensorFlow, requires both PyTorch and TensorFlow to be installed. Please see "
|
| 172 |
+
"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions."
|
| 173 |
+
)
|
| 174 |
+
raise
|
| 175 |
+
|
| 176 |
+
# Treats a single file as a collection of shards with 1 shard.
|
| 177 |
+
if isinstance(pytorch_checkpoint_path, str):
|
| 178 |
+
pytorch_checkpoint_path = [pytorch_checkpoint_path]
|
| 179 |
+
|
| 180 |
+
# Loads all shards into a single state dictionary
|
| 181 |
+
pt_state_dict = {}
|
| 182 |
+
for path in pytorch_checkpoint_path:
|
| 183 |
+
pt_path = os.path.abspath(path)
|
| 184 |
+
logger.info(f"Loading PyTorch weights from {pt_path}")
|
| 185 |
+
pt_state_dict.update(torch.load(pt_path, map_location="cpu"))
|
| 186 |
+
|
| 187 |
+
logger.info(f"PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values()):,} parameters")
|
| 188 |
+
|
| 189 |
+
return load_pytorch_weights_in_tf2_model(
|
| 190 |
+
tf_model,
|
| 191 |
+
pt_state_dict,
|
| 192 |
+
tf_inputs=tf_inputs,
|
| 193 |
+
allow_missing_keys=allow_missing_keys,
|
| 194 |
+
output_loading_info=output_loading_info,
|
| 195 |
+
_prefix=_prefix,
|
| 196 |
+
tf_to_pt_weight_rename=tf_to_pt_weight_rename,
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def load_pytorch_model_in_tf2_model(tf_model, pt_model, tf_inputs=None, allow_missing_keys=False):
|
| 201 |
+
"""Load pytorch checkpoints in a TF 2.0 model"""
|
| 202 |
+
pt_state_dict = pt_model.state_dict()
|
| 203 |
+
|
| 204 |
+
return load_pytorch_weights_in_tf2_model(
|
| 205 |
+
tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def load_pytorch_weights_in_tf2_model(
|
| 210 |
+
tf_model,
|
| 211 |
+
pt_state_dict,
|
| 212 |
+
tf_inputs=None,
|
| 213 |
+
allow_missing_keys=False,
|
| 214 |
+
output_loading_info=False,
|
| 215 |
+
_prefix=None,
|
| 216 |
+
tf_to_pt_weight_rename=None,
|
| 217 |
+
):
|
| 218 |
+
"""Load pytorch state_dict in a TF 2.0 model."""
|
| 219 |
+
try:
|
| 220 |
+
import tensorflow as tf # noqa: F401
|
| 221 |
+
import torch # noqa: F401
|
| 222 |
+
except ImportError:
|
| 223 |
+
logger.error(
|
| 224 |
+
"Loading a PyTorch model in TensorFlow, requires both PyTorch and TensorFlow to be installed. Please see "
|
| 225 |
+
"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions."
|
| 226 |
+
)
|
| 227 |
+
raise
|
| 228 |
+
|
| 229 |
+
pt_state_dict = {k: v.numpy() for k, v in pt_state_dict.items()}
|
| 230 |
+
return load_pytorch_state_dict_in_tf2_model(
|
| 231 |
+
tf_model,
|
| 232 |
+
pt_state_dict,
|
| 233 |
+
tf_inputs=tf_inputs,
|
| 234 |
+
allow_missing_keys=allow_missing_keys,
|
| 235 |
+
output_loading_info=output_loading_info,
|
| 236 |
+
_prefix=_prefix,
|
| 237 |
+
tf_to_pt_weight_rename=tf_to_pt_weight_rename,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def load_pytorch_state_dict_in_tf2_model(
|
| 242 |
+
tf_model,
|
| 243 |
+
pt_state_dict,
|
| 244 |
+
tf_inputs=None,
|
| 245 |
+
allow_missing_keys=False,
|
| 246 |
+
output_loading_info=False,
|
| 247 |
+
_prefix=None,
|
| 248 |
+
tf_to_pt_weight_rename=None,
|
| 249 |
+
ignore_mismatched_sizes=False,
|
| 250 |
+
):
|
| 251 |
+
"""Load a pytorch state_dict in a TF 2.0 model."""
|
| 252 |
+
import tensorflow as tf
|
| 253 |
+
from packaging.version import parse
|
| 254 |
+
|
| 255 |
+
if parse(tf.__version__) >= parse("2.11.0"):
|
| 256 |
+
from keras import backend as K
|
| 257 |
+
else:
|
| 258 |
+
from tensorflow.python.keras import backend as K
|
| 259 |
+
|
| 260 |
+
if tf_inputs is None:
|
| 261 |
+
tf_inputs = tf_model.dummy_inputs
|
| 262 |
+
|
| 263 |
+
if _prefix is None:
|
| 264 |
+
_prefix = ""
|
| 265 |
+
if tf_inputs is not None:
|
| 266 |
+
with tf.name_scope(_prefix):
|
| 267 |
+
tf_model(tf_inputs, training=False) # Make sure model is built
|
| 268 |
+
# Adapt state dict - TODO remove this and update the AWS weights files instead
|
| 269 |
+
# Convert old format to new format if needed from a PyTorch state_dict
|
| 270 |
+
old_keys = []
|
| 271 |
+
new_keys = []
|
| 272 |
+
for key in pt_state_dict.keys():
|
| 273 |
+
new_key = None
|
| 274 |
+
if "gamma" in key:
|
| 275 |
+
new_key = key.replace("gamma", "weight")
|
| 276 |
+
if "beta" in key:
|
| 277 |
+
new_key = key.replace("beta", "bias")
|
| 278 |
+
if "running_var" in key:
|
| 279 |
+
new_key = key.replace("running_var", "moving_variance")
|
| 280 |
+
if "running_mean" in key:
|
| 281 |
+
new_key = key.replace("running_mean", "moving_mean")
|
| 282 |
+
if new_key:
|
| 283 |
+
old_keys.append(key)
|
| 284 |
+
new_keys.append(new_key)
|
| 285 |
+
for old_key, new_key in zip(old_keys, new_keys):
|
| 286 |
+
pt_state_dict[new_key] = pt_state_dict.pop(old_key)
|
| 287 |
+
|
| 288 |
+
# Matt: All TF models store the actual model stem in a MainLayer class, including the base model.
|
| 289 |
+
# In PT, the derived models (with heads) use the base model class as the stem instead, and the base model
|
| 290 |
+
# just contains the stem itself, and there is no MainLayer class. This means that TF base classes have one
|
| 291 |
+
# extra layer in their weight names, corresponding to the MainLayer class. This code block compensates for that.
|
| 292 |
+
start_prefix_to_remove = ""
|
| 293 |
+
if not any(s.startswith(tf_model.base_model_prefix) for s in pt_state_dict.keys()):
|
| 294 |
+
start_prefix_to_remove = tf_model.base_model_prefix + "."
|
| 295 |
+
|
| 296 |
+
symbolic_weights = tf_model.trainable_weights + tf_model.non_trainable_weights
|
| 297 |
+
tf_loaded_numel = 0
|
| 298 |
+
weight_value_tuples = []
|
| 299 |
+
all_pytorch_weights = set(pt_state_dict.keys())
|
| 300 |
+
missing_keys = []
|
| 301 |
+
mismatched_keys = []
|
| 302 |
+
for symbolic_weight in symbolic_weights:
|
| 303 |
+
sw_name = symbolic_weight.name
|
| 304 |
+
name, transpose = convert_tf_weight_name_to_pt_weight_name(
|
| 305 |
+
sw_name,
|
| 306 |
+
start_prefix_to_remove=start_prefix_to_remove,
|
| 307 |
+
tf_weight_shape=symbolic_weight.shape,
|
| 308 |
+
name_scope=_prefix,
|
| 309 |
+
)
|
| 310 |
+
if tf_to_pt_weight_rename is not None:
|
| 311 |
+
name = tf_to_pt_weight_rename(name)
|
| 312 |
+
|
| 313 |
+
# Find associated numpy array in pytorch model state dict
|
| 314 |
+
if name not in pt_state_dict:
|
| 315 |
+
if allow_missing_keys:
|
| 316 |
+
missing_keys.append(name)
|
| 317 |
+
continue
|
| 318 |
+
elif tf_model._keys_to_ignore_on_load_missing is not None:
|
| 319 |
+
# authorized missing keys don't have to be loaded
|
| 320 |
+
if any(re.search(pat, name) is not None for pat in tf_model._keys_to_ignore_on_load_missing):
|
| 321 |
+
continue
|
| 322 |
+
raise AttributeError(f"{name} not found in PyTorch model")
|
| 323 |
+
|
| 324 |
+
try:
|
| 325 |
+
array = apply_transpose(transpose, pt_state_dict[name], symbolic_weight.shape)
|
| 326 |
+
except tf.errors.InvalidArgumentError as e:
|
| 327 |
+
if not ignore_mismatched_sizes:
|
| 328 |
+
error_msg = str(e)
|
| 329 |
+
error_msg += (
|
| 330 |
+
"\n\tYou may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method."
|
| 331 |
+
)
|
| 332 |
+
raise tf.errors.InvalidArgumentError(error_msg)
|
| 333 |
+
else:
|
| 334 |
+
mismatched_keys.append((name, pt_state_dict[name].shape, symbolic_weight.shape))
|
| 335 |
+
continue
|
| 336 |
+
|
| 337 |
+
tf_loaded_numel += tensor_size(array)
|
| 338 |
+
|
| 339 |
+
weight_value_tuples.append((symbolic_weight, array))
|
| 340 |
+
all_pytorch_weights.discard(name)
|
| 341 |
+
|
| 342 |
+
K.batch_set_value(weight_value_tuples)
|
| 343 |
+
|
| 344 |
+
if tf_inputs is not None:
|
| 345 |
+
tf_model(tf_inputs, training=False) # Make sure restore ops are run
|
| 346 |
+
|
| 347 |
+
logger.info(f"Loaded {tf_loaded_numel:,} parameters in the TF 2.0 model.")
|
| 348 |
+
|
| 349 |
+
unexpected_keys = list(all_pytorch_weights)
|
| 350 |
+
|
| 351 |
+
if tf_model._keys_to_ignore_on_load_missing is not None:
|
| 352 |
+
for pat in tf_model._keys_to_ignore_on_load_missing:
|
| 353 |
+
missing_keys = [k for k in missing_keys if re.search(pat, k) is None]
|
| 354 |
+
if tf_model._keys_to_ignore_on_load_unexpected is not None:
|
| 355 |
+
for pat in tf_model._keys_to_ignore_on_load_unexpected:
|
| 356 |
+
unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
|
| 357 |
+
|
| 358 |
+
if len(unexpected_keys) > 0:
|
| 359 |
+
logger.warning(
|
| 360 |
+
"Some weights of the PyTorch model were not used when initializing the TF 2.0 model"
|
| 361 |
+
f" {tf_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing"
|
| 362 |
+
f" {tf_model.__class__.__name__} from a PyTorch model trained on another task or with another architecture"
|
| 363 |
+
" (e.g. initializing a TFBertForSequenceClassification model from a BertForPreTraining model).\n- This IS"
|
| 364 |
+
f" NOT expected if you are initializing {tf_model.__class__.__name__} from a PyTorch model that you expect"
|
| 365 |
+
" to be exactly identical (e.g. initializing a TFBertForSequenceClassification model from a"
|
| 366 |
+
" BertForSequenceClassification model)."
|
| 367 |
+
)
|
| 368 |
+
else:
|
| 369 |
+
logger.warning(f"All PyTorch model weights were used when initializing {tf_model.__class__.__name__}.\n")
|
| 370 |
+
if len(missing_keys) > 0:
|
| 371 |
+
logger.warning(
|
| 372 |
+
f"Some weights or buffers of the TF 2.0 model {tf_model.__class__.__name__} were not initialized from the"
|
| 373 |
+
f" PyTorch model and are newly initialized: {missing_keys}\nYou should probably TRAIN this model on a"
|
| 374 |
+
" down-stream task to be able to use it for predictions and inference."
|
| 375 |
+
)
|
| 376 |
+
else:
|
| 377 |
+
logger.warning(
|
| 378 |
+
f"All the weights of {tf_model.__class__.__name__} were initialized from the PyTorch model.\n"
|
| 379 |
+
"If your task is similar to the task the model of the checkpoint was trained on, "
|
| 380 |
+
f"you can already use {tf_model.__class__.__name__} for predictions without further training."
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
if len(mismatched_keys) > 0:
|
| 384 |
+
mismatched_warning = "\n".join(
|
| 385 |
+
[
|
| 386 |
+
f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated"
|
| 387 |
+
for key, shape1, shape2 in mismatched_keys
|
| 388 |
+
]
|
| 389 |
+
)
|
| 390 |
+
logger.warning(
|
| 391 |
+
f"Some weights of {tf_model.__class__.__name__} were not initialized from the model checkpoint"
|
| 392 |
+
f" are newly initialized because the shapes did not"
|
| 393 |
+
f" match:\n{mismatched_warning}\nYou should probably TRAIN this model on a down-stream task to be able"
|
| 394 |
+
" to use it for predictions and inference."
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
if output_loading_info:
|
| 398 |
+
loading_info = {
|
| 399 |
+
"missing_keys": missing_keys,
|
| 400 |
+
"unexpected_keys": unexpected_keys,
|
| 401 |
+
"mismatched_keys": mismatched_keys,
|
| 402 |
+
}
|
| 403 |
+
return tf_model, loading_info
|
| 404 |
+
|
| 405 |
+
return tf_model
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
#####################
|
| 409 |
+
# TF 2.0 => PyTorch #
|
| 410 |
+
#####################
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def load_tf2_checkpoint_in_pytorch_model(
|
| 414 |
+
pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False, output_loading_info=False
|
| 415 |
+
):
|
| 416 |
+
"""
|
| 417 |
+
Load TF 2.0 HDF5 checkpoint in a PyTorch model We use HDF5 to easily do transfer learning (see
|
| 418 |
+
https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357).
|
| 419 |
+
"""
|
| 420 |
+
try:
|
| 421 |
+
import tensorflow as tf # noqa: F401
|
| 422 |
+
import torch # noqa: F401
|
| 423 |
+
except ImportError:
|
| 424 |
+
logger.error(
|
| 425 |
+
"Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see "
|
| 426 |
+
"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions."
|
| 427 |
+
)
|
| 428 |
+
raise
|
| 429 |
+
|
| 430 |
+
import transformers
|
| 431 |
+
|
| 432 |
+
from .modeling_tf_utils import load_tf_weights
|
| 433 |
+
|
| 434 |
+
logger.info(f"Loading TensorFlow weights from {tf_checkpoint_path}")
|
| 435 |
+
|
| 436 |
+
# Instantiate and load the associated TF 2.0 model
|
| 437 |
+
tf_model_class_name = "TF" + pt_model.__class__.__name__ # Add "TF" at the beginning
|
| 438 |
+
tf_model_class = getattr(transformers, tf_model_class_name)
|
| 439 |
+
tf_model = tf_model_class(pt_model.config)
|
| 440 |
+
|
| 441 |
+
if tf_inputs is None:
|
| 442 |
+
tf_inputs = tf_model.dummy_inputs
|
| 443 |
+
|
| 444 |
+
if tf_inputs is not None:
|
| 445 |
+
tf_model(tf_inputs, training=False) # Make sure model is built
|
| 446 |
+
|
| 447 |
+
load_tf_weights(tf_model, tf_checkpoint_path)
|
| 448 |
+
|
| 449 |
+
return load_tf2_model_in_pytorch_model(
|
| 450 |
+
pt_model, tf_model, allow_missing_keys=allow_missing_keys, output_loading_info=output_loading_info
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False, output_loading_info=False):
|
| 455 |
+
"""Load TF 2.0 model in a pytorch model"""
|
| 456 |
+
weights = tf_model.weights
|
| 457 |
+
|
| 458 |
+
return load_tf2_weights_in_pytorch_model(
|
| 459 |
+
pt_model, weights, allow_missing_keys=allow_missing_keys, output_loading_info=output_loading_info
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False, output_loading_info=False):
|
| 464 |
+
"""Load TF2.0 symbolic weights in a PyTorch model"""
|
| 465 |
+
try:
|
| 466 |
+
import tensorflow as tf # noqa: F401
|
| 467 |
+
import torch # noqa: F401
|
| 468 |
+
except ImportError:
|
| 469 |
+
logger.error(
|
| 470 |
+
"Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see "
|
| 471 |
+
"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions."
|
| 472 |
+
)
|
| 473 |
+
raise
|
| 474 |
+
|
| 475 |
+
tf_state_dict = {tf_weight.name: tf_weight.numpy() for tf_weight in tf_weights}
|
| 476 |
+
return load_tf2_state_dict_in_pytorch_model(
|
| 477 |
+
pt_model, tf_state_dict, allow_missing_keys=allow_missing_keys, output_loading_info=output_loading_info
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def load_tf2_state_dict_in_pytorch_model(pt_model, tf_state_dict, allow_missing_keys=False, output_loading_info=False):
|
| 482 |
+
import torch
|
| 483 |
+
|
| 484 |
+
new_pt_params_dict = {}
|
| 485 |
+
current_pt_params_dict = dict(pt_model.named_parameters())
|
| 486 |
+
|
| 487 |
+
# Make sure we are able to load PyTorch base models as well as derived models (with heads)
|
| 488 |
+
# TF models always have a prefix, some of PyTorch models (base ones) don't
|
| 489 |
+
start_prefix_to_remove = ""
|
| 490 |
+
if not any(s.startswith(pt_model.base_model_prefix) for s in current_pt_params_dict.keys()):
|
| 491 |
+
start_prefix_to_remove = pt_model.base_model_prefix + "."
|
| 492 |
+
|
| 493 |
+
# Build a map from potential PyTorch weight names to TF 2.0 Variables
|
| 494 |
+
tf_weights_map = {}
|
| 495 |
+
for name, tf_weight in tf_state_dict.items():
|
| 496 |
+
pt_name, transpose = convert_tf_weight_name_to_pt_weight_name(
|
| 497 |
+
name, start_prefix_to_remove=start_prefix_to_remove, tf_weight_shape=tf_weight.shape
|
| 498 |
+
)
|
| 499 |
+
tf_weights_map[pt_name] = (tf_weight, transpose)
|
| 500 |
+
|
| 501 |
+
all_tf_weights = set(tf_weights_map.keys())
|
| 502 |
+
loaded_pt_weights_data_ptr = {}
|
| 503 |
+
missing_keys_pt = []
|
| 504 |
+
for pt_weight_name, pt_weight in current_pt_params_dict.items():
|
| 505 |
+
# Handle PyTorch shared weight ()not duplicated in TF 2.0
|
| 506 |
+
if pt_weight.data_ptr() in loaded_pt_weights_data_ptr:
|
| 507 |
+
new_pt_params_dict[pt_weight_name] = loaded_pt_weights_data_ptr[pt_weight.data_ptr()]
|
| 508 |
+
continue
|
| 509 |
+
|
| 510 |
+
# Find associated numpy array in pytorch model state dict
|
| 511 |
+
if pt_weight_name not in tf_weights_map:
|
| 512 |
+
if allow_missing_keys:
|
| 513 |
+
missing_keys_pt.append(pt_weight_name)
|
| 514 |
+
continue
|
| 515 |
+
|
| 516 |
+
raise AttributeError(f"{pt_weight_name} not found in TF 2.0 model")
|
| 517 |
+
|
| 518 |
+
array, transpose = tf_weights_map[pt_weight_name]
|
| 519 |
+
|
| 520 |
+
array = apply_transpose(transpose, array, pt_weight.shape, pt_to_tf=False)
|
| 521 |
+
|
| 522 |
+
if numpy.isscalar(array):
|
| 523 |
+
array = numpy.array(array)
|
| 524 |
+
if not is_torch_tensor(array) and not is_numpy_array(array):
|
| 525 |
+
array = array.numpy()
|
| 526 |
+
if is_numpy_array(array):
|
| 527 |
+
# Convert to torch tensor
|
| 528 |
+
array = torch.from_numpy(array)
|
| 529 |
+
|
| 530 |
+
new_pt_params_dict[pt_weight_name] = array
|
| 531 |
+
loaded_pt_weights_data_ptr[pt_weight.data_ptr()] = array
|
| 532 |
+
all_tf_weights.discard(pt_weight_name)
|
| 533 |
+
|
| 534 |
+
missing_keys, unexpected_keys = pt_model.load_state_dict(new_pt_params_dict, strict=False)
|
| 535 |
+
missing_keys += missing_keys_pt
|
| 536 |
+
|
| 537 |
+
# Some models may have keys that are not in the state by design, removing them before needlessly warning
|
| 538 |
+
# the user.
|
| 539 |
+
if pt_model._keys_to_ignore_on_load_missing is not None:
|
| 540 |
+
for pat in pt_model._keys_to_ignore_on_load_missing:
|
| 541 |
+
missing_keys = [k for k in missing_keys if re.search(pat, k) is None]
|
| 542 |
+
|
| 543 |
+
if pt_model._keys_to_ignore_on_load_unexpected is not None:
|
| 544 |
+
for pat in pt_model._keys_to_ignore_on_load_unexpected:
|
| 545 |
+
unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
|
| 546 |
+
|
| 547 |
+
if len(unexpected_keys) > 0:
|
| 548 |
+
logger.warning(
|
| 549 |
+
"Some weights of the TF 2.0 model were not used when initializing the PyTorch model"
|
| 550 |
+
f" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing"
|
| 551 |
+
f" {pt_model.__class__.__name__} from a TF 2.0 model trained on another task or with another architecture"
|
| 552 |
+
" (e.g. initializing a BertForSequenceClassification model from a TFBertForPreTraining model).\n- This IS"
|
| 553 |
+
f" NOT expected if you are initializing {pt_model.__class__.__name__} from a TF 2.0 model that you expect"
|
| 554 |
+
" to be exactly identical (e.g. initializing a BertForSequenceClassification model from a"
|
| 555 |
+
" TFBertForSequenceClassification model)."
|
| 556 |
+
)
|
| 557 |
+
else:
|
| 558 |
+
logger.warning(f"All TF 2.0 model weights were used when initializing {pt_model.__class__.__name__}.\n")
|
| 559 |
+
if len(missing_keys) > 0:
|
| 560 |
+
logger.warning(
|
| 561 |
+
f"Some weights of {pt_model.__class__.__name__} were not initialized from the TF 2.0 model and are newly"
|
| 562 |
+
f" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to"
|
| 563 |
+
" use it for predictions and inference."
|
| 564 |
+
)
|
| 565 |
+
else:
|
| 566 |
+
logger.warning(
|
| 567 |
+
f"All the weights of {pt_model.__class__.__name__} were initialized from the TF 2.0 model.\n"
|
| 568 |
+
"If your task is similar to the task the model of the checkpoint was trained on, "
|
| 569 |
+
f"you can already use {pt_model.__class__.__name__} for predictions without further training."
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
logger.info(f"Weights or buffers not loaded from TF 2.0 model: {all_tf_weights}")
|
| 573 |
+
|
| 574 |
+
if output_loading_info:
|
| 575 |
+
loading_info = {"missing_keys": missing_keys, "unexpected_keys": unexpected_keys}
|
| 576 |
+
return pt_model, loading_info
|
| 577 |
+
|
| 578 |
+
return pt_model
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/__init__.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ...utils import (
|
| 18 |
+
OptionalDependencyNotAvailable,
|
| 19 |
+
_LazyModule,
|
| 20 |
+
is_flax_available,
|
| 21 |
+
is_sentencepiece_available,
|
| 22 |
+
is_tf_available,
|
| 23 |
+
is_tokenizers_available,
|
| 24 |
+
is_torch_available,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
_import_structure = {
|
| 29 |
+
"configuration_albert": ["ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "AlbertConfig", "AlbertOnnxConfig"],
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
if not is_sentencepiece_available():
|
| 34 |
+
raise OptionalDependencyNotAvailable()
|
| 35 |
+
except OptionalDependencyNotAvailable:
|
| 36 |
+
pass
|
| 37 |
+
else:
|
| 38 |
+
_import_structure["tokenization_albert"] = ["AlbertTokenizer"]
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
if not is_tokenizers_available():
|
| 42 |
+
raise OptionalDependencyNotAvailable()
|
| 43 |
+
except OptionalDependencyNotAvailable:
|
| 44 |
+
pass
|
| 45 |
+
else:
|
| 46 |
+
_import_structure["tokenization_albert_fast"] = ["AlbertTokenizerFast"]
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
if not is_torch_available():
|
| 50 |
+
raise OptionalDependencyNotAvailable()
|
| 51 |
+
except OptionalDependencyNotAvailable:
|
| 52 |
+
pass
|
| 53 |
+
else:
|
| 54 |
+
_import_structure["modeling_albert"] = [
|
| 55 |
+
"ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 56 |
+
"AlbertForMaskedLM",
|
| 57 |
+
"AlbertForMultipleChoice",
|
| 58 |
+
"AlbertForPreTraining",
|
| 59 |
+
"AlbertForQuestionAnswering",
|
| 60 |
+
"AlbertForSequenceClassification",
|
| 61 |
+
"AlbertForTokenClassification",
|
| 62 |
+
"AlbertModel",
|
| 63 |
+
"AlbertPreTrainedModel",
|
| 64 |
+
"load_tf_weights_in_albert",
|
| 65 |
+
]
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
if not is_tf_available():
|
| 69 |
+
raise OptionalDependencyNotAvailable()
|
| 70 |
+
except OptionalDependencyNotAvailable:
|
| 71 |
+
pass
|
| 72 |
+
else:
|
| 73 |
+
_import_structure["modeling_tf_albert"] = [
|
| 74 |
+
"TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 75 |
+
"TFAlbertForMaskedLM",
|
| 76 |
+
"TFAlbertForMultipleChoice",
|
| 77 |
+
"TFAlbertForPreTraining",
|
| 78 |
+
"TFAlbertForQuestionAnswering",
|
| 79 |
+
"TFAlbertForSequenceClassification",
|
| 80 |
+
"TFAlbertForTokenClassification",
|
| 81 |
+
"TFAlbertMainLayer",
|
| 82 |
+
"TFAlbertModel",
|
| 83 |
+
"TFAlbertPreTrainedModel",
|
| 84 |
+
]
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
if not is_flax_available():
|
| 88 |
+
raise OptionalDependencyNotAvailable()
|
| 89 |
+
except OptionalDependencyNotAvailable:
|
| 90 |
+
pass
|
| 91 |
+
else:
|
| 92 |
+
_import_structure["modeling_flax_albert"] = [
|
| 93 |
+
"FlaxAlbertForMaskedLM",
|
| 94 |
+
"FlaxAlbertForMultipleChoice",
|
| 95 |
+
"FlaxAlbertForPreTraining",
|
| 96 |
+
"FlaxAlbertForQuestionAnswering",
|
| 97 |
+
"FlaxAlbertForSequenceClassification",
|
| 98 |
+
"FlaxAlbertForTokenClassification",
|
| 99 |
+
"FlaxAlbertModel",
|
| 100 |
+
"FlaxAlbertPreTrainedModel",
|
| 101 |
+
]
|
| 102 |
+
|
| 103 |
+
if TYPE_CHECKING:
|
| 104 |
+
from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
if not is_sentencepiece_available():
|
| 108 |
+
raise OptionalDependencyNotAvailable()
|
| 109 |
+
except OptionalDependencyNotAvailable:
|
| 110 |
+
pass
|
| 111 |
+
else:
|
| 112 |
+
from .tokenization_albert import AlbertTokenizer
|
| 113 |
+
|
| 114 |
+
try:
|
| 115 |
+
if not is_tokenizers_available():
|
| 116 |
+
raise OptionalDependencyNotAvailable()
|
| 117 |
+
except OptionalDependencyNotAvailable:
|
| 118 |
+
pass
|
| 119 |
+
else:
|
| 120 |
+
from .tokenization_albert_fast import AlbertTokenizerFast
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
if not is_torch_available():
|
| 124 |
+
raise OptionalDependencyNotAvailable()
|
| 125 |
+
except OptionalDependencyNotAvailable:
|
| 126 |
+
pass
|
| 127 |
+
else:
|
| 128 |
+
from .modeling_albert import (
|
| 129 |
+
ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 130 |
+
AlbertForMaskedLM,
|
| 131 |
+
AlbertForMultipleChoice,
|
| 132 |
+
AlbertForPreTraining,
|
| 133 |
+
AlbertForQuestionAnswering,
|
| 134 |
+
AlbertForSequenceClassification,
|
| 135 |
+
AlbertForTokenClassification,
|
| 136 |
+
AlbertModel,
|
| 137 |
+
AlbertPreTrainedModel,
|
| 138 |
+
load_tf_weights_in_albert,
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
try:
|
| 142 |
+
if not is_tf_available():
|
| 143 |
+
raise OptionalDependencyNotAvailable()
|
| 144 |
+
except OptionalDependencyNotAvailable:
|
| 145 |
+
pass
|
| 146 |
+
else:
|
| 147 |
+
from .modeling_tf_albert import (
|
| 148 |
+
TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 149 |
+
TFAlbertForMaskedLM,
|
| 150 |
+
TFAlbertForMultipleChoice,
|
| 151 |
+
TFAlbertForPreTraining,
|
| 152 |
+
TFAlbertForQuestionAnswering,
|
| 153 |
+
TFAlbertForSequenceClassification,
|
| 154 |
+
TFAlbertForTokenClassification,
|
| 155 |
+
TFAlbertMainLayer,
|
| 156 |
+
TFAlbertModel,
|
| 157 |
+
TFAlbertPreTrainedModel,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
try:
|
| 161 |
+
if not is_flax_available():
|
| 162 |
+
raise OptionalDependencyNotAvailable()
|
| 163 |
+
except OptionalDependencyNotAvailable:
|
| 164 |
+
pass
|
| 165 |
+
else:
|
| 166 |
+
from .modeling_flax_albert import (
|
| 167 |
+
FlaxAlbertForMaskedLM,
|
| 168 |
+
FlaxAlbertForMultipleChoice,
|
| 169 |
+
FlaxAlbertForPreTraining,
|
| 170 |
+
FlaxAlbertForQuestionAnswering,
|
| 171 |
+
FlaxAlbertForSequenceClassification,
|
| 172 |
+
FlaxAlbertForTokenClassification,
|
| 173 |
+
FlaxAlbertModel,
|
| 174 |
+
FlaxAlbertPreTrainedModel,
|
| 175 |
+
)
|
| 176 |
+
else:
|
| 177 |
+
import sys
|
| 178 |
+
|
| 179 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/configuration_albert.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
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|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
""" ALBERT model configuration"""
|
| 17 |
+
from collections import OrderedDict
|
| 18 |
+
from typing import Mapping
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PretrainedConfig
|
| 21 |
+
from ...onnx import OnnxConfig
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 25 |
+
"albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/config.json",
|
| 26 |
+
"albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/config.json",
|
| 27 |
+
"albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/config.json",
|
| 28 |
+
"albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json",
|
| 29 |
+
"albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/config.json",
|
| 30 |
+
"albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/config.json",
|
| 31 |
+
"albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/config.json",
|
| 32 |
+
"albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json",
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class AlbertConfig(PretrainedConfig):
|
| 37 |
+
r"""
|
| 38 |
+
This is the configuration class to store the configuration of a [`AlbertModel`] or a [`TFAlbertModel`]. It is used
|
| 39 |
+
to instantiate an ALBERT model according to the specified arguments, defining the model architecture. Instantiating
|
| 40 |
+
a configuration with the defaults will yield a similar configuration to that of the ALBERT
|
| 41 |
+
[albert-xxlarge-v2](https://huggingface.co/albert-xxlarge-v2) architecture.
|
| 42 |
+
|
| 43 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 44 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
vocab_size (`int`, *optional*, defaults to 30000):
|
| 48 |
+
Vocabulary size of the ALBERT model. Defines the number of different tokens that can be represented by the
|
| 49 |
+
`inputs_ids` passed when calling [`AlbertModel`] or [`TFAlbertModel`].
|
| 50 |
+
embedding_size (`int`, *optional*, defaults to 128):
|
| 51 |
+
Dimensionality of vocabulary embeddings.
|
| 52 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 53 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 54 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 55 |
+
Number of hidden layers in the Transformer encoder.
|
| 56 |
+
num_hidden_groups (`int`, *optional*, defaults to 1):
|
| 57 |
+
Number of groups for the hidden layers, parameters in the same group are shared.
|
| 58 |
+
num_attention_heads (`int`, *optional*, defaults to 64):
|
| 59 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 60 |
+
intermediate_size (`int`, *optional*, defaults to 16384):
|
| 61 |
+
The dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 62 |
+
inner_group_num (`int`, *optional*, defaults to 1):
|
| 63 |
+
The number of inner repetition of attention and ffn.
|
| 64 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu_new"`):
|
| 65 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 66 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 67 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0):
|
| 68 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 69 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0):
|
| 70 |
+
The dropout ratio for the attention probabilities.
|
| 71 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 72 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 73 |
+
(e.g., 512 or 1024 or 2048).
|
| 74 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 75 |
+
The vocabulary size of the `token_type_ids` passed when calling [`AlbertModel`] or [`TFAlbertModel`].
|
| 76 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 77 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 78 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 79 |
+
The epsilon used by the layer normalization layers.
|
| 80 |
+
classifier_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 81 |
+
The dropout ratio for attached classifiers.
|
| 82 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 83 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 84 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 85 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 86 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 87 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 88 |
+
|
| 89 |
+
Examples:
|
| 90 |
+
|
| 91 |
+
```python
|
| 92 |
+
>>> from transformers import AlbertConfig, AlbertModel
|
| 93 |
+
|
| 94 |
+
>>> # Initializing an ALBERT-xxlarge style configuration
|
| 95 |
+
>>> albert_xxlarge_configuration = AlbertConfig()
|
| 96 |
+
|
| 97 |
+
>>> # Initializing an ALBERT-base style configuration
|
| 98 |
+
>>> albert_base_configuration = AlbertConfig(
|
| 99 |
+
... hidden_size=768,
|
| 100 |
+
... num_attention_heads=12,
|
| 101 |
+
... intermediate_size=3072,
|
| 102 |
+
... )
|
| 103 |
+
|
| 104 |
+
>>> # Initializing a model (with random weights) from the ALBERT-base style configuration
|
| 105 |
+
>>> model = AlbertModel(albert_xxlarge_configuration)
|
| 106 |
+
|
| 107 |
+
>>> # Accessing the model configuration
|
| 108 |
+
>>> configuration = model.config
|
| 109 |
+
```"""
|
| 110 |
+
|
| 111 |
+
model_type = "albert"
|
| 112 |
+
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
vocab_size=30000,
|
| 116 |
+
embedding_size=128,
|
| 117 |
+
hidden_size=4096,
|
| 118 |
+
num_hidden_layers=12,
|
| 119 |
+
num_hidden_groups=1,
|
| 120 |
+
num_attention_heads=64,
|
| 121 |
+
intermediate_size=16384,
|
| 122 |
+
inner_group_num=1,
|
| 123 |
+
hidden_act="gelu_new",
|
| 124 |
+
hidden_dropout_prob=0,
|
| 125 |
+
attention_probs_dropout_prob=0,
|
| 126 |
+
max_position_embeddings=512,
|
| 127 |
+
type_vocab_size=2,
|
| 128 |
+
initializer_range=0.02,
|
| 129 |
+
layer_norm_eps=1e-12,
|
| 130 |
+
classifier_dropout_prob=0.1,
|
| 131 |
+
position_embedding_type="absolute",
|
| 132 |
+
pad_token_id=0,
|
| 133 |
+
bos_token_id=2,
|
| 134 |
+
eos_token_id=3,
|
| 135 |
+
**kwargs,
|
| 136 |
+
):
|
| 137 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 138 |
+
|
| 139 |
+
self.vocab_size = vocab_size
|
| 140 |
+
self.embedding_size = embedding_size
|
| 141 |
+
self.hidden_size = hidden_size
|
| 142 |
+
self.num_hidden_layers = num_hidden_layers
|
| 143 |
+
self.num_hidden_groups = num_hidden_groups
|
| 144 |
+
self.num_attention_heads = num_attention_heads
|
| 145 |
+
self.inner_group_num = inner_group_num
|
| 146 |
+
self.hidden_act = hidden_act
|
| 147 |
+
self.intermediate_size = intermediate_size
|
| 148 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 149 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 150 |
+
self.max_position_embeddings = max_position_embeddings
|
| 151 |
+
self.type_vocab_size = type_vocab_size
|
| 152 |
+
self.initializer_range = initializer_range
|
| 153 |
+
self.layer_norm_eps = layer_norm_eps
|
| 154 |
+
self.classifier_dropout_prob = classifier_dropout_prob
|
| 155 |
+
self.position_embedding_type = position_embedding_type
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
# Copied from transformers.models.bert.configuration_bert.BertOnnxConfig with Roberta->Albert
|
| 159 |
+
class AlbertOnnxConfig(OnnxConfig):
|
| 160 |
+
@property
|
| 161 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 162 |
+
if self.task == "multiple-choice":
|
| 163 |
+
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
|
| 164 |
+
else:
|
| 165 |
+
dynamic_axis = {0: "batch", 1: "sequence"}
|
| 166 |
+
return OrderedDict(
|
| 167 |
+
[
|
| 168 |
+
("input_ids", dynamic_axis),
|
| 169 |
+
("attention_mask", dynamic_axis),
|
| 170 |
+
("token_type_ids", dynamic_axis),
|
| 171 |
+
]
|
| 172 |
+
)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/convert_albert_original_tf_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert ALBERT checkpoint."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from ...utils import logging
|
| 23 |
+
from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logging.set_verbosity_info()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, albert_config_file, pytorch_dump_path):
|
| 30 |
+
# Initialise PyTorch model
|
| 31 |
+
config = AlbertConfig.from_json_file(albert_config_file)
|
| 32 |
+
print(f"Building PyTorch model from configuration: {config}")
|
| 33 |
+
model = AlbertForPreTraining(config)
|
| 34 |
+
|
| 35 |
+
# Load weights from tf checkpoint
|
| 36 |
+
load_tf_weights_in_albert(model, config, tf_checkpoint_path)
|
| 37 |
+
|
| 38 |
+
# Save pytorch-model
|
| 39 |
+
print(f"Save PyTorch model to {pytorch_dump_path}")
|
| 40 |
+
torch.save(model.state_dict(), pytorch_dump_path)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if __name__ == "__main__":
|
| 44 |
+
parser = argparse.ArgumentParser()
|
| 45 |
+
# Required parameters
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
|
| 48 |
+
)
|
| 49 |
+
parser.add_argument(
|
| 50 |
+
"--albert_config_file",
|
| 51 |
+
default=None,
|
| 52 |
+
type=str,
|
| 53 |
+
required=True,
|
| 54 |
+
help=(
|
| 55 |
+
"The config json file corresponding to the pre-trained ALBERT model. \n"
|
| 56 |
+
"This specifies the model architecture."
|
| 57 |
+
),
|
| 58 |
+
)
|
| 59 |
+
parser.add_argument(
|
| 60 |
+
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
|
| 61 |
+
)
|
| 62 |
+
args = parser.parse_args()
|
| 63 |
+
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/modeling_albert.py
ADDED
|
@@ -0,0 +1,1403 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch ALBERT model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import Dict, List, Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from torch import nn
|
| 24 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 25 |
+
|
| 26 |
+
from ...activations import ACT2FN
|
| 27 |
+
from ...modeling_outputs import (
|
| 28 |
+
BaseModelOutput,
|
| 29 |
+
BaseModelOutputWithPooling,
|
| 30 |
+
MaskedLMOutput,
|
| 31 |
+
MultipleChoiceModelOutput,
|
| 32 |
+
QuestionAnsweringModelOutput,
|
| 33 |
+
SequenceClassifierOutput,
|
| 34 |
+
TokenClassifierOutput,
|
| 35 |
+
)
|
| 36 |
+
from ...modeling_utils import PreTrainedModel
|
| 37 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 38 |
+
from ...utils import (
|
| 39 |
+
ModelOutput,
|
| 40 |
+
add_code_sample_docstrings,
|
| 41 |
+
add_start_docstrings,
|
| 42 |
+
add_start_docstrings_to_model_forward,
|
| 43 |
+
logging,
|
| 44 |
+
replace_return_docstrings,
|
| 45 |
+
)
|
| 46 |
+
from .configuration_albert import AlbertConfig
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
logger = logging.get_logger(__name__)
|
| 50 |
+
|
| 51 |
+
_CHECKPOINT_FOR_DOC = "albert-base-v2"
|
| 52 |
+
_CONFIG_FOR_DOC = "AlbertConfig"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 56 |
+
"albert-base-v1",
|
| 57 |
+
"albert-large-v1",
|
| 58 |
+
"albert-xlarge-v1",
|
| 59 |
+
"albert-xxlarge-v1",
|
| 60 |
+
"albert-base-v2",
|
| 61 |
+
"albert-large-v2",
|
| 62 |
+
"albert-xlarge-v2",
|
| 63 |
+
"albert-xxlarge-v2",
|
| 64 |
+
# See all ALBERT models at https://huggingface.co/models?filter=albert
|
| 65 |
+
]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_tf_weights_in_albert(model, config, tf_checkpoint_path):
|
| 69 |
+
"""Load tf checkpoints in a pytorch model."""
|
| 70 |
+
try:
|
| 71 |
+
import re
|
| 72 |
+
|
| 73 |
+
import numpy as np
|
| 74 |
+
import tensorflow as tf
|
| 75 |
+
except ImportError:
|
| 76 |
+
logger.error(
|
| 77 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
| 78 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
| 79 |
+
)
|
| 80 |
+
raise
|
| 81 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
| 82 |
+
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
|
| 83 |
+
# Load weights from TF model
|
| 84 |
+
init_vars = tf.train.list_variables(tf_path)
|
| 85 |
+
names = []
|
| 86 |
+
arrays = []
|
| 87 |
+
for name, shape in init_vars:
|
| 88 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
| 89 |
+
array = tf.train.load_variable(tf_path, name)
|
| 90 |
+
names.append(name)
|
| 91 |
+
arrays.append(array)
|
| 92 |
+
|
| 93 |
+
for name, array in zip(names, arrays):
|
| 94 |
+
print(name)
|
| 95 |
+
|
| 96 |
+
for name, array in zip(names, arrays):
|
| 97 |
+
original_name = name
|
| 98 |
+
|
| 99 |
+
# If saved from the TF HUB module
|
| 100 |
+
name = name.replace("module/", "")
|
| 101 |
+
|
| 102 |
+
# Renaming and simplifying
|
| 103 |
+
name = name.replace("ffn_1", "ffn")
|
| 104 |
+
name = name.replace("bert/", "albert/")
|
| 105 |
+
name = name.replace("attention_1", "attention")
|
| 106 |
+
name = name.replace("transform/", "")
|
| 107 |
+
name = name.replace("LayerNorm_1", "full_layer_layer_norm")
|
| 108 |
+
name = name.replace("LayerNorm", "attention/LayerNorm")
|
| 109 |
+
name = name.replace("transformer/", "")
|
| 110 |
+
|
| 111 |
+
# The feed forward layer had an 'intermediate' step which has been abstracted away
|
| 112 |
+
name = name.replace("intermediate/dense/", "")
|
| 113 |
+
name = name.replace("ffn/intermediate/output/dense/", "ffn_output/")
|
| 114 |
+
|
| 115 |
+
# ALBERT attention was split between self and output which have been abstracted away
|
| 116 |
+
name = name.replace("/output/", "/")
|
| 117 |
+
name = name.replace("/self/", "/")
|
| 118 |
+
|
| 119 |
+
# The pooler is a linear layer
|
| 120 |
+
name = name.replace("pooler/dense", "pooler")
|
| 121 |
+
|
| 122 |
+
# The classifier was simplified to predictions from cls/predictions
|
| 123 |
+
name = name.replace("cls/predictions", "predictions")
|
| 124 |
+
name = name.replace("predictions/attention", "predictions")
|
| 125 |
+
|
| 126 |
+
# Naming was changed to be more explicit
|
| 127 |
+
name = name.replace("embeddings/attention", "embeddings")
|
| 128 |
+
name = name.replace("inner_group_", "albert_layers/")
|
| 129 |
+
name = name.replace("group_", "albert_layer_groups/")
|
| 130 |
+
|
| 131 |
+
# Classifier
|
| 132 |
+
if len(name.split("/")) == 1 and ("output_bias" in name or "output_weights" in name):
|
| 133 |
+
name = "classifier/" + name
|
| 134 |
+
|
| 135 |
+
# No ALBERT model currently handles the next sentence prediction task
|
| 136 |
+
if "seq_relationship" in name:
|
| 137 |
+
name = name.replace("seq_relationship/output_", "sop_classifier/classifier/")
|
| 138 |
+
name = name.replace("weights", "weight")
|
| 139 |
+
|
| 140 |
+
name = name.split("/")
|
| 141 |
+
|
| 142 |
+
# Ignore the gradients applied by the LAMB/ADAM optimizers.
|
| 143 |
+
if (
|
| 144 |
+
"adam_m" in name
|
| 145 |
+
or "adam_v" in name
|
| 146 |
+
or "AdamWeightDecayOptimizer" in name
|
| 147 |
+
or "AdamWeightDecayOptimizer_1" in name
|
| 148 |
+
or "global_step" in name
|
| 149 |
+
):
|
| 150 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
| 151 |
+
continue
|
| 152 |
+
|
| 153 |
+
pointer = model
|
| 154 |
+
for m_name in name:
|
| 155 |
+
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
|
| 156 |
+
scope_names = re.split(r"_(\d+)", m_name)
|
| 157 |
+
else:
|
| 158 |
+
scope_names = [m_name]
|
| 159 |
+
|
| 160 |
+
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
|
| 161 |
+
pointer = getattr(pointer, "weight")
|
| 162 |
+
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
|
| 163 |
+
pointer = getattr(pointer, "bias")
|
| 164 |
+
elif scope_names[0] == "output_weights":
|
| 165 |
+
pointer = getattr(pointer, "weight")
|
| 166 |
+
elif scope_names[0] == "squad":
|
| 167 |
+
pointer = getattr(pointer, "classifier")
|
| 168 |
+
else:
|
| 169 |
+
try:
|
| 170 |
+
pointer = getattr(pointer, scope_names[0])
|
| 171 |
+
except AttributeError:
|
| 172 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
| 173 |
+
continue
|
| 174 |
+
if len(scope_names) >= 2:
|
| 175 |
+
num = int(scope_names[1])
|
| 176 |
+
pointer = pointer[num]
|
| 177 |
+
|
| 178 |
+
if m_name[-11:] == "_embeddings":
|
| 179 |
+
pointer = getattr(pointer, "weight")
|
| 180 |
+
elif m_name == "kernel":
|
| 181 |
+
array = np.transpose(array)
|
| 182 |
+
try:
|
| 183 |
+
if pointer.shape != array.shape:
|
| 184 |
+
raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
|
| 185 |
+
except AssertionError as e:
|
| 186 |
+
e.args += (pointer.shape, array.shape)
|
| 187 |
+
raise
|
| 188 |
+
print(f"Initialize PyTorch weight {name} from {original_name}")
|
| 189 |
+
pointer.data = torch.from_numpy(array)
|
| 190 |
+
|
| 191 |
+
return model
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class AlbertEmbeddings(nn.Module):
|
| 195 |
+
"""
|
| 196 |
+
Construct the embeddings from word, position and token_type embeddings.
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
def __init__(self, config: AlbertConfig):
|
| 200 |
+
super().__init__()
|
| 201 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
|
| 202 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.embedding_size)
|
| 203 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.embedding_size)
|
| 204 |
+
|
| 205 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 206 |
+
# any TensorFlow checkpoint file
|
| 207 |
+
self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
|
| 208 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 209 |
+
|
| 210 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 211 |
+
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
|
| 212 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 213 |
+
self.register_buffer(
|
| 214 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# Copied from transformers.models.bert.modeling_bert.BertEmbeddings.forward
|
| 218 |
+
def forward(
|
| 219 |
+
self,
|
| 220 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 221 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 222 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 223 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 224 |
+
past_key_values_length: int = 0,
|
| 225 |
+
) -> torch.Tensor:
|
| 226 |
+
if input_ids is not None:
|
| 227 |
+
input_shape = input_ids.size()
|
| 228 |
+
else:
|
| 229 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 230 |
+
|
| 231 |
+
seq_length = input_shape[1]
|
| 232 |
+
|
| 233 |
+
if position_ids is None:
|
| 234 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 235 |
+
|
| 236 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 237 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 238 |
+
# issue #5664
|
| 239 |
+
if token_type_ids is None:
|
| 240 |
+
if hasattr(self, "token_type_ids"):
|
| 241 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 242 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 243 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 244 |
+
else:
|
| 245 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 246 |
+
|
| 247 |
+
if inputs_embeds is None:
|
| 248 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 249 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 250 |
+
|
| 251 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 252 |
+
if self.position_embedding_type == "absolute":
|
| 253 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 254 |
+
embeddings += position_embeddings
|
| 255 |
+
embeddings = self.LayerNorm(embeddings)
|
| 256 |
+
embeddings = self.dropout(embeddings)
|
| 257 |
+
return embeddings
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class AlbertAttention(nn.Module):
|
| 261 |
+
def __init__(self, config: AlbertConfig):
|
| 262 |
+
super().__init__()
|
| 263 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 264 |
+
raise ValueError(
|
| 265 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 266 |
+
f"heads ({config.num_attention_heads}"
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
self.num_attention_heads = config.num_attention_heads
|
| 270 |
+
self.hidden_size = config.hidden_size
|
| 271 |
+
self.attention_head_size = config.hidden_size // config.num_attention_heads
|
| 272 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 273 |
+
|
| 274 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 275 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 276 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 277 |
+
|
| 278 |
+
self.attention_dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 279 |
+
self.output_dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 280 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 281 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 282 |
+
self.pruned_heads = set()
|
| 283 |
+
|
| 284 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 285 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 286 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 287 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 288 |
+
|
| 289 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfAttention.transpose_for_scores
|
| 290 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 291 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 292 |
+
x = x.view(new_x_shape)
|
| 293 |
+
return x.permute(0, 2, 1, 3)
|
| 294 |
+
|
| 295 |
+
def prune_heads(self, heads: List[int]) -> None:
|
| 296 |
+
if len(heads) == 0:
|
| 297 |
+
return
|
| 298 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 299 |
+
heads, self.num_attention_heads, self.attention_head_size, self.pruned_heads
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
# Prune linear layers
|
| 303 |
+
self.query = prune_linear_layer(self.query, index)
|
| 304 |
+
self.key = prune_linear_layer(self.key, index)
|
| 305 |
+
self.value = prune_linear_layer(self.value, index)
|
| 306 |
+
self.dense = prune_linear_layer(self.dense, index, dim=1)
|
| 307 |
+
|
| 308 |
+
# Update hyper params and store pruned heads
|
| 309 |
+
self.num_attention_heads = self.num_attention_heads - len(heads)
|
| 310 |
+
self.all_head_size = self.attention_head_size * self.num_attention_heads
|
| 311 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 312 |
+
|
| 313 |
+
def forward(
|
| 314 |
+
self,
|
| 315 |
+
hidden_states: torch.Tensor,
|
| 316 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 317 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 318 |
+
output_attentions: bool = False,
|
| 319 |
+
) -> Union[Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor]]:
|
| 320 |
+
mixed_query_layer = self.query(hidden_states)
|
| 321 |
+
mixed_key_layer = self.key(hidden_states)
|
| 322 |
+
mixed_value_layer = self.value(hidden_states)
|
| 323 |
+
|
| 324 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 325 |
+
key_layer = self.transpose_for_scores(mixed_key_layer)
|
| 326 |
+
value_layer = self.transpose_for_scores(mixed_value_layer)
|
| 327 |
+
|
| 328 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 329 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 330 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 331 |
+
|
| 332 |
+
if attention_mask is not None:
|
| 333 |
+
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
|
| 334 |
+
attention_scores = attention_scores + attention_mask
|
| 335 |
+
|
| 336 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 337 |
+
seq_length = hidden_states.size()[1]
|
| 338 |
+
position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 339 |
+
position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 340 |
+
distance = position_ids_l - position_ids_r
|
| 341 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 342 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 343 |
+
|
| 344 |
+
if self.position_embedding_type == "relative_key":
|
| 345 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 346 |
+
attention_scores = attention_scores + relative_position_scores
|
| 347 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 348 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 349 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 350 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 351 |
+
|
| 352 |
+
# Normalize the attention scores to probabilities.
|
| 353 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 354 |
+
|
| 355 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 356 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 357 |
+
attention_probs = self.attention_dropout(attention_probs)
|
| 358 |
+
|
| 359 |
+
# Mask heads if we want to
|
| 360 |
+
if head_mask is not None:
|
| 361 |
+
attention_probs = attention_probs * head_mask
|
| 362 |
+
|
| 363 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 364 |
+
context_layer = context_layer.transpose(2, 1).flatten(2)
|
| 365 |
+
|
| 366 |
+
projected_context_layer = self.dense(context_layer)
|
| 367 |
+
projected_context_layer_dropout = self.output_dropout(projected_context_layer)
|
| 368 |
+
layernormed_context_layer = self.LayerNorm(hidden_states + projected_context_layer_dropout)
|
| 369 |
+
return (layernormed_context_layer, attention_probs) if output_attentions else (layernormed_context_layer,)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
class AlbertLayer(nn.Module):
|
| 373 |
+
def __init__(self, config: AlbertConfig):
|
| 374 |
+
super().__init__()
|
| 375 |
+
|
| 376 |
+
self.config = config
|
| 377 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 378 |
+
self.seq_len_dim = 1
|
| 379 |
+
self.full_layer_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 380 |
+
self.attention = AlbertAttention(config)
|
| 381 |
+
self.ffn = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 382 |
+
self.ffn_output = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 383 |
+
self.activation = ACT2FN[config.hidden_act]
|
| 384 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 385 |
+
|
| 386 |
+
def forward(
|
| 387 |
+
self,
|
| 388 |
+
hidden_states: torch.Tensor,
|
| 389 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 390 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 391 |
+
output_attentions: bool = False,
|
| 392 |
+
output_hidden_states: bool = False,
|
| 393 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 394 |
+
attention_output = self.attention(hidden_states, attention_mask, head_mask, output_attentions)
|
| 395 |
+
|
| 396 |
+
ffn_output = apply_chunking_to_forward(
|
| 397 |
+
self.ff_chunk,
|
| 398 |
+
self.chunk_size_feed_forward,
|
| 399 |
+
self.seq_len_dim,
|
| 400 |
+
attention_output[0],
|
| 401 |
+
)
|
| 402 |
+
hidden_states = self.full_layer_layer_norm(ffn_output + attention_output[0])
|
| 403 |
+
|
| 404 |
+
return (hidden_states,) + attention_output[1:] # add attentions if we output them
|
| 405 |
+
|
| 406 |
+
def ff_chunk(self, attention_output: torch.Tensor) -> torch.Tensor:
|
| 407 |
+
ffn_output = self.ffn(attention_output)
|
| 408 |
+
ffn_output = self.activation(ffn_output)
|
| 409 |
+
ffn_output = self.ffn_output(ffn_output)
|
| 410 |
+
return ffn_output
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
class AlbertLayerGroup(nn.Module):
|
| 414 |
+
def __init__(self, config: AlbertConfig):
|
| 415 |
+
super().__init__()
|
| 416 |
+
|
| 417 |
+
self.albert_layers = nn.ModuleList([AlbertLayer(config) for _ in range(config.inner_group_num)])
|
| 418 |
+
|
| 419 |
+
def forward(
|
| 420 |
+
self,
|
| 421 |
+
hidden_states: torch.Tensor,
|
| 422 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 423 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 424 |
+
output_attentions: bool = False,
|
| 425 |
+
output_hidden_states: bool = False,
|
| 426 |
+
) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
|
| 427 |
+
layer_hidden_states = ()
|
| 428 |
+
layer_attentions = ()
|
| 429 |
+
|
| 430 |
+
for layer_index, albert_layer in enumerate(self.albert_layers):
|
| 431 |
+
layer_output = albert_layer(hidden_states, attention_mask, head_mask[layer_index], output_attentions)
|
| 432 |
+
hidden_states = layer_output[0]
|
| 433 |
+
|
| 434 |
+
if output_attentions:
|
| 435 |
+
layer_attentions = layer_attentions + (layer_output[1],)
|
| 436 |
+
|
| 437 |
+
if output_hidden_states:
|
| 438 |
+
layer_hidden_states = layer_hidden_states + (hidden_states,)
|
| 439 |
+
|
| 440 |
+
outputs = (hidden_states,)
|
| 441 |
+
if output_hidden_states:
|
| 442 |
+
outputs = outputs + (layer_hidden_states,)
|
| 443 |
+
if output_attentions:
|
| 444 |
+
outputs = outputs + (layer_attentions,)
|
| 445 |
+
return outputs # last-layer hidden state, (layer hidden states), (layer attentions)
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
class AlbertTransformer(nn.Module):
|
| 449 |
+
def __init__(self, config: AlbertConfig):
|
| 450 |
+
super().__init__()
|
| 451 |
+
|
| 452 |
+
self.config = config
|
| 453 |
+
self.embedding_hidden_mapping_in = nn.Linear(config.embedding_size, config.hidden_size)
|
| 454 |
+
self.albert_layer_groups = nn.ModuleList([AlbertLayerGroup(config) for _ in range(config.num_hidden_groups)])
|
| 455 |
+
|
| 456 |
+
def forward(
|
| 457 |
+
self,
|
| 458 |
+
hidden_states: torch.Tensor,
|
| 459 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 460 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 461 |
+
output_attentions: bool = False,
|
| 462 |
+
output_hidden_states: bool = False,
|
| 463 |
+
return_dict: bool = True,
|
| 464 |
+
) -> Union[BaseModelOutput, Tuple]:
|
| 465 |
+
hidden_states = self.embedding_hidden_mapping_in(hidden_states)
|
| 466 |
+
|
| 467 |
+
all_hidden_states = (hidden_states,) if output_hidden_states else None
|
| 468 |
+
all_attentions = () if output_attentions else None
|
| 469 |
+
|
| 470 |
+
head_mask = [None] * self.config.num_hidden_layers if head_mask is None else head_mask
|
| 471 |
+
|
| 472 |
+
for i in range(self.config.num_hidden_layers):
|
| 473 |
+
# Number of layers in a hidden group
|
| 474 |
+
layers_per_group = int(self.config.num_hidden_layers / self.config.num_hidden_groups)
|
| 475 |
+
|
| 476 |
+
# Index of the hidden group
|
| 477 |
+
group_idx = int(i / (self.config.num_hidden_layers / self.config.num_hidden_groups))
|
| 478 |
+
|
| 479 |
+
layer_group_output = self.albert_layer_groups[group_idx](
|
| 480 |
+
hidden_states,
|
| 481 |
+
attention_mask,
|
| 482 |
+
head_mask[group_idx * layers_per_group : (group_idx + 1) * layers_per_group],
|
| 483 |
+
output_attentions,
|
| 484 |
+
output_hidden_states,
|
| 485 |
+
)
|
| 486 |
+
hidden_states = layer_group_output[0]
|
| 487 |
+
|
| 488 |
+
if output_attentions:
|
| 489 |
+
all_attentions = all_attentions + layer_group_output[-1]
|
| 490 |
+
|
| 491 |
+
if output_hidden_states:
|
| 492 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 493 |
+
|
| 494 |
+
if not return_dict:
|
| 495 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
|
| 496 |
+
return BaseModelOutput(
|
| 497 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
class AlbertPreTrainedModel(PreTrainedModel):
|
| 502 |
+
"""
|
| 503 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 504 |
+
models.
|
| 505 |
+
"""
|
| 506 |
+
|
| 507 |
+
config_class = AlbertConfig
|
| 508 |
+
load_tf_weights = load_tf_weights_in_albert
|
| 509 |
+
base_model_prefix = "albert"
|
| 510 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
| 511 |
+
|
| 512 |
+
def _init_weights(self, module):
|
| 513 |
+
"""Initialize the weights."""
|
| 514 |
+
if isinstance(module, nn.Linear):
|
| 515 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 516 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 517 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 518 |
+
if module.bias is not None:
|
| 519 |
+
module.bias.data.zero_()
|
| 520 |
+
elif isinstance(module, nn.Embedding):
|
| 521 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 522 |
+
if module.padding_idx is not None:
|
| 523 |
+
module.weight.data[module.padding_idx].zero_()
|
| 524 |
+
elif isinstance(module, nn.LayerNorm):
|
| 525 |
+
module.bias.data.zero_()
|
| 526 |
+
module.weight.data.fill_(1.0)
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
@dataclass
|
| 530 |
+
class AlbertForPreTrainingOutput(ModelOutput):
|
| 531 |
+
"""
|
| 532 |
+
Output type of [`AlbertForPreTraining`].
|
| 533 |
+
|
| 534 |
+
Args:
|
| 535 |
+
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
| 536 |
+
Total loss as the sum of the masked language modeling loss and the next sequence prediction
|
| 537 |
+
(classification) loss.
|
| 538 |
+
prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 539 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 540 |
+
sop_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
|
| 541 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
| 542 |
+
before SoftMax).
|
| 543 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 544 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 545 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
| 546 |
+
|
| 547 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 548 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 549 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 550 |
+
sequence_length)`.
|
| 551 |
+
|
| 552 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 553 |
+
heads.
|
| 554 |
+
"""
|
| 555 |
+
|
| 556 |
+
loss: Optional[torch.FloatTensor] = None
|
| 557 |
+
prediction_logits: torch.FloatTensor = None
|
| 558 |
+
sop_logits: torch.FloatTensor = None
|
| 559 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 560 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
ALBERT_START_DOCSTRING = r"""
|
| 564 |
+
|
| 565 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 566 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 567 |
+
etc.)
|
| 568 |
+
|
| 569 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 570 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 571 |
+
and behavior.
|
| 572 |
+
|
| 573 |
+
Args:
|
| 574 |
+
config ([`AlbertConfig`]): Model configuration class with all the parameters of the model.
|
| 575 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 576 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 577 |
+
"""
|
| 578 |
+
|
| 579 |
+
ALBERT_INPUTS_DOCSTRING = r"""
|
| 580 |
+
Args:
|
| 581 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
| 582 |
+
Indices of input sequence tokens in the vocabulary.
|
| 583 |
+
|
| 584 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 585 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 586 |
+
|
| 587 |
+
[What are input IDs?](../glossary#input-ids)
|
| 588 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
| 589 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 590 |
+
|
| 591 |
+
- 1 for tokens that are **not masked**,
|
| 592 |
+
- 0 for tokens that are **masked**.
|
| 593 |
+
|
| 594 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 595 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 596 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 597 |
+
1]`:
|
| 598 |
+
|
| 599 |
+
- 0 corresponds to a *sentence A* token,
|
| 600 |
+
- 1 corresponds to a *sentence B* token.
|
| 601 |
+
|
| 602 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 603 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 604 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 605 |
+
config.max_position_embeddings - 1]`.
|
| 606 |
+
|
| 607 |
+
[What are position IDs?](../glossary#position-ids)
|
| 608 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 609 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 610 |
+
|
| 611 |
+
- 1 indicates the head is **not masked**,
|
| 612 |
+
- 0 indicates the head is **masked**.
|
| 613 |
+
|
| 614 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 615 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 616 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 617 |
+
model's internal embedding lookup matrix.
|
| 618 |
+
output_attentions (`bool`, *optional*):
|
| 619 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 620 |
+
tensors for more detail.
|
| 621 |
+
output_hidden_states (`bool`, *optional*):
|
| 622 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 623 |
+
more detail.
|
| 624 |
+
return_dict (`bool`, *optional*):
|
| 625 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 626 |
+
"""
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
@add_start_docstrings(
|
| 630 |
+
"The bare ALBERT Model transformer outputting raw hidden-states without any specific head on top.",
|
| 631 |
+
ALBERT_START_DOCSTRING,
|
| 632 |
+
)
|
| 633 |
+
class AlbertModel(AlbertPreTrainedModel):
|
| 634 |
+
config_class = AlbertConfig
|
| 635 |
+
base_model_prefix = "albert"
|
| 636 |
+
|
| 637 |
+
def __init__(self, config: AlbertConfig, add_pooling_layer: bool = True):
|
| 638 |
+
super().__init__(config)
|
| 639 |
+
|
| 640 |
+
self.config = config
|
| 641 |
+
self.embeddings = AlbertEmbeddings(config)
|
| 642 |
+
self.encoder = AlbertTransformer(config)
|
| 643 |
+
if add_pooling_layer:
|
| 644 |
+
self.pooler = nn.Linear(config.hidden_size, config.hidden_size)
|
| 645 |
+
self.pooler_activation = nn.Tanh()
|
| 646 |
+
else:
|
| 647 |
+
self.pooler = None
|
| 648 |
+
self.pooler_activation = None
|
| 649 |
+
|
| 650 |
+
# Initialize weights and apply final processing
|
| 651 |
+
self.post_init()
|
| 652 |
+
|
| 653 |
+
def get_input_embeddings(self) -> nn.Embedding:
|
| 654 |
+
return self.embeddings.word_embeddings
|
| 655 |
+
|
| 656 |
+
def set_input_embeddings(self, value: nn.Embedding) -> None:
|
| 657 |
+
self.embeddings.word_embeddings = value
|
| 658 |
+
|
| 659 |
+
def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
|
| 660 |
+
"""
|
| 661 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} ALBERT has
|
| 662 |
+
a different architecture in that its layers are shared across groups, which then has inner groups. If an ALBERT
|
| 663 |
+
model has 12 hidden layers and 2 hidden groups, with two inner groups, there is a total of 4 different layers.
|
| 664 |
+
|
| 665 |
+
These layers are flattened: the indices [0,1] correspond to the two inner groups of the first hidden layer,
|
| 666 |
+
while [2,3] correspond to the two inner groups of the second hidden layer.
|
| 667 |
+
|
| 668 |
+
Any layer with in index other than [0,1,2,3] will result in an error. See base class PreTrainedModel for more
|
| 669 |
+
information about head pruning
|
| 670 |
+
"""
|
| 671 |
+
for layer, heads in heads_to_prune.items():
|
| 672 |
+
group_idx = int(layer / self.config.inner_group_num)
|
| 673 |
+
inner_group_idx = int(layer - group_idx * self.config.inner_group_num)
|
| 674 |
+
self.encoder.albert_layer_groups[group_idx].albert_layers[inner_group_idx].attention.prune_heads(heads)
|
| 675 |
+
|
| 676 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 677 |
+
@add_code_sample_docstrings(
|
| 678 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 679 |
+
output_type=BaseModelOutputWithPooling,
|
| 680 |
+
config_class=_CONFIG_FOR_DOC,
|
| 681 |
+
)
|
| 682 |
+
def forward(
|
| 683 |
+
self,
|
| 684 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 685 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 686 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 687 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 688 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 689 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 690 |
+
output_attentions: Optional[None] = None,
|
| 691 |
+
output_hidden_states: Optional[None] = None,
|
| 692 |
+
return_dict: Optional[None] = None,
|
| 693 |
+
) -> Union[BaseModelOutputWithPooling, Tuple]:
|
| 694 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 695 |
+
output_hidden_states = (
|
| 696 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 697 |
+
)
|
| 698 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 699 |
+
|
| 700 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 701 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 702 |
+
elif input_ids is not None:
|
| 703 |
+
input_shape = input_ids.size()
|
| 704 |
+
elif inputs_embeds is not None:
|
| 705 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 706 |
+
else:
|
| 707 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 708 |
+
|
| 709 |
+
batch_size, seq_length = input_shape
|
| 710 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 711 |
+
|
| 712 |
+
if attention_mask is None:
|
| 713 |
+
attention_mask = torch.ones(input_shape, device=device)
|
| 714 |
+
if token_type_ids is None:
|
| 715 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 716 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 717 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 718 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 719 |
+
else:
|
| 720 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 721 |
+
|
| 722 |
+
extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 723 |
+
extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
| 724 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(self.dtype).min
|
| 725 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 726 |
+
|
| 727 |
+
embedding_output = self.embeddings(
|
| 728 |
+
input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
|
| 729 |
+
)
|
| 730 |
+
encoder_outputs = self.encoder(
|
| 731 |
+
embedding_output,
|
| 732 |
+
extended_attention_mask,
|
| 733 |
+
head_mask=head_mask,
|
| 734 |
+
output_attentions=output_attentions,
|
| 735 |
+
output_hidden_states=output_hidden_states,
|
| 736 |
+
return_dict=return_dict,
|
| 737 |
+
)
|
| 738 |
+
|
| 739 |
+
sequence_output = encoder_outputs[0]
|
| 740 |
+
|
| 741 |
+
pooled_output = self.pooler_activation(self.pooler(sequence_output[:, 0])) if self.pooler is not None else None
|
| 742 |
+
|
| 743 |
+
if not return_dict:
|
| 744 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 745 |
+
|
| 746 |
+
return BaseModelOutputWithPooling(
|
| 747 |
+
last_hidden_state=sequence_output,
|
| 748 |
+
pooler_output=pooled_output,
|
| 749 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 750 |
+
attentions=encoder_outputs.attentions,
|
| 751 |
+
)
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
@add_start_docstrings(
|
| 755 |
+
"""
|
| 756 |
+
Albert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
|
| 757 |
+
`sentence order prediction (classification)` head.
|
| 758 |
+
""",
|
| 759 |
+
ALBERT_START_DOCSTRING,
|
| 760 |
+
)
|
| 761 |
+
class AlbertForPreTraining(AlbertPreTrainedModel):
|
| 762 |
+
_keys_to_ignore_on_load_missing = [
|
| 763 |
+
"predictions.decoder.weight",
|
| 764 |
+
"predictions.decoder.bias",
|
| 765 |
+
"embeddings.position_ids",
|
| 766 |
+
]
|
| 767 |
+
|
| 768 |
+
def __init__(self, config: AlbertConfig):
|
| 769 |
+
super().__init__(config)
|
| 770 |
+
|
| 771 |
+
self.albert = AlbertModel(config)
|
| 772 |
+
self.predictions = AlbertMLMHead(config)
|
| 773 |
+
self.sop_classifier = AlbertSOPHead(config)
|
| 774 |
+
|
| 775 |
+
# Initialize weights and apply final processing
|
| 776 |
+
self.post_init()
|
| 777 |
+
|
| 778 |
+
def get_output_embeddings(self) -> nn.Linear:
|
| 779 |
+
return self.predictions.decoder
|
| 780 |
+
|
| 781 |
+
def set_output_embeddings(self, new_embeddings: nn.Linear) -> None:
|
| 782 |
+
self.predictions.decoder = new_embeddings
|
| 783 |
+
|
| 784 |
+
def get_input_embeddings(self) -> nn.Embedding:
|
| 785 |
+
return self.albert.embeddings.word_embeddings
|
| 786 |
+
|
| 787 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 788 |
+
@replace_return_docstrings(output_type=AlbertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
|
| 789 |
+
def forward(
|
| 790 |
+
self,
|
| 791 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 792 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 793 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 794 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 795 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 796 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 797 |
+
labels: Optional[torch.LongTensor] = None,
|
| 798 |
+
sentence_order_label: Optional[torch.LongTensor] = None,
|
| 799 |
+
output_attentions: Optional[bool] = None,
|
| 800 |
+
output_hidden_states: Optional[bool] = None,
|
| 801 |
+
return_dict: Optional[bool] = None,
|
| 802 |
+
) -> Union[AlbertForPreTrainingOutput, Tuple]:
|
| 803 |
+
r"""
|
| 804 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 805 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 806 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 807 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 808 |
+
sentence_order_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 809 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
|
| 810 |
+
(see `input_ids` docstring) Indices should be in `[0, 1]`. `0` indicates original order (sequence A, then
|
| 811 |
+
sequence B), `1` indicates switched order (sequence B, then sequence A).
|
| 812 |
+
|
| 813 |
+
Returns:
|
| 814 |
+
|
| 815 |
+
Example:
|
| 816 |
+
|
| 817 |
+
```python
|
| 818 |
+
>>> from transformers import AutoTokenizer, AlbertForPreTraining
|
| 819 |
+
>>> import torch
|
| 820 |
+
|
| 821 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("albert-base-v2")
|
| 822 |
+
>>> model = AlbertForPreTraining.from_pretrained("albert-base-v2")
|
| 823 |
+
|
| 824 |
+
>>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)
|
| 825 |
+
>>> # Batch size 1
|
| 826 |
+
>>> outputs = model(input_ids)
|
| 827 |
+
|
| 828 |
+
>>> prediction_logits = outputs.prediction_logits
|
| 829 |
+
>>> sop_logits = outputs.sop_logits
|
| 830 |
+
```"""
|
| 831 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 832 |
+
|
| 833 |
+
outputs = self.albert(
|
| 834 |
+
input_ids,
|
| 835 |
+
attention_mask=attention_mask,
|
| 836 |
+
token_type_ids=token_type_ids,
|
| 837 |
+
position_ids=position_ids,
|
| 838 |
+
head_mask=head_mask,
|
| 839 |
+
inputs_embeds=inputs_embeds,
|
| 840 |
+
output_attentions=output_attentions,
|
| 841 |
+
output_hidden_states=output_hidden_states,
|
| 842 |
+
return_dict=return_dict,
|
| 843 |
+
)
|
| 844 |
+
|
| 845 |
+
sequence_output, pooled_output = outputs[:2]
|
| 846 |
+
|
| 847 |
+
prediction_scores = self.predictions(sequence_output)
|
| 848 |
+
sop_scores = self.sop_classifier(pooled_output)
|
| 849 |
+
|
| 850 |
+
total_loss = None
|
| 851 |
+
if labels is not None and sentence_order_label is not None:
|
| 852 |
+
loss_fct = CrossEntropyLoss()
|
| 853 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 854 |
+
sentence_order_loss = loss_fct(sop_scores.view(-1, 2), sentence_order_label.view(-1))
|
| 855 |
+
total_loss = masked_lm_loss + sentence_order_loss
|
| 856 |
+
|
| 857 |
+
if not return_dict:
|
| 858 |
+
output = (prediction_scores, sop_scores) + outputs[2:]
|
| 859 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 860 |
+
|
| 861 |
+
return AlbertForPreTrainingOutput(
|
| 862 |
+
loss=total_loss,
|
| 863 |
+
prediction_logits=prediction_scores,
|
| 864 |
+
sop_logits=sop_scores,
|
| 865 |
+
hidden_states=outputs.hidden_states,
|
| 866 |
+
attentions=outputs.attentions,
|
| 867 |
+
)
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
class AlbertMLMHead(nn.Module):
|
| 871 |
+
def __init__(self, config: AlbertConfig):
|
| 872 |
+
super().__init__()
|
| 873 |
+
|
| 874 |
+
self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps)
|
| 875 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 876 |
+
self.dense = nn.Linear(config.hidden_size, config.embedding_size)
|
| 877 |
+
self.decoder = nn.Linear(config.embedding_size, config.vocab_size)
|
| 878 |
+
self.activation = ACT2FN[config.hidden_act]
|
| 879 |
+
self.decoder.bias = self.bias
|
| 880 |
+
|
| 881 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 882 |
+
hidden_states = self.dense(hidden_states)
|
| 883 |
+
hidden_states = self.activation(hidden_states)
|
| 884 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 885 |
+
hidden_states = self.decoder(hidden_states)
|
| 886 |
+
|
| 887 |
+
prediction_scores = hidden_states
|
| 888 |
+
|
| 889 |
+
return prediction_scores
|
| 890 |
+
|
| 891 |
+
def _tie_weights(self) -> None:
|
| 892 |
+
# To tie those two weights if they get disconnected (on TPU or when the bias is resized)
|
| 893 |
+
self.bias = self.decoder.bias
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
class AlbertSOPHead(nn.Module):
|
| 897 |
+
def __init__(self, config: AlbertConfig):
|
| 898 |
+
super().__init__()
|
| 899 |
+
|
| 900 |
+
self.dropout = nn.Dropout(config.classifier_dropout_prob)
|
| 901 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 902 |
+
|
| 903 |
+
def forward(self, pooled_output: torch.Tensor) -> torch.Tensor:
|
| 904 |
+
dropout_pooled_output = self.dropout(pooled_output)
|
| 905 |
+
logits = self.classifier(dropout_pooled_output)
|
| 906 |
+
return logits
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
@add_start_docstrings(
|
| 910 |
+
"Albert Model with a `language modeling` head on top.",
|
| 911 |
+
ALBERT_START_DOCSTRING,
|
| 912 |
+
)
|
| 913 |
+
class AlbertForMaskedLM(AlbertPreTrainedModel):
|
| 914 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
| 915 |
+
_keys_to_ignore_on_load_missing = [
|
| 916 |
+
"predictions.decoder.weight",
|
| 917 |
+
"predictions.decoder.bias",
|
| 918 |
+
"embeddings.position_ids",
|
| 919 |
+
]
|
| 920 |
+
|
| 921 |
+
def __init__(self, config):
|
| 922 |
+
super().__init__(config)
|
| 923 |
+
|
| 924 |
+
self.albert = AlbertModel(config, add_pooling_layer=False)
|
| 925 |
+
self.predictions = AlbertMLMHead(config)
|
| 926 |
+
|
| 927 |
+
# Initialize weights and apply final processing
|
| 928 |
+
self.post_init()
|
| 929 |
+
|
| 930 |
+
def get_output_embeddings(self) -> nn.Linear:
|
| 931 |
+
return self.predictions.decoder
|
| 932 |
+
|
| 933 |
+
def set_output_embeddings(self, new_embeddings: nn.Linear) -> None:
|
| 934 |
+
self.predictions.decoder = new_embeddings
|
| 935 |
+
|
| 936 |
+
def get_input_embeddings(self) -> nn.Embedding:
|
| 937 |
+
return self.albert.embeddings.word_embeddings
|
| 938 |
+
|
| 939 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 940 |
+
@replace_return_docstrings(output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 941 |
+
def forward(
|
| 942 |
+
self,
|
| 943 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 944 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 945 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 946 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 947 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 948 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 949 |
+
labels: Optional[torch.LongTensor] = None,
|
| 950 |
+
output_attentions: Optional[bool] = None,
|
| 951 |
+
output_hidden_states: Optional[bool] = None,
|
| 952 |
+
return_dict: Optional[bool] = None,
|
| 953 |
+
) -> Union[MaskedLMOutput, Tuple]:
|
| 954 |
+
r"""
|
| 955 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 956 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 957 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 958 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 959 |
+
|
| 960 |
+
Returns:
|
| 961 |
+
|
| 962 |
+
Example:
|
| 963 |
+
|
| 964 |
+
```python
|
| 965 |
+
>>> import torch
|
| 966 |
+
>>> from transformers import AutoTokenizer, AlbertForMaskedLM
|
| 967 |
+
|
| 968 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("albert-base-v2")
|
| 969 |
+
>>> model = AlbertForMaskedLM.from_pretrained("albert-base-v2")
|
| 970 |
+
|
| 971 |
+
>>> # add mask_token
|
| 972 |
+
>>> inputs = tokenizer("The capital of [MASK] is Paris.", return_tensors="pt")
|
| 973 |
+
>>> with torch.no_grad():
|
| 974 |
+
... logits = model(**inputs).logits
|
| 975 |
+
|
| 976 |
+
>>> # retrieve index of [MASK]
|
| 977 |
+
>>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]
|
| 978 |
+
>>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)
|
| 979 |
+
>>> tokenizer.decode(predicted_token_id)
|
| 980 |
+
'france'
|
| 981 |
+
```
|
| 982 |
+
|
| 983 |
+
```python
|
| 984 |
+
>>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]
|
| 985 |
+
>>> labels = torch.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)
|
| 986 |
+
>>> outputs = model(**inputs, labels=labels)
|
| 987 |
+
>>> round(outputs.loss.item(), 2)
|
| 988 |
+
0.81
|
| 989 |
+
```
|
| 990 |
+
"""
|
| 991 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 992 |
+
|
| 993 |
+
outputs = self.albert(
|
| 994 |
+
input_ids=input_ids,
|
| 995 |
+
attention_mask=attention_mask,
|
| 996 |
+
token_type_ids=token_type_ids,
|
| 997 |
+
position_ids=position_ids,
|
| 998 |
+
head_mask=head_mask,
|
| 999 |
+
inputs_embeds=inputs_embeds,
|
| 1000 |
+
output_attentions=output_attentions,
|
| 1001 |
+
output_hidden_states=output_hidden_states,
|
| 1002 |
+
return_dict=return_dict,
|
| 1003 |
+
)
|
| 1004 |
+
sequence_outputs = outputs[0]
|
| 1005 |
+
|
| 1006 |
+
prediction_scores = self.predictions(sequence_outputs)
|
| 1007 |
+
|
| 1008 |
+
masked_lm_loss = None
|
| 1009 |
+
if labels is not None:
|
| 1010 |
+
loss_fct = CrossEntropyLoss()
|
| 1011 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1012 |
+
|
| 1013 |
+
if not return_dict:
|
| 1014 |
+
output = (prediction_scores,) + outputs[2:]
|
| 1015 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1016 |
+
|
| 1017 |
+
return MaskedLMOutput(
|
| 1018 |
+
loss=masked_lm_loss,
|
| 1019 |
+
logits=prediction_scores,
|
| 1020 |
+
hidden_states=outputs.hidden_states,
|
| 1021 |
+
attentions=outputs.attentions,
|
| 1022 |
+
)
|
| 1023 |
+
|
| 1024 |
+
|
| 1025 |
+
@add_start_docstrings(
|
| 1026 |
+
"""
|
| 1027 |
+
Albert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
| 1028 |
+
output) e.g. for GLUE tasks.
|
| 1029 |
+
""",
|
| 1030 |
+
ALBERT_START_DOCSTRING,
|
| 1031 |
+
)
|
| 1032 |
+
class AlbertForSequenceClassification(AlbertPreTrainedModel):
|
| 1033 |
+
def __init__(self, config: AlbertConfig):
|
| 1034 |
+
super().__init__(config)
|
| 1035 |
+
self.num_labels = config.num_labels
|
| 1036 |
+
self.config = config
|
| 1037 |
+
|
| 1038 |
+
self.albert = AlbertModel(config)
|
| 1039 |
+
self.dropout = nn.Dropout(config.classifier_dropout_prob)
|
| 1040 |
+
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
|
| 1041 |
+
|
| 1042 |
+
# Initialize weights and apply final processing
|
| 1043 |
+
self.post_init()
|
| 1044 |
+
|
| 1045 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1046 |
+
@add_code_sample_docstrings(
|
| 1047 |
+
checkpoint="textattack/albert-base-v2-imdb",
|
| 1048 |
+
output_type=SequenceClassifierOutput,
|
| 1049 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1050 |
+
expected_output="'LABEL_1'",
|
| 1051 |
+
expected_loss=0.12,
|
| 1052 |
+
)
|
| 1053 |
+
def forward(
|
| 1054 |
+
self,
|
| 1055 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1056 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1057 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1058 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1059 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1060 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1061 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1062 |
+
output_attentions: Optional[bool] = None,
|
| 1063 |
+
output_hidden_states: Optional[bool] = None,
|
| 1064 |
+
return_dict: Optional[bool] = None,
|
| 1065 |
+
) -> Union[SequenceClassifierOutput, Tuple]:
|
| 1066 |
+
r"""
|
| 1067 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1068 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1069 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1070 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1071 |
+
"""
|
| 1072 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1073 |
+
|
| 1074 |
+
outputs = self.albert(
|
| 1075 |
+
input_ids=input_ids,
|
| 1076 |
+
attention_mask=attention_mask,
|
| 1077 |
+
token_type_ids=token_type_ids,
|
| 1078 |
+
position_ids=position_ids,
|
| 1079 |
+
head_mask=head_mask,
|
| 1080 |
+
inputs_embeds=inputs_embeds,
|
| 1081 |
+
output_attentions=output_attentions,
|
| 1082 |
+
output_hidden_states=output_hidden_states,
|
| 1083 |
+
return_dict=return_dict,
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
pooled_output = outputs[1]
|
| 1087 |
+
|
| 1088 |
+
pooled_output = self.dropout(pooled_output)
|
| 1089 |
+
logits = self.classifier(pooled_output)
|
| 1090 |
+
|
| 1091 |
+
loss = None
|
| 1092 |
+
if labels is not None:
|
| 1093 |
+
if self.config.problem_type is None:
|
| 1094 |
+
if self.num_labels == 1:
|
| 1095 |
+
self.config.problem_type = "regression"
|
| 1096 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1097 |
+
self.config.problem_type = "single_label_classification"
|
| 1098 |
+
else:
|
| 1099 |
+
self.config.problem_type = "multi_label_classification"
|
| 1100 |
+
|
| 1101 |
+
if self.config.problem_type == "regression":
|
| 1102 |
+
loss_fct = MSELoss()
|
| 1103 |
+
if self.num_labels == 1:
|
| 1104 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1105 |
+
else:
|
| 1106 |
+
loss = loss_fct(logits, labels)
|
| 1107 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1108 |
+
loss_fct = CrossEntropyLoss()
|
| 1109 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1110 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1111 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1112 |
+
loss = loss_fct(logits, labels)
|
| 1113 |
+
|
| 1114 |
+
if not return_dict:
|
| 1115 |
+
output = (logits,) + outputs[2:]
|
| 1116 |
+
return ((loss,) + output) if loss is not None else output
|
| 1117 |
+
|
| 1118 |
+
return SequenceClassifierOutput(
|
| 1119 |
+
loss=loss,
|
| 1120 |
+
logits=logits,
|
| 1121 |
+
hidden_states=outputs.hidden_states,
|
| 1122 |
+
attentions=outputs.attentions,
|
| 1123 |
+
)
|
| 1124 |
+
|
| 1125 |
+
|
| 1126 |
+
@add_start_docstrings(
|
| 1127 |
+
"""
|
| 1128 |
+
Albert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1129 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1130 |
+
""",
|
| 1131 |
+
ALBERT_START_DOCSTRING,
|
| 1132 |
+
)
|
| 1133 |
+
class AlbertForTokenClassification(AlbertPreTrainedModel):
|
| 1134 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
| 1135 |
+
|
| 1136 |
+
def __init__(self, config: AlbertConfig):
|
| 1137 |
+
super().__init__(config)
|
| 1138 |
+
self.num_labels = config.num_labels
|
| 1139 |
+
|
| 1140 |
+
self.albert = AlbertModel(config, add_pooling_layer=False)
|
| 1141 |
+
classifier_dropout_prob = (
|
| 1142 |
+
config.classifier_dropout_prob
|
| 1143 |
+
if config.classifier_dropout_prob is not None
|
| 1144 |
+
else config.hidden_dropout_prob
|
| 1145 |
+
)
|
| 1146 |
+
self.dropout = nn.Dropout(classifier_dropout_prob)
|
| 1147 |
+
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
|
| 1148 |
+
|
| 1149 |
+
# Initialize weights and apply final processing
|
| 1150 |
+
self.post_init()
|
| 1151 |
+
|
| 1152 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1153 |
+
@add_code_sample_docstrings(
|
| 1154 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1155 |
+
output_type=TokenClassifierOutput,
|
| 1156 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1157 |
+
)
|
| 1158 |
+
def forward(
|
| 1159 |
+
self,
|
| 1160 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1161 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1162 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1163 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1164 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1165 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1166 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1167 |
+
output_attentions: Optional[bool] = None,
|
| 1168 |
+
output_hidden_states: Optional[bool] = None,
|
| 1169 |
+
return_dict: Optional[bool] = None,
|
| 1170 |
+
) -> Union[TokenClassifierOutput, Tuple]:
|
| 1171 |
+
r"""
|
| 1172 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1173 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1174 |
+
"""
|
| 1175 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1176 |
+
|
| 1177 |
+
outputs = self.albert(
|
| 1178 |
+
input_ids,
|
| 1179 |
+
attention_mask=attention_mask,
|
| 1180 |
+
token_type_ids=token_type_ids,
|
| 1181 |
+
position_ids=position_ids,
|
| 1182 |
+
head_mask=head_mask,
|
| 1183 |
+
inputs_embeds=inputs_embeds,
|
| 1184 |
+
output_attentions=output_attentions,
|
| 1185 |
+
output_hidden_states=output_hidden_states,
|
| 1186 |
+
return_dict=return_dict,
|
| 1187 |
+
)
|
| 1188 |
+
|
| 1189 |
+
sequence_output = outputs[0]
|
| 1190 |
+
|
| 1191 |
+
sequence_output = self.dropout(sequence_output)
|
| 1192 |
+
logits = self.classifier(sequence_output)
|
| 1193 |
+
|
| 1194 |
+
loss = None
|
| 1195 |
+
if labels is not None:
|
| 1196 |
+
loss_fct = CrossEntropyLoss()
|
| 1197 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1198 |
+
|
| 1199 |
+
if not return_dict:
|
| 1200 |
+
output = (logits,) + outputs[2:]
|
| 1201 |
+
return ((loss,) + output) if loss is not None else output
|
| 1202 |
+
|
| 1203 |
+
return TokenClassifierOutput(
|
| 1204 |
+
loss=loss,
|
| 1205 |
+
logits=logits,
|
| 1206 |
+
hidden_states=outputs.hidden_states,
|
| 1207 |
+
attentions=outputs.attentions,
|
| 1208 |
+
)
|
| 1209 |
+
|
| 1210 |
+
|
| 1211 |
+
@add_start_docstrings(
|
| 1212 |
+
"""
|
| 1213 |
+
Albert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1214 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1215 |
+
""",
|
| 1216 |
+
ALBERT_START_DOCSTRING,
|
| 1217 |
+
)
|
| 1218 |
+
class AlbertForQuestionAnswering(AlbertPreTrainedModel):
|
| 1219 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
| 1220 |
+
|
| 1221 |
+
def __init__(self, config: AlbertConfig):
|
| 1222 |
+
super().__init__(config)
|
| 1223 |
+
self.num_labels = config.num_labels
|
| 1224 |
+
|
| 1225 |
+
self.albert = AlbertModel(config, add_pooling_layer=False)
|
| 1226 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1227 |
+
|
| 1228 |
+
# Initialize weights and apply final processing
|
| 1229 |
+
self.post_init()
|
| 1230 |
+
|
| 1231 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1232 |
+
@add_code_sample_docstrings(
|
| 1233 |
+
checkpoint="twmkn9/albert-base-v2-squad2",
|
| 1234 |
+
output_type=QuestionAnsweringModelOutput,
|
| 1235 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1236 |
+
qa_target_start_index=12,
|
| 1237 |
+
qa_target_end_index=13,
|
| 1238 |
+
expected_output="'a nice puppet'",
|
| 1239 |
+
expected_loss=7.36,
|
| 1240 |
+
)
|
| 1241 |
+
def forward(
|
| 1242 |
+
self,
|
| 1243 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1244 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1245 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1246 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1247 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1248 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1249 |
+
start_positions: Optional[torch.LongTensor] = None,
|
| 1250 |
+
end_positions: Optional[torch.LongTensor] = None,
|
| 1251 |
+
output_attentions: Optional[bool] = None,
|
| 1252 |
+
output_hidden_states: Optional[bool] = None,
|
| 1253 |
+
return_dict: Optional[bool] = None,
|
| 1254 |
+
) -> Union[AlbertForPreTrainingOutput, Tuple]:
|
| 1255 |
+
r"""
|
| 1256 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1257 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1258 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1259 |
+
are not taken into account for computing the loss.
|
| 1260 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1261 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1262 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1263 |
+
are not taken into account for computing the loss.
|
| 1264 |
+
"""
|
| 1265 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1266 |
+
|
| 1267 |
+
outputs = self.albert(
|
| 1268 |
+
input_ids=input_ids,
|
| 1269 |
+
attention_mask=attention_mask,
|
| 1270 |
+
token_type_ids=token_type_ids,
|
| 1271 |
+
position_ids=position_ids,
|
| 1272 |
+
head_mask=head_mask,
|
| 1273 |
+
inputs_embeds=inputs_embeds,
|
| 1274 |
+
output_attentions=output_attentions,
|
| 1275 |
+
output_hidden_states=output_hidden_states,
|
| 1276 |
+
return_dict=return_dict,
|
| 1277 |
+
)
|
| 1278 |
+
|
| 1279 |
+
sequence_output = outputs[0]
|
| 1280 |
+
|
| 1281 |
+
logits: torch.Tensor = self.qa_outputs(sequence_output)
|
| 1282 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1283 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1284 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1285 |
+
|
| 1286 |
+
total_loss = None
|
| 1287 |
+
if start_positions is not None and end_positions is not None:
|
| 1288 |
+
# If we are on multi-GPU, split add a dimension
|
| 1289 |
+
if len(start_positions.size()) > 1:
|
| 1290 |
+
start_positions = start_positions.squeeze(-1)
|
| 1291 |
+
if len(end_positions.size()) > 1:
|
| 1292 |
+
end_positions = end_positions.squeeze(-1)
|
| 1293 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1294 |
+
ignored_index = start_logits.size(1)
|
| 1295 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1296 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1297 |
+
|
| 1298 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1299 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1300 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1301 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1302 |
+
|
| 1303 |
+
if not return_dict:
|
| 1304 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1305 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1306 |
+
|
| 1307 |
+
return QuestionAnsweringModelOutput(
|
| 1308 |
+
loss=total_loss,
|
| 1309 |
+
start_logits=start_logits,
|
| 1310 |
+
end_logits=end_logits,
|
| 1311 |
+
hidden_states=outputs.hidden_states,
|
| 1312 |
+
attentions=outputs.attentions,
|
| 1313 |
+
)
|
| 1314 |
+
|
| 1315 |
+
|
| 1316 |
+
@add_start_docstrings(
|
| 1317 |
+
"""
|
| 1318 |
+
Albert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 1319 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 1320 |
+
""",
|
| 1321 |
+
ALBERT_START_DOCSTRING,
|
| 1322 |
+
)
|
| 1323 |
+
class AlbertForMultipleChoice(AlbertPreTrainedModel):
|
| 1324 |
+
def __init__(self, config: AlbertConfig):
|
| 1325 |
+
super().__init__(config)
|
| 1326 |
+
|
| 1327 |
+
self.albert = AlbertModel(config)
|
| 1328 |
+
self.dropout = nn.Dropout(config.classifier_dropout_prob)
|
| 1329 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 1330 |
+
|
| 1331 |
+
# Initialize weights and apply final processing
|
| 1332 |
+
self.post_init()
|
| 1333 |
+
|
| 1334 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
|
| 1335 |
+
@add_code_sample_docstrings(
|
| 1336 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1337 |
+
output_type=MultipleChoiceModelOutput,
|
| 1338 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1339 |
+
)
|
| 1340 |
+
def forward(
|
| 1341 |
+
self,
|
| 1342 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1343 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1344 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 1345 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1346 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1347 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1348 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1349 |
+
output_attentions: Optional[bool] = None,
|
| 1350 |
+
output_hidden_states: Optional[bool] = None,
|
| 1351 |
+
return_dict: Optional[bool] = None,
|
| 1352 |
+
) -> Union[AlbertForPreTrainingOutput, Tuple]:
|
| 1353 |
+
r"""
|
| 1354 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1355 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
| 1356 |
+
num_choices-1]` where *num_choices* is the size of the second dimension of the input tensors. (see
|
| 1357 |
+
*input_ids* above)
|
| 1358 |
+
"""
|
| 1359 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1360 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
| 1361 |
+
|
| 1362 |
+
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
| 1363 |
+
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 1364 |
+
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
| 1365 |
+
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
| 1366 |
+
inputs_embeds = (
|
| 1367 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
| 1368 |
+
if inputs_embeds is not None
|
| 1369 |
+
else None
|
| 1370 |
+
)
|
| 1371 |
+
outputs = self.albert(
|
| 1372 |
+
input_ids,
|
| 1373 |
+
attention_mask=attention_mask,
|
| 1374 |
+
token_type_ids=token_type_ids,
|
| 1375 |
+
position_ids=position_ids,
|
| 1376 |
+
head_mask=head_mask,
|
| 1377 |
+
inputs_embeds=inputs_embeds,
|
| 1378 |
+
output_attentions=output_attentions,
|
| 1379 |
+
output_hidden_states=output_hidden_states,
|
| 1380 |
+
return_dict=return_dict,
|
| 1381 |
+
)
|
| 1382 |
+
|
| 1383 |
+
pooled_output = outputs[1]
|
| 1384 |
+
|
| 1385 |
+
pooled_output = self.dropout(pooled_output)
|
| 1386 |
+
logits: torch.Tensor = self.classifier(pooled_output)
|
| 1387 |
+
reshaped_logits = logits.view(-1, num_choices)
|
| 1388 |
+
|
| 1389 |
+
loss = None
|
| 1390 |
+
if labels is not None:
|
| 1391 |
+
loss_fct = CrossEntropyLoss()
|
| 1392 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 1393 |
+
|
| 1394 |
+
if not return_dict:
|
| 1395 |
+
output = (reshaped_logits,) + outputs[2:]
|
| 1396 |
+
return ((loss,) + output) if loss is not None else output
|
| 1397 |
+
|
| 1398 |
+
return MultipleChoiceModelOutput(
|
| 1399 |
+
loss=loss,
|
| 1400 |
+
logits=reshaped_logits,
|
| 1401 |
+
hidden_states=outputs.hidden_states,
|
| 1402 |
+
attentions=outputs.attentions,
|
| 1403 |
+
)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/modeling_flax_albert.py
ADDED
|
@@ -0,0 +1,1119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 Google AI, Google Brain and the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import Callable, Optional, Tuple
|
| 17 |
+
|
| 18 |
+
import flax
|
| 19 |
+
import flax.linen as nn
|
| 20 |
+
import jax
|
| 21 |
+
import jax.numpy as jnp
|
| 22 |
+
import numpy as np
|
| 23 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
| 24 |
+
from flax.linen.attention import dot_product_attention_weights
|
| 25 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 26 |
+
from jax import lax
|
| 27 |
+
|
| 28 |
+
from ...modeling_flax_outputs import (
|
| 29 |
+
FlaxBaseModelOutput,
|
| 30 |
+
FlaxBaseModelOutputWithPooling,
|
| 31 |
+
FlaxMaskedLMOutput,
|
| 32 |
+
FlaxMultipleChoiceModelOutput,
|
| 33 |
+
FlaxQuestionAnsweringModelOutput,
|
| 34 |
+
FlaxSequenceClassifierOutput,
|
| 35 |
+
FlaxTokenClassifierOutput,
|
| 36 |
+
)
|
| 37 |
+
from ...modeling_flax_utils import (
|
| 38 |
+
ACT2FN,
|
| 39 |
+
FlaxPreTrainedModel,
|
| 40 |
+
append_call_sample_docstring,
|
| 41 |
+
append_replace_return_docstrings,
|
| 42 |
+
overwrite_call_docstring,
|
| 43 |
+
)
|
| 44 |
+
from ...utils import ModelOutput, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 45 |
+
from .configuration_albert import AlbertConfig
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
logger = logging.get_logger(__name__)
|
| 49 |
+
|
| 50 |
+
_CHECKPOINT_FOR_DOC = "albert-base-v2"
|
| 51 |
+
_CONFIG_FOR_DOC = "AlbertConfig"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@flax.struct.dataclass
|
| 55 |
+
class FlaxAlbertForPreTrainingOutput(ModelOutput):
|
| 56 |
+
"""
|
| 57 |
+
Output type of [`FlaxAlbertForPreTraining`].
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
prediction_logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 61 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 62 |
+
sop_logits (`jnp.ndarray` of shape `(batch_size, 2)`):
|
| 63 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
| 64 |
+
before SoftMax).
|
| 65 |
+
hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 66 |
+
Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 67 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 68 |
+
|
| 69 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 70 |
+
attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 71 |
+
Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 72 |
+
sequence_length)`.
|
| 73 |
+
|
| 74 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 75 |
+
heads.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
prediction_logits: jnp.ndarray = None
|
| 79 |
+
sop_logits: jnp.ndarray = None
|
| 80 |
+
hidden_states: Optional[Tuple[jnp.ndarray]] = None
|
| 81 |
+
attentions: Optional[Tuple[jnp.ndarray]] = None
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
ALBERT_START_DOCSTRING = r"""
|
| 85 |
+
|
| 86 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 87 |
+
library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
|
| 88 |
+
|
| 89 |
+
This model is also a Flax Linen [flax.linen.Module](https://flax.readthedocs.io/en/latest/flax.linen.html#module)
|
| 90 |
+
subclass. Use it as a regular Flax linen Module and refer to the Flax documentation for all matter related to
|
| 91 |
+
general usage and behavior.
|
| 92 |
+
|
| 93 |
+
Finally, this model supports inherent JAX features such as:
|
| 94 |
+
|
| 95 |
+
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
|
| 96 |
+
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
|
| 97 |
+
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
|
| 98 |
+
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
|
| 99 |
+
|
| 100 |
+
Parameters:
|
| 101 |
+
config ([`AlbertConfig`]): Model configuration class with all the parameters of the model.
|
| 102 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 103 |
+
configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 104 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
| 105 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
| 106 |
+
`jax.numpy.bfloat16` (on TPUs).
|
| 107 |
+
|
| 108 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
| 109 |
+
specified all the computation will be performed with the given `dtype`.
|
| 110 |
+
|
| 111 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
| 112 |
+
parameters.**
|
| 113 |
+
|
| 114 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
| 115 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
ALBERT_INPUTS_DOCSTRING = r"""
|
| 119 |
+
Args:
|
| 120 |
+
input_ids (`numpy.ndarray` of shape `({0})`):
|
| 121 |
+
Indices of input sequence tokens in the vocabulary.
|
| 122 |
+
|
| 123 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 124 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 125 |
+
|
| 126 |
+
[What are input IDs?](../glossary#input-ids)
|
| 127 |
+
attention_mask (`numpy.ndarray` of shape `({0})`, *optional*):
|
| 128 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 129 |
+
|
| 130 |
+
- 1 for tokens that are **not masked**,
|
| 131 |
+
- 0 for tokens that are **masked**.
|
| 132 |
+
|
| 133 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 134 |
+
token_type_ids (`numpy.ndarray` of shape `({0})`, *optional*):
|
| 135 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 136 |
+
1]`:
|
| 137 |
+
|
| 138 |
+
- 0 corresponds to a *sentence A* token,
|
| 139 |
+
- 1 corresponds to a *sentence B* token.
|
| 140 |
+
|
| 141 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 142 |
+
position_ids (`numpy.ndarray` of shape `({0})`, *optional*):
|
| 143 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 144 |
+
config.max_position_embeddings - 1]`.
|
| 145 |
+
return_dict (`bool`, *optional*):
|
| 146 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 147 |
+
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class FlaxAlbertEmbeddings(nn.Module):
|
| 152 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 153 |
+
|
| 154 |
+
config: AlbertConfig
|
| 155 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 156 |
+
|
| 157 |
+
def setup(self):
|
| 158 |
+
self.word_embeddings = nn.Embed(
|
| 159 |
+
self.config.vocab_size,
|
| 160 |
+
self.config.embedding_size,
|
| 161 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 162 |
+
)
|
| 163 |
+
self.position_embeddings = nn.Embed(
|
| 164 |
+
self.config.max_position_embeddings,
|
| 165 |
+
self.config.embedding_size,
|
| 166 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 167 |
+
)
|
| 168 |
+
self.token_type_embeddings = nn.Embed(
|
| 169 |
+
self.config.type_vocab_size,
|
| 170 |
+
self.config.embedding_size,
|
| 171 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 172 |
+
)
|
| 173 |
+
self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 174 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 175 |
+
|
| 176 |
+
# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertEmbeddings.__call__
|
| 177 |
+
def __call__(self, input_ids, token_type_ids, position_ids, deterministic: bool = True):
|
| 178 |
+
# Embed
|
| 179 |
+
inputs_embeds = self.word_embeddings(input_ids.astype("i4"))
|
| 180 |
+
position_embeds = self.position_embeddings(position_ids.astype("i4"))
|
| 181 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids.astype("i4"))
|
| 182 |
+
|
| 183 |
+
# Sum all embeddings
|
| 184 |
+
hidden_states = inputs_embeds + token_type_embeddings + position_embeds
|
| 185 |
+
|
| 186 |
+
# Layer Norm
|
| 187 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 188 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 189 |
+
return hidden_states
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class FlaxAlbertSelfAttention(nn.Module):
|
| 193 |
+
config: AlbertConfig
|
| 194 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 195 |
+
|
| 196 |
+
def setup(self):
|
| 197 |
+
if self.config.hidden_size % self.config.num_attention_heads != 0:
|
| 198 |
+
raise ValueError(
|
| 199 |
+
"`config.hidden_size`: {self.config.hidden_size} has to be a multiple of `config.num_attention_heads` "
|
| 200 |
+
" : {self.config.num_attention_heads}"
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
self.query = nn.Dense(
|
| 204 |
+
self.config.hidden_size,
|
| 205 |
+
dtype=self.dtype,
|
| 206 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 207 |
+
)
|
| 208 |
+
self.key = nn.Dense(
|
| 209 |
+
self.config.hidden_size,
|
| 210 |
+
dtype=self.dtype,
|
| 211 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 212 |
+
)
|
| 213 |
+
self.value = nn.Dense(
|
| 214 |
+
self.config.hidden_size,
|
| 215 |
+
dtype=self.dtype,
|
| 216 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 217 |
+
)
|
| 218 |
+
self.dense = nn.Dense(
|
| 219 |
+
self.config.hidden_size,
|
| 220 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 221 |
+
dtype=self.dtype,
|
| 222 |
+
)
|
| 223 |
+
self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 224 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 225 |
+
|
| 226 |
+
def __call__(self, hidden_states, attention_mask, deterministic=True, output_attentions: bool = False):
|
| 227 |
+
head_dim = self.config.hidden_size // self.config.num_attention_heads
|
| 228 |
+
|
| 229 |
+
query_states = self.query(hidden_states).reshape(
|
| 230 |
+
hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
|
| 231 |
+
)
|
| 232 |
+
value_states = self.value(hidden_states).reshape(
|
| 233 |
+
hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
|
| 234 |
+
)
|
| 235 |
+
key_states = self.key(hidden_states).reshape(
|
| 236 |
+
hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# Convert the boolean attention mask to an attention bias.
|
| 240 |
+
if attention_mask is not None:
|
| 241 |
+
# attention mask in the form of attention bias
|
| 242 |
+
attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
|
| 243 |
+
attention_bias = lax.select(
|
| 244 |
+
attention_mask > 0,
|
| 245 |
+
jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
|
| 246 |
+
jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
|
| 247 |
+
)
|
| 248 |
+
else:
|
| 249 |
+
attention_bias = None
|
| 250 |
+
|
| 251 |
+
dropout_rng = None
|
| 252 |
+
if not deterministic and self.config.attention_probs_dropout_prob > 0.0:
|
| 253 |
+
dropout_rng = self.make_rng("dropout")
|
| 254 |
+
|
| 255 |
+
attn_weights = dot_product_attention_weights(
|
| 256 |
+
query_states,
|
| 257 |
+
key_states,
|
| 258 |
+
bias=attention_bias,
|
| 259 |
+
dropout_rng=dropout_rng,
|
| 260 |
+
dropout_rate=self.config.attention_probs_dropout_prob,
|
| 261 |
+
broadcast_dropout=True,
|
| 262 |
+
deterministic=deterministic,
|
| 263 |
+
dtype=self.dtype,
|
| 264 |
+
precision=None,
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
|
| 268 |
+
attn_output = attn_output.reshape(attn_output.shape[:2] + (-1,))
|
| 269 |
+
|
| 270 |
+
projected_attn_output = self.dense(attn_output)
|
| 271 |
+
projected_attn_output = self.dropout(projected_attn_output, deterministic=deterministic)
|
| 272 |
+
layernormed_attn_output = self.LayerNorm(projected_attn_output + hidden_states)
|
| 273 |
+
outputs = (layernormed_attn_output, attn_weights) if output_attentions else (layernormed_attn_output,)
|
| 274 |
+
return outputs
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
class FlaxAlbertLayer(nn.Module):
|
| 278 |
+
config: AlbertConfig
|
| 279 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 280 |
+
|
| 281 |
+
def setup(self):
|
| 282 |
+
self.attention = FlaxAlbertSelfAttention(self.config, dtype=self.dtype)
|
| 283 |
+
self.ffn = nn.Dense(
|
| 284 |
+
self.config.intermediate_size,
|
| 285 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 286 |
+
dtype=self.dtype,
|
| 287 |
+
)
|
| 288 |
+
self.activation = ACT2FN[self.config.hidden_act]
|
| 289 |
+
self.ffn_output = nn.Dense(
|
| 290 |
+
self.config.hidden_size,
|
| 291 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 292 |
+
dtype=self.dtype,
|
| 293 |
+
)
|
| 294 |
+
self.full_layer_layer_norm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 295 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 296 |
+
|
| 297 |
+
def __call__(
|
| 298 |
+
self,
|
| 299 |
+
hidden_states,
|
| 300 |
+
attention_mask,
|
| 301 |
+
deterministic: bool = True,
|
| 302 |
+
output_attentions: bool = False,
|
| 303 |
+
):
|
| 304 |
+
attention_outputs = self.attention(
|
| 305 |
+
hidden_states, attention_mask, deterministic=deterministic, output_attentions=output_attentions
|
| 306 |
+
)
|
| 307 |
+
attention_output = attention_outputs[0]
|
| 308 |
+
ffn_output = self.ffn(attention_output)
|
| 309 |
+
ffn_output = self.activation(ffn_output)
|
| 310 |
+
ffn_output = self.ffn_output(ffn_output)
|
| 311 |
+
ffn_output = self.dropout(ffn_output, deterministic=deterministic)
|
| 312 |
+
hidden_states = self.full_layer_layer_norm(ffn_output + attention_output)
|
| 313 |
+
|
| 314 |
+
outputs = (hidden_states,)
|
| 315 |
+
|
| 316 |
+
if output_attentions:
|
| 317 |
+
outputs += (attention_outputs[1],)
|
| 318 |
+
return outputs
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class FlaxAlbertLayerCollection(nn.Module):
|
| 322 |
+
config: AlbertConfig
|
| 323 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 324 |
+
|
| 325 |
+
def setup(self):
|
| 326 |
+
self.layers = [
|
| 327 |
+
FlaxAlbertLayer(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.inner_group_num)
|
| 328 |
+
]
|
| 329 |
+
|
| 330 |
+
def __call__(
|
| 331 |
+
self,
|
| 332 |
+
hidden_states,
|
| 333 |
+
attention_mask,
|
| 334 |
+
deterministic: bool = True,
|
| 335 |
+
output_attentions: bool = False,
|
| 336 |
+
output_hidden_states: bool = False,
|
| 337 |
+
):
|
| 338 |
+
layer_hidden_states = ()
|
| 339 |
+
layer_attentions = ()
|
| 340 |
+
|
| 341 |
+
for layer_index, albert_layer in enumerate(self.layers):
|
| 342 |
+
layer_output = albert_layer(
|
| 343 |
+
hidden_states,
|
| 344 |
+
attention_mask,
|
| 345 |
+
deterministic=deterministic,
|
| 346 |
+
output_attentions=output_attentions,
|
| 347 |
+
)
|
| 348 |
+
hidden_states = layer_output[0]
|
| 349 |
+
|
| 350 |
+
if output_attentions:
|
| 351 |
+
layer_attentions = layer_attentions + (layer_output[1],)
|
| 352 |
+
|
| 353 |
+
if output_hidden_states:
|
| 354 |
+
layer_hidden_states = layer_hidden_states + (hidden_states,)
|
| 355 |
+
|
| 356 |
+
outputs = (hidden_states,)
|
| 357 |
+
if output_hidden_states:
|
| 358 |
+
outputs = outputs + (layer_hidden_states,)
|
| 359 |
+
if output_attentions:
|
| 360 |
+
outputs = outputs + (layer_attentions,)
|
| 361 |
+
return outputs # last-layer hidden state, (layer hidden states), (layer attentions)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class FlaxAlbertLayerCollections(nn.Module):
|
| 365 |
+
config: AlbertConfig
|
| 366 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 367 |
+
layer_index: Optional[str] = None
|
| 368 |
+
|
| 369 |
+
def setup(self):
|
| 370 |
+
self.albert_layers = FlaxAlbertLayerCollection(self.config, dtype=self.dtype)
|
| 371 |
+
|
| 372 |
+
def __call__(
|
| 373 |
+
self,
|
| 374 |
+
hidden_states,
|
| 375 |
+
attention_mask,
|
| 376 |
+
deterministic: bool = True,
|
| 377 |
+
output_attentions: bool = False,
|
| 378 |
+
output_hidden_states: bool = False,
|
| 379 |
+
):
|
| 380 |
+
outputs = self.albert_layers(
|
| 381 |
+
hidden_states,
|
| 382 |
+
attention_mask,
|
| 383 |
+
deterministic=deterministic,
|
| 384 |
+
output_attentions=output_attentions,
|
| 385 |
+
output_hidden_states=output_hidden_states,
|
| 386 |
+
)
|
| 387 |
+
return outputs
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
class FlaxAlbertLayerGroups(nn.Module):
|
| 391 |
+
config: AlbertConfig
|
| 392 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 393 |
+
|
| 394 |
+
def setup(self):
|
| 395 |
+
self.layers = [
|
| 396 |
+
FlaxAlbertLayerCollections(self.config, name=str(i), layer_index=str(i), dtype=self.dtype)
|
| 397 |
+
for i in range(self.config.num_hidden_groups)
|
| 398 |
+
]
|
| 399 |
+
|
| 400 |
+
def __call__(
|
| 401 |
+
self,
|
| 402 |
+
hidden_states,
|
| 403 |
+
attention_mask,
|
| 404 |
+
deterministic: bool = True,
|
| 405 |
+
output_attentions: bool = False,
|
| 406 |
+
output_hidden_states: bool = False,
|
| 407 |
+
return_dict: bool = True,
|
| 408 |
+
):
|
| 409 |
+
all_attentions = () if output_attentions else None
|
| 410 |
+
all_hidden_states = (hidden_states,) if output_hidden_states else None
|
| 411 |
+
|
| 412 |
+
for i in range(self.config.num_hidden_layers):
|
| 413 |
+
# Index of the hidden group
|
| 414 |
+
group_idx = int(i / (self.config.num_hidden_layers / self.config.num_hidden_groups))
|
| 415 |
+
layer_group_output = self.layers[group_idx](
|
| 416 |
+
hidden_states,
|
| 417 |
+
attention_mask,
|
| 418 |
+
deterministic=deterministic,
|
| 419 |
+
output_attentions=output_attentions,
|
| 420 |
+
output_hidden_states=output_hidden_states,
|
| 421 |
+
)
|
| 422 |
+
hidden_states = layer_group_output[0]
|
| 423 |
+
|
| 424 |
+
if output_attentions:
|
| 425 |
+
all_attentions = all_attentions + layer_group_output[-1]
|
| 426 |
+
|
| 427 |
+
if output_hidden_states:
|
| 428 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 429 |
+
|
| 430 |
+
if not return_dict:
|
| 431 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
|
| 432 |
+
return FlaxBaseModelOutput(
|
| 433 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
class FlaxAlbertEncoder(nn.Module):
|
| 438 |
+
config: AlbertConfig
|
| 439 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 440 |
+
|
| 441 |
+
def setup(self):
|
| 442 |
+
self.embedding_hidden_mapping_in = nn.Dense(
|
| 443 |
+
self.config.hidden_size,
|
| 444 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 445 |
+
dtype=self.dtype,
|
| 446 |
+
)
|
| 447 |
+
self.albert_layer_groups = FlaxAlbertLayerGroups(self.config, dtype=self.dtype)
|
| 448 |
+
|
| 449 |
+
def __call__(
|
| 450 |
+
self,
|
| 451 |
+
hidden_states,
|
| 452 |
+
attention_mask,
|
| 453 |
+
deterministic: bool = True,
|
| 454 |
+
output_attentions: bool = False,
|
| 455 |
+
output_hidden_states: bool = False,
|
| 456 |
+
return_dict: bool = True,
|
| 457 |
+
):
|
| 458 |
+
hidden_states = self.embedding_hidden_mapping_in(hidden_states)
|
| 459 |
+
return self.albert_layer_groups(
|
| 460 |
+
hidden_states,
|
| 461 |
+
attention_mask,
|
| 462 |
+
deterministic=deterministic,
|
| 463 |
+
output_attentions=output_attentions,
|
| 464 |
+
output_hidden_states=output_hidden_states,
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
class FlaxAlbertOnlyMLMHead(nn.Module):
|
| 469 |
+
config: AlbertConfig
|
| 470 |
+
dtype: jnp.dtype = jnp.float32
|
| 471 |
+
bias_init: Callable[..., np.ndarray] = jax.nn.initializers.zeros
|
| 472 |
+
|
| 473 |
+
def setup(self):
|
| 474 |
+
self.dense = nn.Dense(self.config.embedding_size, dtype=self.dtype)
|
| 475 |
+
self.activation = ACT2FN[self.config.hidden_act]
|
| 476 |
+
self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 477 |
+
self.decoder = nn.Dense(self.config.vocab_size, dtype=self.dtype, use_bias=False)
|
| 478 |
+
self.bias = self.param("bias", self.bias_init, (self.config.vocab_size,))
|
| 479 |
+
|
| 480 |
+
def __call__(self, hidden_states, shared_embedding=None):
|
| 481 |
+
hidden_states = self.dense(hidden_states)
|
| 482 |
+
hidden_states = self.activation(hidden_states)
|
| 483 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 484 |
+
|
| 485 |
+
if shared_embedding is not None:
|
| 486 |
+
hidden_states = self.decoder.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
|
| 487 |
+
else:
|
| 488 |
+
hidden_states = self.decoder(hidden_states)
|
| 489 |
+
|
| 490 |
+
hidden_states += self.bias
|
| 491 |
+
return hidden_states
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
class FlaxAlbertSOPHead(nn.Module):
|
| 495 |
+
config: AlbertConfig
|
| 496 |
+
dtype: jnp.dtype = jnp.float32
|
| 497 |
+
|
| 498 |
+
def setup(self):
|
| 499 |
+
self.dropout = nn.Dropout(self.config.classifier_dropout_prob)
|
| 500 |
+
self.classifier = nn.Dense(2, dtype=self.dtype)
|
| 501 |
+
|
| 502 |
+
def __call__(self, pooled_output, deterministic=True):
|
| 503 |
+
pooled_output = self.dropout(pooled_output, deterministic=deterministic)
|
| 504 |
+
logits = self.classifier(pooled_output)
|
| 505 |
+
return logits
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
class FlaxAlbertPreTrainedModel(FlaxPreTrainedModel):
|
| 509 |
+
"""
|
| 510 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 511 |
+
models.
|
| 512 |
+
"""
|
| 513 |
+
|
| 514 |
+
config_class = AlbertConfig
|
| 515 |
+
base_model_prefix = "albert"
|
| 516 |
+
module_class: nn.Module = None
|
| 517 |
+
|
| 518 |
+
def __init__(
|
| 519 |
+
self,
|
| 520 |
+
config: AlbertConfig,
|
| 521 |
+
input_shape: Tuple = (1, 1),
|
| 522 |
+
seed: int = 0,
|
| 523 |
+
dtype: jnp.dtype = jnp.float32,
|
| 524 |
+
_do_init: bool = True,
|
| 525 |
+
**kwargs,
|
| 526 |
+
):
|
| 527 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
| 528 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
| 529 |
+
|
| 530 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
|
| 531 |
+
# init input tensors
|
| 532 |
+
input_ids = jnp.zeros(input_shape, dtype="i4")
|
| 533 |
+
token_type_ids = jnp.zeros_like(input_ids)
|
| 534 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
|
| 535 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 536 |
+
|
| 537 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
| 538 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
| 539 |
+
|
| 540 |
+
random_params = self.module.init(
|
| 541 |
+
rngs, input_ids, attention_mask, token_type_ids, position_ids, return_dict=False
|
| 542 |
+
)["params"]
|
| 543 |
+
|
| 544 |
+
if params is not None:
|
| 545 |
+
random_params = flatten_dict(unfreeze(random_params))
|
| 546 |
+
params = flatten_dict(unfreeze(params))
|
| 547 |
+
for missing_key in self._missing_keys:
|
| 548 |
+
params[missing_key] = random_params[missing_key]
|
| 549 |
+
self._missing_keys = set()
|
| 550 |
+
return freeze(unflatten_dict(params))
|
| 551 |
+
else:
|
| 552 |
+
return random_params
|
| 553 |
+
|
| 554 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 555 |
+
def __call__(
|
| 556 |
+
self,
|
| 557 |
+
input_ids,
|
| 558 |
+
attention_mask=None,
|
| 559 |
+
token_type_ids=None,
|
| 560 |
+
position_ids=None,
|
| 561 |
+
params: dict = None,
|
| 562 |
+
dropout_rng: jax.random.PRNGKey = None,
|
| 563 |
+
train: bool = False,
|
| 564 |
+
output_attentions: Optional[bool] = None,
|
| 565 |
+
output_hidden_states: Optional[bool] = None,
|
| 566 |
+
return_dict: Optional[bool] = None,
|
| 567 |
+
):
|
| 568 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 569 |
+
output_hidden_states = (
|
| 570 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 571 |
+
)
|
| 572 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 573 |
+
|
| 574 |
+
# init input tensors if not passed
|
| 575 |
+
if token_type_ids is None:
|
| 576 |
+
token_type_ids = jnp.zeros_like(input_ids)
|
| 577 |
+
|
| 578 |
+
if position_ids is None:
|
| 579 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
|
| 580 |
+
|
| 581 |
+
if attention_mask is None:
|
| 582 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 583 |
+
|
| 584 |
+
# Handle any PRNG if needed
|
| 585 |
+
rngs = {}
|
| 586 |
+
if dropout_rng is not None:
|
| 587 |
+
rngs["dropout"] = dropout_rng
|
| 588 |
+
|
| 589 |
+
return self.module.apply(
|
| 590 |
+
{"params": params or self.params},
|
| 591 |
+
jnp.array(input_ids, dtype="i4"),
|
| 592 |
+
jnp.array(attention_mask, dtype="i4"),
|
| 593 |
+
jnp.array(token_type_ids, dtype="i4"),
|
| 594 |
+
jnp.array(position_ids, dtype="i4"),
|
| 595 |
+
not train,
|
| 596 |
+
output_attentions,
|
| 597 |
+
output_hidden_states,
|
| 598 |
+
return_dict,
|
| 599 |
+
rngs=rngs,
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
class FlaxAlbertModule(nn.Module):
|
| 604 |
+
config: AlbertConfig
|
| 605 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 606 |
+
add_pooling_layer: bool = True
|
| 607 |
+
|
| 608 |
+
def setup(self):
|
| 609 |
+
self.embeddings = FlaxAlbertEmbeddings(self.config, dtype=self.dtype)
|
| 610 |
+
self.encoder = FlaxAlbertEncoder(self.config, dtype=self.dtype)
|
| 611 |
+
if self.add_pooling_layer:
|
| 612 |
+
self.pooler = nn.Dense(
|
| 613 |
+
self.config.hidden_size,
|
| 614 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 615 |
+
dtype=self.dtype,
|
| 616 |
+
name="pooler",
|
| 617 |
+
)
|
| 618 |
+
self.pooler_activation = nn.tanh
|
| 619 |
+
else:
|
| 620 |
+
self.pooler = None
|
| 621 |
+
self.pooler_activation = None
|
| 622 |
+
|
| 623 |
+
def __call__(
|
| 624 |
+
self,
|
| 625 |
+
input_ids,
|
| 626 |
+
attention_mask,
|
| 627 |
+
token_type_ids: Optional[np.ndarray] = None,
|
| 628 |
+
position_ids: Optional[np.ndarray] = None,
|
| 629 |
+
deterministic: bool = True,
|
| 630 |
+
output_attentions: bool = False,
|
| 631 |
+
output_hidden_states: bool = False,
|
| 632 |
+
return_dict: bool = True,
|
| 633 |
+
):
|
| 634 |
+
# make sure `token_type_ids` is correctly initialized when not passed
|
| 635 |
+
if token_type_ids is None:
|
| 636 |
+
token_type_ids = jnp.zeros_like(input_ids)
|
| 637 |
+
|
| 638 |
+
# make sure `position_ids` is correctly initialized when not passed
|
| 639 |
+
if position_ids is None:
|
| 640 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
|
| 641 |
+
|
| 642 |
+
hidden_states = self.embeddings(input_ids, token_type_ids, position_ids, deterministic=deterministic)
|
| 643 |
+
|
| 644 |
+
outputs = self.encoder(
|
| 645 |
+
hidden_states,
|
| 646 |
+
attention_mask,
|
| 647 |
+
deterministic=deterministic,
|
| 648 |
+
output_attentions=output_attentions,
|
| 649 |
+
output_hidden_states=output_hidden_states,
|
| 650 |
+
return_dict=return_dict,
|
| 651 |
+
)
|
| 652 |
+
hidden_states = outputs[0]
|
| 653 |
+
if self.add_pooling_layer:
|
| 654 |
+
pooled = self.pooler(hidden_states[:, 0])
|
| 655 |
+
pooled = self.pooler_activation(pooled)
|
| 656 |
+
else:
|
| 657 |
+
pooled = None
|
| 658 |
+
|
| 659 |
+
if not return_dict:
|
| 660 |
+
# if pooled is None, don't return it
|
| 661 |
+
if pooled is None:
|
| 662 |
+
return (hidden_states,) + outputs[1:]
|
| 663 |
+
return (hidden_states, pooled) + outputs[1:]
|
| 664 |
+
|
| 665 |
+
return FlaxBaseModelOutputWithPooling(
|
| 666 |
+
last_hidden_state=hidden_states,
|
| 667 |
+
pooler_output=pooled,
|
| 668 |
+
hidden_states=outputs.hidden_states,
|
| 669 |
+
attentions=outputs.attentions,
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
@add_start_docstrings(
|
| 674 |
+
"The bare Albert Model transformer outputting raw hidden-states without any specific head on top.",
|
| 675 |
+
ALBERT_START_DOCSTRING,
|
| 676 |
+
)
|
| 677 |
+
class FlaxAlbertModel(FlaxAlbertPreTrainedModel):
|
| 678 |
+
module_class = FlaxAlbertModule
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
append_call_sample_docstring(FlaxAlbertModel, _CHECKPOINT_FOR_DOC, FlaxBaseModelOutputWithPooling, _CONFIG_FOR_DOC)
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
class FlaxAlbertForPreTrainingModule(nn.Module):
|
| 685 |
+
config: AlbertConfig
|
| 686 |
+
dtype: jnp.dtype = jnp.float32
|
| 687 |
+
|
| 688 |
+
def setup(self):
|
| 689 |
+
self.albert = FlaxAlbertModule(config=self.config, dtype=self.dtype)
|
| 690 |
+
self.predictions = FlaxAlbertOnlyMLMHead(config=self.config, dtype=self.dtype)
|
| 691 |
+
self.sop_classifier = FlaxAlbertSOPHead(config=self.config, dtype=self.dtype)
|
| 692 |
+
|
| 693 |
+
def __call__(
|
| 694 |
+
self,
|
| 695 |
+
input_ids,
|
| 696 |
+
attention_mask,
|
| 697 |
+
token_type_ids,
|
| 698 |
+
position_ids,
|
| 699 |
+
deterministic: bool = True,
|
| 700 |
+
output_attentions: bool = False,
|
| 701 |
+
output_hidden_states: bool = False,
|
| 702 |
+
return_dict: bool = True,
|
| 703 |
+
):
|
| 704 |
+
# Model
|
| 705 |
+
outputs = self.albert(
|
| 706 |
+
input_ids,
|
| 707 |
+
attention_mask,
|
| 708 |
+
token_type_ids,
|
| 709 |
+
position_ids,
|
| 710 |
+
deterministic=deterministic,
|
| 711 |
+
output_attentions=output_attentions,
|
| 712 |
+
output_hidden_states=output_hidden_states,
|
| 713 |
+
return_dict=return_dict,
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
if self.config.tie_word_embeddings:
|
| 717 |
+
shared_embedding = self.albert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
|
| 718 |
+
else:
|
| 719 |
+
shared_embedding = None
|
| 720 |
+
|
| 721 |
+
hidden_states = outputs[0]
|
| 722 |
+
pooled_output = outputs[1]
|
| 723 |
+
|
| 724 |
+
prediction_scores = self.predictions(hidden_states, shared_embedding=shared_embedding)
|
| 725 |
+
sop_scores = self.sop_classifier(pooled_output, deterministic=deterministic)
|
| 726 |
+
|
| 727 |
+
if not return_dict:
|
| 728 |
+
return (prediction_scores, sop_scores) + outputs[2:]
|
| 729 |
+
|
| 730 |
+
return FlaxAlbertForPreTrainingOutput(
|
| 731 |
+
prediction_logits=prediction_scores,
|
| 732 |
+
sop_logits=sop_scores,
|
| 733 |
+
hidden_states=outputs.hidden_states,
|
| 734 |
+
attentions=outputs.attentions,
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
|
| 738 |
+
@add_start_docstrings(
|
| 739 |
+
"""
|
| 740 |
+
Albert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
|
| 741 |
+
`sentence order prediction (classification)` head.
|
| 742 |
+
""",
|
| 743 |
+
ALBERT_START_DOCSTRING,
|
| 744 |
+
)
|
| 745 |
+
class FlaxAlbertForPreTraining(FlaxAlbertPreTrainedModel):
|
| 746 |
+
module_class = FlaxAlbertForPreTrainingModule
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
FLAX_ALBERT_FOR_PRETRAINING_DOCSTRING = """
|
| 750 |
+
Returns:
|
| 751 |
+
|
| 752 |
+
Example:
|
| 753 |
+
|
| 754 |
+
```python
|
| 755 |
+
>>> from transformers import AutoTokenizer, FlaxAlbertForPreTraining
|
| 756 |
+
|
| 757 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("albert-base-v2")
|
| 758 |
+
>>> model = FlaxAlbertForPreTraining.from_pretrained("albert-base-v2")
|
| 759 |
+
|
| 760 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")
|
| 761 |
+
>>> outputs = model(**inputs)
|
| 762 |
+
|
| 763 |
+
>>> prediction_logits = outputs.prediction_logits
|
| 764 |
+
>>> seq_relationship_logits = outputs.sop_logits
|
| 765 |
+
```
|
| 766 |
+
"""
|
| 767 |
+
|
| 768 |
+
overwrite_call_docstring(
|
| 769 |
+
FlaxAlbertForPreTraining,
|
| 770 |
+
ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length") + FLAX_ALBERT_FOR_PRETRAINING_DOCSTRING,
|
| 771 |
+
)
|
| 772 |
+
append_replace_return_docstrings(
|
| 773 |
+
FlaxAlbertForPreTraining, output_type=FlaxAlbertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC
|
| 774 |
+
)
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
class FlaxAlbertForMaskedLMModule(nn.Module):
|
| 778 |
+
config: AlbertConfig
|
| 779 |
+
dtype: jnp.dtype = jnp.float32
|
| 780 |
+
|
| 781 |
+
def setup(self):
|
| 782 |
+
self.albert = FlaxAlbertModule(config=self.config, add_pooling_layer=False, dtype=self.dtype)
|
| 783 |
+
self.predictions = FlaxAlbertOnlyMLMHead(config=self.config, dtype=self.dtype)
|
| 784 |
+
|
| 785 |
+
def __call__(
|
| 786 |
+
self,
|
| 787 |
+
input_ids,
|
| 788 |
+
attention_mask,
|
| 789 |
+
token_type_ids,
|
| 790 |
+
position_ids,
|
| 791 |
+
deterministic: bool = True,
|
| 792 |
+
output_attentions: bool = False,
|
| 793 |
+
output_hidden_states: bool = False,
|
| 794 |
+
return_dict: bool = True,
|
| 795 |
+
):
|
| 796 |
+
# Model
|
| 797 |
+
outputs = self.albert(
|
| 798 |
+
input_ids,
|
| 799 |
+
attention_mask,
|
| 800 |
+
token_type_ids,
|
| 801 |
+
position_ids,
|
| 802 |
+
deterministic=deterministic,
|
| 803 |
+
output_attentions=output_attentions,
|
| 804 |
+
output_hidden_states=output_hidden_states,
|
| 805 |
+
return_dict=return_dict,
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
hidden_states = outputs[0]
|
| 809 |
+
if self.config.tie_word_embeddings:
|
| 810 |
+
shared_embedding = self.albert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
|
| 811 |
+
else:
|
| 812 |
+
shared_embedding = None
|
| 813 |
+
|
| 814 |
+
# Compute the prediction scores
|
| 815 |
+
logits = self.predictions(hidden_states, shared_embedding=shared_embedding)
|
| 816 |
+
|
| 817 |
+
if not return_dict:
|
| 818 |
+
return (logits,) + outputs[1:]
|
| 819 |
+
|
| 820 |
+
return FlaxMaskedLMOutput(
|
| 821 |
+
logits=logits,
|
| 822 |
+
hidden_states=outputs.hidden_states,
|
| 823 |
+
attentions=outputs.attentions,
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
@add_start_docstrings("""Albert Model with a `language modeling` head on top.""", ALBERT_START_DOCSTRING)
|
| 828 |
+
class FlaxAlbertForMaskedLM(FlaxAlbertPreTrainedModel):
|
| 829 |
+
module_class = FlaxAlbertForMaskedLMModule
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
append_call_sample_docstring(FlaxAlbertForMaskedLM, _CHECKPOINT_FOR_DOC, FlaxMaskedLMOutput, _CONFIG_FOR_DOC)
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
class FlaxAlbertForSequenceClassificationModule(nn.Module):
|
| 836 |
+
config: AlbertConfig
|
| 837 |
+
dtype: jnp.dtype = jnp.float32
|
| 838 |
+
|
| 839 |
+
def setup(self):
|
| 840 |
+
self.albert = FlaxAlbertModule(config=self.config, dtype=self.dtype)
|
| 841 |
+
classifier_dropout = (
|
| 842 |
+
self.config.classifier_dropout_prob
|
| 843 |
+
if self.config.classifier_dropout_prob is not None
|
| 844 |
+
else self.config.hidden_dropout_prob
|
| 845 |
+
)
|
| 846 |
+
self.dropout = nn.Dropout(rate=classifier_dropout)
|
| 847 |
+
self.classifier = nn.Dense(
|
| 848 |
+
self.config.num_labels,
|
| 849 |
+
dtype=self.dtype,
|
| 850 |
+
)
|
| 851 |
+
|
| 852 |
+
def __call__(
|
| 853 |
+
self,
|
| 854 |
+
input_ids,
|
| 855 |
+
attention_mask,
|
| 856 |
+
token_type_ids,
|
| 857 |
+
position_ids,
|
| 858 |
+
deterministic: bool = True,
|
| 859 |
+
output_attentions: bool = False,
|
| 860 |
+
output_hidden_states: bool = False,
|
| 861 |
+
return_dict: bool = True,
|
| 862 |
+
):
|
| 863 |
+
# Model
|
| 864 |
+
outputs = self.albert(
|
| 865 |
+
input_ids,
|
| 866 |
+
attention_mask,
|
| 867 |
+
token_type_ids,
|
| 868 |
+
position_ids,
|
| 869 |
+
deterministic=deterministic,
|
| 870 |
+
output_attentions=output_attentions,
|
| 871 |
+
output_hidden_states=output_hidden_states,
|
| 872 |
+
return_dict=return_dict,
|
| 873 |
+
)
|
| 874 |
+
|
| 875 |
+
pooled_output = outputs[1]
|
| 876 |
+
pooled_output = self.dropout(pooled_output, deterministic=deterministic)
|
| 877 |
+
logits = self.classifier(pooled_output)
|
| 878 |
+
|
| 879 |
+
if not return_dict:
|
| 880 |
+
return (logits,) + outputs[2:]
|
| 881 |
+
|
| 882 |
+
return FlaxSequenceClassifierOutput(
|
| 883 |
+
logits=logits,
|
| 884 |
+
hidden_states=outputs.hidden_states,
|
| 885 |
+
attentions=outputs.attentions,
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
@add_start_docstrings(
|
| 890 |
+
"""
|
| 891 |
+
Albert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
| 892 |
+
output) e.g. for GLUE tasks.
|
| 893 |
+
""",
|
| 894 |
+
ALBERT_START_DOCSTRING,
|
| 895 |
+
)
|
| 896 |
+
class FlaxAlbertForSequenceClassification(FlaxAlbertPreTrainedModel):
|
| 897 |
+
module_class = FlaxAlbertForSequenceClassificationModule
|
| 898 |
+
|
| 899 |
+
|
| 900 |
+
append_call_sample_docstring(
|
| 901 |
+
FlaxAlbertForSequenceClassification,
|
| 902 |
+
_CHECKPOINT_FOR_DOC,
|
| 903 |
+
FlaxSequenceClassifierOutput,
|
| 904 |
+
_CONFIG_FOR_DOC,
|
| 905 |
+
)
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
class FlaxAlbertForMultipleChoiceModule(nn.Module):
|
| 909 |
+
config: AlbertConfig
|
| 910 |
+
dtype: jnp.dtype = jnp.float32
|
| 911 |
+
|
| 912 |
+
def setup(self):
|
| 913 |
+
self.albert = FlaxAlbertModule(config=self.config, dtype=self.dtype)
|
| 914 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 915 |
+
self.classifier = nn.Dense(1, dtype=self.dtype)
|
| 916 |
+
|
| 917 |
+
def __call__(
|
| 918 |
+
self,
|
| 919 |
+
input_ids,
|
| 920 |
+
attention_mask,
|
| 921 |
+
token_type_ids,
|
| 922 |
+
position_ids,
|
| 923 |
+
deterministic: bool = True,
|
| 924 |
+
output_attentions: bool = False,
|
| 925 |
+
output_hidden_states: bool = False,
|
| 926 |
+
return_dict: bool = True,
|
| 927 |
+
):
|
| 928 |
+
num_choices = input_ids.shape[1]
|
| 929 |
+
input_ids = input_ids.reshape(-1, input_ids.shape[-1]) if input_ids is not None else None
|
| 930 |
+
attention_mask = attention_mask.reshape(-1, attention_mask.shape[-1]) if attention_mask is not None else None
|
| 931 |
+
token_type_ids = token_type_ids.reshape(-1, token_type_ids.shape[-1]) if token_type_ids is not None else None
|
| 932 |
+
position_ids = position_ids.reshape(-1, position_ids.shape[-1]) if position_ids is not None else None
|
| 933 |
+
|
| 934 |
+
# Model
|
| 935 |
+
outputs = self.albert(
|
| 936 |
+
input_ids,
|
| 937 |
+
attention_mask,
|
| 938 |
+
token_type_ids,
|
| 939 |
+
position_ids,
|
| 940 |
+
deterministic=deterministic,
|
| 941 |
+
output_attentions=output_attentions,
|
| 942 |
+
output_hidden_states=output_hidden_states,
|
| 943 |
+
return_dict=return_dict,
|
| 944 |
+
)
|
| 945 |
+
|
| 946 |
+
pooled_output = outputs[1]
|
| 947 |
+
pooled_output = self.dropout(pooled_output, deterministic=deterministic)
|
| 948 |
+
logits = self.classifier(pooled_output)
|
| 949 |
+
|
| 950 |
+
reshaped_logits = logits.reshape(-1, num_choices)
|
| 951 |
+
|
| 952 |
+
if not return_dict:
|
| 953 |
+
return (reshaped_logits,) + outputs[2:]
|
| 954 |
+
|
| 955 |
+
return FlaxMultipleChoiceModelOutput(
|
| 956 |
+
logits=reshaped_logits,
|
| 957 |
+
hidden_states=outputs.hidden_states,
|
| 958 |
+
attentions=outputs.attentions,
|
| 959 |
+
)
|
| 960 |
+
|
| 961 |
+
|
| 962 |
+
@add_start_docstrings(
|
| 963 |
+
"""
|
| 964 |
+
Albert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 965 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 966 |
+
""",
|
| 967 |
+
ALBERT_START_DOCSTRING,
|
| 968 |
+
)
|
| 969 |
+
class FlaxAlbertForMultipleChoice(FlaxAlbertPreTrainedModel):
|
| 970 |
+
module_class = FlaxAlbertForMultipleChoiceModule
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
overwrite_call_docstring(
|
| 974 |
+
FlaxAlbertForMultipleChoice, ALBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
|
| 975 |
+
)
|
| 976 |
+
append_call_sample_docstring(
|
| 977 |
+
FlaxAlbertForMultipleChoice,
|
| 978 |
+
_CHECKPOINT_FOR_DOC,
|
| 979 |
+
FlaxMultipleChoiceModelOutput,
|
| 980 |
+
_CONFIG_FOR_DOC,
|
| 981 |
+
)
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
class FlaxAlbertForTokenClassificationModule(nn.Module):
|
| 985 |
+
config: AlbertConfig
|
| 986 |
+
dtype: jnp.dtype = jnp.float32
|
| 987 |
+
|
| 988 |
+
def setup(self):
|
| 989 |
+
self.albert = FlaxAlbertModule(config=self.config, dtype=self.dtype, add_pooling_layer=False)
|
| 990 |
+
classifier_dropout = (
|
| 991 |
+
self.config.classifier_dropout_prob
|
| 992 |
+
if self.config.classifier_dropout_prob is not None
|
| 993 |
+
else self.config.hidden_dropout_prob
|
| 994 |
+
)
|
| 995 |
+
self.dropout = nn.Dropout(rate=classifier_dropout)
|
| 996 |
+
self.classifier = nn.Dense(self.config.num_labels, dtype=self.dtype)
|
| 997 |
+
|
| 998 |
+
def __call__(
|
| 999 |
+
self,
|
| 1000 |
+
input_ids,
|
| 1001 |
+
attention_mask,
|
| 1002 |
+
token_type_ids,
|
| 1003 |
+
position_ids,
|
| 1004 |
+
deterministic: bool = True,
|
| 1005 |
+
output_attentions: bool = False,
|
| 1006 |
+
output_hidden_states: bool = False,
|
| 1007 |
+
return_dict: bool = True,
|
| 1008 |
+
):
|
| 1009 |
+
# Model
|
| 1010 |
+
outputs = self.albert(
|
| 1011 |
+
input_ids,
|
| 1012 |
+
attention_mask,
|
| 1013 |
+
token_type_ids,
|
| 1014 |
+
position_ids,
|
| 1015 |
+
deterministic=deterministic,
|
| 1016 |
+
output_attentions=output_attentions,
|
| 1017 |
+
output_hidden_states=output_hidden_states,
|
| 1018 |
+
return_dict=return_dict,
|
| 1019 |
+
)
|
| 1020 |
+
|
| 1021 |
+
hidden_states = outputs[0]
|
| 1022 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 1023 |
+
logits = self.classifier(hidden_states)
|
| 1024 |
+
|
| 1025 |
+
if not return_dict:
|
| 1026 |
+
return (logits,) + outputs[1:]
|
| 1027 |
+
|
| 1028 |
+
return FlaxTokenClassifierOutput(
|
| 1029 |
+
logits=logits,
|
| 1030 |
+
hidden_states=outputs.hidden_states,
|
| 1031 |
+
attentions=outputs.attentions,
|
| 1032 |
+
)
|
| 1033 |
+
|
| 1034 |
+
|
| 1035 |
+
@add_start_docstrings(
|
| 1036 |
+
"""
|
| 1037 |
+
Albert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1038 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1039 |
+
""",
|
| 1040 |
+
ALBERT_START_DOCSTRING,
|
| 1041 |
+
)
|
| 1042 |
+
class FlaxAlbertForTokenClassification(FlaxAlbertPreTrainedModel):
|
| 1043 |
+
module_class = FlaxAlbertForTokenClassificationModule
|
| 1044 |
+
|
| 1045 |
+
|
| 1046 |
+
append_call_sample_docstring(
|
| 1047 |
+
FlaxAlbertForTokenClassification,
|
| 1048 |
+
_CHECKPOINT_FOR_DOC,
|
| 1049 |
+
FlaxTokenClassifierOutput,
|
| 1050 |
+
_CONFIG_FOR_DOC,
|
| 1051 |
+
)
|
| 1052 |
+
|
| 1053 |
+
|
| 1054 |
+
class FlaxAlbertForQuestionAnsweringModule(nn.Module):
|
| 1055 |
+
config: AlbertConfig
|
| 1056 |
+
dtype: jnp.dtype = jnp.float32
|
| 1057 |
+
|
| 1058 |
+
def setup(self):
|
| 1059 |
+
self.albert = FlaxAlbertModule(config=self.config, dtype=self.dtype, add_pooling_layer=False)
|
| 1060 |
+
self.qa_outputs = nn.Dense(self.config.num_labels, dtype=self.dtype)
|
| 1061 |
+
|
| 1062 |
+
def __call__(
|
| 1063 |
+
self,
|
| 1064 |
+
input_ids,
|
| 1065 |
+
attention_mask,
|
| 1066 |
+
token_type_ids,
|
| 1067 |
+
position_ids,
|
| 1068 |
+
deterministic: bool = True,
|
| 1069 |
+
output_attentions: bool = False,
|
| 1070 |
+
output_hidden_states: bool = False,
|
| 1071 |
+
return_dict: bool = True,
|
| 1072 |
+
):
|
| 1073 |
+
# Model
|
| 1074 |
+
outputs = self.albert(
|
| 1075 |
+
input_ids,
|
| 1076 |
+
attention_mask,
|
| 1077 |
+
token_type_ids,
|
| 1078 |
+
position_ids,
|
| 1079 |
+
deterministic=deterministic,
|
| 1080 |
+
output_attentions=output_attentions,
|
| 1081 |
+
output_hidden_states=output_hidden_states,
|
| 1082 |
+
return_dict=return_dict,
|
| 1083 |
+
)
|
| 1084 |
+
|
| 1085 |
+
hidden_states = outputs[0]
|
| 1086 |
+
|
| 1087 |
+
logits = self.qa_outputs(hidden_states)
|
| 1088 |
+
start_logits, end_logits = logits.split(self.config.num_labels, axis=-1)
|
| 1089 |
+
start_logits = start_logits.squeeze(-1)
|
| 1090 |
+
end_logits = end_logits.squeeze(-1)
|
| 1091 |
+
|
| 1092 |
+
if not return_dict:
|
| 1093 |
+
return (start_logits, end_logits) + outputs[1:]
|
| 1094 |
+
|
| 1095 |
+
return FlaxQuestionAnsweringModelOutput(
|
| 1096 |
+
start_logits=start_logits,
|
| 1097 |
+
end_logits=end_logits,
|
| 1098 |
+
hidden_states=outputs.hidden_states,
|
| 1099 |
+
attentions=outputs.attentions,
|
| 1100 |
+
)
|
| 1101 |
+
|
| 1102 |
+
|
| 1103 |
+
@add_start_docstrings(
|
| 1104 |
+
"""
|
| 1105 |
+
Albert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1106 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1107 |
+
""",
|
| 1108 |
+
ALBERT_START_DOCSTRING,
|
| 1109 |
+
)
|
| 1110 |
+
class FlaxAlbertForQuestionAnswering(FlaxAlbertPreTrainedModel):
|
| 1111 |
+
module_class = FlaxAlbertForQuestionAnsweringModule
|
| 1112 |
+
|
| 1113 |
+
|
| 1114 |
+
append_call_sample_docstring(
|
| 1115 |
+
FlaxAlbertForQuestionAnswering,
|
| 1116 |
+
_CHECKPOINT_FOR_DOC,
|
| 1117 |
+
FlaxQuestionAnsweringModelOutput,
|
| 1118 |
+
_CONFIG_FOR_DOC,
|
| 1119 |
+
)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/modeling_tf_albert.py
ADDED
|
@@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
""" TF 2.0 ALBERT model."""
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import Dict, Optional, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import tensorflow as tf
|
| 24 |
+
|
| 25 |
+
from ...activations_tf import get_tf_activation
|
| 26 |
+
from ...modeling_tf_outputs import (
|
| 27 |
+
TFBaseModelOutput,
|
| 28 |
+
TFBaseModelOutputWithPooling,
|
| 29 |
+
TFMaskedLMOutput,
|
| 30 |
+
TFMultipleChoiceModelOutput,
|
| 31 |
+
TFQuestionAnsweringModelOutput,
|
| 32 |
+
TFSequenceClassifierOutput,
|
| 33 |
+
TFTokenClassifierOutput,
|
| 34 |
+
)
|
| 35 |
+
from ...modeling_tf_utils import (
|
| 36 |
+
TFMaskedLanguageModelingLoss,
|
| 37 |
+
TFModelInputType,
|
| 38 |
+
TFMultipleChoiceLoss,
|
| 39 |
+
TFPreTrainedModel,
|
| 40 |
+
TFQuestionAnsweringLoss,
|
| 41 |
+
TFSequenceClassificationLoss,
|
| 42 |
+
TFTokenClassificationLoss,
|
| 43 |
+
get_initializer,
|
| 44 |
+
keras_serializable,
|
| 45 |
+
unpack_inputs,
|
| 46 |
+
)
|
| 47 |
+
from ...tf_utils import shape_list, stable_softmax
|
| 48 |
+
from ...utils import (
|
| 49 |
+
MULTIPLE_CHOICE_DUMMY_INPUTS,
|
| 50 |
+
ModelOutput,
|
| 51 |
+
add_code_sample_docstrings,
|
| 52 |
+
add_start_docstrings,
|
| 53 |
+
add_start_docstrings_to_model_forward,
|
| 54 |
+
logging,
|
| 55 |
+
replace_return_docstrings,
|
| 56 |
+
)
|
| 57 |
+
from .configuration_albert import AlbertConfig
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
logger = logging.get_logger(__name__)
|
| 61 |
+
|
| 62 |
+
_CHECKPOINT_FOR_DOC = "albert-base-v2"
|
| 63 |
+
_CONFIG_FOR_DOC = "AlbertConfig"
|
| 64 |
+
|
| 65 |
+
TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 66 |
+
"albert-base-v1",
|
| 67 |
+
"albert-large-v1",
|
| 68 |
+
"albert-xlarge-v1",
|
| 69 |
+
"albert-xxlarge-v1",
|
| 70 |
+
"albert-base-v2",
|
| 71 |
+
"albert-large-v2",
|
| 72 |
+
"albert-xlarge-v2",
|
| 73 |
+
"albert-xxlarge-v2",
|
| 74 |
+
# See all ALBERT models at https://huggingface.co/models?filter=albert
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class TFAlbertPreTrainingLoss:
|
| 79 |
+
"""
|
| 80 |
+
Loss function suitable for ALBERT pretraining, that is, the task of pretraining a language model by combining SOP +
|
| 81 |
+
MLM. .. note:: Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
def hf_compute_loss(self, labels: tf.Tensor, logits: tf.Tensor) -> tf.Tensor:
|
| 85 |
+
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(
|
| 86 |
+
from_logits=True, reduction=tf.keras.losses.Reduction.NONE
|
| 87 |
+
)
|
| 88 |
+
if self.config.tf_legacy_loss:
|
| 89 |
+
# make sure only labels that are not equal to -100
|
| 90 |
+
# are taken into account as loss
|
| 91 |
+
masked_lm_active_loss = tf.not_equal(tf.reshape(tensor=labels["labels"], shape=(-1,)), -100)
|
| 92 |
+
masked_lm_reduced_logits = tf.boolean_mask(
|
| 93 |
+
tensor=tf.reshape(tensor=logits[0], shape=(-1, shape_list(logits[0])[2])),
|
| 94 |
+
mask=masked_lm_active_loss,
|
| 95 |
+
)
|
| 96 |
+
masked_lm_labels = tf.boolean_mask(
|
| 97 |
+
tensor=tf.reshape(tensor=labels["labels"], shape=(-1,)), mask=masked_lm_active_loss
|
| 98 |
+
)
|
| 99 |
+
sentence_order_active_loss = tf.not_equal(
|
| 100 |
+
tf.reshape(tensor=labels["sentence_order_label"], shape=(-1,)), -100
|
| 101 |
+
)
|
| 102 |
+
sentence_order_reduced_logits = tf.boolean_mask(
|
| 103 |
+
tensor=tf.reshape(tensor=logits[1], shape=(-1, 2)), mask=sentence_order_active_loss
|
| 104 |
+
)
|
| 105 |
+
sentence_order_label = tf.boolean_mask(
|
| 106 |
+
tensor=tf.reshape(tensor=labels["sentence_order_label"], shape=(-1,)), mask=sentence_order_active_loss
|
| 107 |
+
)
|
| 108 |
+
masked_lm_loss = loss_fn(y_true=masked_lm_labels, y_pred=masked_lm_reduced_logits)
|
| 109 |
+
sentence_order_loss = loss_fn(y_true=sentence_order_label, y_pred=sentence_order_reduced_logits)
|
| 110 |
+
masked_lm_loss = tf.reshape(tensor=masked_lm_loss, shape=(-1, shape_list(sentence_order_loss)[0]))
|
| 111 |
+
masked_lm_loss = tf.reduce_mean(input_tensor=masked_lm_loss, axis=0)
|
| 112 |
+
|
| 113 |
+
return masked_lm_loss + sentence_order_loss
|
| 114 |
+
|
| 115 |
+
# Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
|
| 116 |
+
unmasked_lm_losses = loss_fn(y_true=tf.nn.relu(labels["labels"]), y_pred=logits[0])
|
| 117 |
+
# make sure only labels that are not equal to -100
|
| 118 |
+
# are taken into account for the loss computation
|
| 119 |
+
lm_loss_mask = tf.cast(labels["labels"] != -100, dtype=unmasked_lm_losses.dtype)
|
| 120 |
+
masked_lm_losses = unmasked_lm_losses * lm_loss_mask
|
| 121 |
+
reduced_masked_lm_loss = tf.reduce_sum(masked_lm_losses) / tf.reduce_sum(lm_loss_mask)
|
| 122 |
+
|
| 123 |
+
sop_logits = tf.reshape(logits[1], (-1, 2))
|
| 124 |
+
# Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
|
| 125 |
+
unmasked_sop_loss = loss_fn(y_true=tf.nn.relu(labels["sentence_order_label"]), y_pred=sop_logits)
|
| 126 |
+
sop_loss_mask = tf.cast(labels["sentence_order_label"] != -100, dtype=unmasked_sop_loss.dtype)
|
| 127 |
+
|
| 128 |
+
masked_sop_loss = unmasked_sop_loss * sop_loss_mask
|
| 129 |
+
reduced_masked_sop_loss = tf.reduce_sum(masked_sop_loss) / tf.reduce_sum(sop_loss_mask)
|
| 130 |
+
|
| 131 |
+
return tf.reshape(reduced_masked_lm_loss + reduced_masked_sop_loss, (1,))
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class TFAlbertEmbeddings(tf.keras.layers.Layer):
|
| 135 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 136 |
+
|
| 137 |
+
def __init__(self, config: AlbertConfig, **kwargs):
|
| 138 |
+
super().__init__(**kwargs)
|
| 139 |
+
|
| 140 |
+
self.config = config
|
| 141 |
+
self.embedding_size = config.embedding_size
|
| 142 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 143 |
+
self.initializer_range = config.initializer_range
|
| 144 |
+
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 145 |
+
self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 146 |
+
|
| 147 |
+
def build(self, input_shape: tf.TensorShape):
|
| 148 |
+
with tf.name_scope("word_embeddings"):
|
| 149 |
+
self.weight = self.add_weight(
|
| 150 |
+
name="weight",
|
| 151 |
+
shape=[self.config.vocab_size, self.embedding_size],
|
| 152 |
+
initializer=get_initializer(self.initializer_range),
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
with tf.name_scope("token_type_embeddings"):
|
| 156 |
+
self.token_type_embeddings = self.add_weight(
|
| 157 |
+
name="embeddings",
|
| 158 |
+
shape=[self.config.type_vocab_size, self.embedding_size],
|
| 159 |
+
initializer=get_initializer(self.initializer_range),
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
with tf.name_scope("position_embeddings"):
|
| 163 |
+
self.position_embeddings = self.add_weight(
|
| 164 |
+
name="embeddings",
|
| 165 |
+
shape=[self.max_position_embeddings, self.embedding_size],
|
| 166 |
+
initializer=get_initializer(self.initializer_range),
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
super().build(input_shape)
|
| 170 |
+
|
| 171 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertEmbeddings.call
|
| 172 |
+
def call(
|
| 173 |
+
self,
|
| 174 |
+
input_ids: tf.Tensor = None,
|
| 175 |
+
position_ids: tf.Tensor = None,
|
| 176 |
+
token_type_ids: tf.Tensor = None,
|
| 177 |
+
inputs_embeds: tf.Tensor = None,
|
| 178 |
+
past_key_values_length=0,
|
| 179 |
+
training: bool = False,
|
| 180 |
+
) -> tf.Tensor:
|
| 181 |
+
"""
|
| 182 |
+
Applies embedding based on inputs tensor.
|
| 183 |
+
|
| 184 |
+
Returns:
|
| 185 |
+
final_embeddings (`tf.Tensor`): output embedding tensor.
|
| 186 |
+
"""
|
| 187 |
+
if input_ids is None and inputs_embeds is None:
|
| 188 |
+
raise ValueError("Need to provide either `input_ids` or `input_embeds`.")
|
| 189 |
+
|
| 190 |
+
if input_ids is not None:
|
| 191 |
+
# Note: tf.gather, on which the embedding layer is based, won't check positive out of bound
|
| 192 |
+
# indices on GPU, returning zeros instead. This is a dangerous silent behavior.
|
| 193 |
+
tf.debugging.assert_less(
|
| 194 |
+
input_ids,
|
| 195 |
+
tf.cast(self.config.vocab_size, dtype=input_ids.dtype),
|
| 196 |
+
message=(
|
| 197 |
+
"input_ids must be smaller than the embedding layer's input dimension (got"
|
| 198 |
+
f" {tf.math.reduce_max(input_ids)} >= {self.config.vocab_size})"
|
| 199 |
+
),
|
| 200 |
+
)
|
| 201 |
+
inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
|
| 202 |
+
|
| 203 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 204 |
+
|
| 205 |
+
if token_type_ids is None:
|
| 206 |
+
token_type_ids = tf.fill(dims=input_shape, value=0)
|
| 207 |
+
|
| 208 |
+
if position_ids is None:
|
| 209 |
+
position_ids = tf.expand_dims(
|
| 210 |
+
tf.range(start=past_key_values_length, limit=input_shape[1] + past_key_values_length), axis=0
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
|
| 214 |
+
token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
|
| 215 |
+
final_embeddings = inputs_embeds + position_embeds + token_type_embeds
|
| 216 |
+
final_embeddings = self.LayerNorm(inputs=final_embeddings)
|
| 217 |
+
final_embeddings = self.dropout(inputs=final_embeddings, training=training)
|
| 218 |
+
|
| 219 |
+
return final_embeddings
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class TFAlbertAttention(tf.keras.layers.Layer):
|
| 223 |
+
"""Contains the complete attention sublayer, including both dropouts and layer norm."""
|
| 224 |
+
|
| 225 |
+
def __init__(self, config: AlbertConfig, **kwargs):
|
| 226 |
+
super().__init__(**kwargs)
|
| 227 |
+
|
| 228 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
| 229 |
+
raise ValueError(
|
| 230 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number "
|
| 231 |
+
f"of attention heads ({config.num_attention_heads})"
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
self.num_attention_heads = config.num_attention_heads
|
| 235 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 236 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 237 |
+
self.sqrt_att_head_size = math.sqrt(self.attention_head_size)
|
| 238 |
+
self.output_attentions = config.output_attentions
|
| 239 |
+
|
| 240 |
+
self.query = tf.keras.layers.Dense(
|
| 241 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
|
| 242 |
+
)
|
| 243 |
+
self.key = tf.keras.layers.Dense(
|
| 244 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
|
| 245 |
+
)
|
| 246 |
+
self.value = tf.keras.layers.Dense(
|
| 247 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
|
| 248 |
+
)
|
| 249 |
+
self.dense = tf.keras.layers.Dense(
|
| 250 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 251 |
+
)
|
| 252 |
+
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 253 |
+
# Two different dropout probabilities; see https://github.com/google-research/albert/blob/master/modeling.py#L971-L993
|
| 254 |
+
self.attention_dropout = tf.keras.layers.Dropout(rate=config.attention_probs_dropout_prob)
|
| 255 |
+
self.output_dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 256 |
+
|
| 257 |
+
def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
|
| 258 |
+
# Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
|
| 259 |
+
tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))
|
| 260 |
+
|
| 261 |
+
# Transpose the tensor from [batch_size, seq_length, num_attention_heads, attention_head_size] to [batch_size, num_attention_heads, seq_length, attention_head_size]
|
| 262 |
+
return tf.transpose(tensor, perm=[0, 2, 1, 3])
|
| 263 |
+
|
| 264 |
+
def call(
|
| 265 |
+
self,
|
| 266 |
+
input_tensor: tf.Tensor,
|
| 267 |
+
attention_mask: tf.Tensor,
|
| 268 |
+
head_mask: tf.Tensor,
|
| 269 |
+
output_attentions: bool,
|
| 270 |
+
training: bool = False,
|
| 271 |
+
) -> Tuple[tf.Tensor]:
|
| 272 |
+
batch_size = shape_list(input_tensor)[0]
|
| 273 |
+
mixed_query_layer = self.query(inputs=input_tensor)
|
| 274 |
+
mixed_key_layer = self.key(inputs=input_tensor)
|
| 275 |
+
mixed_value_layer = self.value(inputs=input_tensor)
|
| 276 |
+
query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
|
| 277 |
+
key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)
|
| 278 |
+
value_layer = self.transpose_for_scores(mixed_value_layer, batch_size)
|
| 279 |
+
|
| 280 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 281 |
+
# (batch size, num_heads, seq_len_q, seq_len_k)
|
| 282 |
+
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
|
| 283 |
+
dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
|
| 284 |
+
attention_scores = tf.divide(attention_scores, dk)
|
| 285 |
+
|
| 286 |
+
if attention_mask is not None:
|
| 287 |
+
# Apply the attention mask is (precomputed for all layers in TFAlbertModel call() function)
|
| 288 |
+
attention_scores = tf.add(attention_scores, attention_mask)
|
| 289 |
+
|
| 290 |
+
# Normalize the attention scores to probabilities.
|
| 291 |
+
attention_probs = stable_softmax(logits=attention_scores, axis=-1)
|
| 292 |
+
|
| 293 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 294 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 295 |
+
attention_probs = self.attention_dropout(inputs=attention_probs, training=training)
|
| 296 |
+
|
| 297 |
+
# Mask heads if we want to
|
| 298 |
+
if head_mask is not None:
|
| 299 |
+
attention_probs = tf.multiply(attention_probs, head_mask)
|
| 300 |
+
|
| 301 |
+
context_layer = tf.matmul(attention_probs, value_layer)
|
| 302 |
+
context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])
|
| 303 |
+
|
| 304 |
+
# (batch_size, seq_len_q, all_head_size)
|
| 305 |
+
context_layer = tf.reshape(tensor=context_layer, shape=(batch_size, -1, self.all_head_size))
|
| 306 |
+
self_outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 307 |
+
hidden_states = self_outputs[0]
|
| 308 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 309 |
+
hidden_states = self.output_dropout(inputs=hidden_states, training=training)
|
| 310 |
+
attention_output = self.LayerNorm(inputs=hidden_states + input_tensor)
|
| 311 |
+
|
| 312 |
+
# add attentions if we output them
|
| 313 |
+
outputs = (attention_output,) + self_outputs[1:]
|
| 314 |
+
|
| 315 |
+
return outputs
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class TFAlbertLayer(tf.keras.layers.Layer):
|
| 319 |
+
def __init__(self, config: AlbertConfig, **kwargs):
|
| 320 |
+
super().__init__(**kwargs)
|
| 321 |
+
|
| 322 |
+
self.attention = TFAlbertAttention(config, name="attention")
|
| 323 |
+
self.ffn = tf.keras.layers.Dense(
|
| 324 |
+
units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="ffn"
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
if isinstance(config.hidden_act, str):
|
| 328 |
+
self.activation = get_tf_activation(config.hidden_act)
|
| 329 |
+
else:
|
| 330 |
+
self.activation = config.hidden_act
|
| 331 |
+
|
| 332 |
+
self.ffn_output = tf.keras.layers.Dense(
|
| 333 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="ffn_output"
|
| 334 |
+
)
|
| 335 |
+
self.full_layer_layer_norm = tf.keras.layers.LayerNormalization(
|
| 336 |
+
epsilon=config.layer_norm_eps, name="full_layer_layer_norm"
|
| 337 |
+
)
|
| 338 |
+
self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 339 |
+
|
| 340 |
+
def call(
|
| 341 |
+
self,
|
| 342 |
+
hidden_states: tf.Tensor,
|
| 343 |
+
attention_mask: tf.Tensor,
|
| 344 |
+
head_mask: tf.Tensor,
|
| 345 |
+
output_attentions: bool,
|
| 346 |
+
training: bool = False,
|
| 347 |
+
) -> Tuple[tf.Tensor]:
|
| 348 |
+
attention_outputs = self.attention(
|
| 349 |
+
input_tensor=hidden_states,
|
| 350 |
+
attention_mask=attention_mask,
|
| 351 |
+
head_mask=head_mask,
|
| 352 |
+
output_attentions=output_attentions,
|
| 353 |
+
training=training,
|
| 354 |
+
)
|
| 355 |
+
ffn_output = self.ffn(inputs=attention_outputs[0])
|
| 356 |
+
ffn_output = self.activation(ffn_output)
|
| 357 |
+
ffn_output = self.ffn_output(inputs=ffn_output)
|
| 358 |
+
ffn_output = self.dropout(inputs=ffn_output, training=training)
|
| 359 |
+
hidden_states = self.full_layer_layer_norm(inputs=ffn_output + attention_outputs[0])
|
| 360 |
+
|
| 361 |
+
# add attentions if we output them
|
| 362 |
+
outputs = (hidden_states,) + attention_outputs[1:]
|
| 363 |
+
|
| 364 |
+
return outputs
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
class TFAlbertLayerGroup(tf.keras.layers.Layer):
|
| 368 |
+
def __init__(self, config: AlbertConfig, **kwargs):
|
| 369 |
+
super().__init__(**kwargs)
|
| 370 |
+
|
| 371 |
+
self.albert_layers = [
|
| 372 |
+
TFAlbertLayer(config, name=f"albert_layers_._{i}") for i in range(config.inner_group_num)
|
| 373 |
+
]
|
| 374 |
+
|
| 375 |
+
def call(
|
| 376 |
+
self,
|
| 377 |
+
hidden_states: tf.Tensor,
|
| 378 |
+
attention_mask: tf.Tensor,
|
| 379 |
+
head_mask: tf.Tensor,
|
| 380 |
+
output_attentions: bool,
|
| 381 |
+
output_hidden_states: bool,
|
| 382 |
+
training: bool = False,
|
| 383 |
+
) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
|
| 384 |
+
layer_hidden_states = () if output_hidden_states else None
|
| 385 |
+
layer_attentions = () if output_attentions else None
|
| 386 |
+
|
| 387 |
+
for layer_index, albert_layer in enumerate(self.albert_layers):
|
| 388 |
+
if output_hidden_states:
|
| 389 |
+
layer_hidden_states = layer_hidden_states + (hidden_states,)
|
| 390 |
+
|
| 391 |
+
layer_output = albert_layer(
|
| 392 |
+
hidden_states=hidden_states,
|
| 393 |
+
attention_mask=attention_mask,
|
| 394 |
+
head_mask=head_mask[layer_index],
|
| 395 |
+
output_attentions=output_attentions,
|
| 396 |
+
training=training,
|
| 397 |
+
)
|
| 398 |
+
hidden_states = layer_output[0]
|
| 399 |
+
|
| 400 |
+
if output_attentions:
|
| 401 |
+
layer_attentions = layer_attentions + (layer_output[1],)
|
| 402 |
+
|
| 403 |
+
# Add last layer
|
| 404 |
+
if output_hidden_states:
|
| 405 |
+
layer_hidden_states = layer_hidden_states + (hidden_states,)
|
| 406 |
+
|
| 407 |
+
return tuple(v for v in [hidden_states, layer_hidden_states, layer_attentions] if v is not None)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
class TFAlbertTransformer(tf.keras.layers.Layer):
|
| 411 |
+
def __init__(self, config: AlbertConfig, **kwargs):
|
| 412 |
+
super().__init__(**kwargs)
|
| 413 |
+
|
| 414 |
+
self.num_hidden_layers = config.num_hidden_layers
|
| 415 |
+
self.num_hidden_groups = config.num_hidden_groups
|
| 416 |
+
# Number of layers in a hidden group
|
| 417 |
+
self.layers_per_group = int(config.num_hidden_layers / config.num_hidden_groups)
|
| 418 |
+
self.embedding_hidden_mapping_in = tf.keras.layers.Dense(
|
| 419 |
+
units=config.hidden_size,
|
| 420 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 421 |
+
name="embedding_hidden_mapping_in",
|
| 422 |
+
)
|
| 423 |
+
self.albert_layer_groups = [
|
| 424 |
+
TFAlbertLayerGroup(config, name=f"albert_layer_groups_._{i}") for i in range(config.num_hidden_groups)
|
| 425 |
+
]
|
| 426 |
+
|
| 427 |
+
def call(
|
| 428 |
+
self,
|
| 429 |
+
hidden_states: tf.Tensor,
|
| 430 |
+
attention_mask: tf.Tensor,
|
| 431 |
+
head_mask: tf.Tensor,
|
| 432 |
+
output_attentions: bool,
|
| 433 |
+
output_hidden_states: bool,
|
| 434 |
+
return_dict: bool,
|
| 435 |
+
training: bool = False,
|
| 436 |
+
) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
|
| 437 |
+
hidden_states = self.embedding_hidden_mapping_in(inputs=hidden_states)
|
| 438 |
+
all_attentions = () if output_attentions else None
|
| 439 |
+
all_hidden_states = (hidden_states,) if output_hidden_states else None
|
| 440 |
+
|
| 441 |
+
for i in range(self.num_hidden_layers):
|
| 442 |
+
# Index of the hidden group
|
| 443 |
+
group_idx = int(i / (self.num_hidden_layers / self.num_hidden_groups))
|
| 444 |
+
layer_group_output = self.albert_layer_groups[group_idx](
|
| 445 |
+
hidden_states=hidden_states,
|
| 446 |
+
attention_mask=attention_mask,
|
| 447 |
+
head_mask=head_mask[group_idx * self.layers_per_group : (group_idx + 1) * self.layers_per_group],
|
| 448 |
+
output_attentions=output_attentions,
|
| 449 |
+
output_hidden_states=output_hidden_states,
|
| 450 |
+
training=training,
|
| 451 |
+
)
|
| 452 |
+
hidden_states = layer_group_output[0]
|
| 453 |
+
|
| 454 |
+
if output_attentions:
|
| 455 |
+
all_attentions = all_attentions + layer_group_output[-1]
|
| 456 |
+
|
| 457 |
+
if output_hidden_states:
|
| 458 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 459 |
+
|
| 460 |
+
if not return_dict:
|
| 461 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
|
| 462 |
+
|
| 463 |
+
return TFBaseModelOutput(
|
| 464 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
class TFAlbertPreTrainedModel(TFPreTrainedModel):
|
| 469 |
+
"""
|
| 470 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 471 |
+
models.
|
| 472 |
+
"""
|
| 473 |
+
|
| 474 |
+
config_class = AlbertConfig
|
| 475 |
+
base_model_prefix = "albert"
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class TFAlbertMLMHead(tf.keras.layers.Layer):
|
| 479 |
+
def __init__(self, config: AlbertConfig, input_embeddings: tf.keras.layers.Layer, **kwargs):
|
| 480 |
+
super().__init__(**kwargs)
|
| 481 |
+
|
| 482 |
+
self.config = config
|
| 483 |
+
self.embedding_size = config.embedding_size
|
| 484 |
+
self.dense = tf.keras.layers.Dense(
|
| 485 |
+
config.embedding_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 486 |
+
)
|
| 487 |
+
if isinstance(config.hidden_act, str):
|
| 488 |
+
self.activation = get_tf_activation(config.hidden_act)
|
| 489 |
+
else:
|
| 490 |
+
self.activation = config.hidden_act
|
| 491 |
+
|
| 492 |
+
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 493 |
+
|
| 494 |
+
# The output weights are the same as the input embeddings, but there is
|
| 495 |
+
# an output-only bias for each token.
|
| 496 |
+
self.decoder = input_embeddings
|
| 497 |
+
|
| 498 |
+
def build(self, input_shape: tf.TensorShape):
|
| 499 |
+
self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
|
| 500 |
+
self.decoder_bias = self.add_weight(
|
| 501 |
+
shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="decoder/bias"
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
super().build(input_shape)
|
| 505 |
+
|
| 506 |
+
def get_output_embeddings(self) -> tf.keras.layers.Layer:
|
| 507 |
+
return self.decoder
|
| 508 |
+
|
| 509 |
+
def set_output_embeddings(self, value: tf.Variable):
|
| 510 |
+
self.decoder.weight = value
|
| 511 |
+
self.decoder.vocab_size = shape_list(value)[0]
|
| 512 |
+
|
| 513 |
+
def get_bias(self) -> Dict[str, tf.Variable]:
|
| 514 |
+
return {"bias": self.bias, "decoder_bias": self.decoder_bias}
|
| 515 |
+
|
| 516 |
+
def set_bias(self, value: tf.Variable):
|
| 517 |
+
self.bias = value["bias"]
|
| 518 |
+
self.decoder_bias = value["decoder_bias"]
|
| 519 |
+
self.config.vocab_size = shape_list(value["bias"])[0]
|
| 520 |
+
|
| 521 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 522 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 523 |
+
hidden_states = self.activation(hidden_states)
|
| 524 |
+
hidden_states = self.LayerNorm(inputs=hidden_states)
|
| 525 |
+
seq_length = shape_list(tensor=hidden_states)[1]
|
| 526 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.embedding_size])
|
| 527 |
+
hidden_states = tf.matmul(a=hidden_states, b=self.decoder.weight, transpose_b=True)
|
| 528 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
|
| 529 |
+
hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.decoder_bias)
|
| 530 |
+
|
| 531 |
+
return hidden_states
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
@keras_serializable
|
| 535 |
+
class TFAlbertMainLayer(tf.keras.layers.Layer):
|
| 536 |
+
config_class = AlbertConfig
|
| 537 |
+
|
| 538 |
+
def __init__(self, config: AlbertConfig, add_pooling_layer: bool = True, **kwargs):
|
| 539 |
+
super().__init__(**kwargs)
|
| 540 |
+
|
| 541 |
+
self.config = config
|
| 542 |
+
|
| 543 |
+
self.embeddings = TFAlbertEmbeddings(config, name="embeddings")
|
| 544 |
+
self.encoder = TFAlbertTransformer(config, name="encoder")
|
| 545 |
+
self.pooler = (
|
| 546 |
+
tf.keras.layers.Dense(
|
| 547 |
+
units=config.hidden_size,
|
| 548 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 549 |
+
activation="tanh",
|
| 550 |
+
name="pooler",
|
| 551 |
+
)
|
| 552 |
+
if add_pooling_layer
|
| 553 |
+
else None
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
def get_input_embeddings(self) -> tf.keras.layers.Layer:
|
| 557 |
+
return self.embeddings
|
| 558 |
+
|
| 559 |
+
def set_input_embeddings(self, value: tf.Variable):
|
| 560 |
+
self.embeddings.weight = value
|
| 561 |
+
self.embeddings.vocab_size = shape_list(value)[0]
|
| 562 |
+
|
| 563 |
+
def _prune_heads(self, heads_to_prune):
|
| 564 |
+
"""
|
| 565 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 566 |
+
class PreTrainedModel
|
| 567 |
+
"""
|
| 568 |
+
raise NotImplementedError
|
| 569 |
+
|
| 570 |
+
@unpack_inputs
|
| 571 |
+
def call(
|
| 572 |
+
self,
|
| 573 |
+
input_ids: Optional[TFModelInputType] = None,
|
| 574 |
+
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 575 |
+
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 576 |
+
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 577 |
+
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 578 |
+
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 579 |
+
output_attentions: Optional[bool] = None,
|
| 580 |
+
output_hidden_states: Optional[bool] = None,
|
| 581 |
+
return_dict: Optional[bool] = None,
|
| 582 |
+
training: bool = False,
|
| 583 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
| 584 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 585 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 586 |
+
elif input_ids is not None:
|
| 587 |
+
input_shape = shape_list(input_ids)
|
| 588 |
+
elif inputs_embeds is not None:
|
| 589 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 590 |
+
else:
|
| 591 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 592 |
+
|
| 593 |
+
if attention_mask is None:
|
| 594 |
+
attention_mask = tf.fill(dims=input_shape, value=1)
|
| 595 |
+
|
| 596 |
+
if token_type_ids is None:
|
| 597 |
+
token_type_ids = tf.fill(dims=input_shape, value=0)
|
| 598 |
+
|
| 599 |
+
embedding_output = self.embeddings(
|
| 600 |
+
input_ids=input_ids,
|
| 601 |
+
position_ids=position_ids,
|
| 602 |
+
token_type_ids=token_type_ids,
|
| 603 |
+
inputs_embeds=inputs_embeds,
|
| 604 |
+
training=training,
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
| 608 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
| 609 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
| 610 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
| 611 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
| 612 |
+
extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))
|
| 613 |
+
|
| 614 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 615 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 616 |
+
# positions we want to attend and -10000.0 for masked positions.
|
| 617 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 618 |
+
# effectively the same as removing these entirely.
|
| 619 |
+
extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)
|
| 620 |
+
one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
|
| 621 |
+
ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
|
| 622 |
+
extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
|
| 623 |
+
|
| 624 |
+
# Prepare head mask if needed
|
| 625 |
+
# 1.0 in head_mask indicate we keep the head
|
| 626 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 627 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 628 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 629 |
+
if head_mask is not None:
|
| 630 |
+
raise NotImplementedError
|
| 631 |
+
else:
|
| 632 |
+
head_mask = [None] * self.config.num_hidden_layers
|
| 633 |
+
|
| 634 |
+
encoder_outputs = self.encoder(
|
| 635 |
+
hidden_states=embedding_output,
|
| 636 |
+
attention_mask=extended_attention_mask,
|
| 637 |
+
head_mask=head_mask,
|
| 638 |
+
output_attentions=output_attentions,
|
| 639 |
+
output_hidden_states=output_hidden_states,
|
| 640 |
+
return_dict=return_dict,
|
| 641 |
+
training=training,
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
sequence_output = encoder_outputs[0]
|
| 645 |
+
pooled_output = self.pooler(inputs=sequence_output[:, 0]) if self.pooler is not None else None
|
| 646 |
+
|
| 647 |
+
if not return_dict:
|
| 648 |
+
return (
|
| 649 |
+
sequence_output,
|
| 650 |
+
pooled_output,
|
| 651 |
+
) + encoder_outputs[1:]
|
| 652 |
+
|
| 653 |
+
return TFBaseModelOutputWithPooling(
|
| 654 |
+
last_hidden_state=sequence_output,
|
| 655 |
+
pooler_output=pooled_output,
|
| 656 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 657 |
+
attentions=encoder_outputs.attentions,
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
@dataclass
|
| 662 |
+
class TFAlbertForPreTrainingOutput(ModelOutput):
|
| 663 |
+
"""
|
| 664 |
+
Output type of [`TFAlbertForPreTraining`].
|
| 665 |
+
|
| 666 |
+
Args:
|
| 667 |
+
prediction_logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 668 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 669 |
+
sop_logits (`tf.Tensor` of shape `(batch_size, 2)`):
|
| 670 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
| 671 |
+
before SoftMax).
|
| 672 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 673 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 674 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 675 |
+
|
| 676 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 677 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 678 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 679 |
+
sequence_length)`.
|
| 680 |
+
|
| 681 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 682 |
+
heads.
|
| 683 |
+
"""
|
| 684 |
+
|
| 685 |
+
loss: tf.Tensor = None
|
| 686 |
+
prediction_logits: tf.Tensor = None
|
| 687 |
+
sop_logits: tf.Tensor = None
|
| 688 |
+
hidden_states: Optional[Tuple[tf.Tensor]] = None
|
| 689 |
+
attentions: Optional[Tuple[tf.Tensor]] = None
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
ALBERT_START_DOCSTRING = r"""
|
| 693 |
+
|
| 694 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 695 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 696 |
+
etc.)
|
| 697 |
+
|
| 698 |
+
This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 699 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 700 |
+
behavior.
|
| 701 |
+
|
| 702 |
+
<Tip>
|
| 703 |
+
|
| 704 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 705 |
+
|
| 706 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 707 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 708 |
+
|
| 709 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 710 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 711 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 712 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 713 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 714 |
+
positional argument:
|
| 715 |
+
|
| 716 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 717 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 718 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 719 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 720 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 721 |
+
|
| 722 |
+
Note that when creating models and layers with
|
| 723 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 724 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 725 |
+
|
| 726 |
+
</Tip>
|
| 727 |
+
|
| 728 |
+
Args:
|
| 729 |
+
config ([`AlbertConfig`]): Model configuration class with all the parameters of the model.
|
| 730 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 731 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 732 |
+
"""
|
| 733 |
+
|
| 734 |
+
ALBERT_INPUTS_DOCSTRING = r"""
|
| 735 |
+
Args:
|
| 736 |
+
input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
|
| 737 |
+
Indices of input sequence tokens in the vocabulary.
|
| 738 |
+
|
| 739 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 740 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 741 |
+
|
| 742 |
+
[What are input IDs?](../glossary#input-ids)
|
| 743 |
+
attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 744 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 745 |
+
|
| 746 |
+
- 1 for tokens that are **not masked**,
|
| 747 |
+
- 0 for tokens that are **masked**.
|
| 748 |
+
|
| 749 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 750 |
+
token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 751 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 752 |
+
1]`:
|
| 753 |
+
|
| 754 |
+
- 0 corresponds to a *sentence A* token,
|
| 755 |
+
- 1 corresponds to a *sentence B* token.
|
| 756 |
+
|
| 757 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 758 |
+
position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 759 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 760 |
+
config.max_position_embeddings - 1]`.
|
| 761 |
+
|
| 762 |
+
[What are position IDs?](../glossary#position-ids)
|
| 763 |
+
head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 764 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 765 |
+
|
| 766 |
+
- 1 indicates the head is **not masked**,
|
| 767 |
+
- 0 indicates the head is **masked**.
|
| 768 |
+
|
| 769 |
+
inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
|
| 770 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 771 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 772 |
+
model's internal embedding lookup matrix.
|
| 773 |
+
output_attentions (`bool`, *optional*):
|
| 774 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 775 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 776 |
+
config will be used instead.
|
| 777 |
+
output_hidden_states (`bool`, *optional*):
|
| 778 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 779 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 780 |
+
used instead.
|
| 781 |
+
return_dict (`bool`, *optional*):
|
| 782 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 783 |
+
eager mode, in graph mode the value will always be set to True.
|
| 784 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 785 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 786 |
+
behaviors between training and evaluation).
|
| 787 |
+
"""
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
@add_start_docstrings(
|
| 791 |
+
"The bare Albert Model transformer outputting raw hidden-states without any specific head on top.",
|
| 792 |
+
ALBERT_START_DOCSTRING,
|
| 793 |
+
)
|
| 794 |
+
class TFAlbertModel(TFAlbertPreTrainedModel):
|
| 795 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 796 |
+
super().__init__(config, *inputs, **kwargs)
|
| 797 |
+
|
| 798 |
+
self.albert = TFAlbertMainLayer(config, name="albert")
|
| 799 |
+
|
| 800 |
+
@unpack_inputs
|
| 801 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 802 |
+
@add_code_sample_docstrings(
|
| 803 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 804 |
+
output_type=TFBaseModelOutputWithPooling,
|
| 805 |
+
config_class=_CONFIG_FOR_DOC,
|
| 806 |
+
)
|
| 807 |
+
def call(
|
| 808 |
+
self,
|
| 809 |
+
input_ids: Optional[TFModelInputType] = None,
|
| 810 |
+
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 811 |
+
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 812 |
+
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 813 |
+
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 814 |
+
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 815 |
+
output_attentions: Optional[bool] = None,
|
| 816 |
+
output_hidden_states: Optional[bool] = None,
|
| 817 |
+
return_dict: Optional[bool] = None,
|
| 818 |
+
training: Optional[bool] = False,
|
| 819 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
| 820 |
+
outputs = self.albert(
|
| 821 |
+
input_ids=input_ids,
|
| 822 |
+
attention_mask=attention_mask,
|
| 823 |
+
token_type_ids=token_type_ids,
|
| 824 |
+
position_ids=position_ids,
|
| 825 |
+
head_mask=head_mask,
|
| 826 |
+
inputs_embeds=inputs_embeds,
|
| 827 |
+
output_attentions=output_attentions,
|
| 828 |
+
output_hidden_states=output_hidden_states,
|
| 829 |
+
return_dict=return_dict,
|
| 830 |
+
training=training,
|
| 831 |
+
)
|
| 832 |
+
|
| 833 |
+
return outputs
|
| 834 |
+
|
| 835 |
+
def serving_output(self, output: TFBaseModelOutputWithPooling) -> TFBaseModelOutputWithPooling:
|
| 836 |
+
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
|
| 837 |
+
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
|
| 838 |
+
|
| 839 |
+
return TFBaseModelOutputWithPooling(
|
| 840 |
+
last_hidden_state=output.last_hidden_state,
|
| 841 |
+
pooler_output=output.pooler_output,
|
| 842 |
+
hidden_states=hs,
|
| 843 |
+
attentions=attns,
|
| 844 |
+
)
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
@add_start_docstrings(
|
| 848 |
+
"""
|
| 849 |
+
Albert Model with two heads on top for pretraining: a `masked language modeling` head and a `sentence order
|
| 850 |
+
prediction` (classification) head.
|
| 851 |
+
""",
|
| 852 |
+
ALBERT_START_DOCSTRING,
|
| 853 |
+
)
|
| 854 |
+
class TFAlbertForPreTraining(TFAlbertPreTrainedModel, TFAlbertPreTrainingLoss):
|
| 855 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 856 |
+
_keys_to_ignore_on_load_unexpected = [r"predictions.decoder.weight"]
|
| 857 |
+
|
| 858 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 859 |
+
super().__init__(config, *inputs, **kwargs)
|
| 860 |
+
|
| 861 |
+
self.num_labels = config.num_labels
|
| 862 |
+
|
| 863 |
+
self.albert = TFAlbertMainLayer(config, name="albert")
|
| 864 |
+
self.predictions = TFAlbertMLMHead(config, input_embeddings=self.albert.embeddings, name="predictions")
|
| 865 |
+
self.sop_classifier = TFAlbertSOPHead(config, name="sop_classifier")
|
| 866 |
+
|
| 867 |
+
def get_lm_head(self) -> tf.keras.layers.Layer:
|
| 868 |
+
return self.predictions
|
| 869 |
+
|
| 870 |
+
@unpack_inputs
|
| 871 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 872 |
+
@replace_return_docstrings(output_type=TFAlbertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
|
| 873 |
+
def call(
|
| 874 |
+
self,
|
| 875 |
+
input_ids: Optional[TFModelInputType] = None,
|
| 876 |
+
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 877 |
+
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 878 |
+
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 879 |
+
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 880 |
+
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 881 |
+
output_attentions: Optional[bool] = None,
|
| 882 |
+
output_hidden_states: Optional[bool] = None,
|
| 883 |
+
return_dict: Optional[bool] = None,
|
| 884 |
+
labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 885 |
+
sentence_order_label: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 886 |
+
training: Optional[bool] = False,
|
| 887 |
+
) -> Union[TFAlbertForPreTrainingOutput, Tuple[tf.Tensor]]:
|
| 888 |
+
r"""
|
| 889 |
+
Return:
|
| 890 |
+
|
| 891 |
+
Example:
|
| 892 |
+
|
| 893 |
+
```python
|
| 894 |
+
>>> import tensorflow as tf
|
| 895 |
+
>>> from transformers import AutoTokenizer, TFAlbertForPreTraining
|
| 896 |
+
|
| 897 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("albert-base-v2")
|
| 898 |
+
>>> model = TFAlbertForPreTraining.from_pretrained("albert-base-v2")
|
| 899 |
+
|
| 900 |
+
>>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True))[None, :]
|
| 901 |
+
>>> # Batch size 1
|
| 902 |
+
>>> outputs = model(input_ids)
|
| 903 |
+
|
| 904 |
+
>>> prediction_logits = outputs.prediction_logits
|
| 905 |
+
>>> sop_logits = outputs.sop_logits
|
| 906 |
+
```"""
|
| 907 |
+
|
| 908 |
+
outputs = self.albert(
|
| 909 |
+
input_ids=input_ids,
|
| 910 |
+
attention_mask=attention_mask,
|
| 911 |
+
token_type_ids=token_type_ids,
|
| 912 |
+
position_ids=position_ids,
|
| 913 |
+
head_mask=head_mask,
|
| 914 |
+
inputs_embeds=inputs_embeds,
|
| 915 |
+
output_attentions=output_attentions,
|
| 916 |
+
output_hidden_states=output_hidden_states,
|
| 917 |
+
return_dict=return_dict,
|
| 918 |
+
training=training,
|
| 919 |
+
)
|
| 920 |
+
sequence_output, pooled_output = outputs[:2]
|
| 921 |
+
prediction_scores = self.predictions(hidden_states=sequence_output)
|
| 922 |
+
sop_scores = self.sop_classifier(pooled_output=pooled_output, training=training)
|
| 923 |
+
total_loss = None
|
| 924 |
+
|
| 925 |
+
if labels is not None and sentence_order_label is not None:
|
| 926 |
+
d_labels = {"labels": labels}
|
| 927 |
+
d_labels["sentence_order_label"] = sentence_order_label
|
| 928 |
+
total_loss = self.hf_compute_loss(labels=d_labels, logits=(prediction_scores, sop_scores))
|
| 929 |
+
|
| 930 |
+
if not return_dict:
|
| 931 |
+
output = (prediction_scores, sop_scores) + outputs[2:]
|
| 932 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 933 |
+
|
| 934 |
+
return TFAlbertForPreTrainingOutput(
|
| 935 |
+
loss=total_loss,
|
| 936 |
+
prediction_logits=prediction_scores,
|
| 937 |
+
sop_logits=sop_scores,
|
| 938 |
+
hidden_states=outputs.hidden_states,
|
| 939 |
+
attentions=outputs.attentions,
|
| 940 |
+
)
|
| 941 |
+
|
| 942 |
+
def serving_output(self, output: TFAlbertForPreTrainingOutput) -> TFAlbertForPreTrainingOutput:
|
| 943 |
+
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
|
| 944 |
+
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
|
| 945 |
+
|
| 946 |
+
return TFAlbertForPreTrainingOutput(
|
| 947 |
+
prediction_logits=output.prediction_logits,
|
| 948 |
+
sop_logits=output.sop_logits,
|
| 949 |
+
hidden_states=hs,
|
| 950 |
+
attentions=attns,
|
| 951 |
+
)
|
| 952 |
+
|
| 953 |
+
|
| 954 |
+
class TFAlbertSOPHead(tf.keras.layers.Layer):
|
| 955 |
+
def __init__(self, config: AlbertConfig, **kwargs):
|
| 956 |
+
super().__init__(**kwargs)
|
| 957 |
+
|
| 958 |
+
self.dropout = tf.keras.layers.Dropout(rate=config.classifier_dropout_prob)
|
| 959 |
+
self.classifier = tf.keras.layers.Dense(
|
| 960 |
+
units=config.num_labels,
|
| 961 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 962 |
+
name="classifier",
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
def call(self, pooled_output: tf.Tensor, training: bool) -> tf.Tensor:
|
| 966 |
+
dropout_pooled_output = self.dropout(inputs=pooled_output, training=training)
|
| 967 |
+
logits = self.classifier(inputs=dropout_pooled_output)
|
| 968 |
+
|
| 969 |
+
return logits
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
@add_start_docstrings("""Albert Model with a `language modeling` head on top.""", ALBERT_START_DOCSTRING)
|
| 973 |
+
class TFAlbertForMaskedLM(TFAlbertPreTrainedModel, TFMaskedLanguageModelingLoss):
|
| 974 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 975 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"predictions.decoder.weight"]
|
| 976 |
+
|
| 977 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 978 |
+
super().__init__(config, *inputs, **kwargs)
|
| 979 |
+
|
| 980 |
+
self.albert = TFAlbertMainLayer(config, add_pooling_layer=False, name="albert")
|
| 981 |
+
self.predictions = TFAlbertMLMHead(config, input_embeddings=self.albert.embeddings, name="predictions")
|
| 982 |
+
|
| 983 |
+
def get_lm_head(self) -> tf.keras.layers.Layer:
|
| 984 |
+
return self.predictions
|
| 985 |
+
|
| 986 |
+
@unpack_inputs
|
| 987 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 988 |
+
@replace_return_docstrings(output_type=TFMaskedLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 989 |
+
def call(
|
| 990 |
+
self,
|
| 991 |
+
input_ids: Optional[TFModelInputType] = None,
|
| 992 |
+
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 993 |
+
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 994 |
+
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 995 |
+
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 996 |
+
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 997 |
+
output_attentions: Optional[bool] = None,
|
| 998 |
+
output_hidden_states: Optional[bool] = None,
|
| 999 |
+
return_dict: Optional[bool] = None,
|
| 1000 |
+
labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1001 |
+
training: Optional[bool] = False,
|
| 1002 |
+
) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]:
|
| 1003 |
+
r"""
|
| 1004 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1005 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 1006 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 1007 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1008 |
+
|
| 1009 |
+
Returns:
|
| 1010 |
+
|
| 1011 |
+
Example:
|
| 1012 |
+
|
| 1013 |
+
```python
|
| 1014 |
+
>>> import tensorflow as tf
|
| 1015 |
+
>>> from transformers import AutoTokenizer, TFAlbertForMaskedLM
|
| 1016 |
+
|
| 1017 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("albert-base-v2")
|
| 1018 |
+
>>> model = TFAlbertForMaskedLM.from_pretrained("albert-base-v2")
|
| 1019 |
+
|
| 1020 |
+
>>> # add mask_token
|
| 1021 |
+
>>> inputs = tokenizer(f"The capital of [MASK] is Paris.", return_tensors="tf")
|
| 1022 |
+
>>> logits = model(**inputs).logits
|
| 1023 |
+
|
| 1024 |
+
>>> # retrieve index of [MASK]
|
| 1025 |
+
>>> mask_token_index = tf.where(inputs.input_ids == tokenizer.mask_token_id)[0][1]
|
| 1026 |
+
>>> predicted_token_id = tf.math.argmax(logits[0, mask_token_index], axis=-1)
|
| 1027 |
+
>>> tokenizer.decode(predicted_token_id)
|
| 1028 |
+
'france'
|
| 1029 |
+
```
|
| 1030 |
+
|
| 1031 |
+
```python
|
| 1032 |
+
>>> labels = tokenizer("The capital of France is Paris.", return_tensors="tf")["input_ids"]
|
| 1033 |
+
>>> labels = tf.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)
|
| 1034 |
+
>>> outputs = model(**inputs, labels=labels)
|
| 1035 |
+
>>> round(float(outputs.loss), 2)
|
| 1036 |
+
0.81
|
| 1037 |
+
```
|
| 1038 |
+
"""
|
| 1039 |
+
outputs = self.albert(
|
| 1040 |
+
input_ids=input_ids,
|
| 1041 |
+
attention_mask=attention_mask,
|
| 1042 |
+
token_type_ids=token_type_ids,
|
| 1043 |
+
position_ids=position_ids,
|
| 1044 |
+
head_mask=head_mask,
|
| 1045 |
+
inputs_embeds=inputs_embeds,
|
| 1046 |
+
output_attentions=output_attentions,
|
| 1047 |
+
output_hidden_states=output_hidden_states,
|
| 1048 |
+
return_dict=return_dict,
|
| 1049 |
+
training=training,
|
| 1050 |
+
)
|
| 1051 |
+
sequence_output = outputs[0]
|
| 1052 |
+
prediction_scores = self.predictions(hidden_states=sequence_output, training=training)
|
| 1053 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=prediction_scores)
|
| 1054 |
+
|
| 1055 |
+
if not return_dict:
|
| 1056 |
+
output = (prediction_scores,) + outputs[2:]
|
| 1057 |
+
|
| 1058 |
+
return ((loss,) + output) if loss is not None else output
|
| 1059 |
+
|
| 1060 |
+
return TFMaskedLMOutput(
|
| 1061 |
+
loss=loss,
|
| 1062 |
+
logits=prediction_scores,
|
| 1063 |
+
hidden_states=outputs.hidden_states,
|
| 1064 |
+
attentions=outputs.attentions,
|
| 1065 |
+
)
|
| 1066 |
+
|
| 1067 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertForMaskedLM.serving_output
|
| 1068 |
+
def serving_output(self, output: TFMaskedLMOutput) -> TFMaskedLMOutput:
|
| 1069 |
+
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
|
| 1070 |
+
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
|
| 1071 |
+
|
| 1072 |
+
return TFMaskedLMOutput(logits=output.logits, hidden_states=hs, attentions=attns)
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
@add_start_docstrings(
|
| 1076 |
+
"""
|
| 1077 |
+
Albert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
| 1078 |
+
output) e.g. for GLUE tasks.
|
| 1079 |
+
""",
|
| 1080 |
+
ALBERT_START_DOCSTRING,
|
| 1081 |
+
)
|
| 1082 |
+
class TFAlbertForSequenceClassification(TFAlbertPreTrainedModel, TFSequenceClassificationLoss):
|
| 1083 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1084 |
+
_keys_to_ignore_on_load_unexpected = [r"predictions"]
|
| 1085 |
+
_keys_to_ignore_on_load_missing = [r"dropout"]
|
| 1086 |
+
|
| 1087 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 1088 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1089 |
+
|
| 1090 |
+
self.num_labels = config.num_labels
|
| 1091 |
+
|
| 1092 |
+
self.albert = TFAlbertMainLayer(config, name="albert")
|
| 1093 |
+
self.dropout = tf.keras.layers.Dropout(rate=config.classifier_dropout_prob)
|
| 1094 |
+
self.classifier = tf.keras.layers.Dense(
|
| 1095 |
+
units=config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 1096 |
+
)
|
| 1097 |
+
|
| 1098 |
+
@unpack_inputs
|
| 1099 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1100 |
+
@add_code_sample_docstrings(
|
| 1101 |
+
checkpoint="vumichien/albert-base-v2-imdb",
|
| 1102 |
+
output_type=TFSequenceClassifierOutput,
|
| 1103 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1104 |
+
expected_output="'LABEL_1'",
|
| 1105 |
+
expected_loss=0.12,
|
| 1106 |
+
)
|
| 1107 |
+
def call(
|
| 1108 |
+
self,
|
| 1109 |
+
input_ids: Optional[TFModelInputType] = None,
|
| 1110 |
+
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1111 |
+
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1112 |
+
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1113 |
+
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1114 |
+
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1115 |
+
output_attentions: Optional[bool] = None,
|
| 1116 |
+
output_hidden_states: Optional[bool] = None,
|
| 1117 |
+
return_dict: Optional[bool] = None,
|
| 1118 |
+
labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1119 |
+
training: Optional[bool] = False,
|
| 1120 |
+
) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
|
| 1121 |
+
r"""
|
| 1122 |
+
labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1123 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1124 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1125 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1126 |
+
"""
|
| 1127 |
+
outputs = self.albert(
|
| 1128 |
+
input_ids=input_ids,
|
| 1129 |
+
attention_mask=attention_mask,
|
| 1130 |
+
token_type_ids=token_type_ids,
|
| 1131 |
+
position_ids=position_ids,
|
| 1132 |
+
head_mask=head_mask,
|
| 1133 |
+
inputs_embeds=inputs_embeds,
|
| 1134 |
+
output_attentions=output_attentions,
|
| 1135 |
+
output_hidden_states=output_hidden_states,
|
| 1136 |
+
return_dict=return_dict,
|
| 1137 |
+
training=training,
|
| 1138 |
+
)
|
| 1139 |
+
pooled_output = outputs[1]
|
| 1140 |
+
pooled_output = self.dropout(inputs=pooled_output, training=training)
|
| 1141 |
+
logits = self.classifier(inputs=pooled_output)
|
| 1142 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
|
| 1143 |
+
|
| 1144 |
+
if not return_dict:
|
| 1145 |
+
output = (logits,) + outputs[2:]
|
| 1146 |
+
|
| 1147 |
+
return ((loss,) + output) if loss is not None else output
|
| 1148 |
+
|
| 1149 |
+
return TFSequenceClassifierOutput(
|
| 1150 |
+
loss=loss,
|
| 1151 |
+
logits=logits,
|
| 1152 |
+
hidden_states=outputs.hidden_states,
|
| 1153 |
+
attentions=outputs.attentions,
|
| 1154 |
+
)
|
| 1155 |
+
|
| 1156 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertForSequenceClassification.serving_output
|
| 1157 |
+
def serving_output(self, output: TFSequenceClassifierOutput) -> TFSequenceClassifierOutput:
|
| 1158 |
+
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
|
| 1159 |
+
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
|
| 1160 |
+
|
| 1161 |
+
return TFSequenceClassifierOutput(logits=output.logits, hidden_states=hs, attentions=attns)
|
| 1162 |
+
|
| 1163 |
+
|
| 1164 |
+
@add_start_docstrings(
|
| 1165 |
+
"""
|
| 1166 |
+
Albert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1167 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1168 |
+
""",
|
| 1169 |
+
ALBERT_START_DOCSTRING,
|
| 1170 |
+
)
|
| 1171 |
+
class TFAlbertForTokenClassification(TFAlbertPreTrainedModel, TFTokenClassificationLoss):
|
| 1172 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1173 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"predictions"]
|
| 1174 |
+
_keys_to_ignore_on_load_missing = [r"dropout"]
|
| 1175 |
+
|
| 1176 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 1177 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1178 |
+
|
| 1179 |
+
self.num_labels = config.num_labels
|
| 1180 |
+
|
| 1181 |
+
self.albert = TFAlbertMainLayer(config, add_pooling_layer=False, name="albert")
|
| 1182 |
+
classifier_dropout_prob = (
|
| 1183 |
+
config.classifier_dropout_prob
|
| 1184 |
+
if config.classifier_dropout_prob is not None
|
| 1185 |
+
else config.hidden_dropout_prob
|
| 1186 |
+
)
|
| 1187 |
+
self.dropout = tf.keras.layers.Dropout(rate=classifier_dropout_prob)
|
| 1188 |
+
self.classifier = tf.keras.layers.Dense(
|
| 1189 |
+
units=config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 1190 |
+
)
|
| 1191 |
+
|
| 1192 |
+
@unpack_inputs
|
| 1193 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1194 |
+
@add_code_sample_docstrings(
|
| 1195 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1196 |
+
output_type=TFTokenClassifierOutput,
|
| 1197 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1198 |
+
)
|
| 1199 |
+
def call(
|
| 1200 |
+
self,
|
| 1201 |
+
input_ids: Optional[TFModelInputType] = None,
|
| 1202 |
+
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1203 |
+
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1204 |
+
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1205 |
+
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1206 |
+
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1207 |
+
output_attentions: Optional[bool] = None,
|
| 1208 |
+
output_hidden_states: Optional[bool] = None,
|
| 1209 |
+
return_dict: Optional[bool] = None,
|
| 1210 |
+
labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1211 |
+
training: Optional[bool] = False,
|
| 1212 |
+
) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:
|
| 1213 |
+
r"""
|
| 1214 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1215 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1216 |
+
"""
|
| 1217 |
+
outputs = self.albert(
|
| 1218 |
+
input_ids=input_ids,
|
| 1219 |
+
attention_mask=attention_mask,
|
| 1220 |
+
token_type_ids=token_type_ids,
|
| 1221 |
+
position_ids=position_ids,
|
| 1222 |
+
head_mask=head_mask,
|
| 1223 |
+
inputs_embeds=inputs_embeds,
|
| 1224 |
+
output_attentions=output_attentions,
|
| 1225 |
+
output_hidden_states=output_hidden_states,
|
| 1226 |
+
return_dict=return_dict,
|
| 1227 |
+
training=training,
|
| 1228 |
+
)
|
| 1229 |
+
sequence_output = outputs[0]
|
| 1230 |
+
sequence_output = self.dropout(inputs=sequence_output, training=training)
|
| 1231 |
+
logits = self.classifier(inputs=sequence_output)
|
| 1232 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
|
| 1233 |
+
|
| 1234 |
+
if not return_dict:
|
| 1235 |
+
output = (logits,) + outputs[2:]
|
| 1236 |
+
|
| 1237 |
+
return ((loss,) + output) if loss is not None else output
|
| 1238 |
+
|
| 1239 |
+
return TFTokenClassifierOutput(
|
| 1240 |
+
loss=loss,
|
| 1241 |
+
logits=logits,
|
| 1242 |
+
hidden_states=outputs.hidden_states,
|
| 1243 |
+
attentions=outputs.attentions,
|
| 1244 |
+
)
|
| 1245 |
+
|
| 1246 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertForTokenClassification.serving_output
|
| 1247 |
+
def serving_output(self, output: TFTokenClassifierOutput) -> TFTokenClassifierOutput:
|
| 1248 |
+
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
|
| 1249 |
+
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
|
| 1250 |
+
|
| 1251 |
+
return TFTokenClassifierOutput(logits=output.logits, hidden_states=hs, attentions=attns)
|
| 1252 |
+
|
| 1253 |
+
|
| 1254 |
+
@add_start_docstrings(
|
| 1255 |
+
"""
|
| 1256 |
+
Albert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1257 |
+
layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1258 |
+
""",
|
| 1259 |
+
ALBERT_START_DOCSTRING,
|
| 1260 |
+
)
|
| 1261 |
+
class TFAlbertForQuestionAnswering(TFAlbertPreTrainedModel, TFQuestionAnsweringLoss):
|
| 1262 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1263 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"predictions"]
|
| 1264 |
+
|
| 1265 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 1266 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1267 |
+
|
| 1268 |
+
self.num_labels = config.num_labels
|
| 1269 |
+
|
| 1270 |
+
self.albert = TFAlbertMainLayer(config, add_pooling_layer=False, name="albert")
|
| 1271 |
+
self.qa_outputs = tf.keras.layers.Dense(
|
| 1272 |
+
units=config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
|
| 1273 |
+
)
|
| 1274 |
+
|
| 1275 |
+
@unpack_inputs
|
| 1276 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1277 |
+
@add_code_sample_docstrings(
|
| 1278 |
+
checkpoint="vumichien/albert-base-v2-squad2",
|
| 1279 |
+
output_type=TFQuestionAnsweringModelOutput,
|
| 1280 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1281 |
+
qa_target_start_index=12,
|
| 1282 |
+
qa_target_end_index=13,
|
| 1283 |
+
expected_output="'a nice puppet'",
|
| 1284 |
+
expected_loss=7.36,
|
| 1285 |
+
)
|
| 1286 |
+
def call(
|
| 1287 |
+
self,
|
| 1288 |
+
input_ids: Optional[TFModelInputType] = None,
|
| 1289 |
+
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1290 |
+
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1291 |
+
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1292 |
+
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1293 |
+
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1294 |
+
output_attentions: Optional[bool] = None,
|
| 1295 |
+
output_hidden_states: Optional[bool] = None,
|
| 1296 |
+
return_dict: Optional[bool] = None,
|
| 1297 |
+
start_positions: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1298 |
+
end_positions: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1299 |
+
training: Optional[bool] = False,
|
| 1300 |
+
) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
|
| 1301 |
+
r"""
|
| 1302 |
+
start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1303 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1304 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1305 |
+
are not taken into account for computing the loss.
|
| 1306 |
+
end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1307 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1308 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1309 |
+
are not taken into account for computing the loss.
|
| 1310 |
+
"""
|
| 1311 |
+
outputs = self.albert(
|
| 1312 |
+
input_ids=input_ids,
|
| 1313 |
+
attention_mask=attention_mask,
|
| 1314 |
+
token_type_ids=token_type_ids,
|
| 1315 |
+
position_ids=position_ids,
|
| 1316 |
+
head_mask=head_mask,
|
| 1317 |
+
inputs_embeds=inputs_embeds,
|
| 1318 |
+
output_attentions=output_attentions,
|
| 1319 |
+
output_hidden_states=output_hidden_states,
|
| 1320 |
+
return_dict=return_dict,
|
| 1321 |
+
training=training,
|
| 1322 |
+
)
|
| 1323 |
+
sequence_output = outputs[0]
|
| 1324 |
+
logits = self.qa_outputs(inputs=sequence_output)
|
| 1325 |
+
start_logits, end_logits = tf.split(value=logits, num_or_size_splits=2, axis=-1)
|
| 1326 |
+
start_logits = tf.squeeze(input=start_logits, axis=-1)
|
| 1327 |
+
end_logits = tf.squeeze(input=end_logits, axis=-1)
|
| 1328 |
+
loss = None
|
| 1329 |
+
|
| 1330 |
+
if start_positions is not None and end_positions is not None:
|
| 1331 |
+
labels = {"start_position": start_positions}
|
| 1332 |
+
labels["end_position"] = end_positions
|
| 1333 |
+
loss = self.hf_compute_loss(labels=labels, logits=(start_logits, end_logits))
|
| 1334 |
+
|
| 1335 |
+
if not return_dict:
|
| 1336 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1337 |
+
|
| 1338 |
+
return ((loss,) + output) if loss is not None else output
|
| 1339 |
+
|
| 1340 |
+
return TFQuestionAnsweringModelOutput(
|
| 1341 |
+
loss=loss,
|
| 1342 |
+
start_logits=start_logits,
|
| 1343 |
+
end_logits=end_logits,
|
| 1344 |
+
hidden_states=outputs.hidden_states,
|
| 1345 |
+
attentions=outputs.attentions,
|
| 1346 |
+
)
|
| 1347 |
+
|
| 1348 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertForQuestionAnswering.serving_output
|
| 1349 |
+
def serving_output(self, output: TFQuestionAnsweringModelOutput) -> TFQuestionAnsweringModelOutput:
|
| 1350 |
+
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
|
| 1351 |
+
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
|
| 1352 |
+
|
| 1353 |
+
return TFQuestionAnsweringModelOutput(
|
| 1354 |
+
start_logits=output.start_logits, end_logits=output.end_logits, hidden_states=hs, attentions=attns
|
| 1355 |
+
)
|
| 1356 |
+
|
| 1357 |
+
|
| 1358 |
+
@add_start_docstrings(
|
| 1359 |
+
"""
|
| 1360 |
+
Albert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 1361 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 1362 |
+
""",
|
| 1363 |
+
ALBERT_START_DOCSTRING,
|
| 1364 |
+
)
|
| 1365 |
+
class TFAlbertForMultipleChoice(TFAlbertPreTrainedModel, TFMultipleChoiceLoss):
|
| 1366 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1367 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler", r"predictions"]
|
| 1368 |
+
_keys_to_ignore_on_load_missing = [r"dropout"]
|
| 1369 |
+
|
| 1370 |
+
def __init__(self, config: AlbertConfig, *inputs, **kwargs):
|
| 1371 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1372 |
+
|
| 1373 |
+
self.albert = TFAlbertMainLayer(config, name="albert")
|
| 1374 |
+
self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 1375 |
+
self.classifier = tf.keras.layers.Dense(
|
| 1376 |
+
units=1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 1377 |
+
)
|
| 1378 |
+
|
| 1379 |
+
@property
|
| 1380 |
+
def dummy_inputs(self):
|
| 1381 |
+
"""
|
| 1382 |
+
Dummy inputs to build the network.
|
| 1383 |
+
|
| 1384 |
+
Returns:
|
| 1385 |
+
tf.Tensor with dummy inputs
|
| 1386 |
+
"""
|
| 1387 |
+
return {"input_ids": tf.constant(MULTIPLE_CHOICE_DUMMY_INPUTS, dtype=tf.int32)}
|
| 1388 |
+
|
| 1389 |
+
@unpack_inputs
|
| 1390 |
+
@add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
|
| 1391 |
+
@add_code_sample_docstrings(
|
| 1392 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1393 |
+
output_type=TFMultipleChoiceModelOutput,
|
| 1394 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1395 |
+
)
|
| 1396 |
+
def call(
|
| 1397 |
+
self,
|
| 1398 |
+
input_ids: Optional[TFModelInputType] = None,
|
| 1399 |
+
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1400 |
+
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1401 |
+
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1402 |
+
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1403 |
+
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1404 |
+
output_attentions: Optional[bool] = None,
|
| 1405 |
+
output_hidden_states: Optional[bool] = None,
|
| 1406 |
+
return_dict: Optional[bool] = None,
|
| 1407 |
+
labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
|
| 1408 |
+
training: Optional[bool] = False,
|
| 1409 |
+
) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:
|
| 1410 |
+
r"""
|
| 1411 |
+
labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1412 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
|
| 1413 |
+
where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
|
| 1414 |
+
"""
|
| 1415 |
+
|
| 1416 |
+
if input_ids is not None:
|
| 1417 |
+
num_choices = shape_list(input_ids)[1]
|
| 1418 |
+
seq_length = shape_list(input_ids)[2]
|
| 1419 |
+
else:
|
| 1420 |
+
num_choices = shape_list(inputs_embeds)[1]
|
| 1421 |
+
seq_length = shape_list(inputs_embeds)[2]
|
| 1422 |
+
|
| 1423 |
+
flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
|
| 1424 |
+
flat_attention_mask = (
|
| 1425 |
+
tf.reshape(tensor=attention_mask, shape=(-1, seq_length)) if attention_mask is not None else None
|
| 1426 |
+
)
|
| 1427 |
+
flat_token_type_ids = (
|
| 1428 |
+
tf.reshape(tensor=token_type_ids, shape=(-1, seq_length)) if token_type_ids is not None else None
|
| 1429 |
+
)
|
| 1430 |
+
flat_position_ids = (
|
| 1431 |
+
tf.reshape(tensor=position_ids, shape=(-1, seq_length)) if position_ids is not None else None
|
| 1432 |
+
)
|
| 1433 |
+
flat_inputs_embeds = (
|
| 1434 |
+
tf.reshape(tensor=inputs_embeds, shape=(-1, seq_length, shape_list(inputs_embeds)[3]))
|
| 1435 |
+
if inputs_embeds is not None
|
| 1436 |
+
else None
|
| 1437 |
+
)
|
| 1438 |
+
outputs = self.albert(
|
| 1439 |
+
input_ids=flat_input_ids,
|
| 1440 |
+
attention_mask=flat_attention_mask,
|
| 1441 |
+
token_type_ids=flat_token_type_ids,
|
| 1442 |
+
position_ids=flat_position_ids,
|
| 1443 |
+
head_mask=head_mask,
|
| 1444 |
+
inputs_embeds=flat_inputs_embeds,
|
| 1445 |
+
output_attentions=output_attentions,
|
| 1446 |
+
output_hidden_states=output_hidden_states,
|
| 1447 |
+
return_dict=return_dict,
|
| 1448 |
+
training=training,
|
| 1449 |
+
)
|
| 1450 |
+
pooled_output = outputs[1]
|
| 1451 |
+
pooled_output = self.dropout(inputs=pooled_output, training=training)
|
| 1452 |
+
logits = self.classifier(inputs=pooled_output)
|
| 1453 |
+
reshaped_logits = tf.reshape(tensor=logits, shape=(-1, num_choices))
|
| 1454 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=reshaped_logits)
|
| 1455 |
+
|
| 1456 |
+
if not return_dict:
|
| 1457 |
+
output = (reshaped_logits,) + outputs[2:]
|
| 1458 |
+
return ((loss,) + output) if loss is not None else output
|
| 1459 |
+
|
| 1460 |
+
return TFMultipleChoiceModelOutput(
|
| 1461 |
+
loss=loss,
|
| 1462 |
+
logits=reshaped_logits,
|
| 1463 |
+
hidden_states=outputs.hidden_states,
|
| 1464 |
+
attentions=outputs.attentions,
|
| 1465 |
+
)
|
| 1466 |
+
|
| 1467 |
+
@tf.function(
|
| 1468 |
+
input_signature=[
|
| 1469 |
+
{
|
| 1470 |
+
"input_ids": tf.TensorSpec((None, None, None), tf.int32, name="input_ids"),
|
| 1471 |
+
"attention_mask": tf.TensorSpec((None, None, None), tf.int32, name="attention_mask"),
|
| 1472 |
+
"token_type_ids": tf.TensorSpec((None, None, None), tf.int32, name="token_type_ids"),
|
| 1473 |
+
}
|
| 1474 |
+
]
|
| 1475 |
+
)
|
| 1476 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertForMultipleChoice.serving
|
| 1477 |
+
def serving(self, inputs: Dict[str, tf.Tensor]) -> TFMultipleChoiceModelOutput:
|
| 1478 |
+
output = self.call(input_ids=inputs)
|
| 1479 |
+
|
| 1480 |
+
return self.serving_output(output)
|
| 1481 |
+
|
| 1482 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertForMultipleChoice.serving_output
|
| 1483 |
+
def serving_output(self, output: TFMultipleChoiceModelOutput) -> TFMultipleChoiceModelOutput:
|
| 1484 |
+
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
|
| 1485 |
+
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
|
| 1486 |
+
|
| 1487 |
+
return TFMultipleChoiceModelOutput(logits=output.logits, hidden_states=hs, attentions=attns)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/tokenization_albert.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Tokenization classes for ALBERT model."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import unicodedata
|
| 20 |
+
from shutil import copyfile
|
| 21 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 22 |
+
|
| 23 |
+
import sentencepiece as spm
|
| 24 |
+
|
| 25 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 26 |
+
from ...utils import logging
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
|
| 31 |
+
|
| 32 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
| 33 |
+
"vocab_file": {
|
| 34 |
+
"albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model",
|
| 35 |
+
"albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model",
|
| 36 |
+
"albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model",
|
| 37 |
+
"albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model",
|
| 38 |
+
"albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model",
|
| 39 |
+
"albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model",
|
| 40 |
+
"albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model",
|
| 41 |
+
"albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model",
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
| 46 |
+
"albert-base-v1": 512,
|
| 47 |
+
"albert-large-v1": 512,
|
| 48 |
+
"albert-xlarge-v1": 512,
|
| 49 |
+
"albert-xxlarge-v1": 512,
|
| 50 |
+
"albert-base-v2": 512,
|
| 51 |
+
"albert-large-v2": 512,
|
| 52 |
+
"albert-xlarge-v2": 512,
|
| 53 |
+
"albert-xxlarge-v2": 512,
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
SPIECE_UNDERLINE = "▁"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class AlbertTokenizer(PreTrainedTokenizer):
|
| 60 |
+
"""
|
| 61 |
+
Construct an ALBERT tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
| 62 |
+
|
| 63 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 64 |
+
this superclass for more information regarding those methods.
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
vocab_file (`str`):
|
| 68 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 69 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 70 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 71 |
+
Whether or not to lowercase the input when tokenizing.
|
| 72 |
+
remove_space (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
|
| 74 |
+
keep_accents (`bool`, *optional*, defaults to `False`):
|
| 75 |
+
Whether or not to keep accents when tokenizing.
|
| 76 |
+
bos_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 77 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 78 |
+
|
| 79 |
+
<Tip>
|
| 80 |
+
|
| 81 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 82 |
+
sequence. The token used is the `cls_token`.
|
| 83 |
+
|
| 84 |
+
</Tip>
|
| 85 |
+
|
| 86 |
+
eos_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 87 |
+
The end of sequence token.
|
| 88 |
+
|
| 89 |
+
<Tip>
|
| 90 |
+
|
| 91 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
| 92 |
+
The token used is the `sep_token`.
|
| 93 |
+
|
| 94 |
+
</Tip>
|
| 95 |
+
|
| 96 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 97 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 98 |
+
token instead.
|
| 99 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 100 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 101 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 102 |
+
token of a sequence built with special tokens.
|
| 103 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 104 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 105 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 106 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 107 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 108 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 109 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 110 |
+
modeling. This is the token which the model will try to predict.
|
| 111 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 112 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 113 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 114 |
+
to set:
|
| 115 |
+
|
| 116 |
+
- `enable_sampling`: Enable subword regularization.
|
| 117 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 118 |
+
|
| 119 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 120 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 121 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 122 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 123 |
+
|
| 124 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 125 |
+
BPE-dropout.
|
| 126 |
+
|
| 127 |
+
Attributes:
|
| 128 |
+
sp_model (`SentencePieceProcessor`):
|
| 129 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 133 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
| 134 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
| 135 |
+
|
| 136 |
+
def __init__(
|
| 137 |
+
self,
|
| 138 |
+
vocab_file,
|
| 139 |
+
do_lower_case=True,
|
| 140 |
+
remove_space=True,
|
| 141 |
+
keep_accents=False,
|
| 142 |
+
bos_token="[CLS]",
|
| 143 |
+
eos_token="[SEP]",
|
| 144 |
+
unk_token="<unk>",
|
| 145 |
+
sep_token="[SEP]",
|
| 146 |
+
pad_token="<pad>",
|
| 147 |
+
cls_token="[CLS]",
|
| 148 |
+
mask_token="[MASK]",
|
| 149 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
| 150 |
+
**kwargs,
|
| 151 |
+
) -> None:
|
| 152 |
+
# Mask token behave like a normal word, i.e. include the space before it and
|
| 153 |
+
# is included in the raw text, there should be a match in a non-normalized sentence.
|
| 154 |
+
mask_token = (
|
| 155 |
+
AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
|
| 156 |
+
if isinstance(mask_token, str)
|
| 157 |
+
else mask_token
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 161 |
+
|
| 162 |
+
super().__init__(
|
| 163 |
+
do_lower_case=do_lower_case,
|
| 164 |
+
remove_space=remove_space,
|
| 165 |
+
keep_accents=keep_accents,
|
| 166 |
+
bos_token=bos_token,
|
| 167 |
+
eos_token=eos_token,
|
| 168 |
+
unk_token=unk_token,
|
| 169 |
+
sep_token=sep_token,
|
| 170 |
+
pad_token=pad_token,
|
| 171 |
+
cls_token=cls_token,
|
| 172 |
+
mask_token=mask_token,
|
| 173 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 174 |
+
**kwargs,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
self.do_lower_case = do_lower_case
|
| 178 |
+
self.remove_space = remove_space
|
| 179 |
+
self.keep_accents = keep_accents
|
| 180 |
+
self.vocab_file = vocab_file
|
| 181 |
+
|
| 182 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 183 |
+
self.sp_model.Load(vocab_file)
|
| 184 |
+
|
| 185 |
+
@property
|
| 186 |
+
def vocab_size(self):
|
| 187 |
+
return len(self.sp_model)
|
| 188 |
+
|
| 189 |
+
def get_vocab(self):
|
| 190 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 191 |
+
vocab.update(self.added_tokens_encoder)
|
| 192 |
+
return vocab
|
| 193 |
+
|
| 194 |
+
def __getstate__(self):
|
| 195 |
+
state = self.__dict__.copy()
|
| 196 |
+
state["sp_model"] = None
|
| 197 |
+
return state
|
| 198 |
+
|
| 199 |
+
def __setstate__(self, d):
|
| 200 |
+
self.__dict__ = d
|
| 201 |
+
|
| 202 |
+
# for backward compatibility
|
| 203 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 204 |
+
self.sp_model_kwargs = {}
|
| 205 |
+
|
| 206 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 207 |
+
self.sp_model.Load(self.vocab_file)
|
| 208 |
+
|
| 209 |
+
def preprocess_text(self, inputs):
|
| 210 |
+
if self.remove_space:
|
| 211 |
+
outputs = " ".join(inputs.strip().split())
|
| 212 |
+
else:
|
| 213 |
+
outputs = inputs
|
| 214 |
+
outputs = outputs.replace("``", '"').replace("''", '"')
|
| 215 |
+
|
| 216 |
+
if not self.keep_accents:
|
| 217 |
+
outputs = unicodedata.normalize("NFKD", outputs)
|
| 218 |
+
outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
|
| 219 |
+
if self.do_lower_case:
|
| 220 |
+
outputs = outputs.lower()
|
| 221 |
+
|
| 222 |
+
return outputs
|
| 223 |
+
|
| 224 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 225 |
+
"""Tokenize a string."""
|
| 226 |
+
text = self.preprocess_text(text)
|
| 227 |
+
pieces = self.sp_model.encode(text, out_type=str)
|
| 228 |
+
new_pieces = []
|
| 229 |
+
for piece in pieces:
|
| 230 |
+
if len(piece) > 1 and piece[-1] == str(",") and piece[-2].isdigit():
|
| 231 |
+
cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
|
| 232 |
+
if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
|
| 233 |
+
if len(cur_pieces[0]) == 1:
|
| 234 |
+
cur_pieces = cur_pieces[1:]
|
| 235 |
+
else:
|
| 236 |
+
cur_pieces[0] = cur_pieces[0][1:]
|
| 237 |
+
cur_pieces.append(piece[-1])
|
| 238 |
+
new_pieces.extend(cur_pieces)
|
| 239 |
+
else:
|
| 240 |
+
new_pieces.append(piece)
|
| 241 |
+
|
| 242 |
+
return new_pieces
|
| 243 |
+
|
| 244 |
+
def _convert_token_to_id(self, token):
|
| 245 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 246 |
+
return self.sp_model.PieceToId(token)
|
| 247 |
+
|
| 248 |
+
def _convert_id_to_token(self, index):
|
| 249 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 250 |
+
return self.sp_model.IdToPiece(index)
|
| 251 |
+
|
| 252 |
+
def convert_tokens_to_string(self, tokens):
|
| 253 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 254 |
+
current_sub_tokens = []
|
| 255 |
+
out_string = ""
|
| 256 |
+
prev_is_special = False
|
| 257 |
+
for token in tokens:
|
| 258 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
| 259 |
+
if token in self.all_special_tokens:
|
| 260 |
+
if not prev_is_special:
|
| 261 |
+
out_string += " "
|
| 262 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
| 263 |
+
prev_is_special = True
|
| 264 |
+
current_sub_tokens = []
|
| 265 |
+
else:
|
| 266 |
+
current_sub_tokens.append(token)
|
| 267 |
+
prev_is_special = False
|
| 268 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
| 269 |
+
return out_string.strip()
|
| 270 |
+
|
| 271 |
+
def build_inputs_with_special_tokens(
|
| 272 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 273 |
+
) -> List[int]:
|
| 274 |
+
"""
|
| 275 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 276 |
+
adding special tokens. An ALBERT sequence has the following format:
|
| 277 |
+
|
| 278 |
+
- single sequence: `[CLS] X [SEP]`
|
| 279 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 280 |
+
|
| 281 |
+
Args:
|
| 282 |
+
token_ids_0 (`List[int]`):
|
| 283 |
+
List of IDs to which the special tokens will be added.
|
| 284 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 285 |
+
Optional second list of IDs for sequence pairs.
|
| 286 |
+
|
| 287 |
+
Returns:
|
| 288 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 289 |
+
"""
|
| 290 |
+
sep = [self.sep_token_id]
|
| 291 |
+
cls = [self.cls_token_id]
|
| 292 |
+
if token_ids_1 is None:
|
| 293 |
+
return cls + token_ids_0 + sep
|
| 294 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 295 |
+
|
| 296 |
+
def get_special_tokens_mask(
|
| 297 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 298 |
+
) -> List[int]:
|
| 299 |
+
"""
|
| 300 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 301 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 302 |
+
|
| 303 |
+
Args:
|
| 304 |
+
token_ids_0 (`List[int]`):
|
| 305 |
+
List of IDs.
|
| 306 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 307 |
+
Optional second list of IDs for sequence pairs.
|
| 308 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 309 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 310 |
+
|
| 311 |
+
Returns:
|
| 312 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 313 |
+
"""
|
| 314 |
+
|
| 315 |
+
if already_has_special_tokens:
|
| 316 |
+
return super().get_special_tokens_mask(
|
| 317 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
if token_ids_1 is not None:
|
| 321 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 322 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 323 |
+
|
| 324 |
+
def create_token_type_ids_from_sequences(
|
| 325 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 326 |
+
) -> List[int]:
|
| 327 |
+
"""
|
| 328 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
|
| 329 |
+
sequence pair mask has the following format:
|
| 330 |
+
|
| 331 |
+
```
|
| 332 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 333 |
+
| first sequence | second sequence |
|
| 334 |
+
```
|
| 335 |
+
|
| 336 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 337 |
+
|
| 338 |
+
Args:
|
| 339 |
+
token_ids_0 (`List[int]`):
|
| 340 |
+
List of IDs.
|
| 341 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 342 |
+
Optional second list of IDs for sequence pairs.
|
| 343 |
+
|
| 344 |
+
Returns:
|
| 345 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 346 |
+
"""
|
| 347 |
+
sep = [self.sep_token_id]
|
| 348 |
+
cls = [self.cls_token_id]
|
| 349 |
+
|
| 350 |
+
if token_ids_1 is None:
|
| 351 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 352 |
+
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
| 353 |
+
|
| 354 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 355 |
+
if not os.path.isdir(save_directory):
|
| 356 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 357 |
+
return
|
| 358 |
+
out_vocab_file = os.path.join(
|
| 359 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 363 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 364 |
+
elif not os.path.isfile(self.vocab_file):
|
| 365 |
+
with open(out_vocab_file, "wb") as fi:
|
| 366 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 367 |
+
fi.write(content_spiece_model)
|
| 368 |
+
|
| 369 |
+
return (out_vocab_file,)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/albert/tokenization_albert_fast.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Google AI, Google Brain and the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Tokenization classes for ALBERT model."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
from shutil import copyfile
|
| 20 |
+
from typing import List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
from ...tokenization_utils import AddedToken
|
| 23 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 24 |
+
from ...utils import is_sentencepiece_available, logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if is_sentencepiece_available():
|
| 28 |
+
from .tokenization_albert import AlbertTokenizer
|
| 29 |
+
else:
|
| 30 |
+
AlbertTokenizer = None
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
|
| 34 |
+
|
| 35 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
| 36 |
+
"vocab_file": {
|
| 37 |
+
"albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model",
|
| 38 |
+
"albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model",
|
| 39 |
+
"albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model",
|
| 40 |
+
"albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model",
|
| 41 |
+
"albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model",
|
| 42 |
+
"albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model",
|
| 43 |
+
"albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model",
|
| 44 |
+
"albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model",
|
| 45 |
+
},
|
| 46 |
+
"tokenizer_file": {
|
| 47 |
+
"albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json",
|
| 48 |
+
"albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json",
|
| 49 |
+
"albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json",
|
| 50 |
+
"albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json",
|
| 51 |
+
"albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json",
|
| 52 |
+
"albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json",
|
| 53 |
+
"albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json",
|
| 54 |
+
"albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json",
|
| 55 |
+
},
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
| 59 |
+
"albert-base-v1": 512,
|
| 60 |
+
"albert-large-v1": 512,
|
| 61 |
+
"albert-xlarge-v1": 512,
|
| 62 |
+
"albert-xxlarge-v1": 512,
|
| 63 |
+
"albert-base-v2": 512,
|
| 64 |
+
"albert-large-v2": 512,
|
| 65 |
+
"albert-xlarge-v2": 512,
|
| 66 |
+
"albert-xxlarge-v2": 512,
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
SPIECE_UNDERLINE = "▁"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class AlbertTokenizerFast(PreTrainedTokenizerFast):
|
| 73 |
+
"""
|
| 74 |
+
Construct a "fast" ALBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on
|
| 75 |
+
[Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This
|
| 76 |
+
tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to
|
| 77 |
+
this superclass for more information regarding those methods
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
vocab_file (`str`):
|
| 81 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 82 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 83 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 84 |
+
Whether or not to lowercase the input when tokenizing.
|
| 85 |
+
remove_space (`bool`, *optional*, defaults to `True`):
|
| 86 |
+
Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
|
| 87 |
+
keep_accents (`bool`, *optional*, defaults to `False`):
|
| 88 |
+
Whether or not to keep accents when tokenizing.
|
| 89 |
+
bos_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 90 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
| 91 |
+
|
| 92 |
+
<Tip>
|
| 93 |
+
|
| 94 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
| 95 |
+
sequence. The token used is the `cls_token`.
|
| 96 |
+
|
| 97 |
+
</Tip>
|
| 98 |
+
|
| 99 |
+
eos_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 100 |
+
The end of sequence token. .. note:: When building a sequence using special tokens, this is not the token
|
| 101 |
+
that is used for the end of sequence. The token used is the `sep_token`.
|
| 102 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 103 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 104 |
+
token instead.
|
| 105 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 106 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 107 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 108 |
+
token of a sequence built with special tokens.
|
| 109 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 110 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 111 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 112 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 113 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 114 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 115 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 116 |
+
modeling. This is the token which the model will try to predict.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 120 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
| 121 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
| 122 |
+
slow_tokenizer_class = AlbertTokenizer
|
| 123 |
+
|
| 124 |
+
def __init__(
|
| 125 |
+
self,
|
| 126 |
+
vocab_file=None,
|
| 127 |
+
tokenizer_file=None,
|
| 128 |
+
do_lower_case=True,
|
| 129 |
+
remove_space=True,
|
| 130 |
+
keep_accents=False,
|
| 131 |
+
bos_token="[CLS]",
|
| 132 |
+
eos_token="[SEP]",
|
| 133 |
+
unk_token="<unk>",
|
| 134 |
+
sep_token="[SEP]",
|
| 135 |
+
pad_token="<pad>",
|
| 136 |
+
cls_token="[CLS]",
|
| 137 |
+
mask_token="[MASK]",
|
| 138 |
+
**kwargs,
|
| 139 |
+
):
|
| 140 |
+
# Mask token behave like a normal word, i.e. include the space before it and
|
| 141 |
+
# is included in the raw text, there should be a match in a non-normalized sentence.
|
| 142 |
+
mask_token = (
|
| 143 |
+
AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
|
| 144 |
+
if isinstance(mask_token, str)
|
| 145 |
+
else mask_token
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
super().__init__(
|
| 149 |
+
vocab_file,
|
| 150 |
+
tokenizer_file=tokenizer_file,
|
| 151 |
+
do_lower_case=do_lower_case,
|
| 152 |
+
remove_space=remove_space,
|
| 153 |
+
keep_accents=keep_accents,
|
| 154 |
+
bos_token=bos_token,
|
| 155 |
+
eos_token=eos_token,
|
| 156 |
+
unk_token=unk_token,
|
| 157 |
+
sep_token=sep_token,
|
| 158 |
+
pad_token=pad_token,
|
| 159 |
+
cls_token=cls_token,
|
| 160 |
+
mask_token=mask_token,
|
| 161 |
+
**kwargs,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
self.do_lower_case = do_lower_case
|
| 165 |
+
self.remove_space = remove_space
|
| 166 |
+
self.keep_accents = keep_accents
|
| 167 |
+
self.vocab_file = vocab_file
|
| 168 |
+
self.can_save_slow_tokenizer = False if not self.vocab_file else True
|
| 169 |
+
|
| 170 |
+
def build_inputs_with_special_tokens(
|
| 171 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 172 |
+
) -> List[int]:
|
| 173 |
+
"""
|
| 174 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 175 |
+
adding special tokens. An ALBERT sequence has the following format:
|
| 176 |
+
|
| 177 |
+
- single sequence: `[CLS] X [SEP]`
|
| 178 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 179 |
+
|
| 180 |
+
Args:
|
| 181 |
+
token_ids_0 (`List[int]`):
|
| 182 |
+
List of IDs to which the special tokens will be added
|
| 183 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 184 |
+
Optional second list of IDs for sequence pairs.
|
| 185 |
+
|
| 186 |
+
Returns:
|
| 187 |
+
`List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 188 |
+
"""
|
| 189 |
+
sep = [self.sep_token_id]
|
| 190 |
+
cls = [self.cls_token_id]
|
| 191 |
+
if token_ids_1 is None:
|
| 192 |
+
return cls + token_ids_0 + sep
|
| 193 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 194 |
+
|
| 195 |
+
def create_token_type_ids_from_sequences(
|
| 196 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 197 |
+
) -> List[int]:
|
| 198 |
+
"""
|
| 199 |
+
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
|
| 200 |
+
sequence pair mask has the following format:
|
| 201 |
+
|
| 202 |
+
```
|
| 203 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 204 |
+
| first sequence | second sequence |
|
| 205 |
+
```
|
| 206 |
+
|
| 207 |
+
if token_ids_1 is None, only returns the first portion of the mask (0s).
|
| 208 |
+
|
| 209 |
+
Args:
|
| 210 |
+
token_ids_0 (`List[int]`):
|
| 211 |
+
List of ids.
|
| 212 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 213 |
+
Optional second list of IDs for sequence pairs.
|
| 214 |
+
|
| 215 |
+
Returns:
|
| 216 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 217 |
+
"""
|
| 218 |
+
sep = [self.sep_token_id]
|
| 219 |
+
cls = [self.cls_token_id]
|
| 220 |
+
|
| 221 |
+
if token_ids_1 is None:
|
| 222 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 223 |
+
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
| 224 |
+
|
| 225 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 226 |
+
if not self.can_save_slow_tokenizer:
|
| 227 |
+
raise ValueError(
|
| 228 |
+
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
|
| 229 |
+
"tokenizer."
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
if not os.path.isdir(save_directory):
|
| 233 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 234 |
+
return
|
| 235 |
+
out_vocab_file = os.path.join(
|
| 236 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
| 240 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 241 |
+
|
| 242 |
+
return (out_vocab_file,)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/align/__init__.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import (
|
| 17 |
+
OptionalDependencyNotAvailable,
|
| 18 |
+
_LazyModule,
|
| 19 |
+
is_torch_available,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_import_structure = {
|
| 24 |
+
"configuration_align": [
|
| 25 |
+
"ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
| 26 |
+
"AlignConfig",
|
| 27 |
+
"AlignTextConfig",
|
| 28 |
+
"AlignVisionConfig",
|
| 29 |
+
],
|
| 30 |
+
"processing_align": ["AlignProcessor"],
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
if not is_torch_available():
|
| 35 |
+
raise OptionalDependencyNotAvailable()
|
| 36 |
+
except OptionalDependencyNotAvailable:
|
| 37 |
+
pass
|
| 38 |
+
else:
|
| 39 |
+
_import_structure["modeling_align"] = [
|
| 40 |
+
"ALIGN_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 41 |
+
"AlignModel",
|
| 42 |
+
"AlignPreTrainedModel",
|
| 43 |
+
"AlignTextModel",
|
| 44 |
+
"AlignVisionModel",
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
if TYPE_CHECKING:
|
| 48 |
+
from .configuration_align import (
|
| 49 |
+
ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
| 50 |
+
AlignConfig,
|
| 51 |
+
AlignTextConfig,
|
| 52 |
+
AlignVisionConfig,
|
| 53 |
+
)
|
| 54 |
+
from .processing_align import AlignProcessor
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
if not is_torch_available():
|
| 58 |
+
raise OptionalDependencyNotAvailable()
|
| 59 |
+
except OptionalDependencyNotAvailable:
|
| 60 |
+
pass
|
| 61 |
+
else:
|
| 62 |
+
from .modeling_align import (
|
| 63 |
+
ALIGN_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 64 |
+
AlignModel,
|
| 65 |
+
AlignPreTrainedModel,
|
| 66 |
+
AlignTextModel,
|
| 67 |
+
AlignVisionModel,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
else:
|
| 71 |
+
import sys
|
| 72 |
+
|
| 73 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/align/configuration_align.py
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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f-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" ALIGN model configuration"""
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
import os
|
| 19 |
+
from typing import TYPE_CHECKING, List, Union
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
pass
|
| 24 |
+
|
| 25 |
+
from ...configuration_utils import PretrainedConfig
|
| 26 |
+
from ...utils import logging
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__)
|
| 30 |
+
|
| 31 |
+
ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 32 |
+
"kakaobrain/align-base": "https://huggingface.co/kakaobrain/align-base/resolve/main/config.json",
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class AlignTextConfig(PretrainedConfig):
|
| 37 |
+
r"""
|
| 38 |
+
This is the configuration class to store the configuration of a [`AlignTextModel`]. It is used to instantiate a
|
| 39 |
+
ALIGN text encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 40 |
+
configuration with the defaults will yield a similar configuration to that of the text encoder of the ALIGN
|
| 41 |
+
[kakaobrain/align-base](https://huggingface.co/kakaobrain/align-base) architecture. The default values here are
|
| 42 |
+
copied from BERT.
|
| 43 |
+
|
| 44 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 45 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 49 |
+
Vocabulary size of the Align Text model. Defines the number of different tokens that can be represented by
|
| 50 |
+
the `inputs_ids` passed when calling [`AlignTextModel`].
|
| 51 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 52 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 53 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 54 |
+
Number of hidden layers in the Transformer encoder.
|
| 55 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 56 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 57 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 58 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 59 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
| 60 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 61 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 62 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 63 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 64 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 65 |
+
The dropout ratio for the attention probabilities.
|
| 66 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 67 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 68 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 69 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 70 |
+
The vocabulary size of the `token_type_ids` passed when calling [`AlignTextModel`].
|
| 71 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 72 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 73 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 74 |
+
The epsilon used by the layer normalization layers.
|
| 75 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 76 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 77 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 78 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 79 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 80 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 81 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 82 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 83 |
+
relevant if `config.is_decoder=True`.
|
| 84 |
+
pad_token_id (`int`, *optional*, defaults to 0)
|
| 85 |
+
Padding token id.
|
| 86 |
+
|
| 87 |
+
Example:
|
| 88 |
+
|
| 89 |
+
```python
|
| 90 |
+
>>> from transformers import AlignTextConfig, AlignTextModel
|
| 91 |
+
|
| 92 |
+
>>> # Initializing a AlignTextConfig with kakaobrain/align-base style configuration
|
| 93 |
+
>>> configuration = AlignTextConfig()
|
| 94 |
+
|
| 95 |
+
>>> # Initializing a AlignTextModel (with random weights) from the kakaobrain/align-base style configuration
|
| 96 |
+
>>> model = AlignTextModel(configuration)
|
| 97 |
+
|
| 98 |
+
>>> # Accessing the model configuration
|
| 99 |
+
>>> configuration = model.config
|
| 100 |
+
```"""
|
| 101 |
+
model_type = "align_text_model"
|
| 102 |
+
|
| 103 |
+
def __init__(
|
| 104 |
+
self,
|
| 105 |
+
vocab_size=30522,
|
| 106 |
+
hidden_size=768,
|
| 107 |
+
num_hidden_layers=12,
|
| 108 |
+
num_attention_heads=12,
|
| 109 |
+
intermediate_size=3072,
|
| 110 |
+
hidden_act="gelu",
|
| 111 |
+
hidden_dropout_prob=0.1,
|
| 112 |
+
attention_probs_dropout_prob=0.1,
|
| 113 |
+
max_position_embeddings=512,
|
| 114 |
+
type_vocab_size=2,
|
| 115 |
+
initializer_range=0.02,
|
| 116 |
+
layer_norm_eps=1e-12,
|
| 117 |
+
pad_token_id=0,
|
| 118 |
+
position_embedding_type="absolute",
|
| 119 |
+
use_cache=True,
|
| 120 |
+
**kwargs,
|
| 121 |
+
):
|
| 122 |
+
super().__init__(**kwargs)
|
| 123 |
+
|
| 124 |
+
self.vocab_size = vocab_size
|
| 125 |
+
self.hidden_size = hidden_size
|
| 126 |
+
self.num_hidden_layers = num_hidden_layers
|
| 127 |
+
self.num_attention_heads = num_attention_heads
|
| 128 |
+
self.hidden_act = hidden_act
|
| 129 |
+
self.intermediate_size = intermediate_size
|
| 130 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 131 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 132 |
+
self.max_position_embeddings = max_position_embeddings
|
| 133 |
+
self.type_vocab_size = type_vocab_size
|
| 134 |
+
self.initializer_range = initializer_range
|
| 135 |
+
self.layer_norm_eps = layer_norm_eps
|
| 136 |
+
self.position_embedding_type = position_embedding_type
|
| 137 |
+
self.use_cache = use_cache
|
| 138 |
+
self.pad_token_id = pad_token_id
|
| 139 |
+
|
| 140 |
+
@classmethod
|
| 141 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 142 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 143 |
+
|
| 144 |
+
# get the text config dict if we are loading from AlignConfig
|
| 145 |
+
if config_dict.get("model_type") == "align":
|
| 146 |
+
config_dict = config_dict["text_config"]
|
| 147 |
+
|
| 148 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 149 |
+
logger.warning(
|
| 150 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 151 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class AlignVisionConfig(PretrainedConfig):
|
| 158 |
+
r"""
|
| 159 |
+
This is the configuration class to store the configuration of a [`AlignVisionModel`]. It is used to instantiate a
|
| 160 |
+
ALIGN vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 161 |
+
configuration with the defaults will yield a similar configuration to that of the vision encoder of the ALIGN
|
| 162 |
+
[kakaobrain/align-base](https://huggingface.co/kakaobrain/align-base) architecture. The default values are copied
|
| 163 |
+
from EfficientNet (efficientnet-b7)
|
| 164 |
+
|
| 165 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 166 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 170 |
+
The number of input channels.
|
| 171 |
+
image_size (`int`, *optional*, defaults to 600):
|
| 172 |
+
The input image size.
|
| 173 |
+
width_coefficient (`float`, *optional*, defaults to 2.0):
|
| 174 |
+
Scaling coefficient for network width at each stage.
|
| 175 |
+
depth_coefficient (`float`, *optional*, defaults to 3.1):
|
| 176 |
+
Scaling coefficient for network depth at each stage.
|
| 177 |
+
depth_divisor `int`, *optional*, defaults to 8):
|
| 178 |
+
A unit of network width.
|
| 179 |
+
kernel_sizes (`List[int]`, *optional*, defaults to `[3, 3, 5, 3, 5, 5, 3]`):
|
| 180 |
+
List of kernel sizes to be used in each block.
|
| 181 |
+
in_channels (`List[int]`, *optional*, defaults to `[32, 16, 24, 40, 80, 112, 192]`):
|
| 182 |
+
List of input channel sizes to be used in each block for convolutional layers.
|
| 183 |
+
out_channels (`List[int]`, *optional*, defaults to `[16, 24, 40, 80, 112, 192, 320]`):
|
| 184 |
+
List of output channel sizes to be used in each block for convolutional layers.
|
| 185 |
+
depthwise_padding (`List[int]`, *optional*, defaults to `[]`):
|
| 186 |
+
List of block indices with square padding.
|
| 187 |
+
strides: (`List[int]`, *optional*, defaults to `[1, 2, 2, 2, 1, 2, 1]`):
|
| 188 |
+
List of stride sizes to be used in each block for convolutional layers.
|
| 189 |
+
num_block_repeats (`List[int]`, *optional*, defaults to `[1, 2, 2, 3, 3, 4, 1]`):
|
| 190 |
+
List of the number of times each block is to repeated.
|
| 191 |
+
expand_ratios (`List[int]`, *optional*, defaults to `[1, 6, 6, 6, 6, 6, 6]`):
|
| 192 |
+
List of scaling coefficient of each block.
|
| 193 |
+
squeeze_expansion_ratio (`float`, *optional*, defaults to 0.25):
|
| 194 |
+
Squeeze expansion ratio.
|
| 195 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 196 |
+
The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`,
|
| 197 |
+
`"selu", `"gelu_new"`, `"silu"` and `"mish"` are supported.
|
| 198 |
+
hiddem_dim (`int`, *optional*, defaults to 1280):
|
| 199 |
+
The hidden dimension of the layer before the classification head.
|
| 200 |
+
pooling_type (`str` or `function`, *optional*, defaults to `"mean"`):
|
| 201 |
+
Type of final pooling to be applied before the dense classification head. Available options are [`"mean"`,
|
| 202 |
+
`"max"`]
|
| 203 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 204 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 205 |
+
batch_norm_eps (`float`, *optional*, defaults to 1e-3):
|
| 206 |
+
The epsilon used by the batch normalization layers.
|
| 207 |
+
batch_norm_momentum (`float`, *optional*, defaults to 0.99):
|
| 208 |
+
The momentum used by the batch normalization layers.
|
| 209 |
+
dropout_rate (`float`, *optional*, defaults to 0.5):
|
| 210 |
+
The dropout rate to be applied before final classifier layer.
|
| 211 |
+
drop_connect_rate (`float`, *optional*, defaults to 0.2):
|
| 212 |
+
The drop rate for skip connections.
|
| 213 |
+
|
| 214 |
+
Example:
|
| 215 |
+
|
| 216 |
+
```python
|
| 217 |
+
>>> from transformers import AlignVisionConfig, AlignVisionModel
|
| 218 |
+
|
| 219 |
+
>>> # Initializing a AlignVisionConfig with kakaobrain/align-base style configuration
|
| 220 |
+
>>> configuration = AlignVisionConfig()
|
| 221 |
+
|
| 222 |
+
>>> # Initializing a AlignVisionModel (with random weights) from the kakaobrain/align-base style configuration
|
| 223 |
+
>>> model = AlignVisionModel(configuration)
|
| 224 |
+
|
| 225 |
+
>>> # Accessing the model configuration
|
| 226 |
+
>>> configuration = model.config
|
| 227 |
+
```"""
|
| 228 |
+
|
| 229 |
+
model_type = "align_vision_model"
|
| 230 |
+
|
| 231 |
+
def __init__(
|
| 232 |
+
self,
|
| 233 |
+
num_channels: int = 3,
|
| 234 |
+
image_size: int = 600,
|
| 235 |
+
width_coefficient: float = 2.0,
|
| 236 |
+
depth_coefficient: float = 3.1,
|
| 237 |
+
depth_divisor: int = 8,
|
| 238 |
+
kernel_sizes: List[int] = [3, 3, 5, 3, 5, 5, 3],
|
| 239 |
+
in_channels: List[int] = [32, 16, 24, 40, 80, 112, 192],
|
| 240 |
+
out_channels: List[int] = [16, 24, 40, 80, 112, 192, 320],
|
| 241 |
+
depthwise_padding: List[int] = [],
|
| 242 |
+
strides: List[int] = [1, 2, 2, 2, 1, 2, 1],
|
| 243 |
+
num_block_repeats: List[int] = [1, 2, 2, 3, 3, 4, 1],
|
| 244 |
+
expand_ratios: List[int] = [1, 6, 6, 6, 6, 6, 6],
|
| 245 |
+
squeeze_expansion_ratio: float = 0.25,
|
| 246 |
+
hidden_act: str = "swish",
|
| 247 |
+
hidden_dim: int = 2560,
|
| 248 |
+
pooling_type: str = "mean",
|
| 249 |
+
initializer_range: float = 0.02,
|
| 250 |
+
batch_norm_eps: float = 0.001,
|
| 251 |
+
batch_norm_momentum: float = 0.99,
|
| 252 |
+
dropout_rate: float = 0.5,
|
| 253 |
+
drop_connect_rate: float = 0.2,
|
| 254 |
+
**kwargs,
|
| 255 |
+
):
|
| 256 |
+
super().__init__(**kwargs)
|
| 257 |
+
|
| 258 |
+
self.num_channels = num_channels
|
| 259 |
+
self.image_size = image_size
|
| 260 |
+
self.width_coefficient = width_coefficient
|
| 261 |
+
self.depth_coefficient = depth_coefficient
|
| 262 |
+
self.depth_divisor = depth_divisor
|
| 263 |
+
self.kernel_sizes = kernel_sizes
|
| 264 |
+
self.in_channels = in_channels
|
| 265 |
+
self.out_channels = out_channels
|
| 266 |
+
self.depthwise_padding = depthwise_padding
|
| 267 |
+
self.strides = strides
|
| 268 |
+
self.num_block_repeats = num_block_repeats
|
| 269 |
+
self.expand_ratios = expand_ratios
|
| 270 |
+
self.squeeze_expansion_ratio = squeeze_expansion_ratio
|
| 271 |
+
self.hidden_act = hidden_act
|
| 272 |
+
self.hidden_dim = hidden_dim
|
| 273 |
+
self.pooling_type = pooling_type
|
| 274 |
+
self.initializer_range = initializer_range
|
| 275 |
+
self.batch_norm_eps = batch_norm_eps
|
| 276 |
+
self.batch_norm_momentum = batch_norm_momentum
|
| 277 |
+
self.dropout_rate = dropout_rate
|
| 278 |
+
self.drop_connect_rate = drop_connect_rate
|
| 279 |
+
self.num_hidden_layers = sum(num_block_repeats) * 4
|
| 280 |
+
|
| 281 |
+
@classmethod
|
| 282 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 283 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 284 |
+
|
| 285 |
+
# get the vision config dict if we are loading from AlignConfig
|
| 286 |
+
if config_dict.get("model_type") == "align":
|
| 287 |
+
config_dict = config_dict["vision_config"]
|
| 288 |
+
|
| 289 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 290 |
+
logger.warning(
|
| 291 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 292 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class AlignConfig(PretrainedConfig):
|
| 299 |
+
r"""
|
| 300 |
+
[`AlignConfig`] is the configuration class to store the configuration of a [`AlignModel`]. It is used to
|
| 301 |
+
instantiate a ALIGN model according to the specified arguments, defining the text model and vision model configs.
|
| 302 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the ALIGN
|
| 303 |
+
[kakaobrain/align-base](https://huggingface.co/kakaobrain/align-base) architecture.
|
| 304 |
+
|
| 305 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 306 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
text_config (`dict`, *optional*):
|
| 310 |
+
Dictionary of configuration options used to initialize [`AlignTextConfig`].
|
| 311 |
+
vision_config (`dict`, *optional*):
|
| 312 |
+
Dictionary of configuration options used to initialize [`AlignVisionConfig`].
|
| 313 |
+
projection_dim (`int`, *optional*, defaults to 640):
|
| 314 |
+
Dimentionality of text and vision projection layers.
|
| 315 |
+
temperature_init_value (`float`, *optional*, defaults to 1.0):
|
| 316 |
+
The inital value of the *temperature* paramter. Default is used as per the original ALIGN implementation.
|
| 317 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 318 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 319 |
+
kwargs (*optional*):
|
| 320 |
+
Dictionary of keyword arguments.
|
| 321 |
+
|
| 322 |
+
Example:
|
| 323 |
+
|
| 324 |
+
```python
|
| 325 |
+
>>> from transformers import AlignConfig, AlignModel
|
| 326 |
+
|
| 327 |
+
>>> # Initializing a AlignConfig with kakaobrain/align-base style configuration
|
| 328 |
+
>>> configuration = AlignConfig()
|
| 329 |
+
|
| 330 |
+
>>> # Initializing a AlignModel (with random weights) from the kakaobrain/align-base style configuration
|
| 331 |
+
>>> model = AlignModel(configuration)
|
| 332 |
+
|
| 333 |
+
>>> # Accessing the model configuration
|
| 334 |
+
>>> configuration = model.config
|
| 335 |
+
|
| 336 |
+
>>> # We can also initialize a AlignConfig from a AlignTextConfig and a AlignVisionConfig
|
| 337 |
+
>>> from transformers import AlignTextConfig, AlignVisionConfig
|
| 338 |
+
|
| 339 |
+
>>> # Initializing ALIGN Text and Vision configurations
|
| 340 |
+
>>> config_text = AlignTextConfig()
|
| 341 |
+
>>> config_vision = AlignVisionConfig()
|
| 342 |
+
|
| 343 |
+
>>> config = AlignConfig.from_text_vision_configs(config_text, config_vision)
|
| 344 |
+
```"""
|
| 345 |
+
|
| 346 |
+
model_type = "align"
|
| 347 |
+
is_composition = True
|
| 348 |
+
|
| 349 |
+
def __init__(
|
| 350 |
+
self,
|
| 351 |
+
text_config=None,
|
| 352 |
+
vision_config=None,
|
| 353 |
+
projection_dim=640,
|
| 354 |
+
temperature_init_value=1.0,
|
| 355 |
+
initializer_range=0.02,
|
| 356 |
+
**kwargs,
|
| 357 |
+
):
|
| 358 |
+
super().__init__(**kwargs)
|
| 359 |
+
|
| 360 |
+
if text_config is None:
|
| 361 |
+
text_config = {}
|
| 362 |
+
logger.info("text_config is None. Initializing the AlignTextConfig with default values.")
|
| 363 |
+
|
| 364 |
+
if vision_config is None:
|
| 365 |
+
vision_config = {}
|
| 366 |
+
logger.info("vision_config is None. Initializing the AlignVisionConfig with default values.")
|
| 367 |
+
|
| 368 |
+
self.text_config = AlignTextConfig(**text_config)
|
| 369 |
+
self.vision_config = AlignVisionConfig(**vision_config)
|
| 370 |
+
|
| 371 |
+
self.projection_dim = projection_dim
|
| 372 |
+
self.temperature_init_value = temperature_init_value
|
| 373 |
+
self.initializer_range = initializer_range
|
| 374 |
+
|
| 375 |
+
@classmethod
|
| 376 |
+
def from_text_vision_configs(cls, text_config: AlignTextConfig, vision_config: AlignVisionConfig, **kwargs):
|
| 377 |
+
r"""
|
| 378 |
+
Instantiate a [`AlignConfig`] (or a derived class) from align text model configuration and align vision model
|
| 379 |
+
configuration.
|
| 380 |
+
|
| 381 |
+
Returns:
|
| 382 |
+
[`AlignConfig`]: An instance of a configuration object
|
| 383 |
+
"""
|
| 384 |
+
|
| 385 |
+
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
|
| 386 |
+
|
| 387 |
+
def to_dict(self):
|
| 388 |
+
"""
|
| 389 |
+
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
|
| 390 |
+
|
| 391 |
+
Returns:
|
| 392 |
+
`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
|
| 393 |
+
"""
|
| 394 |
+
output = copy.deepcopy(self.__dict__)
|
| 395 |
+
output["text_config"] = self.text_config.to_dict()
|
| 396 |
+
output["vision_config"] = self.vision_config.to_dict()
|
| 397 |
+
output["model_type"] = self.__class__.model_type
|
| 398 |
+
return output
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/align/convert_align_tf_to_hf.py
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert ALIGN checkpoints from the original repository."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
import align
|
| 21 |
+
import numpy as np
|
| 22 |
+
import requests
|
| 23 |
+
import tensorflow as tf
|
| 24 |
+
import torch
|
| 25 |
+
from PIL import Image
|
| 26 |
+
from tokenizer import Tokenizer
|
| 27 |
+
|
| 28 |
+
from transformers import (
|
| 29 |
+
AlignConfig,
|
| 30 |
+
AlignModel,
|
| 31 |
+
AlignProcessor,
|
| 32 |
+
BertConfig,
|
| 33 |
+
BertTokenizer,
|
| 34 |
+
EfficientNetConfig,
|
| 35 |
+
EfficientNetImageProcessor,
|
| 36 |
+
)
|
| 37 |
+
from transformers.utils import logging
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logging.set_verbosity_info()
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def preprocess(image):
|
| 45 |
+
image = tf.image.resize(image, (346, 346))
|
| 46 |
+
image = tf.image.crop_to_bounding_box(image, (346 - 289) // 2, (346 - 289) // 2, 289, 289)
|
| 47 |
+
return image
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_align_config():
|
| 51 |
+
vision_config = EfficientNetConfig.from_pretrained("google/efficientnet-b7")
|
| 52 |
+
vision_config.image_size = 289
|
| 53 |
+
vision_config.hidden_dim = 640
|
| 54 |
+
vision_config.id2label = {"0": "LABEL_0", "1": "LABEL_1"}
|
| 55 |
+
vision_config.label2id = {"LABEL_0": 0, "LABEL_1": 1}
|
| 56 |
+
vision_config.depthwise_padding = []
|
| 57 |
+
|
| 58 |
+
text_config = BertConfig()
|
| 59 |
+
config = AlignConfig.from_text_vision_configs(
|
| 60 |
+
text_config=text_config, vision_config=vision_config, projection_dim=640
|
| 61 |
+
)
|
| 62 |
+
return config
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# We will verify our results on an image of cute cats
|
| 66 |
+
def prepare_img():
|
| 67 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 68 |
+
im = Image.open(requests.get(url, stream=True).raw)
|
| 69 |
+
return im
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def get_processor():
|
| 73 |
+
image_processor = EfficientNetImageProcessor(
|
| 74 |
+
do_center_crop=True,
|
| 75 |
+
rescale_factor=1 / 127.5,
|
| 76 |
+
rescale_offset=True,
|
| 77 |
+
do_normalize=False,
|
| 78 |
+
include_top=False,
|
| 79 |
+
resample=Image.BILINEAR,
|
| 80 |
+
)
|
| 81 |
+
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
|
| 82 |
+
tokenizer.model_max_length = 64
|
| 83 |
+
processor = AlignProcessor(image_processor=image_processor, tokenizer=tokenizer)
|
| 84 |
+
return processor
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# here we list all keys to be renamed (original name on the left, our name on the right)
|
| 88 |
+
def rename_keys(original_param_names):
|
| 89 |
+
# EfficientNet image encoder
|
| 90 |
+
block_names = [v.split("_")[0].split("block")[1] for v in original_param_names if v.startswith("block")]
|
| 91 |
+
block_names = list(set(block_names))
|
| 92 |
+
block_names = sorted(block_names)
|
| 93 |
+
num_blocks = len(block_names)
|
| 94 |
+
block_name_mapping = {b: str(i) for b, i in zip(block_names, range(num_blocks))}
|
| 95 |
+
|
| 96 |
+
rename_keys = []
|
| 97 |
+
rename_keys.append(("stem_conv/kernel:0", "embeddings.convolution.weight"))
|
| 98 |
+
rename_keys.append(("stem_bn/gamma:0", "embeddings.batchnorm.weight"))
|
| 99 |
+
rename_keys.append(("stem_bn/beta:0", "embeddings.batchnorm.bias"))
|
| 100 |
+
rename_keys.append(("stem_bn/moving_mean:0", "embeddings.batchnorm.running_mean"))
|
| 101 |
+
rename_keys.append(("stem_bn/moving_variance:0", "embeddings.batchnorm.running_var"))
|
| 102 |
+
|
| 103 |
+
for b in block_names:
|
| 104 |
+
hf_b = block_name_mapping[b]
|
| 105 |
+
rename_keys.append((f"block{b}_expand_conv/kernel:0", f"encoder.blocks.{hf_b}.expansion.expand_conv.weight"))
|
| 106 |
+
rename_keys.append((f"block{b}_expand_bn/gamma:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.weight"))
|
| 107 |
+
rename_keys.append((f"block{b}_expand_bn/beta:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.bias"))
|
| 108 |
+
rename_keys.append(
|
| 109 |
+
(f"block{b}_expand_bn/moving_mean:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.running_mean")
|
| 110 |
+
)
|
| 111 |
+
rename_keys.append(
|
| 112 |
+
(f"block{b}_expand_bn/moving_variance:0", f"encoder.blocks.{hf_b}.expansion.expand_bn.running_var")
|
| 113 |
+
)
|
| 114 |
+
rename_keys.append(
|
| 115 |
+
(f"block{b}_dwconv/depthwise_kernel:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight")
|
| 116 |
+
)
|
| 117 |
+
rename_keys.append((f"block{b}_bn/gamma:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight"))
|
| 118 |
+
rename_keys.append((f"block{b}_bn/beta:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias"))
|
| 119 |
+
rename_keys.append(
|
| 120 |
+
(f"block{b}_bn/moving_mean:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean")
|
| 121 |
+
)
|
| 122 |
+
rename_keys.append(
|
| 123 |
+
(f"block{b}_bn/moving_variance:0", f"encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var")
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
rename_keys.append((f"block{b}_se_reduce/kernel:0", f"encoder.blocks.{hf_b}.squeeze_excite.reduce.weight"))
|
| 127 |
+
rename_keys.append((f"block{b}_se_reduce/bias:0", f"encoder.blocks.{hf_b}.squeeze_excite.reduce.bias"))
|
| 128 |
+
rename_keys.append((f"block{b}_se_expand/kernel:0", f"encoder.blocks.{hf_b}.squeeze_excite.expand.weight"))
|
| 129 |
+
rename_keys.append((f"block{b}_se_expand/bias:0", f"encoder.blocks.{hf_b}.squeeze_excite.expand.bias"))
|
| 130 |
+
rename_keys.append(
|
| 131 |
+
(f"block{b}_project_conv/kernel:0", f"encoder.blocks.{hf_b}.projection.project_conv.weight")
|
| 132 |
+
)
|
| 133 |
+
rename_keys.append((f"block{b}_project_bn/gamma:0", f"encoder.blocks.{hf_b}.projection.project_bn.weight"))
|
| 134 |
+
rename_keys.append((f"block{b}_project_bn/beta:0", f"encoder.blocks.{hf_b}.projection.project_bn.bias"))
|
| 135 |
+
rename_keys.append(
|
| 136 |
+
(f"block{b}_project_bn/moving_mean:0", f"encoder.blocks.{hf_b}.projection.project_bn.running_mean")
|
| 137 |
+
)
|
| 138 |
+
rename_keys.append(
|
| 139 |
+
(f"block{b}_project_bn/moving_variance:0", f"encoder.blocks.{hf_b}.projection.project_bn.running_var")
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
key_mapping = {}
|
| 143 |
+
for item in rename_keys:
|
| 144 |
+
if item[0] in original_param_names:
|
| 145 |
+
key_mapping[item[0]] = "vision_model." + item[1]
|
| 146 |
+
|
| 147 |
+
# BERT text encoder
|
| 148 |
+
rename_keys = []
|
| 149 |
+
old = "tf_bert_model/bert"
|
| 150 |
+
new = "text_model"
|
| 151 |
+
for i in range(12):
|
| 152 |
+
rename_keys.append(
|
| 153 |
+
(
|
| 154 |
+
f"{old}/encoder/layer_._{i}/attention/self/query/kernel:0",
|
| 155 |
+
f"{new}.encoder.layer.{i}.attention.self.query.weight",
|
| 156 |
+
)
|
| 157 |
+
)
|
| 158 |
+
rename_keys.append(
|
| 159 |
+
(
|
| 160 |
+
f"{old}/encoder/layer_._{i}/attention/self/query/bias:0",
|
| 161 |
+
f"{new}.encoder.layer.{i}.attention.self.query.bias",
|
| 162 |
+
)
|
| 163 |
+
)
|
| 164 |
+
rename_keys.append(
|
| 165 |
+
(
|
| 166 |
+
f"{old}/encoder/layer_._{i}/attention/self/key/kernel:0",
|
| 167 |
+
f"{new}.encoder.layer.{i}.attention.self.key.weight",
|
| 168 |
+
)
|
| 169 |
+
)
|
| 170 |
+
rename_keys.append(
|
| 171 |
+
(
|
| 172 |
+
f"{old}/encoder/layer_._{i}/attention/self/key/bias:0",
|
| 173 |
+
f"{new}.encoder.layer.{i}.attention.self.key.bias",
|
| 174 |
+
)
|
| 175 |
+
)
|
| 176 |
+
rename_keys.append(
|
| 177 |
+
(
|
| 178 |
+
f"{old}/encoder/layer_._{i}/attention/self/value/kernel:0",
|
| 179 |
+
f"{new}.encoder.layer.{i}.attention.self.value.weight",
|
| 180 |
+
)
|
| 181 |
+
)
|
| 182 |
+
rename_keys.append(
|
| 183 |
+
(
|
| 184 |
+
f"{old}/encoder/layer_._{i}/attention/self/value/bias:0",
|
| 185 |
+
f"{new}.encoder.layer.{i}.attention.self.value.bias",
|
| 186 |
+
)
|
| 187 |
+
)
|
| 188 |
+
rename_keys.append(
|
| 189 |
+
(
|
| 190 |
+
f"{old}/encoder/layer_._{i}/attention/output/dense/kernel:0",
|
| 191 |
+
f"{new}.encoder.layer.{i}.attention.output.dense.weight",
|
| 192 |
+
)
|
| 193 |
+
)
|
| 194 |
+
rename_keys.append(
|
| 195 |
+
(
|
| 196 |
+
f"{old}/encoder/layer_._{i}/attention/output/dense/bias:0",
|
| 197 |
+
f"{new}.encoder.layer.{i}.attention.output.dense.bias",
|
| 198 |
+
)
|
| 199 |
+
)
|
| 200 |
+
rename_keys.append(
|
| 201 |
+
(
|
| 202 |
+
f"{old}/encoder/layer_._{i}/attention/output/LayerNorm/gamma:0",
|
| 203 |
+
f"{new}.encoder.layer.{i}.attention.output.LayerNorm.weight",
|
| 204 |
+
)
|
| 205 |
+
)
|
| 206 |
+
rename_keys.append(
|
| 207 |
+
(
|
| 208 |
+
f"{old}/encoder/layer_._{i}/attention/output/LayerNorm/beta:0",
|
| 209 |
+
f"{new}.encoder.layer.{i}.attention.output.LayerNorm.bias",
|
| 210 |
+
)
|
| 211 |
+
)
|
| 212 |
+
rename_keys.append(
|
| 213 |
+
(
|
| 214 |
+
f"{old}/encoder/layer_._{i}/intermediate/dense/kernel:0",
|
| 215 |
+
f"{new}.encoder.layer.{i}.intermediate.dense.weight",
|
| 216 |
+
)
|
| 217 |
+
)
|
| 218 |
+
rename_keys.append(
|
| 219 |
+
(
|
| 220 |
+
f"{old}/encoder/layer_._{i}/intermediate/dense/bias:0",
|
| 221 |
+
f"{new}.encoder.layer.{i}.intermediate.dense.bias",
|
| 222 |
+
)
|
| 223 |
+
)
|
| 224 |
+
rename_keys.append(
|
| 225 |
+
(f"{old}/encoder/layer_._{i}/output/dense/kernel:0", f"{new}.encoder.layer.{i}.output.dense.weight")
|
| 226 |
+
)
|
| 227 |
+
rename_keys.append(
|
| 228 |
+
(f"{old}/encoder/layer_._{i}/output/dense/bias:0", f"{new}.encoder.layer.{i}.output.dense.bias")
|
| 229 |
+
)
|
| 230 |
+
rename_keys.append(
|
| 231 |
+
(f"{old}/encoder/layer_._{i}/output/LayerNorm/gamma:0", f"{new}.encoder.layer.{i}.output.LayerNorm.weight")
|
| 232 |
+
)
|
| 233 |
+
rename_keys.append(
|
| 234 |
+
(f"{old}/encoder/layer_._{i}/output/LayerNorm/beta:0", f"{new}.encoder.layer.{i}.output.LayerNorm.bias")
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
rename_keys.append((f"{old}/embeddings/word_embeddings/weight:0", f"{new}.embeddings.word_embeddings.weight"))
|
| 238 |
+
rename_keys.append(
|
| 239 |
+
(f"{old}/embeddings/position_embeddings/embeddings:0", f"{new}.embeddings.position_embeddings.weight")
|
| 240 |
+
)
|
| 241 |
+
rename_keys.append(
|
| 242 |
+
(f"{old}/embeddings/token_type_embeddings/embeddings:0", f"{new}.embeddings.token_type_embeddings.weight")
|
| 243 |
+
)
|
| 244 |
+
rename_keys.append((f"{old}/embeddings/LayerNorm/gamma:0", f"{new}.embeddings.LayerNorm.weight"))
|
| 245 |
+
rename_keys.append((f"{old}/embeddings/LayerNorm/beta:0", f"{new}.embeddings.LayerNorm.bias"))
|
| 246 |
+
|
| 247 |
+
rename_keys.append((f"{old}/pooler/dense/kernel:0", f"{new}.pooler.dense.weight"))
|
| 248 |
+
rename_keys.append((f"{old}/pooler/dense/bias:0", f"{new}.pooler.dense.bias"))
|
| 249 |
+
rename_keys.append(("dense/kernel:0", "text_projection.weight"))
|
| 250 |
+
rename_keys.append(("dense/bias:0", "text_projection.bias"))
|
| 251 |
+
rename_keys.append(("dense/bias:0", "text_projection.bias"))
|
| 252 |
+
rename_keys.append(("temperature:0", "temperature"))
|
| 253 |
+
|
| 254 |
+
for item in rename_keys:
|
| 255 |
+
if item[0] in original_param_names:
|
| 256 |
+
key_mapping[item[0]] = item[1]
|
| 257 |
+
return key_mapping
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def replace_params(hf_params, tf_params, key_mapping):
|
| 261 |
+
list(hf_params.keys())
|
| 262 |
+
|
| 263 |
+
for key, value in tf_params.items():
|
| 264 |
+
if key not in key_mapping:
|
| 265 |
+
continue
|
| 266 |
+
|
| 267 |
+
hf_key = key_mapping[key]
|
| 268 |
+
if "_conv" in key and "kernel" in key:
|
| 269 |
+
new_hf_value = torch.from_numpy(value).permute(3, 2, 0, 1)
|
| 270 |
+
elif "embeddings" in key:
|
| 271 |
+
new_hf_value = torch.from_numpy(value)
|
| 272 |
+
elif "depthwise_kernel" in key:
|
| 273 |
+
new_hf_value = torch.from_numpy(value).permute(2, 3, 0, 1)
|
| 274 |
+
elif "kernel" in key:
|
| 275 |
+
new_hf_value = torch.from_numpy(np.transpose(value))
|
| 276 |
+
elif "temperature" in key:
|
| 277 |
+
new_hf_value = value
|
| 278 |
+
elif "bn/gamma" or "bn/beta" in key:
|
| 279 |
+
new_hf_value = torch.from_numpy(np.transpose(value)).squeeze()
|
| 280 |
+
else:
|
| 281 |
+
new_hf_value = torch.from_numpy(value)
|
| 282 |
+
|
| 283 |
+
# Replace HF parameters with original TF model parameters
|
| 284 |
+
hf_params[hf_key].copy_(new_hf_value)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@torch.no_grad()
|
| 288 |
+
def convert_align_checkpoint(checkpoint_path, pytorch_dump_folder_path, save_model, push_to_hub):
|
| 289 |
+
"""
|
| 290 |
+
Copy/paste/tweak model's weights to our ALIGN structure.
|
| 291 |
+
"""
|
| 292 |
+
# Load original model
|
| 293 |
+
seq_length = 64
|
| 294 |
+
tok = Tokenizer(seq_length)
|
| 295 |
+
original_model = align.Align("efficientnet-b7", "bert-base", 640, seq_length, tok.get_vocab_size())
|
| 296 |
+
original_model.compile()
|
| 297 |
+
original_model.load_weights(checkpoint_path)
|
| 298 |
+
|
| 299 |
+
tf_params = original_model.trainable_variables
|
| 300 |
+
tf_non_train_params = original_model.non_trainable_variables
|
| 301 |
+
tf_params = {param.name: param.numpy() for param in tf_params}
|
| 302 |
+
for param in tf_non_train_params:
|
| 303 |
+
tf_params[param.name] = param.numpy()
|
| 304 |
+
tf_param_names = list(tf_params.keys())
|
| 305 |
+
|
| 306 |
+
# Load HuggingFace model
|
| 307 |
+
config = get_align_config()
|
| 308 |
+
hf_model = AlignModel(config).eval()
|
| 309 |
+
hf_params = hf_model.state_dict()
|
| 310 |
+
|
| 311 |
+
# Create src-to-dst parameter name mapping dictionary
|
| 312 |
+
print("Converting parameters...")
|
| 313 |
+
key_mapping = rename_keys(tf_param_names)
|
| 314 |
+
replace_params(hf_params, tf_params, key_mapping)
|
| 315 |
+
|
| 316 |
+
# Initialize processor
|
| 317 |
+
processor = get_processor()
|
| 318 |
+
inputs = processor(
|
| 319 |
+
images=prepare_img(), text="A picture of a cat", padding="max_length", max_length=64, return_tensors="pt"
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
# HF model inference
|
| 323 |
+
hf_model.eval()
|
| 324 |
+
with torch.no_grad():
|
| 325 |
+
outputs = hf_model(**inputs)
|
| 326 |
+
|
| 327 |
+
hf_image_features = outputs.image_embeds.detach().numpy()
|
| 328 |
+
hf_text_features = outputs.text_embeds.detach().numpy()
|
| 329 |
+
|
| 330 |
+
# Original model inference
|
| 331 |
+
original_model.trainable = False
|
| 332 |
+
tf_image_processor = EfficientNetImageProcessor(
|
| 333 |
+
do_center_crop=True,
|
| 334 |
+
do_rescale=False,
|
| 335 |
+
do_normalize=False,
|
| 336 |
+
include_top=False,
|
| 337 |
+
resample=Image.BILINEAR,
|
| 338 |
+
)
|
| 339 |
+
image = tf_image_processor(images=prepare_img(), return_tensors="tf", data_format="channels_last")["pixel_values"]
|
| 340 |
+
text = tok(tf.constant(["A picture of a cat"]))
|
| 341 |
+
|
| 342 |
+
image_features = original_model.image_encoder(image, training=False)
|
| 343 |
+
text_features = original_model.text_encoder(text, training=False)
|
| 344 |
+
|
| 345 |
+
image_features = tf.nn.l2_normalize(image_features, axis=-1)
|
| 346 |
+
text_features = tf.nn.l2_normalize(text_features, axis=-1)
|
| 347 |
+
|
| 348 |
+
# Check whether original and HF model outputs match -> np.allclose
|
| 349 |
+
assert np.allclose(image_features, hf_image_features, atol=1e-3), "The predicted image features are not the same."
|
| 350 |
+
assert np.allclose(text_features, hf_text_features, atol=1e-3), "The predicted text features are not the same."
|
| 351 |
+
print("Model outputs match!")
|
| 352 |
+
|
| 353 |
+
if save_model:
|
| 354 |
+
# Create folder to save model
|
| 355 |
+
if not os.path.isdir(pytorch_dump_folder_path):
|
| 356 |
+
os.mkdir(pytorch_dump_folder_path)
|
| 357 |
+
# Save converted model and feature extractor
|
| 358 |
+
hf_model.save_pretrained(pytorch_dump_folder_path)
|
| 359 |
+
processor.save_pretrained(pytorch_dump_folder_path)
|
| 360 |
+
|
| 361 |
+
if push_to_hub:
|
| 362 |
+
# Push model and feature extractor to hub
|
| 363 |
+
print("Pushing converted ALIGN to the hub...")
|
| 364 |
+
processor.push_to_hub("align-base")
|
| 365 |
+
hf_model.push_to_hub("align-base")
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
if __name__ == "__main__":
|
| 369 |
+
parser = argparse.ArgumentParser()
|
| 370 |
+
# Required parameters
|
| 371 |
+
parser.add_argument(
|
| 372 |
+
"--checkpoint_path",
|
| 373 |
+
default="./weights/model-weights",
|
| 374 |
+
type=str,
|
| 375 |
+
help="Path to the pretrained TF ALIGN checkpoint.",
|
| 376 |
+
)
|
| 377 |
+
parser.add_argument(
|
| 378 |
+
"--pytorch_dump_folder_path",
|
| 379 |
+
default="hf_model",
|
| 380 |
+
type=str,
|
| 381 |
+
help="Path to the output PyTorch model directory.",
|
| 382 |
+
)
|
| 383 |
+
parser.add_argument("--save_model", action="store_true", help="Save model to local")
|
| 384 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Push model and feature extractor to the hub")
|
| 385 |
+
|
| 386 |
+
args = parser.parse_args()
|
| 387 |
+
convert_align_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/align/modeling_align.py
ADDED
|
@@ -0,0 +1,1642 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The Google Research Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" PyTorch ALIGN model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Any, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
|
| 25 |
+
from ...activations import ACT2FN
|
| 26 |
+
from ...modeling_outputs import (
|
| 27 |
+
BaseModelOutputWithNoAttention,
|
| 28 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 29 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 30 |
+
BaseModelOutputWithPoolingAndNoAttention,
|
| 31 |
+
)
|
| 32 |
+
from ...modeling_utils import PreTrainedModel
|
| 33 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 34 |
+
from ...utils import (
|
| 35 |
+
ModelOutput,
|
| 36 |
+
add_start_docstrings,
|
| 37 |
+
add_start_docstrings_to_model_forward,
|
| 38 |
+
logging,
|
| 39 |
+
replace_return_docstrings,
|
| 40 |
+
)
|
| 41 |
+
from .configuration_align import AlignConfig, AlignTextConfig, AlignVisionConfig
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__)
|
| 45 |
+
|
| 46 |
+
_CHECKPOINT_FOR_DOC = "kakaobrain/align-base"
|
| 47 |
+
_CONFIG_FOR_DOC = "AlignConfig"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
ALIGN_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 51 |
+
"kakaobrain/align-base",
|
| 52 |
+
# See all ALIGN models at https://huggingface.co/models?filter=align
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
ALIGN_START_DOCSTRING = r"""
|
| 57 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 58 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 59 |
+
etc.)
|
| 60 |
+
|
| 61 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 62 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 63 |
+
and behavior.
|
| 64 |
+
|
| 65 |
+
Parameters:
|
| 66 |
+
config ([`AlignConfig`]): Model configuration class with all the parameters of the model.
|
| 67 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 68 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
ALIGN_TEXT_INPUTS_DOCSTRING = r"""
|
| 72 |
+
Args:
|
| 73 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 74 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 75 |
+
it.
|
| 76 |
+
|
| 77 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 78 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 79 |
+
|
| 80 |
+
[What are input IDs?](../glossary#input-ids)
|
| 81 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 82 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 83 |
+
|
| 84 |
+
- 1 for tokens that are **not masked**,
|
| 85 |
+
- 0 for tokens that are **masked**.
|
| 86 |
+
|
| 87 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 88 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 89 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 90 |
+
config.max_position_embeddings - 1]`.
|
| 91 |
+
|
| 92 |
+
[What are position IDs?](../glossary#position-ids)
|
| 93 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 94 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 95 |
+
1]`:
|
| 96 |
+
|
| 97 |
+
- 0 corresponds to a *sentence A* token,
|
| 98 |
+
- 1 corresponds to a *sentence B* token.
|
| 99 |
+
|
| 100 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 101 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 102 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 103 |
+
|
| 104 |
+
- 1 indicates the head is **not masked**,
|
| 105 |
+
- 0 indicates the head is **masked**.
|
| 106 |
+
|
| 107 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 108 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 109 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 110 |
+
model's internal embedding lookup matrix.
|
| 111 |
+
output_attentions (`bool`, *optional*):
|
| 112 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 113 |
+
tensors for more detail.
|
| 114 |
+
output_hidden_states (`bool`, *optional*):
|
| 115 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 116 |
+
more detail.
|
| 117 |
+
return_dict (`bool`, *optional*):
|
| 118 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
ALIGN_VISION_INPUTS_DOCSTRING = r"""
|
| 122 |
+
Args:
|
| 123 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 124 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 125 |
+
[`AutoImageProcessor`]. See [`EfficientNetImageProcessor.__call__`] for details.
|
| 126 |
+
output_hidden_states (`bool`, *optional*):
|
| 127 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 128 |
+
more detail.
|
| 129 |
+
return_dict (`bool`, *optional*):
|
| 130 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
ALIGN_INPUTS_DOCSTRING = r"""
|
| 134 |
+
Args:
|
| 135 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 136 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 137 |
+
it.
|
| 138 |
+
|
| 139 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 140 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 141 |
+
|
| 142 |
+
[What are input IDs?](../glossary#input-ids)
|
| 143 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 144 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 145 |
+
|
| 146 |
+
- 1 for tokens that are **not masked**,
|
| 147 |
+
- 0 for tokens that are **masked**.
|
| 148 |
+
|
| 149 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 150 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 151 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 152 |
+
config.max_position_embeddings - 1]`.
|
| 153 |
+
|
| 154 |
+
[What are position IDs?](../glossary#position-ids)
|
| 155 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 156 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 157 |
+
1]`:
|
| 158 |
+
|
| 159 |
+
- 0 corresponds to a *sentence A* token,
|
| 160 |
+
- 1 corresponds to a *sentence B* token.
|
| 161 |
+
|
| 162 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 163 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 164 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 165 |
+
|
| 166 |
+
- 1 indicates the head is **not masked**,
|
| 167 |
+
- 0 indicates the head is **masked**.
|
| 168 |
+
|
| 169 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 170 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 171 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 172 |
+
model's internal embedding lookup matrix.
|
| 173 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 174 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 175 |
+
[`AutoImageProcessor`]. See [`EfficientNetImageProcessor.__call__`] for details.
|
| 176 |
+
return_loss (`bool`, *optional*):
|
| 177 |
+
Whether or not to return the contrastive loss.
|
| 178 |
+
output_attentions (`bool`, *optional*):
|
| 179 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 180 |
+
tensors for more detail.
|
| 181 |
+
output_hidden_states (`bool`, *optional*):
|
| 182 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 183 |
+
more detail.
|
| 184 |
+
return_dict (`bool`, *optional*):
|
| 185 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@dataclass
|
| 190 |
+
class AlignVisionModelOutput(ModelOutput):
|
| 191 |
+
"""
|
| 192 |
+
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 196 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 197 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 198 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 199 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 200 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 201 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 202 |
+
|
| 203 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 207 |
+
last_hidden_state: torch.FloatTensor = None
|
| 208 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@dataclass
|
| 212 |
+
class AlignTextModelOutput(ModelOutput):
|
| 213 |
+
"""
|
| 214 |
+
Base class for text model's outputs that also contains a pooling of the last hidden states.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 218 |
+
The text embeddings obtained by applying the projection layer to the pooler_output.
|
| 219 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 220 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 221 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 222 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 223 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 224 |
+
|
| 225 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 226 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 227 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 228 |
+
sequence_length)`.
|
| 229 |
+
|
| 230 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 231 |
+
heads.
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
| 235 |
+
last_hidden_state: torch.FloatTensor = None
|
| 236 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 237 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
@dataclass
|
| 241 |
+
class AlignOutput(ModelOutput):
|
| 242 |
+
"""
|
| 243 |
+
Args:
|
| 244 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 245 |
+
Contrastive loss for image-text similarity.
|
| 246 |
+
logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
| 247 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
| 248 |
+
similarity scores.
|
| 249 |
+
logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
| 250 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
| 251 |
+
similarity scores.
|
| 252 |
+
text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 253 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`AlignTextModel`].
|
| 254 |
+
image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 255 |
+
The output of [`AlignVisionModel`].
|
| 256 |
+
text_model_output(`BaseModelOutputWithPoolingAndCrossAttentions`):
|
| 257 |
+
The output of the [`AlignTextModel`].
|
| 258 |
+
vision_model_output(`BaseModelOutputWithPoolingAndNoAttention`):
|
| 259 |
+
The output of the [`AlignVisionModel`].
|
| 260 |
+
"""
|
| 261 |
+
|
| 262 |
+
loss: Optional[torch.FloatTensor] = None
|
| 263 |
+
logits_per_image: torch.FloatTensor = None
|
| 264 |
+
logits_per_text: torch.FloatTensor = None
|
| 265 |
+
text_embeds: torch.FloatTensor = None
|
| 266 |
+
image_embeds: torch.FloatTensor = None
|
| 267 |
+
text_model_output: BaseModelOutputWithPoolingAndCrossAttentions = None
|
| 268 |
+
vision_model_output: BaseModelOutputWithPoolingAndNoAttention = None
|
| 269 |
+
|
| 270 |
+
def to_tuple(self) -> Tuple[Any]:
|
| 271 |
+
return tuple(
|
| 272 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 273 |
+
for k in self.keys()
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
# contrastive loss function, adapted from
|
| 278 |
+
# https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
|
| 279 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
| 280 |
+
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device), label_smoothing=0.1)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def align_loss(similarity: torch.Tensor) -> torch.Tensor:
|
| 284 |
+
caption_loss = contrastive_loss(similarity)
|
| 285 |
+
image_loss = contrastive_loss(similarity.t())
|
| 286 |
+
return (caption_loss + image_loss) / 2.0
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
# Copied from transformers.models.efficientnet.modeling_efficientnet.round_filters with EfficientNet -> AlignVision
|
| 290 |
+
def round_filters(config: AlignVisionConfig, num_channels: int):
|
| 291 |
+
r"""
|
| 292 |
+
Round number of filters based on depth multiplier.
|
| 293 |
+
"""
|
| 294 |
+
divisor = config.depth_divisor
|
| 295 |
+
num_channels *= config.width_coefficient
|
| 296 |
+
new_dim = max(divisor, int(num_channels + divisor / 2) // divisor * divisor)
|
| 297 |
+
|
| 298 |
+
# Make sure that round down does not go down by more than 10%.
|
| 299 |
+
if new_dim < 0.9 * num_channels:
|
| 300 |
+
new_dim += divisor
|
| 301 |
+
|
| 302 |
+
return int(new_dim)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
# Copied from transformers.models.efficientnet.modeling_efficientnet.correct_pad
|
| 306 |
+
def correct_pad(kernel_size: Union[int, Tuple], adjust: bool = True):
|
| 307 |
+
r"""
|
| 308 |
+
Utility function to get the tuple padding value for the depthwise convolution.
|
| 309 |
+
|
| 310 |
+
Args:
|
| 311 |
+
kernel_size (`int` or `tuple`):
|
| 312 |
+
Kernel size of the convolution layers.
|
| 313 |
+
adjust (`bool`, *optional*, defaults to `True`):
|
| 314 |
+
Adjusts padding value to apply to right and bottom sides of the input.
|
| 315 |
+
"""
|
| 316 |
+
if isinstance(kernel_size, int):
|
| 317 |
+
kernel_size = (kernel_size, kernel_size)
|
| 318 |
+
|
| 319 |
+
correct = (kernel_size[0] // 2, kernel_size[1] // 2)
|
| 320 |
+
if adjust:
|
| 321 |
+
return (correct[1] - 1, correct[1], correct[0] - 1, correct[0])
|
| 322 |
+
else:
|
| 323 |
+
return (correct[1], correct[1], correct[0], correct[0])
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
# Copied from transformers.models.efficientnet.modeling_efficientnet.EfficientNetEmbeddings with EfficientNet->AlignVision
|
| 327 |
+
class AlignVisionEmbeddings(nn.Module):
|
| 328 |
+
r"""
|
| 329 |
+
A module that corresponds to the stem module of the original work.
|
| 330 |
+
"""
|
| 331 |
+
|
| 332 |
+
def __init__(self, config: AlignVisionConfig):
|
| 333 |
+
super().__init__()
|
| 334 |
+
|
| 335 |
+
self.out_dim = round_filters(config, 32)
|
| 336 |
+
self.padding = nn.ZeroPad2d(padding=(0, 1, 0, 1))
|
| 337 |
+
self.convolution = nn.Conv2d(
|
| 338 |
+
config.num_channels, self.out_dim, kernel_size=3, stride=2, padding="valid", bias=False
|
| 339 |
+
)
|
| 340 |
+
self.batchnorm = nn.BatchNorm2d(self.out_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum)
|
| 341 |
+
self.activation = ACT2FN[config.hidden_act]
|
| 342 |
+
|
| 343 |
+
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
|
| 344 |
+
features = self.padding(pixel_values)
|
| 345 |
+
features = self.convolution(features)
|
| 346 |
+
features = self.batchnorm(features)
|
| 347 |
+
features = self.activation(features)
|
| 348 |
+
|
| 349 |
+
return features
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
# Copied from transformers.models.efficientnet.modeling_efficientnet.EfficientNetDepthwiseConv2d with EfficientNet->AlignVision
|
| 353 |
+
class AlignVisionDepthwiseConv2d(nn.Conv2d):
|
| 354 |
+
def __init__(
|
| 355 |
+
self,
|
| 356 |
+
in_channels,
|
| 357 |
+
depth_multiplier=1,
|
| 358 |
+
kernel_size=3,
|
| 359 |
+
stride=1,
|
| 360 |
+
padding=0,
|
| 361 |
+
dilation=1,
|
| 362 |
+
bias=True,
|
| 363 |
+
padding_mode="zeros",
|
| 364 |
+
):
|
| 365 |
+
out_channels = in_channels * depth_multiplier
|
| 366 |
+
super().__init__(
|
| 367 |
+
in_channels=in_channels,
|
| 368 |
+
out_channels=out_channels,
|
| 369 |
+
kernel_size=kernel_size,
|
| 370 |
+
stride=stride,
|
| 371 |
+
padding=padding,
|
| 372 |
+
dilation=dilation,
|
| 373 |
+
groups=in_channels,
|
| 374 |
+
bias=bias,
|
| 375 |
+
padding_mode=padding_mode,
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
# Copied from transformers.models.efficientnet.modeling_efficientnet.EfficientNetExpansionLayer with EfficientNet->AlignVision
|
| 380 |
+
class AlignVisionExpansionLayer(nn.Module):
|
| 381 |
+
r"""
|
| 382 |
+
This corresponds to the expansion phase of each block in the original implementation.
|
| 383 |
+
"""
|
| 384 |
+
|
| 385 |
+
def __init__(self, config: AlignVisionConfig, in_dim: int, out_dim: int, stride: int):
|
| 386 |
+
super().__init__()
|
| 387 |
+
self.expand_conv = nn.Conv2d(
|
| 388 |
+
in_channels=in_dim,
|
| 389 |
+
out_channels=out_dim,
|
| 390 |
+
kernel_size=1,
|
| 391 |
+
padding="same",
|
| 392 |
+
bias=False,
|
| 393 |
+
)
|
| 394 |
+
self.expand_bn = nn.BatchNorm2d(num_features=out_dim, eps=config.batch_norm_eps)
|
| 395 |
+
self.expand_act = ACT2FN[config.hidden_act]
|
| 396 |
+
|
| 397 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
|
| 398 |
+
# Expand phase
|
| 399 |
+
hidden_states = self.expand_conv(hidden_states)
|
| 400 |
+
hidden_states = self.expand_bn(hidden_states)
|
| 401 |
+
hidden_states = self.expand_act(hidden_states)
|
| 402 |
+
|
| 403 |
+
return hidden_states
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
# Copied from transformers.models.efficientnet.modeling_efficientnet.EfficientNetDepthwiseLayer with with EfficientNet->AlignVision
|
| 407 |
+
class AlignVisionDepthwiseLayer(nn.Module):
|
| 408 |
+
r"""
|
| 409 |
+
This corresponds to the depthwise convolution phase of each block in the original implementation.
|
| 410 |
+
"""
|
| 411 |
+
|
| 412 |
+
def __init__(
|
| 413 |
+
self,
|
| 414 |
+
config: AlignVisionConfig,
|
| 415 |
+
in_dim: int,
|
| 416 |
+
stride: int,
|
| 417 |
+
kernel_size: int,
|
| 418 |
+
adjust_padding: bool,
|
| 419 |
+
):
|
| 420 |
+
super().__init__()
|
| 421 |
+
self.stride = stride
|
| 422 |
+
conv_pad = "valid" if self.stride == 2 else "same"
|
| 423 |
+
padding = correct_pad(kernel_size, adjust=adjust_padding)
|
| 424 |
+
|
| 425 |
+
self.depthwise_conv_pad = nn.ZeroPad2d(padding=padding)
|
| 426 |
+
self.depthwise_conv = AlignVisionDepthwiseConv2d(
|
| 427 |
+
in_dim, kernel_size=kernel_size, stride=stride, padding=conv_pad, bias=False
|
| 428 |
+
)
|
| 429 |
+
self.depthwise_norm = nn.BatchNorm2d(
|
| 430 |
+
num_features=in_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum
|
| 431 |
+
)
|
| 432 |
+
self.depthwise_act = ACT2FN[config.hidden_act]
|
| 433 |
+
|
| 434 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
|
| 435 |
+
# Depthwise convolution
|
| 436 |
+
if self.stride == 2:
|
| 437 |
+
hidden_states = self.depthwise_conv_pad(hidden_states)
|
| 438 |
+
|
| 439 |
+
hidden_states = self.depthwise_conv(hidden_states)
|
| 440 |
+
hidden_states = self.depthwise_norm(hidden_states)
|
| 441 |
+
hidden_states = self.depthwise_act(hidden_states)
|
| 442 |
+
|
| 443 |
+
return hidden_states
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
# Copied from transformers.models.efficientnet.modeling_efficientnet.EfficientNetSqueezeExciteLayer with with EfficientNet->AlignVision
|
| 447 |
+
class AlignVisionSqueezeExciteLayer(nn.Module):
|
| 448 |
+
r"""
|
| 449 |
+
This corresponds to the Squeeze and Excitement phase of each block in the original implementation.
|
| 450 |
+
"""
|
| 451 |
+
|
| 452 |
+
def __init__(self, config: AlignVisionConfig, in_dim: int, expand_dim: int, expand: bool = False):
|
| 453 |
+
super().__init__()
|
| 454 |
+
self.dim = expand_dim if expand else in_dim
|
| 455 |
+
self.dim_se = max(1, int(in_dim * config.squeeze_expansion_ratio))
|
| 456 |
+
|
| 457 |
+
self.squeeze = nn.AdaptiveAvgPool2d(output_size=1)
|
| 458 |
+
self.reduce = nn.Conv2d(
|
| 459 |
+
in_channels=self.dim,
|
| 460 |
+
out_channels=self.dim_se,
|
| 461 |
+
kernel_size=1,
|
| 462 |
+
padding="same",
|
| 463 |
+
)
|
| 464 |
+
self.expand = nn.Conv2d(
|
| 465 |
+
in_channels=self.dim_se,
|
| 466 |
+
out_channels=self.dim,
|
| 467 |
+
kernel_size=1,
|
| 468 |
+
padding="same",
|
| 469 |
+
)
|
| 470 |
+
self.act_reduce = ACT2FN[config.hidden_act]
|
| 471 |
+
self.act_expand = nn.Sigmoid()
|
| 472 |
+
|
| 473 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
|
| 474 |
+
inputs = hidden_states
|
| 475 |
+
hidden_states = self.squeeze(hidden_states)
|
| 476 |
+
hidden_states = self.reduce(hidden_states)
|
| 477 |
+
hidden_states = self.act_reduce(hidden_states)
|
| 478 |
+
|
| 479 |
+
hidden_states = self.expand(hidden_states)
|
| 480 |
+
hidden_states = self.act_expand(hidden_states)
|
| 481 |
+
hidden_states = torch.mul(inputs, hidden_states)
|
| 482 |
+
|
| 483 |
+
return hidden_states
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
class AlignVisionFinalBlockLayer(nn.Module):
|
| 487 |
+
r"""
|
| 488 |
+
This corresponds to the final phase of each block in the original implementation.
|
| 489 |
+
"""
|
| 490 |
+
|
| 491 |
+
def __init__(
|
| 492 |
+
self, config: AlignVisionConfig, in_dim: int, out_dim: int, stride: int, drop_rate: float, id_skip: bool
|
| 493 |
+
):
|
| 494 |
+
super().__init__()
|
| 495 |
+
self.apply_dropout = stride == 1 and not id_skip
|
| 496 |
+
self.project_conv = nn.Conv2d(
|
| 497 |
+
in_channels=in_dim,
|
| 498 |
+
out_channels=out_dim,
|
| 499 |
+
kernel_size=1,
|
| 500 |
+
padding="same",
|
| 501 |
+
bias=False,
|
| 502 |
+
)
|
| 503 |
+
self.project_bn = nn.BatchNorm2d(
|
| 504 |
+
num_features=out_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum
|
| 505 |
+
)
|
| 506 |
+
self.dropout = nn.Dropout(p=drop_rate)
|
| 507 |
+
|
| 508 |
+
def forward(self, embeddings: torch.FloatTensor, hidden_states: torch.FloatTensor) -> torch.Tensor:
|
| 509 |
+
hidden_states = self.project_conv(hidden_states)
|
| 510 |
+
hidden_states = self.project_bn(hidden_states)
|
| 511 |
+
|
| 512 |
+
if self.apply_dropout:
|
| 513 |
+
hidden_states = self.dropout(hidden_states)
|
| 514 |
+
hidden_states = hidden_states + embeddings
|
| 515 |
+
|
| 516 |
+
return hidden_states
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
class AlignVisionBlock(nn.Module):
|
| 520 |
+
r"""
|
| 521 |
+
This corresponds to the block module of original the EfficientNet vision encoder implementation.
|
| 522 |
+
|
| 523 |
+
Args:
|
| 524 |
+
config ([`AlignVisionConfig`]):
|
| 525 |
+
Model configuration class.
|
| 526 |
+
in_dim (`int`):
|
| 527 |
+
Number of input channels.
|
| 528 |
+
out_dim (`int`):
|
| 529 |
+
Number of output channels.
|
| 530 |
+
stride (`int`):
|
| 531 |
+
Stride size to be used in convolution layers.
|
| 532 |
+
expand_ratio (`int`):
|
| 533 |
+
Expand ratio to set the output dimensions for the expansion and squeeze-excite layers.
|
| 534 |
+
kernel_size (`int`):
|
| 535 |
+
Kernel size for the depthwise convolution layer.
|
| 536 |
+
drop_rate (`float`):
|
| 537 |
+
Dropout rate to be used in the final phase of each block.
|
| 538 |
+
id_skip (`bool`):
|
| 539 |
+
Whether to apply dropout and sum the final hidden states with the input embeddings during the final phase
|
| 540 |
+
of each block. Set to `True` for the first block of each stage.
|
| 541 |
+
adjust_padding (`bool`):
|
| 542 |
+
Whether to apply padding to only right and bottom side of the input kernel before the depthwise convolution
|
| 543 |
+
operation, set to `True` for inputs with odd input sizes.
|
| 544 |
+
"""
|
| 545 |
+
|
| 546 |
+
def __init__(
|
| 547 |
+
self,
|
| 548 |
+
config: AlignVisionConfig,
|
| 549 |
+
in_dim: int,
|
| 550 |
+
out_dim: int,
|
| 551 |
+
stride: int,
|
| 552 |
+
expand_ratio: int,
|
| 553 |
+
kernel_size: int,
|
| 554 |
+
drop_rate: float,
|
| 555 |
+
id_skip: bool,
|
| 556 |
+
adjust_padding: bool,
|
| 557 |
+
):
|
| 558 |
+
super().__init__()
|
| 559 |
+
self.expand_ratio = expand_ratio
|
| 560 |
+
self.expand = True if self.expand_ratio != 1 else False
|
| 561 |
+
expand_in_dim = in_dim * expand_ratio
|
| 562 |
+
|
| 563 |
+
if self.expand:
|
| 564 |
+
self.expansion = AlignVisionExpansionLayer(
|
| 565 |
+
config=config, in_dim=in_dim, out_dim=expand_in_dim, stride=stride
|
| 566 |
+
)
|
| 567 |
+
|
| 568 |
+
self.depthwise_conv = AlignVisionDepthwiseLayer(
|
| 569 |
+
config=config,
|
| 570 |
+
in_dim=expand_in_dim if self.expand else in_dim,
|
| 571 |
+
stride=stride,
|
| 572 |
+
kernel_size=kernel_size,
|
| 573 |
+
adjust_padding=adjust_padding,
|
| 574 |
+
)
|
| 575 |
+
self.squeeze_excite = AlignVisionSqueezeExciteLayer(
|
| 576 |
+
config=config, in_dim=in_dim, expand_dim=expand_in_dim, expand=self.expand
|
| 577 |
+
)
|
| 578 |
+
self.projection = AlignVisionFinalBlockLayer(
|
| 579 |
+
config=config,
|
| 580 |
+
in_dim=expand_in_dim if self.expand else in_dim,
|
| 581 |
+
out_dim=out_dim,
|
| 582 |
+
stride=stride,
|
| 583 |
+
drop_rate=drop_rate,
|
| 584 |
+
id_skip=id_skip,
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
|
| 588 |
+
embeddings = hidden_states
|
| 589 |
+
# Expansion and depthwise convolution phase
|
| 590 |
+
if self.expand_ratio != 1:
|
| 591 |
+
hidden_states = self.expansion(hidden_states)
|
| 592 |
+
hidden_states = self.depthwise_conv(hidden_states)
|
| 593 |
+
|
| 594 |
+
# Squeeze and excite phase
|
| 595 |
+
hidden_states = self.squeeze_excite(hidden_states)
|
| 596 |
+
hidden_states = self.projection(embeddings, hidden_states)
|
| 597 |
+
return hidden_states
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
class AlignVisionEncoder(nn.Module):
|
| 601 |
+
r"""
|
| 602 |
+
Forward propogates the embeddings through each vision encoder (EfficientNet) block.
|
| 603 |
+
|
| 604 |
+
Args:
|
| 605 |
+
config ([`AlignVisionConfig`]):
|
| 606 |
+
Model configuration class.
|
| 607 |
+
"""
|
| 608 |
+
|
| 609 |
+
def __init__(self, config: AlignVisionConfig):
|
| 610 |
+
super().__init__()
|
| 611 |
+
self.depth_coefficient = config.depth_coefficient
|
| 612 |
+
|
| 613 |
+
def round_repeats(repeats):
|
| 614 |
+
# Round number of block repeats based on depth multiplier.
|
| 615 |
+
return int(math.ceil(self.depth_coefficient * repeats))
|
| 616 |
+
|
| 617 |
+
num_base_blocks = len(config.in_channels)
|
| 618 |
+
num_blocks = sum(round_repeats(n) for n in config.num_block_repeats)
|
| 619 |
+
|
| 620 |
+
curr_block_num = 0
|
| 621 |
+
blocks = []
|
| 622 |
+
for i in range(num_base_blocks):
|
| 623 |
+
in_dim = round_filters(config, config.in_channels[i])
|
| 624 |
+
out_dim = round_filters(config, config.out_channels[i])
|
| 625 |
+
stride = config.strides[i]
|
| 626 |
+
kernel_size = config.kernel_sizes[i]
|
| 627 |
+
expand_ratio = config.expand_ratios[i]
|
| 628 |
+
|
| 629 |
+
for j in range(round_repeats(config.num_block_repeats[i])):
|
| 630 |
+
id_skip = True if j == 0 else False
|
| 631 |
+
stride = 1 if j > 0 else stride
|
| 632 |
+
in_dim = out_dim if j > 0 else in_dim
|
| 633 |
+
adjust_padding = False if curr_block_num in config.depthwise_padding else True
|
| 634 |
+
drop_rate = config.drop_connect_rate * curr_block_num / num_blocks
|
| 635 |
+
|
| 636 |
+
block = AlignVisionBlock(
|
| 637 |
+
config=config,
|
| 638 |
+
in_dim=in_dim,
|
| 639 |
+
out_dim=out_dim,
|
| 640 |
+
stride=stride,
|
| 641 |
+
kernel_size=kernel_size,
|
| 642 |
+
expand_ratio=expand_ratio,
|
| 643 |
+
drop_rate=drop_rate,
|
| 644 |
+
id_skip=id_skip,
|
| 645 |
+
adjust_padding=adjust_padding,
|
| 646 |
+
)
|
| 647 |
+
blocks.append(block)
|
| 648 |
+
curr_block_num += 1
|
| 649 |
+
|
| 650 |
+
self.blocks = nn.ModuleList(blocks)
|
| 651 |
+
|
| 652 |
+
def forward(
|
| 653 |
+
self,
|
| 654 |
+
hidden_states: torch.FloatTensor,
|
| 655 |
+
output_hidden_states: Optional[bool] = False,
|
| 656 |
+
return_dict: Optional[bool] = True,
|
| 657 |
+
) -> BaseModelOutputWithPoolingAndNoAttention:
|
| 658 |
+
all_hidden_states = (hidden_states,) if output_hidden_states else None
|
| 659 |
+
|
| 660 |
+
for block in self.blocks:
|
| 661 |
+
hidden_states = block(hidden_states)
|
| 662 |
+
if output_hidden_states:
|
| 663 |
+
all_hidden_states += (hidden_states,)
|
| 664 |
+
|
| 665 |
+
if not return_dict:
|
| 666 |
+
return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
|
| 667 |
+
|
| 668 |
+
return BaseModelOutputWithNoAttention(
|
| 669 |
+
last_hidden_state=hidden_states,
|
| 670 |
+
hidden_states=all_hidden_states,
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
# Copied from transformers.models.bert.modeling_bert.BertEmbeddings with Bert->AlignText
|
| 675 |
+
class AlignTextEmbeddings(nn.Module):
|
| 676 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 677 |
+
|
| 678 |
+
def __init__(self, config):
|
| 679 |
+
super().__init__()
|
| 680 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 681 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 682 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 683 |
+
|
| 684 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 685 |
+
# any TensorFlow checkpoint file
|
| 686 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 687 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 688 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 689 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 690 |
+
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
|
| 691 |
+
self.register_buffer(
|
| 692 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
def forward(
|
| 696 |
+
self,
|
| 697 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 698 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 699 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 700 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 701 |
+
past_key_values_length: int = 0,
|
| 702 |
+
) -> torch.Tensor:
|
| 703 |
+
if input_ids is not None:
|
| 704 |
+
input_shape = input_ids.size()
|
| 705 |
+
else:
|
| 706 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 707 |
+
|
| 708 |
+
seq_length = input_shape[1]
|
| 709 |
+
|
| 710 |
+
if position_ids is None:
|
| 711 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 712 |
+
|
| 713 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 714 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 715 |
+
# issue #5664
|
| 716 |
+
if token_type_ids is None:
|
| 717 |
+
if hasattr(self, "token_type_ids"):
|
| 718 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 719 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 720 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 721 |
+
else:
|
| 722 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 723 |
+
|
| 724 |
+
if inputs_embeds is None:
|
| 725 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 726 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 727 |
+
|
| 728 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 729 |
+
if self.position_embedding_type == "absolute":
|
| 730 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 731 |
+
embeddings += position_embeddings
|
| 732 |
+
embeddings = self.LayerNorm(embeddings)
|
| 733 |
+
embeddings = self.dropout(embeddings)
|
| 734 |
+
return embeddings
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->AlignText
|
| 738 |
+
class AlignTextSelfAttention(nn.Module):
|
| 739 |
+
def __init__(self, config, position_embedding_type=None):
|
| 740 |
+
super().__init__()
|
| 741 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 742 |
+
raise ValueError(
|
| 743 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 744 |
+
f"heads ({config.num_attention_heads})"
|
| 745 |
+
)
|
| 746 |
+
|
| 747 |
+
self.num_attention_heads = config.num_attention_heads
|
| 748 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 749 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 750 |
+
|
| 751 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 752 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 753 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 754 |
+
|
| 755 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 756 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
| 757 |
+
config, "position_embedding_type", "absolute"
|
| 758 |
+
)
|
| 759 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 760 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 761 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 762 |
+
|
| 763 |
+
self.is_decoder = config.is_decoder
|
| 764 |
+
|
| 765 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 766 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 767 |
+
x = x.view(new_x_shape)
|
| 768 |
+
return x.permute(0, 2, 1, 3)
|
| 769 |
+
|
| 770 |
+
def forward(
|
| 771 |
+
self,
|
| 772 |
+
hidden_states: torch.Tensor,
|
| 773 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 774 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 775 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 776 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 777 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 778 |
+
output_attentions: Optional[bool] = False,
|
| 779 |
+
) -> Tuple[torch.Tensor]:
|
| 780 |
+
mixed_query_layer = self.query(hidden_states)
|
| 781 |
+
|
| 782 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 783 |
+
# and values come from an encoder; the attention mask needs to be
|
| 784 |
+
# such that the encoder's padding tokens are not attended to.
|
| 785 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 786 |
+
|
| 787 |
+
if is_cross_attention and past_key_value is not None:
|
| 788 |
+
# reuse k,v, cross_attentions
|
| 789 |
+
key_layer = past_key_value[0]
|
| 790 |
+
value_layer = past_key_value[1]
|
| 791 |
+
attention_mask = encoder_attention_mask
|
| 792 |
+
elif is_cross_attention:
|
| 793 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 794 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 795 |
+
attention_mask = encoder_attention_mask
|
| 796 |
+
elif past_key_value is not None:
|
| 797 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 798 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 799 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
| 800 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
| 801 |
+
else:
|
| 802 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 803 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 804 |
+
|
| 805 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 806 |
+
|
| 807 |
+
use_cache = past_key_value is not None
|
| 808 |
+
if self.is_decoder:
|
| 809 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 810 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 811 |
+
# key/value_states (first "if" case)
|
| 812 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 813 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 814 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 815 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 816 |
+
past_key_value = (key_layer, value_layer)
|
| 817 |
+
|
| 818 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 819 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 820 |
+
|
| 821 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 822 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
| 823 |
+
if use_cache:
|
| 824 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
| 825 |
+
-1, 1
|
| 826 |
+
)
|
| 827 |
+
else:
|
| 828 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 829 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 830 |
+
distance = position_ids_l - position_ids_r
|
| 831 |
+
|
| 832 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 833 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 834 |
+
|
| 835 |
+
if self.position_embedding_type == "relative_key":
|
| 836 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 837 |
+
attention_scores = attention_scores + relative_position_scores
|
| 838 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 839 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 840 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 841 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 842 |
+
|
| 843 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 844 |
+
if attention_mask is not None:
|
| 845 |
+
# Apply the attention mask is (precomputed for all layers in AlignTextModel forward() function)
|
| 846 |
+
attention_scores = attention_scores + attention_mask
|
| 847 |
+
|
| 848 |
+
# Normalize the attention scores to probabilities.
|
| 849 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 850 |
+
|
| 851 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 852 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 853 |
+
attention_probs = self.dropout(attention_probs)
|
| 854 |
+
|
| 855 |
+
# Mask heads if we want to
|
| 856 |
+
if head_mask is not None:
|
| 857 |
+
attention_probs = attention_probs * head_mask
|
| 858 |
+
|
| 859 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 860 |
+
|
| 861 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 862 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 863 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 864 |
+
|
| 865 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 866 |
+
|
| 867 |
+
if self.is_decoder:
|
| 868 |
+
outputs = outputs + (past_key_value,)
|
| 869 |
+
return outputs
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->AlignText
|
| 873 |
+
class AlignTextSelfOutput(nn.Module):
|
| 874 |
+
def __init__(self, config):
|
| 875 |
+
super().__init__()
|
| 876 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 877 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 878 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 879 |
+
|
| 880 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 881 |
+
hidden_states = self.dense(hidden_states)
|
| 882 |
+
hidden_states = self.dropout(hidden_states)
|
| 883 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 884 |
+
return hidden_states
|
| 885 |
+
|
| 886 |
+
|
| 887 |
+
# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->AlignText
|
| 888 |
+
class AlignTextAttention(nn.Module):
|
| 889 |
+
def __init__(self, config, position_embedding_type=None):
|
| 890 |
+
super().__init__()
|
| 891 |
+
self.self = AlignTextSelfAttention(config, position_embedding_type=position_embedding_type)
|
| 892 |
+
self.output = AlignTextSelfOutput(config)
|
| 893 |
+
self.pruned_heads = set()
|
| 894 |
+
|
| 895 |
+
def prune_heads(self, heads):
|
| 896 |
+
if len(heads) == 0:
|
| 897 |
+
return
|
| 898 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 899 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
# Prune linear layers
|
| 903 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 904 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 905 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 906 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 907 |
+
|
| 908 |
+
# Update hyper params and store pruned heads
|
| 909 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 910 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 911 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 912 |
+
|
| 913 |
+
def forward(
|
| 914 |
+
self,
|
| 915 |
+
hidden_states: torch.Tensor,
|
| 916 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 917 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 918 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 919 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 920 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 921 |
+
output_attentions: Optional[bool] = False,
|
| 922 |
+
) -> Tuple[torch.Tensor]:
|
| 923 |
+
self_outputs = self.self(
|
| 924 |
+
hidden_states,
|
| 925 |
+
attention_mask,
|
| 926 |
+
head_mask,
|
| 927 |
+
encoder_hidden_states,
|
| 928 |
+
encoder_attention_mask,
|
| 929 |
+
past_key_value,
|
| 930 |
+
output_attentions,
|
| 931 |
+
)
|
| 932 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 933 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 934 |
+
return outputs
|
| 935 |
+
|
| 936 |
+
|
| 937 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->AlignText
|
| 938 |
+
class AlignTextIntermediate(nn.Module):
|
| 939 |
+
def __init__(self, config):
|
| 940 |
+
super().__init__()
|
| 941 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 942 |
+
if isinstance(config.hidden_act, str):
|
| 943 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 944 |
+
else:
|
| 945 |
+
self.intermediate_act_fn = config.hidden_act
|
| 946 |
+
|
| 947 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 948 |
+
hidden_states = self.dense(hidden_states)
|
| 949 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 950 |
+
return hidden_states
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->AlignText
|
| 954 |
+
class AlignTextOutput(nn.Module):
|
| 955 |
+
def __init__(self, config):
|
| 956 |
+
super().__init__()
|
| 957 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 958 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 959 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 960 |
+
|
| 961 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 962 |
+
hidden_states = self.dense(hidden_states)
|
| 963 |
+
hidden_states = self.dropout(hidden_states)
|
| 964 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 965 |
+
return hidden_states
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
# Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->AlignText
|
| 969 |
+
class AlignTextLayer(nn.Module):
|
| 970 |
+
def __init__(self, config):
|
| 971 |
+
super().__init__()
|
| 972 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 973 |
+
self.seq_len_dim = 1
|
| 974 |
+
self.attention = AlignTextAttention(config)
|
| 975 |
+
self.is_decoder = config.is_decoder
|
| 976 |
+
self.add_cross_attention = config.add_cross_attention
|
| 977 |
+
if self.add_cross_attention:
|
| 978 |
+
if not self.is_decoder:
|
| 979 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 980 |
+
self.crossattention = AlignTextAttention(config, position_embedding_type="absolute")
|
| 981 |
+
self.intermediate = AlignTextIntermediate(config)
|
| 982 |
+
self.output = AlignTextOutput(config)
|
| 983 |
+
|
| 984 |
+
def forward(
|
| 985 |
+
self,
|
| 986 |
+
hidden_states: torch.Tensor,
|
| 987 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 988 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 989 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 990 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 991 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 992 |
+
output_attentions: Optional[bool] = False,
|
| 993 |
+
) -> Tuple[torch.Tensor]:
|
| 994 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 995 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 996 |
+
self_attention_outputs = self.attention(
|
| 997 |
+
hidden_states,
|
| 998 |
+
attention_mask,
|
| 999 |
+
head_mask,
|
| 1000 |
+
output_attentions=output_attentions,
|
| 1001 |
+
past_key_value=self_attn_past_key_value,
|
| 1002 |
+
)
|
| 1003 |
+
attention_output = self_attention_outputs[0]
|
| 1004 |
+
|
| 1005 |
+
# if decoder, the last output is tuple of self-attn cache
|
| 1006 |
+
if self.is_decoder:
|
| 1007 |
+
outputs = self_attention_outputs[1:-1]
|
| 1008 |
+
present_key_value = self_attention_outputs[-1]
|
| 1009 |
+
else:
|
| 1010 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 1011 |
+
|
| 1012 |
+
cross_attn_present_key_value = None
|
| 1013 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 1014 |
+
if not hasattr(self, "crossattention"):
|
| 1015 |
+
raise ValueError(
|
| 1016 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 1017 |
+
" by setting `config.add_cross_attention=True`"
|
| 1018 |
+
)
|
| 1019 |
+
|
| 1020 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
| 1021 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 1022 |
+
cross_attention_outputs = self.crossattention(
|
| 1023 |
+
attention_output,
|
| 1024 |
+
attention_mask,
|
| 1025 |
+
head_mask,
|
| 1026 |
+
encoder_hidden_states,
|
| 1027 |
+
encoder_attention_mask,
|
| 1028 |
+
cross_attn_past_key_value,
|
| 1029 |
+
output_attentions,
|
| 1030 |
+
)
|
| 1031 |
+
attention_output = cross_attention_outputs[0]
|
| 1032 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 1033 |
+
|
| 1034 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
| 1035 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
| 1036 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 1037 |
+
|
| 1038 |
+
layer_output = apply_chunking_to_forward(
|
| 1039 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 1040 |
+
)
|
| 1041 |
+
outputs = (layer_output,) + outputs
|
| 1042 |
+
|
| 1043 |
+
# if decoder, return the attn key/values as the last output
|
| 1044 |
+
if self.is_decoder:
|
| 1045 |
+
outputs = outputs + (present_key_value,)
|
| 1046 |
+
|
| 1047 |
+
return outputs
|
| 1048 |
+
|
| 1049 |
+
def feed_forward_chunk(self, attention_output):
|
| 1050 |
+
intermediate_output = self.intermediate(attention_output)
|
| 1051 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 1052 |
+
return layer_output
|
| 1053 |
+
|
| 1054 |
+
|
| 1055 |
+
# Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->AlignText
|
| 1056 |
+
class AlignTextEncoder(nn.Module):
|
| 1057 |
+
def __init__(self, config):
|
| 1058 |
+
super().__init__()
|
| 1059 |
+
self.config = config
|
| 1060 |
+
self.layer = nn.ModuleList([AlignTextLayer(config) for _ in range(config.num_hidden_layers)])
|
| 1061 |
+
self.gradient_checkpointing = False
|
| 1062 |
+
|
| 1063 |
+
def forward(
|
| 1064 |
+
self,
|
| 1065 |
+
hidden_states: torch.Tensor,
|
| 1066 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1067 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 1068 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 1069 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 1070 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 1071 |
+
use_cache: Optional[bool] = None,
|
| 1072 |
+
output_attentions: Optional[bool] = False,
|
| 1073 |
+
output_hidden_states: Optional[bool] = False,
|
| 1074 |
+
return_dict: Optional[bool] = True,
|
| 1075 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
| 1076 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1077 |
+
all_self_attentions = () if output_attentions else None
|
| 1078 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 1079 |
+
|
| 1080 |
+
if self.gradient_checkpointing and self.training:
|
| 1081 |
+
if use_cache:
|
| 1082 |
+
logger.warning_once(
|
| 1083 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 1084 |
+
)
|
| 1085 |
+
use_cache = False
|
| 1086 |
+
|
| 1087 |
+
next_decoder_cache = () if use_cache else None
|
| 1088 |
+
for i, layer_module in enumerate(self.layer):
|
| 1089 |
+
if output_hidden_states:
|
| 1090 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 1091 |
+
|
| 1092 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 1093 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 1094 |
+
|
| 1095 |
+
if self.gradient_checkpointing and self.training:
|
| 1096 |
+
|
| 1097 |
+
def create_custom_forward(module):
|
| 1098 |
+
def custom_forward(*inputs):
|
| 1099 |
+
return module(*inputs, past_key_value, output_attentions)
|
| 1100 |
+
|
| 1101 |
+
return custom_forward
|
| 1102 |
+
|
| 1103 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 1104 |
+
create_custom_forward(layer_module),
|
| 1105 |
+
hidden_states,
|
| 1106 |
+
attention_mask,
|
| 1107 |
+
layer_head_mask,
|
| 1108 |
+
encoder_hidden_states,
|
| 1109 |
+
encoder_attention_mask,
|
| 1110 |
+
)
|
| 1111 |
+
else:
|
| 1112 |
+
layer_outputs = layer_module(
|
| 1113 |
+
hidden_states,
|
| 1114 |
+
attention_mask,
|
| 1115 |
+
layer_head_mask,
|
| 1116 |
+
encoder_hidden_states,
|
| 1117 |
+
encoder_attention_mask,
|
| 1118 |
+
past_key_value,
|
| 1119 |
+
output_attentions,
|
| 1120 |
+
)
|
| 1121 |
+
|
| 1122 |
+
hidden_states = layer_outputs[0]
|
| 1123 |
+
if use_cache:
|
| 1124 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 1125 |
+
if output_attentions:
|
| 1126 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 1127 |
+
if self.config.add_cross_attention:
|
| 1128 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 1129 |
+
|
| 1130 |
+
if output_hidden_states:
|
| 1131 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 1132 |
+
|
| 1133 |
+
if not return_dict:
|
| 1134 |
+
return tuple(
|
| 1135 |
+
v
|
| 1136 |
+
for v in [
|
| 1137 |
+
hidden_states,
|
| 1138 |
+
next_decoder_cache,
|
| 1139 |
+
all_hidden_states,
|
| 1140 |
+
all_self_attentions,
|
| 1141 |
+
all_cross_attentions,
|
| 1142 |
+
]
|
| 1143 |
+
if v is not None
|
| 1144 |
+
)
|
| 1145 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 1146 |
+
last_hidden_state=hidden_states,
|
| 1147 |
+
past_key_values=next_decoder_cache,
|
| 1148 |
+
hidden_states=all_hidden_states,
|
| 1149 |
+
attentions=all_self_attentions,
|
| 1150 |
+
cross_attentions=all_cross_attentions,
|
| 1151 |
+
)
|
| 1152 |
+
|
| 1153 |
+
|
| 1154 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler with Bert -> AlignText
|
| 1155 |
+
class AlignTextPooler(nn.Module):
|
| 1156 |
+
def __init__(self, config):
|
| 1157 |
+
super().__init__()
|
| 1158 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 1159 |
+
self.activation = nn.Tanh()
|
| 1160 |
+
|
| 1161 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 1162 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 1163 |
+
# to the first token.
|
| 1164 |
+
first_token_tensor = hidden_states[:, 0]
|
| 1165 |
+
pooled_output = self.dense(first_token_tensor)
|
| 1166 |
+
pooled_output = self.activation(pooled_output)
|
| 1167 |
+
return pooled_output
|
| 1168 |
+
|
| 1169 |
+
|
| 1170 |
+
class AlignPreTrainedModel(PreTrainedModel):
|
| 1171 |
+
"""
|
| 1172 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 1173 |
+
models.
|
| 1174 |
+
"""
|
| 1175 |
+
|
| 1176 |
+
config_class = AlignConfig
|
| 1177 |
+
base_model_prefix = "align"
|
| 1178 |
+
supports_gradient_checkpointing = True
|
| 1179 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
| 1180 |
+
|
| 1181 |
+
def _init_weights(self, module):
|
| 1182 |
+
"""Initialize the weights"""
|
| 1183 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 1184 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 1185 |
+
if module.bias is not None:
|
| 1186 |
+
module.bias.data.zero_()
|
| 1187 |
+
elif isinstance(module, AlignModel):
|
| 1188 |
+
nn.init.xavier_uniform_(module.text_projection.weight)
|
| 1189 |
+
module.text_projection.bias.data.zero_()
|
| 1190 |
+
module.text_projection._is_hf_initialized = True
|
| 1191 |
+
elif isinstance(module, nn.Embedding):
|
| 1192 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 1193 |
+
if module.padding_idx is not None:
|
| 1194 |
+
module.weight.data[module.padding_idx].zero_()
|
| 1195 |
+
if isinstance(module, nn.LayerNorm):
|
| 1196 |
+
module.bias.data.zero_()
|
| 1197 |
+
module.weight.data.fill_(1.0)
|
| 1198 |
+
|
| 1199 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 1200 |
+
if isinstance(module, (AlignTextModel, AlignVisionModel)):
|
| 1201 |
+
module.gradient_checkpointing = value
|
| 1202 |
+
|
| 1203 |
+
|
| 1204 |
+
@add_start_docstrings(
|
| 1205 |
+
"""The text model from ALIGN without any head or projection on top.""",
|
| 1206 |
+
ALIGN_START_DOCSTRING,
|
| 1207 |
+
)
|
| 1208 |
+
class AlignTextModel(AlignPreTrainedModel):
|
| 1209 |
+
config_class = AlignTextConfig
|
| 1210 |
+
|
| 1211 |
+
def __init__(self, config: AlignTextConfig, add_pooling_layer: bool = True):
|
| 1212 |
+
super().__init__(config)
|
| 1213 |
+
self.config = config
|
| 1214 |
+
|
| 1215 |
+
self.embeddings = AlignTextEmbeddings(config)
|
| 1216 |
+
self.encoder = AlignTextEncoder(config)
|
| 1217 |
+
|
| 1218 |
+
self.pooler = AlignTextPooler(config) if add_pooling_layer else None
|
| 1219 |
+
|
| 1220 |
+
# Initialize weights and apply final processing
|
| 1221 |
+
self.post_init()
|
| 1222 |
+
|
| 1223 |
+
def get_input_embeddings(self):
|
| 1224 |
+
return self.embeddings.word_embeddings
|
| 1225 |
+
|
| 1226 |
+
def set_input_embeddings(self, value):
|
| 1227 |
+
self.embeddings.word_embeddings = value
|
| 1228 |
+
|
| 1229 |
+
@add_start_docstrings_to_model_forward(ALIGN_TEXT_INPUTS_DOCSTRING)
|
| 1230 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPoolingAndCrossAttentions, config_class=AlignTextConfig)
|
| 1231 |
+
def forward(
|
| 1232 |
+
self,
|
| 1233 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1234 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1235 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1236 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1237 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1238 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1239 |
+
output_attentions: Optional[bool] = None,
|
| 1240 |
+
output_hidden_states: Optional[bool] = None,
|
| 1241 |
+
return_dict: Optional[bool] = None,
|
| 1242 |
+
) -> Union[Tuple, BaseModelOutputWithPoolingAndCrossAttentions]:
|
| 1243 |
+
r"""
|
| 1244 |
+
Returns:
|
| 1245 |
+
|
| 1246 |
+
Examples:
|
| 1247 |
+
|
| 1248 |
+
```python
|
| 1249 |
+
>>> from transformers import AutoTokenizer, AlignTextModel
|
| 1250 |
+
|
| 1251 |
+
>>> model = AlignTextModel.from_pretrained("kakaobrain/align-base")
|
| 1252 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("kakaobrain/align-base")
|
| 1253 |
+
|
| 1254 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
| 1255 |
+
|
| 1256 |
+
>>> outputs = model(**inputs)
|
| 1257 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 1258 |
+
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
|
| 1259 |
+
```"""
|
| 1260 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1261 |
+
output_hidden_states = (
|
| 1262 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1263 |
+
)
|
| 1264 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1265 |
+
|
| 1266 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1267 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 1268 |
+
elif input_ids is not None:
|
| 1269 |
+
input_shape = input_ids.size()
|
| 1270 |
+
elif inputs_embeds is not None:
|
| 1271 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1272 |
+
else:
|
| 1273 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1274 |
+
|
| 1275 |
+
batch_size, seq_length = input_shape
|
| 1276 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 1277 |
+
|
| 1278 |
+
if attention_mask is None:
|
| 1279 |
+
attention_mask = torch.ones(((batch_size, seq_length)), device=device)
|
| 1280 |
+
|
| 1281 |
+
if token_type_ids is None:
|
| 1282 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 1283 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 1284 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 1285 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 1286 |
+
else:
|
| 1287 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 1288 |
+
|
| 1289 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 1290 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 1291 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 1292 |
+
|
| 1293 |
+
# Prepare head mask if needed
|
| 1294 |
+
# 1.0 in head_mask indicate we keep the head
|
| 1295 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 1296 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 1297 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 1298 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 1299 |
+
|
| 1300 |
+
embedding_output = self.embeddings(
|
| 1301 |
+
input_ids=input_ids,
|
| 1302 |
+
position_ids=position_ids,
|
| 1303 |
+
token_type_ids=token_type_ids,
|
| 1304 |
+
inputs_embeds=inputs_embeds,
|
| 1305 |
+
)
|
| 1306 |
+
encoder_outputs = self.encoder(
|
| 1307 |
+
embedding_output,
|
| 1308 |
+
attention_mask=extended_attention_mask,
|
| 1309 |
+
head_mask=head_mask,
|
| 1310 |
+
output_attentions=output_attentions,
|
| 1311 |
+
output_hidden_states=output_hidden_states,
|
| 1312 |
+
return_dict=return_dict,
|
| 1313 |
+
)
|
| 1314 |
+
sequence_output = encoder_outputs[0]
|
| 1315 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 1316 |
+
|
| 1317 |
+
if not return_dict:
|
| 1318 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 1319 |
+
|
| 1320 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
| 1321 |
+
last_hidden_state=sequence_output,
|
| 1322 |
+
pooler_output=pooled_output,
|
| 1323 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1324 |
+
attentions=encoder_outputs.attentions,
|
| 1325 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 1326 |
+
)
|
| 1327 |
+
|
| 1328 |
+
|
| 1329 |
+
@add_start_docstrings(
|
| 1330 |
+
"""The vision model from ALIGN without any head or projection on top.""",
|
| 1331 |
+
ALIGN_START_DOCSTRING,
|
| 1332 |
+
)
|
| 1333 |
+
class AlignVisionModel(AlignPreTrainedModel):
|
| 1334 |
+
config_class = AlignVisionConfig
|
| 1335 |
+
main_input_name = "pixel_values"
|
| 1336 |
+
|
| 1337 |
+
def __init__(self, config: AlignVisionConfig):
|
| 1338 |
+
super().__init__(config)
|
| 1339 |
+
self.config = config
|
| 1340 |
+
self.embeddings = AlignVisionEmbeddings(config)
|
| 1341 |
+
self.encoder = AlignVisionEncoder(config)
|
| 1342 |
+
|
| 1343 |
+
# Final pooling layer
|
| 1344 |
+
if config.pooling_type == "mean":
|
| 1345 |
+
self.pooler = nn.AvgPool2d(config.hidden_dim, ceil_mode=True)
|
| 1346 |
+
elif config.pooling_type == "max":
|
| 1347 |
+
self.pooler = nn.MaxPool2d(config.hidden_dim, ceil_mode=True)
|
| 1348 |
+
else:
|
| 1349 |
+
raise ValueError(f"config.pooling must be one of ['mean', 'max'] got {config.pooling}")
|
| 1350 |
+
|
| 1351 |
+
# Initialize weights and apply final processing
|
| 1352 |
+
self.post_init()
|
| 1353 |
+
|
| 1354 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1355 |
+
return self.vision_model.embeddings.convolution
|
| 1356 |
+
|
| 1357 |
+
@add_start_docstrings_to_model_forward(ALIGN_VISION_INPUTS_DOCSTRING)
|
| 1358 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPoolingAndNoAttention, config_class=AlignVisionConfig)
|
| 1359 |
+
def forward(
|
| 1360 |
+
self,
|
| 1361 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1362 |
+
output_hidden_states: Optional[bool] = None,
|
| 1363 |
+
return_dict: Optional[bool] = None,
|
| 1364 |
+
) -> Union[Tuple, BaseModelOutputWithPoolingAndNoAttention]:
|
| 1365 |
+
r"""
|
| 1366 |
+
Returns:
|
| 1367 |
+
|
| 1368 |
+
Examples:
|
| 1369 |
+
|
| 1370 |
+
```python
|
| 1371 |
+
>>> from PIL import Image
|
| 1372 |
+
>>> import requests
|
| 1373 |
+
>>> from transformers import AutoProcessor, AlignVisionModel
|
| 1374 |
+
|
| 1375 |
+
>>> model = AlignVisionModel.from_pretrained("kakaobrain/align-base")
|
| 1376 |
+
>>> processor = AutoProcessor.from_pretrained("kakaobrain/align-base")
|
| 1377 |
+
|
| 1378 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1379 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1380 |
+
|
| 1381 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1382 |
+
|
| 1383 |
+
>>> outputs = model(**inputs)
|
| 1384 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 1385 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
| 1386 |
+
```"""
|
| 1387 |
+
output_hidden_states = (
|
| 1388 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1389 |
+
)
|
| 1390 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1391 |
+
|
| 1392 |
+
if pixel_values is None:
|
| 1393 |
+
raise ValueError("You have to specify pixel_values")
|
| 1394 |
+
|
| 1395 |
+
embedding_output = self.embeddings(pixel_values)
|
| 1396 |
+
encoder_outputs = self.encoder(
|
| 1397 |
+
embedding_output,
|
| 1398 |
+
output_hidden_states=output_hidden_states,
|
| 1399 |
+
return_dict=return_dict,
|
| 1400 |
+
)
|
| 1401 |
+
# Apply pooling
|
| 1402 |
+
last_hidden_state = encoder_outputs[0]
|
| 1403 |
+
pooled_output = self.pooler(last_hidden_state)
|
| 1404 |
+
# Reshape (batch_size, projection_dim, 1 , 1) -> (batch_size, projection_dim)
|
| 1405 |
+
pooled_output = pooled_output.reshape(pooled_output.shape[:2])
|
| 1406 |
+
|
| 1407 |
+
if not return_dict:
|
| 1408 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 1409 |
+
|
| 1410 |
+
return BaseModelOutputWithPoolingAndNoAttention(
|
| 1411 |
+
last_hidden_state=last_hidden_state,
|
| 1412 |
+
pooler_output=pooled_output,
|
| 1413 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1414 |
+
)
|
| 1415 |
+
|
| 1416 |
+
|
| 1417 |
+
@add_start_docstrings(ALIGN_START_DOCSTRING)
|
| 1418 |
+
class AlignModel(AlignPreTrainedModel):
|
| 1419 |
+
config_class = AlignConfig
|
| 1420 |
+
|
| 1421 |
+
def __init__(self, config: AlignConfig):
|
| 1422 |
+
super().__init__(config)
|
| 1423 |
+
|
| 1424 |
+
if not isinstance(config.text_config, AlignTextConfig):
|
| 1425 |
+
raise ValueError(
|
| 1426 |
+
"config.text_config is expected to be of type AlignTextConfig but is of type"
|
| 1427 |
+
f" {type(config.text_config)}."
|
| 1428 |
+
)
|
| 1429 |
+
|
| 1430 |
+
if not isinstance(config.vision_config, AlignVisionConfig):
|
| 1431 |
+
raise ValueError(
|
| 1432 |
+
"config.vision_config is expected to be of type AlignVisionConfig but is of type"
|
| 1433 |
+
f" {type(config.vision_config)}."
|
| 1434 |
+
)
|
| 1435 |
+
|
| 1436 |
+
text_config = config.text_config
|
| 1437 |
+
vision_config = config.vision_config
|
| 1438 |
+
|
| 1439 |
+
self.projection_dim = config.projection_dim
|
| 1440 |
+
self.text_embed_dim = text_config.hidden_size
|
| 1441 |
+
|
| 1442 |
+
self.text_model = AlignTextModel(text_config)
|
| 1443 |
+
self.vision_model = AlignVisionModel(vision_config)
|
| 1444 |
+
|
| 1445 |
+
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim)
|
| 1446 |
+
self.temperature = nn.Parameter(torch.ones([]) * self.config.temperature_init_value)
|
| 1447 |
+
|
| 1448 |
+
# Initialize weights and apply final processing
|
| 1449 |
+
self.post_init()
|
| 1450 |
+
|
| 1451 |
+
@add_start_docstrings_to_model_forward(ALIGN_TEXT_INPUTS_DOCSTRING)
|
| 1452 |
+
def get_text_features(
|
| 1453 |
+
self,
|
| 1454 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1455 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1456 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1457 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1458 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1459 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1460 |
+
output_attentions: Optional[bool] = None,
|
| 1461 |
+
output_hidden_states: Optional[bool] = None,
|
| 1462 |
+
return_dict: Optional[bool] = None,
|
| 1463 |
+
) -> torch.FloatTensor:
|
| 1464 |
+
r"""
|
| 1465 |
+
Returns:
|
| 1466 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
| 1467 |
+
applying the projection layer to the pooled output of [`AlignTextModel`].
|
| 1468 |
+
|
| 1469 |
+
Examples:
|
| 1470 |
+
|
| 1471 |
+
```python
|
| 1472 |
+
>>> from transformers import AutoTokenizer, AlignModel
|
| 1473 |
+
|
| 1474 |
+
>>> model = AlignModel.from_pretrained("kakaobrain/align-base")
|
| 1475 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("kakaobrain/align-base")
|
| 1476 |
+
|
| 1477 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
| 1478 |
+
>>> text_features = model.get_text_features(**inputs)
|
| 1479 |
+
```"""
|
| 1480 |
+
# Use ALIGN model's config for some fields (if specified) instead of those of vision & text components.
|
| 1481 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1482 |
+
output_hidden_states = (
|
| 1483 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1484 |
+
)
|
| 1485 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1486 |
+
|
| 1487 |
+
text_outputs = self.text_model(
|
| 1488 |
+
input_ids=input_ids,
|
| 1489 |
+
attention_mask=attention_mask,
|
| 1490 |
+
token_type_ids=token_type_ids,
|
| 1491 |
+
position_ids=position_ids,
|
| 1492 |
+
head_mask=head_mask,
|
| 1493 |
+
inputs_embeds=inputs_embeds,
|
| 1494 |
+
output_attentions=output_attentions,
|
| 1495 |
+
output_hidden_states=output_hidden_states,
|
| 1496 |
+
return_dict=return_dict,
|
| 1497 |
+
)
|
| 1498 |
+
|
| 1499 |
+
last_hidden_state = text_outputs[0][:, 0, :]
|
| 1500 |
+
text_features = self.text_projection(last_hidden_state)
|
| 1501 |
+
|
| 1502 |
+
return text_features
|
| 1503 |
+
|
| 1504 |
+
@add_start_docstrings_to_model_forward(ALIGN_VISION_INPUTS_DOCSTRING)
|
| 1505 |
+
def get_image_features(
|
| 1506 |
+
self,
|
| 1507 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1508 |
+
output_hidden_states: Optional[bool] = None,
|
| 1509 |
+
return_dict: Optional[bool] = None,
|
| 1510 |
+
) -> torch.FloatTensor:
|
| 1511 |
+
r"""
|
| 1512 |
+
Returns:
|
| 1513 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
| 1514 |
+
applying the projection layer to the pooled output of [`AlignVisionModel`].
|
| 1515 |
+
|
| 1516 |
+
Examples:
|
| 1517 |
+
|
| 1518 |
+
```python
|
| 1519 |
+
>>> from PIL import Image
|
| 1520 |
+
>>> import requests
|
| 1521 |
+
>>> from transformers import AutoProcessor, AlignModel
|
| 1522 |
+
|
| 1523 |
+
>>> model = AlignModel.from_pretrained("kakaobrain/align-base")
|
| 1524 |
+
>>> processor = AutoProcessor.from_pretrained("kakaobrain/align-base")
|
| 1525 |
+
|
| 1526 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1527 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1528 |
+
|
| 1529 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1530 |
+
|
| 1531 |
+
>>> image_features = model.get_image_features(**inputs)
|
| 1532 |
+
```"""
|
| 1533 |
+
# Use ALIGN model's config for some fields (if specified) instead of those of vision & text components.
|
| 1534 |
+
output_hidden_states = (
|
| 1535 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1536 |
+
)
|
| 1537 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1538 |
+
|
| 1539 |
+
vision_outputs = self.vision_model(
|
| 1540 |
+
pixel_values=pixel_values,
|
| 1541 |
+
output_hidden_states=output_hidden_states,
|
| 1542 |
+
return_dict=return_dict,
|
| 1543 |
+
)
|
| 1544 |
+
|
| 1545 |
+
image_features = vision_outputs[1] # pooled_output
|
| 1546 |
+
|
| 1547 |
+
return image_features
|
| 1548 |
+
|
| 1549 |
+
@add_start_docstrings_to_model_forward(ALIGN_INPUTS_DOCSTRING)
|
| 1550 |
+
@replace_return_docstrings(output_type=AlignOutput, config_class=AlignConfig)
|
| 1551 |
+
def forward(
|
| 1552 |
+
self,
|
| 1553 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1554 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1555 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1556 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1557 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1558 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1559 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1560 |
+
return_loss: Optional[bool] = None,
|
| 1561 |
+
output_attentions: Optional[bool] = None,
|
| 1562 |
+
output_hidden_states: Optional[bool] = None,
|
| 1563 |
+
return_dict: Optional[bool] = None,
|
| 1564 |
+
) -> Union[Tuple, AlignOutput]:
|
| 1565 |
+
r"""
|
| 1566 |
+
Returns:
|
| 1567 |
+
|
| 1568 |
+
Examples:
|
| 1569 |
+
|
| 1570 |
+
```python
|
| 1571 |
+
>>> from PIL import Image
|
| 1572 |
+
>>> import requests
|
| 1573 |
+
>>> from transformers import AutoProcessor, AlignModel
|
| 1574 |
+
|
| 1575 |
+
>>> model = AlignModel.from_pretrained("kakaobrain/align-base")
|
| 1576 |
+
>>> processor = AutoProcessor.from_pretrained("kakaobrain/align-base")
|
| 1577 |
+
|
| 1578 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1579 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1580 |
+
|
| 1581 |
+
>>> inputs = processor(
|
| 1582 |
+
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
|
| 1583 |
+
... )
|
| 1584 |
+
|
| 1585 |
+
>>> outputs = model(**inputs)
|
| 1586 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
| 1587 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
| 1588 |
+
```"""
|
| 1589 |
+
# Use ALIGN model's config for some fields (if specified) instead of those of vision & text components.
|
| 1590 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1591 |
+
output_hidden_states = (
|
| 1592 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1593 |
+
)
|
| 1594 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1595 |
+
|
| 1596 |
+
vision_outputs = self.vision_model(
|
| 1597 |
+
pixel_values=pixel_values,
|
| 1598 |
+
output_hidden_states=output_hidden_states,
|
| 1599 |
+
return_dict=return_dict,
|
| 1600 |
+
)
|
| 1601 |
+
|
| 1602 |
+
text_outputs = self.text_model(
|
| 1603 |
+
input_ids=input_ids,
|
| 1604 |
+
attention_mask=attention_mask,
|
| 1605 |
+
token_type_ids=token_type_ids,
|
| 1606 |
+
position_ids=position_ids,
|
| 1607 |
+
head_mask=head_mask,
|
| 1608 |
+
inputs_embeds=inputs_embeds,
|
| 1609 |
+
output_attentions=output_attentions,
|
| 1610 |
+
output_hidden_states=output_hidden_states,
|
| 1611 |
+
return_dict=return_dict,
|
| 1612 |
+
)
|
| 1613 |
+
|
| 1614 |
+
image_embeds = vision_outputs[1]
|
| 1615 |
+
text_embeds = text_outputs[0][:, 0, :]
|
| 1616 |
+
text_embeds = self.text_projection(text_embeds)
|
| 1617 |
+
|
| 1618 |
+
# normalized features
|
| 1619 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1620 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1621 |
+
|
| 1622 |
+
# cosine similarity as logits
|
| 1623 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) / self.temperature
|
| 1624 |
+
logits_per_image = logits_per_text.t()
|
| 1625 |
+
|
| 1626 |
+
loss = None
|
| 1627 |
+
if return_loss:
|
| 1628 |
+
loss = align_loss(logits_per_text)
|
| 1629 |
+
|
| 1630 |
+
if not return_dict:
|
| 1631 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
| 1632 |
+
return ((loss,) + output) if loss is not None else output
|
| 1633 |
+
|
| 1634 |
+
return AlignOutput(
|
| 1635 |
+
loss=loss,
|
| 1636 |
+
logits_per_image=logits_per_image,
|
| 1637 |
+
logits_per_text=logits_per_text,
|
| 1638 |
+
text_embeds=text_embeds,
|
| 1639 |
+
image_embeds=image_embeds,
|
| 1640 |
+
text_model_output=text_outputs,
|
| 1641 |
+
vision_model_output=vision_outputs,
|
| 1642 |
+
)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/align/processing_align.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Image/Text processor class for ALIGN
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
from ...processing_utils import ProcessorMixin
|
| 21 |
+
from ...tokenization_utils_base import BatchEncoding
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class AlignProcessor(ProcessorMixin):
|
| 25 |
+
r"""
|
| 26 |
+
Constructs an ALIGN processor which wraps [`EfficientNetImageProcessor`] and
|
| 27 |
+
[`BertTokenizer`]/[`BertTokenizerFast`] into a single processor that interits both the image processor and
|
| 28 |
+
tokenizer functionalities. See the [`~AlignProcessor.__call__`] and [`~OwlViTProcessor.decode`] for more
|
| 29 |
+
information.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
image_processor ([`EfficientNetImageProcessor`]):
|
| 33 |
+
The image processor is a required input.
|
| 34 |
+
tokenizer ([`BertTokenizer`, `BertTokenizerFast`]):
|
| 35 |
+
The tokenizer is a required input.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
attributes = ["image_processor", "tokenizer"]
|
| 39 |
+
image_processor_class = "EfficientNetImageProcessor"
|
| 40 |
+
tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
|
| 41 |
+
|
| 42 |
+
def __init__(self, image_processor, tokenizer):
|
| 43 |
+
super().__init__(image_processor, tokenizer)
|
| 44 |
+
|
| 45 |
+
def __call__(self, text=None, images=None, padding="max_length", max_length=64, return_tensors=None, **kwargs):
|
| 46 |
+
"""
|
| 47 |
+
Main method to prepare text(s) and image(s) to be fed as input to the model. This method forwards the `text`
|
| 48 |
+
and `kwargs` arguments to BertTokenizerFast's [`~BertTokenizerFast.__call__`] if `text` is not `None` to encode
|
| 49 |
+
the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to
|
| 50 |
+
EfficientNetImageProcessor's [`~EfficientNetImageProcessor.__call__`] if `images` is not `None`. Please refer
|
| 51 |
+
to the doctsring of the above two methods for more information.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
text (`str`, `List[str]`):
|
| 55 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 56 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 57 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 58 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
| 59 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 60 |
+
tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
|
| 61 |
+
number of channels, H and W are image height and width.
|
| 62 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `max_length`):
|
| 63 |
+
Activates and controls padding for tokenization of input text. Choose between [`True` or `'longest'`,
|
| 64 |
+
`'max_length'`, `False` or `'do_not_pad'`]
|
| 65 |
+
max_length (`int`, *optional*, defaults to `max_length`):
|
| 66 |
+
Maximum padding value to use to pad the input text during tokenization.
|
| 67 |
+
|
| 68 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 69 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 70 |
+
|
| 71 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 72 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 73 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 74 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
[`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
|
| 78 |
+
|
| 79 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 80 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 81 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 82 |
+
`None`).
|
| 83 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 84 |
+
"""
|
| 85 |
+
if text is None and images is None:
|
| 86 |
+
raise ValueError("You have to specify either text or images. Both cannot be none.")
|
| 87 |
+
|
| 88 |
+
if text is not None:
|
| 89 |
+
encoding = self.tokenizer(
|
| 90 |
+
text, padding=padding, max_length=max_length, return_tensors=return_tensors, **kwargs
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
if images is not None:
|
| 94 |
+
image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs)
|
| 95 |
+
|
| 96 |
+
if text is not None and images is not None:
|
| 97 |
+
encoding["pixel_values"] = image_features.pixel_values
|
| 98 |
+
return encoding
|
| 99 |
+
elif text is not None:
|
| 100 |
+
return encoding
|
| 101 |
+
else:
|
| 102 |
+
return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
|
| 103 |
+
|
| 104 |
+
def batch_decode(self, *args, **kwargs):
|
| 105 |
+
"""
|
| 106 |
+
This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 107 |
+
refer to the docstring of this method for more information.
|
| 108 |
+
"""
|
| 109 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 110 |
+
|
| 111 |
+
def decode(self, *args, **kwargs):
|
| 112 |
+
"""
|
| 113 |
+
This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
| 114 |
+
the docstring of this method for more information.
|
| 115 |
+
"""
|
| 116 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def model_input_names(self):
|
| 120 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 121 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 122 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/altclip/__init__.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
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_altclip": [
|
| 21 |
+
"ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
| 22 |
+
"AltCLIPConfig",
|
| 23 |
+
"AltCLIPTextConfig",
|
| 24 |
+
"AltCLIPVisionConfig",
|
| 25 |
+
],
|
| 26 |
+
"processing_altclip": ["AltCLIPProcessor"],
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
if not is_torch_available():
|
| 31 |
+
raise OptionalDependencyNotAvailable()
|
| 32 |
+
except OptionalDependencyNotAvailable:
|
| 33 |
+
pass
|
| 34 |
+
else:
|
| 35 |
+
_import_structure["modeling_altclip"] = [
|
| 36 |
+
"ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 37 |
+
"AltCLIPPreTrainedModel",
|
| 38 |
+
"AltCLIPModel",
|
| 39 |
+
"AltCLIPTextModel",
|
| 40 |
+
"AltCLIPVisionModel",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if TYPE_CHECKING:
|
| 45 |
+
from .configuration_altclip import (
|
| 46 |
+
ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
| 47 |
+
AltCLIPConfig,
|
| 48 |
+
AltCLIPTextConfig,
|
| 49 |
+
AltCLIPVisionConfig,
|
| 50 |
+
)
|
| 51 |
+
from .processing_altclip import AltCLIPProcessor
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
if not is_torch_available():
|
| 55 |
+
raise OptionalDependencyNotAvailable()
|
| 56 |
+
except OptionalDependencyNotAvailable:
|
| 57 |
+
pass
|
| 58 |
+
else:
|
| 59 |
+
from .modeling_altclip import (
|
| 60 |
+
ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 61 |
+
AltCLIPModel,
|
| 62 |
+
AltCLIPPreTrainedModel,
|
| 63 |
+
AltCLIPTextModel,
|
| 64 |
+
AltCLIPVisionModel,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
else:
|
| 69 |
+
import sys
|
| 70 |
+
|
| 71 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/altclip/configuration_altclip.py
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 WenXiang ZhongzhiCheng LedellWu LiuGuang BoWenZhang 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 |
+
""" AltCLIP model configuration"""
|
| 16 |
+
import copy
|
| 17 |
+
import os
|
| 18 |
+
from typing import Union
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PretrainedConfig
|
| 21 |
+
from ...utils import logging
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 27 |
+
"BAAI/AltCLIP": "https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json",
|
| 28 |
+
# See all AltCLIP models at https://huggingface.co/models?filter=altclip
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class AltCLIPTextConfig(PretrainedConfig):
|
| 33 |
+
r"""
|
| 34 |
+
This is the configuration class to store the configuration of a [`AltCLIPTextModel`]. It is used to instantiate a
|
| 35 |
+
AltCLIP text model according to the specified arguments, defining the model architecture. Instantiating a
|
| 36 |
+
configuration with the defaults will yield a similar configuration to that of the AltCLIP
|
| 37 |
+
[BAAI/AltCLIP](https://huggingface.co/BAAI/AltCLIP) architecture.
|
| 38 |
+
|
| 39 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 40 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
vocab_size (`int`, *optional*, defaults to 250002):
|
| 45 |
+
Vocabulary size of the AltCLIP model. Defines the number of different tokens that can be represented by the
|
| 46 |
+
`inputs_ids` passed when calling [`AltCLIPTextModel`].
|
| 47 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
| 48 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 49 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
| 50 |
+
Number of hidden layers in the Transformer encoder.
|
| 51 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 52 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 53 |
+
intermediate_size (`int`, *optional*, defaults to 4096):
|
| 54 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 55 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
| 56 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 57 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 58 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 59 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 60 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 61 |
+
The dropout ratio for the attention probabilities.
|
| 62 |
+
max_position_embeddings (`int`, *optional*, defaults to 514):
|
| 63 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 64 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 65 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 66 |
+
The vocabulary size of the `token_type_ids` passed when calling [`AltCLIPTextModel`]
|
| 67 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 68 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 69 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
| 70 |
+
The epsilon used by the layer normalization layers.
|
| 71 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 72 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 73 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 74 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 75 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 76 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 77 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 78 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 79 |
+
relevant if `config.is_decoder=True`.
|
| 80 |
+
project_dim (`int`, *optional*, defaults to 768):
|
| 81 |
+
The dimentions of the teacher model before the mapping layer.
|
| 82 |
+
|
| 83 |
+
Examples:
|
| 84 |
+
|
| 85 |
+
```python
|
| 86 |
+
>>> from transformers import AltCLIPTextModel, AltCLIPTextConfig
|
| 87 |
+
|
| 88 |
+
>>> # Initializing a AltCLIPTextConfig with BAAI/AltCLIP style configuration
|
| 89 |
+
>>> configuration = AltCLIPTextConfig()
|
| 90 |
+
|
| 91 |
+
>>> # Initializing a AltCLIPTextModel (with random weights) from the BAAI/AltCLIP style configuration
|
| 92 |
+
>>> model = AltCLIPTextModel(configuration)
|
| 93 |
+
|
| 94 |
+
>>> # Accessing the model configuration
|
| 95 |
+
>>> configuration = model.config
|
| 96 |
+
```"""
|
| 97 |
+
model_type = "altclip_text_model"
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
vocab_size=250002,
|
| 102 |
+
hidden_size=1024,
|
| 103 |
+
num_hidden_layers=24,
|
| 104 |
+
num_attention_heads=16,
|
| 105 |
+
intermediate_size=4096,
|
| 106 |
+
hidden_act="gelu",
|
| 107 |
+
hidden_dropout_prob=0.1,
|
| 108 |
+
attention_probs_dropout_prob=0.1,
|
| 109 |
+
max_position_embeddings=514,
|
| 110 |
+
type_vocab_size=1,
|
| 111 |
+
initializer_range=0.02,
|
| 112 |
+
initializer_factor=0.02,
|
| 113 |
+
layer_norm_eps=1e-05,
|
| 114 |
+
pad_token_id=1,
|
| 115 |
+
bos_token_id=0,
|
| 116 |
+
eos_token_id=2,
|
| 117 |
+
position_embedding_type="absolute",
|
| 118 |
+
use_cache=True,
|
| 119 |
+
project_dim=768,
|
| 120 |
+
**kwargs,
|
| 121 |
+
):
|
| 122 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 123 |
+
|
| 124 |
+
self.vocab_size = vocab_size
|
| 125 |
+
self.hidden_size = hidden_size
|
| 126 |
+
self.num_hidden_layers = num_hidden_layers
|
| 127 |
+
self.num_attention_heads = num_attention_heads
|
| 128 |
+
self.hidden_act = hidden_act
|
| 129 |
+
self.intermediate_size = intermediate_size
|
| 130 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 131 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 132 |
+
self.max_position_embeddings = max_position_embeddings
|
| 133 |
+
self.type_vocab_size = type_vocab_size
|
| 134 |
+
self.initializer_range = initializer_range
|
| 135 |
+
self.initializer_factor = initializer_factor
|
| 136 |
+
self.layer_norm_eps = layer_norm_eps
|
| 137 |
+
self.position_embedding_type = position_embedding_type
|
| 138 |
+
self.use_cache = use_cache
|
| 139 |
+
self.project_dim = project_dim
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class AltCLIPVisionConfig(PretrainedConfig):
|
| 143 |
+
r"""
|
| 144 |
+
This is the configuration class to store the configuration of a [`AltCLIPModel`]. It is used to instantiate an
|
| 145 |
+
AltCLIP model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 146 |
+
with the defaults will yield a similar configuration to that of the AltCLIP
|
| 147 |
+
[BAAI/AltCLIP](https://huggingface.co/BAAI/AltCLIP) architecture.
|
| 148 |
+
|
| 149 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 150 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
Args:
|
| 154 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 155 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 156 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 157 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 158 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 159 |
+
Number of hidden layers in the Transformer encoder.
|
| 160 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 161 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 162 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 163 |
+
The size (resolution) of each image.
|
| 164 |
+
patch_size (`int`, *optional*, defaults to 32):
|
| 165 |
+
The size (resolution) of each patch.
|
| 166 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
| 167 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 168 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
|
| 169 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
| 170 |
+
The epsilon used by the layer normalization layers.
|
| 171 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 172 |
+
The dropout ratio for the attention probabilities.
|
| 173 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 174 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 175 |
+
initializer_factor (`float``, *optional*, defaults to 1):
|
| 176 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
| 177 |
+
testing).
|
| 178 |
+
|
| 179 |
+
Example:
|
| 180 |
+
|
| 181 |
+
```python
|
| 182 |
+
>>> from transformers import AltCLIPVisionConfig, AltCLIPVisionModel
|
| 183 |
+
|
| 184 |
+
>>> # Initializing a AltCLIPVisionConfig with BAAI/AltCLIP style configuration
|
| 185 |
+
>>> configuration = AltCLIPVisionConfig()
|
| 186 |
+
|
| 187 |
+
>>> # Initializing a AltCLIPVisionModel (with random weights) from the BAAI/AltCLIP style configuration
|
| 188 |
+
>>> model = AltCLIPVisionModel(configuration)
|
| 189 |
+
|
| 190 |
+
>>> # Accessing the model configuration
|
| 191 |
+
>>> configuration = model.config
|
| 192 |
+
```"""
|
| 193 |
+
|
| 194 |
+
model_type = "altclip_vision_model"
|
| 195 |
+
|
| 196 |
+
def __init__(
|
| 197 |
+
self,
|
| 198 |
+
hidden_size=768,
|
| 199 |
+
intermediate_size=3072,
|
| 200 |
+
projection_dim=512,
|
| 201 |
+
num_hidden_layers=12,
|
| 202 |
+
num_attention_heads=12,
|
| 203 |
+
num_channels=3,
|
| 204 |
+
image_size=224,
|
| 205 |
+
patch_size=32,
|
| 206 |
+
hidden_act="quick_gelu",
|
| 207 |
+
layer_norm_eps=1e-5,
|
| 208 |
+
attention_dropout=0.0,
|
| 209 |
+
initializer_range=0.02,
|
| 210 |
+
initializer_factor=1.0,
|
| 211 |
+
**kwargs,
|
| 212 |
+
):
|
| 213 |
+
super().__init__(**kwargs)
|
| 214 |
+
|
| 215 |
+
self.hidden_size = hidden_size
|
| 216 |
+
self.intermediate_size = intermediate_size
|
| 217 |
+
self.projection_dim = projection_dim
|
| 218 |
+
self.num_hidden_layers = num_hidden_layers
|
| 219 |
+
self.num_attention_heads = num_attention_heads
|
| 220 |
+
self.num_channels = num_channels
|
| 221 |
+
self.patch_size = patch_size
|
| 222 |
+
self.image_size = image_size
|
| 223 |
+
self.initializer_range = initializer_range
|
| 224 |
+
self.initializer_factor = initializer_factor
|
| 225 |
+
self.attention_dropout = attention_dropout
|
| 226 |
+
self.layer_norm_eps = layer_norm_eps
|
| 227 |
+
self.hidden_act = hidden_act
|
| 228 |
+
|
| 229 |
+
@classmethod
|
| 230 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
| 231 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 232 |
+
|
| 233 |
+
# get the vision config dict if we are loading from AltCLIPConfig
|
| 234 |
+
if config_dict.get("model_type") == "altclip":
|
| 235 |
+
config_dict = config_dict["vision_config"]
|
| 236 |
+
|
| 237 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
| 238 |
+
logger.warning(
|
| 239 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
| 240 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
return cls.from_dict(config_dict, **kwargs)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class AltCLIPConfig(PretrainedConfig):
|
| 247 |
+
r"""
|
| 248 |
+
This is the configuration class to store the configuration of a [`AltCLIPModel`]. It is used to instantiate an
|
| 249 |
+
AltCLIP model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 250 |
+
with the defaults will yield a similar configuration to that of the AltCLIP
|
| 251 |
+
[BAAI/AltCLIP](https://huggingface.co/BAAI/AltCLIP) architecture.
|
| 252 |
+
|
| 253 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 254 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
text_config (`dict`, *optional*):
|
| 258 |
+
Dictionary of configuration options used to initialize [`AltCLIPTextConfig`].
|
| 259 |
+
vision_config (`dict`, *optional*):
|
| 260 |
+
Dictionary of configuration options used to initialize [`AltCLIPVisionConfig`].
|
| 261 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
| 262 |
+
Dimentionality of text and vision projection layers.
|
| 263 |
+
logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
|
| 264 |
+
The inital value of the *logit_scale* paramter. Default is used as per the original CLIP implementation.
|
| 265 |
+
kwargs (*optional*):
|
| 266 |
+
Dictionary of keyword arguments.
|
| 267 |
+
|
| 268 |
+
Example:
|
| 269 |
+
|
| 270 |
+
```python
|
| 271 |
+
>>> from transformers import AltCLIPConfig, AltCLIPModel
|
| 272 |
+
|
| 273 |
+
>>> # Initializing a AltCLIPConfig with BAAI/AltCLIP style configuration
|
| 274 |
+
>>> configuration = AltCLIPConfig()
|
| 275 |
+
|
| 276 |
+
>>> # Initializing a AltCLIPModel (with random weights) from the BAAI/AltCLIP style configuration
|
| 277 |
+
>>> model = AltCLIPModel(configuration)
|
| 278 |
+
|
| 279 |
+
>>> # Accessing the model configuration
|
| 280 |
+
>>> configuration = model.config
|
| 281 |
+
|
| 282 |
+
>>> # We can also initialize a AltCLIPConfig from a AltCLIPTextConfig and a AltCLIPVisionConfig
|
| 283 |
+
|
| 284 |
+
>>> # Initializing a AltCLIPText and AltCLIPVision configuration
|
| 285 |
+
>>> config_text = AltCLIPTextConfig()
|
| 286 |
+
>>> config_vision = AltCLIPVisionConfig()
|
| 287 |
+
|
| 288 |
+
>>> config = AltCLIPConfig.from_text_vision_configs(config_text, config_vision)
|
| 289 |
+
```"""
|
| 290 |
+
|
| 291 |
+
model_type = "altclip"
|
| 292 |
+
is_composition = True
|
| 293 |
+
|
| 294 |
+
def __init__(
|
| 295 |
+
self, text_config=None, vision_config=None, projection_dim=768, logit_scale_init_value=2.6592, **kwargs
|
| 296 |
+
):
|
| 297 |
+
# If `_config_dict` exist, we use them for the backward compatibility.
|
| 298 |
+
# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
|
| 299 |
+
# of confusion!).
|
| 300 |
+
text_config_dict = kwargs.pop("text_config_dict", None)
|
| 301 |
+
vision_config_dict = kwargs.pop("vision_config_dict", None)
|
| 302 |
+
|
| 303 |
+
super().__init__(**kwargs)
|
| 304 |
+
|
| 305 |
+
# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
|
| 306 |
+
# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
|
| 307 |
+
# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
|
| 308 |
+
if text_config_dict is not None:
|
| 309 |
+
if text_config is None:
|
| 310 |
+
text_config = {}
|
| 311 |
+
|
| 312 |
+
# This is the complete result when using `text_config_dict`.
|
| 313 |
+
_text_config_dict = AltCLIPTextConfig(**text_config_dict).to_dict()
|
| 314 |
+
|
| 315 |
+
# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
|
| 316 |
+
for key, value in _text_config_dict.items():
|
| 317 |
+
if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
|
| 318 |
+
# If specified in `text_config_dict`
|
| 319 |
+
if key in text_config_dict:
|
| 320 |
+
message = (
|
| 321 |
+
f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
|
| 322 |
+
f'The value `text_config_dict["{key}"]` will be used instead.'
|
| 323 |
+
)
|
| 324 |
+
# If inferred from default argument values (just to be super careful)
|
| 325 |
+
else:
|
| 326 |
+
message = (
|
| 327 |
+
f"`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The "
|
| 328 |
+
f'value `text_config["{key}"]` will be overriden.'
|
| 329 |
+
)
|
| 330 |
+
logger.warning(message)
|
| 331 |
+
|
| 332 |
+
# Update all values in `text_config` with the ones in `_text_config_dict`.
|
| 333 |
+
text_config.update(_text_config_dict)
|
| 334 |
+
|
| 335 |
+
if vision_config_dict is not None:
|
| 336 |
+
if vision_config is None:
|
| 337 |
+
vision_config = {}
|
| 338 |
+
|
| 339 |
+
# This is the complete result when using `vision_config_dict`.
|
| 340 |
+
_vision_config_dict = AltCLIPVisionConfig(**vision_config_dict).to_dict()
|
| 341 |
+
# convert keys to string instead of integer
|
| 342 |
+
if "id2label" in _vision_config_dict:
|
| 343 |
+
_vision_config_dict["id2label"] = {
|
| 344 |
+
str(key): value for key, value in _vision_config_dict["id2label"].items()
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
|
| 348 |
+
for key, value in _vision_config_dict.items():
|
| 349 |
+
if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
|
| 350 |
+
# If specified in `vision_config_dict`
|
| 351 |
+
if key in vision_config_dict:
|
| 352 |
+
message = (
|
| 353 |
+
f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
|
| 354 |
+
f'values. The value `vision_config_dict["{key}"]` will be used instead.'
|
| 355 |
+
)
|
| 356 |
+
# If inferred from default argument values (just to be super careful)
|
| 357 |
+
else:
|
| 358 |
+
message = (
|
| 359 |
+
f"`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. "
|
| 360 |
+
f'The value `vision_config["{key}"]` will be overriden.'
|
| 361 |
+
)
|
| 362 |
+
logger.warning(message)
|
| 363 |
+
|
| 364 |
+
# Update all values in `vision_config` with the ones in `_vision_config_dict`.
|
| 365 |
+
vision_config.update(_vision_config_dict)
|
| 366 |
+
|
| 367 |
+
if text_config is None:
|
| 368 |
+
text_config = {}
|
| 369 |
+
logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.")
|
| 370 |
+
|
| 371 |
+
if vision_config is None:
|
| 372 |
+
vision_config = {}
|
| 373 |
+
logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.")
|
| 374 |
+
|
| 375 |
+
self.text_config = AltCLIPTextConfig(**text_config)
|
| 376 |
+
self.vision_config = AltCLIPVisionConfig(**vision_config)
|
| 377 |
+
|
| 378 |
+
self.projection_dim = projection_dim
|
| 379 |
+
self.logit_scale_init_value = logit_scale_init_value
|
| 380 |
+
self.initializer_factor = 1.0
|
| 381 |
+
|
| 382 |
+
@classmethod
|
| 383 |
+
def from_text_vision_configs(cls, text_config: AltCLIPTextConfig, vision_config: AltCLIPVisionConfig, **kwargs):
|
| 384 |
+
r"""
|
| 385 |
+
Instantiate a [`AltCLIPConfig`] (or a derived class) from altclip text model configuration and altclip vision
|
| 386 |
+
model configuration.
|
| 387 |
+
|
| 388 |
+
Returns:
|
| 389 |
+
[`AltCLIPConfig`]: An instance of a configuration object
|
| 390 |
+
"""
|
| 391 |
+
|
| 392 |
+
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
|
| 393 |
+
|
| 394 |
+
def to_dict(self):
|
| 395 |
+
"""
|
| 396 |
+
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
|
| 397 |
+
|
| 398 |
+
Returns:
|
| 399 |
+
`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
|
| 400 |
+
"""
|
| 401 |
+
output = copy.deepcopy(self.__dict__)
|
| 402 |
+
output["text_config"] = self.text_config.to_dict()
|
| 403 |
+
output["vision_config"] = self.vision_config.to_dict()
|
| 404 |
+
output["model_type"] = self.__class__.model_type
|
| 405 |
+
return output
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/altclip/modeling_altclip.py
ADDED
|
@@ -0,0 +1,1712 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The BAAI Teams 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 AltCLIP model."""
|
| 16 |
+
import math
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from typing import Any, List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...modeling_outputs import (
|
| 26 |
+
BaseModelOutput,
|
| 27 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 28 |
+
BaseModelOutputWithPooling,
|
| 29 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 30 |
+
BaseModelOutputWithPoolingAndProjection,
|
| 31 |
+
)
|
| 32 |
+
from ...modeling_utils import PreTrainedModel
|
| 33 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 34 |
+
from ...utils import ModelOutput, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
|
| 35 |
+
from .configuration_altclip import AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
logger = logging.get_logger(__name__)
|
| 39 |
+
|
| 40 |
+
_CHECKPOINT_FOR_DOC = "BAAI/AltCLIP"
|
| 41 |
+
_CONFIG_FOR_DOC = "AltCLIPConfig"
|
| 42 |
+
|
| 43 |
+
ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 44 |
+
"BAAI/AltCLIP",
|
| 45 |
+
# See all AltCLIP models at https://huggingface.co/models?filter=altclip
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
ALTCLIP_START_DOCSTRING = r"""
|
| 50 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 51 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 52 |
+
etc.)
|
| 53 |
+
|
| 54 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 55 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 56 |
+
and behavior.
|
| 57 |
+
|
| 58 |
+
Parameters:
|
| 59 |
+
config ([`CLIPConfig`]): Model configuration class with all the parameters of the model.
|
| 60 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 61 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
ALTCLIP_TEXT_INPUTS_DOCSTRING = r"""
|
| 65 |
+
Args:
|
| 66 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 67 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 68 |
+
it.
|
| 69 |
+
|
| 70 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 71 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 72 |
+
|
| 73 |
+
[What are input IDs?](../glossary#input-ids)
|
| 74 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 75 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 76 |
+
|
| 77 |
+
- 1 for tokens that are **not masked**,
|
| 78 |
+
- 0 for tokens that are **masked**.
|
| 79 |
+
|
| 80 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 81 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 82 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 83 |
+
config.max_position_embeddings - 1]`.
|
| 84 |
+
|
| 85 |
+
[What are position IDs?](../glossary#position-ids)
|
| 86 |
+
output_attentions (`bool`, *optional*):
|
| 87 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 88 |
+
tensors for more detail.
|
| 89 |
+
output_hidden_states (`bool`, *optional*):
|
| 90 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 91 |
+
more detail.
|
| 92 |
+
return_dict (`bool`, *optional*):
|
| 93 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
ALTCLIP_VISION_INPUTS_DOCSTRING = r"""
|
| 97 |
+
Args:
|
| 98 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 99 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 100 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
| 101 |
+
output_attentions (`bool`, *optional*):
|
| 102 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 103 |
+
tensors for more detail.
|
| 104 |
+
output_hidden_states (`bool`, *optional*):
|
| 105 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 106 |
+
more detail.
|
| 107 |
+
return_dict (`bool`, *optional*):
|
| 108 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
ALTCLIP_INPUTS_DOCSTRING = r"""
|
| 112 |
+
Args:
|
| 113 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 114 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 115 |
+
it.
|
| 116 |
+
|
| 117 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 118 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 119 |
+
|
| 120 |
+
[What are input IDs?](../glossary#input-ids)
|
| 121 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 122 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 123 |
+
|
| 124 |
+
- 1 for tokens that are **not masked**,
|
| 125 |
+
- 0 for tokens that are **masked**.
|
| 126 |
+
|
| 127 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 128 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 129 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 130 |
+
config.max_position_embeddings - 1]`.
|
| 131 |
+
|
| 132 |
+
[What are position IDs?](../glossary#position-ids)
|
| 133 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 134 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 135 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
| 136 |
+
return_loss (`bool`, *optional*):
|
| 137 |
+
Whether or not to return the contrastive loss.
|
| 138 |
+
output_attentions (`bool`, *optional*):
|
| 139 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 140 |
+
tensors for more detail.
|
| 141 |
+
output_hidden_states (`bool`, *optional*):
|
| 142 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 143 |
+
more detail.
|
| 144 |
+
return_dict (`bool`, *optional*):
|
| 145 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# contrastive loss function, adapted from
|
| 150 |
+
# https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
|
| 151 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
| 152 |
+
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def clip_loss(similarity: torch.Tensor) -> torch.Tensor:
|
| 156 |
+
caption_loss = contrastive_loss(similarity)
|
| 157 |
+
image_loss = contrastive_loss(similarity.t())
|
| 158 |
+
return (caption_loss + image_loss) / 2.0
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@dataclass
|
| 162 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP
|
| 163 |
+
class AltCLIPOutput(ModelOutput):
|
| 164 |
+
"""
|
| 165 |
+
Args:
|
| 166 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 167 |
+
Contrastive loss for image-text similarity.
|
| 168 |
+
logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
| 169 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
| 170 |
+
similarity scores.
|
| 171 |
+
logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
| 172 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
| 173 |
+
similarity scores.
|
| 174 |
+
text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 175 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`AltCLIPTextModel`].
|
| 176 |
+
image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 177 |
+
The image embeddings obtained by applying the projection layer to the pooled output of
|
| 178 |
+
[`AltCLIPVisionModel`].
|
| 179 |
+
text_model_output(`BaseModelOutputWithPooling`):
|
| 180 |
+
The output of the [`AltCLIPTextModel`].
|
| 181 |
+
vision_model_output(`BaseModelOutputWithPooling`):
|
| 182 |
+
The output of the [`AltCLIPVisionModel`].
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
loss: Optional[torch.FloatTensor] = None
|
| 186 |
+
logits_per_image: torch.FloatTensor = None
|
| 187 |
+
logits_per_text: torch.FloatTensor = None
|
| 188 |
+
text_embeds: torch.FloatTensor = None
|
| 189 |
+
image_embeds: torch.FloatTensor = None
|
| 190 |
+
text_model_output: BaseModelOutputWithPooling = None
|
| 191 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
| 192 |
+
|
| 193 |
+
def to_tuple(self) -> Tuple[Any]:
|
| 194 |
+
return tuple(
|
| 195 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 196 |
+
for k in self.keys()
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->AltRoberta
|
| 201 |
+
class AltRobertaEmbeddings(nn.Module):
|
| 202 |
+
"""
|
| 203 |
+
Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
# Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__
|
| 207 |
+
def __init__(self, config):
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 210 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 211 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 212 |
+
|
| 213 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 214 |
+
# any TensorFlow checkpoint file
|
| 215 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 216 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 217 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 218 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 219 |
+
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
|
| 220 |
+
self.register_buffer(
|
| 221 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
# End copy
|
| 225 |
+
self.padding_idx = config.pad_token_id
|
| 226 |
+
self.position_embeddings = nn.Embedding(
|
| 227 |
+
config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
def forward(
|
| 231 |
+
self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
|
| 232 |
+
):
|
| 233 |
+
if position_ids is None:
|
| 234 |
+
if input_ids is not None:
|
| 235 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
| 236 |
+
position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
|
| 237 |
+
else:
|
| 238 |
+
position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
|
| 239 |
+
|
| 240 |
+
if input_ids is not None:
|
| 241 |
+
input_shape = input_ids.size()
|
| 242 |
+
else:
|
| 243 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 244 |
+
|
| 245 |
+
seq_length = input_shape[1]
|
| 246 |
+
|
| 247 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 248 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 249 |
+
# issue #5664
|
| 250 |
+
if token_type_ids is None:
|
| 251 |
+
if hasattr(self, "token_type_ids"):
|
| 252 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 253 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 254 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 255 |
+
else:
|
| 256 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 257 |
+
|
| 258 |
+
if inputs_embeds is None:
|
| 259 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 260 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 261 |
+
|
| 262 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 263 |
+
if self.position_embedding_type == "absolute":
|
| 264 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 265 |
+
embeddings += position_embeddings
|
| 266 |
+
embeddings = self.LayerNorm(embeddings)
|
| 267 |
+
embeddings = self.dropout(embeddings)
|
| 268 |
+
return embeddings
|
| 269 |
+
|
| 270 |
+
def create_position_ids_from_inputs_embeds(self, inputs_embeds):
|
| 271 |
+
"""
|
| 272 |
+
We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
|
| 273 |
+
|
| 274 |
+
Args:
|
| 275 |
+
inputs_embeds: torch.Tensor
|
| 276 |
+
|
| 277 |
+
Returns: torch.Tensor
|
| 278 |
+
"""
|
| 279 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 280 |
+
sequence_length = input_shape[1]
|
| 281 |
+
|
| 282 |
+
position_ids = torch.arange(
|
| 283 |
+
self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
|
| 284 |
+
)
|
| 285 |
+
return position_ids.unsqueeze(0).expand(input_shape)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfAttention with Roberta->AltRoberta
|
| 289 |
+
class AltRobertaSelfAttention(nn.Module):
|
| 290 |
+
def __init__(self, config, position_embedding_type=None):
|
| 291 |
+
super().__init__()
|
| 292 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 293 |
+
raise ValueError(
|
| 294 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 295 |
+
f"heads ({config.num_attention_heads})"
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
self.num_attention_heads = config.num_attention_heads
|
| 299 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 300 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 301 |
+
|
| 302 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 303 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 304 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 305 |
+
|
| 306 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 307 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
| 308 |
+
config, "position_embedding_type", "absolute"
|
| 309 |
+
)
|
| 310 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 311 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 312 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 313 |
+
|
| 314 |
+
self.is_decoder = config.is_decoder
|
| 315 |
+
|
| 316 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 317 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 318 |
+
x = x.view(new_x_shape)
|
| 319 |
+
return x.permute(0, 2, 1, 3)
|
| 320 |
+
|
| 321 |
+
def forward(
|
| 322 |
+
self,
|
| 323 |
+
hidden_states: torch.Tensor,
|
| 324 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 325 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 326 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 327 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 328 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 329 |
+
output_attentions: Optional[bool] = False,
|
| 330 |
+
) -> Tuple[torch.Tensor]:
|
| 331 |
+
mixed_query_layer = self.query(hidden_states)
|
| 332 |
+
|
| 333 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 334 |
+
# and values come from an encoder; the attention mask needs to be
|
| 335 |
+
# such that the encoder's padding tokens are not attended to.
|
| 336 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 337 |
+
|
| 338 |
+
if is_cross_attention and past_key_value is not None:
|
| 339 |
+
# reuse k,v, cross_attentions
|
| 340 |
+
key_layer = past_key_value[0]
|
| 341 |
+
value_layer = past_key_value[1]
|
| 342 |
+
attention_mask = encoder_attention_mask
|
| 343 |
+
elif is_cross_attention:
|
| 344 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 345 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 346 |
+
attention_mask = encoder_attention_mask
|
| 347 |
+
elif past_key_value is not None:
|
| 348 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 349 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 350 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
| 351 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
| 352 |
+
else:
|
| 353 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 354 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 355 |
+
|
| 356 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 357 |
+
|
| 358 |
+
use_cache = past_key_value is not None
|
| 359 |
+
if self.is_decoder:
|
| 360 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 361 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 362 |
+
# key/value_states (first "if" case)
|
| 363 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 364 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 365 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 366 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 367 |
+
past_key_value = (key_layer, value_layer)
|
| 368 |
+
|
| 369 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 370 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 371 |
+
|
| 372 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 373 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
| 374 |
+
if use_cache:
|
| 375 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
| 376 |
+
-1, 1
|
| 377 |
+
)
|
| 378 |
+
else:
|
| 379 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 380 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 381 |
+
distance = position_ids_l - position_ids_r
|
| 382 |
+
|
| 383 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 384 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 385 |
+
|
| 386 |
+
if self.position_embedding_type == "relative_key":
|
| 387 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 388 |
+
attention_scores = attention_scores + relative_position_scores
|
| 389 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 390 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 391 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 392 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 393 |
+
|
| 394 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 395 |
+
if attention_mask is not None:
|
| 396 |
+
# Apply the attention mask is (precomputed for all layers in AltRobertaModel forward() function)
|
| 397 |
+
attention_scores = attention_scores + attention_mask
|
| 398 |
+
|
| 399 |
+
# Normalize the attention scores to probabilities.
|
| 400 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 401 |
+
|
| 402 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 403 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 404 |
+
attention_probs = self.dropout(attention_probs)
|
| 405 |
+
|
| 406 |
+
# Mask heads if we want to
|
| 407 |
+
if head_mask is not None:
|
| 408 |
+
attention_probs = attention_probs * head_mask
|
| 409 |
+
|
| 410 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 411 |
+
|
| 412 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 413 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 414 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 415 |
+
|
| 416 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 417 |
+
|
| 418 |
+
if self.is_decoder:
|
| 419 |
+
outputs = outputs + (past_key_value,)
|
| 420 |
+
return outputs
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput
|
| 424 |
+
class AltRobertaSelfOutput(nn.Module):
|
| 425 |
+
def __init__(self, config):
|
| 426 |
+
super().__init__()
|
| 427 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 428 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 429 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 430 |
+
|
| 431 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 432 |
+
hidden_states = self.dense(hidden_states)
|
| 433 |
+
hidden_states = self.dropout(hidden_states)
|
| 434 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 435 |
+
return hidden_states
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaAttention with Roberta->AltRoberta
|
| 439 |
+
class AltRobertaAttention(nn.Module):
|
| 440 |
+
def __init__(self, config, position_embedding_type=None):
|
| 441 |
+
super().__init__()
|
| 442 |
+
self.self = AltRobertaSelfAttention(config, position_embedding_type=position_embedding_type)
|
| 443 |
+
self.output = AltRobertaSelfOutput(config)
|
| 444 |
+
self.pruned_heads = set()
|
| 445 |
+
|
| 446 |
+
def prune_heads(self, heads):
|
| 447 |
+
if len(heads) == 0:
|
| 448 |
+
return
|
| 449 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 450 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
# Prune linear layers
|
| 454 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 455 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 456 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 457 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 458 |
+
|
| 459 |
+
# Update hyper params and store pruned heads
|
| 460 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 461 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 462 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 463 |
+
|
| 464 |
+
def forward(
|
| 465 |
+
self,
|
| 466 |
+
hidden_states: torch.Tensor,
|
| 467 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 468 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 469 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 470 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 471 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 472 |
+
output_attentions: Optional[bool] = False,
|
| 473 |
+
) -> Tuple[torch.Tensor]:
|
| 474 |
+
self_outputs = self.self(
|
| 475 |
+
hidden_states,
|
| 476 |
+
attention_mask,
|
| 477 |
+
head_mask,
|
| 478 |
+
encoder_hidden_states,
|
| 479 |
+
encoder_attention_mask,
|
| 480 |
+
past_key_value,
|
| 481 |
+
output_attentions,
|
| 482 |
+
)
|
| 483 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 484 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 485 |
+
return outputs
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaIntermediate with Roberta->AltRoberta
|
| 489 |
+
class AltRobertaIntermediate(nn.Module):
|
| 490 |
+
def __init__(self, config):
|
| 491 |
+
super().__init__()
|
| 492 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 493 |
+
if isinstance(config.hidden_act, str):
|
| 494 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 495 |
+
else:
|
| 496 |
+
self.intermediate_act_fn = config.hidden_act
|
| 497 |
+
|
| 498 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 499 |
+
hidden_states = self.dense(hidden_states)
|
| 500 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 501 |
+
return hidden_states
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaOutput
|
| 505 |
+
class AltRobertaOutput(nn.Module):
|
| 506 |
+
def __init__(self, config):
|
| 507 |
+
super().__init__()
|
| 508 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 509 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 510 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 511 |
+
|
| 512 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 513 |
+
hidden_states = self.dense(hidden_states)
|
| 514 |
+
hidden_states = self.dropout(hidden_states)
|
| 515 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 516 |
+
return hidden_states
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaLayer with Roberta->AltRoberta
|
| 520 |
+
class AltRobertaLayer(nn.Module):
|
| 521 |
+
def __init__(self, config):
|
| 522 |
+
super().__init__()
|
| 523 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 524 |
+
self.seq_len_dim = 1
|
| 525 |
+
self.attention = AltRobertaAttention(config)
|
| 526 |
+
self.is_decoder = config.is_decoder
|
| 527 |
+
self.add_cross_attention = config.add_cross_attention
|
| 528 |
+
if self.add_cross_attention:
|
| 529 |
+
if not self.is_decoder:
|
| 530 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 531 |
+
self.crossattention = AltRobertaAttention(config, position_embedding_type="absolute")
|
| 532 |
+
self.intermediate = AltRobertaIntermediate(config)
|
| 533 |
+
self.output = AltRobertaOutput(config)
|
| 534 |
+
|
| 535 |
+
def forward(
|
| 536 |
+
self,
|
| 537 |
+
hidden_states: torch.Tensor,
|
| 538 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 539 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 540 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 541 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 542 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 543 |
+
output_attentions: Optional[bool] = False,
|
| 544 |
+
) -> Tuple[torch.Tensor]:
|
| 545 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 546 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 547 |
+
self_attention_outputs = self.attention(
|
| 548 |
+
hidden_states,
|
| 549 |
+
attention_mask,
|
| 550 |
+
head_mask,
|
| 551 |
+
output_attentions=output_attentions,
|
| 552 |
+
past_key_value=self_attn_past_key_value,
|
| 553 |
+
)
|
| 554 |
+
attention_output = self_attention_outputs[0]
|
| 555 |
+
|
| 556 |
+
# if decoder, the last output is tuple of self-attn cache
|
| 557 |
+
if self.is_decoder:
|
| 558 |
+
outputs = self_attention_outputs[1:-1]
|
| 559 |
+
present_key_value = self_attention_outputs[-1]
|
| 560 |
+
else:
|
| 561 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 562 |
+
|
| 563 |
+
cross_attn_present_key_value = None
|
| 564 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 565 |
+
if not hasattr(self, "crossattention"):
|
| 566 |
+
raise ValueError(
|
| 567 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 568 |
+
" by setting `config.add_cross_attention=True`"
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
| 572 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 573 |
+
cross_attention_outputs = self.crossattention(
|
| 574 |
+
attention_output,
|
| 575 |
+
attention_mask,
|
| 576 |
+
head_mask,
|
| 577 |
+
encoder_hidden_states,
|
| 578 |
+
encoder_attention_mask,
|
| 579 |
+
cross_attn_past_key_value,
|
| 580 |
+
output_attentions,
|
| 581 |
+
)
|
| 582 |
+
attention_output = cross_attention_outputs[0]
|
| 583 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 584 |
+
|
| 585 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
| 586 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
| 587 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 588 |
+
|
| 589 |
+
layer_output = apply_chunking_to_forward(
|
| 590 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 591 |
+
)
|
| 592 |
+
outputs = (layer_output,) + outputs
|
| 593 |
+
|
| 594 |
+
# if decoder, return the attn key/values as the last output
|
| 595 |
+
if self.is_decoder:
|
| 596 |
+
outputs = outputs + (present_key_value,)
|
| 597 |
+
|
| 598 |
+
return outputs
|
| 599 |
+
|
| 600 |
+
def feed_forward_chunk(self, attention_output):
|
| 601 |
+
intermediate_output = self.intermediate(attention_output)
|
| 602 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 603 |
+
return layer_output
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaEncoder with Roberta->AltRoberta
|
| 607 |
+
class AltRobertaEncoder(nn.Module):
|
| 608 |
+
def __init__(self, config):
|
| 609 |
+
super().__init__()
|
| 610 |
+
self.config = config
|
| 611 |
+
self.layer = nn.ModuleList([AltRobertaLayer(config) for _ in range(config.num_hidden_layers)])
|
| 612 |
+
self.gradient_checkpointing = False
|
| 613 |
+
|
| 614 |
+
def forward(
|
| 615 |
+
self,
|
| 616 |
+
hidden_states: torch.Tensor,
|
| 617 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 618 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 619 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 620 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 621 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 622 |
+
use_cache: Optional[bool] = None,
|
| 623 |
+
output_attentions: Optional[bool] = False,
|
| 624 |
+
output_hidden_states: Optional[bool] = False,
|
| 625 |
+
return_dict: Optional[bool] = True,
|
| 626 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
| 627 |
+
all_hidden_states = () if output_hidden_states else None
|
| 628 |
+
all_self_attentions = () if output_attentions else None
|
| 629 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 630 |
+
|
| 631 |
+
if self.gradient_checkpointing and self.training:
|
| 632 |
+
if use_cache:
|
| 633 |
+
logger.warning_once(
|
| 634 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 635 |
+
)
|
| 636 |
+
use_cache = False
|
| 637 |
+
|
| 638 |
+
next_decoder_cache = () if use_cache else None
|
| 639 |
+
for i, layer_module in enumerate(self.layer):
|
| 640 |
+
if output_hidden_states:
|
| 641 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 642 |
+
|
| 643 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 644 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 645 |
+
|
| 646 |
+
if self.gradient_checkpointing and self.training:
|
| 647 |
+
|
| 648 |
+
def create_custom_forward(module):
|
| 649 |
+
def custom_forward(*inputs):
|
| 650 |
+
return module(*inputs, past_key_value, output_attentions)
|
| 651 |
+
|
| 652 |
+
return custom_forward
|
| 653 |
+
|
| 654 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 655 |
+
create_custom_forward(layer_module),
|
| 656 |
+
hidden_states,
|
| 657 |
+
attention_mask,
|
| 658 |
+
layer_head_mask,
|
| 659 |
+
encoder_hidden_states,
|
| 660 |
+
encoder_attention_mask,
|
| 661 |
+
)
|
| 662 |
+
else:
|
| 663 |
+
layer_outputs = layer_module(
|
| 664 |
+
hidden_states,
|
| 665 |
+
attention_mask,
|
| 666 |
+
layer_head_mask,
|
| 667 |
+
encoder_hidden_states,
|
| 668 |
+
encoder_attention_mask,
|
| 669 |
+
past_key_value,
|
| 670 |
+
output_attentions,
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
hidden_states = layer_outputs[0]
|
| 674 |
+
if use_cache:
|
| 675 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 676 |
+
if output_attentions:
|
| 677 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 678 |
+
if self.config.add_cross_attention:
|
| 679 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 680 |
+
|
| 681 |
+
if output_hidden_states:
|
| 682 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 683 |
+
|
| 684 |
+
if not return_dict:
|
| 685 |
+
return tuple(
|
| 686 |
+
v
|
| 687 |
+
for v in [
|
| 688 |
+
hidden_states,
|
| 689 |
+
next_decoder_cache,
|
| 690 |
+
all_hidden_states,
|
| 691 |
+
all_self_attentions,
|
| 692 |
+
all_cross_attentions,
|
| 693 |
+
]
|
| 694 |
+
if v is not None
|
| 695 |
+
)
|
| 696 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 697 |
+
last_hidden_state=hidden_states,
|
| 698 |
+
past_key_values=next_decoder_cache,
|
| 699 |
+
hidden_states=all_hidden_states,
|
| 700 |
+
attentions=all_self_attentions,
|
| 701 |
+
cross_attentions=all_cross_attentions,
|
| 702 |
+
)
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaPooler
|
| 706 |
+
class AltRobertaPooler(nn.Module):
|
| 707 |
+
def __init__(self, config):
|
| 708 |
+
super().__init__()
|
| 709 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 710 |
+
self.activation = nn.Tanh()
|
| 711 |
+
|
| 712 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 713 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 714 |
+
# to the first token.
|
| 715 |
+
first_token_tensor = hidden_states[:, 0]
|
| 716 |
+
pooled_output = self.dense(first_token_tensor)
|
| 717 |
+
pooled_output = self.activation(pooled_output)
|
| 718 |
+
return pooled_output
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPAttention with CLIP->AltCLIP
|
| 722 |
+
class AltCLIPAttention(nn.Module):
|
| 723 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 724 |
+
|
| 725 |
+
def __init__(self, config):
|
| 726 |
+
super().__init__()
|
| 727 |
+
self.config = config
|
| 728 |
+
self.embed_dim = config.hidden_size
|
| 729 |
+
self.num_heads = config.num_attention_heads
|
| 730 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 731 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 732 |
+
raise ValueError(
|
| 733 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 734 |
+
f" {self.num_heads})."
|
| 735 |
+
)
|
| 736 |
+
self.scale = self.head_dim**-0.5
|
| 737 |
+
self.dropout = config.attention_dropout
|
| 738 |
+
|
| 739 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 740 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 741 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 742 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 743 |
+
|
| 744 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 745 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 746 |
+
|
| 747 |
+
def forward(
|
| 748 |
+
self,
|
| 749 |
+
hidden_states: torch.Tensor,
|
| 750 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 751 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
| 752 |
+
output_attentions: Optional[bool] = False,
|
| 753 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 754 |
+
"""Input shape: Batch x Time x Channel"""
|
| 755 |
+
|
| 756 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
| 757 |
+
|
| 758 |
+
# get query proj
|
| 759 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
| 760 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 761 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 762 |
+
|
| 763 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 764 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 765 |
+
key_states = key_states.view(*proj_shape)
|
| 766 |
+
value_states = value_states.view(*proj_shape)
|
| 767 |
+
|
| 768 |
+
src_len = key_states.size(1)
|
| 769 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 770 |
+
|
| 771 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 772 |
+
raise ValueError(
|
| 773 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 774 |
+
f" {attn_weights.size()}"
|
| 775 |
+
)
|
| 776 |
+
|
| 777 |
+
# apply the causal_attention_mask first
|
| 778 |
+
if causal_attention_mask is not None:
|
| 779 |
+
if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 780 |
+
raise ValueError(
|
| 781 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
| 782 |
+
f" {causal_attention_mask.size()}"
|
| 783 |
+
)
|
| 784 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
|
| 785 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 786 |
+
|
| 787 |
+
if attention_mask is not None:
|
| 788 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 789 |
+
raise ValueError(
|
| 790 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 791 |
+
)
|
| 792 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 793 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 794 |
+
|
| 795 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 796 |
+
|
| 797 |
+
if output_attentions:
|
| 798 |
+
# this operation is a bit akward, but it's required to
|
| 799 |
+
# make sure that attn_weights keeps its gradient.
|
| 800 |
+
# In order to do so, attn_weights have to reshaped
|
| 801 |
+
# twice and have to be reused in the following
|
| 802 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 803 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 804 |
+
else:
|
| 805 |
+
attn_weights_reshaped = None
|
| 806 |
+
|
| 807 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 808 |
+
|
| 809 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 810 |
+
|
| 811 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 812 |
+
raise ValueError(
|
| 813 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 814 |
+
f" {attn_output.size()}"
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 818 |
+
attn_output = attn_output.transpose(1, 2)
|
| 819 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
| 820 |
+
|
| 821 |
+
attn_output = self.out_proj(attn_output)
|
| 822 |
+
|
| 823 |
+
return attn_output, attn_weights_reshaped
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->AltCLIP
|
| 827 |
+
class AltCLIPMLP(nn.Module):
|
| 828 |
+
def __init__(self, config):
|
| 829 |
+
super().__init__()
|
| 830 |
+
self.config = config
|
| 831 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 832 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 833 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 834 |
+
|
| 835 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 836 |
+
hidden_states = self.fc1(hidden_states)
|
| 837 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 838 |
+
hidden_states = self.fc2(hidden_states)
|
| 839 |
+
return hidden_states
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->AltCLIP
|
| 843 |
+
class AltCLIPEncoderLayer(nn.Module):
|
| 844 |
+
def __init__(self, config: AltCLIPConfig):
|
| 845 |
+
super().__init__()
|
| 846 |
+
self.embed_dim = config.hidden_size
|
| 847 |
+
self.self_attn = AltCLIPAttention(config)
|
| 848 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 849 |
+
self.mlp = AltCLIPMLP(config)
|
| 850 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 851 |
+
|
| 852 |
+
def forward(
|
| 853 |
+
self,
|
| 854 |
+
hidden_states: torch.Tensor,
|
| 855 |
+
attention_mask: torch.Tensor,
|
| 856 |
+
causal_attention_mask: torch.Tensor,
|
| 857 |
+
output_attentions: Optional[bool] = False,
|
| 858 |
+
) -> Tuple[torch.FloatTensor]:
|
| 859 |
+
"""
|
| 860 |
+
Args:
|
| 861 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 862 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 863 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 864 |
+
`(config.encoder_attention_heads,)`.
|
| 865 |
+
output_attentions (`bool`, *optional*):
|
| 866 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 867 |
+
returned tensors for more detail.
|
| 868 |
+
"""
|
| 869 |
+
residual = hidden_states
|
| 870 |
+
|
| 871 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 872 |
+
hidden_states, attn_weights = self.self_attn(
|
| 873 |
+
hidden_states=hidden_states,
|
| 874 |
+
attention_mask=attention_mask,
|
| 875 |
+
causal_attention_mask=causal_attention_mask,
|
| 876 |
+
output_attentions=output_attentions,
|
| 877 |
+
)
|
| 878 |
+
hidden_states = residual + hidden_states
|
| 879 |
+
|
| 880 |
+
residual = hidden_states
|
| 881 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 882 |
+
hidden_states = self.mlp(hidden_states)
|
| 883 |
+
hidden_states = residual + hidden_states
|
| 884 |
+
|
| 885 |
+
outputs = (hidden_states,)
|
| 886 |
+
|
| 887 |
+
if output_attentions:
|
| 888 |
+
outputs += (attn_weights,)
|
| 889 |
+
|
| 890 |
+
return outputs
|
| 891 |
+
|
| 892 |
+
|
| 893 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->AltCLIP
|
| 894 |
+
class AltCLIPEncoder(nn.Module):
|
| 895 |
+
"""
|
| 896 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 897 |
+
[`AltCLIPEncoderLayer`].
|
| 898 |
+
|
| 899 |
+
Args:
|
| 900 |
+
config: AltCLIPConfig
|
| 901 |
+
"""
|
| 902 |
+
|
| 903 |
+
def __init__(self, config: AltCLIPConfig):
|
| 904 |
+
super().__init__()
|
| 905 |
+
self.config = config
|
| 906 |
+
self.layers = nn.ModuleList([AltCLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 907 |
+
self.gradient_checkpointing = False
|
| 908 |
+
|
| 909 |
+
def forward(
|
| 910 |
+
self,
|
| 911 |
+
inputs_embeds,
|
| 912 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 913 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
| 914 |
+
output_attentions: Optional[bool] = None,
|
| 915 |
+
output_hidden_states: Optional[bool] = None,
|
| 916 |
+
return_dict: Optional[bool] = None,
|
| 917 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 918 |
+
r"""
|
| 919 |
+
Args:
|
| 920 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 921 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 922 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 923 |
+
than the model's internal embedding lookup matrix.
|
| 924 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 925 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 926 |
+
|
| 927 |
+
- 1 for tokens that are **not masked**,
|
| 928 |
+
- 0 for tokens that are **masked**.
|
| 929 |
+
|
| 930 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 931 |
+
causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 932 |
+
Causal mask for the text model. Mask values selected in `[0, 1]`:
|
| 933 |
+
|
| 934 |
+
- 1 for tokens that are **not masked**,
|
| 935 |
+
- 0 for tokens that are **masked**.
|
| 936 |
+
|
| 937 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 938 |
+
output_attentions (`bool`, *optional*):
|
| 939 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 940 |
+
returned tensors for more detail.
|
| 941 |
+
output_hidden_states (`bool`, *optional*):
|
| 942 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 943 |
+
for more detail.
|
| 944 |
+
return_dict (`bool`, *optional*):
|
| 945 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 946 |
+
"""
|
| 947 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 948 |
+
output_hidden_states = (
|
| 949 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 950 |
+
)
|
| 951 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 952 |
+
|
| 953 |
+
encoder_states = () if output_hidden_states else None
|
| 954 |
+
all_attentions = () if output_attentions else None
|
| 955 |
+
|
| 956 |
+
hidden_states = inputs_embeds
|
| 957 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 958 |
+
if output_hidden_states:
|
| 959 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 960 |
+
if self.gradient_checkpointing and self.training:
|
| 961 |
+
|
| 962 |
+
def create_custom_forward(module):
|
| 963 |
+
def custom_forward(*inputs):
|
| 964 |
+
return module(*inputs, output_attentions)
|
| 965 |
+
|
| 966 |
+
return custom_forward
|
| 967 |
+
|
| 968 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 969 |
+
create_custom_forward(encoder_layer),
|
| 970 |
+
hidden_states,
|
| 971 |
+
attention_mask,
|
| 972 |
+
causal_attention_mask,
|
| 973 |
+
)
|
| 974 |
+
else:
|
| 975 |
+
layer_outputs = encoder_layer(
|
| 976 |
+
hidden_states,
|
| 977 |
+
attention_mask,
|
| 978 |
+
causal_attention_mask,
|
| 979 |
+
output_attentions=output_attentions,
|
| 980 |
+
)
|
| 981 |
+
|
| 982 |
+
hidden_states = layer_outputs[0]
|
| 983 |
+
|
| 984 |
+
if output_attentions:
|
| 985 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 986 |
+
|
| 987 |
+
if output_hidden_states:
|
| 988 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 989 |
+
|
| 990 |
+
if not return_dict:
|
| 991 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 992 |
+
return BaseModelOutput(
|
| 993 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 994 |
+
)
|
| 995 |
+
|
| 996 |
+
|
| 997 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->AltCLIP
|
| 998 |
+
class AltCLIPVisionEmbeddings(nn.Module):
|
| 999 |
+
def __init__(self, config: AltCLIPVisionConfig):
|
| 1000 |
+
super().__init__()
|
| 1001 |
+
self.config = config
|
| 1002 |
+
self.embed_dim = config.hidden_size
|
| 1003 |
+
self.image_size = config.image_size
|
| 1004 |
+
self.patch_size = config.patch_size
|
| 1005 |
+
|
| 1006 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
| 1007 |
+
|
| 1008 |
+
self.patch_embedding = nn.Conv2d(
|
| 1009 |
+
in_channels=config.num_channels,
|
| 1010 |
+
out_channels=self.embed_dim,
|
| 1011 |
+
kernel_size=self.patch_size,
|
| 1012 |
+
stride=self.patch_size,
|
| 1013 |
+
bias=False,
|
| 1014 |
+
)
|
| 1015 |
+
|
| 1016 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 1017 |
+
self.num_positions = self.num_patches + 1
|
| 1018 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
| 1019 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)))
|
| 1020 |
+
|
| 1021 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 1022 |
+
batch_size = pixel_values.shape[0]
|
| 1023 |
+
patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
|
| 1024 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
| 1025 |
+
|
| 1026 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
| 1027 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 1028 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
| 1029 |
+
return embeddings
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
class AltCLIPPreTrainedModel(PreTrainedModel):
|
| 1033 |
+
"""
|
| 1034 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 1035 |
+
models.
|
| 1036 |
+
"""
|
| 1037 |
+
|
| 1038 |
+
config_class = AltCLIPConfig
|
| 1039 |
+
base_model_prefix = "altclip"
|
| 1040 |
+
supports_gradient_checkpointing = True
|
| 1041 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
| 1042 |
+
|
| 1043 |
+
def _init_weights(self, module):
|
| 1044 |
+
"""Initialize the weights"""
|
| 1045 |
+
factor = self.config.initializer_factor
|
| 1046 |
+
if isinstance(module, AltCLIPVisionEmbeddings):
|
| 1047 |
+
factor = self.config.initializer_factor
|
| 1048 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
| 1049 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
| 1050 |
+
nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
|
| 1051 |
+
elif isinstance(module, AltCLIPAttention):
|
| 1052 |
+
factor = self.config.initializer_factor
|
| 1053 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 1054 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
| 1055 |
+
nn.init.normal_(module.q_proj.weight, std=in_proj_std)
|
| 1056 |
+
nn.init.normal_(module.k_proj.weight, std=in_proj_std)
|
| 1057 |
+
nn.init.normal_(module.v_proj.weight, std=in_proj_std)
|
| 1058 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
| 1059 |
+
elif isinstance(module, AltCLIPMLP):
|
| 1060 |
+
factor = self.config.initializer_factor
|
| 1061 |
+
in_proj_std = (
|
| 1062 |
+
(module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 1063 |
+
)
|
| 1064 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
| 1065 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
| 1066 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
| 1067 |
+
elif isinstance(module, AltCLIPModel):
|
| 1068 |
+
nn.init.normal_(
|
| 1069 |
+
module.text_projection.weight,
|
| 1070 |
+
std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
|
| 1071 |
+
)
|
| 1072 |
+
module.text_projection._is_hf_initialized = True
|
| 1073 |
+
nn.init.normal_(
|
| 1074 |
+
module.visual_projection.weight,
|
| 1075 |
+
std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
|
| 1076 |
+
)
|
| 1077 |
+
module.visual_projection._is_hf_initialized = True
|
| 1078 |
+
elif isinstance(module, nn.LayerNorm):
|
| 1079 |
+
module.bias.data.zero_()
|
| 1080 |
+
module.weight.data.fill_(1.0)
|
| 1081 |
+
elif isinstance(module, nn.Linear):
|
| 1082 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_factor)
|
| 1083 |
+
if module.bias is not None:
|
| 1084 |
+
module.bias.data.zero_()
|
| 1085 |
+
elif isinstance(module, nn.Embedding):
|
| 1086 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_factor)
|
| 1087 |
+
if module.padding_idx is not None:
|
| 1088 |
+
module.weight.data[module.padding_idx].zero_()
|
| 1089 |
+
|
| 1090 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 1091 |
+
if isinstance(module, AltCLIPEncoder):
|
| 1092 |
+
module.gradient_checkpointing = value
|
| 1093 |
+
if isinstance(module, AltRobertaEncoder):
|
| 1094 |
+
module.gradient_checkpointing = value
|
| 1095 |
+
|
| 1096 |
+
|
| 1097 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionTransformer with CLIPVisionTransformer->AltCLIPVisionTransformer,CLIPVisionConfig->AltCLIPVisionConfig,CLIPVisionEmbeddings->AltCLIPVisionEmbeddings,CLIPEncoder->AltCLIPEncoder,CLIP_VISION_INPUTS_DOCSTRING->ALTCLIP_VISION_INPUTS_DOCSTRING
|
| 1098 |
+
class AltCLIPVisionTransformer(nn.Module):
|
| 1099 |
+
def __init__(self, config: AltCLIPVisionConfig):
|
| 1100 |
+
super().__init__()
|
| 1101 |
+
self.config = config
|
| 1102 |
+
embed_dim = config.hidden_size
|
| 1103 |
+
|
| 1104 |
+
self.embeddings = AltCLIPVisionEmbeddings(config)
|
| 1105 |
+
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 1106 |
+
self.encoder = AltCLIPEncoder(config)
|
| 1107 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 1108 |
+
|
| 1109 |
+
@add_start_docstrings_to_model_forward(ALTCLIP_VISION_INPUTS_DOCSTRING)
|
| 1110 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=AltCLIPVisionConfig)
|
| 1111 |
+
def forward(
|
| 1112 |
+
self,
|
| 1113 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1114 |
+
output_attentions: Optional[bool] = None,
|
| 1115 |
+
output_hidden_states: Optional[bool] = None,
|
| 1116 |
+
return_dict: Optional[bool] = None,
|
| 1117 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 1118 |
+
r"""
|
| 1119 |
+
Returns:
|
| 1120 |
+
|
| 1121 |
+
"""
|
| 1122 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1123 |
+
output_hidden_states = (
|
| 1124 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1125 |
+
)
|
| 1126 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1127 |
+
|
| 1128 |
+
if pixel_values is None:
|
| 1129 |
+
raise ValueError("You have to specify pixel_values")
|
| 1130 |
+
|
| 1131 |
+
hidden_states = self.embeddings(pixel_values)
|
| 1132 |
+
hidden_states = self.pre_layrnorm(hidden_states)
|
| 1133 |
+
|
| 1134 |
+
encoder_outputs = self.encoder(
|
| 1135 |
+
inputs_embeds=hidden_states,
|
| 1136 |
+
output_attentions=output_attentions,
|
| 1137 |
+
output_hidden_states=output_hidden_states,
|
| 1138 |
+
return_dict=return_dict,
|
| 1139 |
+
)
|
| 1140 |
+
|
| 1141 |
+
last_hidden_state = encoder_outputs[0]
|
| 1142 |
+
pooled_output = last_hidden_state[:, 0, :]
|
| 1143 |
+
pooled_output = self.post_layernorm(pooled_output)
|
| 1144 |
+
|
| 1145 |
+
if not return_dict:
|
| 1146 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 1147 |
+
|
| 1148 |
+
return BaseModelOutputWithPooling(
|
| 1149 |
+
last_hidden_state=last_hidden_state,
|
| 1150 |
+
pooler_output=pooled_output,
|
| 1151 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1152 |
+
attentions=encoder_outputs.attentions,
|
| 1153 |
+
)
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
class AltCLIPVisionModel(AltCLIPPreTrainedModel):
|
| 1157 |
+
config_class = AltCLIPVisionConfig
|
| 1158 |
+
main_input_name = "pixel_values"
|
| 1159 |
+
|
| 1160 |
+
def __init__(self, config: AltCLIPVisionConfig):
|
| 1161 |
+
super().__init__(config)
|
| 1162 |
+
self.vision_model = AltCLIPVisionTransformer(config)
|
| 1163 |
+
# Initialize weights and apply final processing
|
| 1164 |
+
self.post_init()
|
| 1165 |
+
|
| 1166 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1167 |
+
return self.vision_model.embeddings.patch_embedding
|
| 1168 |
+
|
| 1169 |
+
@add_start_docstrings_to_model_forward(ALTCLIP_VISION_INPUTS_DOCSTRING)
|
| 1170 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=AltCLIPVisionConfig)
|
| 1171 |
+
def forward(
|
| 1172 |
+
self,
|
| 1173 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1174 |
+
output_attentions: Optional[bool] = None,
|
| 1175 |
+
output_hidden_states: Optional[bool] = None,
|
| 1176 |
+
return_dict: Optional[bool] = None,
|
| 1177 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 1178 |
+
r"""
|
| 1179 |
+
Returns:
|
| 1180 |
+
|
| 1181 |
+
Examples:
|
| 1182 |
+
|
| 1183 |
+
```python
|
| 1184 |
+
>>> from PIL import Image
|
| 1185 |
+
>>> import requests
|
| 1186 |
+
>>> from transformers import AutoProcessor, AltCLIPVisionModel
|
| 1187 |
+
|
| 1188 |
+
>>> model = AltCLIPVisionModel.from_pretrained("BAAI/AltCLIP")
|
| 1189 |
+
>>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
|
| 1190 |
+
|
| 1191 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1192 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1193 |
+
|
| 1194 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1195 |
+
|
| 1196 |
+
>>> outputs = model(**inputs)
|
| 1197 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 1198 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
| 1199 |
+
```"""
|
| 1200 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1201 |
+
|
| 1202 |
+
return self.vision_model(
|
| 1203 |
+
pixel_values=pixel_values,
|
| 1204 |
+
output_attentions=output_attentions,
|
| 1205 |
+
output_hidden_states=output_hidden_states,
|
| 1206 |
+
return_dict=return_dict,
|
| 1207 |
+
)
|
| 1208 |
+
|
| 1209 |
+
|
| 1210 |
+
class AltRobertaModel(AltCLIPPreTrainedModel):
|
| 1211 |
+
"""
|
| 1212 |
+
|
| 1213 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 1214 |
+
cross-attention is added between the self-attention layers, following the architecture described in *Attention is
|
| 1215 |
+
all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
|
| 1216 |
+
Kaiser and Illia Polosukhin.
|
| 1217 |
+
|
| 1218 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
| 1219 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
| 1220 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
| 1221 |
+
|
| 1222 |
+
.. _*Attention is all you need*: https://arxiv.org/abs/1706.03762
|
| 1223 |
+
|
| 1224 |
+
"""
|
| 1225 |
+
|
| 1226 |
+
config_class = AltCLIPTextConfig
|
| 1227 |
+
|
| 1228 |
+
# Copied from transformers.models.bert.modeling_bert.BertModel.__init__ with Bert->AltRoberta
|
| 1229 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 1230 |
+
super().__init__(config)
|
| 1231 |
+
self.config = config
|
| 1232 |
+
|
| 1233 |
+
self.embeddings = AltRobertaEmbeddings(config)
|
| 1234 |
+
self.encoder = AltRobertaEncoder(config)
|
| 1235 |
+
|
| 1236 |
+
self.pooler = AltRobertaPooler(config) if add_pooling_layer else None
|
| 1237 |
+
|
| 1238 |
+
# Initialize weights and apply final processing
|
| 1239 |
+
self.post_init()
|
| 1240 |
+
|
| 1241 |
+
def get_input_embeddings(self):
|
| 1242 |
+
return self.embeddings.word_embeddings
|
| 1243 |
+
|
| 1244 |
+
def set_input_embeddings(self, value):
|
| 1245 |
+
self.embeddings.word_embeddings = value
|
| 1246 |
+
|
| 1247 |
+
def _prune_heads(self, heads_to_prune):
|
| 1248 |
+
"""
|
| 1249 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 1250 |
+
class PreTrainedModel
|
| 1251 |
+
"""
|
| 1252 |
+
for layer, heads in heads_to_prune.items():
|
| 1253 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 1254 |
+
|
| 1255 |
+
# Copied from transformers.models.bert.modeling_bert.BertModel.forward
|
| 1256 |
+
def forward(
|
| 1257 |
+
self,
|
| 1258 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1259 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1260 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1261 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1262 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1263 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1264 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1265 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1266 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1267 |
+
use_cache: Optional[bool] = None,
|
| 1268 |
+
output_attentions: Optional[bool] = None,
|
| 1269 |
+
output_hidden_states: Optional[bool] = None,
|
| 1270 |
+
return_dict: Optional[bool] = None,
|
| 1271 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
| 1272 |
+
r"""
|
| 1273 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1274 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 1275 |
+
the model is configured as a decoder.
|
| 1276 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1277 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 1278 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1279 |
+
|
| 1280 |
+
- 1 for tokens that are **not masked**,
|
| 1281 |
+
- 0 for tokens that are **masked**.
|
| 1282 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
| 1283 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 1284 |
+
|
| 1285 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 1286 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 1287 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1288 |
+
use_cache (`bool`, *optional*):
|
| 1289 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 1290 |
+
`past_key_values`).
|
| 1291 |
+
"""
|
| 1292 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1293 |
+
output_hidden_states = (
|
| 1294 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1295 |
+
)
|
| 1296 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1297 |
+
|
| 1298 |
+
if self.config.is_decoder:
|
| 1299 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1300 |
+
else:
|
| 1301 |
+
use_cache = False
|
| 1302 |
+
|
| 1303 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1304 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 1305 |
+
elif input_ids is not None:
|
| 1306 |
+
input_shape = input_ids.size()
|
| 1307 |
+
elif inputs_embeds is not None:
|
| 1308 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1309 |
+
else:
|
| 1310 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1311 |
+
|
| 1312 |
+
batch_size, seq_length = input_shape
|
| 1313 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 1314 |
+
|
| 1315 |
+
# past_key_values_length
|
| 1316 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 1317 |
+
|
| 1318 |
+
if attention_mask is None:
|
| 1319 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
| 1320 |
+
|
| 1321 |
+
if token_type_ids is None:
|
| 1322 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 1323 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 1324 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 1325 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 1326 |
+
else:
|
| 1327 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 1328 |
+
|
| 1329 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 1330 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 1331 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 1332 |
+
|
| 1333 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
| 1334 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 1335 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
| 1336 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
| 1337 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
| 1338 |
+
if encoder_attention_mask is None:
|
| 1339 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
| 1340 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
| 1341 |
+
else:
|
| 1342 |
+
encoder_extended_attention_mask = None
|
| 1343 |
+
|
| 1344 |
+
# Prepare head mask if needed
|
| 1345 |
+
# 1.0 in head_mask indicate we keep the head
|
| 1346 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 1347 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 1348 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 1349 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 1350 |
+
|
| 1351 |
+
embedding_output = self.embeddings(
|
| 1352 |
+
input_ids=input_ids,
|
| 1353 |
+
position_ids=position_ids,
|
| 1354 |
+
token_type_ids=token_type_ids,
|
| 1355 |
+
inputs_embeds=inputs_embeds,
|
| 1356 |
+
past_key_values_length=past_key_values_length,
|
| 1357 |
+
)
|
| 1358 |
+
encoder_outputs = self.encoder(
|
| 1359 |
+
embedding_output,
|
| 1360 |
+
attention_mask=extended_attention_mask,
|
| 1361 |
+
head_mask=head_mask,
|
| 1362 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1363 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 1364 |
+
past_key_values=past_key_values,
|
| 1365 |
+
use_cache=use_cache,
|
| 1366 |
+
output_attentions=output_attentions,
|
| 1367 |
+
output_hidden_states=output_hidden_states,
|
| 1368 |
+
return_dict=return_dict,
|
| 1369 |
+
)
|
| 1370 |
+
sequence_output = encoder_outputs[0]
|
| 1371 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 1372 |
+
|
| 1373 |
+
if not return_dict:
|
| 1374 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 1375 |
+
|
| 1376 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
| 1377 |
+
last_hidden_state=sequence_output,
|
| 1378 |
+
pooler_output=pooled_output,
|
| 1379 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 1380 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1381 |
+
attentions=encoder_outputs.attentions,
|
| 1382 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 1383 |
+
)
|
| 1384 |
+
|
| 1385 |
+
|
| 1386 |
+
class AltCLIPTextModel(AltCLIPPreTrainedModel):
|
| 1387 |
+
config_class = AltCLIPTextConfig
|
| 1388 |
+
|
| 1389 |
+
def __init__(self, config):
|
| 1390 |
+
super().__init__(config)
|
| 1391 |
+
self.roberta = AltRobertaModel(config, add_pooling_layer=False)
|
| 1392 |
+
self.transformation = nn.Linear(config.hidden_size, config.project_dim)
|
| 1393 |
+
self.pre_LN = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 1394 |
+
self.post_init()
|
| 1395 |
+
|
| 1396 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1397 |
+
return self.roberta.embeddings.word_embeddings
|
| 1398 |
+
|
| 1399 |
+
def set_input_embeddings(self, value: nn.Embedding) -> None:
|
| 1400 |
+
self.roberta.embeddings.word_embeddings = value
|
| 1401 |
+
|
| 1402 |
+
def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding:
|
| 1403 |
+
return super().resize_token_embeddings(new_num_tokens)
|
| 1404 |
+
|
| 1405 |
+
@add_start_docstrings_to_model_forward(ALTCLIP_TEXT_INPUTS_DOCSTRING)
|
| 1406 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPoolingAndProjection, config_class=AltCLIPTextConfig)
|
| 1407 |
+
def forward(
|
| 1408 |
+
self,
|
| 1409 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1410 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1411 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1412 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1413 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1414 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1415 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1416 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1417 |
+
output_attentions: Optional[bool] = None,
|
| 1418 |
+
return_dict: Optional[bool] = None,
|
| 1419 |
+
output_hidden_states: Optional[bool] = None,
|
| 1420 |
+
):
|
| 1421 |
+
r"""
|
| 1422 |
+
Returns:
|
| 1423 |
+
|
| 1424 |
+
Examples:
|
| 1425 |
+
|
| 1426 |
+
```python
|
| 1427 |
+
>>> from transformers import AutoProcessor, AltCLIPTextModel
|
| 1428 |
+
|
| 1429 |
+
>>> model = AltCLIPTextModel.from_pretrained("BAAI/AltCLIP")
|
| 1430 |
+
>>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
|
| 1431 |
+
|
| 1432 |
+
>>> texts = ["it's a cat", "it's a dog"]
|
| 1433 |
+
|
| 1434 |
+
>>> inputs = processor(text=texts, padding=True, return_tensors="pt")
|
| 1435 |
+
|
| 1436 |
+
>>> outputs = model(**inputs)
|
| 1437 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 1438 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
| 1439 |
+
```"""
|
| 1440 |
+
|
| 1441 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1442 |
+
|
| 1443 |
+
outputs = self.roberta(
|
| 1444 |
+
input_ids=input_ids,
|
| 1445 |
+
attention_mask=attention_mask,
|
| 1446 |
+
token_type_ids=token_type_ids,
|
| 1447 |
+
position_ids=position_ids,
|
| 1448 |
+
head_mask=head_mask,
|
| 1449 |
+
inputs_embeds=inputs_embeds,
|
| 1450 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1451 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1452 |
+
output_attentions=output_attentions,
|
| 1453 |
+
output_hidden_states=output_hidden_states,
|
| 1454 |
+
return_dict=return_dict,
|
| 1455 |
+
)
|
| 1456 |
+
|
| 1457 |
+
# last module outputs
|
| 1458 |
+
sequence_output = outputs[0]
|
| 1459 |
+
|
| 1460 |
+
# project every module
|
| 1461 |
+
sequence_output = self.pre_LN(sequence_output)
|
| 1462 |
+
|
| 1463 |
+
# pooler
|
| 1464 |
+
projection_state = self.transformation(sequence_output)
|
| 1465 |
+
pooler_output = projection_state[:, 0]
|
| 1466 |
+
|
| 1467 |
+
if not return_dict:
|
| 1468 |
+
return (projection_state, pooler_output) + outputs[2:4]
|
| 1469 |
+
|
| 1470 |
+
return BaseModelOutputWithPoolingAndProjection(
|
| 1471 |
+
last_hidden_state=projection_state,
|
| 1472 |
+
pooler_output=pooler_output,
|
| 1473 |
+
hidden_states=outputs.hidden_states,
|
| 1474 |
+
attentions=outputs.attentions,
|
| 1475 |
+
)
|
| 1476 |
+
|
| 1477 |
+
|
| 1478 |
+
class AltCLIPModel(AltCLIPPreTrainedModel):
|
| 1479 |
+
config_class = AltCLIPConfig
|
| 1480 |
+
|
| 1481 |
+
def __init__(self, config: AltCLIPConfig):
|
| 1482 |
+
super().__init__(config)
|
| 1483 |
+
|
| 1484 |
+
if not isinstance(config.vision_config, AltCLIPVisionConfig):
|
| 1485 |
+
raise ValueError(
|
| 1486 |
+
"config.vision_config is expected to be of type AltCLIPVisionConfig but is of type"
|
| 1487 |
+
f" {type(config.vision_config)}."
|
| 1488 |
+
)
|
| 1489 |
+
if not isinstance(config.text_config, AltCLIPTextConfig):
|
| 1490 |
+
raise ValueError(
|
| 1491 |
+
"config.text_config is expected to be of type AltCLIPTextConfig but is of type"
|
| 1492 |
+
f" {type(config.text_config)}."
|
| 1493 |
+
)
|
| 1494 |
+
|
| 1495 |
+
text_config = config.text_config
|
| 1496 |
+
vision_config = config.vision_config
|
| 1497 |
+
|
| 1498 |
+
self.projection_dim = config.projection_dim
|
| 1499 |
+
self.text_embed_dim = text_config.project_dim
|
| 1500 |
+
self.vision_embed_dim = vision_config.hidden_size
|
| 1501 |
+
|
| 1502 |
+
self.text_model = AltCLIPTextModel(text_config)
|
| 1503 |
+
self.vision_model = AltCLIPVisionTransformer(vision_config)
|
| 1504 |
+
|
| 1505 |
+
self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
|
| 1506 |
+
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
|
| 1507 |
+
self.logit_scale = nn.Parameter(torch.ones([]) * self.config.logit_scale_init_value)
|
| 1508 |
+
|
| 1509 |
+
# Initialize weights and apply final processing
|
| 1510 |
+
self.post_init()
|
| 1511 |
+
|
| 1512 |
+
@add_start_docstrings_to_model_forward(ALTCLIP_TEXT_INPUTS_DOCSTRING)
|
| 1513 |
+
def get_text_features(
|
| 1514 |
+
self,
|
| 1515 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1516 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1517 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1518 |
+
token_type_ids=None,
|
| 1519 |
+
output_attentions: Optional[bool] = None,
|
| 1520 |
+
output_hidden_states: Optional[bool] = None,
|
| 1521 |
+
return_dict: Optional[bool] = None,
|
| 1522 |
+
) -> torch.FloatTensor:
|
| 1523 |
+
r"""
|
| 1524 |
+
Returns:
|
| 1525 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
| 1526 |
+
applying the projection layer to the pooled output of [`AltCLIPTextModel`].
|
| 1527 |
+
|
| 1528 |
+
Examples:
|
| 1529 |
+
|
| 1530 |
+
```python
|
| 1531 |
+
>>> from transformers import AutoProcessor, AltCLIPModel
|
| 1532 |
+
|
| 1533 |
+
>>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
|
| 1534 |
+
>>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
|
| 1535 |
+
>>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
| 1536 |
+
>>> text_features = model.get_text_features(**inputs)
|
| 1537 |
+
```"""
|
| 1538 |
+
# Use AltCLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1539 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1540 |
+
output_hidden_states = (
|
| 1541 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1542 |
+
)
|
| 1543 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1544 |
+
|
| 1545 |
+
text_outputs = self.text_model(
|
| 1546 |
+
input_ids=input_ids,
|
| 1547 |
+
attention_mask=attention_mask,
|
| 1548 |
+
position_ids=position_ids,
|
| 1549 |
+
token_type_ids=token_type_ids,
|
| 1550 |
+
output_attentions=output_attentions,
|
| 1551 |
+
output_hidden_states=output_hidden_states,
|
| 1552 |
+
return_dict=return_dict,
|
| 1553 |
+
)
|
| 1554 |
+
pooled_output = text_outputs[1]
|
| 1555 |
+
text_features = self.text_projection(pooled_output)
|
| 1556 |
+
|
| 1557 |
+
return text_features
|
| 1558 |
+
|
| 1559 |
+
@add_start_docstrings_to_model_forward(ALTCLIP_VISION_INPUTS_DOCSTRING)
|
| 1560 |
+
def get_image_features(
|
| 1561 |
+
self,
|
| 1562 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1563 |
+
output_attentions: Optional[bool] = None,
|
| 1564 |
+
output_hidden_states: Optional[bool] = None,
|
| 1565 |
+
return_dict: Optional[bool] = None,
|
| 1566 |
+
) -> torch.FloatTensor:
|
| 1567 |
+
r"""
|
| 1568 |
+
Returns:
|
| 1569 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
| 1570 |
+
applying the projection layer to the pooled output of [`AltCLIPVisionModel`].
|
| 1571 |
+
|
| 1572 |
+
Examples:
|
| 1573 |
+
|
| 1574 |
+
```python
|
| 1575 |
+
>>> from PIL import Image
|
| 1576 |
+
>>> import requests
|
| 1577 |
+
>>> from transformers import AutoProcessor, AltCLIPModel
|
| 1578 |
+
|
| 1579 |
+
>>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
|
| 1580 |
+
>>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
|
| 1581 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1582 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1583 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1584 |
+
>>> image_features = model.get_image_features(**inputs)
|
| 1585 |
+
```"""
|
| 1586 |
+
# Use AltCLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1587 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1588 |
+
output_hidden_states = (
|
| 1589 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1590 |
+
)
|
| 1591 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1592 |
+
|
| 1593 |
+
vision_outputs = self.vision_model(
|
| 1594 |
+
pixel_values=pixel_values,
|
| 1595 |
+
output_attentions=output_attentions,
|
| 1596 |
+
output_hidden_states=output_hidden_states,
|
| 1597 |
+
return_dict=return_dict,
|
| 1598 |
+
)
|
| 1599 |
+
|
| 1600 |
+
pooled_output = vision_outputs[1] # pooled_output
|
| 1601 |
+
image_features = self.visual_projection(pooled_output)
|
| 1602 |
+
|
| 1603 |
+
return image_features
|
| 1604 |
+
|
| 1605 |
+
@add_start_docstrings_to_model_forward(ALTCLIP_INPUTS_DOCSTRING)
|
| 1606 |
+
@replace_return_docstrings(output_type=AltCLIPOutput, config_class=AltCLIPConfig)
|
| 1607 |
+
def forward(
|
| 1608 |
+
self,
|
| 1609 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1610 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1611 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1612 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1613 |
+
token_type_ids=None,
|
| 1614 |
+
return_loss: Optional[bool] = None,
|
| 1615 |
+
output_attentions: Optional[bool] = None,
|
| 1616 |
+
output_hidden_states: Optional[bool] = None,
|
| 1617 |
+
return_dict: Optional[bool] = None,
|
| 1618 |
+
) -> Union[Tuple, AltCLIPOutput]:
|
| 1619 |
+
r"""
|
| 1620 |
+
Returns:
|
| 1621 |
+
|
| 1622 |
+
Examples:
|
| 1623 |
+
|
| 1624 |
+
```python
|
| 1625 |
+
>>> from PIL import Image
|
| 1626 |
+
>>> import requests
|
| 1627 |
+
>>> from transformers import AutoProcessor, AltCLIPModel
|
| 1628 |
+
|
| 1629 |
+
>>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
|
| 1630 |
+
>>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
|
| 1631 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1632 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1633 |
+
>>> inputs = processor(
|
| 1634 |
+
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
|
| 1635 |
+
... )
|
| 1636 |
+
>>> outputs = model(**inputs)
|
| 1637 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
| 1638 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
| 1639 |
+
```"""
|
| 1640 |
+
# Use AltCLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1641 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1642 |
+
output_hidden_states = (
|
| 1643 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1644 |
+
)
|
| 1645 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1646 |
+
|
| 1647 |
+
text_outputs = self.text_model(
|
| 1648 |
+
input_ids=input_ids,
|
| 1649 |
+
attention_mask=attention_mask,
|
| 1650 |
+
token_type_ids=token_type_ids,
|
| 1651 |
+
position_ids=position_ids,
|
| 1652 |
+
output_attentions=output_attentions,
|
| 1653 |
+
output_hidden_states=output_hidden_states,
|
| 1654 |
+
return_dict=return_dict,
|
| 1655 |
+
)
|
| 1656 |
+
|
| 1657 |
+
vision_outputs = self.vision_model(
|
| 1658 |
+
pixel_values=pixel_values,
|
| 1659 |
+
output_attentions=output_attentions,
|
| 1660 |
+
output_hidden_states=output_hidden_states,
|
| 1661 |
+
return_dict=return_dict,
|
| 1662 |
+
)
|
| 1663 |
+
|
| 1664 |
+
image_embeds = vision_outputs[1]
|
| 1665 |
+
image_embeds = self.visual_projection(image_embeds)
|
| 1666 |
+
|
| 1667 |
+
text_embeds = text_outputs[1]
|
| 1668 |
+
text_embeds = self.text_projection(text_embeds)
|
| 1669 |
+
|
| 1670 |
+
# normalized features
|
| 1671 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1672 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1673 |
+
|
| 1674 |
+
# cosine similarity as logits
|
| 1675 |
+
logit_scale = self.logit_scale.exp()
|
| 1676 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
|
| 1677 |
+
logits_per_image = logits_per_text.T
|
| 1678 |
+
|
| 1679 |
+
loss = None
|
| 1680 |
+
if return_loss:
|
| 1681 |
+
loss = clip_loss(logits_per_text)
|
| 1682 |
+
|
| 1683 |
+
if not return_dict:
|
| 1684 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
| 1685 |
+
return ((loss,) + output) if loss is not None else output
|
| 1686 |
+
|
| 1687 |
+
return AltCLIPOutput(
|
| 1688 |
+
loss=loss,
|
| 1689 |
+
logits_per_image=logits_per_image,
|
| 1690 |
+
logits_per_text=logits_per_text,
|
| 1691 |
+
text_embeds=text_embeds,
|
| 1692 |
+
image_embeds=image_embeds,
|
| 1693 |
+
text_model_output=text_outputs,
|
| 1694 |
+
vision_model_output=vision_outputs,
|
| 1695 |
+
)
|
| 1696 |
+
|
| 1697 |
+
|
| 1698 |
+
# Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
|
| 1699 |
+
def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
|
| 1700 |
+
"""
|
| 1701 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
|
| 1702 |
+
are ignored. This is modified from fairseq's `utils.make_positions`.
|
| 1703 |
+
|
| 1704 |
+
Args:
|
| 1705 |
+
x: torch.Tensor x:
|
| 1706 |
+
|
| 1707 |
+
Returns: torch.Tensor
|
| 1708 |
+
"""
|
| 1709 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
| 1710 |
+
mask = input_ids.ne(padding_idx).int()
|
| 1711 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
| 1712 |
+
return incremental_indices.long() + padding_idx
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/altclip/processing_altclip.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 WenXiang ZhongzhiCheng LedellWu LiuGuang BoWenZhang 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 |
+
"""
|
| 16 |
+
Image/Text processor class for AltCLIP
|
| 17 |
+
"""
|
| 18 |
+
import warnings
|
| 19 |
+
|
| 20 |
+
from ...processing_utils import ProcessorMixin
|
| 21 |
+
from ...tokenization_utils_base import BatchEncoding
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class AltCLIPProcessor(ProcessorMixin):
|
| 25 |
+
r"""
|
| 26 |
+
Constructs a AltCLIP processor which wraps a CLIP image processor and a XLM-Roberta tokenizer into a single
|
| 27 |
+
processor.
|
| 28 |
+
|
| 29 |
+
[`AltCLIPProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`XLMRobertaTokenizerFast`]. See
|
| 30 |
+
the [`~AltCLIPProcessor.__call__`] and [`~AltCLIPProcessor.decode`] for more information.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
image_processor ([`CLIPImageProcessor`]):
|
| 34 |
+
The image processor is a required input.
|
| 35 |
+
tokenizer ([`XLMRobertaTokenizerFast`]):
|
| 36 |
+
The tokenizer is a required input.
|
| 37 |
+
"""
|
| 38 |
+
attributes = ["image_processor", "tokenizer"]
|
| 39 |
+
image_processor_class = "CLIPImageProcessor"
|
| 40 |
+
tokenizer_class = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")
|
| 41 |
+
|
| 42 |
+
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
|
| 43 |
+
if "feature_extractor" in kwargs:
|
| 44 |
+
warnings.warn(
|
| 45 |
+
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
|
| 46 |
+
" instead.",
|
| 47 |
+
FutureWarning,
|
| 48 |
+
)
|
| 49 |
+
feature_extractor = kwargs.pop("feature_extractor")
|
| 50 |
+
|
| 51 |
+
image_processor = image_processor if image_processor is not None else feature_extractor
|
| 52 |
+
if image_processor is None:
|
| 53 |
+
raise ValueError("You need to specify an `image_processor`.")
|
| 54 |
+
if tokenizer is None:
|
| 55 |
+
raise ValueError("You need to specify a `tokenizer`.")
|
| 56 |
+
|
| 57 |
+
super().__init__(image_processor, tokenizer)
|
| 58 |
+
|
| 59 |
+
def __call__(self, text=None, images=None, return_tensors=None, **kwargs):
|
| 60 |
+
"""
|
| 61 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
| 62 |
+
and `kwargs` arguments to XLMRobertaTokenizerFast's [`~XLMRobertaTokenizerFast.__call__`] if `text` is not
|
| 63 |
+
`None` to encode the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
|
| 64 |
+
CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
|
| 65 |
+
of the above two methods for more information.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
| 69 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 70 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 71 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 72 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
| 73 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 74 |
+
tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
|
| 75 |
+
number of channels, H and W are image height and width.
|
| 76 |
+
|
| 77 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 78 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 79 |
+
|
| 80 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 81 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 82 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 83 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
[`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
|
| 87 |
+
|
| 88 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 89 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 90 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 91 |
+
`None`).
|
| 92 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
if text is None and images is None:
|
| 96 |
+
raise ValueError("You have to specify either text or images. Both cannot be none.")
|
| 97 |
+
|
| 98 |
+
if text is not None:
|
| 99 |
+
encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)
|
| 100 |
+
|
| 101 |
+
if images is not None:
|
| 102 |
+
image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs)
|
| 103 |
+
|
| 104 |
+
if text is not None and images is not None:
|
| 105 |
+
encoding["pixel_values"] = image_features.pixel_values
|
| 106 |
+
return encoding
|
| 107 |
+
elif text is not None:
|
| 108 |
+
return encoding
|
| 109 |
+
else:
|
| 110 |
+
return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
|
| 111 |
+
|
| 112 |
+
def batch_decode(self, *args, **kwargs):
|
| 113 |
+
"""
|
| 114 |
+
This method forwards all its arguments to XLMRobertaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`].
|
| 115 |
+
Please refer to the docstring of this method for more information.
|
| 116 |
+
"""
|
| 117 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 118 |
+
|
| 119 |
+
def decode(self, *args, **kwargs):
|
| 120 |
+
"""
|
| 121 |
+
This method forwards all its arguments to XLMRobertaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please
|
| 122 |
+
refer to the docstring of this method for more information.
|
| 123 |
+
"""
|
| 124 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def model_input_names(self):
|
| 128 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 129 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 130 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/audio_spectrogram_transformer/__init__.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_import_structure = {
|
| 20 |
+
"configuration_audio_spectrogram_transformer": [
|
| 21 |
+
"AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
| 22 |
+
"ASTConfig",
|
| 23 |
+
]
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
if not is_torch_available():
|
| 28 |
+
raise OptionalDependencyNotAvailable()
|
| 29 |
+
except OptionalDependencyNotAvailable:
|
| 30 |
+
pass
|
| 31 |
+
else:
|
| 32 |
+
_import_structure["modeling_audio_spectrogram_transformer"] = [
|
| 33 |
+
"AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
|
| 34 |
+
"ASTForAudioClassification",
|
| 35 |
+
"ASTModel",
|
| 36 |
+
"ASTPreTrainedModel",
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
if not is_speech_available():
|
| 41 |
+
raise OptionalDependencyNotAvailable()
|
| 42 |
+
except OptionalDependencyNotAvailable:
|
| 43 |
+
pass
|
| 44 |
+
else:
|
| 45 |
+
_import_structure["feature_extraction_audio_spectrogram_transformer"] = ["ASTFeatureExtractor"]
|
| 46 |
+
|
| 47 |
+
if TYPE_CHECKING:
|
| 48 |
+
from .configuration_audio_spectrogram_transformer import (
|
| 49 |
+
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
| 50 |
+
ASTConfig,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
if not is_torch_available():
|
| 55 |
+
raise OptionalDependencyNotAvailable()
|
| 56 |
+
except OptionalDependencyNotAvailable:
|
| 57 |
+
pass
|
| 58 |
+
else:
|
| 59 |
+
from .modeling_audio_spectrogram_transformer import (
|
| 60 |
+
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
|
| 61 |
+
ASTForAudioClassification,
|
| 62 |
+
ASTModel,
|
| 63 |
+
ASTPreTrainedModel,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
if not is_speech_available():
|
| 68 |
+
raise OptionalDependencyNotAvailable()
|
| 69 |
+
except OptionalDependencyNotAvailable:
|
| 70 |
+
pass
|
| 71 |
+
else:
|
| 72 |
+
from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
else:
|
| 76 |
+
import sys
|
| 77 |
+
|
| 78 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 Google AI and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Audio Spectogram Transformer (AST) model configuration"""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PretrainedConfig
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
| 25 |
+
"MIT/ast-finetuned-audioset-10-10-0.4593": (
|
| 26 |
+
"https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json"
|
| 27 |
+
),
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ASTConfig(PretrainedConfig):
|
| 32 |
+
r"""
|
| 33 |
+
This is the configuration class to store the configuration of a [`ASTModel`]. It is used to instantiate an AST
|
| 34 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 35 |
+
defaults will yield a similar configuration to that of the AST
|
| 36 |
+
[MIT/ast-finetuned-audioset-10-10-0.4593](https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593)
|
| 37 |
+
architecture.
|
| 38 |
+
|
| 39 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 40 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 44 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 45 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 46 |
+
Number of hidden layers in the Transformer encoder.
|
| 47 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 48 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 49 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 50 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 51 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 52 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 53 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 54 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 55 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 56 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 57 |
+
The dropout ratio for the attention probabilities.
|
| 58 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 59 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 60 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 61 |
+
The epsilon used by the layer normalization layers.
|
| 62 |
+
patch_size (`int`, *optional*, defaults to `16`):
|
| 63 |
+
The size (resolution) of each patch.
|
| 64 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 65 |
+
Whether to add a bias to the queries, keys and values.
|
| 66 |
+
frequency_stride (`int`, *optional*, defaults to 10):
|
| 67 |
+
Frequency stride to use when patchifying the spectrograms.
|
| 68 |
+
time_stride (`int`, *optional*, defaults to 10):
|
| 69 |
+
Temporal stride to use when patchifying the spectrograms.
|
| 70 |
+
max_length (`int`, *optional*, defaults to 1024):
|
| 71 |
+
Temporal dimension of the spectrograms.
|
| 72 |
+
num_mel_bins (`int`, *optional*, defaults to 128):
|
| 73 |
+
Frequency dimension of the spectrograms (number of Mel-frequency bins).
|
| 74 |
+
|
| 75 |
+
Example:
|
| 76 |
+
|
| 77 |
+
```python
|
| 78 |
+
>>> from transformers import ASTConfig, ASTModel
|
| 79 |
+
|
| 80 |
+
>>> # Initializing a AST MIT/ast-finetuned-audioset-10-10-0.4593 style configuration
|
| 81 |
+
>>> configuration = ASTConfig()
|
| 82 |
+
|
| 83 |
+
>>> # Initializing a model (with random weights) from the MIT/ast-finetuned-audioset-10-10-0.4593 style configuration
|
| 84 |
+
>>> model = ASTModel(configuration)
|
| 85 |
+
|
| 86 |
+
>>> # Accessing the model configuration
|
| 87 |
+
>>> configuration = model.config
|
| 88 |
+
```"""
|
| 89 |
+
model_type = "audio-spectrogram-transformer"
|
| 90 |
+
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
hidden_size=768,
|
| 94 |
+
num_hidden_layers=12,
|
| 95 |
+
num_attention_heads=12,
|
| 96 |
+
intermediate_size=3072,
|
| 97 |
+
hidden_act="gelu",
|
| 98 |
+
hidden_dropout_prob=0.0,
|
| 99 |
+
attention_probs_dropout_prob=0.0,
|
| 100 |
+
initializer_range=0.02,
|
| 101 |
+
layer_norm_eps=1e-12,
|
| 102 |
+
patch_size=16,
|
| 103 |
+
qkv_bias=True,
|
| 104 |
+
frequency_stride=10,
|
| 105 |
+
time_stride=10,
|
| 106 |
+
max_length=1024,
|
| 107 |
+
num_mel_bins=128,
|
| 108 |
+
**kwargs,
|
| 109 |
+
):
|
| 110 |
+
super().__init__(**kwargs)
|
| 111 |
+
|
| 112 |
+
self.hidden_size = hidden_size
|
| 113 |
+
self.num_hidden_layers = num_hidden_layers
|
| 114 |
+
self.num_attention_heads = num_attention_heads
|
| 115 |
+
self.intermediate_size = intermediate_size
|
| 116 |
+
self.hidden_act = hidden_act
|
| 117 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 118 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 119 |
+
self.initializer_range = initializer_range
|
| 120 |
+
self.layer_norm_eps = layer_norm_eps
|
| 121 |
+
self.patch_size = patch_size
|
| 122 |
+
self.qkv_bias = qkv_bias
|
| 123 |
+
self.frequency_stride = frequency_stride
|
| 124 |
+
self.time_stride = time_stride
|
| 125 |
+
self.max_length = max_length
|
| 126 |
+
self.num_mel_bins = num_mel_bins
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/audio_spectrogram_transformer/convert_audio_spectrogram_transformer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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 Audio Spectrogram Transformer checkpoints from the original repository. URL: https://github.com/YuanGongND/ast"""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import json
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torchaudio
|
| 24 |
+
from datasets import load_dataset
|
| 25 |
+
from huggingface_hub import hf_hub_download
|
| 26 |
+
|
| 27 |
+
from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification
|
| 28 |
+
from transformers.utils import logging
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logging.set_verbosity_info()
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_audio_spectrogram_transformer_config(model_name):
|
| 36 |
+
config = ASTConfig()
|
| 37 |
+
|
| 38 |
+
if "10-10" in model_name:
|
| 39 |
+
pass
|
| 40 |
+
elif "speech-commands" in model_name:
|
| 41 |
+
config.max_length = 128
|
| 42 |
+
elif "12-12" in model_name:
|
| 43 |
+
config.time_stride = 12
|
| 44 |
+
config.frequency_stride = 12
|
| 45 |
+
elif "14-14" in model_name:
|
| 46 |
+
config.time_stride = 14
|
| 47 |
+
config.frequency_stride = 14
|
| 48 |
+
elif "16-16" in model_name:
|
| 49 |
+
config.time_stride = 16
|
| 50 |
+
config.frequency_stride = 16
|
| 51 |
+
else:
|
| 52 |
+
raise ValueError("Model not supported")
|
| 53 |
+
|
| 54 |
+
repo_id = "huggingface/label-files"
|
| 55 |
+
if "speech-commands" in model_name:
|
| 56 |
+
config.num_labels = 35
|
| 57 |
+
filename = "speech-commands-v2-id2label.json"
|
| 58 |
+
else:
|
| 59 |
+
config.num_labels = 527
|
| 60 |
+
filename = "audioset-id2label.json"
|
| 61 |
+
|
| 62 |
+
id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
|
| 63 |
+
id2label = {int(k): v for k, v in id2label.items()}
|
| 64 |
+
config.id2label = id2label
|
| 65 |
+
config.label2id = {v: k for k, v in id2label.items()}
|
| 66 |
+
|
| 67 |
+
return config
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def rename_key(name):
|
| 71 |
+
if "module.v" in name:
|
| 72 |
+
name = name.replace("module.v", "audio_spectrogram_transformer")
|
| 73 |
+
if "cls_token" in name:
|
| 74 |
+
name = name.replace("cls_token", "embeddings.cls_token")
|
| 75 |
+
if "dist_token" in name:
|
| 76 |
+
name = name.replace("dist_token", "embeddings.distillation_token")
|
| 77 |
+
if "pos_embed" in name:
|
| 78 |
+
name = name.replace("pos_embed", "embeddings.position_embeddings")
|
| 79 |
+
if "patch_embed.proj" in name:
|
| 80 |
+
name = name.replace("patch_embed.proj", "embeddings.patch_embeddings.projection")
|
| 81 |
+
# transformer blocks
|
| 82 |
+
if "blocks" in name:
|
| 83 |
+
name = name.replace("blocks", "encoder.layer")
|
| 84 |
+
if "attn.proj" in name:
|
| 85 |
+
name = name.replace("attn.proj", "attention.output.dense")
|
| 86 |
+
if "attn" in name:
|
| 87 |
+
name = name.replace("attn", "attention.self")
|
| 88 |
+
if "norm1" in name:
|
| 89 |
+
name = name.replace("norm1", "layernorm_before")
|
| 90 |
+
if "norm2" in name:
|
| 91 |
+
name = name.replace("norm2", "layernorm_after")
|
| 92 |
+
if "mlp.fc1" in name:
|
| 93 |
+
name = name.replace("mlp.fc1", "intermediate.dense")
|
| 94 |
+
if "mlp.fc2" in name:
|
| 95 |
+
name = name.replace("mlp.fc2", "output.dense")
|
| 96 |
+
# final layernorm
|
| 97 |
+
if "audio_spectrogram_transformer.norm" in name:
|
| 98 |
+
name = name.replace("audio_spectrogram_transformer.norm", "audio_spectrogram_transformer.layernorm")
|
| 99 |
+
# classifier head
|
| 100 |
+
if "module.mlp_head.0" in name:
|
| 101 |
+
name = name.replace("module.mlp_head.0", "classifier.layernorm")
|
| 102 |
+
if "module.mlp_head.1" in name:
|
| 103 |
+
name = name.replace("module.mlp_head.1", "classifier.dense")
|
| 104 |
+
|
| 105 |
+
return name
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def convert_state_dict(orig_state_dict, config):
|
| 109 |
+
for key in orig_state_dict.copy().keys():
|
| 110 |
+
val = orig_state_dict.pop(key)
|
| 111 |
+
|
| 112 |
+
if "qkv" in key:
|
| 113 |
+
key_split = key.split(".")
|
| 114 |
+
layer_num = int(key_split[3])
|
| 115 |
+
dim = config.hidden_size
|
| 116 |
+
if "weight" in key:
|
| 117 |
+
orig_state_dict[
|
| 118 |
+
f"audio_spectrogram_transformer.encoder.layer.{layer_num}.attention.attention.query.weight"
|
| 119 |
+
] = val[:dim, :]
|
| 120 |
+
orig_state_dict[
|
| 121 |
+
f"audio_spectrogram_transformer.encoder.layer.{layer_num}.attention.attention.key.weight"
|
| 122 |
+
] = val[dim : dim * 2, :]
|
| 123 |
+
orig_state_dict[
|
| 124 |
+
f"audio_spectrogram_transformer.encoder.layer.{layer_num}.attention.attention.value.weight"
|
| 125 |
+
] = val[-dim:, :]
|
| 126 |
+
else:
|
| 127 |
+
orig_state_dict[
|
| 128 |
+
f"audio_spectrogram_transformer.encoder.layer.{layer_num}.attention.attention.query.bias"
|
| 129 |
+
] = val[:dim]
|
| 130 |
+
orig_state_dict[
|
| 131 |
+
f"audio_spectrogram_transformer.encoder.layer.{layer_num}.attention.attention.key.bias"
|
| 132 |
+
] = val[dim : dim * 2]
|
| 133 |
+
orig_state_dict[
|
| 134 |
+
f"audio_spectrogram_transformer.encoder.layer.{layer_num}.attention.attention.value.bias"
|
| 135 |
+
] = val[-dim:]
|
| 136 |
+
else:
|
| 137 |
+
orig_state_dict[rename_key(key)] = val
|
| 138 |
+
|
| 139 |
+
return orig_state_dict
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def remove_keys(state_dict):
|
| 143 |
+
ignore_keys = [
|
| 144 |
+
"module.v.head.weight",
|
| 145 |
+
"module.v.head.bias",
|
| 146 |
+
"module.v.head_dist.weight",
|
| 147 |
+
"module.v.head_dist.bias",
|
| 148 |
+
]
|
| 149 |
+
for k in ignore_keys:
|
| 150 |
+
state_dict.pop(k, None)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@torch.no_grad()
|
| 154 |
+
def convert_audio_spectrogram_transformer_checkpoint(model_name, pytorch_dump_folder_path, push_to_hub=False):
|
| 155 |
+
"""
|
| 156 |
+
Copy/paste/tweak model's weights to our Audio Spectrogram Transformer structure.
|
| 157 |
+
"""
|
| 158 |
+
config = get_audio_spectrogram_transformer_config(model_name)
|
| 159 |
+
|
| 160 |
+
model_name_to_url = {
|
| 161 |
+
"ast-finetuned-audioset-10-10-0.4593": (
|
| 162 |
+
"https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1"
|
| 163 |
+
),
|
| 164 |
+
"ast-finetuned-audioset-10-10-0.450": (
|
| 165 |
+
"https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1"
|
| 166 |
+
),
|
| 167 |
+
"ast-finetuned-audioset-10-10-0.448": (
|
| 168 |
+
"https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1"
|
| 169 |
+
),
|
| 170 |
+
"ast-finetuned-audioset-10-10-0.448-v2": (
|
| 171 |
+
"https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1"
|
| 172 |
+
),
|
| 173 |
+
"ast-finetuned-audioset-12-12-0.447": (
|
| 174 |
+
"https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1"
|
| 175 |
+
),
|
| 176 |
+
"ast-finetuned-audioset-14-14-0.443": (
|
| 177 |
+
"https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1"
|
| 178 |
+
),
|
| 179 |
+
"ast-finetuned-audioset-16-16-0.442": (
|
| 180 |
+
"https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1"
|
| 181 |
+
),
|
| 182 |
+
"ast-finetuned-speech-commands-v2": (
|
| 183 |
+
"https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1"
|
| 184 |
+
),
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
# load original state_dict
|
| 188 |
+
checkpoint_url = model_name_to_url[model_name]
|
| 189 |
+
state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")
|
| 190 |
+
# remove some keys
|
| 191 |
+
remove_keys(state_dict)
|
| 192 |
+
# rename some keys
|
| 193 |
+
new_state_dict = convert_state_dict(state_dict, config)
|
| 194 |
+
|
| 195 |
+
# load 🤗 model
|
| 196 |
+
model = ASTForAudioClassification(config)
|
| 197 |
+
model.eval()
|
| 198 |
+
|
| 199 |
+
model.load_state_dict(new_state_dict)
|
| 200 |
+
|
| 201 |
+
# verify outputs on dummy input
|
| 202 |
+
# source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62
|
| 203 |
+
mean = -4.2677393 if "speech-commands" not in model_name else -6.845978
|
| 204 |
+
std = 4.5689974 if "speech-commands" not in model_name else 5.5654526
|
| 205 |
+
max_length = 1024 if "speech-commands" not in model_name else 128
|
| 206 |
+
feature_extractor = ASTFeatureExtractor(mean=mean, std=std, max_length=max_length)
|
| 207 |
+
|
| 208 |
+
if "speech-commands" in model_name:
|
| 209 |
+
dataset = load_dataset("speech_commands", "v0.02", split="validation")
|
| 210 |
+
waveform = dataset[0]["audio"]["array"]
|
| 211 |
+
else:
|
| 212 |
+
filepath = hf_hub_download(
|
| 213 |
+
repo_id="nielsr/audio-spectogram-transformer-checkpoint",
|
| 214 |
+
filename="sample_audio.flac",
|
| 215 |
+
repo_type="dataset",
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
waveform, _ = torchaudio.load(filepath)
|
| 219 |
+
waveform = waveform.squeeze().numpy()
|
| 220 |
+
|
| 221 |
+
inputs = feature_extractor(waveform, sampling_rate=16000, return_tensors="pt")
|
| 222 |
+
|
| 223 |
+
# forward pass
|
| 224 |
+
outputs = model(**inputs)
|
| 225 |
+
logits = outputs.logits
|
| 226 |
+
|
| 227 |
+
if model_name == "ast-finetuned-audioset-10-10-0.4593":
|
| 228 |
+
expected_slice = torch.tensor([-0.8760, -7.0042, -8.6602])
|
| 229 |
+
elif model_name == "ast-finetuned-audioset-10-10-0.450":
|
| 230 |
+
expected_slice = torch.tensor([-1.1986, -7.0903, -8.2718])
|
| 231 |
+
elif model_name == "ast-finetuned-audioset-10-10-0.448":
|
| 232 |
+
expected_slice = torch.tensor([-2.6128, -8.0080, -9.4344])
|
| 233 |
+
elif model_name == "ast-finetuned-audioset-10-10-0.448-v2":
|
| 234 |
+
expected_slice = torch.tensor([-1.5080, -7.4534, -8.8917])
|
| 235 |
+
elif model_name == "ast-finetuned-audioset-12-12-0.447":
|
| 236 |
+
expected_slice = torch.tensor([-0.5050, -6.5833, -8.0843])
|
| 237 |
+
elif model_name == "ast-finetuned-audioset-14-14-0.443":
|
| 238 |
+
expected_slice = torch.tensor([-0.3826, -7.0336, -8.2413])
|
| 239 |
+
elif model_name == "ast-finetuned-audioset-16-16-0.442":
|
| 240 |
+
expected_slice = torch.tensor([-1.2113, -6.9101, -8.3470])
|
| 241 |
+
elif model_name == "ast-finetuned-speech-commands-v2":
|
| 242 |
+
expected_slice = torch.tensor([6.1589, -8.0566, -8.7984])
|
| 243 |
+
else:
|
| 244 |
+
raise ValueError("Unknown model name")
|
| 245 |
+
if not torch.allclose(logits[0, :3], expected_slice, atol=1e-4):
|
| 246 |
+
raise ValueError("Logits don't match")
|
| 247 |
+
print("Looks ok!")
|
| 248 |
+
|
| 249 |
+
if pytorch_dump_folder_path is not None:
|
| 250 |
+
Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
|
| 251 |
+
print(f"Saving model {model_name} to {pytorch_dump_folder_path}")
|
| 252 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 253 |
+
print(f"Saving feature extractor to {pytorch_dump_folder_path}")
|
| 254 |
+
feature_extractor.save_pretrained(pytorch_dump_folder_path)
|
| 255 |
+
|
| 256 |
+
if push_to_hub:
|
| 257 |
+
print("Pushing model and feature extractor to the hub...")
|
| 258 |
+
model.push_to_hub(f"MIT/{model_name}")
|
| 259 |
+
feature_extractor.push_to_hub(f"MIT/{model_name}")
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
if __name__ == "__main__":
|
| 263 |
+
parser = argparse.ArgumentParser()
|
| 264 |
+
# Required parameters
|
| 265 |
+
parser.add_argument(
|
| 266 |
+
"--model_name",
|
| 267 |
+
default="ast-finetuned-audioset-10-10-0.4593",
|
| 268 |
+
type=str,
|
| 269 |
+
help="Name of the Audio Spectrogram Transformer model you'd like to convert.",
|
| 270 |
+
)
|
| 271 |
+
parser.add_argument(
|
| 272 |
+
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
|
| 273 |
+
)
|
| 274 |
+
parser.add_argument(
|
| 275 |
+
"--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
args = parser.parse_args()
|
| 279 |
+
convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Feature extractor class for Audio Spectrogram Transformer.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from typing import List, Optional, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
import torchaudio.compliance.kaldi as ta_kaldi
|
| 24 |
+
|
| 25 |
+
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
|
| 26 |
+
from ...feature_extraction_utils import BatchFeature
|
| 27 |
+
from ...utils import TensorType, logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ASTFeatureExtractor(SequenceFeatureExtractor):
|
| 34 |
+
r"""
|
| 35 |
+
Constructs a Audio Spectrogram Transformer (AST) feature extractor.
|
| 36 |
+
|
| 37 |
+
This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
|
| 38 |
+
most of the main methods. Users should refer to this superclass for more information regarding those methods.
|
| 39 |
+
|
| 40 |
+
This class extracts mel-filter bank features from raw speech using TorchAudio, pads/truncates them to a fixed
|
| 41 |
+
length and normalizes them using a mean and standard deviation.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
feature_size (`int`, *optional*, defaults to 1):
|
| 45 |
+
The feature dimension of the extracted features.
|
| 46 |
+
sampling_rate (`int`, *optional*, defaults to 16000):
|
| 47 |
+
The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
|
| 48 |
+
num_mel_bins (`int`, *optional*, defaults to 128):
|
| 49 |
+
Number of Mel-frequency bins.
|
| 50 |
+
max_length (`int`, *optional*, defaults to 1024):
|
| 51 |
+
Maximum length to which to pad/truncate the extracted features.
|
| 52 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 53 |
+
Whether or not to normalize the log-Mel features using `mean` and `std`.
|
| 54 |
+
mean (`float`, *optional*, defaults to -4.2677393):
|
| 55 |
+
The mean value used to normalize the log-Mel features. Uses the AudioSet mean by default.
|
| 56 |
+
std (`float`, *optional*, defaults to 4.5689974):
|
| 57 |
+
The standard deviation value used to normalize the log-Mel features. Uses the AudioSet standard deviation
|
| 58 |
+
by default.
|
| 59 |
+
return_attention_mask (`bool`, *optional*, defaults to `False`):
|
| 60 |
+
Whether or not [`~ASTFeatureExtractor.__call__`] should return `attention_mask`.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
model_input_names = ["input_values", "attention_mask"]
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
feature_size=1,
|
| 68 |
+
sampling_rate=16000,
|
| 69 |
+
num_mel_bins=128,
|
| 70 |
+
max_length=1024,
|
| 71 |
+
padding_value=0.0,
|
| 72 |
+
do_normalize=True,
|
| 73 |
+
mean=-4.2677393,
|
| 74 |
+
std=4.5689974,
|
| 75 |
+
return_attention_mask=False,
|
| 76 |
+
**kwargs,
|
| 77 |
+
):
|
| 78 |
+
super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
|
| 79 |
+
self.num_mel_bins = num_mel_bins
|
| 80 |
+
self.max_length = max_length
|
| 81 |
+
self.do_normalize = do_normalize
|
| 82 |
+
self.mean = mean
|
| 83 |
+
self.std = std
|
| 84 |
+
self.return_attention_mask = return_attention_mask
|
| 85 |
+
|
| 86 |
+
def _extract_fbank_features(
|
| 87 |
+
self,
|
| 88 |
+
waveform: np.ndarray,
|
| 89 |
+
max_length: int,
|
| 90 |
+
) -> np.ndarray:
|
| 91 |
+
"""
|
| 92 |
+
Get mel-filter bank features using TorchAudio. Note that TorchAudio requires 16-bit signed integers as inputs
|
| 93 |
+
and hence the waveform should not be normalized before feature extraction.
|
| 94 |
+
"""
|
| 95 |
+
# waveform = waveform * (2**15) # Kaldi compliance: 16-bit signed integers
|
| 96 |
+
waveform = torch.from_numpy(waveform).unsqueeze(0)
|
| 97 |
+
fbank = ta_kaldi.fbank(
|
| 98 |
+
waveform,
|
| 99 |
+
htk_compat=True,
|
| 100 |
+
sample_frequency=self.sampling_rate,
|
| 101 |
+
use_energy=False,
|
| 102 |
+
window_type="hanning",
|
| 103 |
+
num_mel_bins=self.num_mel_bins,
|
| 104 |
+
dither=0.0,
|
| 105 |
+
frame_shift=10,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
n_frames = fbank.shape[0]
|
| 109 |
+
difference = max_length - n_frames
|
| 110 |
+
|
| 111 |
+
# pad or truncate, depending on difference
|
| 112 |
+
if difference > 0:
|
| 113 |
+
pad_module = torch.nn.ZeroPad2d((0, 0, 0, difference))
|
| 114 |
+
fbank = pad_module(fbank)
|
| 115 |
+
elif difference < 0:
|
| 116 |
+
fbank = fbank[0:max_length, :]
|
| 117 |
+
|
| 118 |
+
fbank = fbank.numpy()
|
| 119 |
+
|
| 120 |
+
return fbank
|
| 121 |
+
|
| 122 |
+
def normalize(self, input_values: np.ndarray) -> np.ndarray:
|
| 123 |
+
return (input_values - (self.mean)) / (self.std * 2)
|
| 124 |
+
|
| 125 |
+
def __call__(
|
| 126 |
+
self,
|
| 127 |
+
raw_speech: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],
|
| 128 |
+
sampling_rate: Optional[int] = None,
|
| 129 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 130 |
+
**kwargs,
|
| 131 |
+
) -> BatchFeature:
|
| 132 |
+
"""
|
| 133 |
+
Main method to featurize and prepare for the model one or several sequence(s).
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
raw_speech (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`):
|
| 137 |
+
The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
|
| 138 |
+
values, a list of numpy arrays or a list of list of float values.
|
| 139 |
+
sampling_rate (`int`, *optional*):
|
| 140 |
+
The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
|
| 141 |
+
`sampling_rate` at the forward call to prevent silent errors.
|
| 142 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 143 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 144 |
+
|
| 145 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 146 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 147 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
if sampling_rate is not None:
|
| 151 |
+
if sampling_rate != self.sampling_rate:
|
| 152 |
+
raise ValueError(
|
| 153 |
+
f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
|
| 154 |
+
f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"
|
| 155 |
+
f" {self.sampling_rate} and not {sampling_rate}."
|
| 156 |
+
)
|
| 157 |
+
else:
|
| 158 |
+
logger.warning(
|
| 159 |
+
"It is strongly recommended to pass the `sampling_rate` argument to this function. "
|
| 160 |
+
"Failing to do so can result in silent errors that might be hard to debug."
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
is_batched = bool(
|
| 164 |
+
isinstance(raw_speech, (list, tuple))
|
| 165 |
+
and (isinstance(raw_speech[0], np.ndarray) or isinstance(raw_speech[0], (tuple, list)))
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
if is_batched:
|
| 169 |
+
raw_speech = [np.asarray(speech, dtype=np.float32) for speech in raw_speech]
|
| 170 |
+
elif not is_batched and not isinstance(raw_speech, np.ndarray):
|
| 171 |
+
raw_speech = np.asarray(raw_speech, dtype=np.float32)
|
| 172 |
+
elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
|
| 173 |
+
raw_speech = raw_speech.astype(np.float32)
|
| 174 |
+
|
| 175 |
+
# always return batch
|
| 176 |
+
if not is_batched:
|
| 177 |
+
raw_speech = [raw_speech]
|
| 178 |
+
|
| 179 |
+
# extract fbank features and pad/truncate to max_length
|
| 180 |
+
features = [self._extract_fbank_features(waveform, max_length=self.max_length) for waveform in raw_speech]
|
| 181 |
+
|
| 182 |
+
# convert into BatchFeature
|
| 183 |
+
padded_inputs = BatchFeature({"input_values": features})
|
| 184 |
+
|
| 185 |
+
# make sure list is in array format
|
| 186 |
+
input_values = padded_inputs.get("input_values")
|
| 187 |
+
if isinstance(input_values[0], list):
|
| 188 |
+
padded_inputs["input_values"] = [np.asarray(feature, dtype=np.float32) for feature in input_values]
|
| 189 |
+
|
| 190 |
+
# normalization
|
| 191 |
+
if self.do_normalize:
|
| 192 |
+
padded_inputs["input_values"] = [self.normalize(feature) for feature in input_values]
|
| 193 |
+
|
| 194 |
+
if return_tensors is not None:
|
| 195 |
+
padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
|
| 196 |
+
|
| 197 |
+
return padded_inputs
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py
ADDED
|
@@ -0,0 +1,627 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 MIT 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 Audio Spectrogram Transformer (AST) model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from typing import Dict, List, Optional, Set, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.utils.checkpoint
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 24 |
+
|
| 25 |
+
from ...activations import ACT2FN
|
| 26 |
+
from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, SequenceClassifierOutput
|
| 27 |
+
from ...modeling_utils import PreTrainedModel
|
| 28 |
+
from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
|
| 29 |
+
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 30 |
+
from .configuration_audio_spectrogram_transformer import ASTConfig
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
# General docstring
|
| 36 |
+
_CONFIG_FOR_DOC = "ASTConfig"
|
| 37 |
+
|
| 38 |
+
# Base docstring
|
| 39 |
+
_CHECKPOINT_FOR_DOC = "MIT/ast-finetuned-audioset-10-10-0.4593"
|
| 40 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 1214, 768]
|
| 41 |
+
|
| 42 |
+
# Audio classification docstring
|
| 43 |
+
_SEQ_CLASS_CHECKPOINT = "MIT/ast-finetuned-audioset-10-10-0.4593"
|
| 44 |
+
_SEQ_CLASS_EXPECTED_OUTPUT = "'Speech'"
|
| 45 |
+
_SEQ_CLASS_EXPECTED_LOSS = 0.17
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 49 |
+
"MIT/ast-finetuned-audioset-10-10-0.4593",
|
| 50 |
+
# See all Audio Spectrogram Transformer models at https://huggingface.co/models?filter=ast
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class ASTEmbeddings(nn.Module):
|
| 55 |
+
"""
|
| 56 |
+
Construct the CLS token, position and patch embeddings.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(self, config: ASTConfig) -> None:
|
| 60 |
+
super().__init__()
|
| 61 |
+
|
| 62 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 63 |
+
self.distillation_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 64 |
+
self.patch_embeddings = ASTPatchEmbeddings(config)
|
| 65 |
+
|
| 66 |
+
frequency_out_dimension, time_out_dimension = self.get_shape(config)
|
| 67 |
+
num_patches = frequency_out_dimension * time_out_dimension
|
| 68 |
+
self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 2, config.hidden_size))
|
| 69 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 70 |
+
self.config = config
|
| 71 |
+
|
| 72 |
+
def get_shape(self, config):
|
| 73 |
+
# see Karpathy's cs231n blog on how to calculate the output dimensions
|
| 74 |
+
# https://cs231n.github.io/convolutional-networks/#conv
|
| 75 |
+
frequency_out_dimension = (config.num_mel_bins - config.patch_size) // config.frequency_stride + 1
|
| 76 |
+
time_out_dimension = (config.max_length - config.patch_size) // config.time_stride + 1
|
| 77 |
+
|
| 78 |
+
return frequency_out_dimension, time_out_dimension
|
| 79 |
+
|
| 80 |
+
def forward(self, input_values: torch.Tensor) -> torch.Tensor:
|
| 81 |
+
batch_size = input_values.shape[0]
|
| 82 |
+
embeddings = self.patch_embeddings(input_values)
|
| 83 |
+
|
| 84 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 85 |
+
distillation_tokens = self.distillation_token.expand(batch_size, -1, -1)
|
| 86 |
+
embeddings = torch.cat((cls_tokens, distillation_tokens, embeddings), dim=1)
|
| 87 |
+
embeddings = embeddings + self.position_embeddings
|
| 88 |
+
embeddings = self.dropout(embeddings)
|
| 89 |
+
|
| 90 |
+
return embeddings
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class ASTPatchEmbeddings(nn.Module):
|
| 94 |
+
"""
|
| 95 |
+
This class turns `input_values` into the initial `hidden_states` (patch embeddings) of shape `(batch_size,
|
| 96 |
+
seq_length, hidden_size)` to be consumed by a Transformer.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
def __init__(self, config):
|
| 100 |
+
super().__init__()
|
| 101 |
+
|
| 102 |
+
patch_size = config.patch_size
|
| 103 |
+
frequency_stride = config.frequency_stride
|
| 104 |
+
time_stride = config.time_stride
|
| 105 |
+
|
| 106 |
+
self.projection = nn.Conv2d(
|
| 107 |
+
1, config.hidden_size, kernel_size=(patch_size, patch_size), stride=(frequency_stride, time_stride)
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
def forward(self, input_values: torch.Tensor) -> torch.Tensor:
|
| 111 |
+
input_values = input_values.unsqueeze(1)
|
| 112 |
+
input_values = input_values.transpose(2, 3)
|
| 113 |
+
embeddings = self.projection(input_values).flatten(2).transpose(1, 2)
|
| 114 |
+
return embeddings
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSelfAttention with ViT->AST
|
| 118 |
+
class ASTSelfAttention(nn.Module):
|
| 119 |
+
def __init__(self, config: ASTConfig) -> None:
|
| 120 |
+
super().__init__()
|
| 121 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 122 |
+
raise ValueError(
|
| 123 |
+
f"The hidden size {config.hidden_size,} is not a multiple of the number of attention "
|
| 124 |
+
f"heads {config.num_attention_heads}."
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
self.num_attention_heads = config.num_attention_heads
|
| 128 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 129 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 130 |
+
|
| 131 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 132 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 133 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 134 |
+
|
| 135 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 136 |
+
|
| 137 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 138 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 139 |
+
x = x.view(new_x_shape)
|
| 140 |
+
return x.permute(0, 2, 1, 3)
|
| 141 |
+
|
| 142 |
+
def forward(
|
| 143 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 144 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 145 |
+
mixed_query_layer = self.query(hidden_states)
|
| 146 |
+
|
| 147 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 148 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 149 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 150 |
+
|
| 151 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 152 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 153 |
+
|
| 154 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 155 |
+
|
| 156 |
+
# Normalize the attention scores to probabilities.
|
| 157 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 158 |
+
|
| 159 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 160 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 161 |
+
attention_probs = self.dropout(attention_probs)
|
| 162 |
+
|
| 163 |
+
# Mask heads if we want to
|
| 164 |
+
if head_mask is not None:
|
| 165 |
+
attention_probs = attention_probs * head_mask
|
| 166 |
+
|
| 167 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 168 |
+
|
| 169 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 170 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 171 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 172 |
+
|
| 173 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 174 |
+
|
| 175 |
+
return outputs
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->AST
|
| 179 |
+
class ASTSelfOutput(nn.Module):
|
| 180 |
+
"""
|
| 181 |
+
The residual connection is defined in ASTLayer instead of here (as is the case with other models), due to the
|
| 182 |
+
layernorm applied before each block.
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
def __init__(self, config: ASTConfig) -> None:
|
| 186 |
+
super().__init__()
|
| 187 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 188 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 189 |
+
|
| 190 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 191 |
+
hidden_states = self.dense(hidden_states)
|
| 192 |
+
hidden_states = self.dropout(hidden_states)
|
| 193 |
+
|
| 194 |
+
return hidden_states
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->AST
|
| 198 |
+
class ASTAttention(nn.Module):
|
| 199 |
+
def __init__(self, config: ASTConfig) -> None:
|
| 200 |
+
super().__init__()
|
| 201 |
+
self.attention = ASTSelfAttention(config)
|
| 202 |
+
self.output = ASTSelfOutput(config)
|
| 203 |
+
self.pruned_heads = set()
|
| 204 |
+
|
| 205 |
+
def prune_heads(self, heads: Set[int]) -> None:
|
| 206 |
+
if len(heads) == 0:
|
| 207 |
+
return
|
| 208 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 209 |
+
heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
# Prune linear layers
|
| 213 |
+
self.attention.query = prune_linear_layer(self.attention.query, index)
|
| 214 |
+
self.attention.key = prune_linear_layer(self.attention.key, index)
|
| 215 |
+
self.attention.value = prune_linear_layer(self.attention.value, index)
|
| 216 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 217 |
+
|
| 218 |
+
# Update hyper params and store pruned heads
|
| 219 |
+
self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
|
| 220 |
+
self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
|
| 221 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 222 |
+
|
| 223 |
+
def forward(
|
| 224 |
+
self,
|
| 225 |
+
hidden_states: torch.Tensor,
|
| 226 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 227 |
+
output_attentions: bool = False,
|
| 228 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 229 |
+
self_outputs = self.attention(hidden_states, head_mask, output_attentions)
|
| 230 |
+
|
| 231 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 232 |
+
|
| 233 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 234 |
+
return outputs
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# Copied from transformers.models.vit.modeling_vit.ViTIntermediate with ViT->AST
|
| 238 |
+
class ASTIntermediate(nn.Module):
|
| 239 |
+
def __init__(self, config: ASTConfig) -> None:
|
| 240 |
+
super().__init__()
|
| 241 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 242 |
+
if isinstance(config.hidden_act, str):
|
| 243 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 244 |
+
else:
|
| 245 |
+
self.intermediate_act_fn = config.hidden_act
|
| 246 |
+
|
| 247 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 248 |
+
hidden_states = self.dense(hidden_states)
|
| 249 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 250 |
+
|
| 251 |
+
return hidden_states
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
# Copied from transformers.models.vit.modeling_vit.ViTOutput with ViT->AST
|
| 255 |
+
class ASTOutput(nn.Module):
|
| 256 |
+
def __init__(self, config: ASTConfig) -> None:
|
| 257 |
+
super().__init__()
|
| 258 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 259 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 260 |
+
|
| 261 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 262 |
+
hidden_states = self.dense(hidden_states)
|
| 263 |
+
hidden_states = self.dropout(hidden_states)
|
| 264 |
+
|
| 265 |
+
hidden_states = hidden_states + input_tensor
|
| 266 |
+
|
| 267 |
+
return hidden_states
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
# Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->AST
|
| 271 |
+
class ASTLayer(nn.Module):
|
| 272 |
+
"""This corresponds to the Block class in the timm implementation."""
|
| 273 |
+
|
| 274 |
+
def __init__(self, config: ASTConfig) -> None:
|
| 275 |
+
super().__init__()
|
| 276 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 277 |
+
self.seq_len_dim = 1
|
| 278 |
+
self.attention = ASTAttention(config)
|
| 279 |
+
self.intermediate = ASTIntermediate(config)
|
| 280 |
+
self.output = ASTOutput(config)
|
| 281 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 282 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 283 |
+
|
| 284 |
+
def forward(
|
| 285 |
+
self,
|
| 286 |
+
hidden_states: torch.Tensor,
|
| 287 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 288 |
+
output_attentions: bool = False,
|
| 289 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 290 |
+
self_attention_outputs = self.attention(
|
| 291 |
+
self.layernorm_before(hidden_states), # in AST, layernorm is applied before self-attention
|
| 292 |
+
head_mask,
|
| 293 |
+
output_attentions=output_attentions,
|
| 294 |
+
)
|
| 295 |
+
attention_output = self_attention_outputs[0]
|
| 296 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 297 |
+
|
| 298 |
+
# first residual connection
|
| 299 |
+
hidden_states = attention_output + hidden_states
|
| 300 |
+
|
| 301 |
+
# in AST, layernorm is also applied after self-attention
|
| 302 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 303 |
+
layer_output = self.intermediate(layer_output)
|
| 304 |
+
|
| 305 |
+
# second residual connection is done here
|
| 306 |
+
layer_output = self.output(layer_output, hidden_states)
|
| 307 |
+
|
| 308 |
+
outputs = (layer_output,) + outputs
|
| 309 |
+
|
| 310 |
+
return outputs
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
# Copied from transformers.models.vit.modeling_vit.ViTEncoder with ViT->AST
|
| 314 |
+
class ASTEncoder(nn.Module):
|
| 315 |
+
def __init__(self, config: ASTConfig) -> None:
|
| 316 |
+
super().__init__()
|
| 317 |
+
self.config = config
|
| 318 |
+
self.layer = nn.ModuleList([ASTLayer(config) for _ in range(config.num_hidden_layers)])
|
| 319 |
+
self.gradient_checkpointing = False
|
| 320 |
+
|
| 321 |
+
def forward(
|
| 322 |
+
self,
|
| 323 |
+
hidden_states: torch.Tensor,
|
| 324 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 325 |
+
output_attentions: bool = False,
|
| 326 |
+
output_hidden_states: bool = False,
|
| 327 |
+
return_dict: bool = True,
|
| 328 |
+
) -> Union[tuple, BaseModelOutput]:
|
| 329 |
+
all_hidden_states = () if output_hidden_states else None
|
| 330 |
+
all_self_attentions = () if output_attentions else None
|
| 331 |
+
|
| 332 |
+
for i, layer_module in enumerate(self.layer):
|
| 333 |
+
if output_hidden_states:
|
| 334 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 335 |
+
|
| 336 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 337 |
+
|
| 338 |
+
if self.gradient_checkpointing and self.training:
|
| 339 |
+
|
| 340 |
+
def create_custom_forward(module):
|
| 341 |
+
def custom_forward(*inputs):
|
| 342 |
+
return module(*inputs, output_attentions)
|
| 343 |
+
|
| 344 |
+
return custom_forward
|
| 345 |
+
|
| 346 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 347 |
+
create_custom_forward(layer_module),
|
| 348 |
+
hidden_states,
|
| 349 |
+
layer_head_mask,
|
| 350 |
+
)
|
| 351 |
+
else:
|
| 352 |
+
layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions)
|
| 353 |
+
|
| 354 |
+
hidden_states = layer_outputs[0]
|
| 355 |
+
|
| 356 |
+
if output_attentions:
|
| 357 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 358 |
+
|
| 359 |
+
if output_hidden_states:
|
| 360 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 361 |
+
|
| 362 |
+
if not return_dict:
|
| 363 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
| 364 |
+
return BaseModelOutput(
|
| 365 |
+
last_hidden_state=hidden_states,
|
| 366 |
+
hidden_states=all_hidden_states,
|
| 367 |
+
attentions=all_self_attentions,
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class ASTPreTrainedModel(PreTrainedModel):
|
| 372 |
+
"""
|
| 373 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 374 |
+
models.
|
| 375 |
+
"""
|
| 376 |
+
|
| 377 |
+
config_class = ASTConfig
|
| 378 |
+
base_model_prefix = "audio_spectrogram_transformer"
|
| 379 |
+
main_input_name = "input_values"
|
| 380 |
+
supports_gradient_checkpointing = True
|
| 381 |
+
|
| 382 |
+
# Copied from transformers.models.deit.modeling_deit.DeiTPreTrainedModel._init_weights
|
| 383 |
+
def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
|
| 384 |
+
"""Initialize the weights"""
|
| 385 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 386 |
+
# Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
|
| 387 |
+
# `trunc_normal_cpu` not implemented in `half` issues
|
| 388 |
+
module.weight.data = nn.init.trunc_normal_(
|
| 389 |
+
module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
|
| 390 |
+
).to(module.weight.dtype)
|
| 391 |
+
if module.bias is not None:
|
| 392 |
+
module.bias.data.zero_()
|
| 393 |
+
elif isinstance(module, nn.LayerNorm):
|
| 394 |
+
module.bias.data.zero_()
|
| 395 |
+
module.weight.data.fill_(1.0)
|
| 396 |
+
|
| 397 |
+
# Copied from transformers.models.vit.modeling_vit.ViTPreTrainedModel._set_gradient_checkpointing with ViT->AST
|
| 398 |
+
def _set_gradient_checkpointing(self, module: ASTEncoder, value: bool = False) -> None:
|
| 399 |
+
if isinstance(module, ASTEncoder):
|
| 400 |
+
module.gradient_checkpointing = value
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
AUDIO_SPECTROGRAM_TRANSFORMER_START_DOCSTRING = r"""
|
| 404 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 405 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 406 |
+
behavior.
|
| 407 |
+
|
| 408 |
+
Parameters:
|
| 409 |
+
config ([`ASTConfig`]):
|
| 410 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 411 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 412 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 413 |
+
"""
|
| 414 |
+
|
| 415 |
+
AUDIO_SPECTROGRAM_TRANSFORMER_INPUTS_DOCSTRING = r"""
|
| 416 |
+
Args:
|
| 417 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, max_length, num_mel_bins)`):
|
| 418 |
+
Float values mel features extracted from the raw audio waveform. Raw audio waveform can be obtained by
|
| 419 |
+
loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via
|
| 420 |
+
the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the
|
| 421 |
+
[`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a
|
| 422 |
+
tensor of type `torch.FloatTensor`. See [`~ASTFeatureExtractor.__call__`]
|
| 423 |
+
|
| 424 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 425 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 426 |
+
|
| 427 |
+
- 1 indicates the head is **not masked**,
|
| 428 |
+
- 0 indicates the head is **masked**.
|
| 429 |
+
|
| 430 |
+
output_attentions (`bool`, *optional*):
|
| 431 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 432 |
+
tensors for more detail.
|
| 433 |
+
output_hidden_states (`bool`, *optional*):
|
| 434 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 435 |
+
more detail.
|
| 436 |
+
return_dict (`bool`, *optional*):
|
| 437 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 438 |
+
"""
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
@add_start_docstrings(
|
| 442 |
+
"The bare AST Model transformer outputting raw hidden-states without any specific head on top.",
|
| 443 |
+
AUDIO_SPECTROGRAM_TRANSFORMER_START_DOCSTRING,
|
| 444 |
+
)
|
| 445 |
+
class ASTModel(ASTPreTrainedModel):
|
| 446 |
+
def __init__(self, config: ASTConfig):
|
| 447 |
+
super().__init__(config)
|
| 448 |
+
self.config = config
|
| 449 |
+
|
| 450 |
+
self.embeddings = ASTEmbeddings(config)
|
| 451 |
+
self.encoder = ASTEncoder(config)
|
| 452 |
+
|
| 453 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 454 |
+
|
| 455 |
+
# Initialize weights and apply final processing
|
| 456 |
+
self.post_init()
|
| 457 |
+
|
| 458 |
+
def get_input_embeddings(self) -> ASTPatchEmbeddings:
|
| 459 |
+
return self.embeddings.patch_embeddings
|
| 460 |
+
|
| 461 |
+
def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
|
| 462 |
+
"""
|
| 463 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 464 |
+
class PreTrainedModel
|
| 465 |
+
"""
|
| 466 |
+
for layer, heads in heads_to_prune.items():
|
| 467 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 468 |
+
|
| 469 |
+
@add_start_docstrings_to_model_forward(AUDIO_SPECTROGRAM_TRANSFORMER_INPUTS_DOCSTRING)
|
| 470 |
+
@add_code_sample_docstrings(
|
| 471 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 472 |
+
output_type=BaseModelOutputWithPooling,
|
| 473 |
+
config_class=_CONFIG_FOR_DOC,
|
| 474 |
+
modality="audio",
|
| 475 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 476 |
+
)
|
| 477 |
+
def forward(
|
| 478 |
+
self,
|
| 479 |
+
input_values: Optional[torch.Tensor] = None,
|
| 480 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 481 |
+
output_attentions: Optional[bool] = None,
|
| 482 |
+
output_hidden_states: Optional[bool] = None,
|
| 483 |
+
return_dict: Optional[bool] = None,
|
| 484 |
+
):
|
| 485 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 486 |
+
output_hidden_states = (
|
| 487 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 488 |
+
)
|
| 489 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 490 |
+
|
| 491 |
+
if input_values is None:
|
| 492 |
+
raise ValueError("You have to specify input_values")
|
| 493 |
+
|
| 494 |
+
# Prepare head mask if needed
|
| 495 |
+
# 1.0 in head_mask indicate we keep the head
|
| 496 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 497 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 498 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 499 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 500 |
+
|
| 501 |
+
embedding_output = self.embeddings(input_values)
|
| 502 |
+
|
| 503 |
+
encoder_outputs = self.encoder(
|
| 504 |
+
embedding_output,
|
| 505 |
+
head_mask=head_mask,
|
| 506 |
+
output_attentions=output_attentions,
|
| 507 |
+
output_hidden_states=output_hidden_states,
|
| 508 |
+
return_dict=return_dict,
|
| 509 |
+
)
|
| 510 |
+
sequence_output = encoder_outputs[0]
|
| 511 |
+
sequence_output = self.layernorm(sequence_output)
|
| 512 |
+
|
| 513 |
+
pooled_output = (sequence_output[:, 0] + sequence_output[:, 1]) / 2
|
| 514 |
+
|
| 515 |
+
if not return_dict:
|
| 516 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 517 |
+
|
| 518 |
+
return BaseModelOutputWithPooling(
|
| 519 |
+
last_hidden_state=sequence_output,
|
| 520 |
+
pooler_output=pooled_output,
|
| 521 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 522 |
+
attentions=encoder_outputs.attentions,
|
| 523 |
+
)
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
class ASTMLPHead(nn.Module):
|
| 527 |
+
def __init__(self, config: ASTConfig):
|
| 528 |
+
super().__init__()
|
| 529 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 530 |
+
self.dense = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 531 |
+
|
| 532 |
+
def forward(self, hidden_state):
|
| 533 |
+
hidden_state = self.layernorm(hidden_state)
|
| 534 |
+
hidden_state = self.dense(hidden_state)
|
| 535 |
+
return hidden_state
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
@add_start_docstrings(
|
| 539 |
+
"""
|
| 540 |
+
Audio Spectrogram Transformer model with an audio classification head on top (a linear layer on top of the pooled
|
| 541 |
+
output) e.g. for datasets like AudioSet, Speech Commands v2.
|
| 542 |
+
""",
|
| 543 |
+
AUDIO_SPECTROGRAM_TRANSFORMER_START_DOCSTRING,
|
| 544 |
+
)
|
| 545 |
+
class ASTForAudioClassification(ASTPreTrainedModel):
|
| 546 |
+
def __init__(self, config: ASTConfig) -> None:
|
| 547 |
+
super().__init__(config)
|
| 548 |
+
|
| 549 |
+
self.num_labels = config.num_labels
|
| 550 |
+
self.audio_spectrogram_transformer = ASTModel(config)
|
| 551 |
+
|
| 552 |
+
# Classifier head
|
| 553 |
+
self.classifier = ASTMLPHead(config)
|
| 554 |
+
|
| 555 |
+
# Initialize weights and apply final processing
|
| 556 |
+
self.post_init()
|
| 557 |
+
|
| 558 |
+
@add_start_docstrings_to_model_forward(AUDIO_SPECTROGRAM_TRANSFORMER_INPUTS_DOCSTRING)
|
| 559 |
+
@add_code_sample_docstrings(
|
| 560 |
+
checkpoint=_SEQ_CLASS_CHECKPOINT,
|
| 561 |
+
output_type=SequenceClassifierOutput,
|
| 562 |
+
config_class=_CONFIG_FOR_DOC,
|
| 563 |
+
modality="audio",
|
| 564 |
+
expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
|
| 565 |
+
expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
|
| 566 |
+
)
|
| 567 |
+
def forward(
|
| 568 |
+
self,
|
| 569 |
+
input_values: Optional[torch.Tensor] = None,
|
| 570 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 571 |
+
labels: Optional[torch.Tensor] = None,
|
| 572 |
+
output_attentions: Optional[bool] = None,
|
| 573 |
+
output_hidden_states: Optional[bool] = None,
|
| 574 |
+
return_dict: Optional[bool] = None,
|
| 575 |
+
) -> Union[tuple, SequenceClassifierOutput]:
|
| 576 |
+
r"""
|
| 577 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 578 |
+
Labels for computing the audio classification/regression loss. Indices should be in `[0, ...,
|
| 579 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 580 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 581 |
+
"""
|
| 582 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 583 |
+
|
| 584 |
+
outputs = self.audio_spectrogram_transformer(
|
| 585 |
+
input_values,
|
| 586 |
+
head_mask=head_mask,
|
| 587 |
+
output_attentions=output_attentions,
|
| 588 |
+
output_hidden_states=output_hidden_states,
|
| 589 |
+
return_dict=return_dict,
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
pooled_output = outputs[1]
|
| 593 |
+
logits = self.classifier(pooled_output)
|
| 594 |
+
|
| 595 |
+
loss = None
|
| 596 |
+
if labels is not None:
|
| 597 |
+
if self.config.problem_type is None:
|
| 598 |
+
if self.num_labels == 1:
|
| 599 |
+
self.config.problem_type = "regression"
|
| 600 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 601 |
+
self.config.problem_type = "single_label_classification"
|
| 602 |
+
else:
|
| 603 |
+
self.config.problem_type = "multi_label_classification"
|
| 604 |
+
|
| 605 |
+
if self.config.problem_type == "regression":
|
| 606 |
+
loss_fct = MSELoss()
|
| 607 |
+
if self.num_labels == 1:
|
| 608 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 609 |
+
else:
|
| 610 |
+
loss = loss_fct(logits, labels)
|
| 611 |
+
elif self.config.problem_type == "single_label_classification":
|
| 612 |
+
loss_fct = CrossEntropyLoss()
|
| 613 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 614 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 615 |
+
loss_fct = BCEWithLogitsLoss()
|
| 616 |
+
loss = loss_fct(logits, labels)
|
| 617 |
+
|
| 618 |
+
if not return_dict:
|
| 619 |
+
output = (logits,) + outputs[2:]
|
| 620 |
+
return ((loss,) + output) if loss is not None else output
|
| 621 |
+
|
| 622 |
+
return SequenceClassifierOutput(
|
| 623 |
+
loss=loss,
|
| 624 |
+
logits=logits,
|
| 625 |
+
hidden_states=outputs.hidden_states,
|
| 626 |
+
attentions=outputs.attentions,
|
| 627 |
+
)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/__init__.py
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ...utils import (
|
| 18 |
+
OptionalDependencyNotAvailable,
|
| 19 |
+
_LazyModule,
|
| 20 |
+
is_flax_available,
|
| 21 |
+
is_tf_available,
|
| 22 |
+
is_torch_available,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
_import_structure = {
|
| 27 |
+
"auto_factory": ["get_values"],
|
| 28 |
+
"configuration_auto": ["ALL_PRETRAINED_CONFIG_ARCHIVE_MAP", "CONFIG_MAPPING", "MODEL_NAMES_MAPPING", "AutoConfig"],
|
| 29 |
+
"feature_extraction_auto": ["FEATURE_EXTRACTOR_MAPPING", "AutoFeatureExtractor"],
|
| 30 |
+
"image_processing_auto": ["IMAGE_PROCESSOR_MAPPING", "AutoImageProcessor"],
|
| 31 |
+
"processing_auto": ["PROCESSOR_MAPPING", "AutoProcessor"],
|
| 32 |
+
"tokenization_auto": ["TOKENIZER_MAPPING", "AutoTokenizer"],
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
if not is_torch_available():
|
| 37 |
+
raise OptionalDependencyNotAvailable()
|
| 38 |
+
except OptionalDependencyNotAvailable:
|
| 39 |
+
pass
|
| 40 |
+
else:
|
| 41 |
+
_import_structure["modeling_auto"] = [
|
| 42 |
+
"MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING",
|
| 43 |
+
"MODEL_FOR_AUDIO_XVECTOR_MAPPING",
|
| 44 |
+
"MODEL_FOR_BACKBONE_MAPPING",
|
| 45 |
+
"MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING",
|
| 46 |
+
"MODEL_FOR_CAUSAL_LM_MAPPING",
|
| 47 |
+
"MODEL_FOR_CTC_MAPPING",
|
| 48 |
+
"MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING",
|
| 49 |
+
"MODEL_FOR_DEPTH_ESTIMATION_MAPPING",
|
| 50 |
+
"MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING",
|
| 51 |
+
"MODEL_FOR_IMAGE_SEGMENTATION_MAPPING",
|
| 52 |
+
"MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING",
|
| 53 |
+
"MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING",
|
| 54 |
+
"MODEL_FOR_MASKED_LM_MAPPING",
|
| 55 |
+
"MODEL_FOR_MASK_GENERATION_MAPPING",
|
| 56 |
+
"MODEL_FOR_MULTIPLE_CHOICE_MAPPING",
|
| 57 |
+
"MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING",
|
| 58 |
+
"MODEL_FOR_OBJECT_DETECTION_MAPPING",
|
| 59 |
+
"MODEL_FOR_PRETRAINING_MAPPING",
|
| 60 |
+
"MODEL_FOR_QUESTION_ANSWERING_MAPPING",
|
| 61 |
+
"MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING",
|
| 62 |
+
"MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING",
|
| 63 |
+
"MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING",
|
| 64 |
+
"MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING",
|
| 65 |
+
"MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING",
|
| 66 |
+
"MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING",
|
| 67 |
+
"MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING",
|
| 68 |
+
"MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING",
|
| 69 |
+
"MODEL_FOR_VISION_2_SEQ_MAPPING",
|
| 70 |
+
"MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING",
|
| 71 |
+
"MODEL_MAPPING",
|
| 72 |
+
"MODEL_WITH_LM_HEAD_MAPPING",
|
| 73 |
+
"MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING",
|
| 74 |
+
"MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING",
|
| 75 |
+
"AutoModel",
|
| 76 |
+
"AutoBackbone",
|
| 77 |
+
"AutoModelForAudioClassification",
|
| 78 |
+
"AutoModelForAudioFrameClassification",
|
| 79 |
+
"AutoModelForAudioXVector",
|
| 80 |
+
"AutoModelForCausalLM",
|
| 81 |
+
"AutoModelForCTC",
|
| 82 |
+
"AutoModelForDepthEstimation",
|
| 83 |
+
"AutoModelForImageClassification",
|
| 84 |
+
"AutoModelForImageSegmentation",
|
| 85 |
+
"AutoModelForInstanceSegmentation",
|
| 86 |
+
"AutoModelForMaskGeneration",
|
| 87 |
+
"AutoModelForMaskedImageModeling",
|
| 88 |
+
"AutoModelForMaskedLM",
|
| 89 |
+
"AutoModelForMultipleChoice",
|
| 90 |
+
"AutoModelForNextSentencePrediction",
|
| 91 |
+
"AutoModelForObjectDetection",
|
| 92 |
+
"AutoModelForPreTraining",
|
| 93 |
+
"AutoModelForQuestionAnswering",
|
| 94 |
+
"AutoModelForSemanticSegmentation",
|
| 95 |
+
"AutoModelForSeq2SeqLM",
|
| 96 |
+
"AutoModelForSequenceClassification",
|
| 97 |
+
"AutoModelForSpeechSeq2Seq",
|
| 98 |
+
"AutoModelForTableQuestionAnswering",
|
| 99 |
+
"AutoModelForTokenClassification",
|
| 100 |
+
"AutoModelForUniversalSegmentation",
|
| 101 |
+
"AutoModelForVideoClassification",
|
| 102 |
+
"AutoModelForVision2Seq",
|
| 103 |
+
"AutoModelForVisualQuestionAnswering",
|
| 104 |
+
"AutoModelForDocumentQuestionAnswering",
|
| 105 |
+
"AutoModelWithLMHead",
|
| 106 |
+
"AutoModelForZeroShotImageClassification",
|
| 107 |
+
"AutoModelForZeroShotObjectDetection",
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
if not is_tf_available():
|
| 112 |
+
raise OptionalDependencyNotAvailable()
|
| 113 |
+
except OptionalDependencyNotAvailable:
|
| 114 |
+
pass
|
| 115 |
+
else:
|
| 116 |
+
_import_structure["modeling_tf_auto"] = [
|
| 117 |
+
"TF_MODEL_FOR_CAUSAL_LM_MAPPING",
|
| 118 |
+
"TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING",
|
| 119 |
+
"TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING",
|
| 120 |
+
"TF_MODEL_FOR_MASKED_LM_MAPPING",
|
| 121 |
+
"TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING",
|
| 122 |
+
"TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING",
|
| 123 |
+
"TF_MODEL_FOR_PRETRAINING_MAPPING",
|
| 124 |
+
"TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING",
|
| 125 |
+
"TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING",
|
| 126 |
+
"TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING",
|
| 127 |
+
"TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING",
|
| 128 |
+
"TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING",
|
| 129 |
+
"TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING",
|
| 130 |
+
"TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING",
|
| 131 |
+
"TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING",
|
| 132 |
+
"TF_MODEL_FOR_VISION_2_SEQ_MAPPING",
|
| 133 |
+
"TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING",
|
| 134 |
+
"TF_MODEL_MAPPING",
|
| 135 |
+
"TF_MODEL_WITH_LM_HEAD_MAPPING",
|
| 136 |
+
"TFAutoModel",
|
| 137 |
+
"TFAutoModelForCausalLM",
|
| 138 |
+
"TFAutoModelForImageClassification",
|
| 139 |
+
"TFAutoModelForMaskedLM",
|
| 140 |
+
"TFAutoModelForMultipleChoice",
|
| 141 |
+
"TFAutoModelForNextSentencePrediction",
|
| 142 |
+
"TFAutoModelForPreTraining",
|
| 143 |
+
"TFAutoModelForDocumentQuestionAnswering",
|
| 144 |
+
"TFAutoModelForQuestionAnswering",
|
| 145 |
+
"TFAutoModelForSemanticSegmentation",
|
| 146 |
+
"TFAutoModelForSeq2SeqLM",
|
| 147 |
+
"TFAutoModelForSequenceClassification",
|
| 148 |
+
"TFAutoModelForSpeechSeq2Seq",
|
| 149 |
+
"TFAutoModelForTableQuestionAnswering",
|
| 150 |
+
"TFAutoModelForTokenClassification",
|
| 151 |
+
"TFAutoModelForVision2Seq",
|
| 152 |
+
"TFAutoModelForZeroShotImageClassification",
|
| 153 |
+
"TFAutoModelWithLMHead",
|
| 154 |
+
]
|
| 155 |
+
|
| 156 |
+
try:
|
| 157 |
+
if not is_flax_available():
|
| 158 |
+
raise OptionalDependencyNotAvailable()
|
| 159 |
+
except OptionalDependencyNotAvailable:
|
| 160 |
+
pass
|
| 161 |
+
else:
|
| 162 |
+
_import_structure["modeling_flax_auto"] = [
|
| 163 |
+
"FLAX_MODEL_FOR_CAUSAL_LM_MAPPING",
|
| 164 |
+
"FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING",
|
| 165 |
+
"FLAX_MODEL_FOR_MASKED_LM_MAPPING",
|
| 166 |
+
"FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING",
|
| 167 |
+
"FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING",
|
| 168 |
+
"FLAX_MODEL_FOR_PRETRAINING_MAPPING",
|
| 169 |
+
"FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING",
|
| 170 |
+
"FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING",
|
| 171 |
+
"FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING",
|
| 172 |
+
"FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING",
|
| 173 |
+
"FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING",
|
| 174 |
+
"FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING",
|
| 175 |
+
"FLAX_MODEL_MAPPING",
|
| 176 |
+
"FlaxAutoModel",
|
| 177 |
+
"FlaxAutoModelForCausalLM",
|
| 178 |
+
"FlaxAutoModelForImageClassification",
|
| 179 |
+
"FlaxAutoModelForMaskedLM",
|
| 180 |
+
"FlaxAutoModelForMultipleChoice",
|
| 181 |
+
"FlaxAutoModelForNextSentencePrediction",
|
| 182 |
+
"FlaxAutoModelForPreTraining",
|
| 183 |
+
"FlaxAutoModelForQuestionAnswering",
|
| 184 |
+
"FlaxAutoModelForSeq2SeqLM",
|
| 185 |
+
"FlaxAutoModelForSequenceClassification",
|
| 186 |
+
"FlaxAutoModelForSpeechSeq2Seq",
|
| 187 |
+
"FlaxAutoModelForTokenClassification",
|
| 188 |
+
"FlaxAutoModelForVision2Seq",
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
if TYPE_CHECKING:
|
| 193 |
+
from .auto_factory import get_values
|
| 194 |
+
from .configuration_auto import ALL_PRETRAINED_CONFIG_ARCHIVE_MAP, CONFIG_MAPPING, MODEL_NAMES_MAPPING, AutoConfig
|
| 195 |
+
from .feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING, AutoFeatureExtractor
|
| 196 |
+
from .image_processing_auto import IMAGE_PROCESSOR_MAPPING, AutoImageProcessor
|
| 197 |
+
from .processing_auto import PROCESSOR_MAPPING, AutoProcessor
|
| 198 |
+
from .tokenization_auto import TOKENIZER_MAPPING, AutoTokenizer
|
| 199 |
+
|
| 200 |
+
try:
|
| 201 |
+
if not is_torch_available():
|
| 202 |
+
raise OptionalDependencyNotAvailable()
|
| 203 |
+
except OptionalDependencyNotAvailable:
|
| 204 |
+
pass
|
| 205 |
+
else:
|
| 206 |
+
from .modeling_auto import (
|
| 207 |
+
MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING,
|
| 208 |
+
MODEL_FOR_AUDIO_XVECTOR_MAPPING,
|
| 209 |
+
MODEL_FOR_BACKBONE_MAPPING,
|
| 210 |
+
MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING,
|
| 211 |
+
MODEL_FOR_CAUSAL_LM_MAPPING,
|
| 212 |
+
MODEL_FOR_CTC_MAPPING,
|
| 213 |
+
MODEL_FOR_DEPTH_ESTIMATION_MAPPING,
|
| 214 |
+
MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING,
|
| 215 |
+
MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
|
| 216 |
+
MODEL_FOR_IMAGE_SEGMENTATION_MAPPING,
|
| 217 |
+
MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING,
|
| 218 |
+
MODEL_FOR_MASK_GENERATION_MAPPING,
|
| 219 |
+
MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING,
|
| 220 |
+
MODEL_FOR_MASKED_LM_MAPPING,
|
| 221 |
+
MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
|
| 222 |
+
MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
|
| 223 |
+
MODEL_FOR_OBJECT_DETECTION_MAPPING,
|
| 224 |
+
MODEL_FOR_PRETRAINING_MAPPING,
|
| 225 |
+
MODEL_FOR_QUESTION_ANSWERING_MAPPING,
|
| 226 |
+
MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING,
|
| 227 |
+
MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
|
| 228 |
+
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
|
| 229 |
+
MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
|
| 230 |
+
MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
|
| 231 |
+
MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
|
| 232 |
+
MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING,
|
| 233 |
+
MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
|
| 234 |
+
MODEL_FOR_VISION_2_SEQ_MAPPING,
|
| 235 |
+
MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING,
|
| 236 |
+
MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING,
|
| 237 |
+
MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING,
|
| 238 |
+
MODEL_MAPPING,
|
| 239 |
+
MODEL_WITH_LM_HEAD_MAPPING,
|
| 240 |
+
AutoBackbone,
|
| 241 |
+
AutoModel,
|
| 242 |
+
AutoModelForAudioClassification,
|
| 243 |
+
AutoModelForAudioFrameClassification,
|
| 244 |
+
AutoModelForAudioXVector,
|
| 245 |
+
AutoModelForCausalLM,
|
| 246 |
+
AutoModelForCTC,
|
| 247 |
+
AutoModelForDepthEstimation,
|
| 248 |
+
AutoModelForDocumentQuestionAnswering,
|
| 249 |
+
AutoModelForImageClassification,
|
| 250 |
+
AutoModelForImageSegmentation,
|
| 251 |
+
AutoModelForInstanceSegmentation,
|
| 252 |
+
AutoModelForMaskedImageModeling,
|
| 253 |
+
AutoModelForMaskedLM,
|
| 254 |
+
AutoModelForMaskGeneration,
|
| 255 |
+
AutoModelForMultipleChoice,
|
| 256 |
+
AutoModelForNextSentencePrediction,
|
| 257 |
+
AutoModelForObjectDetection,
|
| 258 |
+
AutoModelForPreTraining,
|
| 259 |
+
AutoModelForQuestionAnswering,
|
| 260 |
+
AutoModelForSemanticSegmentation,
|
| 261 |
+
AutoModelForSeq2SeqLM,
|
| 262 |
+
AutoModelForSequenceClassification,
|
| 263 |
+
AutoModelForSpeechSeq2Seq,
|
| 264 |
+
AutoModelForTableQuestionAnswering,
|
| 265 |
+
AutoModelForTokenClassification,
|
| 266 |
+
AutoModelForUniversalSegmentation,
|
| 267 |
+
AutoModelForVideoClassification,
|
| 268 |
+
AutoModelForVision2Seq,
|
| 269 |
+
AutoModelForVisualQuestionAnswering,
|
| 270 |
+
AutoModelForZeroShotImageClassification,
|
| 271 |
+
AutoModelForZeroShotObjectDetection,
|
| 272 |
+
AutoModelWithLMHead,
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
try:
|
| 276 |
+
if not is_tf_available():
|
| 277 |
+
raise OptionalDependencyNotAvailable()
|
| 278 |
+
except OptionalDependencyNotAvailable:
|
| 279 |
+
pass
|
| 280 |
+
else:
|
| 281 |
+
from .modeling_tf_auto import (
|
| 282 |
+
TF_MODEL_FOR_CAUSAL_LM_MAPPING,
|
| 283 |
+
TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING,
|
| 284 |
+
TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
|
| 285 |
+
TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING,
|
| 286 |
+
TF_MODEL_FOR_MASKED_LM_MAPPING,
|
| 287 |
+
TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
|
| 288 |
+
TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
|
| 289 |
+
TF_MODEL_FOR_PRETRAINING_MAPPING,
|
| 290 |
+
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
|
| 291 |
+
TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING,
|
| 292 |
+
TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
|
| 293 |
+
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
|
| 294 |
+
TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
|
| 295 |
+
TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
|
| 296 |
+
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
|
| 297 |
+
TF_MODEL_FOR_VISION_2_SEQ_MAPPING,
|
| 298 |
+
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING,
|
| 299 |
+
TF_MODEL_MAPPING,
|
| 300 |
+
TF_MODEL_WITH_LM_HEAD_MAPPING,
|
| 301 |
+
TFAutoModel,
|
| 302 |
+
TFAutoModelForCausalLM,
|
| 303 |
+
TFAutoModelForDocumentQuestionAnswering,
|
| 304 |
+
TFAutoModelForImageClassification,
|
| 305 |
+
TFAutoModelForMaskedLM,
|
| 306 |
+
TFAutoModelForMultipleChoice,
|
| 307 |
+
TFAutoModelForNextSentencePrediction,
|
| 308 |
+
TFAutoModelForPreTraining,
|
| 309 |
+
TFAutoModelForQuestionAnswering,
|
| 310 |
+
TFAutoModelForSemanticSegmentation,
|
| 311 |
+
TFAutoModelForSeq2SeqLM,
|
| 312 |
+
TFAutoModelForSequenceClassification,
|
| 313 |
+
TFAutoModelForSpeechSeq2Seq,
|
| 314 |
+
TFAutoModelForTableQuestionAnswering,
|
| 315 |
+
TFAutoModelForTokenClassification,
|
| 316 |
+
TFAutoModelForVision2Seq,
|
| 317 |
+
TFAutoModelForZeroShotImageClassification,
|
| 318 |
+
TFAutoModelWithLMHead,
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
try:
|
| 322 |
+
if not is_flax_available():
|
| 323 |
+
raise OptionalDependencyNotAvailable()
|
| 324 |
+
except OptionalDependencyNotAvailable:
|
| 325 |
+
pass
|
| 326 |
+
else:
|
| 327 |
+
from .modeling_flax_auto import (
|
| 328 |
+
FLAX_MODEL_FOR_CAUSAL_LM_MAPPING,
|
| 329 |
+
FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
|
| 330 |
+
FLAX_MODEL_FOR_MASKED_LM_MAPPING,
|
| 331 |
+
FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
|
| 332 |
+
FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
|
| 333 |
+
FLAX_MODEL_FOR_PRETRAINING_MAPPING,
|
| 334 |
+
FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
|
| 335 |
+
FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
|
| 336 |
+
FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
|
| 337 |
+
FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
|
| 338 |
+
FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
|
| 339 |
+
FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING,
|
| 340 |
+
FLAX_MODEL_MAPPING,
|
| 341 |
+
FlaxAutoModel,
|
| 342 |
+
FlaxAutoModelForCausalLM,
|
| 343 |
+
FlaxAutoModelForImageClassification,
|
| 344 |
+
FlaxAutoModelForMaskedLM,
|
| 345 |
+
FlaxAutoModelForMultipleChoice,
|
| 346 |
+
FlaxAutoModelForNextSentencePrediction,
|
| 347 |
+
FlaxAutoModelForPreTraining,
|
| 348 |
+
FlaxAutoModelForQuestionAnswering,
|
| 349 |
+
FlaxAutoModelForSeq2SeqLM,
|
| 350 |
+
FlaxAutoModelForSequenceClassification,
|
| 351 |
+
FlaxAutoModelForSpeechSeq2Seq,
|
| 352 |
+
FlaxAutoModelForTokenClassification,
|
| 353 |
+
FlaxAutoModelForVision2Seq,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
else:
|
| 357 |
+
import sys
|
| 358 |
+
|
| 359 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/auto_factory.py
ADDED
|
@@ -0,0 +1,670 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Factory function to build auto-model classes."""
|
| 16 |
+
import copy
|
| 17 |
+
import importlib
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
|
| 20 |
+
from ...configuration_utils import PretrainedConfig
|
| 21 |
+
from ...dynamic_module_utils import get_class_from_dynamic_module
|
| 22 |
+
from ...utils import copy_func, logging
|
| 23 |
+
from .configuration_auto import AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
CLASS_DOCSTRING = """
|
| 30 |
+
This is a generic model class that will be instantiated as one of the model classes of the library when created
|
| 31 |
+
with the [`~BaseAutoModelClass.from_pretrained`] class method or the [`~BaseAutoModelClass.from_config`] class
|
| 32 |
+
method.
|
| 33 |
+
|
| 34 |
+
This class cannot be instantiated directly using `__init__()` (throws an error).
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
FROM_CONFIG_DOCSTRING = """
|
| 38 |
+
Instantiates one of the model classes of the library from a configuration.
|
| 39 |
+
|
| 40 |
+
Note:
|
| 41 |
+
Loading a model from its configuration file does **not** load the model weights. It only affects the
|
| 42 |
+
model's configuration. Use [`~BaseAutoModelClass.from_pretrained`] to load the model weights.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
config ([`PretrainedConfig`]):
|
| 46 |
+
The model class to instantiate is selected based on the configuration class:
|
| 47 |
+
|
| 48 |
+
List options
|
| 49 |
+
|
| 50 |
+
Examples:
|
| 51 |
+
|
| 52 |
+
```python
|
| 53 |
+
>>> from transformers import AutoConfig, BaseAutoModelClass
|
| 54 |
+
|
| 55 |
+
>>> # Download configuration from huggingface.co and cache.
|
| 56 |
+
>>> config = AutoConfig.from_pretrained("checkpoint_placeholder")
|
| 57 |
+
>>> model = BaseAutoModelClass.from_config(config)
|
| 58 |
+
```
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
FROM_PRETRAINED_TORCH_DOCSTRING = """
|
| 62 |
+
Instantiate one of the model classes of the library from a pretrained model.
|
| 63 |
+
|
| 64 |
+
The model class to instantiate is selected based on the `model_type` property of the config object (either
|
| 65 |
+
passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
|
| 66 |
+
falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 67 |
+
|
| 68 |
+
List options
|
| 69 |
+
|
| 70 |
+
The model is set in evaluation mode by default using `model.eval()` (so for instance, dropout modules are
|
| 71 |
+
deactivated). To train the model, you should first set it back in training mode with `model.train()`
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 75 |
+
Can be either:
|
| 76 |
+
|
| 77 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
| 78 |
+
Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
|
| 79 |
+
user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 80 |
+
- A path to a *directory* containing model weights saved using
|
| 81 |
+
[`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
|
| 82 |
+
- A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
|
| 83 |
+
this case, `from_tf` should be set to `True` and a configuration object should be provided as
|
| 84 |
+
`config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
|
| 85 |
+
PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
|
| 86 |
+
model_args (additional positional arguments, *optional*):
|
| 87 |
+
Will be passed along to the underlying model `__init__()` method.
|
| 88 |
+
config ([`PretrainedConfig`], *optional*):
|
| 89 |
+
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
|
| 90 |
+
be automatically loaded when:
|
| 91 |
+
|
| 92 |
+
- The model is a model provided by the library (loaded with the *model id* string of a pretrained
|
| 93 |
+
model).
|
| 94 |
+
- The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
|
| 95 |
+
save directory.
|
| 96 |
+
- The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
|
| 97 |
+
configuration JSON file named *config.json* is found in the directory.
|
| 98 |
+
state_dict (*Dict[str, torch.Tensor]*, *optional*):
|
| 99 |
+
A state dictionary to use instead of a state dictionary loaded from saved weights file.
|
| 100 |
+
|
| 101 |
+
This option can be used if you want to create a model from a pretrained configuration but load your own
|
| 102 |
+
weights. In this case though, you should check if using [`~PreTrainedModel.save_pretrained`] and
|
| 103 |
+
[`~PreTrainedModel.from_pretrained`] is not a simpler option.
|
| 104 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 105 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 106 |
+
standard cache should not be used.
|
| 107 |
+
from_tf (`bool`, *optional*, defaults to `False`):
|
| 108 |
+
Load the model weights from a TensorFlow checkpoint save file (see docstring of
|
| 109 |
+
`pretrained_model_name_or_path` argument).
|
| 110 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 111 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 112 |
+
cached versions if they exist.
|
| 113 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 114 |
+
Whether or not to delete incompletely received files. Will attempt to resume the download if such a
|
| 115 |
+
file exists.
|
| 116 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 117 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 118 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 119 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
| 120 |
+
Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
| 121 |
+
local_files_only(`bool`, *optional*, defaults to `False`):
|
| 122 |
+
Whether or not to only look at local files (e.g., not try downloading the model).
|
| 123 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 124 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 125 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 126 |
+
identifier allowed by git.
|
| 127 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 128 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 129 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 130 |
+
execute code present on the Hub on your local machine.
|
| 131 |
+
kwargs (additional keyword arguments, *optional*):
|
| 132 |
+
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
|
| 133 |
+
`output_attentions=True`). Behaves differently depending on whether a `config` is provided or
|
| 134 |
+
automatically loaded:
|
| 135 |
+
|
| 136 |
+
- If a configuration is provided with `config`, `**kwargs` will be directly passed to the
|
| 137 |
+
underlying model's `__init__` method (we assume all relevant updates to the configuration have
|
| 138 |
+
already been done)
|
| 139 |
+
- If a configuration is not provided, `kwargs` will be first passed to the configuration class
|
| 140 |
+
initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
|
| 141 |
+
corresponds to a configuration attribute will be used to override said attribute with the
|
| 142 |
+
supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
|
| 143 |
+
will be passed to the underlying model's `__init__` function.
|
| 144 |
+
|
| 145 |
+
Examples:
|
| 146 |
+
|
| 147 |
+
```python
|
| 148 |
+
>>> from transformers import AutoConfig, BaseAutoModelClass
|
| 149 |
+
|
| 150 |
+
>>> # Download model and configuration from huggingface.co and cache.
|
| 151 |
+
>>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder")
|
| 152 |
+
|
| 153 |
+
>>> # Update configuration during loading
|
| 154 |
+
>>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder", output_attentions=True)
|
| 155 |
+
>>> model.config.output_attentions
|
| 156 |
+
True
|
| 157 |
+
|
| 158 |
+
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
|
| 159 |
+
>>> config = AutoConfig.from_pretrained("./tf_model/shortcut_placeholder_tf_model_config.json")
|
| 160 |
+
>>> model = BaseAutoModelClass.from_pretrained(
|
| 161 |
+
... "./tf_model/shortcut_placeholder_tf_checkpoint.ckpt.index", from_tf=True, config=config
|
| 162 |
+
... )
|
| 163 |
+
```
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
FROM_PRETRAINED_TF_DOCSTRING = """
|
| 167 |
+
Instantiate one of the model classes of the library from a pretrained model.
|
| 168 |
+
|
| 169 |
+
The model class to instantiate is selected based on the `model_type` property of the config object (either
|
| 170 |
+
passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
|
| 171 |
+
falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 172 |
+
|
| 173 |
+
List options
|
| 174 |
+
|
| 175 |
+
Args:
|
| 176 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 177 |
+
Can be either:
|
| 178 |
+
|
| 179 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
| 180 |
+
Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
|
| 181 |
+
user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 182 |
+
- A path to a *directory* containing model weights saved using
|
| 183 |
+
[`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
|
| 184 |
+
- A path or url to a *PyTorch state_dict save file* (e.g, `./pt_model/pytorch_model.bin`). In this
|
| 185 |
+
case, `from_pt` should be set to `True` and a configuration object should be provided as `config`
|
| 186 |
+
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model
|
| 187 |
+
using the provided conversion scripts and loading the TensorFlow model afterwards.
|
| 188 |
+
model_args (additional positional arguments, *optional*):
|
| 189 |
+
Will be passed along to the underlying model `__init__()` method.
|
| 190 |
+
config ([`PretrainedConfig`], *optional*):
|
| 191 |
+
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
|
| 192 |
+
be automatically loaded when:
|
| 193 |
+
|
| 194 |
+
- The model is a model provided by the library (loaded with the *model id* string of a pretrained
|
| 195 |
+
model).
|
| 196 |
+
- The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
|
| 197 |
+
save directory.
|
| 198 |
+
- The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
|
| 199 |
+
configuration JSON file named *config.json* is found in the directory.
|
| 200 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 201 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 202 |
+
standard cache should not be used.
|
| 203 |
+
from_pt (`bool`, *optional*, defaults to `False`):
|
| 204 |
+
Load the model weights from a PyTorch checkpoint save file (see docstring of
|
| 205 |
+
`pretrained_model_name_or_path` argument).
|
| 206 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 207 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 208 |
+
cached versions if they exist.
|
| 209 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 210 |
+
Whether or not to delete incompletely received files. Will attempt to resume the download if such a
|
| 211 |
+
file exists.
|
| 212 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 213 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 214 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 215 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
| 216 |
+
Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
| 217 |
+
local_files_only(`bool`, *optional*, defaults to `False`):
|
| 218 |
+
Whether or not to only look at local files (e.g., not try downloading the model).
|
| 219 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 220 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 221 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 222 |
+
identifier allowed by git.
|
| 223 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 224 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 225 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 226 |
+
execute code present on the Hub on your local machine.
|
| 227 |
+
kwargs (additional keyword arguments, *optional*):
|
| 228 |
+
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
|
| 229 |
+
`output_attentions=True`). Behaves differently depending on whether a `config` is provided or
|
| 230 |
+
automatically loaded:
|
| 231 |
+
|
| 232 |
+
- If a configuration is provided with `config`, `**kwargs` will be directly passed to the
|
| 233 |
+
underlying model's `__init__` method (we assume all relevant updates to the configuration have
|
| 234 |
+
already been done)
|
| 235 |
+
- If a configuration is not provided, `kwargs` will be first passed to the configuration class
|
| 236 |
+
initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
|
| 237 |
+
corresponds to a configuration attribute will be used to override said attribute with the
|
| 238 |
+
supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
|
| 239 |
+
will be passed to the underlying model's `__init__` function.
|
| 240 |
+
|
| 241 |
+
Examples:
|
| 242 |
+
|
| 243 |
+
```python
|
| 244 |
+
>>> from transformers import AutoConfig, BaseAutoModelClass
|
| 245 |
+
|
| 246 |
+
>>> # Download model and configuration from huggingface.co and cache.
|
| 247 |
+
>>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder")
|
| 248 |
+
|
| 249 |
+
>>> # Update configuration during loading
|
| 250 |
+
>>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder", output_attentions=True)
|
| 251 |
+
>>> model.config.output_attentions
|
| 252 |
+
True
|
| 253 |
+
|
| 254 |
+
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
|
| 255 |
+
>>> config = AutoConfig.from_pretrained("./pt_model/shortcut_placeholder_pt_model_config.json")
|
| 256 |
+
>>> model = BaseAutoModelClass.from_pretrained(
|
| 257 |
+
... "./pt_model/shortcut_placeholder_pytorch_model.bin", from_pt=True, config=config
|
| 258 |
+
... )
|
| 259 |
+
```
|
| 260 |
+
"""
|
| 261 |
+
|
| 262 |
+
FROM_PRETRAINED_FLAX_DOCSTRING = """
|
| 263 |
+
Instantiate one of the model classes of the library from a pretrained model.
|
| 264 |
+
|
| 265 |
+
The model class to instantiate is selected based on the `model_type` property of the config object (either
|
| 266 |
+
passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
|
| 267 |
+
falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 268 |
+
|
| 269 |
+
List options
|
| 270 |
+
|
| 271 |
+
Args:
|
| 272 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 273 |
+
Can be either:
|
| 274 |
+
|
| 275 |
+
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
|
| 276 |
+
Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
|
| 277 |
+
user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 278 |
+
- A path to a *directory* containing model weights saved using
|
| 279 |
+
[`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
|
| 280 |
+
- A path or url to a *PyTorch state_dict save file* (e.g, `./pt_model/pytorch_model.bin`). In this
|
| 281 |
+
case, `from_pt` should be set to `True` and a configuration object should be provided as `config`
|
| 282 |
+
argument. This loading path is slower than converting the PyTorch model in a TensorFlow model
|
| 283 |
+
using the provided conversion scripts and loading the TensorFlow model afterwards.
|
| 284 |
+
model_args (additional positional arguments, *optional*):
|
| 285 |
+
Will be passed along to the underlying model `__init__()` method.
|
| 286 |
+
config ([`PretrainedConfig`], *optional*):
|
| 287 |
+
Configuration for the model to use instead of an automatically loaded configuration. Configuration can
|
| 288 |
+
be automatically loaded when:
|
| 289 |
+
|
| 290 |
+
- The model is a model provided by the library (loaded with the *model id* string of a pretrained
|
| 291 |
+
model).
|
| 292 |
+
- The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the
|
| 293 |
+
save directory.
|
| 294 |
+
- The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a
|
| 295 |
+
configuration JSON file named *config.json* is found in the directory.
|
| 296 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 297 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 298 |
+
standard cache should not be used.
|
| 299 |
+
from_pt (`bool`, *optional*, defaults to `False`):
|
| 300 |
+
Load the model weights from a PyTorch checkpoint save file (see docstring of
|
| 301 |
+
`pretrained_model_name_or_path` argument).
|
| 302 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 303 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 304 |
+
cached versions if they exist.
|
| 305 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 306 |
+
Whether or not to delete incompletely received files. Will attempt to resume the download if such a
|
| 307 |
+
file exists.
|
| 308 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 309 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 310 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 311 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
| 312 |
+
Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
| 313 |
+
local_files_only(`bool`, *optional*, defaults to `False`):
|
| 314 |
+
Whether or not to only look at local files (e.g., not try downloading the model).
|
| 315 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 316 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 317 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 318 |
+
identifier allowed by git.
|
| 319 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 320 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 321 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 322 |
+
execute code present on the Hub on your local machine.
|
| 323 |
+
kwargs (additional keyword arguments, *optional*):
|
| 324 |
+
Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
|
| 325 |
+
`output_attentions=True`). Behaves differently depending on whether a `config` is provided or
|
| 326 |
+
automatically loaded:
|
| 327 |
+
|
| 328 |
+
- If a configuration is provided with `config`, `**kwargs` will be directly passed to the
|
| 329 |
+
underlying model's `__init__` method (we assume all relevant updates to the configuration have
|
| 330 |
+
already been done)
|
| 331 |
+
- If a configuration is not provided, `kwargs` will be first passed to the configuration class
|
| 332 |
+
initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that
|
| 333 |
+
corresponds to a configuration attribute will be used to override said attribute with the
|
| 334 |
+
supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute
|
| 335 |
+
will be passed to the underlying model's `__init__` function.
|
| 336 |
+
|
| 337 |
+
Examples:
|
| 338 |
+
|
| 339 |
+
```python
|
| 340 |
+
>>> from transformers import AutoConfig, BaseAutoModelClass
|
| 341 |
+
|
| 342 |
+
>>> # Download model and configuration from huggingface.co and cache.
|
| 343 |
+
>>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder")
|
| 344 |
+
|
| 345 |
+
>>> # Update configuration during loading
|
| 346 |
+
>>> model = BaseAutoModelClass.from_pretrained("checkpoint_placeholder", output_attentions=True)
|
| 347 |
+
>>> model.config.output_attentions
|
| 348 |
+
True
|
| 349 |
+
|
| 350 |
+
>>> # Loading from a PyTorch checkpoint file instead of a TensorFlow model (slower)
|
| 351 |
+
>>> config = AutoConfig.from_pretrained("./pt_model/shortcut_placeholder_pt_model_config.json")
|
| 352 |
+
>>> model = BaseAutoModelClass.from_pretrained(
|
| 353 |
+
... "./pt_model/shortcut_placeholder_pytorch_model.bin", from_pt=True, config=config
|
| 354 |
+
... )
|
| 355 |
+
```
|
| 356 |
+
"""
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def _get_model_class(config, model_mapping):
|
| 360 |
+
supported_models = model_mapping[type(config)]
|
| 361 |
+
if not isinstance(supported_models, (list, tuple)):
|
| 362 |
+
return supported_models
|
| 363 |
+
|
| 364 |
+
name_to_model = {model.__name__: model for model in supported_models}
|
| 365 |
+
architectures = getattr(config, "architectures", [])
|
| 366 |
+
for arch in architectures:
|
| 367 |
+
if arch in name_to_model:
|
| 368 |
+
return name_to_model[arch]
|
| 369 |
+
elif f"TF{arch}" in name_to_model:
|
| 370 |
+
return name_to_model[f"TF{arch}"]
|
| 371 |
+
elif f"Flax{arch}" in name_to_model:
|
| 372 |
+
return name_to_model[f"Flax{arch}"]
|
| 373 |
+
|
| 374 |
+
# If not architecture is set in the config or match the supported models, the first element of the tuple is the
|
| 375 |
+
# defaults.
|
| 376 |
+
return supported_models[0]
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
class _BaseAutoModelClass:
|
| 380 |
+
# Base class for auto models.
|
| 381 |
+
_model_mapping = None
|
| 382 |
+
|
| 383 |
+
def __init__(self, *args, **kwargs):
|
| 384 |
+
raise EnvironmentError(
|
| 385 |
+
f"{self.__class__.__name__} is designed to be instantiated "
|
| 386 |
+
f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or "
|
| 387 |
+
f"`{self.__class__.__name__}.from_config(config)` methods."
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
@classmethod
|
| 391 |
+
def from_config(cls, config, **kwargs):
|
| 392 |
+
trust_remote_code = kwargs.pop("trust_remote_code", False)
|
| 393 |
+
if hasattr(config, "auto_map") and cls.__name__ in config.auto_map:
|
| 394 |
+
if not trust_remote_code:
|
| 395 |
+
raise ValueError(
|
| 396 |
+
"Loading this model requires you to execute the modeling file in that repo "
|
| 397 |
+
"on your local machine. Make sure you have read the code there to avoid malicious use, then set "
|
| 398 |
+
"the option `trust_remote_code=True` to remove this error."
|
| 399 |
+
)
|
| 400 |
+
if kwargs.get("revision", None) is None:
|
| 401 |
+
logger.warning(
|
| 402 |
+
"Explicitly passing a `revision` is encouraged when loading a model with custom code to ensure "
|
| 403 |
+
"no malicious code has been contributed in a newer revision."
|
| 404 |
+
)
|
| 405 |
+
class_ref = config.auto_map[cls.__name__]
|
| 406 |
+
if "--" in class_ref:
|
| 407 |
+
repo_id, class_ref = class_ref.split("--")
|
| 408 |
+
else:
|
| 409 |
+
repo_id = config.name_or_path
|
| 410 |
+
model_class = get_class_from_dynamic_module(class_ref, repo_id, **kwargs)
|
| 411 |
+
return model_class._from_config(config, **kwargs)
|
| 412 |
+
elif type(config) in cls._model_mapping.keys():
|
| 413 |
+
model_class = _get_model_class(config, cls._model_mapping)
|
| 414 |
+
return model_class._from_config(config, **kwargs)
|
| 415 |
+
|
| 416 |
+
raise ValueError(
|
| 417 |
+
f"Unrecognized configuration class {config.__class__} for this kind of AutoModel: {cls.__name__}.\n"
|
| 418 |
+
f"Model type should be one of {', '.join(c.__name__ for c in cls._model_mapping.keys())}."
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
@classmethod
|
| 422 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 423 |
+
config = kwargs.pop("config", None)
|
| 424 |
+
trust_remote_code = kwargs.pop("trust_remote_code", False)
|
| 425 |
+
kwargs["_from_auto"] = True
|
| 426 |
+
hub_kwargs_names = [
|
| 427 |
+
"cache_dir",
|
| 428 |
+
"force_download",
|
| 429 |
+
"local_files_only",
|
| 430 |
+
"proxies",
|
| 431 |
+
"resume_download",
|
| 432 |
+
"revision",
|
| 433 |
+
"subfolder",
|
| 434 |
+
"use_auth_token",
|
| 435 |
+
]
|
| 436 |
+
hub_kwargs = {name: kwargs.pop(name) for name in hub_kwargs_names if name in kwargs}
|
| 437 |
+
if not isinstance(config, PretrainedConfig):
|
| 438 |
+
kwargs_copy = copy.deepcopy(kwargs)
|
| 439 |
+
# ensure not to pollute the config object with torch_dtype="auto" - since it's
|
| 440 |
+
# meaningless in the context of the config object - torch.dtype values are acceptable
|
| 441 |
+
if kwargs_copy.get("torch_dtype", None) == "auto":
|
| 442 |
+
_ = kwargs_copy.pop("torch_dtype")
|
| 443 |
+
|
| 444 |
+
config, kwargs = AutoConfig.from_pretrained(
|
| 445 |
+
pretrained_model_name_or_path,
|
| 446 |
+
return_unused_kwargs=True,
|
| 447 |
+
trust_remote_code=trust_remote_code,
|
| 448 |
+
**hub_kwargs,
|
| 449 |
+
**kwargs_copy,
|
| 450 |
+
)
|
| 451 |
+
if hasattr(config, "auto_map") and cls.__name__ in config.auto_map:
|
| 452 |
+
if not trust_remote_code:
|
| 453 |
+
raise ValueError(
|
| 454 |
+
f"Loading {pretrained_model_name_or_path} requires you to execute the modeling file in that repo "
|
| 455 |
+
"on your local machine. Make sure you have read the code there to avoid malicious use, then set "
|
| 456 |
+
"the option `trust_remote_code=True` to remove this error."
|
| 457 |
+
)
|
| 458 |
+
class_ref = config.auto_map[cls.__name__]
|
| 459 |
+
model_class = get_class_from_dynamic_module(
|
| 460 |
+
class_ref, pretrained_model_name_or_path, **hub_kwargs, **kwargs
|
| 461 |
+
)
|
| 462 |
+
return model_class.from_pretrained(
|
| 463 |
+
pretrained_model_name_or_path, *model_args, config=config, **hub_kwargs, **kwargs
|
| 464 |
+
)
|
| 465 |
+
elif type(config) in cls._model_mapping.keys():
|
| 466 |
+
model_class = _get_model_class(config, cls._model_mapping)
|
| 467 |
+
return model_class.from_pretrained(
|
| 468 |
+
pretrained_model_name_or_path, *model_args, config=config, **hub_kwargs, **kwargs
|
| 469 |
+
)
|
| 470 |
+
raise ValueError(
|
| 471 |
+
f"Unrecognized configuration class {config.__class__} for this kind of AutoModel: {cls.__name__}.\n"
|
| 472 |
+
f"Model type should be one of {', '.join(c.__name__ for c in cls._model_mapping.keys())}."
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
@classmethod
|
| 476 |
+
def register(cls, config_class, model_class):
|
| 477 |
+
"""
|
| 478 |
+
Register a new model for this class.
|
| 479 |
+
|
| 480 |
+
Args:
|
| 481 |
+
config_class ([`PretrainedConfig`]):
|
| 482 |
+
The configuration corresponding to the model to register.
|
| 483 |
+
model_class ([`PreTrainedModel`]):
|
| 484 |
+
The model to register.
|
| 485 |
+
"""
|
| 486 |
+
if hasattr(model_class, "config_class") and model_class.config_class != config_class:
|
| 487 |
+
raise ValueError(
|
| 488 |
+
"The model class you are passing has a `config_class` attribute that is not consistent with the "
|
| 489 |
+
f"config class you passed (model has {model_class.config_class} and you passed {config_class}. Fix "
|
| 490 |
+
"one of those so they match!"
|
| 491 |
+
)
|
| 492 |
+
cls._model_mapping.register(config_class, model_class)
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def insert_head_doc(docstring, head_doc=""):
|
| 496 |
+
if len(head_doc) > 0:
|
| 497 |
+
return docstring.replace(
|
| 498 |
+
"one of the model classes of the library ",
|
| 499 |
+
f"one of the model classes of the library (with a {head_doc} head) ",
|
| 500 |
+
)
|
| 501 |
+
return docstring.replace(
|
| 502 |
+
"one of the model classes of the library ", "one of the base model classes of the library "
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def auto_class_update(cls, checkpoint_for_example="bert-base-cased", head_doc=""):
|
| 507 |
+
# Create a new class with the right name from the base class
|
| 508 |
+
model_mapping = cls._model_mapping
|
| 509 |
+
name = cls.__name__
|
| 510 |
+
class_docstring = insert_head_doc(CLASS_DOCSTRING, head_doc=head_doc)
|
| 511 |
+
cls.__doc__ = class_docstring.replace("BaseAutoModelClass", name)
|
| 512 |
+
|
| 513 |
+
# Now we need to copy and re-register `from_config` and `from_pretrained` as class methods otherwise we can't
|
| 514 |
+
# have a specific docstrings for them.
|
| 515 |
+
from_config = copy_func(_BaseAutoModelClass.from_config)
|
| 516 |
+
from_config_docstring = insert_head_doc(FROM_CONFIG_DOCSTRING, head_doc=head_doc)
|
| 517 |
+
from_config_docstring = from_config_docstring.replace("BaseAutoModelClass", name)
|
| 518 |
+
from_config_docstring = from_config_docstring.replace("checkpoint_placeholder", checkpoint_for_example)
|
| 519 |
+
from_config.__doc__ = from_config_docstring
|
| 520 |
+
from_config = replace_list_option_in_docstrings(model_mapping._model_mapping, use_model_types=False)(from_config)
|
| 521 |
+
cls.from_config = classmethod(from_config)
|
| 522 |
+
|
| 523 |
+
if name.startswith("TF"):
|
| 524 |
+
from_pretrained_docstring = FROM_PRETRAINED_TF_DOCSTRING
|
| 525 |
+
elif name.startswith("Flax"):
|
| 526 |
+
from_pretrained_docstring = FROM_PRETRAINED_FLAX_DOCSTRING
|
| 527 |
+
else:
|
| 528 |
+
from_pretrained_docstring = FROM_PRETRAINED_TORCH_DOCSTRING
|
| 529 |
+
from_pretrained = copy_func(_BaseAutoModelClass.from_pretrained)
|
| 530 |
+
from_pretrained_docstring = insert_head_doc(from_pretrained_docstring, head_doc=head_doc)
|
| 531 |
+
from_pretrained_docstring = from_pretrained_docstring.replace("BaseAutoModelClass", name)
|
| 532 |
+
from_pretrained_docstring = from_pretrained_docstring.replace("checkpoint_placeholder", checkpoint_for_example)
|
| 533 |
+
shortcut = checkpoint_for_example.split("/")[-1].split("-")[0]
|
| 534 |
+
from_pretrained_docstring = from_pretrained_docstring.replace("shortcut_placeholder", shortcut)
|
| 535 |
+
from_pretrained.__doc__ = from_pretrained_docstring
|
| 536 |
+
from_pretrained = replace_list_option_in_docstrings(model_mapping._model_mapping)(from_pretrained)
|
| 537 |
+
cls.from_pretrained = classmethod(from_pretrained)
|
| 538 |
+
return cls
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def get_values(model_mapping):
|
| 542 |
+
result = []
|
| 543 |
+
for model in model_mapping.values():
|
| 544 |
+
if isinstance(model, (list, tuple)):
|
| 545 |
+
result += list(model)
|
| 546 |
+
else:
|
| 547 |
+
result.append(model)
|
| 548 |
+
|
| 549 |
+
return result
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def getattribute_from_module(module, attr):
|
| 553 |
+
if attr is None:
|
| 554 |
+
return None
|
| 555 |
+
if isinstance(attr, tuple):
|
| 556 |
+
return tuple(getattribute_from_module(module, a) for a in attr)
|
| 557 |
+
if hasattr(module, attr):
|
| 558 |
+
return getattr(module, attr)
|
| 559 |
+
# Some of the mappings have entries model_type -> object of another model type. In that case we try to grab the
|
| 560 |
+
# object at the top level.
|
| 561 |
+
transformers_module = importlib.import_module("transformers")
|
| 562 |
+
|
| 563 |
+
if module != transformers_module:
|
| 564 |
+
try:
|
| 565 |
+
return getattribute_from_module(transformers_module, attr)
|
| 566 |
+
except ValueError:
|
| 567 |
+
raise ValueError(f"Could not find {attr} neither in {module} nor in {transformers_module}!")
|
| 568 |
+
else:
|
| 569 |
+
raise ValueError(f"Could not find {attr} in {transformers_module}!")
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
class _LazyAutoMapping(OrderedDict):
|
| 573 |
+
"""
|
| 574 |
+
" A mapping config to object (model or tokenizer for instance) that will load keys and values when it is accessed.
|
| 575 |
+
|
| 576 |
+
Args:
|
| 577 |
+
- config_mapping: The map model type to config class
|
| 578 |
+
- model_mapping: The map model type to model (or tokenizer) class
|
| 579 |
+
"""
|
| 580 |
+
|
| 581 |
+
def __init__(self, config_mapping, model_mapping):
|
| 582 |
+
self._config_mapping = config_mapping
|
| 583 |
+
self._reverse_config_mapping = {v: k for k, v in config_mapping.items()}
|
| 584 |
+
self._model_mapping = model_mapping
|
| 585 |
+
self._extra_content = {}
|
| 586 |
+
self._modules = {}
|
| 587 |
+
|
| 588 |
+
def __len__(self):
|
| 589 |
+
common_keys = set(self._config_mapping.keys()).intersection(self._model_mapping.keys())
|
| 590 |
+
return len(common_keys) + len(self._extra_content)
|
| 591 |
+
|
| 592 |
+
def __getitem__(self, key):
|
| 593 |
+
if key in self._extra_content:
|
| 594 |
+
return self._extra_content[key]
|
| 595 |
+
model_type = self._reverse_config_mapping[key.__name__]
|
| 596 |
+
if model_type in self._model_mapping:
|
| 597 |
+
model_name = self._model_mapping[model_type]
|
| 598 |
+
return self._load_attr_from_module(model_type, model_name)
|
| 599 |
+
|
| 600 |
+
# Maybe there was several model types associated with this config.
|
| 601 |
+
model_types = [k for k, v in self._config_mapping.items() if v == key.__name__]
|
| 602 |
+
for mtype in model_types:
|
| 603 |
+
if mtype in self._model_mapping:
|
| 604 |
+
model_name = self._model_mapping[mtype]
|
| 605 |
+
return self._load_attr_from_module(mtype, model_name)
|
| 606 |
+
raise KeyError(key)
|
| 607 |
+
|
| 608 |
+
def _load_attr_from_module(self, model_type, attr):
|
| 609 |
+
module_name = model_type_to_module_name(model_type)
|
| 610 |
+
if module_name not in self._modules:
|
| 611 |
+
self._modules[module_name] = importlib.import_module(f".{module_name}", "transformers.models")
|
| 612 |
+
return getattribute_from_module(self._modules[module_name], attr)
|
| 613 |
+
|
| 614 |
+
def keys(self):
|
| 615 |
+
mapping_keys = [
|
| 616 |
+
self._load_attr_from_module(key, name)
|
| 617 |
+
for key, name in self._config_mapping.items()
|
| 618 |
+
if key in self._model_mapping.keys()
|
| 619 |
+
]
|
| 620 |
+
return mapping_keys + list(self._extra_content.keys())
|
| 621 |
+
|
| 622 |
+
def get(self, key, default):
|
| 623 |
+
try:
|
| 624 |
+
return self.__getitem__(key)
|
| 625 |
+
except KeyError:
|
| 626 |
+
return default
|
| 627 |
+
|
| 628 |
+
def __bool__(self):
|
| 629 |
+
return bool(self.keys())
|
| 630 |
+
|
| 631 |
+
def values(self):
|
| 632 |
+
mapping_values = [
|
| 633 |
+
self._load_attr_from_module(key, name)
|
| 634 |
+
for key, name in self._model_mapping.items()
|
| 635 |
+
if key in self._config_mapping.keys()
|
| 636 |
+
]
|
| 637 |
+
return mapping_values + list(self._extra_content.values())
|
| 638 |
+
|
| 639 |
+
def items(self):
|
| 640 |
+
mapping_items = [
|
| 641 |
+
(
|
| 642 |
+
self._load_attr_from_module(key, self._config_mapping[key]),
|
| 643 |
+
self._load_attr_from_module(key, self._model_mapping[key]),
|
| 644 |
+
)
|
| 645 |
+
for key in self._model_mapping.keys()
|
| 646 |
+
if key in self._config_mapping.keys()
|
| 647 |
+
]
|
| 648 |
+
return mapping_items + list(self._extra_content.items())
|
| 649 |
+
|
| 650 |
+
def __iter__(self):
|
| 651 |
+
return iter(self.keys())
|
| 652 |
+
|
| 653 |
+
def __contains__(self, item):
|
| 654 |
+
if item in self._extra_content:
|
| 655 |
+
return True
|
| 656 |
+
if not hasattr(item, "__name__") or item.__name__ not in self._reverse_config_mapping:
|
| 657 |
+
return False
|
| 658 |
+
model_type = self._reverse_config_mapping[item.__name__]
|
| 659 |
+
return model_type in self._model_mapping
|
| 660 |
+
|
| 661 |
+
def register(self, key, value):
|
| 662 |
+
"""
|
| 663 |
+
Register a new model in this mapping.
|
| 664 |
+
"""
|
| 665 |
+
if hasattr(key, "__name__") and key.__name__ in self._reverse_config_mapping:
|
| 666 |
+
model_type = self._reverse_config_mapping[key.__name__]
|
| 667 |
+
if model_type in self._model_mapping.keys():
|
| 668 |
+
raise ValueError(f"'{key}' is already used by a Transformers model.")
|
| 669 |
+
|
| 670 |
+
self._extra_content[key] = value
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/configuration_auto.py
ADDED
|
@@ -0,0 +1,970 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Auto Config class."""
|
| 16 |
+
import importlib
|
| 17 |
+
import re
|
| 18 |
+
import warnings
|
| 19 |
+
from collections import OrderedDict
|
| 20 |
+
from typing import List, Union
|
| 21 |
+
|
| 22 |
+
from ...configuration_utils import PretrainedConfig
|
| 23 |
+
from ...dynamic_module_utils import get_class_from_dynamic_module
|
| 24 |
+
from ...utils import CONFIG_NAME, logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
CONFIG_MAPPING_NAMES = OrderedDict(
|
| 30 |
+
[
|
| 31 |
+
# Add configs here
|
| 32 |
+
("albert", "AlbertConfig"),
|
| 33 |
+
("align", "AlignConfig"),
|
| 34 |
+
("altclip", "AltCLIPConfig"),
|
| 35 |
+
("audio-spectrogram-transformer", "ASTConfig"),
|
| 36 |
+
("bart", "BartConfig"),
|
| 37 |
+
("beit", "BeitConfig"),
|
| 38 |
+
("bert", "BertConfig"),
|
| 39 |
+
("bert-generation", "BertGenerationConfig"),
|
| 40 |
+
("big_bird", "BigBirdConfig"),
|
| 41 |
+
("bigbird_pegasus", "BigBirdPegasusConfig"),
|
| 42 |
+
("biogpt", "BioGptConfig"),
|
| 43 |
+
("bit", "BitConfig"),
|
| 44 |
+
("blenderbot", "BlenderbotConfig"),
|
| 45 |
+
("blenderbot-small", "BlenderbotSmallConfig"),
|
| 46 |
+
("blip", "BlipConfig"),
|
| 47 |
+
("blip-2", "Blip2Config"),
|
| 48 |
+
("bloom", "BloomConfig"),
|
| 49 |
+
("bridgetower", "BridgeTowerConfig"),
|
| 50 |
+
("camembert", "CamembertConfig"),
|
| 51 |
+
("canine", "CanineConfig"),
|
| 52 |
+
("chinese_clip", "ChineseCLIPConfig"),
|
| 53 |
+
("clap", "ClapConfig"),
|
| 54 |
+
("clip", "CLIPConfig"),
|
| 55 |
+
("clipseg", "CLIPSegConfig"),
|
| 56 |
+
("codegen", "CodeGenConfig"),
|
| 57 |
+
("conditional_detr", "ConditionalDetrConfig"),
|
| 58 |
+
("convbert", "ConvBertConfig"),
|
| 59 |
+
("convnext", "ConvNextConfig"),
|
| 60 |
+
("convnextv2", "ConvNextV2Config"),
|
| 61 |
+
("cpmant", "CpmAntConfig"),
|
| 62 |
+
("ctrl", "CTRLConfig"),
|
| 63 |
+
("cvt", "CvtConfig"),
|
| 64 |
+
("data2vec-audio", "Data2VecAudioConfig"),
|
| 65 |
+
("data2vec-text", "Data2VecTextConfig"),
|
| 66 |
+
("data2vec-vision", "Data2VecVisionConfig"),
|
| 67 |
+
("deberta", "DebertaConfig"),
|
| 68 |
+
("deberta-v2", "DebertaV2Config"),
|
| 69 |
+
("decision_transformer", "DecisionTransformerConfig"),
|
| 70 |
+
("deformable_detr", "DeformableDetrConfig"),
|
| 71 |
+
("deit", "DeiTConfig"),
|
| 72 |
+
("deta", "DetaConfig"),
|
| 73 |
+
("detr", "DetrConfig"),
|
| 74 |
+
("dinat", "DinatConfig"),
|
| 75 |
+
("distilbert", "DistilBertConfig"),
|
| 76 |
+
("donut-swin", "DonutSwinConfig"),
|
| 77 |
+
("dpr", "DPRConfig"),
|
| 78 |
+
("dpt", "DPTConfig"),
|
| 79 |
+
("efficientformer", "EfficientFormerConfig"),
|
| 80 |
+
("efficientnet", "EfficientNetConfig"),
|
| 81 |
+
("electra", "ElectraConfig"),
|
| 82 |
+
("encoder-decoder", "EncoderDecoderConfig"),
|
| 83 |
+
("ernie", "ErnieConfig"),
|
| 84 |
+
("ernie_m", "ErnieMConfig"),
|
| 85 |
+
("esm", "EsmConfig"),
|
| 86 |
+
("flaubert", "FlaubertConfig"),
|
| 87 |
+
("flava", "FlavaConfig"),
|
| 88 |
+
("fnet", "FNetConfig"),
|
| 89 |
+
("focalnet", "FocalNetConfig"),
|
| 90 |
+
("fsmt", "FSMTConfig"),
|
| 91 |
+
("funnel", "FunnelConfig"),
|
| 92 |
+
("git", "GitConfig"),
|
| 93 |
+
("glpn", "GLPNConfig"),
|
| 94 |
+
("gpt-sw3", "GPT2Config"),
|
| 95 |
+
("gpt2", "GPT2Config"),
|
| 96 |
+
("gpt_bigcode", "GPTBigCodeConfig"),
|
| 97 |
+
("gpt_neo", "GPTNeoConfig"),
|
| 98 |
+
("gpt_neox", "GPTNeoXConfig"),
|
| 99 |
+
("gpt_neox_japanese", "GPTNeoXJapaneseConfig"),
|
| 100 |
+
("gptj", "GPTJConfig"),
|
| 101 |
+
("gptsan-japanese", "GPTSanJapaneseConfig"),
|
| 102 |
+
("graphormer", "GraphormerConfig"),
|
| 103 |
+
("groupvit", "GroupViTConfig"),
|
| 104 |
+
("hubert", "HubertConfig"),
|
| 105 |
+
("ibert", "IBertConfig"),
|
| 106 |
+
("imagegpt", "ImageGPTConfig"),
|
| 107 |
+
("informer", "InformerConfig"),
|
| 108 |
+
("jukebox", "JukeboxConfig"),
|
| 109 |
+
("layoutlm", "LayoutLMConfig"),
|
| 110 |
+
("layoutlmv2", "LayoutLMv2Config"),
|
| 111 |
+
("layoutlmv3", "LayoutLMv3Config"),
|
| 112 |
+
("led", "LEDConfig"),
|
| 113 |
+
("levit", "LevitConfig"),
|
| 114 |
+
("lilt", "LiltConfig"),
|
| 115 |
+
("llama", "LlamaConfig"),
|
| 116 |
+
("longformer", "LongformerConfig"),
|
| 117 |
+
("longt5", "LongT5Config"),
|
| 118 |
+
("luke", "LukeConfig"),
|
| 119 |
+
("lxmert", "LxmertConfig"),
|
| 120 |
+
("m2m_100", "M2M100Config"),
|
| 121 |
+
("marian", "MarianConfig"),
|
| 122 |
+
("markuplm", "MarkupLMConfig"),
|
| 123 |
+
("mask2former", "Mask2FormerConfig"),
|
| 124 |
+
("maskformer", "MaskFormerConfig"),
|
| 125 |
+
("maskformer-swin", "MaskFormerSwinConfig"),
|
| 126 |
+
("mbart", "MBartConfig"),
|
| 127 |
+
("mctct", "MCTCTConfig"),
|
| 128 |
+
("mega", "MegaConfig"),
|
| 129 |
+
("megatron-bert", "MegatronBertConfig"),
|
| 130 |
+
("mgp-str", "MgpstrConfig"),
|
| 131 |
+
("mobilebert", "MobileBertConfig"),
|
| 132 |
+
("mobilenet_v1", "MobileNetV1Config"),
|
| 133 |
+
("mobilenet_v2", "MobileNetV2Config"),
|
| 134 |
+
("mobilevit", "MobileViTConfig"),
|
| 135 |
+
("mpnet", "MPNetConfig"),
|
| 136 |
+
("mt5", "MT5Config"),
|
| 137 |
+
("mvp", "MvpConfig"),
|
| 138 |
+
("nat", "NatConfig"),
|
| 139 |
+
("nezha", "NezhaConfig"),
|
| 140 |
+
("nllb-moe", "NllbMoeConfig"),
|
| 141 |
+
("nystromformer", "NystromformerConfig"),
|
| 142 |
+
("oneformer", "OneFormerConfig"),
|
| 143 |
+
("open-llama", "OpenLlamaConfig"),
|
| 144 |
+
("openai-gpt", "OpenAIGPTConfig"),
|
| 145 |
+
("opt", "OPTConfig"),
|
| 146 |
+
("owlvit", "OwlViTConfig"),
|
| 147 |
+
("pegasus", "PegasusConfig"),
|
| 148 |
+
("pegasus_x", "PegasusXConfig"),
|
| 149 |
+
("perceiver", "PerceiverConfig"),
|
| 150 |
+
("pix2struct", "Pix2StructConfig"),
|
| 151 |
+
("plbart", "PLBartConfig"),
|
| 152 |
+
("poolformer", "PoolFormerConfig"),
|
| 153 |
+
("prophetnet", "ProphetNetConfig"),
|
| 154 |
+
("qdqbert", "QDQBertConfig"),
|
| 155 |
+
("rag", "RagConfig"),
|
| 156 |
+
("realm", "RealmConfig"),
|
| 157 |
+
("reformer", "ReformerConfig"),
|
| 158 |
+
("regnet", "RegNetConfig"),
|
| 159 |
+
("rembert", "RemBertConfig"),
|
| 160 |
+
("resnet", "ResNetConfig"),
|
| 161 |
+
("retribert", "RetriBertConfig"),
|
| 162 |
+
("roberta", "RobertaConfig"),
|
| 163 |
+
("roberta-prelayernorm", "RobertaPreLayerNormConfig"),
|
| 164 |
+
("roc_bert", "RoCBertConfig"),
|
| 165 |
+
("roformer", "RoFormerConfig"),
|
| 166 |
+
("rwkv", "RwkvConfig"),
|
| 167 |
+
("sam", "SamConfig"),
|
| 168 |
+
("segformer", "SegformerConfig"),
|
| 169 |
+
("sew", "SEWConfig"),
|
| 170 |
+
("sew-d", "SEWDConfig"),
|
| 171 |
+
("speech-encoder-decoder", "SpeechEncoderDecoderConfig"),
|
| 172 |
+
("speech_to_text", "Speech2TextConfig"),
|
| 173 |
+
("speech_to_text_2", "Speech2Text2Config"),
|
| 174 |
+
("speecht5", "SpeechT5Config"),
|
| 175 |
+
("splinter", "SplinterConfig"),
|
| 176 |
+
("squeezebert", "SqueezeBertConfig"),
|
| 177 |
+
("swin", "SwinConfig"),
|
| 178 |
+
("swin2sr", "Swin2SRConfig"),
|
| 179 |
+
("swinv2", "Swinv2Config"),
|
| 180 |
+
("switch_transformers", "SwitchTransformersConfig"),
|
| 181 |
+
("t5", "T5Config"),
|
| 182 |
+
("table-transformer", "TableTransformerConfig"),
|
| 183 |
+
("tapas", "TapasConfig"),
|
| 184 |
+
("time_series_transformer", "TimeSeriesTransformerConfig"),
|
| 185 |
+
("timesformer", "TimesformerConfig"),
|
| 186 |
+
("trajectory_transformer", "TrajectoryTransformerConfig"),
|
| 187 |
+
("transfo-xl", "TransfoXLConfig"),
|
| 188 |
+
("trocr", "TrOCRConfig"),
|
| 189 |
+
("tvlt", "TvltConfig"),
|
| 190 |
+
("unispeech", "UniSpeechConfig"),
|
| 191 |
+
("unispeech-sat", "UniSpeechSatConfig"),
|
| 192 |
+
("upernet", "UperNetConfig"),
|
| 193 |
+
("van", "VanConfig"),
|
| 194 |
+
("videomae", "VideoMAEConfig"),
|
| 195 |
+
("vilt", "ViltConfig"),
|
| 196 |
+
("vision-encoder-decoder", "VisionEncoderDecoderConfig"),
|
| 197 |
+
("vision-text-dual-encoder", "VisionTextDualEncoderConfig"),
|
| 198 |
+
("visual_bert", "VisualBertConfig"),
|
| 199 |
+
("vit", "ViTConfig"),
|
| 200 |
+
("vit_hybrid", "ViTHybridConfig"),
|
| 201 |
+
("vit_mae", "ViTMAEConfig"),
|
| 202 |
+
("vit_msn", "ViTMSNConfig"),
|
| 203 |
+
("wav2vec2", "Wav2Vec2Config"),
|
| 204 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerConfig"),
|
| 205 |
+
("wavlm", "WavLMConfig"),
|
| 206 |
+
("whisper", "WhisperConfig"),
|
| 207 |
+
("xclip", "XCLIPConfig"),
|
| 208 |
+
("xglm", "XGLMConfig"),
|
| 209 |
+
("xlm", "XLMConfig"),
|
| 210 |
+
("xlm-prophetnet", "XLMProphetNetConfig"),
|
| 211 |
+
("xlm-roberta", "XLMRobertaConfig"),
|
| 212 |
+
("xlm-roberta-xl", "XLMRobertaXLConfig"),
|
| 213 |
+
("xlnet", "XLNetConfig"),
|
| 214 |
+
("xmod", "XmodConfig"),
|
| 215 |
+
("yolos", "YolosConfig"),
|
| 216 |
+
("yoso", "YosoConfig"),
|
| 217 |
+
]
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
CONFIG_ARCHIVE_MAP_MAPPING_NAMES = OrderedDict(
|
| 221 |
+
[
|
| 222 |
+
# Add archive maps here)
|
| 223 |
+
("albert", "ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 224 |
+
("align", "ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 225 |
+
("altclip", "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 226 |
+
("audio-spectrogram-transformer", "AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 227 |
+
("bart", "BART_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 228 |
+
("beit", "BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 229 |
+
("bert", "BERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 230 |
+
("big_bird", "BIG_BIRD_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 231 |
+
("bigbird_pegasus", "BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 232 |
+
("biogpt", "BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 233 |
+
("bit", "BIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 234 |
+
("blenderbot", "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 235 |
+
("blenderbot-small", "BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 236 |
+
("blip", "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 237 |
+
("blip-2", "BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 238 |
+
("bloom", "BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 239 |
+
("bridgetower", "BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 240 |
+
("camembert", "CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 241 |
+
("canine", "CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 242 |
+
("chinese_clip", "CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 243 |
+
("clap", "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST"),
|
| 244 |
+
("clip", "CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 245 |
+
("clipseg", "CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 246 |
+
("codegen", "CODEGEN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 247 |
+
("conditional_detr", "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 248 |
+
("convbert", "CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 249 |
+
("convnext", "CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 250 |
+
("convnextv2", "CONVNEXTV2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 251 |
+
("cpmant", "CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 252 |
+
("ctrl", "CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 253 |
+
("cvt", "CVT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 254 |
+
("data2vec-audio", "DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 255 |
+
("data2vec-text", "DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 256 |
+
("data2vec-vision", "DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 257 |
+
("deberta", "DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 258 |
+
("deberta-v2", "DEBERTA_V2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 259 |
+
("deformable_detr", "DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 260 |
+
("deit", "DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 261 |
+
("deta", "DETA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 262 |
+
("detr", "DETR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 263 |
+
("dinat", "DINAT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 264 |
+
("distilbert", "DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 265 |
+
("donut-swin", "DONUT_SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 266 |
+
("dpr", "DPR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 267 |
+
("dpt", "DPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 268 |
+
("efficientformer", "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 269 |
+
("efficientnet", "EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 270 |
+
("electra", "ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 271 |
+
("ernie", "ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 272 |
+
("ernie_m", "ERNIE_M_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 273 |
+
("esm", "ESM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 274 |
+
("flaubert", "FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 275 |
+
("flava", "FLAVA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 276 |
+
("fnet", "FNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 277 |
+
("focalnet", "FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 278 |
+
("fsmt", "FSMT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 279 |
+
("funnel", "FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 280 |
+
("git", "GIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 281 |
+
("glpn", "GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 282 |
+
("gpt2", "GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 283 |
+
("gpt_bigcode", "GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 284 |
+
("gpt_neo", "GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 285 |
+
("gpt_neox", "GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 286 |
+
("gpt_neox_japanese", "GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 287 |
+
("gptj", "GPTJ_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 288 |
+
("gptsan-japanese", "GPTSAN_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 289 |
+
("graphormer", "GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 290 |
+
("groupvit", "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 291 |
+
("hubert", "HUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 292 |
+
("ibert", "IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 293 |
+
("imagegpt", "IMAGEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 294 |
+
("informer", "INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 295 |
+
("jukebox", "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 296 |
+
("layoutlm", "LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 297 |
+
("layoutlmv2", "LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 298 |
+
("layoutlmv3", "LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 299 |
+
("led", "LED_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 300 |
+
("levit", "LEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 301 |
+
("lilt", "LILT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 302 |
+
("llama", "LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 303 |
+
("longformer", "LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 304 |
+
("longt5", "LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 305 |
+
("luke", "LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 306 |
+
("lxmert", "LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 307 |
+
("m2m_100", "M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 308 |
+
("markuplm", "MARKUPLM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 309 |
+
("mask2former", "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 310 |
+
("maskformer", "MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 311 |
+
("mbart", "MBART_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 312 |
+
("mctct", "MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 313 |
+
("mega", "MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 314 |
+
("megatron-bert", "MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 315 |
+
("mgp-str", "MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 316 |
+
("mobilenet_v1", "MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 317 |
+
("mobilenet_v2", "MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 318 |
+
("mobilevit", "MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 319 |
+
("mpnet", "MPNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 320 |
+
("mvp", "MVP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 321 |
+
("nat", "NAT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 322 |
+
("nezha", "NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 323 |
+
("nllb-moe", "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 324 |
+
("nystromformer", "NYSTROMFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 325 |
+
("oneformer", "ONEFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 326 |
+
("open-llama", "OPEN_LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 327 |
+
("openai-gpt", "OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 328 |
+
("opt", "OPT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 329 |
+
("owlvit", "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 330 |
+
("pegasus", "PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 331 |
+
("pegasus_x", "PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 332 |
+
("perceiver", "PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 333 |
+
("pix2struct", "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 334 |
+
("plbart", "PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 335 |
+
("poolformer", "POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 336 |
+
("prophetnet", "PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 337 |
+
("qdqbert", "QDQBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 338 |
+
("realm", "REALM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 339 |
+
("regnet", "REGNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 340 |
+
("rembert", "REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 341 |
+
("resnet", "RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 342 |
+
("retribert", "RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 343 |
+
("roberta", "ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 344 |
+
("roberta-prelayernorm", "ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 345 |
+
("roc_bert", "ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 346 |
+
("roformer", "ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 347 |
+
("rwkv", "RWKV_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 348 |
+
("sam", "SAM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 349 |
+
("segformer", "SEGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 350 |
+
("sew", "SEW_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 351 |
+
("sew-d", "SEW_D_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 352 |
+
("speech_to_text", "SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 353 |
+
("speech_to_text_2", "SPEECH_TO_TEXT_2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 354 |
+
("speecht5", "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 355 |
+
("splinter", "SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 356 |
+
("squeezebert", "SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 357 |
+
("swin", "SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 358 |
+
("swin2sr", "SWIN2SR_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 359 |
+
("swinv2", "SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 360 |
+
("switch_transformers", "SWITCH_TRANSFORMERS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 361 |
+
("t5", "T5_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 362 |
+
("table-transformer", "TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 363 |
+
("tapas", "TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 364 |
+
("time_series_transformer", "TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 365 |
+
("timesformer", "TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 366 |
+
("transfo-xl", "TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 367 |
+
("tvlt", "TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 368 |
+
("unispeech", "UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 369 |
+
("unispeech-sat", "UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 370 |
+
("van", "VAN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 371 |
+
("videomae", "VIDEOMAE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 372 |
+
("vilt", "VILT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 373 |
+
("visual_bert", "VISUAL_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 374 |
+
("vit", "VIT_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 375 |
+
("vit_hybrid", "VIT_HYBRID_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 376 |
+
("vit_mae", "VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 377 |
+
("vit_msn", "VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 378 |
+
("wav2vec2", "WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 379 |
+
("wav2vec2-conformer", "WAV2VEC2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 380 |
+
("whisper", "WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 381 |
+
("xclip", "XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 382 |
+
("xglm", "XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 383 |
+
("xlm", "XLM_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 384 |
+
("xlm-prophetnet", "XLM_PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 385 |
+
("xlm-roberta", "XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 386 |
+
("xlnet", "XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 387 |
+
("xmod", "XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 388 |
+
("yolos", "YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 389 |
+
("yoso", "YOSO_PRETRAINED_CONFIG_ARCHIVE_MAP"),
|
| 390 |
+
]
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
MODEL_NAMES_MAPPING = OrderedDict(
|
| 394 |
+
[
|
| 395 |
+
# Add full (and cased) model names here
|
| 396 |
+
("albert", "ALBERT"),
|
| 397 |
+
("align", "ALIGN"),
|
| 398 |
+
("altclip", "AltCLIP"),
|
| 399 |
+
("audio-spectrogram-transformer", "Audio Spectrogram Transformer"),
|
| 400 |
+
("bart", "BART"),
|
| 401 |
+
("barthez", "BARThez"),
|
| 402 |
+
("bartpho", "BARTpho"),
|
| 403 |
+
("beit", "BEiT"),
|
| 404 |
+
("bert", "BERT"),
|
| 405 |
+
("bert-generation", "Bert Generation"),
|
| 406 |
+
("bert-japanese", "BertJapanese"),
|
| 407 |
+
("bertweet", "BERTweet"),
|
| 408 |
+
("big_bird", "BigBird"),
|
| 409 |
+
("bigbird_pegasus", "BigBird-Pegasus"),
|
| 410 |
+
("biogpt", "BioGpt"),
|
| 411 |
+
("bit", "BiT"),
|
| 412 |
+
("blenderbot", "Blenderbot"),
|
| 413 |
+
("blenderbot-small", "BlenderbotSmall"),
|
| 414 |
+
("blip", "BLIP"),
|
| 415 |
+
("blip-2", "BLIP-2"),
|
| 416 |
+
("bloom", "BLOOM"),
|
| 417 |
+
("bort", "BORT"),
|
| 418 |
+
("bridgetower", "BridgeTower"),
|
| 419 |
+
("byt5", "ByT5"),
|
| 420 |
+
("camembert", "CamemBERT"),
|
| 421 |
+
("canine", "CANINE"),
|
| 422 |
+
("chinese_clip", "Chinese-CLIP"),
|
| 423 |
+
("clap", "CLAP"),
|
| 424 |
+
("clip", "CLIP"),
|
| 425 |
+
("clipseg", "CLIPSeg"),
|
| 426 |
+
("codegen", "CodeGen"),
|
| 427 |
+
("conditional_detr", "Conditional DETR"),
|
| 428 |
+
("convbert", "ConvBERT"),
|
| 429 |
+
("convnext", "ConvNeXT"),
|
| 430 |
+
("convnextv2", "ConvNeXTV2"),
|
| 431 |
+
("cpm", "CPM"),
|
| 432 |
+
("cpmant", "CPM-Ant"),
|
| 433 |
+
("ctrl", "CTRL"),
|
| 434 |
+
("cvt", "CvT"),
|
| 435 |
+
("data2vec-audio", "Data2VecAudio"),
|
| 436 |
+
("data2vec-text", "Data2VecText"),
|
| 437 |
+
("data2vec-vision", "Data2VecVision"),
|
| 438 |
+
("deberta", "DeBERTa"),
|
| 439 |
+
("deberta-v2", "DeBERTa-v2"),
|
| 440 |
+
("decision_transformer", "Decision Transformer"),
|
| 441 |
+
("deformable_detr", "Deformable DETR"),
|
| 442 |
+
("deit", "DeiT"),
|
| 443 |
+
("deplot", "DePlot"),
|
| 444 |
+
("deta", "DETA"),
|
| 445 |
+
("detr", "DETR"),
|
| 446 |
+
("dialogpt", "DialoGPT"),
|
| 447 |
+
("dinat", "DiNAT"),
|
| 448 |
+
("distilbert", "DistilBERT"),
|
| 449 |
+
("dit", "DiT"),
|
| 450 |
+
("donut-swin", "DonutSwin"),
|
| 451 |
+
("dpr", "DPR"),
|
| 452 |
+
("dpt", "DPT"),
|
| 453 |
+
("efficientformer", "EfficientFormer"),
|
| 454 |
+
("efficientnet", "EfficientNet"),
|
| 455 |
+
("electra", "ELECTRA"),
|
| 456 |
+
("encoder-decoder", "Encoder decoder"),
|
| 457 |
+
("ernie", "ERNIE"),
|
| 458 |
+
("ernie_m", "ErnieM"),
|
| 459 |
+
("esm", "ESM"),
|
| 460 |
+
("flan-t5", "FLAN-T5"),
|
| 461 |
+
("flan-ul2", "FLAN-UL2"),
|
| 462 |
+
("flaubert", "FlauBERT"),
|
| 463 |
+
("flava", "FLAVA"),
|
| 464 |
+
("fnet", "FNet"),
|
| 465 |
+
("focalnet", "FocalNet"),
|
| 466 |
+
("fsmt", "FairSeq Machine-Translation"),
|
| 467 |
+
("funnel", "Funnel Transformer"),
|
| 468 |
+
("git", "GIT"),
|
| 469 |
+
("glpn", "GLPN"),
|
| 470 |
+
("gpt-sw3", "GPT-Sw3"),
|
| 471 |
+
("gpt2", "OpenAI GPT-2"),
|
| 472 |
+
("gpt_bigcode", "GPTBigCode"),
|
| 473 |
+
("gpt_neo", "GPT Neo"),
|
| 474 |
+
("gpt_neox", "GPT NeoX"),
|
| 475 |
+
("gpt_neox_japanese", "GPT NeoX Japanese"),
|
| 476 |
+
("gptj", "GPT-J"),
|
| 477 |
+
("gptsan-japanese", "GPTSAN-japanese"),
|
| 478 |
+
("graphormer", "Graphormer"),
|
| 479 |
+
("groupvit", "GroupViT"),
|
| 480 |
+
("herbert", "HerBERT"),
|
| 481 |
+
("hubert", "Hubert"),
|
| 482 |
+
("ibert", "I-BERT"),
|
| 483 |
+
("imagegpt", "ImageGPT"),
|
| 484 |
+
("informer", "Informer"),
|
| 485 |
+
("jukebox", "Jukebox"),
|
| 486 |
+
("layoutlm", "LayoutLM"),
|
| 487 |
+
("layoutlmv2", "LayoutLMv2"),
|
| 488 |
+
("layoutlmv3", "LayoutLMv3"),
|
| 489 |
+
("layoutxlm", "LayoutXLM"),
|
| 490 |
+
("led", "LED"),
|
| 491 |
+
("levit", "LeViT"),
|
| 492 |
+
("lilt", "LiLT"),
|
| 493 |
+
("llama", "LLaMA"),
|
| 494 |
+
("longformer", "Longformer"),
|
| 495 |
+
("longt5", "LongT5"),
|
| 496 |
+
("luke", "LUKE"),
|
| 497 |
+
("lxmert", "LXMERT"),
|
| 498 |
+
("m2m_100", "M2M100"),
|
| 499 |
+
("marian", "Marian"),
|
| 500 |
+
("markuplm", "MarkupLM"),
|
| 501 |
+
("mask2former", "Mask2Former"),
|
| 502 |
+
("maskformer", "MaskFormer"),
|
| 503 |
+
("maskformer-swin", "MaskFormerSwin"),
|
| 504 |
+
("matcha", "MatCha"),
|
| 505 |
+
("mbart", "mBART"),
|
| 506 |
+
("mbart50", "mBART-50"),
|
| 507 |
+
("mctct", "M-CTC-T"),
|
| 508 |
+
("mega", "MEGA"),
|
| 509 |
+
("megatron-bert", "Megatron-BERT"),
|
| 510 |
+
("megatron_gpt2", "Megatron-GPT2"),
|
| 511 |
+
("mgp-str", "MGP-STR"),
|
| 512 |
+
("mluke", "mLUKE"),
|
| 513 |
+
("mobilebert", "MobileBERT"),
|
| 514 |
+
("mobilenet_v1", "MobileNetV1"),
|
| 515 |
+
("mobilenet_v2", "MobileNetV2"),
|
| 516 |
+
("mobilevit", "MobileViT"),
|
| 517 |
+
("mpnet", "MPNet"),
|
| 518 |
+
("mt5", "MT5"),
|
| 519 |
+
("mvp", "MVP"),
|
| 520 |
+
("nat", "NAT"),
|
| 521 |
+
("nezha", "Nezha"),
|
| 522 |
+
("nllb", "NLLB"),
|
| 523 |
+
("nllb-moe", "NLLB-MOE"),
|
| 524 |
+
("nystromformer", "Nyströmformer"),
|
| 525 |
+
("oneformer", "OneFormer"),
|
| 526 |
+
("open-llama", "OpenLlama"),
|
| 527 |
+
("openai-gpt", "OpenAI GPT"),
|
| 528 |
+
("opt", "OPT"),
|
| 529 |
+
("owlvit", "OWL-ViT"),
|
| 530 |
+
("pegasus", "Pegasus"),
|
| 531 |
+
("pegasus_x", "PEGASUS-X"),
|
| 532 |
+
("perceiver", "Perceiver"),
|
| 533 |
+
("phobert", "PhoBERT"),
|
| 534 |
+
("pix2struct", "Pix2Struct"),
|
| 535 |
+
("plbart", "PLBart"),
|
| 536 |
+
("poolformer", "PoolFormer"),
|
| 537 |
+
("prophetnet", "ProphetNet"),
|
| 538 |
+
("qdqbert", "QDQBert"),
|
| 539 |
+
("rag", "RAG"),
|
| 540 |
+
("realm", "REALM"),
|
| 541 |
+
("reformer", "Reformer"),
|
| 542 |
+
("regnet", "RegNet"),
|
| 543 |
+
("rembert", "RemBERT"),
|
| 544 |
+
("resnet", "ResNet"),
|
| 545 |
+
("retribert", "RetriBERT"),
|
| 546 |
+
("roberta", "RoBERTa"),
|
| 547 |
+
("roberta-prelayernorm", "RoBERTa-PreLayerNorm"),
|
| 548 |
+
("roc_bert", "RoCBert"),
|
| 549 |
+
("roformer", "RoFormer"),
|
| 550 |
+
("rwkv", "RWKV"),
|
| 551 |
+
("sam", "SAM"),
|
| 552 |
+
("segformer", "SegFormer"),
|
| 553 |
+
("sew", "SEW"),
|
| 554 |
+
("sew-d", "SEW-D"),
|
| 555 |
+
("speech-encoder-decoder", "Speech Encoder decoder"),
|
| 556 |
+
("speech_to_text", "Speech2Text"),
|
| 557 |
+
("speech_to_text_2", "Speech2Text2"),
|
| 558 |
+
("speecht5", "SpeechT5"),
|
| 559 |
+
("splinter", "Splinter"),
|
| 560 |
+
("squeezebert", "SqueezeBERT"),
|
| 561 |
+
("swin", "Swin Transformer"),
|
| 562 |
+
("swin2sr", "Swin2SR"),
|
| 563 |
+
("swinv2", "Swin Transformer V2"),
|
| 564 |
+
("switch_transformers", "SwitchTransformers"),
|
| 565 |
+
("t5", "T5"),
|
| 566 |
+
("t5v1.1", "T5v1.1"),
|
| 567 |
+
("table-transformer", "Table Transformer"),
|
| 568 |
+
("tapas", "TAPAS"),
|
| 569 |
+
("tapex", "TAPEX"),
|
| 570 |
+
("time_series_transformer", "Time Series Transformer"),
|
| 571 |
+
("timesformer", "TimeSformer"),
|
| 572 |
+
("trajectory_transformer", "Trajectory Transformer"),
|
| 573 |
+
("transfo-xl", "Transformer-XL"),
|
| 574 |
+
("trocr", "TrOCR"),
|
| 575 |
+
("tvlt", "TVLT"),
|
| 576 |
+
("ul2", "UL2"),
|
| 577 |
+
("unispeech", "UniSpeech"),
|
| 578 |
+
("unispeech-sat", "UniSpeechSat"),
|
| 579 |
+
("upernet", "UPerNet"),
|
| 580 |
+
("van", "VAN"),
|
| 581 |
+
("videomae", "VideoMAE"),
|
| 582 |
+
("vilt", "ViLT"),
|
| 583 |
+
("vision-encoder-decoder", "Vision Encoder decoder"),
|
| 584 |
+
("vision-text-dual-encoder", "VisionTextDualEncoder"),
|
| 585 |
+
("visual_bert", "VisualBERT"),
|
| 586 |
+
("vit", "ViT"),
|
| 587 |
+
("vit_hybrid", "ViT Hybrid"),
|
| 588 |
+
("vit_mae", "ViTMAE"),
|
| 589 |
+
("vit_msn", "ViTMSN"),
|
| 590 |
+
("wav2vec2", "Wav2Vec2"),
|
| 591 |
+
("wav2vec2-conformer", "Wav2Vec2-Conformer"),
|
| 592 |
+
("wav2vec2_phoneme", "Wav2Vec2Phoneme"),
|
| 593 |
+
("wavlm", "WavLM"),
|
| 594 |
+
("whisper", "Whisper"),
|
| 595 |
+
("xclip", "X-CLIP"),
|
| 596 |
+
("xglm", "XGLM"),
|
| 597 |
+
("xlm", "XLM"),
|
| 598 |
+
("xlm-prophetnet", "XLM-ProphetNet"),
|
| 599 |
+
("xlm-roberta", "XLM-RoBERTa"),
|
| 600 |
+
("xlm-roberta-xl", "XLM-RoBERTa-XL"),
|
| 601 |
+
("xlm-v", "XLM-V"),
|
| 602 |
+
("xlnet", "XLNet"),
|
| 603 |
+
("xls_r", "XLS-R"),
|
| 604 |
+
("xlsr_wav2vec2", "XLSR-Wav2Vec2"),
|
| 605 |
+
("xmod", "X-MOD"),
|
| 606 |
+
("yolos", "YOLOS"),
|
| 607 |
+
("yoso", "YOSO"),
|
| 608 |
+
]
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
SPECIAL_MODEL_TYPE_TO_MODULE_NAME = OrderedDict(
|
| 612 |
+
[
|
| 613 |
+
("openai-gpt", "openai"),
|
| 614 |
+
("data2vec-audio", "data2vec"),
|
| 615 |
+
("data2vec-text", "data2vec"),
|
| 616 |
+
("data2vec-vision", "data2vec"),
|
| 617 |
+
("donut-swin", "donut"),
|
| 618 |
+
("maskformer-swin", "maskformer"),
|
| 619 |
+
("xclip", "x_clip"),
|
| 620 |
+
]
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
def model_type_to_module_name(key):
|
| 625 |
+
"""Converts a config key to the corresponding module."""
|
| 626 |
+
# Special treatment
|
| 627 |
+
if key in SPECIAL_MODEL_TYPE_TO_MODULE_NAME:
|
| 628 |
+
return SPECIAL_MODEL_TYPE_TO_MODULE_NAME[key]
|
| 629 |
+
|
| 630 |
+
return key.replace("-", "_")
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
def config_class_to_model_type(config):
|
| 634 |
+
"""Converts a config class name to the corresponding model type"""
|
| 635 |
+
for key, cls in CONFIG_MAPPING_NAMES.items():
|
| 636 |
+
if cls == config:
|
| 637 |
+
return key
|
| 638 |
+
return None
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
class _LazyConfigMapping(OrderedDict):
|
| 642 |
+
"""
|
| 643 |
+
A dictionary that lazily load its values when they are requested.
|
| 644 |
+
"""
|
| 645 |
+
|
| 646 |
+
def __init__(self, mapping):
|
| 647 |
+
self._mapping = mapping
|
| 648 |
+
self._extra_content = {}
|
| 649 |
+
self._modules = {}
|
| 650 |
+
|
| 651 |
+
def __getitem__(self, key):
|
| 652 |
+
if key in self._extra_content:
|
| 653 |
+
return self._extra_content[key]
|
| 654 |
+
if key not in self._mapping:
|
| 655 |
+
raise KeyError(key)
|
| 656 |
+
value = self._mapping[key]
|
| 657 |
+
module_name = model_type_to_module_name(key)
|
| 658 |
+
if module_name not in self._modules:
|
| 659 |
+
self._modules[module_name] = importlib.import_module(f".{module_name}", "transformers.models")
|
| 660 |
+
if hasattr(self._modules[module_name], value):
|
| 661 |
+
return getattr(self._modules[module_name], value)
|
| 662 |
+
|
| 663 |
+
# Some of the mappings have entries model_type -> config of another model type. In that case we try to grab the
|
| 664 |
+
# object at the top level.
|
| 665 |
+
transformers_module = importlib.import_module("transformers")
|
| 666 |
+
return getattr(transformers_module, value)
|
| 667 |
+
|
| 668 |
+
def keys(self):
|
| 669 |
+
return list(self._mapping.keys()) + list(self._extra_content.keys())
|
| 670 |
+
|
| 671 |
+
def values(self):
|
| 672 |
+
return [self[k] for k in self._mapping.keys()] + list(self._extra_content.values())
|
| 673 |
+
|
| 674 |
+
def items(self):
|
| 675 |
+
return [(k, self[k]) for k in self._mapping.keys()] + list(self._extra_content.items())
|
| 676 |
+
|
| 677 |
+
def __iter__(self):
|
| 678 |
+
return iter(list(self._mapping.keys()) + list(self._extra_content.keys()))
|
| 679 |
+
|
| 680 |
+
def __contains__(self, item):
|
| 681 |
+
return item in self._mapping or item in self._extra_content
|
| 682 |
+
|
| 683 |
+
def register(self, key, value):
|
| 684 |
+
"""
|
| 685 |
+
Register a new configuration in this mapping.
|
| 686 |
+
"""
|
| 687 |
+
if key in self._mapping.keys():
|
| 688 |
+
raise ValueError(f"'{key}' is already used by a Transformers config, pick another name.")
|
| 689 |
+
self._extra_content[key] = value
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
CONFIG_MAPPING = _LazyConfigMapping(CONFIG_MAPPING_NAMES)
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
class _LazyLoadAllMappings(OrderedDict):
|
| 696 |
+
"""
|
| 697 |
+
A mapping that will load all pairs of key values at the first access (either by indexing, requestions keys, values,
|
| 698 |
+
etc.)
|
| 699 |
+
|
| 700 |
+
Args:
|
| 701 |
+
mapping: The mapping to load.
|
| 702 |
+
"""
|
| 703 |
+
|
| 704 |
+
def __init__(self, mapping):
|
| 705 |
+
self._mapping = mapping
|
| 706 |
+
self._initialized = False
|
| 707 |
+
self._data = {}
|
| 708 |
+
|
| 709 |
+
def _initialize(self):
|
| 710 |
+
if self._initialized:
|
| 711 |
+
return
|
| 712 |
+
warnings.warn(
|
| 713 |
+
"ALL_PRETRAINED_CONFIG_ARCHIVE_MAP is deprecated and will be removed in v5 of Transformers. "
|
| 714 |
+
"It does not contain all available model checkpoints, far from it. Checkout hf.co/models for that.",
|
| 715 |
+
FutureWarning,
|
| 716 |
+
)
|
| 717 |
+
|
| 718 |
+
for model_type, map_name in self._mapping.items():
|
| 719 |
+
module_name = model_type_to_module_name(model_type)
|
| 720 |
+
module = importlib.import_module(f".{module_name}", "transformers.models")
|
| 721 |
+
mapping = getattr(module, map_name)
|
| 722 |
+
self._data.update(mapping)
|
| 723 |
+
|
| 724 |
+
self._initialized = True
|
| 725 |
+
|
| 726 |
+
def __getitem__(self, key):
|
| 727 |
+
self._initialize()
|
| 728 |
+
return self._data[key]
|
| 729 |
+
|
| 730 |
+
def keys(self):
|
| 731 |
+
self._initialize()
|
| 732 |
+
return self._data.keys()
|
| 733 |
+
|
| 734 |
+
def values(self):
|
| 735 |
+
self._initialize()
|
| 736 |
+
return self._data.values()
|
| 737 |
+
|
| 738 |
+
def items(self):
|
| 739 |
+
self._initialize()
|
| 740 |
+
return self._data.keys()
|
| 741 |
+
|
| 742 |
+
def __iter__(self):
|
| 743 |
+
self._initialize()
|
| 744 |
+
return iter(self._data)
|
| 745 |
+
|
| 746 |
+
def __contains__(self, item):
|
| 747 |
+
self._initialize()
|
| 748 |
+
return item in self._data
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
ALL_PRETRAINED_CONFIG_ARCHIVE_MAP = _LazyLoadAllMappings(CONFIG_ARCHIVE_MAP_MAPPING_NAMES)
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def _get_class_name(model_class: Union[str, List[str]]):
|
| 755 |
+
if isinstance(model_class, (list, tuple)):
|
| 756 |
+
return " or ".join([f"[`{c}`]" for c in model_class if c is not None])
|
| 757 |
+
return f"[`{model_class}`]"
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
def _list_model_options(indent, config_to_class=None, use_model_types=True):
|
| 761 |
+
if config_to_class is None and not use_model_types:
|
| 762 |
+
raise ValueError("Using `use_model_types=False` requires a `config_to_class` dictionary.")
|
| 763 |
+
if use_model_types:
|
| 764 |
+
if config_to_class is None:
|
| 765 |
+
model_type_to_name = {model_type: f"[`{config}`]" for model_type, config in CONFIG_MAPPING_NAMES.items()}
|
| 766 |
+
else:
|
| 767 |
+
model_type_to_name = {
|
| 768 |
+
model_type: _get_class_name(model_class)
|
| 769 |
+
for model_type, model_class in config_to_class.items()
|
| 770 |
+
if model_type in MODEL_NAMES_MAPPING
|
| 771 |
+
}
|
| 772 |
+
lines = [
|
| 773 |
+
f"{indent}- **{model_type}** -- {model_type_to_name[model_type]} ({MODEL_NAMES_MAPPING[model_type]} model)"
|
| 774 |
+
for model_type in sorted(model_type_to_name.keys())
|
| 775 |
+
]
|
| 776 |
+
else:
|
| 777 |
+
config_to_name = {
|
| 778 |
+
CONFIG_MAPPING_NAMES[config]: _get_class_name(clas)
|
| 779 |
+
for config, clas in config_to_class.items()
|
| 780 |
+
if config in CONFIG_MAPPING_NAMES
|
| 781 |
+
}
|
| 782 |
+
config_to_model_name = {
|
| 783 |
+
config: MODEL_NAMES_MAPPING[model_type] for model_type, config in CONFIG_MAPPING_NAMES.items()
|
| 784 |
+
}
|
| 785 |
+
lines = [
|
| 786 |
+
f"{indent}- [`{config_name}`] configuration class:"
|
| 787 |
+
f" {config_to_name[config_name]} ({config_to_model_name[config_name]} model)"
|
| 788 |
+
for config_name in sorted(config_to_name.keys())
|
| 789 |
+
]
|
| 790 |
+
return "\n".join(lines)
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
def replace_list_option_in_docstrings(config_to_class=None, use_model_types=True):
|
| 794 |
+
def docstring_decorator(fn):
|
| 795 |
+
docstrings = fn.__doc__
|
| 796 |
+
lines = docstrings.split("\n")
|
| 797 |
+
i = 0
|
| 798 |
+
while i < len(lines) and re.search(r"^(\s*)List options\s*$", lines[i]) is None:
|
| 799 |
+
i += 1
|
| 800 |
+
if i < len(lines):
|
| 801 |
+
indent = re.search(r"^(\s*)List options\s*$", lines[i]).groups()[0]
|
| 802 |
+
if use_model_types:
|
| 803 |
+
indent = f"{indent} "
|
| 804 |
+
lines[i] = _list_model_options(indent, config_to_class=config_to_class, use_model_types=use_model_types)
|
| 805 |
+
docstrings = "\n".join(lines)
|
| 806 |
+
else:
|
| 807 |
+
raise ValueError(
|
| 808 |
+
f"The function {fn} should have an empty 'List options' in its docstring as placeholder, current"
|
| 809 |
+
f" docstring is:\n{docstrings}"
|
| 810 |
+
)
|
| 811 |
+
fn.__doc__ = docstrings
|
| 812 |
+
return fn
|
| 813 |
+
|
| 814 |
+
return docstring_decorator
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
class AutoConfig:
|
| 818 |
+
r"""
|
| 819 |
+
This is a generic configuration class that will be instantiated as one of the configuration classes of the library
|
| 820 |
+
when created with the [`~AutoConfig.from_pretrained`] class method.
|
| 821 |
+
|
| 822 |
+
This class cannot be instantiated directly using `__init__()` (throws an error).
|
| 823 |
+
"""
|
| 824 |
+
|
| 825 |
+
def __init__(self):
|
| 826 |
+
raise EnvironmentError(
|
| 827 |
+
"AutoConfig is designed to be instantiated "
|
| 828 |
+
"using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method."
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
@classmethod
|
| 832 |
+
def for_model(cls, model_type: str, *args, **kwargs):
|
| 833 |
+
if model_type in CONFIG_MAPPING:
|
| 834 |
+
config_class = CONFIG_MAPPING[model_type]
|
| 835 |
+
return config_class(*args, **kwargs)
|
| 836 |
+
raise ValueError(
|
| 837 |
+
f"Unrecognized model identifier: {model_type}. Should contain one of {', '.join(CONFIG_MAPPING.keys())}"
|
| 838 |
+
)
|
| 839 |
+
|
| 840 |
+
@classmethod
|
| 841 |
+
@replace_list_option_in_docstrings()
|
| 842 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 843 |
+
r"""
|
| 844 |
+
Instantiate one of the configuration classes of the library from a pretrained model configuration.
|
| 845 |
+
|
| 846 |
+
The configuration class to instantiate is selected based on the `model_type` property of the config object that
|
| 847 |
+
is loaded, or when it's missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 848 |
+
|
| 849 |
+
List options
|
| 850 |
+
|
| 851 |
+
Args:
|
| 852 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 853 |
+
Can be either:
|
| 854 |
+
|
| 855 |
+
- A string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
| 856 |
+
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or
|
| 857 |
+
namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 858 |
+
- A path to a *directory* containing a configuration file saved using the
|
| 859 |
+
[`~PretrainedConfig.save_pretrained`] method, or the [`~PreTrainedModel.save_pretrained`] method,
|
| 860 |
+
e.g., `./my_model_directory/`.
|
| 861 |
+
- A path or url to a saved configuration JSON *file*, e.g.,
|
| 862 |
+
`./my_model_directory/configuration.json`.
|
| 863 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 864 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 865 |
+
standard cache should not be used.
|
| 866 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 867 |
+
Whether or not to force the (re-)download the model weights and configuration files and override the
|
| 868 |
+
cached versions if they exist.
|
| 869 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 870 |
+
Whether or not to delete incompletely received files. Will attempt to resume the download if such a
|
| 871 |
+
file exists.
|
| 872 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 873 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 874 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 875 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 876 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 877 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 878 |
+
identifier allowed by git.
|
| 879 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
| 880 |
+
If `False`, then this function returns just the final configuration object.
|
| 881 |
+
|
| 882 |
+
If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
|
| 883 |
+
dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
|
| 884 |
+
part of `kwargs` which has not been used to update `config` and is otherwise ignored.
|
| 885 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 886 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 887 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 888 |
+
execute code present on the Hub on your local machine.
|
| 889 |
+
kwargs(additional keyword arguments, *optional*):
|
| 890 |
+
The values in kwargs of any keys which are configuration attributes will be used to override the loaded
|
| 891 |
+
values. Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
|
| 892 |
+
by the `return_unused_kwargs` keyword parameter.
|
| 893 |
+
|
| 894 |
+
Examples:
|
| 895 |
+
|
| 896 |
+
```python
|
| 897 |
+
>>> from transformers import AutoConfig
|
| 898 |
+
|
| 899 |
+
>>> # Download configuration from huggingface.co and cache.
|
| 900 |
+
>>> config = AutoConfig.from_pretrained("bert-base-uncased")
|
| 901 |
+
|
| 902 |
+
>>> # Download configuration from huggingface.co (user-uploaded) and cache.
|
| 903 |
+
>>> config = AutoConfig.from_pretrained("dbmdz/bert-base-german-cased")
|
| 904 |
+
|
| 905 |
+
>>> # If configuration file is in a directory (e.g., was saved using *save_pretrained('./test/saved_model/')*).
|
| 906 |
+
>>> config = AutoConfig.from_pretrained("./test/bert_saved_model/")
|
| 907 |
+
|
| 908 |
+
>>> # Load a specific configuration file.
|
| 909 |
+
>>> config = AutoConfig.from_pretrained("./test/bert_saved_model/my_configuration.json")
|
| 910 |
+
|
| 911 |
+
>>> # Change some config attributes when loading a pretrained config.
|
| 912 |
+
>>> config = AutoConfig.from_pretrained("bert-base-uncased", output_attentions=True, foo=False)
|
| 913 |
+
>>> config.output_attentions
|
| 914 |
+
True
|
| 915 |
+
|
| 916 |
+
>>> config, unused_kwargs = AutoConfig.from_pretrained(
|
| 917 |
+
... "bert-base-uncased", output_attentions=True, foo=False, return_unused_kwargs=True
|
| 918 |
+
... )
|
| 919 |
+
>>> config.output_attentions
|
| 920 |
+
True
|
| 921 |
+
|
| 922 |
+
>>> unused_kwargs
|
| 923 |
+
{'foo': False}
|
| 924 |
+
```"""
|
| 925 |
+
kwargs["_from_auto"] = True
|
| 926 |
+
kwargs["name_or_path"] = pretrained_model_name_or_path
|
| 927 |
+
trust_remote_code = kwargs.pop("trust_remote_code", False)
|
| 928 |
+
config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 929 |
+
if "auto_map" in config_dict and "AutoConfig" in config_dict["auto_map"]:
|
| 930 |
+
if not trust_remote_code:
|
| 931 |
+
raise ValueError(
|
| 932 |
+
f"Loading {pretrained_model_name_or_path} requires you to execute the configuration file in that"
|
| 933 |
+
" repo on your local machine. Make sure you have read the code there to avoid malicious use, then"
|
| 934 |
+
" set the option `trust_remote_code=True` to remove this error."
|
| 935 |
+
)
|
| 936 |
+
class_ref = config_dict["auto_map"]["AutoConfig"]
|
| 937 |
+
config_class = get_class_from_dynamic_module(class_ref, pretrained_model_name_or_path, **kwargs)
|
| 938 |
+
return config_class.from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 939 |
+
elif "model_type" in config_dict:
|
| 940 |
+
config_class = CONFIG_MAPPING[config_dict["model_type"]]
|
| 941 |
+
return config_class.from_dict(config_dict, **unused_kwargs)
|
| 942 |
+
else:
|
| 943 |
+
# Fallback: use pattern matching on the string.
|
| 944 |
+
# We go from longer names to shorter names to catch roberta before bert (for instance)
|
| 945 |
+
for pattern in sorted(CONFIG_MAPPING.keys(), key=len, reverse=True):
|
| 946 |
+
if pattern in str(pretrained_model_name_or_path):
|
| 947 |
+
return CONFIG_MAPPING[pattern].from_dict(config_dict, **unused_kwargs)
|
| 948 |
+
|
| 949 |
+
raise ValueError(
|
| 950 |
+
f"Unrecognized model in {pretrained_model_name_or_path}. "
|
| 951 |
+
f"Should have a `model_type` key in its {CONFIG_NAME}, or contain one of the following strings "
|
| 952 |
+
f"in its name: {', '.join(CONFIG_MAPPING.keys())}"
|
| 953 |
+
)
|
| 954 |
+
|
| 955 |
+
@staticmethod
|
| 956 |
+
def register(model_type, config):
|
| 957 |
+
"""
|
| 958 |
+
Register a new configuration for this class.
|
| 959 |
+
|
| 960 |
+
Args:
|
| 961 |
+
model_type (`str`): The model type like "bert" or "gpt".
|
| 962 |
+
config ([`PretrainedConfig`]): The config to register.
|
| 963 |
+
"""
|
| 964 |
+
if issubclass(config, PretrainedConfig) and config.model_type != model_type:
|
| 965 |
+
raise ValueError(
|
| 966 |
+
"The config you are passing has a `model_type` attribute that is not consistent with the model type "
|
| 967 |
+
f"you passed (config has {config.model_type} and you passed {model_type}. Fix one of those so they "
|
| 968 |
+
"match!"
|
| 969 |
+
)
|
| 970 |
+
CONFIG_MAPPING.register(model_type, config)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/feature_extraction_auto.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" AutoFeatureExtractor class."""
|
| 16 |
+
import importlib
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
from collections import OrderedDict
|
| 20 |
+
from typing import Dict, Optional, Union
|
| 21 |
+
|
| 22 |
+
# Build the list of all feature extractors
|
| 23 |
+
from ...configuration_utils import PretrainedConfig
|
| 24 |
+
from ...dynamic_module_utils import get_class_from_dynamic_module
|
| 25 |
+
from ...feature_extraction_utils import FeatureExtractionMixin
|
| 26 |
+
from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
|
| 27 |
+
from .auto_factory import _LazyAutoMapping
|
| 28 |
+
from .configuration_auto import (
|
| 29 |
+
CONFIG_MAPPING_NAMES,
|
| 30 |
+
AutoConfig,
|
| 31 |
+
model_type_to_module_name,
|
| 32 |
+
replace_list_option_in_docstrings,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__)
|
| 37 |
+
|
| 38 |
+
FEATURE_EXTRACTOR_MAPPING_NAMES = OrderedDict(
|
| 39 |
+
[
|
| 40 |
+
("audio-spectrogram-transformer", "ASTFeatureExtractor"),
|
| 41 |
+
("beit", "BeitFeatureExtractor"),
|
| 42 |
+
("chinese_clip", "ChineseCLIPFeatureExtractor"),
|
| 43 |
+
("clap", "ClapFeatureExtractor"),
|
| 44 |
+
("clip", "CLIPFeatureExtractor"),
|
| 45 |
+
("clipseg", "ViTFeatureExtractor"),
|
| 46 |
+
("conditional_detr", "ConditionalDetrFeatureExtractor"),
|
| 47 |
+
("convnext", "ConvNextFeatureExtractor"),
|
| 48 |
+
("cvt", "ConvNextFeatureExtractor"),
|
| 49 |
+
("data2vec-audio", "Wav2Vec2FeatureExtractor"),
|
| 50 |
+
("data2vec-vision", "BeitFeatureExtractor"),
|
| 51 |
+
("deformable_detr", "DeformableDetrFeatureExtractor"),
|
| 52 |
+
("deit", "DeiTFeatureExtractor"),
|
| 53 |
+
("detr", "DetrFeatureExtractor"),
|
| 54 |
+
("dinat", "ViTFeatureExtractor"),
|
| 55 |
+
("donut-swin", "DonutFeatureExtractor"),
|
| 56 |
+
("dpt", "DPTFeatureExtractor"),
|
| 57 |
+
("flava", "FlavaFeatureExtractor"),
|
| 58 |
+
("glpn", "GLPNFeatureExtractor"),
|
| 59 |
+
("groupvit", "CLIPFeatureExtractor"),
|
| 60 |
+
("hubert", "Wav2Vec2FeatureExtractor"),
|
| 61 |
+
("imagegpt", "ImageGPTFeatureExtractor"),
|
| 62 |
+
("layoutlmv2", "LayoutLMv2FeatureExtractor"),
|
| 63 |
+
("layoutlmv3", "LayoutLMv3FeatureExtractor"),
|
| 64 |
+
("levit", "LevitFeatureExtractor"),
|
| 65 |
+
("maskformer", "MaskFormerFeatureExtractor"),
|
| 66 |
+
("mctct", "MCTCTFeatureExtractor"),
|
| 67 |
+
("mobilenet_v1", "MobileNetV1FeatureExtractor"),
|
| 68 |
+
("mobilenet_v2", "MobileNetV2FeatureExtractor"),
|
| 69 |
+
("mobilevit", "MobileViTFeatureExtractor"),
|
| 70 |
+
("nat", "ViTFeatureExtractor"),
|
| 71 |
+
("owlvit", "OwlViTFeatureExtractor"),
|
| 72 |
+
("perceiver", "PerceiverFeatureExtractor"),
|
| 73 |
+
("poolformer", "PoolFormerFeatureExtractor"),
|
| 74 |
+
("regnet", "ConvNextFeatureExtractor"),
|
| 75 |
+
("resnet", "ConvNextFeatureExtractor"),
|
| 76 |
+
("segformer", "SegformerFeatureExtractor"),
|
| 77 |
+
("sew", "Wav2Vec2FeatureExtractor"),
|
| 78 |
+
("sew-d", "Wav2Vec2FeatureExtractor"),
|
| 79 |
+
("speech_to_text", "Speech2TextFeatureExtractor"),
|
| 80 |
+
("speecht5", "SpeechT5FeatureExtractor"),
|
| 81 |
+
("swin", "ViTFeatureExtractor"),
|
| 82 |
+
("swinv2", "ViTFeatureExtractor"),
|
| 83 |
+
("table-transformer", "DetrFeatureExtractor"),
|
| 84 |
+
("timesformer", "VideoMAEFeatureExtractor"),
|
| 85 |
+
("tvlt", "TvltFeatureExtractor"),
|
| 86 |
+
("unispeech", "Wav2Vec2FeatureExtractor"),
|
| 87 |
+
("unispeech-sat", "Wav2Vec2FeatureExtractor"),
|
| 88 |
+
("van", "ConvNextFeatureExtractor"),
|
| 89 |
+
("videomae", "VideoMAEFeatureExtractor"),
|
| 90 |
+
("vilt", "ViltFeatureExtractor"),
|
| 91 |
+
("vit", "ViTFeatureExtractor"),
|
| 92 |
+
("vit_mae", "ViTFeatureExtractor"),
|
| 93 |
+
("vit_msn", "ViTFeatureExtractor"),
|
| 94 |
+
("wav2vec2", "Wav2Vec2FeatureExtractor"),
|
| 95 |
+
("wav2vec2-conformer", "Wav2Vec2FeatureExtractor"),
|
| 96 |
+
("wavlm", "Wav2Vec2FeatureExtractor"),
|
| 97 |
+
("whisper", "WhisperFeatureExtractor"),
|
| 98 |
+
("xclip", "CLIPFeatureExtractor"),
|
| 99 |
+
("yolos", "YolosFeatureExtractor"),
|
| 100 |
+
]
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
FEATURE_EXTRACTOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def feature_extractor_class_from_name(class_name: str):
|
| 107 |
+
for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
|
| 108 |
+
if class_name in extractors:
|
| 109 |
+
module_name = model_type_to_module_name(module_name)
|
| 110 |
+
|
| 111 |
+
module = importlib.import_module(f".{module_name}", "transformers.models")
|
| 112 |
+
try:
|
| 113 |
+
return getattr(module, class_name)
|
| 114 |
+
except AttributeError:
|
| 115 |
+
continue
|
| 116 |
+
|
| 117 |
+
for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
|
| 118 |
+
if getattr(extractor, "__name__", None) == class_name:
|
| 119 |
+
return extractor
|
| 120 |
+
|
| 121 |
+
# We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
|
| 122 |
+
# init and we return the proper dummy to get an appropriate error message.
|
| 123 |
+
main_module = importlib.import_module("transformers")
|
| 124 |
+
if hasattr(main_module, class_name):
|
| 125 |
+
return getattr(main_module, class_name)
|
| 126 |
+
|
| 127 |
+
return None
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def get_feature_extractor_config(
|
| 131 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
| 132 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
| 133 |
+
force_download: bool = False,
|
| 134 |
+
resume_download: bool = False,
|
| 135 |
+
proxies: Optional[Dict[str, str]] = None,
|
| 136 |
+
use_auth_token: Optional[Union[bool, str]] = None,
|
| 137 |
+
revision: Optional[str] = None,
|
| 138 |
+
local_files_only: bool = False,
|
| 139 |
+
**kwargs,
|
| 140 |
+
):
|
| 141 |
+
"""
|
| 142 |
+
Loads the tokenizer configuration from a pretrained model tokenizer configuration.
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 146 |
+
This can be either:
|
| 147 |
+
|
| 148 |
+
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
| 149 |
+
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced
|
| 150 |
+
under a user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 151 |
+
- a path to a *directory* containing a configuration file saved using the
|
| 152 |
+
[`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
|
| 153 |
+
|
| 154 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 155 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
|
| 156 |
+
cache should not be used.
|
| 157 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 158 |
+
Whether or not to force to (re-)download the configuration files and override the cached versions if they
|
| 159 |
+
exist.
|
| 160 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 161 |
+
Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists.
|
| 162 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 163 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 164 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 165 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 166 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
| 167 |
+
when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 168 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 169 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 170 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 171 |
+
identifier allowed by git.
|
| 172 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 173 |
+
If `True`, will only try to load the tokenizer configuration from local files.
|
| 174 |
+
|
| 175 |
+
<Tip>
|
| 176 |
+
|
| 177 |
+
Passing `use_auth_token=True` is required when you want to use a private model.
|
| 178 |
+
|
| 179 |
+
</Tip>
|
| 180 |
+
|
| 181 |
+
Returns:
|
| 182 |
+
`Dict`: The configuration of the tokenizer.
|
| 183 |
+
|
| 184 |
+
Examples:
|
| 185 |
+
|
| 186 |
+
```python
|
| 187 |
+
# Download configuration from huggingface.co and cache.
|
| 188 |
+
tokenizer_config = get_tokenizer_config("bert-base-uncased")
|
| 189 |
+
# This model does not have a tokenizer config so the result will be an empty dict.
|
| 190 |
+
tokenizer_config = get_tokenizer_config("xlm-roberta-base")
|
| 191 |
+
|
| 192 |
+
# Save a pretrained tokenizer locally and you can reload its config
|
| 193 |
+
from transformers import AutoTokenizer
|
| 194 |
+
|
| 195 |
+
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
|
| 196 |
+
tokenizer.save_pretrained("tokenizer-test")
|
| 197 |
+
tokenizer_config = get_tokenizer_config("tokenizer-test")
|
| 198 |
+
```"""
|
| 199 |
+
resolved_config_file = get_file_from_repo(
|
| 200 |
+
pretrained_model_name_or_path,
|
| 201 |
+
FEATURE_EXTRACTOR_NAME,
|
| 202 |
+
cache_dir=cache_dir,
|
| 203 |
+
force_download=force_download,
|
| 204 |
+
resume_download=resume_download,
|
| 205 |
+
proxies=proxies,
|
| 206 |
+
use_auth_token=use_auth_token,
|
| 207 |
+
revision=revision,
|
| 208 |
+
local_files_only=local_files_only,
|
| 209 |
+
)
|
| 210 |
+
if resolved_config_file is None:
|
| 211 |
+
logger.info(
|
| 212 |
+
"Could not locate the feature extractor configuration file, will try to use the model config instead."
|
| 213 |
+
)
|
| 214 |
+
return {}
|
| 215 |
+
|
| 216 |
+
with open(resolved_config_file, encoding="utf-8") as reader:
|
| 217 |
+
return json.load(reader)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class AutoFeatureExtractor:
|
| 221 |
+
r"""
|
| 222 |
+
This is a generic feature extractor class that will be instantiated as one of the feature extractor classes of the
|
| 223 |
+
library when created with the [`AutoFeatureExtractor.from_pretrained`] class method.
|
| 224 |
+
|
| 225 |
+
This class cannot be instantiated directly using `__init__()` (throws an error).
|
| 226 |
+
"""
|
| 227 |
+
|
| 228 |
+
def __init__(self):
|
| 229 |
+
raise EnvironmentError(
|
| 230 |
+
"AutoFeatureExtractor is designed to be instantiated "
|
| 231 |
+
"using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method."
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
@classmethod
|
| 235 |
+
@replace_list_option_in_docstrings(FEATURE_EXTRACTOR_MAPPING_NAMES)
|
| 236 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 237 |
+
r"""
|
| 238 |
+
Instantiate one of the feature extractor classes of the library from a pretrained model vocabulary.
|
| 239 |
+
|
| 240 |
+
The feature extractor class to instantiate is selected based on the `model_type` property of the config object
|
| 241 |
+
(either passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's
|
| 242 |
+
missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 243 |
+
|
| 244 |
+
List options
|
| 245 |
+
|
| 246 |
+
Params:
|
| 247 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 248 |
+
This can be either:
|
| 249 |
+
|
| 250 |
+
- a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
|
| 251 |
+
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or
|
| 252 |
+
namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 253 |
+
- a path to a *directory* containing a feature extractor file saved using the
|
| 254 |
+
[`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] method, e.g.,
|
| 255 |
+
`./my_model_directory/`.
|
| 256 |
+
- a path or url to a saved feature extractor JSON *file*, e.g.,
|
| 257 |
+
`./my_model_directory/preprocessor_config.json`.
|
| 258 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 259 |
+
Path to a directory in which a downloaded pretrained model feature extractor should be cached if the
|
| 260 |
+
standard cache should not be used.
|
| 261 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 262 |
+
Whether or not to force to (re-)download the feature extractor files and override the cached versions
|
| 263 |
+
if they exist.
|
| 264 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 265 |
+
Whether or not to delete incompletely received file. Attempts to resume the download if such a file
|
| 266 |
+
exists.
|
| 267 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 268 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 269 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 270 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 271 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
| 272 |
+
when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 273 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 274 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 275 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 276 |
+
identifier allowed by git.
|
| 277 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
| 278 |
+
If `False`, then this function returns just the final feature extractor object. If `True`, then this
|
| 279 |
+
functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
|
| 280 |
+
consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
|
| 281 |
+
`kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
|
| 282 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 283 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 284 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 285 |
+
execute code present on the Hub on your local machine.
|
| 286 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 287 |
+
The values in kwargs of any keys which are feature extractor attributes will be used to override the
|
| 288 |
+
loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
|
| 289 |
+
controlled by the `return_unused_kwargs` keyword parameter.
|
| 290 |
+
|
| 291 |
+
<Tip>
|
| 292 |
+
|
| 293 |
+
Passing `use_auth_token=True` is required when you want to use a private model.
|
| 294 |
+
|
| 295 |
+
</Tip>
|
| 296 |
+
|
| 297 |
+
Examples:
|
| 298 |
+
|
| 299 |
+
```python
|
| 300 |
+
>>> from transformers import AutoFeatureExtractor
|
| 301 |
+
|
| 302 |
+
>>> # Download feature extractor from huggingface.co and cache.
|
| 303 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h")
|
| 304 |
+
|
| 305 |
+
>>> # If feature extractor files are in a directory (e.g. feature extractor was saved using *save_pretrained('./test/saved_model/')*)
|
| 306 |
+
>>> # feature_extractor = AutoFeatureExtractor.from_pretrained("./test/saved_model/")
|
| 307 |
+
```"""
|
| 308 |
+
config = kwargs.pop("config", None)
|
| 309 |
+
trust_remote_code = kwargs.pop("trust_remote_code", False)
|
| 310 |
+
kwargs["_from_auto"] = True
|
| 311 |
+
|
| 312 |
+
config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs)
|
| 313 |
+
feature_extractor_class = config_dict.get("feature_extractor_type", None)
|
| 314 |
+
feature_extractor_auto_map = None
|
| 315 |
+
if "AutoFeatureExtractor" in config_dict.get("auto_map", {}):
|
| 316 |
+
feature_extractor_auto_map = config_dict["auto_map"]["AutoFeatureExtractor"]
|
| 317 |
+
|
| 318 |
+
# If we don't find the feature extractor class in the feature extractor config, let's try the model config.
|
| 319 |
+
if feature_extractor_class is None and feature_extractor_auto_map is None:
|
| 320 |
+
if not isinstance(config, PretrainedConfig):
|
| 321 |
+
config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 322 |
+
# It could be in `config.feature_extractor_type``
|
| 323 |
+
feature_extractor_class = getattr(config, "feature_extractor_type", None)
|
| 324 |
+
if hasattr(config, "auto_map") and "AutoFeatureExtractor" in config.auto_map:
|
| 325 |
+
feature_extractor_auto_map = config.auto_map["AutoFeatureExtractor"]
|
| 326 |
+
|
| 327 |
+
if feature_extractor_class is not None:
|
| 328 |
+
# If we have custom code for a feature extractor, we get the proper class.
|
| 329 |
+
if feature_extractor_auto_map is not None:
|
| 330 |
+
if not trust_remote_code:
|
| 331 |
+
raise ValueError(
|
| 332 |
+
f"Loading {pretrained_model_name_or_path} requires you to execute the feature extractor file "
|
| 333 |
+
"in that repo on your local machine. Make sure you have read the code there to avoid "
|
| 334 |
+
"malicious use, then set the option `trust_remote_code=True` to remove this error."
|
| 335 |
+
)
|
| 336 |
+
feature_extractor_class = get_class_from_dynamic_module(
|
| 337 |
+
feature_extractor_auto_map, pretrained_model_name_or_path, **kwargs
|
| 338 |
+
)
|
| 339 |
+
else:
|
| 340 |
+
feature_extractor_class = feature_extractor_class_from_name(feature_extractor_class)
|
| 341 |
+
|
| 342 |
+
return feature_extractor_class.from_dict(config_dict, **kwargs)
|
| 343 |
+
# Last try: we use the FEATURE_EXTRACTOR_MAPPING.
|
| 344 |
+
elif type(config) in FEATURE_EXTRACTOR_MAPPING:
|
| 345 |
+
feature_extractor_class = FEATURE_EXTRACTOR_MAPPING[type(config)]
|
| 346 |
+
return feature_extractor_class.from_dict(config_dict, **kwargs)
|
| 347 |
+
|
| 348 |
+
raise ValueError(
|
| 349 |
+
f"Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a "
|
| 350 |
+
f"`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following "
|
| 351 |
+
f"`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys())}"
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
@staticmethod
|
| 355 |
+
def register(config_class, feature_extractor_class):
|
| 356 |
+
"""
|
| 357 |
+
Register a new feature extractor for this class.
|
| 358 |
+
|
| 359 |
+
Args:
|
| 360 |
+
config_class ([`PretrainedConfig`]):
|
| 361 |
+
The configuration corresponding to the model to register.
|
| 362 |
+
feature_extractor_class ([`FeatureExtractorMixin`]): The feature extractor to register.
|
| 363 |
+
"""
|
| 364 |
+
FEATURE_EXTRACTOR_MAPPING.register(config_class, feature_extractor_class)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/image_processing_auto.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
""" AutoImageProcessor class."""
|
| 16 |
+
import importlib
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
from collections import OrderedDict
|
| 20 |
+
from typing import Dict, Optional, Union
|
| 21 |
+
|
| 22 |
+
# Build the list of all image processors
|
| 23 |
+
from ...configuration_utils import PretrainedConfig
|
| 24 |
+
from ...dynamic_module_utils import get_class_from_dynamic_module
|
| 25 |
+
from ...image_processing_utils import ImageProcessingMixin
|
| 26 |
+
from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging
|
| 27 |
+
from .auto_factory import _LazyAutoMapping
|
| 28 |
+
from .configuration_auto import (
|
| 29 |
+
CONFIG_MAPPING_NAMES,
|
| 30 |
+
AutoConfig,
|
| 31 |
+
model_type_to_module_name,
|
| 32 |
+
replace_list_option_in_docstrings,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__)
|
| 37 |
+
|
| 38 |
+
IMAGE_PROCESSOR_MAPPING_NAMES = OrderedDict(
|
| 39 |
+
[
|
| 40 |
+
("align", "EfficientNetImageProcessor"),
|
| 41 |
+
("beit", "BeitImageProcessor"),
|
| 42 |
+
("bit", "BitImageProcessor"),
|
| 43 |
+
("blip", "BlipImageProcessor"),
|
| 44 |
+
("blip-2", "BlipImageProcessor"),
|
| 45 |
+
("bridgetower", "BridgeTowerImageProcessor"),
|
| 46 |
+
("chinese_clip", "ChineseCLIPImageProcessor"),
|
| 47 |
+
("clip", "CLIPImageProcessor"),
|
| 48 |
+
("clipseg", "ViTImageProcessor"),
|
| 49 |
+
("conditional_detr", "ConditionalDetrImageProcessor"),
|
| 50 |
+
("convnext", "ConvNextImageProcessor"),
|
| 51 |
+
("convnextv2", "ConvNextImageProcessor"),
|
| 52 |
+
("cvt", "ConvNextImageProcessor"),
|
| 53 |
+
("data2vec-vision", "BeitImageProcessor"),
|
| 54 |
+
("deformable_detr", "DeformableDetrImageProcessor"),
|
| 55 |
+
("deit", "DeiTImageProcessor"),
|
| 56 |
+
("deta", "DetaImageProcessor"),
|
| 57 |
+
("detr", "DetrImageProcessor"),
|
| 58 |
+
("dinat", "ViTImageProcessor"),
|
| 59 |
+
("donut-swin", "DonutImageProcessor"),
|
| 60 |
+
("dpt", "DPTImageProcessor"),
|
| 61 |
+
("efficientformer", "EfficientFormerImageProcessor"),
|
| 62 |
+
("efficientnet", "EfficientNetImageProcessor"),
|
| 63 |
+
("flava", "FlavaImageProcessor"),
|
| 64 |
+
("focalnet", "BitImageProcessor"),
|
| 65 |
+
("git", "CLIPImageProcessor"),
|
| 66 |
+
("glpn", "GLPNImageProcessor"),
|
| 67 |
+
("groupvit", "CLIPImageProcessor"),
|
| 68 |
+
("imagegpt", "ImageGPTImageProcessor"),
|
| 69 |
+
("layoutlmv2", "LayoutLMv2ImageProcessor"),
|
| 70 |
+
("layoutlmv3", "LayoutLMv3ImageProcessor"),
|
| 71 |
+
("levit", "LevitImageProcessor"),
|
| 72 |
+
("mask2former", "Mask2FormerImageProcessor"),
|
| 73 |
+
("maskformer", "MaskFormerImageProcessor"),
|
| 74 |
+
("mgp-str", "ViTImageProcessor"),
|
| 75 |
+
("mobilenet_v1", "MobileNetV1ImageProcessor"),
|
| 76 |
+
("mobilenet_v2", "MobileNetV2ImageProcessor"),
|
| 77 |
+
("mobilenet_v2", "MobileNetV2ImageProcessor"),
|
| 78 |
+
("mobilevit", "MobileViTImageProcessor"),
|
| 79 |
+
("mobilevit", "MobileViTImageProcessor"),
|
| 80 |
+
("nat", "ViTImageProcessor"),
|
| 81 |
+
("oneformer", "OneFormerImageProcessor"),
|
| 82 |
+
("owlvit", "OwlViTImageProcessor"),
|
| 83 |
+
("perceiver", "PerceiverImageProcessor"),
|
| 84 |
+
("pix2struct", "Pix2StructImageProcessor"),
|
| 85 |
+
("poolformer", "PoolFormerImageProcessor"),
|
| 86 |
+
("regnet", "ConvNextImageProcessor"),
|
| 87 |
+
("resnet", "ConvNextImageProcessor"),
|
| 88 |
+
("sam", "SamImageProcessor"),
|
| 89 |
+
("segformer", "SegformerImageProcessor"),
|
| 90 |
+
("swin", "ViTImageProcessor"),
|
| 91 |
+
("swin2sr", "Swin2SRImageProcessor"),
|
| 92 |
+
("swinv2", "ViTImageProcessor"),
|
| 93 |
+
("table-transformer", "DetrImageProcessor"),
|
| 94 |
+
("timesformer", "VideoMAEImageProcessor"),
|
| 95 |
+
("tvlt", "TvltImageProcessor"),
|
| 96 |
+
("upernet", "SegformerImageProcessor"),
|
| 97 |
+
("van", "ConvNextImageProcessor"),
|
| 98 |
+
("videomae", "VideoMAEImageProcessor"),
|
| 99 |
+
("vilt", "ViltImageProcessor"),
|
| 100 |
+
("vit", "ViTImageProcessor"),
|
| 101 |
+
("vit_hybrid", "ViTHybridImageProcessor"),
|
| 102 |
+
("vit_mae", "ViTImageProcessor"),
|
| 103 |
+
("vit_msn", "ViTImageProcessor"),
|
| 104 |
+
("xclip", "CLIPImageProcessor"),
|
| 105 |
+
("yolos", "YolosImageProcessor"),
|
| 106 |
+
]
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
IMAGE_PROCESSOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def image_processor_class_from_name(class_name: str):
|
| 113 |
+
for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
|
| 114 |
+
if class_name in extractors:
|
| 115 |
+
module_name = model_type_to_module_name(module_name)
|
| 116 |
+
|
| 117 |
+
module = importlib.import_module(f".{module_name}", "transformers.models")
|
| 118 |
+
try:
|
| 119 |
+
return getattr(module, class_name)
|
| 120 |
+
except AttributeError:
|
| 121 |
+
continue
|
| 122 |
+
|
| 123 |
+
for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items():
|
| 124 |
+
if getattr(extractor, "__name__", None) == class_name:
|
| 125 |
+
return extractor
|
| 126 |
+
|
| 127 |
+
# We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
|
| 128 |
+
# init and we return the proper dummy to get an appropriate error message.
|
| 129 |
+
main_module = importlib.import_module("transformers")
|
| 130 |
+
if hasattr(main_module, class_name):
|
| 131 |
+
return getattr(main_module, class_name)
|
| 132 |
+
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def get_image_processor_config(
|
| 137 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
| 138 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
| 139 |
+
force_download: bool = False,
|
| 140 |
+
resume_download: bool = False,
|
| 141 |
+
proxies: Optional[Dict[str, str]] = None,
|
| 142 |
+
use_auth_token: Optional[Union[bool, str]] = None,
|
| 143 |
+
revision: Optional[str] = None,
|
| 144 |
+
local_files_only: bool = False,
|
| 145 |
+
**kwargs,
|
| 146 |
+
):
|
| 147 |
+
"""
|
| 148 |
+
Loads the image processor configuration from a pretrained model image processor configuration.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 152 |
+
This can be either:
|
| 153 |
+
|
| 154 |
+
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
| 155 |
+
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced
|
| 156 |
+
under a user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 157 |
+
- a path to a *directory* containing a configuration file saved using the
|
| 158 |
+
[`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
|
| 159 |
+
|
| 160 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 161 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
|
| 162 |
+
cache should not be used.
|
| 163 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 164 |
+
Whether or not to force to (re-)download the configuration files and override the cached versions if they
|
| 165 |
+
exist.
|
| 166 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 167 |
+
Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists.
|
| 168 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 169 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 170 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 171 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 172 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
| 173 |
+
when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 174 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 175 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 176 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 177 |
+
identifier allowed by git.
|
| 178 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 179 |
+
If `True`, will only try to load the image processor configuration from local files.
|
| 180 |
+
|
| 181 |
+
<Tip>
|
| 182 |
+
|
| 183 |
+
Passing `use_auth_token=True` is required when you want to use a private model.
|
| 184 |
+
|
| 185 |
+
</Tip>
|
| 186 |
+
|
| 187 |
+
Returns:
|
| 188 |
+
`Dict`: The configuration of the image processor.
|
| 189 |
+
|
| 190 |
+
Examples:
|
| 191 |
+
|
| 192 |
+
```python
|
| 193 |
+
# Download configuration from huggingface.co and cache.
|
| 194 |
+
image_processor_config = get_image_processor_config("bert-base-uncased")
|
| 195 |
+
# This model does not have a image processor config so the result will be an empty dict.
|
| 196 |
+
image_processor_config = get_image_processor_config("xlm-roberta-base")
|
| 197 |
+
|
| 198 |
+
# Save a pretrained image processor locally and you can reload its config
|
| 199 |
+
from transformers import AutoTokenizer
|
| 200 |
+
|
| 201 |
+
image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
|
| 202 |
+
image_processor.save_pretrained("image-processor-test")
|
| 203 |
+
image_processor_config = get_image_processor_config("image-processor-test")
|
| 204 |
+
```"""
|
| 205 |
+
resolved_config_file = get_file_from_repo(
|
| 206 |
+
pretrained_model_name_or_path,
|
| 207 |
+
IMAGE_PROCESSOR_NAME,
|
| 208 |
+
cache_dir=cache_dir,
|
| 209 |
+
force_download=force_download,
|
| 210 |
+
resume_download=resume_download,
|
| 211 |
+
proxies=proxies,
|
| 212 |
+
use_auth_token=use_auth_token,
|
| 213 |
+
revision=revision,
|
| 214 |
+
local_files_only=local_files_only,
|
| 215 |
+
)
|
| 216 |
+
if resolved_config_file is None:
|
| 217 |
+
logger.info(
|
| 218 |
+
"Could not locate the image processor configuration file, will try to use the model config instead."
|
| 219 |
+
)
|
| 220 |
+
return {}
|
| 221 |
+
|
| 222 |
+
with open(resolved_config_file, encoding="utf-8") as reader:
|
| 223 |
+
return json.load(reader)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
class AutoImageProcessor:
|
| 227 |
+
r"""
|
| 228 |
+
This is a generic image processor class that will be instantiated as one of the image processor classes of the
|
| 229 |
+
library when created with the [`AutoImageProcessor.from_pretrained`] class method.
|
| 230 |
+
|
| 231 |
+
This class cannot be instantiated directly using `__init__()` (throws an error).
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
def __init__(self):
|
| 235 |
+
raise EnvironmentError(
|
| 236 |
+
"AutoImageProcessor is designed to be instantiated "
|
| 237 |
+
"using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method."
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
@classmethod
|
| 241 |
+
@replace_list_option_in_docstrings(IMAGE_PROCESSOR_MAPPING_NAMES)
|
| 242 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 243 |
+
r"""
|
| 244 |
+
Instantiate one of the image processor classes of the library from a pretrained model vocabulary.
|
| 245 |
+
|
| 246 |
+
The image processor class to instantiate is selected based on the `model_type` property of the config object
|
| 247 |
+
(either passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's
|
| 248 |
+
missing, by falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 249 |
+
|
| 250 |
+
List options
|
| 251 |
+
|
| 252 |
+
Params:
|
| 253 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 254 |
+
This can be either:
|
| 255 |
+
|
| 256 |
+
- a string, the *model id* of a pretrained image_processor hosted inside a model repo on
|
| 257 |
+
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or
|
| 258 |
+
namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 259 |
+
- a path to a *directory* containing a image processor file saved using the
|
| 260 |
+
[`~image_processing_utils.ImageProcessingMixin.save_pretrained`] method, e.g.,
|
| 261 |
+
`./my_model_directory/`.
|
| 262 |
+
- a path or url to a saved image processor JSON *file*, e.g.,
|
| 263 |
+
`./my_model_directory/preprocessor_config.json`.
|
| 264 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 265 |
+
Path to a directory in which a downloaded pretrained model image processor should be cached if the
|
| 266 |
+
standard cache should not be used.
|
| 267 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 268 |
+
Whether or not to force to (re-)download the image processor files and override the cached versions if
|
| 269 |
+
they exist.
|
| 270 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 271 |
+
Whether or not to delete incompletely received file. Attempts to resume the download if such a file
|
| 272 |
+
exists.
|
| 273 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 274 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 275 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 276 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 277 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
| 278 |
+
when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 279 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 280 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 281 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 282 |
+
identifier allowed by git.
|
| 283 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
| 284 |
+
If `False`, then this function returns just the final image processor object. If `True`, then this
|
| 285 |
+
functions returns a `Tuple(image_processor, unused_kwargs)` where *unused_kwargs* is a dictionary
|
| 286 |
+
consisting of the key/value pairs whose keys are not image processor attributes: i.e., the part of
|
| 287 |
+
`kwargs` which has not been used to update `image_processor` and is otherwise ignored.
|
| 288 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 289 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 290 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 291 |
+
execute code present on the Hub on your local machine.
|
| 292 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 293 |
+
The values in kwargs of any keys which are image processor attributes will be used to override the
|
| 294 |
+
loaded values. Behavior concerning key/value pairs whose keys are *not* image processor attributes is
|
| 295 |
+
controlled by the `return_unused_kwargs` keyword parameter.
|
| 296 |
+
|
| 297 |
+
<Tip>
|
| 298 |
+
|
| 299 |
+
Passing `use_auth_token=True` is required when you want to use a private model.
|
| 300 |
+
|
| 301 |
+
</Tip>
|
| 302 |
+
|
| 303 |
+
Examples:
|
| 304 |
+
|
| 305 |
+
```python
|
| 306 |
+
>>> from transformers import AutoImageProcessor
|
| 307 |
+
|
| 308 |
+
>>> # Download image processor from huggingface.co and cache.
|
| 309 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
|
| 310 |
+
|
| 311 |
+
>>> # If image processor files are in a directory (e.g. image processor was saved using *save_pretrained('./test/saved_model/')*)
|
| 312 |
+
>>> # image_processor = AutoImageProcessor.from_pretrained("./test/saved_model/")
|
| 313 |
+
```"""
|
| 314 |
+
config = kwargs.pop("config", None)
|
| 315 |
+
trust_remote_code = kwargs.pop("trust_remote_code", False)
|
| 316 |
+
kwargs["_from_auto"] = True
|
| 317 |
+
|
| 318 |
+
config_dict, _ = ImageProcessingMixin.get_image_processor_dict(pretrained_model_name_or_path, **kwargs)
|
| 319 |
+
image_processor_class = config_dict.get("image_processor_type", None)
|
| 320 |
+
image_processor_auto_map = None
|
| 321 |
+
if "AutoImageProcessor" in config_dict.get("auto_map", {}):
|
| 322 |
+
image_processor_auto_map = config_dict["auto_map"]["AutoImageProcessor"]
|
| 323 |
+
|
| 324 |
+
# If we still don't have the image processor class, check if we're loading from a previous feature extractor config
|
| 325 |
+
# and if so, infer the image processor class from there.
|
| 326 |
+
if image_processor_class is None and image_processor_auto_map is None:
|
| 327 |
+
feature_extractor_class = config_dict.pop("feature_extractor_type", None)
|
| 328 |
+
if feature_extractor_class is not None:
|
| 329 |
+
logger.warning(
|
| 330 |
+
"Could not find image processor class in the image processor config or the model config. Loading"
|
| 331 |
+
" based on pattern matching with the model's feature extractor configuration."
|
| 332 |
+
)
|
| 333 |
+
image_processor_class = feature_extractor_class.replace("FeatureExtractor", "ImageProcessor")
|
| 334 |
+
if "AutoFeatureExtractor" in config_dict.get("auto_map", {}):
|
| 335 |
+
feature_extractor_auto_map = config_dict["auto_map"]["AutoFeatureExtractor"]
|
| 336 |
+
image_processor_auto_map = feature_extractor_auto_map.replace("FeatureExtractor", "ImageProcessor")
|
| 337 |
+
logger.warning(
|
| 338 |
+
"Could not find image processor auto map in the image processor config or the model config."
|
| 339 |
+
" Loading based on pattern matching with the model's feature extractor configuration."
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
# If we don't find the image processor class in the image processor config, let's try the model config.
|
| 343 |
+
if image_processor_class is None and image_processor_auto_map is None:
|
| 344 |
+
if not isinstance(config, PretrainedConfig):
|
| 345 |
+
config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 346 |
+
# It could be in `config.image_processor_type``
|
| 347 |
+
image_processor_class = getattr(config, "image_processor_type", None)
|
| 348 |
+
if hasattr(config, "auto_map") and "AutoImageProcessor" in config.auto_map:
|
| 349 |
+
image_processor_auto_map = config.auto_map["AutoImageProcessor"]
|
| 350 |
+
|
| 351 |
+
if image_processor_class is not None:
|
| 352 |
+
# If we have custom code for a image processor, we get the proper class.
|
| 353 |
+
if image_processor_auto_map is not None:
|
| 354 |
+
if not trust_remote_code:
|
| 355 |
+
raise ValueError(
|
| 356 |
+
f"Loading {pretrained_model_name_or_path} requires you to execute the image processor file "
|
| 357 |
+
"in that repo on your local machine. Make sure you have read the code there to avoid "
|
| 358 |
+
"malicious use, then set the option `trust_remote_code=True` to remove this error."
|
| 359 |
+
)
|
| 360 |
+
image_processor_class = get_class_from_dynamic_module(
|
| 361 |
+
image_processor_auto_map, pretrained_model_name_or_path, **kwargs
|
| 362 |
+
)
|
| 363 |
+
else:
|
| 364 |
+
image_processor_class = image_processor_class_from_name(image_processor_class)
|
| 365 |
+
|
| 366 |
+
return image_processor_class.from_dict(config_dict, **kwargs)
|
| 367 |
+
# Last try: we use the IMAGE_PROCESSOR_MAPPING.
|
| 368 |
+
elif type(config) in IMAGE_PROCESSOR_MAPPING:
|
| 369 |
+
image_processor_class = IMAGE_PROCESSOR_MAPPING[type(config)]
|
| 370 |
+
return image_processor_class.from_dict(config_dict, **kwargs)
|
| 371 |
+
|
| 372 |
+
raise ValueError(
|
| 373 |
+
f"Unrecognized image processor in {pretrained_model_name_or_path}. Should have a "
|
| 374 |
+
f"`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following "
|
| 375 |
+
f"`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys())}"
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
@staticmethod
|
| 379 |
+
def register(config_class, image_processor_class):
|
| 380 |
+
"""
|
| 381 |
+
Register a new image processor for this class.
|
| 382 |
+
|
| 383 |
+
Args:
|
| 384 |
+
config_class ([`PretrainedConfig`]):
|
| 385 |
+
The configuration corresponding to the model to register.
|
| 386 |
+
image_processor_class ([`ImageProcessingMixin`]): The image processor to register.
|
| 387 |
+
"""
|
| 388 |
+
IMAGE_PROCESSOR_MAPPING.register(config_class, image_processor_class)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/modeling_auto.py
ADDED
|
@@ -0,0 +1,1358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Auto Model class."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
|
| 22 |
+
from .configuration_auto import CONFIG_MAPPING_NAMES
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
MODEL_MAPPING_NAMES = OrderedDict(
|
| 29 |
+
[
|
| 30 |
+
# Base model mapping
|
| 31 |
+
("albert", "AlbertModel"),
|
| 32 |
+
("align", "AlignModel"),
|
| 33 |
+
("altclip", "AltCLIPModel"),
|
| 34 |
+
("audio-spectrogram-transformer", "ASTModel"),
|
| 35 |
+
("bart", "BartModel"),
|
| 36 |
+
("beit", "BeitModel"),
|
| 37 |
+
("bert", "BertModel"),
|
| 38 |
+
("bert-generation", "BertGenerationEncoder"),
|
| 39 |
+
("big_bird", "BigBirdModel"),
|
| 40 |
+
("bigbird_pegasus", "BigBirdPegasusModel"),
|
| 41 |
+
("biogpt", "BioGptModel"),
|
| 42 |
+
("bit", "BitModel"),
|
| 43 |
+
("blenderbot", "BlenderbotModel"),
|
| 44 |
+
("blenderbot-small", "BlenderbotSmallModel"),
|
| 45 |
+
("blip", "BlipModel"),
|
| 46 |
+
("blip-2", "Blip2Model"),
|
| 47 |
+
("bloom", "BloomModel"),
|
| 48 |
+
("bridgetower", "BridgeTowerModel"),
|
| 49 |
+
("camembert", "CamembertModel"),
|
| 50 |
+
("canine", "CanineModel"),
|
| 51 |
+
("chinese_clip", "ChineseCLIPModel"),
|
| 52 |
+
("clap", "ClapModel"),
|
| 53 |
+
("clip", "CLIPModel"),
|
| 54 |
+
("clipseg", "CLIPSegModel"),
|
| 55 |
+
("codegen", "CodeGenModel"),
|
| 56 |
+
("conditional_detr", "ConditionalDetrModel"),
|
| 57 |
+
("convbert", "ConvBertModel"),
|
| 58 |
+
("convnext", "ConvNextModel"),
|
| 59 |
+
("convnextv2", "ConvNextV2Model"),
|
| 60 |
+
("cpmant", "CpmAntModel"),
|
| 61 |
+
("ctrl", "CTRLModel"),
|
| 62 |
+
("cvt", "CvtModel"),
|
| 63 |
+
("data2vec-audio", "Data2VecAudioModel"),
|
| 64 |
+
("data2vec-text", "Data2VecTextModel"),
|
| 65 |
+
("data2vec-vision", "Data2VecVisionModel"),
|
| 66 |
+
("deberta", "DebertaModel"),
|
| 67 |
+
("deberta-v2", "DebertaV2Model"),
|
| 68 |
+
("decision_transformer", "DecisionTransformerModel"),
|
| 69 |
+
("deformable_detr", "DeformableDetrModel"),
|
| 70 |
+
("deit", "DeiTModel"),
|
| 71 |
+
("deta", "DetaModel"),
|
| 72 |
+
("detr", "DetrModel"),
|
| 73 |
+
("dinat", "DinatModel"),
|
| 74 |
+
("distilbert", "DistilBertModel"),
|
| 75 |
+
("donut-swin", "DonutSwinModel"),
|
| 76 |
+
("dpr", "DPRQuestionEncoder"),
|
| 77 |
+
("dpt", "DPTModel"),
|
| 78 |
+
("efficientformer", "EfficientFormerModel"),
|
| 79 |
+
("efficientnet", "EfficientNetModel"),
|
| 80 |
+
("electra", "ElectraModel"),
|
| 81 |
+
("ernie", "ErnieModel"),
|
| 82 |
+
("ernie_m", "ErnieMModel"),
|
| 83 |
+
("esm", "EsmModel"),
|
| 84 |
+
("flaubert", "FlaubertModel"),
|
| 85 |
+
("flava", "FlavaModel"),
|
| 86 |
+
("fnet", "FNetModel"),
|
| 87 |
+
("focalnet", "FocalNetModel"),
|
| 88 |
+
("fsmt", "FSMTModel"),
|
| 89 |
+
("funnel", ("FunnelModel", "FunnelBaseModel")),
|
| 90 |
+
("git", "GitModel"),
|
| 91 |
+
("glpn", "GLPNModel"),
|
| 92 |
+
("gpt-sw3", "GPT2Model"),
|
| 93 |
+
("gpt2", "GPT2Model"),
|
| 94 |
+
("gpt_bigcode", "GPTBigCodeModel"),
|
| 95 |
+
("gpt_neo", "GPTNeoModel"),
|
| 96 |
+
("gpt_neox", "GPTNeoXModel"),
|
| 97 |
+
("gpt_neox_japanese", "GPTNeoXJapaneseModel"),
|
| 98 |
+
("gptj", "GPTJModel"),
|
| 99 |
+
("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"),
|
| 100 |
+
("graphormer", "GraphormerModel"),
|
| 101 |
+
("groupvit", "GroupViTModel"),
|
| 102 |
+
("hubert", "HubertModel"),
|
| 103 |
+
("ibert", "IBertModel"),
|
| 104 |
+
("imagegpt", "ImageGPTModel"),
|
| 105 |
+
("informer", "InformerModel"),
|
| 106 |
+
("jukebox", "JukeboxModel"),
|
| 107 |
+
("layoutlm", "LayoutLMModel"),
|
| 108 |
+
("layoutlmv2", "LayoutLMv2Model"),
|
| 109 |
+
("layoutlmv3", "LayoutLMv3Model"),
|
| 110 |
+
("led", "LEDModel"),
|
| 111 |
+
("levit", "LevitModel"),
|
| 112 |
+
("lilt", "LiltModel"),
|
| 113 |
+
("llama", "LlamaModel"),
|
| 114 |
+
("longformer", "LongformerModel"),
|
| 115 |
+
("longt5", "LongT5Model"),
|
| 116 |
+
("luke", "LukeModel"),
|
| 117 |
+
("lxmert", "LxmertModel"),
|
| 118 |
+
("m2m_100", "M2M100Model"),
|
| 119 |
+
("marian", "MarianModel"),
|
| 120 |
+
("markuplm", "MarkupLMModel"),
|
| 121 |
+
("mask2former", "Mask2FormerModel"),
|
| 122 |
+
("maskformer", "MaskFormerModel"),
|
| 123 |
+
("maskformer-swin", "MaskFormerSwinModel"),
|
| 124 |
+
("mbart", "MBartModel"),
|
| 125 |
+
("mctct", "MCTCTModel"),
|
| 126 |
+
("mega", "MegaModel"),
|
| 127 |
+
("megatron-bert", "MegatronBertModel"),
|
| 128 |
+
("mgp-str", "MgpstrForSceneTextRecognition"),
|
| 129 |
+
("mobilebert", "MobileBertModel"),
|
| 130 |
+
("mobilenet_v1", "MobileNetV1Model"),
|
| 131 |
+
("mobilenet_v2", "MobileNetV2Model"),
|
| 132 |
+
("mobilevit", "MobileViTModel"),
|
| 133 |
+
("mpnet", "MPNetModel"),
|
| 134 |
+
("mt5", "MT5Model"),
|
| 135 |
+
("mvp", "MvpModel"),
|
| 136 |
+
("nat", "NatModel"),
|
| 137 |
+
("nezha", "NezhaModel"),
|
| 138 |
+
("nllb-moe", "NllbMoeModel"),
|
| 139 |
+
("nystromformer", "NystromformerModel"),
|
| 140 |
+
("oneformer", "OneFormerModel"),
|
| 141 |
+
("open-llama", "OpenLlamaModel"),
|
| 142 |
+
("openai-gpt", "OpenAIGPTModel"),
|
| 143 |
+
("opt", "OPTModel"),
|
| 144 |
+
("owlvit", "OwlViTModel"),
|
| 145 |
+
("pegasus", "PegasusModel"),
|
| 146 |
+
("pegasus_x", "PegasusXModel"),
|
| 147 |
+
("perceiver", "PerceiverModel"),
|
| 148 |
+
("plbart", "PLBartModel"),
|
| 149 |
+
("poolformer", "PoolFormerModel"),
|
| 150 |
+
("prophetnet", "ProphetNetModel"),
|
| 151 |
+
("qdqbert", "QDQBertModel"),
|
| 152 |
+
("reformer", "ReformerModel"),
|
| 153 |
+
("regnet", "RegNetModel"),
|
| 154 |
+
("rembert", "RemBertModel"),
|
| 155 |
+
("resnet", "ResNetModel"),
|
| 156 |
+
("retribert", "RetriBertModel"),
|
| 157 |
+
("roberta", "RobertaModel"),
|
| 158 |
+
("roberta-prelayernorm", "RobertaPreLayerNormModel"),
|
| 159 |
+
("roc_bert", "RoCBertModel"),
|
| 160 |
+
("roformer", "RoFormerModel"),
|
| 161 |
+
("rwkv", "RwkvModel"),
|
| 162 |
+
("sam", "SamModel"),
|
| 163 |
+
("segformer", "SegformerModel"),
|
| 164 |
+
("sew", "SEWModel"),
|
| 165 |
+
("sew-d", "SEWDModel"),
|
| 166 |
+
("speech_to_text", "Speech2TextModel"),
|
| 167 |
+
("speecht5", "SpeechT5Model"),
|
| 168 |
+
("splinter", "SplinterModel"),
|
| 169 |
+
("squeezebert", "SqueezeBertModel"),
|
| 170 |
+
("swin", "SwinModel"),
|
| 171 |
+
("swin2sr", "Swin2SRModel"),
|
| 172 |
+
("swinv2", "Swinv2Model"),
|
| 173 |
+
("switch_transformers", "SwitchTransformersModel"),
|
| 174 |
+
("t5", "T5Model"),
|
| 175 |
+
("table-transformer", "TableTransformerModel"),
|
| 176 |
+
("tapas", "TapasModel"),
|
| 177 |
+
("time_series_transformer", "TimeSeriesTransformerModel"),
|
| 178 |
+
("timesformer", "TimesformerModel"),
|
| 179 |
+
("trajectory_transformer", "TrajectoryTransformerModel"),
|
| 180 |
+
("transfo-xl", "TransfoXLModel"),
|
| 181 |
+
("tvlt", "TvltModel"),
|
| 182 |
+
("unispeech", "UniSpeechModel"),
|
| 183 |
+
("unispeech-sat", "UniSpeechSatModel"),
|
| 184 |
+
("van", "VanModel"),
|
| 185 |
+
("videomae", "VideoMAEModel"),
|
| 186 |
+
("vilt", "ViltModel"),
|
| 187 |
+
("vision-text-dual-encoder", "VisionTextDualEncoderModel"),
|
| 188 |
+
("visual_bert", "VisualBertModel"),
|
| 189 |
+
("vit", "ViTModel"),
|
| 190 |
+
("vit_hybrid", "ViTHybridModel"),
|
| 191 |
+
("vit_mae", "ViTMAEModel"),
|
| 192 |
+
("vit_msn", "ViTMSNModel"),
|
| 193 |
+
("wav2vec2", "Wav2Vec2Model"),
|
| 194 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerModel"),
|
| 195 |
+
("wavlm", "WavLMModel"),
|
| 196 |
+
("whisper", "WhisperModel"),
|
| 197 |
+
("xclip", "XCLIPModel"),
|
| 198 |
+
("xglm", "XGLMModel"),
|
| 199 |
+
("xlm", "XLMModel"),
|
| 200 |
+
("xlm-prophetnet", "XLMProphetNetModel"),
|
| 201 |
+
("xlm-roberta", "XLMRobertaModel"),
|
| 202 |
+
("xlm-roberta-xl", "XLMRobertaXLModel"),
|
| 203 |
+
("xlnet", "XLNetModel"),
|
| 204 |
+
("xmod", "XmodModel"),
|
| 205 |
+
("yolos", "YolosModel"),
|
| 206 |
+
("yoso", "YosoModel"),
|
| 207 |
+
]
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
MODEL_FOR_PRETRAINING_MAPPING_NAMES = OrderedDict(
|
| 211 |
+
[
|
| 212 |
+
# Model for pre-training mapping
|
| 213 |
+
("albert", "AlbertForPreTraining"),
|
| 214 |
+
("bart", "BartForConditionalGeneration"),
|
| 215 |
+
("bert", "BertForPreTraining"),
|
| 216 |
+
("big_bird", "BigBirdForPreTraining"),
|
| 217 |
+
("bloom", "BloomForCausalLM"),
|
| 218 |
+
("camembert", "CamembertForMaskedLM"),
|
| 219 |
+
("ctrl", "CTRLLMHeadModel"),
|
| 220 |
+
("data2vec-text", "Data2VecTextForMaskedLM"),
|
| 221 |
+
("deberta", "DebertaForMaskedLM"),
|
| 222 |
+
("deberta-v2", "DebertaV2ForMaskedLM"),
|
| 223 |
+
("distilbert", "DistilBertForMaskedLM"),
|
| 224 |
+
("electra", "ElectraForPreTraining"),
|
| 225 |
+
("ernie", "ErnieForPreTraining"),
|
| 226 |
+
("flaubert", "FlaubertWithLMHeadModel"),
|
| 227 |
+
("flava", "FlavaForPreTraining"),
|
| 228 |
+
("fnet", "FNetForPreTraining"),
|
| 229 |
+
("fsmt", "FSMTForConditionalGeneration"),
|
| 230 |
+
("funnel", "FunnelForPreTraining"),
|
| 231 |
+
("gpt-sw3", "GPT2LMHeadModel"),
|
| 232 |
+
("gpt2", "GPT2LMHeadModel"),
|
| 233 |
+
("gpt_bigcode", "GPTBigCodeForCausalLM"),
|
| 234 |
+
("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"),
|
| 235 |
+
("ibert", "IBertForMaskedLM"),
|
| 236 |
+
("layoutlm", "LayoutLMForMaskedLM"),
|
| 237 |
+
("longformer", "LongformerForMaskedLM"),
|
| 238 |
+
("luke", "LukeForMaskedLM"),
|
| 239 |
+
("lxmert", "LxmertForPreTraining"),
|
| 240 |
+
("mega", "MegaForMaskedLM"),
|
| 241 |
+
("megatron-bert", "MegatronBertForPreTraining"),
|
| 242 |
+
("mobilebert", "MobileBertForPreTraining"),
|
| 243 |
+
("mpnet", "MPNetForMaskedLM"),
|
| 244 |
+
("mvp", "MvpForConditionalGeneration"),
|
| 245 |
+
("nezha", "NezhaForPreTraining"),
|
| 246 |
+
("nllb-moe", "NllbMoeForConditionalGeneration"),
|
| 247 |
+
("openai-gpt", "OpenAIGPTLMHeadModel"),
|
| 248 |
+
("retribert", "RetriBertModel"),
|
| 249 |
+
("roberta", "RobertaForMaskedLM"),
|
| 250 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForMaskedLM"),
|
| 251 |
+
("roc_bert", "RoCBertForPreTraining"),
|
| 252 |
+
("rwkv", "RwkvForCausalLM"),
|
| 253 |
+
("splinter", "SplinterForPreTraining"),
|
| 254 |
+
("squeezebert", "SqueezeBertForMaskedLM"),
|
| 255 |
+
("switch_transformers", "SwitchTransformersForConditionalGeneration"),
|
| 256 |
+
("t5", "T5ForConditionalGeneration"),
|
| 257 |
+
("tapas", "TapasForMaskedLM"),
|
| 258 |
+
("transfo-xl", "TransfoXLLMHeadModel"),
|
| 259 |
+
("tvlt", "TvltForPreTraining"),
|
| 260 |
+
("unispeech", "UniSpeechForPreTraining"),
|
| 261 |
+
("unispeech-sat", "UniSpeechSatForPreTraining"),
|
| 262 |
+
("videomae", "VideoMAEForPreTraining"),
|
| 263 |
+
("visual_bert", "VisualBertForPreTraining"),
|
| 264 |
+
("vit_mae", "ViTMAEForPreTraining"),
|
| 265 |
+
("wav2vec2", "Wav2Vec2ForPreTraining"),
|
| 266 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerForPreTraining"),
|
| 267 |
+
("xlm", "XLMWithLMHeadModel"),
|
| 268 |
+
("xlm-roberta", "XLMRobertaForMaskedLM"),
|
| 269 |
+
("xlm-roberta-xl", "XLMRobertaXLForMaskedLM"),
|
| 270 |
+
("xlnet", "XLNetLMHeadModel"),
|
| 271 |
+
("xmod", "XmodForMaskedLM"),
|
| 272 |
+
]
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
MODEL_WITH_LM_HEAD_MAPPING_NAMES = OrderedDict(
|
| 276 |
+
[
|
| 277 |
+
# Model with LM heads mapping
|
| 278 |
+
("albert", "AlbertForMaskedLM"),
|
| 279 |
+
("bart", "BartForConditionalGeneration"),
|
| 280 |
+
("bert", "BertForMaskedLM"),
|
| 281 |
+
("big_bird", "BigBirdForMaskedLM"),
|
| 282 |
+
("bigbird_pegasus", "BigBirdPegasusForConditionalGeneration"),
|
| 283 |
+
("blenderbot-small", "BlenderbotSmallForConditionalGeneration"),
|
| 284 |
+
("bloom", "BloomForCausalLM"),
|
| 285 |
+
("camembert", "CamembertForMaskedLM"),
|
| 286 |
+
("codegen", "CodeGenForCausalLM"),
|
| 287 |
+
("convbert", "ConvBertForMaskedLM"),
|
| 288 |
+
("cpmant", "CpmAntForCausalLM"),
|
| 289 |
+
("ctrl", "CTRLLMHeadModel"),
|
| 290 |
+
("data2vec-text", "Data2VecTextForMaskedLM"),
|
| 291 |
+
("deberta", "DebertaForMaskedLM"),
|
| 292 |
+
("deberta-v2", "DebertaV2ForMaskedLM"),
|
| 293 |
+
("distilbert", "DistilBertForMaskedLM"),
|
| 294 |
+
("electra", "ElectraForMaskedLM"),
|
| 295 |
+
("encoder-decoder", "EncoderDecoderModel"),
|
| 296 |
+
("ernie", "ErnieForMaskedLM"),
|
| 297 |
+
("esm", "EsmForMaskedLM"),
|
| 298 |
+
("flaubert", "FlaubertWithLMHeadModel"),
|
| 299 |
+
("fnet", "FNetForMaskedLM"),
|
| 300 |
+
("fsmt", "FSMTForConditionalGeneration"),
|
| 301 |
+
("funnel", "FunnelForMaskedLM"),
|
| 302 |
+
("git", "GitForCausalLM"),
|
| 303 |
+
("gpt-sw3", "GPT2LMHeadModel"),
|
| 304 |
+
("gpt2", "GPT2LMHeadModel"),
|
| 305 |
+
("gpt_bigcode", "GPTBigCodeForCausalLM"),
|
| 306 |
+
("gpt_neo", "GPTNeoForCausalLM"),
|
| 307 |
+
("gpt_neox", "GPTNeoXForCausalLM"),
|
| 308 |
+
("gpt_neox_japanese", "GPTNeoXJapaneseForCausalLM"),
|
| 309 |
+
("gptj", "GPTJForCausalLM"),
|
| 310 |
+
("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"),
|
| 311 |
+
("ibert", "IBertForMaskedLM"),
|
| 312 |
+
("layoutlm", "LayoutLMForMaskedLM"),
|
| 313 |
+
("led", "LEDForConditionalGeneration"),
|
| 314 |
+
("longformer", "LongformerForMaskedLM"),
|
| 315 |
+
("longt5", "LongT5ForConditionalGeneration"),
|
| 316 |
+
("luke", "LukeForMaskedLM"),
|
| 317 |
+
("m2m_100", "M2M100ForConditionalGeneration"),
|
| 318 |
+
("marian", "MarianMTModel"),
|
| 319 |
+
("mega", "MegaForMaskedLM"),
|
| 320 |
+
("megatron-bert", "MegatronBertForCausalLM"),
|
| 321 |
+
("mobilebert", "MobileBertForMaskedLM"),
|
| 322 |
+
("mpnet", "MPNetForMaskedLM"),
|
| 323 |
+
("mvp", "MvpForConditionalGeneration"),
|
| 324 |
+
("nezha", "NezhaForMaskedLM"),
|
| 325 |
+
("nllb-moe", "NllbMoeForConditionalGeneration"),
|
| 326 |
+
("nystromformer", "NystromformerForMaskedLM"),
|
| 327 |
+
("openai-gpt", "OpenAIGPTLMHeadModel"),
|
| 328 |
+
("pegasus_x", "PegasusXForConditionalGeneration"),
|
| 329 |
+
("plbart", "PLBartForConditionalGeneration"),
|
| 330 |
+
("qdqbert", "QDQBertForMaskedLM"),
|
| 331 |
+
("reformer", "ReformerModelWithLMHead"),
|
| 332 |
+
("rembert", "RemBertForMaskedLM"),
|
| 333 |
+
("roberta", "RobertaForMaskedLM"),
|
| 334 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForMaskedLM"),
|
| 335 |
+
("roc_bert", "RoCBertForMaskedLM"),
|
| 336 |
+
("roformer", "RoFormerForMaskedLM"),
|
| 337 |
+
("rwkv", "RwkvForCausalLM"),
|
| 338 |
+
("speech_to_text", "Speech2TextForConditionalGeneration"),
|
| 339 |
+
("squeezebert", "SqueezeBertForMaskedLM"),
|
| 340 |
+
("switch_transformers", "SwitchTransformersForConditionalGeneration"),
|
| 341 |
+
("t5", "T5ForConditionalGeneration"),
|
| 342 |
+
("tapas", "TapasForMaskedLM"),
|
| 343 |
+
("transfo-xl", "TransfoXLLMHeadModel"),
|
| 344 |
+
("wav2vec2", "Wav2Vec2ForMaskedLM"),
|
| 345 |
+
("whisper", "WhisperForConditionalGeneration"),
|
| 346 |
+
("xlm", "XLMWithLMHeadModel"),
|
| 347 |
+
("xlm-roberta", "XLMRobertaForMaskedLM"),
|
| 348 |
+
("xlm-roberta-xl", "XLMRobertaXLForMaskedLM"),
|
| 349 |
+
("xlnet", "XLNetLMHeadModel"),
|
| 350 |
+
("xmod", "XmodForMaskedLM"),
|
| 351 |
+
("yoso", "YosoForMaskedLM"),
|
| 352 |
+
]
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
|
| 356 |
+
[
|
| 357 |
+
# Model for Causal LM mapping
|
| 358 |
+
("bart", "BartForCausalLM"),
|
| 359 |
+
("bert", "BertLMHeadModel"),
|
| 360 |
+
("bert-generation", "BertGenerationDecoder"),
|
| 361 |
+
("big_bird", "BigBirdForCausalLM"),
|
| 362 |
+
("bigbird_pegasus", "BigBirdPegasusForCausalLM"),
|
| 363 |
+
("biogpt", "BioGptForCausalLM"),
|
| 364 |
+
("blenderbot", "BlenderbotForCausalLM"),
|
| 365 |
+
("blenderbot-small", "BlenderbotSmallForCausalLM"),
|
| 366 |
+
("bloom", "BloomForCausalLM"),
|
| 367 |
+
("camembert", "CamembertForCausalLM"),
|
| 368 |
+
("codegen", "CodeGenForCausalLM"),
|
| 369 |
+
("cpmant", "CpmAntForCausalLM"),
|
| 370 |
+
("ctrl", "CTRLLMHeadModel"),
|
| 371 |
+
("data2vec-text", "Data2VecTextForCausalLM"),
|
| 372 |
+
("electra", "ElectraForCausalLM"),
|
| 373 |
+
("ernie", "ErnieForCausalLM"),
|
| 374 |
+
("git", "GitForCausalLM"),
|
| 375 |
+
("gpt-sw3", "GPT2LMHeadModel"),
|
| 376 |
+
("gpt2", "GPT2LMHeadModel"),
|
| 377 |
+
("gpt_bigcode", "GPTBigCodeForCausalLM"),
|
| 378 |
+
("gpt_neo", "GPTNeoForCausalLM"),
|
| 379 |
+
("gpt_neox", "GPTNeoXForCausalLM"),
|
| 380 |
+
("gpt_neox_japanese", "GPTNeoXJapaneseForCausalLM"),
|
| 381 |
+
("gptj", "GPTJForCausalLM"),
|
| 382 |
+
("llama", "LlamaForCausalLM"),
|
| 383 |
+
("marian", "MarianForCausalLM"),
|
| 384 |
+
("mbart", "MBartForCausalLM"),
|
| 385 |
+
("mega", "MegaForCausalLM"),
|
| 386 |
+
("megatron-bert", "MegatronBertForCausalLM"),
|
| 387 |
+
("mvp", "MvpForCausalLM"),
|
| 388 |
+
("open-llama", "OpenLlamaForCausalLM"),
|
| 389 |
+
("openai-gpt", "OpenAIGPTLMHeadModel"),
|
| 390 |
+
("opt", "OPTForCausalLM"),
|
| 391 |
+
("pegasus", "PegasusForCausalLM"),
|
| 392 |
+
("plbart", "PLBartForCausalLM"),
|
| 393 |
+
("prophetnet", "ProphetNetForCausalLM"),
|
| 394 |
+
("qdqbert", "QDQBertLMHeadModel"),
|
| 395 |
+
("reformer", "ReformerModelWithLMHead"),
|
| 396 |
+
("rembert", "RemBertForCausalLM"),
|
| 397 |
+
("roberta", "RobertaForCausalLM"),
|
| 398 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForCausalLM"),
|
| 399 |
+
("roc_bert", "RoCBertForCausalLM"),
|
| 400 |
+
("roformer", "RoFormerForCausalLM"),
|
| 401 |
+
("rwkv", "RwkvForCausalLM"),
|
| 402 |
+
("speech_to_text_2", "Speech2Text2ForCausalLM"),
|
| 403 |
+
("transfo-xl", "TransfoXLLMHeadModel"),
|
| 404 |
+
("trocr", "TrOCRForCausalLM"),
|
| 405 |
+
("xglm", "XGLMForCausalLM"),
|
| 406 |
+
("xlm", "XLMWithLMHeadModel"),
|
| 407 |
+
("xlm-prophetnet", "XLMProphetNetForCausalLM"),
|
| 408 |
+
("xlm-roberta", "XLMRobertaForCausalLM"),
|
| 409 |
+
("xlm-roberta-xl", "XLMRobertaXLForCausalLM"),
|
| 410 |
+
("xlnet", "XLNetLMHeadModel"),
|
| 411 |
+
("xmod", "XmodForCausalLM"),
|
| 412 |
+
]
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES = OrderedDict(
|
| 416 |
+
[
|
| 417 |
+
("deit", "DeiTForMaskedImageModeling"),
|
| 418 |
+
("focalnet", "FocalNetForMaskedImageModeling"),
|
| 419 |
+
("swin", "SwinForMaskedImageModeling"),
|
| 420 |
+
("swinv2", "Swinv2ForMaskedImageModeling"),
|
| 421 |
+
("vit", "ViTForMaskedImageModeling"),
|
| 422 |
+
]
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING_NAMES = OrderedDict(
|
| 427 |
+
# Model for Causal Image Modeling mapping
|
| 428 |
+
[
|
| 429 |
+
("imagegpt", "ImageGPTForCausalImageModeling"),
|
| 430 |
+
]
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 434 |
+
[
|
| 435 |
+
# Model for Image Classification mapping
|
| 436 |
+
("beit", "BeitForImageClassification"),
|
| 437 |
+
("bit", "BitForImageClassification"),
|
| 438 |
+
("convnext", "ConvNextForImageClassification"),
|
| 439 |
+
("convnextv2", "ConvNextV2ForImageClassification"),
|
| 440 |
+
("cvt", "CvtForImageClassification"),
|
| 441 |
+
("data2vec-vision", "Data2VecVisionForImageClassification"),
|
| 442 |
+
("deit", ("DeiTForImageClassification", "DeiTForImageClassificationWithTeacher")),
|
| 443 |
+
("dinat", "DinatForImageClassification"),
|
| 444 |
+
(
|
| 445 |
+
"efficientformer",
|
| 446 |
+
(
|
| 447 |
+
"EfficientFormerForImageClassification",
|
| 448 |
+
"EfficientFormerForImageClassificationWithTeacher",
|
| 449 |
+
),
|
| 450 |
+
),
|
| 451 |
+
("efficientnet", "EfficientNetForImageClassification"),
|
| 452 |
+
("focalnet", "FocalNetForImageClassification"),
|
| 453 |
+
("imagegpt", "ImageGPTForImageClassification"),
|
| 454 |
+
("levit", ("LevitForImageClassification", "LevitForImageClassificationWithTeacher")),
|
| 455 |
+
("mobilenet_v1", "MobileNetV1ForImageClassification"),
|
| 456 |
+
("mobilenet_v2", "MobileNetV2ForImageClassification"),
|
| 457 |
+
("mobilevit", "MobileViTForImageClassification"),
|
| 458 |
+
("nat", "NatForImageClassification"),
|
| 459 |
+
(
|
| 460 |
+
"perceiver",
|
| 461 |
+
(
|
| 462 |
+
"PerceiverForImageClassificationLearned",
|
| 463 |
+
"PerceiverForImageClassificationFourier",
|
| 464 |
+
"PerceiverForImageClassificationConvProcessing",
|
| 465 |
+
),
|
| 466 |
+
),
|
| 467 |
+
("poolformer", "PoolFormerForImageClassification"),
|
| 468 |
+
("regnet", "RegNetForImageClassification"),
|
| 469 |
+
("resnet", "ResNetForImageClassification"),
|
| 470 |
+
("segformer", "SegformerForImageClassification"),
|
| 471 |
+
("swin", "SwinForImageClassification"),
|
| 472 |
+
("swinv2", "Swinv2ForImageClassification"),
|
| 473 |
+
("van", "VanForImageClassification"),
|
| 474 |
+
("vit", "ViTForImageClassification"),
|
| 475 |
+
("vit_hybrid", "ViTHybridForImageClassification"),
|
| 476 |
+
("vit_msn", "ViTMSNForImageClassification"),
|
| 477 |
+
]
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = OrderedDict(
|
| 481 |
+
[
|
| 482 |
+
# Do not add new models here, this class will be deprecated in the future.
|
| 483 |
+
# Model for Image Segmentation mapping
|
| 484 |
+
("detr", "DetrForSegmentation"),
|
| 485 |
+
]
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = OrderedDict(
|
| 489 |
+
[
|
| 490 |
+
# Model for Semantic Segmentation mapping
|
| 491 |
+
("beit", "BeitForSemanticSegmentation"),
|
| 492 |
+
("data2vec-vision", "Data2VecVisionForSemanticSegmentation"),
|
| 493 |
+
("dpt", "DPTForSemanticSegmentation"),
|
| 494 |
+
("mobilenet_v2", "MobileNetV2ForSemanticSegmentation"),
|
| 495 |
+
("mobilevit", "MobileViTForSemanticSegmentation"),
|
| 496 |
+
("segformer", "SegformerForSemanticSegmentation"),
|
| 497 |
+
("upernet", "UperNetForSemanticSegmentation"),
|
| 498 |
+
]
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES = OrderedDict(
|
| 502 |
+
[
|
| 503 |
+
# Model for Instance Segmentation mapping
|
| 504 |
+
# MaskFormerForInstanceSegmentation can be removed from this mapping in v5
|
| 505 |
+
("maskformer", "MaskFormerForInstanceSegmentation"),
|
| 506 |
+
]
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES = OrderedDict(
|
| 510 |
+
[
|
| 511 |
+
# Model for Universal Segmentation mapping
|
| 512 |
+
("detr", "DetrForSegmentation"),
|
| 513 |
+
("mask2former", "Mask2FormerForUniversalSegmentation"),
|
| 514 |
+
("maskformer", "MaskFormerForInstanceSegmentation"),
|
| 515 |
+
("oneformer", "OneFormerForUniversalSegmentation"),
|
| 516 |
+
]
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 520 |
+
[
|
| 521 |
+
("timesformer", "TimesformerForVideoClassification"),
|
| 522 |
+
("videomae", "VideoMAEForVideoClassification"),
|
| 523 |
+
]
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = OrderedDict(
|
| 527 |
+
[
|
| 528 |
+
("blip", "BlipForConditionalGeneration"),
|
| 529 |
+
("blip-2", "Blip2ForConditionalGeneration"),
|
| 530 |
+
("vision-encoder-decoder", "VisionEncoderDecoderModel"),
|
| 531 |
+
]
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
MODEL_FOR_MASKED_LM_MAPPING_NAMES = OrderedDict(
|
| 535 |
+
[
|
| 536 |
+
# Model for Masked LM mapping
|
| 537 |
+
("albert", "AlbertForMaskedLM"),
|
| 538 |
+
("bart", "BartForConditionalGeneration"),
|
| 539 |
+
("bert", "BertForMaskedLM"),
|
| 540 |
+
("big_bird", "BigBirdForMaskedLM"),
|
| 541 |
+
("camembert", "CamembertForMaskedLM"),
|
| 542 |
+
("convbert", "ConvBertForMaskedLM"),
|
| 543 |
+
("data2vec-text", "Data2VecTextForMaskedLM"),
|
| 544 |
+
("deberta", "DebertaForMaskedLM"),
|
| 545 |
+
("deberta-v2", "DebertaV2ForMaskedLM"),
|
| 546 |
+
("distilbert", "DistilBertForMaskedLM"),
|
| 547 |
+
("electra", "ElectraForMaskedLM"),
|
| 548 |
+
("ernie", "ErnieForMaskedLM"),
|
| 549 |
+
("esm", "EsmForMaskedLM"),
|
| 550 |
+
("flaubert", "FlaubertWithLMHeadModel"),
|
| 551 |
+
("fnet", "FNetForMaskedLM"),
|
| 552 |
+
("funnel", "FunnelForMaskedLM"),
|
| 553 |
+
("ibert", "IBertForMaskedLM"),
|
| 554 |
+
("layoutlm", "LayoutLMForMaskedLM"),
|
| 555 |
+
("longformer", "LongformerForMaskedLM"),
|
| 556 |
+
("luke", "LukeForMaskedLM"),
|
| 557 |
+
("mbart", "MBartForConditionalGeneration"),
|
| 558 |
+
("mega", "MegaForMaskedLM"),
|
| 559 |
+
("megatron-bert", "MegatronBertForMaskedLM"),
|
| 560 |
+
("mobilebert", "MobileBertForMaskedLM"),
|
| 561 |
+
("mpnet", "MPNetForMaskedLM"),
|
| 562 |
+
("mvp", "MvpForConditionalGeneration"),
|
| 563 |
+
("nezha", "NezhaForMaskedLM"),
|
| 564 |
+
("nystromformer", "NystromformerForMaskedLM"),
|
| 565 |
+
("perceiver", "PerceiverForMaskedLM"),
|
| 566 |
+
("qdqbert", "QDQBertForMaskedLM"),
|
| 567 |
+
("reformer", "ReformerForMaskedLM"),
|
| 568 |
+
("rembert", "RemBertForMaskedLM"),
|
| 569 |
+
("roberta", "RobertaForMaskedLM"),
|
| 570 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForMaskedLM"),
|
| 571 |
+
("roc_bert", "RoCBertForMaskedLM"),
|
| 572 |
+
("roformer", "RoFormerForMaskedLM"),
|
| 573 |
+
("squeezebert", "SqueezeBertForMaskedLM"),
|
| 574 |
+
("tapas", "TapasForMaskedLM"),
|
| 575 |
+
("wav2vec2", "Wav2Vec2ForMaskedLM"),
|
| 576 |
+
("xlm", "XLMWithLMHeadModel"),
|
| 577 |
+
("xlm-roberta", "XLMRobertaForMaskedLM"),
|
| 578 |
+
("xlm-roberta-xl", "XLMRobertaXLForMaskedLM"),
|
| 579 |
+
("xmod", "XmodForMaskedLM"),
|
| 580 |
+
("yoso", "YosoForMaskedLM"),
|
| 581 |
+
]
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = OrderedDict(
|
| 585 |
+
[
|
| 586 |
+
# Model for Object Detection mapping
|
| 587 |
+
("conditional_detr", "ConditionalDetrForObjectDetection"),
|
| 588 |
+
("deformable_detr", "DeformableDetrForObjectDetection"),
|
| 589 |
+
("deta", "DetaForObjectDetection"),
|
| 590 |
+
("detr", "DetrForObjectDetection"),
|
| 591 |
+
("table-transformer", "TableTransformerForObjectDetection"),
|
| 592 |
+
("yolos", "YolosForObjectDetection"),
|
| 593 |
+
]
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
+
MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = OrderedDict(
|
| 597 |
+
[
|
| 598 |
+
# Model for Zero Shot Object Detection mapping
|
| 599 |
+
("owlvit", "OwlViTForObjectDetection")
|
| 600 |
+
]
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = OrderedDict(
|
| 604 |
+
[
|
| 605 |
+
# Model for depth estimation mapping
|
| 606 |
+
("dpt", "DPTForDepthEstimation"),
|
| 607 |
+
("glpn", "GLPNForDepthEstimation"),
|
| 608 |
+
]
|
| 609 |
+
)
|
| 610 |
+
MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
|
| 611 |
+
[
|
| 612 |
+
# Model for Seq2Seq Causal LM mapping
|
| 613 |
+
("bart", "BartForConditionalGeneration"),
|
| 614 |
+
("bigbird_pegasus", "BigBirdPegasusForConditionalGeneration"),
|
| 615 |
+
("blenderbot", "BlenderbotForConditionalGeneration"),
|
| 616 |
+
("blenderbot-small", "BlenderbotSmallForConditionalGeneration"),
|
| 617 |
+
("encoder-decoder", "EncoderDecoderModel"),
|
| 618 |
+
("fsmt", "FSMTForConditionalGeneration"),
|
| 619 |
+
("gptsan-japanese", "GPTSanJapaneseForConditionalGeneration"),
|
| 620 |
+
("led", "LEDForConditionalGeneration"),
|
| 621 |
+
("longt5", "LongT5ForConditionalGeneration"),
|
| 622 |
+
("m2m_100", "M2M100ForConditionalGeneration"),
|
| 623 |
+
("marian", "MarianMTModel"),
|
| 624 |
+
("mbart", "MBartForConditionalGeneration"),
|
| 625 |
+
("mt5", "MT5ForConditionalGeneration"),
|
| 626 |
+
("mvp", "MvpForConditionalGeneration"),
|
| 627 |
+
("nllb-moe", "NllbMoeForConditionalGeneration"),
|
| 628 |
+
("pegasus", "PegasusForConditionalGeneration"),
|
| 629 |
+
("pegasus_x", "PegasusXForConditionalGeneration"),
|
| 630 |
+
("plbart", "PLBartForConditionalGeneration"),
|
| 631 |
+
("prophetnet", "ProphetNetForConditionalGeneration"),
|
| 632 |
+
("switch_transformers", "SwitchTransformersForConditionalGeneration"),
|
| 633 |
+
("t5", "T5ForConditionalGeneration"),
|
| 634 |
+
("xlm-prophetnet", "XLMProphetNetForConditionalGeneration"),
|
| 635 |
+
]
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = OrderedDict(
|
| 639 |
+
[
|
| 640 |
+
("speech-encoder-decoder", "SpeechEncoderDecoderModel"),
|
| 641 |
+
("speech_to_text", "Speech2TextForConditionalGeneration"),
|
| 642 |
+
("speecht5", "SpeechT5ForSpeechToText"),
|
| 643 |
+
("whisper", "WhisperForConditionalGeneration"),
|
| 644 |
+
]
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 648 |
+
[
|
| 649 |
+
# Model for Sequence Classification mapping
|
| 650 |
+
("albert", "AlbertForSequenceClassification"),
|
| 651 |
+
("bart", "BartForSequenceClassification"),
|
| 652 |
+
("bert", "BertForSequenceClassification"),
|
| 653 |
+
("big_bird", "BigBirdForSequenceClassification"),
|
| 654 |
+
("bigbird_pegasus", "BigBirdPegasusForSequenceClassification"),
|
| 655 |
+
("biogpt", "BioGptForSequenceClassification"),
|
| 656 |
+
("bloom", "BloomForSequenceClassification"),
|
| 657 |
+
("camembert", "CamembertForSequenceClassification"),
|
| 658 |
+
("canine", "CanineForSequenceClassification"),
|
| 659 |
+
("convbert", "ConvBertForSequenceClassification"),
|
| 660 |
+
("ctrl", "CTRLForSequenceClassification"),
|
| 661 |
+
("data2vec-text", "Data2VecTextForSequenceClassification"),
|
| 662 |
+
("deberta", "DebertaForSequenceClassification"),
|
| 663 |
+
("deberta-v2", "DebertaV2ForSequenceClassification"),
|
| 664 |
+
("distilbert", "DistilBertForSequenceClassification"),
|
| 665 |
+
("electra", "ElectraForSequenceClassification"),
|
| 666 |
+
("ernie", "ErnieForSequenceClassification"),
|
| 667 |
+
("ernie_m", "ErnieMForSequenceClassification"),
|
| 668 |
+
("esm", "EsmForSequenceClassification"),
|
| 669 |
+
("flaubert", "FlaubertForSequenceClassification"),
|
| 670 |
+
("fnet", "FNetForSequenceClassification"),
|
| 671 |
+
("funnel", "FunnelForSequenceClassification"),
|
| 672 |
+
("gpt-sw3", "GPT2ForSequenceClassification"),
|
| 673 |
+
("gpt2", "GPT2ForSequenceClassification"),
|
| 674 |
+
("gpt_bigcode", "GPTBigCodeForSequenceClassification"),
|
| 675 |
+
("gpt_neo", "GPTNeoForSequenceClassification"),
|
| 676 |
+
("gpt_neox", "GPTNeoXForSequenceClassification"),
|
| 677 |
+
("gptj", "GPTJForSequenceClassification"),
|
| 678 |
+
("ibert", "IBertForSequenceClassification"),
|
| 679 |
+
("layoutlm", "LayoutLMForSequenceClassification"),
|
| 680 |
+
("layoutlmv2", "LayoutLMv2ForSequenceClassification"),
|
| 681 |
+
("layoutlmv3", "LayoutLMv3ForSequenceClassification"),
|
| 682 |
+
("led", "LEDForSequenceClassification"),
|
| 683 |
+
("lilt", "LiltForSequenceClassification"),
|
| 684 |
+
("llama", "LlamaForSequenceClassification"),
|
| 685 |
+
("longformer", "LongformerForSequenceClassification"),
|
| 686 |
+
("luke", "LukeForSequenceClassification"),
|
| 687 |
+
("markuplm", "MarkupLMForSequenceClassification"),
|
| 688 |
+
("mbart", "MBartForSequenceClassification"),
|
| 689 |
+
("mega", "MegaForSequenceClassification"),
|
| 690 |
+
("megatron-bert", "MegatronBertForSequenceClassification"),
|
| 691 |
+
("mobilebert", "MobileBertForSequenceClassification"),
|
| 692 |
+
("mpnet", "MPNetForSequenceClassification"),
|
| 693 |
+
("mvp", "MvpForSequenceClassification"),
|
| 694 |
+
("nezha", "NezhaForSequenceClassification"),
|
| 695 |
+
("nystromformer", "NystromformerForSequenceClassification"),
|
| 696 |
+
("open-llama", "OpenLlamaForSequenceClassification"),
|
| 697 |
+
("openai-gpt", "OpenAIGPTForSequenceClassification"),
|
| 698 |
+
("opt", "OPTForSequenceClassification"),
|
| 699 |
+
("perceiver", "PerceiverForSequenceClassification"),
|
| 700 |
+
("plbart", "PLBartForSequenceClassification"),
|
| 701 |
+
("qdqbert", "QDQBertForSequenceClassification"),
|
| 702 |
+
("reformer", "ReformerForSequenceClassification"),
|
| 703 |
+
("rembert", "RemBertForSequenceClassification"),
|
| 704 |
+
("roberta", "RobertaForSequenceClassification"),
|
| 705 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForSequenceClassification"),
|
| 706 |
+
("roc_bert", "RoCBertForSequenceClassification"),
|
| 707 |
+
("roformer", "RoFormerForSequenceClassification"),
|
| 708 |
+
("squeezebert", "SqueezeBertForSequenceClassification"),
|
| 709 |
+
("tapas", "TapasForSequenceClassification"),
|
| 710 |
+
("transfo-xl", "TransfoXLForSequenceClassification"),
|
| 711 |
+
("xlm", "XLMForSequenceClassification"),
|
| 712 |
+
("xlm-roberta", "XLMRobertaForSequenceClassification"),
|
| 713 |
+
("xlm-roberta-xl", "XLMRobertaXLForSequenceClassification"),
|
| 714 |
+
("xlnet", "XLNetForSequenceClassification"),
|
| 715 |
+
("xmod", "XmodForSequenceClassification"),
|
| 716 |
+
("yoso", "YosoForSequenceClassification"),
|
| 717 |
+
]
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
|
| 721 |
+
[
|
| 722 |
+
# Model for Question Answering mapping
|
| 723 |
+
("albert", "AlbertForQuestionAnswering"),
|
| 724 |
+
("bart", "BartForQuestionAnswering"),
|
| 725 |
+
("bert", "BertForQuestionAnswering"),
|
| 726 |
+
("big_bird", "BigBirdForQuestionAnswering"),
|
| 727 |
+
("bigbird_pegasus", "BigBirdPegasusForQuestionAnswering"),
|
| 728 |
+
("bloom", "BloomForQuestionAnswering"),
|
| 729 |
+
("camembert", "CamembertForQuestionAnswering"),
|
| 730 |
+
("canine", "CanineForQuestionAnswering"),
|
| 731 |
+
("convbert", "ConvBertForQuestionAnswering"),
|
| 732 |
+
("data2vec-text", "Data2VecTextForQuestionAnswering"),
|
| 733 |
+
("deberta", "DebertaForQuestionAnswering"),
|
| 734 |
+
("deberta-v2", "DebertaV2ForQuestionAnswering"),
|
| 735 |
+
("distilbert", "DistilBertForQuestionAnswering"),
|
| 736 |
+
("electra", "ElectraForQuestionAnswering"),
|
| 737 |
+
("ernie", "ErnieForQuestionAnswering"),
|
| 738 |
+
("ernie_m", "ErnieMForQuestionAnswering"),
|
| 739 |
+
("flaubert", "FlaubertForQuestionAnsweringSimple"),
|
| 740 |
+
("fnet", "FNetForQuestionAnswering"),
|
| 741 |
+
("funnel", "FunnelForQuestionAnswering"),
|
| 742 |
+
("gpt2", "GPT2ForQuestionAnswering"),
|
| 743 |
+
("gpt_neo", "GPTNeoForQuestionAnswering"),
|
| 744 |
+
("gpt_neox", "GPTNeoXForQuestionAnswering"),
|
| 745 |
+
("gptj", "GPTJForQuestionAnswering"),
|
| 746 |
+
("ibert", "IBertForQuestionAnswering"),
|
| 747 |
+
("layoutlmv2", "LayoutLMv2ForQuestionAnswering"),
|
| 748 |
+
("layoutlmv3", "LayoutLMv3ForQuestionAnswering"),
|
| 749 |
+
("led", "LEDForQuestionAnswering"),
|
| 750 |
+
("lilt", "LiltForQuestionAnswering"),
|
| 751 |
+
("longformer", "LongformerForQuestionAnswering"),
|
| 752 |
+
("luke", "LukeForQuestionAnswering"),
|
| 753 |
+
("lxmert", "LxmertForQuestionAnswering"),
|
| 754 |
+
("markuplm", "MarkupLMForQuestionAnswering"),
|
| 755 |
+
("mbart", "MBartForQuestionAnswering"),
|
| 756 |
+
("mega", "MegaForQuestionAnswering"),
|
| 757 |
+
("megatron-bert", "MegatronBertForQuestionAnswering"),
|
| 758 |
+
("mobilebert", "MobileBertForQuestionAnswering"),
|
| 759 |
+
("mpnet", "MPNetForQuestionAnswering"),
|
| 760 |
+
("mvp", "MvpForQuestionAnswering"),
|
| 761 |
+
("nezha", "NezhaForQuestionAnswering"),
|
| 762 |
+
("nystromformer", "NystromformerForQuestionAnswering"),
|
| 763 |
+
("opt", "OPTForQuestionAnswering"),
|
| 764 |
+
("qdqbert", "QDQBertForQuestionAnswering"),
|
| 765 |
+
("reformer", "ReformerForQuestionAnswering"),
|
| 766 |
+
("rembert", "RemBertForQuestionAnswering"),
|
| 767 |
+
("roberta", "RobertaForQuestionAnswering"),
|
| 768 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForQuestionAnswering"),
|
| 769 |
+
("roc_bert", "RoCBertForQuestionAnswering"),
|
| 770 |
+
("roformer", "RoFormerForQuestionAnswering"),
|
| 771 |
+
("splinter", "SplinterForQuestionAnswering"),
|
| 772 |
+
("squeezebert", "SqueezeBertForQuestionAnswering"),
|
| 773 |
+
("xlm", "XLMForQuestionAnsweringSimple"),
|
| 774 |
+
("xlm-roberta", "XLMRobertaForQuestionAnswering"),
|
| 775 |
+
("xlm-roberta-xl", "XLMRobertaXLForQuestionAnswering"),
|
| 776 |
+
("xlnet", "XLNetForQuestionAnsweringSimple"),
|
| 777 |
+
("xmod", "XmodForQuestionAnswering"),
|
| 778 |
+
("yoso", "YosoForQuestionAnswering"),
|
| 779 |
+
]
|
| 780 |
+
)
|
| 781 |
+
|
| 782 |
+
MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
|
| 783 |
+
[
|
| 784 |
+
# Model for Table Question Answering mapping
|
| 785 |
+
("tapas", "TapasForQuestionAnswering"),
|
| 786 |
+
]
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
|
| 790 |
+
[
|
| 791 |
+
("vilt", "ViltForQuestionAnswering"),
|
| 792 |
+
]
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
|
| 796 |
+
[
|
| 797 |
+
("layoutlm", "LayoutLMForQuestionAnswering"),
|
| 798 |
+
("layoutlmv2", "LayoutLMv2ForQuestionAnswering"),
|
| 799 |
+
("layoutlmv3", "LayoutLMv3ForQuestionAnswering"),
|
| 800 |
+
]
|
| 801 |
+
)
|
| 802 |
+
|
| 803 |
+
MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 804 |
+
[
|
| 805 |
+
# Model for Token Classification mapping
|
| 806 |
+
("albert", "AlbertForTokenClassification"),
|
| 807 |
+
("bert", "BertForTokenClassification"),
|
| 808 |
+
("big_bird", "BigBirdForTokenClassification"),
|
| 809 |
+
("biogpt", "BioGptForTokenClassification"),
|
| 810 |
+
("bloom", "BloomForTokenClassification"),
|
| 811 |
+
("camembert", "CamembertForTokenClassification"),
|
| 812 |
+
("canine", "CanineForTokenClassification"),
|
| 813 |
+
("convbert", "ConvBertForTokenClassification"),
|
| 814 |
+
("data2vec-text", "Data2VecTextForTokenClassification"),
|
| 815 |
+
("deberta", "DebertaForTokenClassification"),
|
| 816 |
+
("deberta-v2", "DebertaV2ForTokenClassification"),
|
| 817 |
+
("distilbert", "DistilBertForTokenClassification"),
|
| 818 |
+
("electra", "ElectraForTokenClassification"),
|
| 819 |
+
("ernie", "ErnieForTokenClassification"),
|
| 820 |
+
("ernie_m", "ErnieMForTokenClassification"),
|
| 821 |
+
("esm", "EsmForTokenClassification"),
|
| 822 |
+
("flaubert", "FlaubertForTokenClassification"),
|
| 823 |
+
("fnet", "FNetForTokenClassification"),
|
| 824 |
+
("funnel", "FunnelForTokenClassification"),
|
| 825 |
+
("gpt-sw3", "GPT2ForTokenClassification"),
|
| 826 |
+
("gpt2", "GPT2ForTokenClassification"),
|
| 827 |
+
("gpt_bigcode", "GPTBigCodeForTokenClassification"),
|
| 828 |
+
("gpt_neo", "GPTNeoForTokenClassification"),
|
| 829 |
+
("gpt_neox", "GPTNeoXForTokenClassification"),
|
| 830 |
+
("ibert", "IBertForTokenClassification"),
|
| 831 |
+
("layoutlm", "LayoutLMForTokenClassification"),
|
| 832 |
+
("layoutlmv2", "LayoutLMv2ForTokenClassification"),
|
| 833 |
+
("layoutlmv3", "LayoutLMv3ForTokenClassification"),
|
| 834 |
+
("lilt", "LiltForTokenClassification"),
|
| 835 |
+
("longformer", "LongformerForTokenClassification"),
|
| 836 |
+
("luke", "LukeForTokenClassification"),
|
| 837 |
+
("markuplm", "MarkupLMForTokenClassification"),
|
| 838 |
+
("mega", "MegaForTokenClassification"),
|
| 839 |
+
("megatron-bert", "MegatronBertForTokenClassification"),
|
| 840 |
+
("mobilebert", "MobileBertForTokenClassification"),
|
| 841 |
+
("mpnet", "MPNetForTokenClassification"),
|
| 842 |
+
("nezha", "NezhaForTokenClassification"),
|
| 843 |
+
("nystromformer", "NystromformerForTokenClassification"),
|
| 844 |
+
("qdqbert", "QDQBertForTokenClassification"),
|
| 845 |
+
("rembert", "RemBertForTokenClassification"),
|
| 846 |
+
("roberta", "RobertaForTokenClassification"),
|
| 847 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForTokenClassification"),
|
| 848 |
+
("roc_bert", "RoCBertForTokenClassification"),
|
| 849 |
+
("roformer", "RoFormerForTokenClassification"),
|
| 850 |
+
("squeezebert", "SqueezeBertForTokenClassification"),
|
| 851 |
+
("xlm", "XLMForTokenClassification"),
|
| 852 |
+
("xlm-roberta", "XLMRobertaForTokenClassification"),
|
| 853 |
+
("xlm-roberta-xl", "XLMRobertaXLForTokenClassification"),
|
| 854 |
+
("xlnet", "XLNetForTokenClassification"),
|
| 855 |
+
("xmod", "XmodForTokenClassification"),
|
| 856 |
+
("yoso", "YosoForTokenClassification"),
|
| 857 |
+
]
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES = OrderedDict(
|
| 861 |
+
[
|
| 862 |
+
# Model for Multiple Choice mapping
|
| 863 |
+
("albert", "AlbertForMultipleChoice"),
|
| 864 |
+
("bert", "BertForMultipleChoice"),
|
| 865 |
+
("big_bird", "BigBirdForMultipleChoice"),
|
| 866 |
+
("camembert", "CamembertForMultipleChoice"),
|
| 867 |
+
("canine", "CanineForMultipleChoice"),
|
| 868 |
+
("convbert", "ConvBertForMultipleChoice"),
|
| 869 |
+
("data2vec-text", "Data2VecTextForMultipleChoice"),
|
| 870 |
+
("deberta-v2", "DebertaV2ForMultipleChoice"),
|
| 871 |
+
("distilbert", "DistilBertForMultipleChoice"),
|
| 872 |
+
("electra", "ElectraForMultipleChoice"),
|
| 873 |
+
("ernie", "ErnieForMultipleChoice"),
|
| 874 |
+
("ernie_m", "ErnieMForMultipleChoice"),
|
| 875 |
+
("flaubert", "FlaubertForMultipleChoice"),
|
| 876 |
+
("fnet", "FNetForMultipleChoice"),
|
| 877 |
+
("funnel", "FunnelForMultipleChoice"),
|
| 878 |
+
("ibert", "IBertForMultipleChoice"),
|
| 879 |
+
("longformer", "LongformerForMultipleChoice"),
|
| 880 |
+
("luke", "LukeForMultipleChoice"),
|
| 881 |
+
("mega", "MegaForMultipleChoice"),
|
| 882 |
+
("megatron-bert", "MegatronBertForMultipleChoice"),
|
| 883 |
+
("mobilebert", "MobileBertForMultipleChoice"),
|
| 884 |
+
("mpnet", "MPNetForMultipleChoice"),
|
| 885 |
+
("nezha", "NezhaForMultipleChoice"),
|
| 886 |
+
("nystromformer", "NystromformerForMultipleChoice"),
|
| 887 |
+
("qdqbert", "QDQBertForMultipleChoice"),
|
| 888 |
+
("rembert", "RemBertForMultipleChoice"),
|
| 889 |
+
("roberta", "RobertaForMultipleChoice"),
|
| 890 |
+
("roberta-prelayernorm", "RobertaPreLayerNormForMultipleChoice"),
|
| 891 |
+
("roc_bert", "RoCBertForMultipleChoice"),
|
| 892 |
+
("roformer", "RoFormerForMultipleChoice"),
|
| 893 |
+
("squeezebert", "SqueezeBertForMultipleChoice"),
|
| 894 |
+
("xlm", "XLMForMultipleChoice"),
|
| 895 |
+
("xlm-roberta", "XLMRobertaForMultipleChoice"),
|
| 896 |
+
("xlm-roberta-xl", "XLMRobertaXLForMultipleChoice"),
|
| 897 |
+
("xlnet", "XLNetForMultipleChoice"),
|
| 898 |
+
("xmod", "XmodForMultipleChoice"),
|
| 899 |
+
("yoso", "YosoForMultipleChoice"),
|
| 900 |
+
]
|
| 901 |
+
)
|
| 902 |
+
|
| 903 |
+
MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES = OrderedDict(
|
| 904 |
+
[
|
| 905 |
+
("bert", "BertForNextSentencePrediction"),
|
| 906 |
+
("ernie", "ErnieForNextSentencePrediction"),
|
| 907 |
+
("fnet", "FNetForNextSentencePrediction"),
|
| 908 |
+
("megatron-bert", "MegatronBertForNextSentencePrediction"),
|
| 909 |
+
("mobilebert", "MobileBertForNextSentencePrediction"),
|
| 910 |
+
("nezha", "NezhaForNextSentencePrediction"),
|
| 911 |
+
("qdqbert", "QDQBertForNextSentencePrediction"),
|
| 912 |
+
]
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 916 |
+
[
|
| 917 |
+
# Model for Audio Classification mapping
|
| 918 |
+
("audio-spectrogram-transformer", "ASTForAudioClassification"),
|
| 919 |
+
("data2vec-audio", "Data2VecAudioForSequenceClassification"),
|
| 920 |
+
("hubert", "HubertForSequenceClassification"),
|
| 921 |
+
("sew", "SEWForSequenceClassification"),
|
| 922 |
+
("sew-d", "SEWDForSequenceClassification"),
|
| 923 |
+
("unispeech", "UniSpeechForSequenceClassification"),
|
| 924 |
+
("unispeech-sat", "UniSpeechSatForSequenceClassification"),
|
| 925 |
+
("wav2vec2", "Wav2Vec2ForSequenceClassification"),
|
| 926 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerForSequenceClassification"),
|
| 927 |
+
("wavlm", "WavLMForSequenceClassification"),
|
| 928 |
+
("whisper", "WhisperForAudioClassification"),
|
| 929 |
+
]
|
| 930 |
+
)
|
| 931 |
+
|
| 932 |
+
MODEL_FOR_CTC_MAPPING_NAMES = OrderedDict(
|
| 933 |
+
[
|
| 934 |
+
# Model for Connectionist temporal classification (CTC) mapping
|
| 935 |
+
("data2vec-audio", "Data2VecAudioForCTC"),
|
| 936 |
+
("hubert", "HubertForCTC"),
|
| 937 |
+
("mctct", "MCTCTForCTC"),
|
| 938 |
+
("sew", "SEWForCTC"),
|
| 939 |
+
("sew-d", "SEWDForCTC"),
|
| 940 |
+
("unispeech", "UniSpeechForCTC"),
|
| 941 |
+
("unispeech-sat", "UniSpeechSatForCTC"),
|
| 942 |
+
("wav2vec2", "Wav2Vec2ForCTC"),
|
| 943 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerForCTC"),
|
| 944 |
+
("wavlm", "WavLMForCTC"),
|
| 945 |
+
]
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 949 |
+
[
|
| 950 |
+
# Model for Audio Classification mapping
|
| 951 |
+
("data2vec-audio", "Data2VecAudioForAudioFrameClassification"),
|
| 952 |
+
("unispeech-sat", "UniSpeechSatForAudioFrameClassification"),
|
| 953 |
+
("wav2vec2", "Wav2Vec2ForAudioFrameClassification"),
|
| 954 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerForAudioFrameClassification"),
|
| 955 |
+
("wavlm", "WavLMForAudioFrameClassification"),
|
| 956 |
+
]
|
| 957 |
+
)
|
| 958 |
+
|
| 959 |
+
MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = OrderedDict(
|
| 960 |
+
[
|
| 961 |
+
# Model for Audio Classification mapping
|
| 962 |
+
("data2vec-audio", "Data2VecAudioForXVector"),
|
| 963 |
+
("unispeech-sat", "UniSpeechSatForXVector"),
|
| 964 |
+
("wav2vec2", "Wav2Vec2ForXVector"),
|
| 965 |
+
("wav2vec2-conformer", "Wav2Vec2ConformerForXVector"),
|
| 966 |
+
("wavlm", "WavLMForXVector"),
|
| 967 |
+
]
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 971 |
+
[
|
| 972 |
+
# Model for Zero Shot Image Classification mapping
|
| 973 |
+
("align", "AlignModel"),
|
| 974 |
+
("altclip", "AltCLIPModel"),
|
| 975 |
+
("blip", "BlipModel"),
|
| 976 |
+
("chinese_clip", "ChineseCLIPModel"),
|
| 977 |
+
("clip", "CLIPModel"),
|
| 978 |
+
("clipseg", "CLIPSegModel"),
|
| 979 |
+
]
|
| 980 |
+
)
|
| 981 |
+
|
| 982 |
+
MODEL_FOR_BACKBONE_MAPPING_NAMES = OrderedDict(
|
| 983 |
+
[
|
| 984 |
+
# Backbone mapping
|
| 985 |
+
("bit", "BitBackbone"),
|
| 986 |
+
("convnext", "ConvNextBackbone"),
|
| 987 |
+
("convnextv2", "ConvNextV2Backbone"),
|
| 988 |
+
("dinat", "DinatBackbone"),
|
| 989 |
+
("focalnet", "FocalNetBackbone"),
|
| 990 |
+
("maskformer-swin", "MaskFormerSwinBackbone"),
|
| 991 |
+
("nat", "NatBackbone"),
|
| 992 |
+
("resnet", "ResNetBackbone"),
|
| 993 |
+
("swin", "SwinBackbone"),
|
| 994 |
+
]
|
| 995 |
+
)
|
| 996 |
+
|
| 997 |
+
MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = OrderedDict(
|
| 998 |
+
[
|
| 999 |
+
("sam", "SamModel"),
|
| 1000 |
+
]
|
| 1001 |
+
)
|
| 1002 |
+
|
| 1003 |
+
MODEL_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_MAPPING_NAMES)
|
| 1004 |
+
MODEL_FOR_PRETRAINING_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_PRETRAINING_MAPPING_NAMES)
|
| 1005 |
+
MODEL_WITH_LM_HEAD_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_WITH_LM_HEAD_MAPPING_NAMES)
|
| 1006 |
+
MODEL_FOR_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
|
| 1007 |
+
MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING = _LazyAutoMapping(
|
| 1008 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING_NAMES
|
| 1009 |
+
)
|
| 1010 |
+
MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1011 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
|
| 1012 |
+
)
|
| 1013 |
+
MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1014 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
|
| 1015 |
+
)
|
| 1016 |
+
MODEL_FOR_IMAGE_SEGMENTATION_MAPPING = _LazyAutoMapping(
|
| 1017 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES
|
| 1018 |
+
)
|
| 1019 |
+
MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING = _LazyAutoMapping(
|
| 1020 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES
|
| 1021 |
+
)
|
| 1022 |
+
MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING = _LazyAutoMapping(
|
| 1023 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES
|
| 1024 |
+
)
|
| 1025 |
+
MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING = _LazyAutoMapping(
|
| 1026 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES
|
| 1027 |
+
)
|
| 1028 |
+
MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1029 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES
|
| 1030 |
+
)
|
| 1031 |
+
MODEL_FOR_VISION_2_SEQ_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
|
| 1032 |
+
MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
|
| 1033 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES
|
| 1034 |
+
)
|
| 1035 |
+
MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
|
| 1036 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES
|
| 1037 |
+
)
|
| 1038 |
+
MODEL_FOR_MASKED_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_MASKED_LM_MAPPING_NAMES)
|
| 1039 |
+
MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING = _LazyAutoMapping(
|
| 1040 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES
|
| 1041 |
+
)
|
| 1042 |
+
MODEL_FOR_OBJECT_DETECTION_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES)
|
| 1043 |
+
MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING = _LazyAutoMapping(
|
| 1044 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES
|
| 1045 |
+
)
|
| 1046 |
+
MODEL_FOR_DEPTH_ESTIMATION_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES)
|
| 1047 |
+
MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING = _LazyAutoMapping(
|
| 1048 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
|
| 1049 |
+
)
|
| 1050 |
+
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1051 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
|
| 1052 |
+
)
|
| 1053 |
+
MODEL_FOR_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
|
| 1054 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
|
| 1055 |
+
)
|
| 1056 |
+
MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
|
| 1057 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES
|
| 1058 |
+
)
|
| 1059 |
+
MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1060 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
|
| 1061 |
+
)
|
| 1062 |
+
MODEL_FOR_MULTIPLE_CHOICE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES)
|
| 1063 |
+
MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING = _LazyAutoMapping(
|
| 1064 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
|
| 1065 |
+
)
|
| 1066 |
+
MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1067 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
|
| 1068 |
+
)
|
| 1069 |
+
MODEL_FOR_CTC_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_CTC_MAPPING_NAMES)
|
| 1070 |
+
MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES)
|
| 1071 |
+
MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 1072 |
+
CONFIG_MAPPING_NAMES, MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES
|
| 1073 |
+
)
|
| 1074 |
+
MODEL_FOR_AUDIO_XVECTOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES)
|
| 1075 |
+
|
| 1076 |
+
MODEL_FOR_BACKBONE_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_BACKBONE_MAPPING_NAMES)
|
| 1077 |
+
|
| 1078 |
+
MODEL_FOR_MASK_GENERATION_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, MODEL_FOR_MASK_GENERATION_MAPPING_NAMES)
|
| 1079 |
+
|
| 1080 |
+
|
| 1081 |
+
class AutoModelForMaskGeneration(_BaseAutoModelClass):
|
| 1082 |
+
_model_mapping = MODEL_FOR_MASK_GENERATION_MAPPING
|
| 1083 |
+
|
| 1084 |
+
|
| 1085 |
+
class AutoModel(_BaseAutoModelClass):
|
| 1086 |
+
_model_mapping = MODEL_MAPPING
|
| 1087 |
+
|
| 1088 |
+
|
| 1089 |
+
AutoModel = auto_class_update(AutoModel)
|
| 1090 |
+
|
| 1091 |
+
|
| 1092 |
+
class AutoModelForPreTraining(_BaseAutoModelClass):
|
| 1093 |
+
_model_mapping = MODEL_FOR_PRETRAINING_MAPPING
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
AutoModelForPreTraining = auto_class_update(AutoModelForPreTraining, head_doc="pretraining")
|
| 1097 |
+
|
| 1098 |
+
|
| 1099 |
+
# Private on purpose, the public class will add the deprecation warnings.
|
| 1100 |
+
class _AutoModelWithLMHead(_BaseAutoModelClass):
|
| 1101 |
+
_model_mapping = MODEL_WITH_LM_HEAD_MAPPING
|
| 1102 |
+
|
| 1103 |
+
|
| 1104 |
+
_AutoModelWithLMHead = auto_class_update(_AutoModelWithLMHead, head_doc="language modeling")
|
| 1105 |
+
|
| 1106 |
+
|
| 1107 |
+
class AutoModelForCausalLM(_BaseAutoModelClass):
|
| 1108 |
+
_model_mapping = MODEL_FOR_CAUSAL_LM_MAPPING
|
| 1109 |
+
|
| 1110 |
+
|
| 1111 |
+
AutoModelForCausalLM = auto_class_update(AutoModelForCausalLM, head_doc="causal language modeling")
|
| 1112 |
+
|
| 1113 |
+
|
| 1114 |
+
class AutoModelForMaskedLM(_BaseAutoModelClass):
|
| 1115 |
+
_model_mapping = MODEL_FOR_MASKED_LM_MAPPING
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
AutoModelForMaskedLM = auto_class_update(AutoModelForMaskedLM, head_doc="masked language modeling")
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
class AutoModelForSeq2SeqLM(_BaseAutoModelClass):
|
| 1122 |
+
_model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
|
| 1123 |
+
|
| 1124 |
+
|
| 1125 |
+
AutoModelForSeq2SeqLM = auto_class_update(
|
| 1126 |
+
AutoModelForSeq2SeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base"
|
| 1127 |
+
)
|
| 1128 |
+
|
| 1129 |
+
|
| 1130 |
+
class AutoModelForSequenceClassification(_BaseAutoModelClass):
|
| 1131 |
+
_model_mapping = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
|
| 1132 |
+
|
| 1133 |
+
|
| 1134 |
+
AutoModelForSequenceClassification = auto_class_update(
|
| 1135 |
+
AutoModelForSequenceClassification, head_doc="sequence classification"
|
| 1136 |
+
)
|
| 1137 |
+
|
| 1138 |
+
|
| 1139 |
+
class AutoModelForQuestionAnswering(_BaseAutoModelClass):
|
| 1140 |
+
_model_mapping = MODEL_FOR_QUESTION_ANSWERING_MAPPING
|
| 1141 |
+
|
| 1142 |
+
|
| 1143 |
+
AutoModelForQuestionAnswering = auto_class_update(AutoModelForQuestionAnswering, head_doc="question answering")
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
class AutoModelForTableQuestionAnswering(_BaseAutoModelClass):
|
| 1147 |
+
_model_mapping = MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING
|
| 1148 |
+
|
| 1149 |
+
|
| 1150 |
+
AutoModelForTableQuestionAnswering = auto_class_update(
|
| 1151 |
+
AutoModelForTableQuestionAnswering,
|
| 1152 |
+
head_doc="table question answering",
|
| 1153 |
+
checkpoint_for_example="google/tapas-base-finetuned-wtq",
|
| 1154 |
+
)
|
| 1155 |
+
|
| 1156 |
+
|
| 1157 |
+
class AutoModelForVisualQuestionAnswering(_BaseAutoModelClass):
|
| 1158 |
+
_model_mapping = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING
|
| 1159 |
+
|
| 1160 |
+
|
| 1161 |
+
AutoModelForVisualQuestionAnswering = auto_class_update(
|
| 1162 |
+
AutoModelForVisualQuestionAnswering,
|
| 1163 |
+
head_doc="visual question answering",
|
| 1164 |
+
checkpoint_for_example="dandelin/vilt-b32-finetuned-vqa",
|
| 1165 |
+
)
|
| 1166 |
+
|
| 1167 |
+
|
| 1168 |
+
class AutoModelForDocumentQuestionAnswering(_BaseAutoModelClass):
|
| 1169 |
+
_model_mapping = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
|
| 1170 |
+
|
| 1171 |
+
|
| 1172 |
+
AutoModelForDocumentQuestionAnswering = auto_class_update(
|
| 1173 |
+
AutoModelForDocumentQuestionAnswering,
|
| 1174 |
+
head_doc="document question answering",
|
| 1175 |
+
checkpoint_for_example='impira/layoutlm-document-qa", revision="52e01b3',
|
| 1176 |
+
)
|
| 1177 |
+
|
| 1178 |
+
|
| 1179 |
+
class AutoModelForTokenClassification(_BaseAutoModelClass):
|
| 1180 |
+
_model_mapping = MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
|
| 1181 |
+
|
| 1182 |
+
|
| 1183 |
+
AutoModelForTokenClassification = auto_class_update(AutoModelForTokenClassification, head_doc="token classification")
|
| 1184 |
+
|
| 1185 |
+
|
| 1186 |
+
class AutoModelForMultipleChoice(_BaseAutoModelClass):
|
| 1187 |
+
_model_mapping = MODEL_FOR_MULTIPLE_CHOICE_MAPPING
|
| 1188 |
+
|
| 1189 |
+
|
| 1190 |
+
AutoModelForMultipleChoice = auto_class_update(AutoModelForMultipleChoice, head_doc="multiple choice")
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
class AutoModelForNextSentencePrediction(_BaseAutoModelClass):
|
| 1194 |
+
_model_mapping = MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
|
| 1195 |
+
|
| 1196 |
+
|
| 1197 |
+
AutoModelForNextSentencePrediction = auto_class_update(
|
| 1198 |
+
AutoModelForNextSentencePrediction, head_doc="next sentence prediction"
|
| 1199 |
+
)
|
| 1200 |
+
|
| 1201 |
+
|
| 1202 |
+
class AutoModelForImageClassification(_BaseAutoModelClass):
|
| 1203 |
+
_model_mapping = MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
|
| 1204 |
+
|
| 1205 |
+
|
| 1206 |
+
AutoModelForImageClassification = auto_class_update(AutoModelForImageClassification, head_doc="image classification")
|
| 1207 |
+
|
| 1208 |
+
|
| 1209 |
+
class AutoModelForZeroShotImageClassification(_BaseAutoModelClass):
|
| 1210 |
+
_model_mapping = MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
|
| 1211 |
+
|
| 1212 |
+
|
| 1213 |
+
AutoModelForZeroShotImageClassification = auto_class_update(
|
| 1214 |
+
AutoModelForZeroShotImageClassification, head_doc="zero-shot image classification"
|
| 1215 |
+
)
|
| 1216 |
+
|
| 1217 |
+
|
| 1218 |
+
class AutoModelForImageSegmentation(_BaseAutoModelClass):
|
| 1219 |
+
_model_mapping = MODEL_FOR_IMAGE_SEGMENTATION_MAPPING
|
| 1220 |
+
|
| 1221 |
+
|
| 1222 |
+
AutoModelForImageSegmentation = auto_class_update(AutoModelForImageSegmentation, head_doc="image segmentation")
|
| 1223 |
+
|
| 1224 |
+
|
| 1225 |
+
class AutoModelForSemanticSegmentation(_BaseAutoModelClass):
|
| 1226 |
+
_model_mapping = MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
|
| 1227 |
+
|
| 1228 |
+
|
| 1229 |
+
AutoModelForSemanticSegmentation = auto_class_update(
|
| 1230 |
+
AutoModelForSemanticSegmentation, head_doc="semantic segmentation"
|
| 1231 |
+
)
|
| 1232 |
+
|
| 1233 |
+
|
| 1234 |
+
class AutoModelForUniversalSegmentation(_BaseAutoModelClass):
|
| 1235 |
+
_model_mapping = MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING
|
| 1236 |
+
|
| 1237 |
+
|
| 1238 |
+
AutoModelForUniversalSegmentation = auto_class_update(
|
| 1239 |
+
AutoModelForUniversalSegmentation, head_doc="universal image segmentation"
|
| 1240 |
+
)
|
| 1241 |
+
|
| 1242 |
+
|
| 1243 |
+
class AutoModelForInstanceSegmentation(_BaseAutoModelClass):
|
| 1244 |
+
_model_mapping = MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING
|
| 1245 |
+
|
| 1246 |
+
|
| 1247 |
+
AutoModelForInstanceSegmentation = auto_class_update(
|
| 1248 |
+
AutoModelForInstanceSegmentation, head_doc="instance segmentation"
|
| 1249 |
+
)
|
| 1250 |
+
|
| 1251 |
+
|
| 1252 |
+
class AutoModelForObjectDetection(_BaseAutoModelClass):
|
| 1253 |
+
_model_mapping = MODEL_FOR_OBJECT_DETECTION_MAPPING
|
| 1254 |
+
|
| 1255 |
+
|
| 1256 |
+
AutoModelForObjectDetection = auto_class_update(AutoModelForObjectDetection, head_doc="object detection")
|
| 1257 |
+
|
| 1258 |
+
|
| 1259 |
+
class AutoModelForZeroShotObjectDetection(_BaseAutoModelClass):
|
| 1260 |
+
_model_mapping = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING
|
| 1261 |
+
|
| 1262 |
+
|
| 1263 |
+
AutoModelForZeroShotObjectDetection = auto_class_update(
|
| 1264 |
+
AutoModelForZeroShotObjectDetection, head_doc="zero-shot object detection"
|
| 1265 |
+
)
|
| 1266 |
+
|
| 1267 |
+
|
| 1268 |
+
class AutoModelForDepthEstimation(_BaseAutoModelClass):
|
| 1269 |
+
_model_mapping = MODEL_FOR_DEPTH_ESTIMATION_MAPPING
|
| 1270 |
+
|
| 1271 |
+
|
| 1272 |
+
AutoModelForDepthEstimation = auto_class_update(AutoModelForDepthEstimation, head_doc="depth estimation")
|
| 1273 |
+
|
| 1274 |
+
|
| 1275 |
+
class AutoModelForVideoClassification(_BaseAutoModelClass):
|
| 1276 |
+
_model_mapping = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING
|
| 1277 |
+
|
| 1278 |
+
|
| 1279 |
+
AutoModelForVideoClassification = auto_class_update(AutoModelForVideoClassification, head_doc="video classification")
|
| 1280 |
+
|
| 1281 |
+
|
| 1282 |
+
class AutoModelForVision2Seq(_BaseAutoModelClass):
|
| 1283 |
+
_model_mapping = MODEL_FOR_VISION_2_SEQ_MAPPING
|
| 1284 |
+
|
| 1285 |
+
|
| 1286 |
+
AutoModelForVision2Seq = auto_class_update(AutoModelForVision2Seq, head_doc="vision-to-text modeling")
|
| 1287 |
+
|
| 1288 |
+
|
| 1289 |
+
class AutoModelForAudioClassification(_BaseAutoModelClass):
|
| 1290 |
+
_model_mapping = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
|
| 1291 |
+
|
| 1292 |
+
|
| 1293 |
+
AutoModelForAudioClassification = auto_class_update(AutoModelForAudioClassification, head_doc="audio classification")
|
| 1294 |
+
|
| 1295 |
+
|
| 1296 |
+
class AutoModelForCTC(_BaseAutoModelClass):
|
| 1297 |
+
_model_mapping = MODEL_FOR_CTC_MAPPING
|
| 1298 |
+
|
| 1299 |
+
|
| 1300 |
+
AutoModelForCTC = auto_class_update(AutoModelForCTC, head_doc="connectionist temporal classification")
|
| 1301 |
+
|
| 1302 |
+
|
| 1303 |
+
class AutoModelForSpeechSeq2Seq(_BaseAutoModelClass):
|
| 1304 |
+
_model_mapping = MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
|
| 1305 |
+
|
| 1306 |
+
|
| 1307 |
+
AutoModelForSpeechSeq2Seq = auto_class_update(
|
| 1308 |
+
AutoModelForSpeechSeq2Seq, head_doc="sequence-to-sequence speech-to-text modeling"
|
| 1309 |
+
)
|
| 1310 |
+
|
| 1311 |
+
|
| 1312 |
+
class AutoModelForAudioFrameClassification(_BaseAutoModelClass):
|
| 1313 |
+
_model_mapping = MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING
|
| 1314 |
+
|
| 1315 |
+
|
| 1316 |
+
AutoModelForAudioFrameClassification = auto_class_update(
|
| 1317 |
+
AutoModelForAudioFrameClassification, head_doc="audio frame (token) classification"
|
| 1318 |
+
)
|
| 1319 |
+
|
| 1320 |
+
|
| 1321 |
+
class AutoModelForAudioXVector(_BaseAutoModelClass):
|
| 1322 |
+
_model_mapping = MODEL_FOR_AUDIO_XVECTOR_MAPPING
|
| 1323 |
+
|
| 1324 |
+
|
| 1325 |
+
class AutoBackbone(_BaseAutoModelClass):
|
| 1326 |
+
_model_mapping = MODEL_FOR_BACKBONE_MAPPING
|
| 1327 |
+
|
| 1328 |
+
|
| 1329 |
+
AutoModelForAudioXVector = auto_class_update(AutoModelForAudioXVector, head_doc="audio retrieval via x-vector")
|
| 1330 |
+
|
| 1331 |
+
|
| 1332 |
+
class AutoModelForMaskedImageModeling(_BaseAutoModelClass):
|
| 1333 |
+
_model_mapping = MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING
|
| 1334 |
+
|
| 1335 |
+
|
| 1336 |
+
AutoModelForMaskedImageModeling = auto_class_update(AutoModelForMaskedImageModeling, head_doc="masked image modeling")
|
| 1337 |
+
|
| 1338 |
+
|
| 1339 |
+
class AutoModelWithLMHead(_AutoModelWithLMHead):
|
| 1340 |
+
@classmethod
|
| 1341 |
+
def from_config(cls, config):
|
| 1342 |
+
warnings.warn(
|
| 1343 |
+
"The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use "
|
| 1344 |
+
"`AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and "
|
| 1345 |
+
"`AutoModelForSeq2SeqLM` for encoder-decoder models.",
|
| 1346 |
+
FutureWarning,
|
| 1347 |
+
)
|
| 1348 |
+
return super().from_config(config)
|
| 1349 |
+
|
| 1350 |
+
@classmethod
|
| 1351 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 1352 |
+
warnings.warn(
|
| 1353 |
+
"The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use "
|
| 1354 |
+
"`AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and "
|
| 1355 |
+
"`AutoModelForSeq2SeqLM` for encoder-decoder models.",
|
| 1356 |
+
FutureWarning,
|
| 1357 |
+
)
|
| 1358 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/modeling_flax_auto.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google Flax Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Auto Model class."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
|
| 20 |
+
from ...utils import logging
|
| 21 |
+
from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
|
| 22 |
+
from .configuration_auto import CONFIG_MAPPING_NAMES
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
FLAX_MODEL_MAPPING_NAMES = OrderedDict(
|
| 29 |
+
[
|
| 30 |
+
# Base model mapping
|
| 31 |
+
("albert", "FlaxAlbertModel"),
|
| 32 |
+
("bart", "FlaxBartModel"),
|
| 33 |
+
("beit", "FlaxBeitModel"),
|
| 34 |
+
("bert", "FlaxBertModel"),
|
| 35 |
+
("big_bird", "FlaxBigBirdModel"),
|
| 36 |
+
("blenderbot", "FlaxBlenderbotModel"),
|
| 37 |
+
("blenderbot-small", "FlaxBlenderbotSmallModel"),
|
| 38 |
+
("clip", "FlaxCLIPModel"),
|
| 39 |
+
("distilbert", "FlaxDistilBertModel"),
|
| 40 |
+
("electra", "FlaxElectraModel"),
|
| 41 |
+
("gpt-sw3", "FlaxGPT2Model"),
|
| 42 |
+
("gpt2", "FlaxGPT2Model"),
|
| 43 |
+
("gpt_neo", "FlaxGPTNeoModel"),
|
| 44 |
+
("gptj", "FlaxGPTJModel"),
|
| 45 |
+
("longt5", "FlaxLongT5Model"),
|
| 46 |
+
("marian", "FlaxMarianModel"),
|
| 47 |
+
("mbart", "FlaxMBartModel"),
|
| 48 |
+
("mt5", "FlaxMT5Model"),
|
| 49 |
+
("opt", "FlaxOPTModel"),
|
| 50 |
+
("pegasus", "FlaxPegasusModel"),
|
| 51 |
+
("regnet", "FlaxRegNetModel"),
|
| 52 |
+
("resnet", "FlaxResNetModel"),
|
| 53 |
+
("roberta", "FlaxRobertaModel"),
|
| 54 |
+
("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"),
|
| 55 |
+
("roformer", "FlaxRoFormerModel"),
|
| 56 |
+
("t5", "FlaxT5Model"),
|
| 57 |
+
("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"),
|
| 58 |
+
("vit", "FlaxViTModel"),
|
| 59 |
+
("wav2vec2", "FlaxWav2Vec2Model"),
|
| 60 |
+
("whisper", "FlaxWhisperModel"),
|
| 61 |
+
("xglm", "FlaxXGLMModel"),
|
| 62 |
+
("xlm-roberta", "FlaxXLMRobertaModel"),
|
| 63 |
+
]
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES = OrderedDict(
|
| 67 |
+
[
|
| 68 |
+
# Model for pre-training mapping
|
| 69 |
+
("albert", "FlaxAlbertForPreTraining"),
|
| 70 |
+
("bart", "FlaxBartForConditionalGeneration"),
|
| 71 |
+
("bert", "FlaxBertForPreTraining"),
|
| 72 |
+
("big_bird", "FlaxBigBirdForPreTraining"),
|
| 73 |
+
("electra", "FlaxElectraForPreTraining"),
|
| 74 |
+
("longt5", "FlaxLongT5ForConditionalGeneration"),
|
| 75 |
+
("mbart", "FlaxMBartForConditionalGeneration"),
|
| 76 |
+
("mt5", "FlaxMT5ForConditionalGeneration"),
|
| 77 |
+
("roberta", "FlaxRobertaForMaskedLM"),
|
| 78 |
+
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"),
|
| 79 |
+
("roformer", "FlaxRoFormerForMaskedLM"),
|
| 80 |
+
("t5", "FlaxT5ForConditionalGeneration"),
|
| 81 |
+
("wav2vec2", "FlaxWav2Vec2ForPreTraining"),
|
| 82 |
+
("whisper", "FlaxWhisperForConditionalGeneration"),
|
| 83 |
+
("xlm-roberta", "FlaxXLMRobertaForMaskedLM"),
|
| 84 |
+
]
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES = OrderedDict(
|
| 88 |
+
[
|
| 89 |
+
# Model for Masked LM mapping
|
| 90 |
+
("albert", "FlaxAlbertForMaskedLM"),
|
| 91 |
+
("bart", "FlaxBartForConditionalGeneration"),
|
| 92 |
+
("bert", "FlaxBertForMaskedLM"),
|
| 93 |
+
("big_bird", "FlaxBigBirdForMaskedLM"),
|
| 94 |
+
("distilbert", "FlaxDistilBertForMaskedLM"),
|
| 95 |
+
("electra", "FlaxElectraForMaskedLM"),
|
| 96 |
+
("mbart", "FlaxMBartForConditionalGeneration"),
|
| 97 |
+
("roberta", "FlaxRobertaForMaskedLM"),
|
| 98 |
+
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"),
|
| 99 |
+
("roformer", "FlaxRoFormerForMaskedLM"),
|
| 100 |
+
("xlm-roberta", "FlaxXLMRobertaForMaskedLM"),
|
| 101 |
+
]
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
|
| 105 |
+
[
|
| 106 |
+
# Model for Seq2Seq Causal LM mapping
|
| 107 |
+
("bart", "FlaxBartForConditionalGeneration"),
|
| 108 |
+
("blenderbot", "FlaxBlenderbotForConditionalGeneration"),
|
| 109 |
+
("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"),
|
| 110 |
+
("encoder-decoder", "FlaxEncoderDecoderModel"),
|
| 111 |
+
("longt5", "FlaxLongT5ForConditionalGeneration"),
|
| 112 |
+
("marian", "FlaxMarianMTModel"),
|
| 113 |
+
("mbart", "FlaxMBartForConditionalGeneration"),
|
| 114 |
+
("mt5", "FlaxMT5ForConditionalGeneration"),
|
| 115 |
+
("pegasus", "FlaxPegasusForConditionalGeneration"),
|
| 116 |
+
("t5", "FlaxT5ForConditionalGeneration"),
|
| 117 |
+
]
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 121 |
+
[
|
| 122 |
+
# Model for Image-classsification
|
| 123 |
+
("beit", "FlaxBeitForImageClassification"),
|
| 124 |
+
("regnet", "FlaxRegNetForImageClassification"),
|
| 125 |
+
("resnet", "FlaxResNetForImageClassification"),
|
| 126 |
+
("vit", "FlaxViTForImageClassification"),
|
| 127 |
+
]
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = OrderedDict(
|
| 131 |
+
[
|
| 132 |
+
("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"),
|
| 133 |
+
]
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
|
| 137 |
+
[
|
| 138 |
+
# Model for Causal LM mapping
|
| 139 |
+
("bart", "FlaxBartForCausalLM"),
|
| 140 |
+
("bert", "FlaxBertForCausalLM"),
|
| 141 |
+
("big_bird", "FlaxBigBirdForCausalLM"),
|
| 142 |
+
("electra", "FlaxElectraForCausalLM"),
|
| 143 |
+
("gpt-sw3", "FlaxGPT2LMHeadModel"),
|
| 144 |
+
("gpt2", "FlaxGPT2LMHeadModel"),
|
| 145 |
+
("gpt_neo", "FlaxGPTNeoForCausalLM"),
|
| 146 |
+
("gptj", "FlaxGPTJForCausalLM"),
|
| 147 |
+
("opt", "FlaxOPTForCausalLM"),
|
| 148 |
+
("roberta", "FlaxRobertaForCausalLM"),
|
| 149 |
+
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"),
|
| 150 |
+
("xglm", "FlaxXGLMForCausalLM"),
|
| 151 |
+
("xlm-roberta", "FlaxXLMRobertaForCausalLM"),
|
| 152 |
+
]
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 156 |
+
[
|
| 157 |
+
# Model for Sequence Classification mapping
|
| 158 |
+
("albert", "FlaxAlbertForSequenceClassification"),
|
| 159 |
+
("bart", "FlaxBartForSequenceClassification"),
|
| 160 |
+
("bert", "FlaxBertForSequenceClassification"),
|
| 161 |
+
("big_bird", "FlaxBigBirdForSequenceClassification"),
|
| 162 |
+
("distilbert", "FlaxDistilBertForSequenceClassification"),
|
| 163 |
+
("electra", "FlaxElectraForSequenceClassification"),
|
| 164 |
+
("mbart", "FlaxMBartForSequenceClassification"),
|
| 165 |
+
("roberta", "FlaxRobertaForSequenceClassification"),
|
| 166 |
+
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"),
|
| 167 |
+
("roformer", "FlaxRoFormerForSequenceClassification"),
|
| 168 |
+
("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"),
|
| 169 |
+
]
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
|
| 173 |
+
[
|
| 174 |
+
# Model for Question Answering mapping
|
| 175 |
+
("albert", "FlaxAlbertForQuestionAnswering"),
|
| 176 |
+
("bart", "FlaxBartForQuestionAnswering"),
|
| 177 |
+
("bert", "FlaxBertForQuestionAnswering"),
|
| 178 |
+
("big_bird", "FlaxBigBirdForQuestionAnswering"),
|
| 179 |
+
("distilbert", "FlaxDistilBertForQuestionAnswering"),
|
| 180 |
+
("electra", "FlaxElectraForQuestionAnswering"),
|
| 181 |
+
("mbart", "FlaxMBartForQuestionAnswering"),
|
| 182 |
+
("roberta", "FlaxRobertaForQuestionAnswering"),
|
| 183 |
+
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"),
|
| 184 |
+
("roformer", "FlaxRoFormerForQuestionAnswering"),
|
| 185 |
+
("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"),
|
| 186 |
+
]
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 190 |
+
[
|
| 191 |
+
# Model for Token Classification mapping
|
| 192 |
+
("albert", "FlaxAlbertForTokenClassification"),
|
| 193 |
+
("bert", "FlaxBertForTokenClassification"),
|
| 194 |
+
("big_bird", "FlaxBigBirdForTokenClassification"),
|
| 195 |
+
("distilbert", "FlaxDistilBertForTokenClassification"),
|
| 196 |
+
("electra", "FlaxElectraForTokenClassification"),
|
| 197 |
+
("roberta", "FlaxRobertaForTokenClassification"),
|
| 198 |
+
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"),
|
| 199 |
+
("roformer", "FlaxRoFormerForTokenClassification"),
|
| 200 |
+
("xlm-roberta", "FlaxXLMRobertaForTokenClassification"),
|
| 201 |
+
]
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES = OrderedDict(
|
| 205 |
+
[
|
| 206 |
+
# Model for Multiple Choice mapping
|
| 207 |
+
("albert", "FlaxAlbertForMultipleChoice"),
|
| 208 |
+
("bert", "FlaxBertForMultipleChoice"),
|
| 209 |
+
("big_bird", "FlaxBigBirdForMultipleChoice"),
|
| 210 |
+
("distilbert", "FlaxDistilBertForMultipleChoice"),
|
| 211 |
+
("electra", "FlaxElectraForMultipleChoice"),
|
| 212 |
+
("roberta", "FlaxRobertaForMultipleChoice"),
|
| 213 |
+
("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"),
|
| 214 |
+
("roformer", "FlaxRoFormerForMultipleChoice"),
|
| 215 |
+
("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"),
|
| 216 |
+
]
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES = OrderedDict(
|
| 220 |
+
[
|
| 221 |
+
("bert", "FlaxBertForNextSentencePrediction"),
|
| 222 |
+
]
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = OrderedDict(
|
| 226 |
+
[
|
| 227 |
+
("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"),
|
| 228 |
+
("whisper", "FlaxWhisperForConditionalGeneration"),
|
| 229 |
+
]
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 233 |
+
[
|
| 234 |
+
("whisper", "FlaxWhisperForAudioClassification"),
|
| 235 |
+
]
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
FLAX_MODEL_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES)
|
| 239 |
+
FLAX_MODEL_FOR_PRETRAINING_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES)
|
| 240 |
+
FLAX_MODEL_FOR_MASKED_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES)
|
| 241 |
+
FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING = _LazyAutoMapping(
|
| 242 |
+
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
|
| 243 |
+
)
|
| 244 |
+
FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 245 |
+
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
|
| 246 |
+
)
|
| 247 |
+
FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
|
| 248 |
+
FLAX_MODEL_FOR_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
|
| 249 |
+
FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 250 |
+
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
|
| 251 |
+
)
|
| 252 |
+
FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
|
| 253 |
+
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
|
| 254 |
+
)
|
| 255 |
+
FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 256 |
+
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
|
| 257 |
+
)
|
| 258 |
+
FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING = _LazyAutoMapping(
|
| 259 |
+
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES
|
| 260 |
+
)
|
| 261 |
+
FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING = _LazyAutoMapping(
|
| 262 |
+
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
|
| 263 |
+
)
|
| 264 |
+
FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING = _LazyAutoMapping(
|
| 265 |
+
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class FlaxAutoModel(_BaseAutoModelClass):
|
| 270 |
+
_model_mapping = FLAX_MODEL_MAPPING
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
FlaxAutoModel = auto_class_update(FlaxAutoModel)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class FlaxAutoModelForPreTraining(_BaseAutoModelClass):
|
| 277 |
+
_model_mapping = FLAX_MODEL_FOR_PRETRAINING_MAPPING
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
FlaxAutoModelForPreTraining = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining")
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class FlaxAutoModelForCausalLM(_BaseAutoModelClass):
|
| 284 |
+
_model_mapping = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
FlaxAutoModelForCausalLM = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling")
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class FlaxAutoModelForMaskedLM(_BaseAutoModelClass):
|
| 291 |
+
_model_mapping = FLAX_MODEL_FOR_MASKED_LM_MAPPING
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
FlaxAutoModelForMaskedLM = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling")
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class FlaxAutoModelForSeq2SeqLM(_BaseAutoModelClass):
|
| 298 |
+
_model_mapping = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
FlaxAutoModelForSeq2SeqLM = auto_class_update(
|
| 302 |
+
FlaxAutoModelForSeq2SeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base"
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
class FlaxAutoModelForSequenceClassification(_BaseAutoModelClass):
|
| 307 |
+
_model_mapping = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
FlaxAutoModelForSequenceClassification = auto_class_update(
|
| 311 |
+
FlaxAutoModelForSequenceClassification, head_doc="sequence classification"
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
class FlaxAutoModelForQuestionAnswering(_BaseAutoModelClass):
|
| 316 |
+
_model_mapping = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
FlaxAutoModelForQuestionAnswering = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering")
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
class FlaxAutoModelForTokenClassification(_BaseAutoModelClass):
|
| 323 |
+
_model_mapping = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
FlaxAutoModelForTokenClassification = auto_class_update(
|
| 327 |
+
FlaxAutoModelForTokenClassification, head_doc="token classification"
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class FlaxAutoModelForMultipleChoice(_BaseAutoModelClass):
|
| 332 |
+
_model_mapping = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
FlaxAutoModelForMultipleChoice = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice")
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class FlaxAutoModelForNextSentencePrediction(_BaseAutoModelClass):
|
| 339 |
+
_model_mapping = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
FlaxAutoModelForNextSentencePrediction = auto_class_update(
|
| 343 |
+
FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction"
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
class FlaxAutoModelForImageClassification(_BaseAutoModelClass):
|
| 348 |
+
_model_mapping = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
FlaxAutoModelForImageClassification = auto_class_update(
|
| 352 |
+
FlaxAutoModelForImageClassification, head_doc="image classification"
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class FlaxAutoModelForVision2Seq(_BaseAutoModelClass):
|
| 357 |
+
_model_mapping = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
FlaxAutoModelForVision2Seq = auto_class_update(FlaxAutoModelForVision2Seq, head_doc="vision-to-text modeling")
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class FlaxAutoModelForSpeechSeq2Seq(_BaseAutoModelClass):
|
| 364 |
+
_model_mapping = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
FlaxAutoModelForSpeechSeq2Seq = auto_class_update(
|
| 368 |
+
FlaxAutoModelForSpeechSeq2Seq, head_doc="sequence-to-sequence speech-to-text modeling"
|
| 369 |
+
)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/modeling_tf_auto.py
ADDED
|
@@ -0,0 +1,668 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Auto Model class."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import warnings
|
| 19 |
+
from collections import OrderedDict
|
| 20 |
+
|
| 21 |
+
from ...utils import logging
|
| 22 |
+
from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
|
| 23 |
+
from .configuration_auto import CONFIG_MAPPING_NAMES
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
TF_MODEL_MAPPING_NAMES = OrderedDict(
|
| 30 |
+
[
|
| 31 |
+
# Base model mapping
|
| 32 |
+
("albert", "TFAlbertModel"),
|
| 33 |
+
("bart", "TFBartModel"),
|
| 34 |
+
("bert", "TFBertModel"),
|
| 35 |
+
("blenderbot", "TFBlenderbotModel"),
|
| 36 |
+
("blenderbot-small", "TFBlenderbotSmallModel"),
|
| 37 |
+
("blip", "TFBlipModel"),
|
| 38 |
+
("camembert", "TFCamembertModel"),
|
| 39 |
+
("clip", "TFCLIPModel"),
|
| 40 |
+
("convbert", "TFConvBertModel"),
|
| 41 |
+
("convnext", "TFConvNextModel"),
|
| 42 |
+
("ctrl", "TFCTRLModel"),
|
| 43 |
+
("cvt", "TFCvtModel"),
|
| 44 |
+
("data2vec-vision", "TFData2VecVisionModel"),
|
| 45 |
+
("deberta", "TFDebertaModel"),
|
| 46 |
+
("deberta-v2", "TFDebertaV2Model"),
|
| 47 |
+
("deit", "TFDeiTModel"),
|
| 48 |
+
("distilbert", "TFDistilBertModel"),
|
| 49 |
+
("dpr", "TFDPRQuestionEncoder"),
|
| 50 |
+
("electra", "TFElectraModel"),
|
| 51 |
+
("esm", "TFEsmModel"),
|
| 52 |
+
("flaubert", "TFFlaubertModel"),
|
| 53 |
+
("funnel", ("TFFunnelModel", "TFFunnelBaseModel")),
|
| 54 |
+
("gpt-sw3", "TFGPT2Model"),
|
| 55 |
+
("gpt2", "TFGPT2Model"),
|
| 56 |
+
("gptj", "TFGPTJModel"),
|
| 57 |
+
("groupvit", "TFGroupViTModel"),
|
| 58 |
+
("hubert", "TFHubertModel"),
|
| 59 |
+
("layoutlm", "TFLayoutLMModel"),
|
| 60 |
+
("layoutlmv3", "TFLayoutLMv3Model"),
|
| 61 |
+
("led", "TFLEDModel"),
|
| 62 |
+
("longformer", "TFLongformerModel"),
|
| 63 |
+
("lxmert", "TFLxmertModel"),
|
| 64 |
+
("marian", "TFMarianModel"),
|
| 65 |
+
("mbart", "TFMBartModel"),
|
| 66 |
+
("mobilebert", "TFMobileBertModel"),
|
| 67 |
+
("mobilevit", "TFMobileViTModel"),
|
| 68 |
+
("mpnet", "TFMPNetModel"),
|
| 69 |
+
("mt5", "TFMT5Model"),
|
| 70 |
+
("openai-gpt", "TFOpenAIGPTModel"),
|
| 71 |
+
("opt", "TFOPTModel"),
|
| 72 |
+
("pegasus", "TFPegasusModel"),
|
| 73 |
+
("regnet", "TFRegNetModel"),
|
| 74 |
+
("rembert", "TFRemBertModel"),
|
| 75 |
+
("resnet", "TFResNetModel"),
|
| 76 |
+
("roberta", "TFRobertaModel"),
|
| 77 |
+
("roberta-prelayernorm", "TFRobertaPreLayerNormModel"),
|
| 78 |
+
("roformer", "TFRoFormerModel"),
|
| 79 |
+
("segformer", "TFSegformerModel"),
|
| 80 |
+
("speech_to_text", "TFSpeech2TextModel"),
|
| 81 |
+
("swin", "TFSwinModel"),
|
| 82 |
+
("t5", "TFT5Model"),
|
| 83 |
+
("tapas", "TFTapasModel"),
|
| 84 |
+
("transfo-xl", "TFTransfoXLModel"),
|
| 85 |
+
("vision-text-dual-encoder", "TFVisionTextDualEncoderModel"),
|
| 86 |
+
("vit", "TFViTModel"),
|
| 87 |
+
("vit_mae", "TFViTMAEModel"),
|
| 88 |
+
("wav2vec2", "TFWav2Vec2Model"),
|
| 89 |
+
("whisper", "TFWhisperModel"),
|
| 90 |
+
("xglm", "TFXGLMModel"),
|
| 91 |
+
("xlm", "TFXLMModel"),
|
| 92 |
+
("xlm-roberta", "TFXLMRobertaModel"),
|
| 93 |
+
("xlnet", "TFXLNetModel"),
|
| 94 |
+
]
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
TF_MODEL_FOR_PRETRAINING_MAPPING_NAMES = OrderedDict(
|
| 98 |
+
[
|
| 99 |
+
# Model for pre-training mapping
|
| 100 |
+
("albert", "TFAlbertForPreTraining"),
|
| 101 |
+
("bart", "TFBartForConditionalGeneration"),
|
| 102 |
+
("bert", "TFBertForPreTraining"),
|
| 103 |
+
("camembert", "TFCamembertForMaskedLM"),
|
| 104 |
+
("ctrl", "TFCTRLLMHeadModel"),
|
| 105 |
+
("distilbert", "TFDistilBertForMaskedLM"),
|
| 106 |
+
("electra", "TFElectraForPreTraining"),
|
| 107 |
+
("flaubert", "TFFlaubertWithLMHeadModel"),
|
| 108 |
+
("funnel", "TFFunnelForPreTraining"),
|
| 109 |
+
("gpt-sw3", "TFGPT2LMHeadModel"),
|
| 110 |
+
("gpt2", "TFGPT2LMHeadModel"),
|
| 111 |
+
("layoutlm", "TFLayoutLMForMaskedLM"),
|
| 112 |
+
("lxmert", "TFLxmertForPreTraining"),
|
| 113 |
+
("mobilebert", "TFMobileBertForPreTraining"),
|
| 114 |
+
("mpnet", "TFMPNetForMaskedLM"),
|
| 115 |
+
("openai-gpt", "TFOpenAIGPTLMHeadModel"),
|
| 116 |
+
("roberta", "TFRobertaForMaskedLM"),
|
| 117 |
+
("roberta-prelayernorm", "TFRobertaPreLayerNormForMaskedLM"),
|
| 118 |
+
("t5", "TFT5ForConditionalGeneration"),
|
| 119 |
+
("tapas", "TFTapasForMaskedLM"),
|
| 120 |
+
("transfo-xl", "TFTransfoXLLMHeadModel"),
|
| 121 |
+
("vit_mae", "TFViTMAEForPreTraining"),
|
| 122 |
+
("xlm", "TFXLMWithLMHeadModel"),
|
| 123 |
+
("xlm-roberta", "TFXLMRobertaForMaskedLM"),
|
| 124 |
+
("xlnet", "TFXLNetLMHeadModel"),
|
| 125 |
+
]
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
TF_MODEL_WITH_LM_HEAD_MAPPING_NAMES = OrderedDict(
|
| 129 |
+
[
|
| 130 |
+
# Model with LM heads mapping
|
| 131 |
+
("albert", "TFAlbertForMaskedLM"),
|
| 132 |
+
("bart", "TFBartForConditionalGeneration"),
|
| 133 |
+
("bert", "TFBertForMaskedLM"),
|
| 134 |
+
("camembert", "TFCamembertForMaskedLM"),
|
| 135 |
+
("convbert", "TFConvBertForMaskedLM"),
|
| 136 |
+
("ctrl", "TFCTRLLMHeadModel"),
|
| 137 |
+
("distilbert", "TFDistilBertForMaskedLM"),
|
| 138 |
+
("electra", "TFElectraForMaskedLM"),
|
| 139 |
+
("esm", "TFEsmForMaskedLM"),
|
| 140 |
+
("flaubert", "TFFlaubertWithLMHeadModel"),
|
| 141 |
+
("funnel", "TFFunnelForMaskedLM"),
|
| 142 |
+
("gpt-sw3", "TFGPT2LMHeadModel"),
|
| 143 |
+
("gpt2", "TFGPT2LMHeadModel"),
|
| 144 |
+
("gptj", "TFGPTJForCausalLM"),
|
| 145 |
+
("layoutlm", "TFLayoutLMForMaskedLM"),
|
| 146 |
+
("led", "TFLEDForConditionalGeneration"),
|
| 147 |
+
("longformer", "TFLongformerForMaskedLM"),
|
| 148 |
+
("marian", "TFMarianMTModel"),
|
| 149 |
+
("mobilebert", "TFMobileBertForMaskedLM"),
|
| 150 |
+
("mpnet", "TFMPNetForMaskedLM"),
|
| 151 |
+
("openai-gpt", "TFOpenAIGPTLMHeadModel"),
|
| 152 |
+
("rembert", "TFRemBertForMaskedLM"),
|
| 153 |
+
("roberta", "TFRobertaForMaskedLM"),
|
| 154 |
+
("roberta-prelayernorm", "TFRobertaPreLayerNormForMaskedLM"),
|
| 155 |
+
("roformer", "TFRoFormerForMaskedLM"),
|
| 156 |
+
("speech_to_text", "TFSpeech2TextForConditionalGeneration"),
|
| 157 |
+
("t5", "TFT5ForConditionalGeneration"),
|
| 158 |
+
("tapas", "TFTapasForMaskedLM"),
|
| 159 |
+
("transfo-xl", "TFTransfoXLLMHeadModel"),
|
| 160 |
+
("whisper", "TFWhisperForConditionalGeneration"),
|
| 161 |
+
("xlm", "TFXLMWithLMHeadModel"),
|
| 162 |
+
("xlm-roberta", "TFXLMRobertaForMaskedLM"),
|
| 163 |
+
("xlnet", "TFXLNetLMHeadModel"),
|
| 164 |
+
]
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
TF_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
|
| 168 |
+
[
|
| 169 |
+
# Model for Causal LM mapping
|
| 170 |
+
("bert", "TFBertLMHeadModel"),
|
| 171 |
+
("camembert", "TFCamembertForCausalLM"),
|
| 172 |
+
("ctrl", "TFCTRLLMHeadModel"),
|
| 173 |
+
("gpt-sw3", "TFGPT2LMHeadModel"),
|
| 174 |
+
("gpt2", "TFGPT2LMHeadModel"),
|
| 175 |
+
("gptj", "TFGPTJForCausalLM"),
|
| 176 |
+
("openai-gpt", "TFOpenAIGPTLMHeadModel"),
|
| 177 |
+
("opt", "TFOPTForCausalLM"),
|
| 178 |
+
("rembert", "TFRemBertForCausalLM"),
|
| 179 |
+
("roberta", "TFRobertaForCausalLM"),
|
| 180 |
+
("roberta-prelayernorm", "TFRobertaPreLayerNormForCausalLM"),
|
| 181 |
+
("roformer", "TFRoFormerForCausalLM"),
|
| 182 |
+
("transfo-xl", "TFTransfoXLLMHeadModel"),
|
| 183 |
+
("xglm", "TFXGLMForCausalLM"),
|
| 184 |
+
("xlm", "TFXLMWithLMHeadModel"),
|
| 185 |
+
("xlm-roberta", "TFXLMRobertaForCausalLM"),
|
| 186 |
+
("xlnet", "TFXLNetLMHeadModel"),
|
| 187 |
+
]
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES = OrderedDict(
|
| 191 |
+
[
|
| 192 |
+
("deit", "TFDeiTForMaskedImageModeling"),
|
| 193 |
+
("swin", "TFSwinForMaskedImageModeling"),
|
| 194 |
+
]
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 198 |
+
[
|
| 199 |
+
# Model for Image-classsification
|
| 200 |
+
("convnext", "TFConvNextForImageClassification"),
|
| 201 |
+
("cvt", "TFCvtForImageClassification"),
|
| 202 |
+
("data2vec-vision", "TFData2VecVisionForImageClassification"),
|
| 203 |
+
("deit", ("TFDeiTForImageClassification", "TFDeiTForImageClassificationWithTeacher")),
|
| 204 |
+
("mobilevit", "TFMobileViTForImageClassification"),
|
| 205 |
+
("regnet", "TFRegNetForImageClassification"),
|
| 206 |
+
("resnet", "TFResNetForImageClassification"),
|
| 207 |
+
("segformer", "TFSegformerForImageClassification"),
|
| 208 |
+
("swin", "TFSwinForImageClassification"),
|
| 209 |
+
("vit", "TFViTForImageClassification"),
|
| 210 |
+
]
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 215 |
+
[
|
| 216 |
+
# Model for Zero Shot Image Classification mapping
|
| 217 |
+
("blip", "TFBlipModel"),
|
| 218 |
+
("clip", "TFCLIPModel"),
|
| 219 |
+
]
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = OrderedDict(
|
| 224 |
+
[
|
| 225 |
+
# Model for Semantic Segmentation mapping
|
| 226 |
+
("data2vec-vision", "TFData2VecVisionForSemanticSegmentation"),
|
| 227 |
+
("mobilevit", "TFMobileViTForSemanticSegmentation"),
|
| 228 |
+
("segformer", "TFSegformerForSemanticSegmentation"),
|
| 229 |
+
]
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
TF_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = OrderedDict(
|
| 233 |
+
[
|
| 234 |
+
("blip", "TFBlipForConditionalGeneration"),
|
| 235 |
+
("vision-encoder-decoder", "TFVisionEncoderDecoderModel"),
|
| 236 |
+
]
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
TF_MODEL_FOR_MASKED_LM_MAPPING_NAMES = OrderedDict(
|
| 240 |
+
[
|
| 241 |
+
# Model for Masked LM mapping
|
| 242 |
+
("albert", "TFAlbertForMaskedLM"),
|
| 243 |
+
("bert", "TFBertForMaskedLM"),
|
| 244 |
+
("camembert", "TFCamembertForMaskedLM"),
|
| 245 |
+
("convbert", "TFConvBertForMaskedLM"),
|
| 246 |
+
("deberta", "TFDebertaForMaskedLM"),
|
| 247 |
+
("deberta-v2", "TFDebertaV2ForMaskedLM"),
|
| 248 |
+
("distilbert", "TFDistilBertForMaskedLM"),
|
| 249 |
+
("electra", "TFElectraForMaskedLM"),
|
| 250 |
+
("esm", "TFEsmForMaskedLM"),
|
| 251 |
+
("flaubert", "TFFlaubertWithLMHeadModel"),
|
| 252 |
+
("funnel", "TFFunnelForMaskedLM"),
|
| 253 |
+
("layoutlm", "TFLayoutLMForMaskedLM"),
|
| 254 |
+
("longformer", "TFLongformerForMaskedLM"),
|
| 255 |
+
("mobilebert", "TFMobileBertForMaskedLM"),
|
| 256 |
+
("mpnet", "TFMPNetForMaskedLM"),
|
| 257 |
+
("rembert", "TFRemBertForMaskedLM"),
|
| 258 |
+
("roberta", "TFRobertaForMaskedLM"),
|
| 259 |
+
("roberta-prelayernorm", "TFRobertaPreLayerNormForMaskedLM"),
|
| 260 |
+
("roformer", "TFRoFormerForMaskedLM"),
|
| 261 |
+
("tapas", "TFTapasForMaskedLM"),
|
| 262 |
+
("xlm", "TFXLMWithLMHeadModel"),
|
| 263 |
+
("xlm-roberta", "TFXLMRobertaForMaskedLM"),
|
| 264 |
+
]
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = OrderedDict(
|
| 268 |
+
[
|
| 269 |
+
# Model for Seq2Seq Causal LM mapping
|
| 270 |
+
("bart", "TFBartForConditionalGeneration"),
|
| 271 |
+
("blenderbot", "TFBlenderbotForConditionalGeneration"),
|
| 272 |
+
("blenderbot-small", "TFBlenderbotSmallForConditionalGeneration"),
|
| 273 |
+
("encoder-decoder", "TFEncoderDecoderModel"),
|
| 274 |
+
("led", "TFLEDForConditionalGeneration"),
|
| 275 |
+
("marian", "TFMarianMTModel"),
|
| 276 |
+
("mbart", "TFMBartForConditionalGeneration"),
|
| 277 |
+
("mt5", "TFMT5ForConditionalGeneration"),
|
| 278 |
+
("pegasus", "TFPegasusForConditionalGeneration"),
|
| 279 |
+
("t5", "TFT5ForConditionalGeneration"),
|
| 280 |
+
]
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = OrderedDict(
|
| 284 |
+
[
|
| 285 |
+
("speech_to_text", "TFSpeech2TextForConditionalGeneration"),
|
| 286 |
+
("whisper", "TFWhisperForConditionalGeneration"),
|
| 287 |
+
]
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 291 |
+
[
|
| 292 |
+
# Model for Sequence Classification mapping
|
| 293 |
+
("albert", "TFAlbertForSequenceClassification"),
|
| 294 |
+
("bart", "TFBartForSequenceClassification"),
|
| 295 |
+
("bert", "TFBertForSequenceClassification"),
|
| 296 |
+
("camembert", "TFCamembertForSequenceClassification"),
|
| 297 |
+
("convbert", "TFConvBertForSequenceClassification"),
|
| 298 |
+
("ctrl", "TFCTRLForSequenceClassification"),
|
| 299 |
+
("deberta", "TFDebertaForSequenceClassification"),
|
| 300 |
+
("deberta-v2", "TFDebertaV2ForSequenceClassification"),
|
| 301 |
+
("distilbert", "TFDistilBertForSequenceClassification"),
|
| 302 |
+
("electra", "TFElectraForSequenceClassification"),
|
| 303 |
+
("esm", "TFEsmForSequenceClassification"),
|
| 304 |
+
("flaubert", "TFFlaubertForSequenceClassification"),
|
| 305 |
+
("funnel", "TFFunnelForSequenceClassification"),
|
| 306 |
+
("gpt-sw3", "TFGPT2ForSequenceClassification"),
|
| 307 |
+
("gpt2", "TFGPT2ForSequenceClassification"),
|
| 308 |
+
("gptj", "TFGPTJForSequenceClassification"),
|
| 309 |
+
("layoutlm", "TFLayoutLMForSequenceClassification"),
|
| 310 |
+
("layoutlmv3", "TFLayoutLMv3ForSequenceClassification"),
|
| 311 |
+
("longformer", "TFLongformerForSequenceClassification"),
|
| 312 |
+
("mobilebert", "TFMobileBertForSequenceClassification"),
|
| 313 |
+
("mpnet", "TFMPNetForSequenceClassification"),
|
| 314 |
+
("openai-gpt", "TFOpenAIGPTForSequenceClassification"),
|
| 315 |
+
("rembert", "TFRemBertForSequenceClassification"),
|
| 316 |
+
("roberta", "TFRobertaForSequenceClassification"),
|
| 317 |
+
("roberta-prelayernorm", "TFRobertaPreLayerNormForSequenceClassification"),
|
| 318 |
+
("roformer", "TFRoFormerForSequenceClassification"),
|
| 319 |
+
("tapas", "TFTapasForSequenceClassification"),
|
| 320 |
+
("transfo-xl", "TFTransfoXLForSequenceClassification"),
|
| 321 |
+
("xlm", "TFXLMForSequenceClassification"),
|
| 322 |
+
("xlm-roberta", "TFXLMRobertaForSequenceClassification"),
|
| 323 |
+
("xlnet", "TFXLNetForSequenceClassification"),
|
| 324 |
+
]
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
|
| 328 |
+
[
|
| 329 |
+
# Model for Question Answering mapping
|
| 330 |
+
("albert", "TFAlbertForQuestionAnswering"),
|
| 331 |
+
("bert", "TFBertForQuestionAnswering"),
|
| 332 |
+
("camembert", "TFCamembertForQuestionAnswering"),
|
| 333 |
+
("convbert", "TFConvBertForQuestionAnswering"),
|
| 334 |
+
("deberta", "TFDebertaForQuestionAnswering"),
|
| 335 |
+
("deberta-v2", "TFDebertaV2ForQuestionAnswering"),
|
| 336 |
+
("distilbert", "TFDistilBertForQuestionAnswering"),
|
| 337 |
+
("electra", "TFElectraForQuestionAnswering"),
|
| 338 |
+
("flaubert", "TFFlaubertForQuestionAnsweringSimple"),
|
| 339 |
+
("funnel", "TFFunnelForQuestionAnswering"),
|
| 340 |
+
("gptj", "TFGPTJForQuestionAnswering"),
|
| 341 |
+
("layoutlmv3", "TFLayoutLMv3ForQuestionAnswering"),
|
| 342 |
+
("longformer", "TFLongformerForQuestionAnswering"),
|
| 343 |
+
("mobilebert", "TFMobileBertForQuestionAnswering"),
|
| 344 |
+
("mpnet", "TFMPNetForQuestionAnswering"),
|
| 345 |
+
("rembert", "TFRemBertForQuestionAnswering"),
|
| 346 |
+
("roberta", "TFRobertaForQuestionAnswering"),
|
| 347 |
+
("roberta-prelayernorm", "TFRobertaPreLayerNormForQuestionAnswering"),
|
| 348 |
+
("roformer", "TFRoFormerForQuestionAnswering"),
|
| 349 |
+
("xlm", "TFXLMForQuestionAnsweringSimple"),
|
| 350 |
+
("xlm-roberta", "TFXLMRobertaForQuestionAnswering"),
|
| 351 |
+
("xlnet", "TFXLNetForQuestionAnsweringSimple"),
|
| 352 |
+
]
|
| 353 |
+
)
|
| 354 |
+
TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = OrderedDict([("wav2vec2", "TFWav2Vec2ForSequenceClassification")])
|
| 355 |
+
|
| 356 |
+
TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
|
| 357 |
+
[
|
| 358 |
+
("layoutlm", "TFLayoutLMForQuestionAnswering"),
|
| 359 |
+
]
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES = OrderedDict(
|
| 364 |
+
[
|
| 365 |
+
# Model for Table Question Answering mapping
|
| 366 |
+
("tapas", "TFTapasForQuestionAnswering"),
|
| 367 |
+
]
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = OrderedDict(
|
| 371 |
+
[
|
| 372 |
+
# Model for Token Classification mapping
|
| 373 |
+
("albert", "TFAlbertForTokenClassification"),
|
| 374 |
+
("bert", "TFBertForTokenClassification"),
|
| 375 |
+
("camembert", "TFCamembertForTokenClassification"),
|
| 376 |
+
("convbert", "TFConvBertForTokenClassification"),
|
| 377 |
+
("deberta", "TFDebertaForTokenClassification"),
|
| 378 |
+
("deberta-v2", "TFDebertaV2ForTokenClassification"),
|
| 379 |
+
("distilbert", "TFDistilBertForTokenClassification"),
|
| 380 |
+
("electra", "TFElectraForTokenClassification"),
|
| 381 |
+
("esm", "TFEsmForTokenClassification"),
|
| 382 |
+
("flaubert", "TFFlaubertForTokenClassification"),
|
| 383 |
+
("funnel", "TFFunnelForTokenClassification"),
|
| 384 |
+
("layoutlm", "TFLayoutLMForTokenClassification"),
|
| 385 |
+
("layoutlmv3", "TFLayoutLMv3ForTokenClassification"),
|
| 386 |
+
("longformer", "TFLongformerForTokenClassification"),
|
| 387 |
+
("mobilebert", "TFMobileBertForTokenClassification"),
|
| 388 |
+
("mpnet", "TFMPNetForTokenClassification"),
|
| 389 |
+
("rembert", "TFRemBertForTokenClassification"),
|
| 390 |
+
("roberta", "TFRobertaForTokenClassification"),
|
| 391 |
+
("roberta-prelayernorm", "TFRobertaPreLayerNormForTokenClassification"),
|
| 392 |
+
("roformer", "TFRoFormerForTokenClassification"),
|
| 393 |
+
("xlm", "TFXLMForTokenClassification"),
|
| 394 |
+
("xlm-roberta", "TFXLMRobertaForTokenClassification"),
|
| 395 |
+
("xlnet", "TFXLNetForTokenClassification"),
|
| 396 |
+
]
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES = OrderedDict(
|
| 400 |
+
[
|
| 401 |
+
# Model for Multiple Choice mapping
|
| 402 |
+
("albert", "TFAlbertForMultipleChoice"),
|
| 403 |
+
("bert", "TFBertForMultipleChoice"),
|
| 404 |
+
("camembert", "TFCamembertForMultipleChoice"),
|
| 405 |
+
("convbert", "TFConvBertForMultipleChoice"),
|
| 406 |
+
("distilbert", "TFDistilBertForMultipleChoice"),
|
| 407 |
+
("electra", "TFElectraForMultipleChoice"),
|
| 408 |
+
("flaubert", "TFFlaubertForMultipleChoice"),
|
| 409 |
+
("funnel", "TFFunnelForMultipleChoice"),
|
| 410 |
+
("longformer", "TFLongformerForMultipleChoice"),
|
| 411 |
+
("mobilebert", "TFMobileBertForMultipleChoice"),
|
| 412 |
+
("mpnet", "TFMPNetForMultipleChoice"),
|
| 413 |
+
("rembert", "TFRemBertForMultipleChoice"),
|
| 414 |
+
("roberta", "TFRobertaForMultipleChoice"),
|
| 415 |
+
("roberta-prelayernorm", "TFRobertaPreLayerNormForMultipleChoice"),
|
| 416 |
+
("roformer", "TFRoFormerForMultipleChoice"),
|
| 417 |
+
("xlm", "TFXLMForMultipleChoice"),
|
| 418 |
+
("xlm-roberta", "TFXLMRobertaForMultipleChoice"),
|
| 419 |
+
("xlnet", "TFXLNetForMultipleChoice"),
|
| 420 |
+
]
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES = OrderedDict(
|
| 424 |
+
[
|
| 425 |
+
("bert", "TFBertForNextSentencePrediction"),
|
| 426 |
+
("mobilebert", "TFMobileBertForNextSentencePrediction"),
|
| 427 |
+
]
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
TF_MODEL_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_MAPPING_NAMES)
|
| 431 |
+
TF_MODEL_FOR_PRETRAINING_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_FOR_PRETRAINING_MAPPING_NAMES)
|
| 432 |
+
TF_MODEL_WITH_LM_HEAD_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_WITH_LM_HEAD_MAPPING_NAMES)
|
| 433 |
+
TF_MODEL_FOR_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
|
| 434 |
+
TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING = _LazyAutoMapping(
|
| 435 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES
|
| 436 |
+
)
|
| 437 |
+
TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 438 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
|
| 439 |
+
)
|
| 440 |
+
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 441 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
|
| 442 |
+
)
|
| 443 |
+
TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING = _LazyAutoMapping(
|
| 444 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES
|
| 445 |
+
)
|
| 446 |
+
TF_MODEL_FOR_VISION_2_SEQ_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
|
| 447 |
+
TF_MODEL_FOR_MASKED_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TF_MODEL_FOR_MASKED_LM_MAPPING_NAMES)
|
| 448 |
+
TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING = _LazyAutoMapping(
|
| 449 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
|
| 450 |
+
)
|
| 451 |
+
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 452 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
|
| 453 |
+
)
|
| 454 |
+
TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING = _LazyAutoMapping(
|
| 455 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES
|
| 456 |
+
)
|
| 457 |
+
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
|
| 458 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
|
| 459 |
+
)
|
| 460 |
+
TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
|
| 461 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES
|
| 462 |
+
)
|
| 463 |
+
TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING = _LazyAutoMapping(
|
| 464 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES
|
| 465 |
+
)
|
| 466 |
+
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 467 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
|
| 468 |
+
)
|
| 469 |
+
TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING = _LazyAutoMapping(
|
| 470 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES
|
| 471 |
+
)
|
| 472 |
+
TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING = _LazyAutoMapping(
|
| 473 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
|
| 474 |
+
)
|
| 475 |
+
TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING = _LazyAutoMapping(
|
| 476 |
+
CONFIG_MAPPING_NAMES, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
class TFAutoModel(_BaseAutoModelClass):
|
| 481 |
+
_model_mapping = TF_MODEL_MAPPING
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
TFAutoModel = auto_class_update(TFAutoModel)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
class TFAutoModelForAudioClassification(_BaseAutoModelClass):
|
| 488 |
+
_model_mapping = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
TFAutoModelForAudioClassification = auto_class_update(
|
| 492 |
+
TFAutoModelForAudioClassification, head_doc="audio classification"
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
class TFAutoModelForPreTraining(_BaseAutoModelClass):
|
| 497 |
+
_model_mapping = TF_MODEL_FOR_PRETRAINING_MAPPING
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
TFAutoModelForPreTraining = auto_class_update(TFAutoModelForPreTraining, head_doc="pretraining")
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
# Private on purpose, the public class will add the deprecation warnings.
|
| 504 |
+
class _TFAutoModelWithLMHead(_BaseAutoModelClass):
|
| 505 |
+
_model_mapping = TF_MODEL_WITH_LM_HEAD_MAPPING
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
_TFAutoModelWithLMHead = auto_class_update(_TFAutoModelWithLMHead, head_doc="language modeling")
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
class TFAutoModelForCausalLM(_BaseAutoModelClass):
|
| 512 |
+
_model_mapping = TF_MODEL_FOR_CAUSAL_LM_MAPPING
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
TFAutoModelForCausalLM = auto_class_update(TFAutoModelForCausalLM, head_doc="causal language modeling")
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
class TFAutoModelForMaskedImageModeling(_BaseAutoModelClass):
|
| 519 |
+
_model_mapping = TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
TFAutoModelForMaskedImageModeling = auto_class_update(
|
| 523 |
+
TFAutoModelForMaskedImageModeling, head_doc="masked image modeling"
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
class TFAutoModelForImageClassification(_BaseAutoModelClass):
|
| 528 |
+
_model_mapping = TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
TFAutoModelForImageClassification = auto_class_update(
|
| 532 |
+
TFAutoModelForImageClassification, head_doc="image classification"
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
class TFAutoModelForZeroShotImageClassification(_BaseAutoModelClass):
|
| 537 |
+
_model_mapping = TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
TFAutoModelForZeroShotImageClassification = auto_class_update(
|
| 541 |
+
TFAutoModelForZeroShotImageClassification, head_doc="zero-shot image classification"
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
class TFAutoModelForSemanticSegmentation(_BaseAutoModelClass):
|
| 546 |
+
_model_mapping = TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
TF_AutoModelForSemanticSegmentation = auto_class_update(
|
| 550 |
+
TFAutoModelForSemanticSegmentation, head_doc="semantic segmentation"
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
class TFAutoModelForVision2Seq(_BaseAutoModelClass):
|
| 555 |
+
_model_mapping = TF_MODEL_FOR_VISION_2_SEQ_MAPPING
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
TFAutoModelForVision2Seq = auto_class_update(TFAutoModelForVision2Seq, head_doc="vision-to-text modeling")
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
class TFAutoModelForMaskedLM(_BaseAutoModelClass):
|
| 562 |
+
_model_mapping = TF_MODEL_FOR_MASKED_LM_MAPPING
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
TFAutoModelForMaskedLM = auto_class_update(TFAutoModelForMaskedLM, head_doc="masked language modeling")
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
class TFAutoModelForSeq2SeqLM(_BaseAutoModelClass):
|
| 569 |
+
_model_mapping = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
TFAutoModelForSeq2SeqLM = auto_class_update(
|
| 573 |
+
TFAutoModelForSeq2SeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base"
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
class TFAutoModelForSequenceClassification(_BaseAutoModelClass):
|
| 578 |
+
_model_mapping = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
TFAutoModelForSequenceClassification = auto_class_update(
|
| 582 |
+
TFAutoModelForSequenceClassification, head_doc="sequence classification"
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
class TFAutoModelForQuestionAnswering(_BaseAutoModelClass):
|
| 587 |
+
_model_mapping = TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
TFAutoModelForQuestionAnswering = auto_class_update(TFAutoModelForQuestionAnswering, head_doc="question answering")
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
class TFAutoModelForDocumentQuestionAnswering(_BaseAutoModelClass):
|
| 594 |
+
_model_mapping = TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
TFAutoModelForDocumentQuestionAnswering = auto_class_update(
|
| 598 |
+
TFAutoModelForDocumentQuestionAnswering,
|
| 599 |
+
head_doc="document question answering",
|
| 600 |
+
checkpoint_for_example='impira/layoutlm-document-qa", revision="52e01b3',
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
class TFAutoModelForTableQuestionAnswering(_BaseAutoModelClass):
|
| 605 |
+
_model_mapping = TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
TFAutoModelForTableQuestionAnswering = auto_class_update(
|
| 609 |
+
TFAutoModelForTableQuestionAnswering,
|
| 610 |
+
head_doc="table question answering",
|
| 611 |
+
checkpoint_for_example="google/tapas-base-finetuned-wtq",
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
class TFAutoModelForTokenClassification(_BaseAutoModelClass):
|
| 616 |
+
_model_mapping = TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
TFAutoModelForTokenClassification = auto_class_update(
|
| 620 |
+
TFAutoModelForTokenClassification, head_doc="token classification"
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
class TFAutoModelForMultipleChoice(_BaseAutoModelClass):
|
| 625 |
+
_model_mapping = TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
TFAutoModelForMultipleChoice = auto_class_update(TFAutoModelForMultipleChoice, head_doc="multiple choice")
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
class TFAutoModelForNextSentencePrediction(_BaseAutoModelClass):
|
| 632 |
+
_model_mapping = TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
TFAutoModelForNextSentencePrediction = auto_class_update(
|
| 636 |
+
TFAutoModelForNextSentencePrediction, head_doc="next sentence prediction"
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
class TFAutoModelForSpeechSeq2Seq(_BaseAutoModelClass):
|
| 641 |
+
_model_mapping = TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
TFAutoModelForSpeechSeq2Seq = auto_class_update(
|
| 645 |
+
TFAutoModelForSpeechSeq2Seq, head_doc="sequence-to-sequence speech-to-text modeling"
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
class TFAutoModelWithLMHead(_TFAutoModelWithLMHead):
|
| 650 |
+
@classmethod
|
| 651 |
+
def from_config(cls, config):
|
| 652 |
+
warnings.warn(
|
| 653 |
+
"The class `TFAutoModelWithLMHead` is deprecated and will be removed in a future version. Please use"
|
| 654 |
+
" `TFAutoModelForCausalLM` for causal language models, `TFAutoModelForMaskedLM` for masked language models"
|
| 655 |
+
" and `TFAutoModelForSeq2SeqLM` for encoder-decoder models.",
|
| 656 |
+
FutureWarning,
|
| 657 |
+
)
|
| 658 |
+
return super().from_config(config)
|
| 659 |
+
|
| 660 |
+
@classmethod
|
| 661 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 662 |
+
warnings.warn(
|
| 663 |
+
"The class `TFAutoModelWithLMHead` is deprecated and will be removed in a future version. Please use"
|
| 664 |
+
" `TFAutoModelForCausalLM` for causal language models, `TFAutoModelForMaskedLM` for masked language models"
|
| 665 |
+
" and `TFAutoModelForSeq2SeqLM` for encoder-decoder models.",
|
| 666 |
+
FutureWarning,
|
| 667 |
+
)
|
| 668 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/processing_auto.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" AutoProcessor class."""
|
| 16 |
+
import importlib
|
| 17 |
+
import inspect
|
| 18 |
+
import json
|
| 19 |
+
from collections import OrderedDict
|
| 20 |
+
|
| 21 |
+
# Build the list of all feature extractors
|
| 22 |
+
from ...configuration_utils import PretrainedConfig
|
| 23 |
+
from ...dynamic_module_utils import get_class_from_dynamic_module
|
| 24 |
+
from ...feature_extraction_utils import FeatureExtractionMixin
|
| 25 |
+
from ...image_processing_utils import ImageProcessingMixin
|
| 26 |
+
from ...tokenization_utils import TOKENIZER_CONFIG_FILE
|
| 27 |
+
from ...utils import FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
|
| 28 |
+
from .auto_factory import _LazyAutoMapping
|
| 29 |
+
from .configuration_auto import (
|
| 30 |
+
CONFIG_MAPPING_NAMES,
|
| 31 |
+
AutoConfig,
|
| 32 |
+
model_type_to_module_name,
|
| 33 |
+
replace_list_option_in_docstrings,
|
| 34 |
+
)
|
| 35 |
+
from .feature_extraction_auto import AutoFeatureExtractor
|
| 36 |
+
from .image_processing_auto import AutoImageProcessor
|
| 37 |
+
from .tokenization_auto import AutoTokenizer
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
PROCESSOR_MAPPING_NAMES = OrderedDict(
|
| 43 |
+
[
|
| 44 |
+
("align", "AlignProcessor"),
|
| 45 |
+
("altclip", "AltCLIPProcessor"),
|
| 46 |
+
("blip", "BlipProcessor"),
|
| 47 |
+
("blip-2", "Blip2Processor"),
|
| 48 |
+
("bridgetower", "BridgeTowerProcessor"),
|
| 49 |
+
("chinese_clip", "ChineseCLIPProcessor"),
|
| 50 |
+
("clap", "ClapProcessor"),
|
| 51 |
+
("clip", "CLIPProcessor"),
|
| 52 |
+
("clipseg", "CLIPSegProcessor"),
|
| 53 |
+
("flava", "FlavaProcessor"),
|
| 54 |
+
("git", "GitProcessor"),
|
| 55 |
+
("groupvit", "CLIPProcessor"),
|
| 56 |
+
("hubert", "Wav2Vec2Processor"),
|
| 57 |
+
("layoutlmv2", "LayoutLMv2Processor"),
|
| 58 |
+
("layoutlmv3", "LayoutLMv3Processor"),
|
| 59 |
+
("markuplm", "MarkupLMProcessor"),
|
| 60 |
+
("mgp-str", "MgpstrProcessor"),
|
| 61 |
+
("oneformer", "OneFormerProcessor"),
|
| 62 |
+
("owlvit", "OwlViTProcessor"),
|
| 63 |
+
("pix2struct", "Pix2StructProcessor"),
|
| 64 |
+
("sam", "SamProcessor"),
|
| 65 |
+
("sew", "Wav2Vec2Processor"),
|
| 66 |
+
("sew-d", "Wav2Vec2Processor"),
|
| 67 |
+
("speech_to_text", "Speech2TextProcessor"),
|
| 68 |
+
("speech_to_text_2", "Speech2Text2Processor"),
|
| 69 |
+
("speecht5", "SpeechT5Processor"),
|
| 70 |
+
("trocr", "TrOCRProcessor"),
|
| 71 |
+
("tvlt", "TvltProcessor"),
|
| 72 |
+
("unispeech", "Wav2Vec2Processor"),
|
| 73 |
+
("unispeech-sat", "Wav2Vec2Processor"),
|
| 74 |
+
("vilt", "ViltProcessor"),
|
| 75 |
+
("vision-text-dual-encoder", "VisionTextDualEncoderProcessor"),
|
| 76 |
+
("wav2vec2", "Wav2Vec2Processor"),
|
| 77 |
+
("wav2vec2-conformer", "Wav2Vec2Processor"),
|
| 78 |
+
("wavlm", "Wav2Vec2Processor"),
|
| 79 |
+
("whisper", "WhisperProcessor"),
|
| 80 |
+
("xclip", "XCLIPProcessor"),
|
| 81 |
+
]
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
PROCESSOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def processor_class_from_name(class_name: str):
|
| 88 |
+
for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
|
| 89 |
+
if class_name in processors:
|
| 90 |
+
module_name = model_type_to_module_name(module_name)
|
| 91 |
+
|
| 92 |
+
module = importlib.import_module(f".{module_name}", "transformers.models")
|
| 93 |
+
try:
|
| 94 |
+
return getattr(module, class_name)
|
| 95 |
+
except AttributeError:
|
| 96 |
+
continue
|
| 97 |
+
|
| 98 |
+
for processor in PROCESSOR_MAPPING._extra_content.values():
|
| 99 |
+
if getattr(processor, "__name__", None) == class_name:
|
| 100 |
+
return processor
|
| 101 |
+
|
| 102 |
+
# We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
|
| 103 |
+
# init and we return the proper dummy to get an appropriate error message.
|
| 104 |
+
main_module = importlib.import_module("transformers")
|
| 105 |
+
if hasattr(main_module, class_name):
|
| 106 |
+
return getattr(main_module, class_name)
|
| 107 |
+
|
| 108 |
+
return None
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class AutoProcessor:
|
| 112 |
+
r"""
|
| 113 |
+
This is a generic processor class that will be instantiated as one of the processor classes of the library when
|
| 114 |
+
created with the [`AutoProcessor.from_pretrained`] class method.
|
| 115 |
+
|
| 116 |
+
This class cannot be instantiated directly using `__init__()` (throws an error).
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
def __init__(self):
|
| 120 |
+
raise EnvironmentError(
|
| 121 |
+
"AutoProcessor is designed to be instantiated "
|
| 122 |
+
"using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method."
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
@classmethod
|
| 126 |
+
@replace_list_option_in_docstrings(PROCESSOR_MAPPING_NAMES)
|
| 127 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 128 |
+
r"""
|
| 129 |
+
Instantiate one of the processor classes of the library from a pretrained model vocabulary.
|
| 130 |
+
|
| 131 |
+
The processor class to instantiate is selected based on the `model_type` property of the config object (either
|
| 132 |
+
passed as an argument or loaded from `pretrained_model_name_or_path` if possible):
|
| 133 |
+
|
| 134 |
+
List options
|
| 135 |
+
|
| 136 |
+
Params:
|
| 137 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 138 |
+
This can be either:
|
| 139 |
+
|
| 140 |
+
- a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
|
| 141 |
+
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or
|
| 142 |
+
namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 143 |
+
- a path to a *directory* containing a processor files saved using the `save_pretrained()` method,
|
| 144 |
+
e.g., `./my_model_directory/`.
|
| 145 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 146 |
+
Path to a directory in which a downloaded pretrained model feature extractor should be cached if the
|
| 147 |
+
standard cache should not be used.
|
| 148 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 149 |
+
Whether or not to force to (re-)download the feature extractor files and override the cached versions
|
| 150 |
+
if they exist.
|
| 151 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 152 |
+
Whether or not to delete incompletely received file. Attempts to resume the download if such a file
|
| 153 |
+
exists.
|
| 154 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 155 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 156 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 157 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 158 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
| 159 |
+
when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 160 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 161 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 162 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 163 |
+
identifier allowed by git.
|
| 164 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
| 165 |
+
If `False`, then this function returns just the final feature extractor object. If `True`, then this
|
| 166 |
+
functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
|
| 167 |
+
consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
|
| 168 |
+
`kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
|
| 169 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 170 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 171 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 172 |
+
execute code present on the Hub on your local machine.
|
| 173 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 174 |
+
The values in kwargs of any keys which are feature extractor attributes will be used to override the
|
| 175 |
+
loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
|
| 176 |
+
controlled by the `return_unused_kwargs` keyword parameter.
|
| 177 |
+
|
| 178 |
+
<Tip>
|
| 179 |
+
|
| 180 |
+
Passing `use_auth_token=True` is required when you want to use a private model.
|
| 181 |
+
|
| 182 |
+
</Tip>
|
| 183 |
+
|
| 184 |
+
Examples:
|
| 185 |
+
|
| 186 |
+
```python
|
| 187 |
+
>>> from transformers import AutoProcessor
|
| 188 |
+
|
| 189 |
+
>>> # Download processor from huggingface.co and cache.
|
| 190 |
+
>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
|
| 191 |
+
|
| 192 |
+
>>> # If processor files are in a directory (e.g. processor was saved using *save_pretrained('./test/saved_model/')*)
|
| 193 |
+
>>> # processor = AutoProcessor.from_pretrained("./test/saved_model/")
|
| 194 |
+
```"""
|
| 195 |
+
config = kwargs.pop("config", None)
|
| 196 |
+
trust_remote_code = kwargs.pop("trust_remote_code", False)
|
| 197 |
+
kwargs["_from_auto"] = True
|
| 198 |
+
|
| 199 |
+
processor_class = None
|
| 200 |
+
processor_auto_map = None
|
| 201 |
+
|
| 202 |
+
# First, let's see if we have a preprocessor config.
|
| 203 |
+
# Filter the kwargs for `get_file_from_repo`.
|
| 204 |
+
get_file_from_repo_kwargs = {
|
| 205 |
+
key: kwargs[key] for key in inspect.signature(get_file_from_repo).parameters.keys() if key in kwargs
|
| 206 |
+
}
|
| 207 |
+
# Let's start by checking whether the processor class is saved in an image processor
|
| 208 |
+
preprocessor_config_file = get_file_from_repo(
|
| 209 |
+
pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME, **get_file_from_repo_kwargs
|
| 210 |
+
)
|
| 211 |
+
if preprocessor_config_file is not None:
|
| 212 |
+
config_dict, _ = ImageProcessingMixin.get_image_processor_dict(pretrained_model_name_or_path, **kwargs)
|
| 213 |
+
processor_class = config_dict.get("processor_class", None)
|
| 214 |
+
if "AutoProcessor" in config_dict.get("auto_map", {}):
|
| 215 |
+
processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
|
| 216 |
+
|
| 217 |
+
# If not found, let's check whether the processor class is saved in a feature extractor config
|
| 218 |
+
if preprocessor_config_file is not None and processor_class is None:
|
| 219 |
+
config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs)
|
| 220 |
+
processor_class = config_dict.get("processor_class", None)
|
| 221 |
+
if "AutoProcessor" in config_dict.get("auto_map", {}):
|
| 222 |
+
processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
|
| 223 |
+
|
| 224 |
+
if processor_class is None:
|
| 225 |
+
# Next, let's check whether the processor class is saved in a tokenizer
|
| 226 |
+
tokenizer_config_file = get_file_from_repo(
|
| 227 |
+
pretrained_model_name_or_path, TOKENIZER_CONFIG_FILE, **get_file_from_repo_kwargs
|
| 228 |
+
)
|
| 229 |
+
if tokenizer_config_file is not None:
|
| 230 |
+
with open(tokenizer_config_file, encoding="utf-8") as reader:
|
| 231 |
+
config_dict = json.load(reader)
|
| 232 |
+
|
| 233 |
+
processor_class = config_dict.get("processor_class", None)
|
| 234 |
+
if "AutoProcessor" in config_dict.get("auto_map", {}):
|
| 235 |
+
processor_auto_map = config_dict["auto_map"]["AutoProcessor"]
|
| 236 |
+
|
| 237 |
+
if processor_class is None:
|
| 238 |
+
# Otherwise, load config, if it can be loaded.
|
| 239 |
+
if not isinstance(config, PretrainedConfig):
|
| 240 |
+
config = AutoConfig.from_pretrained(
|
| 241 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
# And check if the config contains the processor class.
|
| 245 |
+
processor_class = getattr(config, "processor_class", None)
|
| 246 |
+
if hasattr(config, "auto_map") and "AutoProcessor" in config.auto_map:
|
| 247 |
+
processor_auto_map = config.auto_map["AutoProcessor"]
|
| 248 |
+
|
| 249 |
+
if processor_class is not None:
|
| 250 |
+
# If we have custom code for a feature extractor, we get the proper class.
|
| 251 |
+
if processor_auto_map is not None:
|
| 252 |
+
if not trust_remote_code:
|
| 253 |
+
raise ValueError(
|
| 254 |
+
f"Loading {pretrained_model_name_or_path} requires you to execute the feature extractor file "
|
| 255 |
+
"in that repo on your local machine. Make sure you have read the code there to avoid "
|
| 256 |
+
"malicious use, then set the option `trust_remote_code=True` to remove this error."
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
processor_class = get_class_from_dynamic_module(
|
| 260 |
+
processor_auto_map, pretrained_model_name_or_path, **kwargs
|
| 261 |
+
)
|
| 262 |
+
else:
|
| 263 |
+
processor_class = processor_class_from_name(processor_class)
|
| 264 |
+
|
| 265 |
+
return processor_class.from_pretrained(
|
| 266 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
# Last try: we use the PROCESSOR_MAPPING.
|
| 270 |
+
if type(config) in PROCESSOR_MAPPING:
|
| 271 |
+
return PROCESSOR_MAPPING[type(config)].from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 272 |
+
|
| 273 |
+
# At this stage, there doesn't seem to be a `Processor` class available for this model, so let's try a
|
| 274 |
+
# tokenizer.
|
| 275 |
+
try:
|
| 276 |
+
return AutoTokenizer.from_pretrained(
|
| 277 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 278 |
+
)
|
| 279 |
+
except Exception:
|
| 280 |
+
try:
|
| 281 |
+
return AutoImageProcessor.from_pretrained(
|
| 282 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 283 |
+
)
|
| 284 |
+
except Exception:
|
| 285 |
+
pass
|
| 286 |
+
|
| 287 |
+
try:
|
| 288 |
+
return AutoFeatureExtractor.from_pretrained(
|
| 289 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 290 |
+
)
|
| 291 |
+
except Exception:
|
| 292 |
+
pass
|
| 293 |
+
|
| 294 |
+
raise ValueError(
|
| 295 |
+
f"Unrecognized processing class in {pretrained_model_name_or_path}. Can't instantiate a processor, a "
|
| 296 |
+
"tokenizer, an image processor or a feature extractor for this model. Make sure the repository contains"
|
| 297 |
+
"the files of at least one of those processing classes."
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
@staticmethod
|
| 301 |
+
def register(config_class, processor_class):
|
| 302 |
+
"""
|
| 303 |
+
Register a new processor for this class.
|
| 304 |
+
|
| 305 |
+
Args:
|
| 306 |
+
config_class ([`PretrainedConfig`]):
|
| 307 |
+
The configuration corresponding to the model to register.
|
| 308 |
+
processor_class ([`FeatureExtractorMixin`]): The processor to register.
|
| 309 |
+
"""
|
| 310 |
+
PROCESSOR_MAPPING.register(config_class, processor_class)
|
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/auto/tokenization_auto.py
ADDED
|
@@ -0,0 +1,767 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" Auto Tokenizer class."""
|
| 16 |
+
|
| 17 |
+
import importlib
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
from collections import OrderedDict
|
| 21 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
from ...configuration_utils import PretrainedConfig
|
| 24 |
+
from ...dynamic_module_utils import get_class_from_dynamic_module
|
| 25 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 26 |
+
from ...tokenization_utils_base import TOKENIZER_CONFIG_FILE
|
| 27 |
+
from ...utils import cached_file, extract_commit_hash, is_sentencepiece_available, is_tokenizers_available, logging
|
| 28 |
+
from ..encoder_decoder import EncoderDecoderConfig
|
| 29 |
+
from .auto_factory import _LazyAutoMapping
|
| 30 |
+
from .configuration_auto import (
|
| 31 |
+
CONFIG_MAPPING_NAMES,
|
| 32 |
+
AutoConfig,
|
| 33 |
+
config_class_to_model_type,
|
| 34 |
+
model_type_to_module_name,
|
| 35 |
+
replace_list_option_in_docstrings,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if is_tokenizers_available():
|
| 40 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 41 |
+
else:
|
| 42 |
+
PreTrainedTokenizerFast = None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
logger = logging.get_logger(__name__)
|
| 46 |
+
|
| 47 |
+
if TYPE_CHECKING:
|
| 48 |
+
# This significantly improves completion suggestion performance when
|
| 49 |
+
# the transformers package is used with Microsoft's Pylance language server.
|
| 50 |
+
TOKENIZER_MAPPING_NAMES: OrderedDict[str, Tuple[Optional[str], Optional[str]]] = OrderedDict()
|
| 51 |
+
else:
|
| 52 |
+
TOKENIZER_MAPPING_NAMES = OrderedDict(
|
| 53 |
+
[
|
| 54 |
+
(
|
| 55 |
+
"albert",
|
| 56 |
+
(
|
| 57 |
+
"AlbertTokenizer" if is_sentencepiece_available() else None,
|
| 58 |
+
"AlbertTokenizerFast" if is_tokenizers_available() else None,
|
| 59 |
+
),
|
| 60 |
+
),
|
| 61 |
+
("align", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 62 |
+
("bart", ("BartTokenizer", "BartTokenizerFast")),
|
| 63 |
+
(
|
| 64 |
+
"barthez",
|
| 65 |
+
(
|
| 66 |
+
"BarthezTokenizer" if is_sentencepiece_available() else None,
|
| 67 |
+
"BarthezTokenizerFast" if is_tokenizers_available() else None,
|
| 68 |
+
),
|
| 69 |
+
),
|
| 70 |
+
("bartpho", ("BartphoTokenizer", None)),
|
| 71 |
+
("bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 72 |
+
("bert-generation", ("BertGenerationTokenizer" if is_sentencepiece_available() else None, None)),
|
| 73 |
+
("bert-japanese", ("BertJapaneseTokenizer", None)),
|
| 74 |
+
("bertweet", ("BertweetTokenizer", None)),
|
| 75 |
+
(
|
| 76 |
+
"big_bird",
|
| 77 |
+
(
|
| 78 |
+
"BigBirdTokenizer" if is_sentencepiece_available() else None,
|
| 79 |
+
"BigBirdTokenizerFast" if is_tokenizers_available() else None,
|
| 80 |
+
),
|
| 81 |
+
),
|
| 82 |
+
("bigbird_pegasus", ("PegasusTokenizer", "PegasusTokenizerFast" if is_tokenizers_available() else None)),
|
| 83 |
+
("biogpt", ("BioGptTokenizer", None)),
|
| 84 |
+
("blenderbot", ("BlenderbotTokenizer", "BlenderbotTokenizerFast")),
|
| 85 |
+
("blenderbot-small", ("BlenderbotSmallTokenizer", None)),
|
| 86 |
+
("blip", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 87 |
+
("blip-2", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 88 |
+
("bloom", (None, "BloomTokenizerFast" if is_tokenizers_available() else None)),
|
| 89 |
+
("bridgetower", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 90 |
+
("byt5", ("ByT5Tokenizer", None)),
|
| 91 |
+
(
|
| 92 |
+
"camembert",
|
| 93 |
+
(
|
| 94 |
+
"CamembertTokenizer" if is_sentencepiece_available() else None,
|
| 95 |
+
"CamembertTokenizerFast" if is_tokenizers_available() else None,
|
| 96 |
+
),
|
| 97 |
+
),
|
| 98 |
+
("canine", ("CanineTokenizer", None)),
|
| 99 |
+
("chinese_clip", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 100 |
+
(
|
| 101 |
+
"clap",
|
| 102 |
+
(
|
| 103 |
+
"RobertaTokenizer",
|
| 104 |
+
"RobertaTokenizerFast" if is_tokenizers_available() else None,
|
| 105 |
+
),
|
| 106 |
+
),
|
| 107 |
+
(
|
| 108 |
+
"clip",
|
| 109 |
+
(
|
| 110 |
+
"CLIPTokenizer",
|
| 111 |
+
"CLIPTokenizerFast" if is_tokenizers_available() else None,
|
| 112 |
+
),
|
| 113 |
+
),
|
| 114 |
+
(
|
| 115 |
+
"clipseg",
|
| 116 |
+
(
|
| 117 |
+
"CLIPTokenizer",
|
| 118 |
+
"CLIPTokenizerFast" if is_tokenizers_available() else None,
|
| 119 |
+
),
|
| 120 |
+
),
|
| 121 |
+
("codegen", ("CodeGenTokenizer", "CodeGenTokenizerFast" if is_tokenizers_available() else None)),
|
| 122 |
+
("convbert", ("ConvBertTokenizer", "ConvBertTokenizerFast" if is_tokenizers_available() else None)),
|
| 123 |
+
(
|
| 124 |
+
"cpm",
|
| 125 |
+
(
|
| 126 |
+
"CpmTokenizer" if is_sentencepiece_available() else None,
|
| 127 |
+
"CpmTokenizerFast" if is_tokenizers_available() else None,
|
| 128 |
+
),
|
| 129 |
+
),
|
| 130 |
+
("cpmant", ("CpmAntTokenizer", None)),
|
| 131 |
+
("ctrl", ("CTRLTokenizer", None)),
|
| 132 |
+
("data2vec-text", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 133 |
+
("deberta", ("DebertaTokenizer", "DebertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 134 |
+
(
|
| 135 |
+
"deberta-v2",
|
| 136 |
+
(
|
| 137 |
+
"DebertaV2Tokenizer" if is_sentencepiece_available() else None,
|
| 138 |
+
"DebertaV2TokenizerFast" if is_tokenizers_available() else None,
|
| 139 |
+
),
|
| 140 |
+
),
|
| 141 |
+
("distilbert", ("DistilBertTokenizer", "DistilBertTokenizerFast" if is_tokenizers_available() else None)),
|
| 142 |
+
(
|
| 143 |
+
"dpr",
|
| 144 |
+
(
|
| 145 |
+
"DPRQuestionEncoderTokenizer",
|
| 146 |
+
"DPRQuestionEncoderTokenizerFast" if is_tokenizers_available() else None,
|
| 147 |
+
),
|
| 148 |
+
),
|
| 149 |
+
("electra", ("ElectraTokenizer", "ElectraTokenizerFast" if is_tokenizers_available() else None)),
|
| 150 |
+
("ernie", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 151 |
+
("ernie_m", ("ErnieMTokenizer" if is_sentencepiece_available() else None, None)),
|
| 152 |
+
("esm", ("EsmTokenizer", None)),
|
| 153 |
+
("flaubert", ("FlaubertTokenizer", None)),
|
| 154 |
+
("fnet", ("FNetTokenizer", "FNetTokenizerFast" if is_tokenizers_available() else None)),
|
| 155 |
+
("fsmt", ("FSMTTokenizer", None)),
|
| 156 |
+
("funnel", ("FunnelTokenizer", "FunnelTokenizerFast" if is_tokenizers_available() else None)),
|
| 157 |
+
("git", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 158 |
+
("gpt-sw3", ("GPTSw3Tokenizer" if is_sentencepiece_available() else None, None)),
|
| 159 |
+
("gpt2", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 160 |
+
("gpt_bigcode", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 161 |
+
("gpt_neo", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 162 |
+
("gpt_neox", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
|
| 163 |
+
("gpt_neox_japanese", ("GPTNeoXJapaneseTokenizer", None)),
|
| 164 |
+
("gptj", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 165 |
+
("gptsan-japanese", ("GPTSanJapaneseTokenizer", None)),
|
| 166 |
+
("groupvit", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
|
| 167 |
+
("herbert", ("HerbertTokenizer", "HerbertTokenizerFast" if is_tokenizers_available() else None)),
|
| 168 |
+
("hubert", ("Wav2Vec2CTCTokenizer", None)),
|
| 169 |
+
("ibert", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 170 |
+
("jukebox", ("JukeboxTokenizer", None)),
|
| 171 |
+
("layoutlm", ("LayoutLMTokenizer", "LayoutLMTokenizerFast" if is_tokenizers_available() else None)),
|
| 172 |
+
("layoutlmv2", ("LayoutLMv2Tokenizer", "LayoutLMv2TokenizerFast" if is_tokenizers_available() else None)),
|
| 173 |
+
("layoutlmv3", ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast" if is_tokenizers_available() else None)),
|
| 174 |
+
("layoutxlm", ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast" if is_tokenizers_available() else None)),
|
| 175 |
+
("led", ("LEDTokenizer", "LEDTokenizerFast" if is_tokenizers_available() else None)),
|
| 176 |
+
("lilt", ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast" if is_tokenizers_available() else None)),
|
| 177 |
+
(
|
| 178 |
+
"llama",
|
| 179 |
+
(
|
| 180 |
+
"LlamaTokenizer" if is_sentencepiece_available() else None,
|
| 181 |
+
"LlamaTokenizerFast" if is_tokenizers_available() else None,
|
| 182 |
+
),
|
| 183 |
+
),
|
| 184 |
+
("longformer", ("LongformerTokenizer", "LongformerTokenizerFast" if is_tokenizers_available() else None)),
|
| 185 |
+
(
|
| 186 |
+
"longt5",
|
| 187 |
+
(
|
| 188 |
+
"T5Tokenizer" if is_sentencepiece_available() else None,
|
| 189 |
+
"T5TokenizerFast" if is_tokenizers_available() else None,
|
| 190 |
+
),
|
| 191 |
+
),
|
| 192 |
+
("luke", ("LukeTokenizer", None)),
|
| 193 |
+
("lxmert", ("LxmertTokenizer", "LxmertTokenizerFast" if is_tokenizers_available() else None)),
|
| 194 |
+
("m2m_100", ("M2M100Tokenizer" if is_sentencepiece_available() else None, None)),
|
| 195 |
+
("marian", ("MarianTokenizer" if is_sentencepiece_available() else None, None)),
|
| 196 |
+
(
|
| 197 |
+
"mbart",
|
| 198 |
+
(
|
| 199 |
+
"MBartTokenizer" if is_sentencepiece_available() else None,
|
| 200 |
+
"MBartTokenizerFast" if is_tokenizers_available() else None,
|
| 201 |
+
),
|
| 202 |
+
),
|
| 203 |
+
(
|
| 204 |
+
"mbart50",
|
| 205 |
+
(
|
| 206 |
+
"MBart50Tokenizer" if is_sentencepiece_available() else None,
|
| 207 |
+
"MBart50TokenizerFast" if is_tokenizers_available() else None,
|
| 208 |
+
),
|
| 209 |
+
),
|
| 210 |
+
("mega", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 211 |
+
("megatron-bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 212 |
+
("mgp-str", ("MgpstrTokenizer", None)),
|
| 213 |
+
("mluke", ("MLukeTokenizer" if is_sentencepiece_available() else None, None)),
|
| 214 |
+
("mobilebert", ("MobileBertTokenizer", "MobileBertTokenizerFast" if is_tokenizers_available() else None)),
|
| 215 |
+
("mpnet", ("MPNetTokenizer", "MPNetTokenizerFast" if is_tokenizers_available() else None)),
|
| 216 |
+
(
|
| 217 |
+
"mt5",
|
| 218 |
+
(
|
| 219 |
+
"MT5Tokenizer" if is_sentencepiece_available() else None,
|
| 220 |
+
"MT5TokenizerFast" if is_tokenizers_available() else None,
|
| 221 |
+
),
|
| 222 |
+
),
|
| 223 |
+
("mvp", ("MvpTokenizer", "MvpTokenizerFast" if is_tokenizers_available() else None)),
|
| 224 |
+
("nezha", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 225 |
+
(
|
| 226 |
+
"nllb",
|
| 227 |
+
(
|
| 228 |
+
"NllbTokenizer" if is_sentencepiece_available() else None,
|
| 229 |
+
"NllbTokenizerFast" if is_tokenizers_available() else None,
|
| 230 |
+
),
|
| 231 |
+
),
|
| 232 |
+
(
|
| 233 |
+
"nllb-moe",
|
| 234 |
+
(
|
| 235 |
+
"NllbTokenizer" if is_sentencepiece_available() else None,
|
| 236 |
+
"NllbTokenizerFast" if is_tokenizers_available() else None,
|
| 237 |
+
),
|
| 238 |
+
),
|
| 239 |
+
(
|
| 240 |
+
"nystromformer",
|
| 241 |
+
(
|
| 242 |
+
"AlbertTokenizer" if is_sentencepiece_available() else None,
|
| 243 |
+
"AlbertTokenizerFast" if is_tokenizers_available() else None,
|
| 244 |
+
),
|
| 245 |
+
),
|
| 246 |
+
("oneformer", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
|
| 247 |
+
("openai-gpt", ("OpenAIGPTTokenizer", "OpenAIGPTTokenizerFast" if is_tokenizers_available() else None)),
|
| 248 |
+
("opt", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)),
|
| 249 |
+
("owlvit", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
|
| 250 |
+
(
|
| 251 |
+
"pegasus",
|
| 252 |
+
(
|
| 253 |
+
"PegasusTokenizer" if is_sentencepiece_available() else None,
|
| 254 |
+
"PegasusTokenizerFast" if is_tokenizers_available() else None,
|
| 255 |
+
),
|
| 256 |
+
),
|
| 257 |
+
(
|
| 258 |
+
"pegasus_x",
|
| 259 |
+
(
|
| 260 |
+
"PegasusTokenizer" if is_sentencepiece_available() else None,
|
| 261 |
+
"PegasusTokenizerFast" if is_tokenizers_available() else None,
|
| 262 |
+
),
|
| 263 |
+
),
|
| 264 |
+
(
|
| 265 |
+
"perceiver",
|
| 266 |
+
(
|
| 267 |
+
"PerceiverTokenizer",
|
| 268 |
+
None,
|
| 269 |
+
),
|
| 270 |
+
),
|
| 271 |
+
("phobert", ("PhobertTokenizer", None)),
|
| 272 |
+
("pix2struct", ("T5Tokenizer", "T5TokenizerFast" if is_tokenizers_available() else None)),
|
| 273 |
+
("plbart", ("PLBartTokenizer" if is_sentencepiece_available() else None, None)),
|
| 274 |
+
("prophetnet", ("ProphetNetTokenizer", None)),
|
| 275 |
+
("qdqbert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 276 |
+
("rag", ("RagTokenizer", None)),
|
| 277 |
+
("realm", ("RealmTokenizer", "RealmTokenizerFast" if is_tokenizers_available() else None)),
|
| 278 |
+
(
|
| 279 |
+
"reformer",
|
| 280 |
+
(
|
| 281 |
+
"ReformerTokenizer" if is_sentencepiece_available() else None,
|
| 282 |
+
"ReformerTokenizerFast" if is_tokenizers_available() else None,
|
| 283 |
+
),
|
| 284 |
+
),
|
| 285 |
+
(
|
| 286 |
+
"rembert",
|
| 287 |
+
(
|
| 288 |
+
"RemBertTokenizer" if is_sentencepiece_available() else None,
|
| 289 |
+
"RemBertTokenizerFast" if is_tokenizers_available() else None,
|
| 290 |
+
),
|
| 291 |
+
),
|
| 292 |
+
("retribert", ("RetriBertTokenizer", "RetriBertTokenizerFast" if is_tokenizers_available() else None)),
|
| 293 |
+
("roberta", ("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None)),
|
| 294 |
+
(
|
| 295 |
+
"roberta-prelayernorm",
|
| 296 |
+
("RobertaTokenizer", "RobertaTokenizerFast" if is_tokenizers_available() else None),
|
| 297 |
+
),
|
| 298 |
+
("roc_bert", ("RoCBertTokenizer", None)),
|
| 299 |
+
("roformer", ("RoFormerTokenizer", "RoFormerTokenizerFast" if is_tokenizers_available() else None)),
|
| 300 |
+
("rwkv", (None, "GPTNeoXTokenizerFast" if is_tokenizers_available() else None)),
|
| 301 |
+
("speech_to_text", ("Speech2TextTokenizer" if is_sentencepiece_available() else None, None)),
|
| 302 |
+
("speech_to_text_2", ("Speech2Text2Tokenizer", None)),
|
| 303 |
+
("speecht5", ("SpeechT5Tokenizer" if is_sentencepiece_available() else None, None)),
|
| 304 |
+
("splinter", ("SplinterTokenizer", "SplinterTokenizerFast")),
|
| 305 |
+
(
|
| 306 |
+
"squeezebert",
|
| 307 |
+
("SqueezeBertTokenizer", "SqueezeBertTokenizerFast" if is_tokenizers_available() else None),
|
| 308 |
+
),
|
| 309 |
+
(
|
| 310 |
+
"switch_transformers",
|
| 311 |
+
(
|
| 312 |
+
"T5Tokenizer" if is_sentencepiece_available() else None,
|
| 313 |
+
"T5TokenizerFast" if is_tokenizers_available() else None,
|
| 314 |
+
),
|
| 315 |
+
),
|
| 316 |
+
(
|
| 317 |
+
"t5",
|
| 318 |
+
(
|
| 319 |
+
"T5Tokenizer" if is_sentencepiece_available() else None,
|
| 320 |
+
"T5TokenizerFast" if is_tokenizers_available() else None,
|
| 321 |
+
),
|
| 322 |
+
),
|
| 323 |
+
("tapas", ("TapasTokenizer", None)),
|
| 324 |
+
("tapex", ("TapexTokenizer", None)),
|
| 325 |
+
("transfo-xl", ("TransfoXLTokenizer", None)),
|
| 326 |
+
("vilt", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 327 |
+
("visual_bert", ("BertTokenizer", "BertTokenizerFast" if is_tokenizers_available() else None)),
|
| 328 |
+
("wav2vec2", ("Wav2Vec2CTCTokenizer", None)),
|
| 329 |
+
("wav2vec2-conformer", ("Wav2Vec2CTCTokenizer", None)),
|
| 330 |
+
("wav2vec2_phoneme", ("Wav2Vec2PhonemeCTCTokenizer", None)),
|
| 331 |
+
("whisper", ("WhisperTokenizer", "WhisperTokenizerFast" if is_tokenizers_available() else None)),
|
| 332 |
+
("xclip", ("CLIPTokenizer", "CLIPTokenizerFast" if is_tokenizers_available() else None)),
|
| 333 |
+
(
|
| 334 |
+
"xglm",
|
| 335 |
+
(
|
| 336 |
+
"XGLMTokenizer" if is_sentencepiece_available() else None,
|
| 337 |
+
"XGLMTokenizerFast" if is_tokenizers_available() else None,
|
| 338 |
+
),
|
| 339 |
+
),
|
| 340 |
+
("xlm", ("XLMTokenizer", None)),
|
| 341 |
+
("xlm-prophetnet", ("XLMProphetNetTokenizer" if is_sentencepiece_available() else None, None)),
|
| 342 |
+
(
|
| 343 |
+
"xlm-roberta",
|
| 344 |
+
(
|
| 345 |
+
"XLMRobertaTokenizer" if is_sentencepiece_available() else None,
|
| 346 |
+
"XLMRobertaTokenizerFast" if is_tokenizers_available() else None,
|
| 347 |
+
),
|
| 348 |
+
),
|
| 349 |
+
(
|
| 350 |
+
"xlm-roberta-xl",
|
| 351 |
+
(
|
| 352 |
+
"XLMRobertaTokenizer" if is_sentencepiece_available() else None,
|
| 353 |
+
"XLMRobertaTokenizerFast" if is_tokenizers_available() else None,
|
| 354 |
+
),
|
| 355 |
+
),
|
| 356 |
+
(
|
| 357 |
+
"xlnet",
|
| 358 |
+
(
|
| 359 |
+
"XLNetTokenizer" if is_sentencepiece_available() else None,
|
| 360 |
+
"XLNetTokenizerFast" if is_tokenizers_available() else None,
|
| 361 |
+
),
|
| 362 |
+
),
|
| 363 |
+
(
|
| 364 |
+
"xmod",
|
| 365 |
+
(
|
| 366 |
+
"XLMRobertaTokenizer" if is_sentencepiece_available() else None,
|
| 367 |
+
"XLMRobertaTokenizerFast" if is_tokenizers_available() else None,
|
| 368 |
+
),
|
| 369 |
+
),
|
| 370 |
+
(
|
| 371 |
+
"yoso",
|
| 372 |
+
(
|
| 373 |
+
"AlbertTokenizer" if is_sentencepiece_available() else None,
|
| 374 |
+
"AlbertTokenizerFast" if is_tokenizers_available() else None,
|
| 375 |
+
),
|
| 376 |
+
),
|
| 377 |
+
]
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
TOKENIZER_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, TOKENIZER_MAPPING_NAMES)
|
| 381 |
+
|
| 382 |
+
CONFIG_TO_TYPE = {v: k for k, v in CONFIG_MAPPING_NAMES.items()}
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def tokenizer_class_from_name(class_name: str):
|
| 386 |
+
if class_name == "PreTrainedTokenizerFast":
|
| 387 |
+
return PreTrainedTokenizerFast
|
| 388 |
+
|
| 389 |
+
for module_name, tokenizers in TOKENIZER_MAPPING_NAMES.items():
|
| 390 |
+
if class_name in tokenizers:
|
| 391 |
+
module_name = model_type_to_module_name(module_name)
|
| 392 |
+
|
| 393 |
+
module = importlib.import_module(f".{module_name}", "transformers.models")
|
| 394 |
+
try:
|
| 395 |
+
return getattr(module, class_name)
|
| 396 |
+
except AttributeError:
|
| 397 |
+
continue
|
| 398 |
+
|
| 399 |
+
for config, tokenizers in TOKENIZER_MAPPING._extra_content.items():
|
| 400 |
+
for tokenizer in tokenizers:
|
| 401 |
+
if getattr(tokenizer, "__name__", None) == class_name:
|
| 402 |
+
return tokenizer
|
| 403 |
+
|
| 404 |
+
# We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
|
| 405 |
+
# init and we return the proper dummy to get an appropriate error message.
|
| 406 |
+
main_module = importlib.import_module("transformers")
|
| 407 |
+
if hasattr(main_module, class_name):
|
| 408 |
+
return getattr(main_module, class_name)
|
| 409 |
+
|
| 410 |
+
return None
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def get_tokenizer_config(
|
| 414 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
| 415 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
| 416 |
+
force_download: bool = False,
|
| 417 |
+
resume_download: bool = False,
|
| 418 |
+
proxies: Optional[Dict[str, str]] = None,
|
| 419 |
+
use_auth_token: Optional[Union[bool, str]] = None,
|
| 420 |
+
revision: Optional[str] = None,
|
| 421 |
+
local_files_only: bool = False,
|
| 422 |
+
subfolder: str = "",
|
| 423 |
+
**kwargs,
|
| 424 |
+
):
|
| 425 |
+
"""
|
| 426 |
+
Loads the tokenizer configuration from a pretrained model tokenizer configuration.
|
| 427 |
+
|
| 428 |
+
Args:
|
| 429 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 430 |
+
This can be either:
|
| 431 |
+
|
| 432 |
+
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on
|
| 433 |
+
huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced
|
| 434 |
+
under a user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 435 |
+
- a path to a *directory* containing a configuration file saved using the
|
| 436 |
+
[`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
|
| 437 |
+
|
| 438 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 439 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
|
| 440 |
+
cache should not be used.
|
| 441 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 442 |
+
Whether or not to force to (re-)download the configuration files and override the cached versions if they
|
| 443 |
+
exist.
|
| 444 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 445 |
+
Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists.
|
| 446 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 447 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 448 |
+
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
|
| 449 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 450 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
|
| 451 |
+
when running `huggingface-cli login` (stored in `~/.huggingface`).
|
| 452 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 453 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 454 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 455 |
+
identifier allowed by git.
|
| 456 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 457 |
+
If `True`, will only try to load the tokenizer configuration from local files.
|
| 458 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
| 459 |
+
In case the tokenizer config is located inside a subfolder of the model repo on huggingface.co, you can
|
| 460 |
+
specify the folder name here.
|
| 461 |
+
|
| 462 |
+
<Tip>
|
| 463 |
+
|
| 464 |
+
Passing `use_auth_token=True` is required when you want to use a private model.
|
| 465 |
+
|
| 466 |
+
</Tip>
|
| 467 |
+
|
| 468 |
+
Returns:
|
| 469 |
+
`Dict`: The configuration of the tokenizer.
|
| 470 |
+
|
| 471 |
+
Examples:
|
| 472 |
+
|
| 473 |
+
```python
|
| 474 |
+
# Download configuration from huggingface.co and cache.
|
| 475 |
+
tokenizer_config = get_tokenizer_config("bert-base-uncased")
|
| 476 |
+
# This model does not have a tokenizer config so the result will be an empty dict.
|
| 477 |
+
tokenizer_config = get_tokenizer_config("xlm-roberta-base")
|
| 478 |
+
|
| 479 |
+
# Save a pretrained tokenizer locally and you can reload its config
|
| 480 |
+
from transformers import AutoTokenizer
|
| 481 |
+
|
| 482 |
+
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
|
| 483 |
+
tokenizer.save_pretrained("tokenizer-test")
|
| 484 |
+
tokenizer_config = get_tokenizer_config("tokenizer-test")
|
| 485 |
+
```"""
|
| 486 |
+
commit_hash = kwargs.get("_commit_hash", None)
|
| 487 |
+
resolved_config_file = cached_file(
|
| 488 |
+
pretrained_model_name_or_path,
|
| 489 |
+
TOKENIZER_CONFIG_FILE,
|
| 490 |
+
cache_dir=cache_dir,
|
| 491 |
+
force_download=force_download,
|
| 492 |
+
resume_download=resume_download,
|
| 493 |
+
proxies=proxies,
|
| 494 |
+
use_auth_token=use_auth_token,
|
| 495 |
+
revision=revision,
|
| 496 |
+
local_files_only=local_files_only,
|
| 497 |
+
subfolder=subfolder,
|
| 498 |
+
_raise_exceptions_for_missing_entries=False,
|
| 499 |
+
_raise_exceptions_for_connection_errors=False,
|
| 500 |
+
_commit_hash=commit_hash,
|
| 501 |
+
)
|
| 502 |
+
if resolved_config_file is None:
|
| 503 |
+
logger.info("Could not locate the tokenizer configuration file, will try to use the model config instead.")
|
| 504 |
+
return {}
|
| 505 |
+
commit_hash = extract_commit_hash(resolved_config_file, commit_hash)
|
| 506 |
+
|
| 507 |
+
with open(resolved_config_file, encoding="utf-8") as reader:
|
| 508 |
+
result = json.load(reader)
|
| 509 |
+
result["_commit_hash"] = commit_hash
|
| 510 |
+
return result
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class AutoTokenizer:
|
| 514 |
+
r"""
|
| 515 |
+
This is a generic tokenizer class that will be instantiated as one of the tokenizer classes of the library when
|
| 516 |
+
created with the [`AutoTokenizer.from_pretrained`] class method.
|
| 517 |
+
|
| 518 |
+
This class cannot be instantiated directly using `__init__()` (throws an error).
|
| 519 |
+
"""
|
| 520 |
+
|
| 521 |
+
def __init__(self):
|
| 522 |
+
raise EnvironmentError(
|
| 523 |
+
"AutoTokenizer is designed to be instantiated "
|
| 524 |
+
"using the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)` method."
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
@classmethod
|
| 528 |
+
@replace_list_option_in_docstrings(TOKENIZER_MAPPING_NAMES)
|
| 529 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
|
| 530 |
+
r"""
|
| 531 |
+
Instantiate one of the tokenizer classes of the library from a pretrained model vocabulary.
|
| 532 |
+
|
| 533 |
+
The tokenizer class to instantiate is selected based on the `model_type` property of the config object (either
|
| 534 |
+
passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by
|
| 535 |
+
falling back to using pattern matching on `pretrained_model_name_or_path`:
|
| 536 |
+
|
| 537 |
+
List options
|
| 538 |
+
|
| 539 |
+
Params:
|
| 540 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 541 |
+
Can be either:
|
| 542 |
+
|
| 543 |
+
- A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co.
|
| 544 |
+
Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
|
| 545 |
+
user or organization name, like `dbmdz/bert-base-german-cased`.
|
| 546 |
+
- A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved
|
| 547 |
+
using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.
|
| 548 |
+
- A path or url to a single saved vocabulary file if and only if the tokenizer only requires a
|
| 549 |
+
single vocabulary file (like Bert or XLNet), e.g.: `./my_model_directory/vocab.txt`. (Not
|
| 550 |
+
applicable to all derived classes)
|
| 551 |
+
inputs (additional positional arguments, *optional*):
|
| 552 |
+
Will be passed along to the Tokenizer `__init__()` method.
|
| 553 |
+
config ([`PretrainedConfig`], *optional*)
|
| 554 |
+
The configuration object used to dertermine the tokenizer class to instantiate.
|
| 555 |
+
cache_dir (`str` or `os.PathLike`, *optional*):
|
| 556 |
+
Path to a directory in which a downloaded pretrained model configuration should be cached if the
|
| 557 |
+
standard cache should not be used.
|
| 558 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 559 |
+
Whether or not to force the (re-)download the model weights and configuration files and override the
|
| 560 |
+
cached versions if they exist.
|
| 561 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 562 |
+
Whether or not to delete incompletely received files. Will attempt to resume the download if such a
|
| 563 |
+
file exists.
|
| 564 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 565 |
+
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
|
| 566 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 567 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 568 |
+
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
|
| 569 |
+
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
|
| 570 |
+
identifier allowed by git.
|
| 571 |
+
subfolder (`str`, *optional*):
|
| 572 |
+
In case the relevant files are located inside a subfolder of the model repo on huggingface.co (e.g. for
|
| 573 |
+
facebook/rag-token-base), specify it here.
|
| 574 |
+
use_fast (`bool`, *optional*, defaults to `True`):
|
| 575 |
+
Use a [fast Rust-based tokenizer](https://huggingface.co/docs/tokenizers/index) if it is supported for
|
| 576 |
+
a given model. If a fast tokenizer is not available for a given model, a normal Python-based tokenizer
|
| 577 |
+
is returned instead.
|
| 578 |
+
tokenizer_type (`str`, *optional*):
|
| 579 |
+
Tokenizer type to be loaded.
|
| 580 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 581 |
+
Whether or not to allow for custom models defined on the Hub in their own modeling files. This option
|
| 582 |
+
should only be set to `True` for repositories you trust and in which you have read the code, as it will
|
| 583 |
+
execute code present on the Hub on your local machine.
|
| 584 |
+
kwargs (additional keyword arguments, *optional*):
|
| 585 |
+
Will be passed to the Tokenizer `__init__()` method. Can be used to set special tokens like
|
| 586 |
+
`bos_token`, `eos_token`, `unk_token`, `sep_token`, `pad_token`, `cls_token`, `mask_token`,
|
| 587 |
+
`additional_special_tokens`. See parameters in the `__init__()` for more details.
|
| 588 |
+
|
| 589 |
+
Examples:
|
| 590 |
+
|
| 591 |
+
```python
|
| 592 |
+
>>> from transformers import AutoTokenizer
|
| 593 |
+
|
| 594 |
+
>>> # Download vocabulary from huggingface.co and cache.
|
| 595 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
|
| 596 |
+
|
| 597 |
+
>>> # Download vocabulary from huggingface.co (user-uploaded) and cache.
|
| 598 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("dbmdz/bert-base-german-cased")
|
| 599 |
+
|
| 600 |
+
>>> # If vocabulary files are in a directory (e.g. tokenizer was saved using *save_pretrained('./test/saved_model/')*)
|
| 601 |
+
>>> # tokenizer = AutoTokenizer.from_pretrained("./test/bert_saved_model/")
|
| 602 |
+
|
| 603 |
+
>>> # Download vocabulary from huggingface.co and define model-specific arguments
|
| 604 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("roberta-base", add_prefix_space=True)
|
| 605 |
+
```"""
|
| 606 |
+
config = kwargs.pop("config", None)
|
| 607 |
+
kwargs["_from_auto"] = True
|
| 608 |
+
|
| 609 |
+
use_fast = kwargs.pop("use_fast", True)
|
| 610 |
+
tokenizer_type = kwargs.pop("tokenizer_type", None)
|
| 611 |
+
trust_remote_code = kwargs.pop("trust_remote_code", False)
|
| 612 |
+
|
| 613 |
+
# First, let's see whether the tokenizer_type is passed so that we can leverage it
|
| 614 |
+
if tokenizer_type is not None:
|
| 615 |
+
tokenizer_class = None
|
| 616 |
+
tokenizer_class_tuple = TOKENIZER_MAPPING_NAMES.get(tokenizer_type, None)
|
| 617 |
+
|
| 618 |
+
if tokenizer_class_tuple is None:
|
| 619 |
+
raise ValueError(
|
| 620 |
+
f"Passed `tokenizer_type` {tokenizer_type} does not exist. `tokenizer_type` should be one of "
|
| 621 |
+
f"{', '.join(c for c in TOKENIZER_MAPPING_NAMES.keys())}."
|
| 622 |
+
)
|
| 623 |
+
|
| 624 |
+
tokenizer_class_name, tokenizer_fast_class_name = tokenizer_class_tuple
|
| 625 |
+
|
| 626 |
+
if use_fast:
|
| 627 |
+
if tokenizer_fast_class_name is not None:
|
| 628 |
+
tokenizer_class = tokenizer_class_from_name(tokenizer_fast_class_name)
|
| 629 |
+
else:
|
| 630 |
+
logger.warning(
|
| 631 |
+
"`use_fast` is set to `True` but the tokenizer class does not have a fast version. "
|
| 632 |
+
" Falling back to the slow version."
|
| 633 |
+
)
|
| 634 |
+
if tokenizer_class is None:
|
| 635 |
+
tokenizer_class = tokenizer_class_from_name(tokenizer_class_name)
|
| 636 |
+
|
| 637 |
+
if tokenizer_class is None:
|
| 638 |
+
raise ValueError(f"Tokenizer class {tokenizer_class_name} is not currently imported.")
|
| 639 |
+
|
| 640 |
+
return tokenizer_class.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
|
| 641 |
+
|
| 642 |
+
# Next, let's try to use the tokenizer_config file to get the tokenizer class.
|
| 643 |
+
tokenizer_config = get_tokenizer_config(pretrained_model_name_or_path, **kwargs)
|
| 644 |
+
if "_commit_hash" in tokenizer_config:
|
| 645 |
+
kwargs["_commit_hash"] = tokenizer_config["_commit_hash"]
|
| 646 |
+
config_tokenizer_class = tokenizer_config.get("tokenizer_class")
|
| 647 |
+
tokenizer_auto_map = None
|
| 648 |
+
if "auto_map" in tokenizer_config:
|
| 649 |
+
if isinstance(tokenizer_config["auto_map"], (tuple, list)):
|
| 650 |
+
# Legacy format for dynamic tokenizers
|
| 651 |
+
tokenizer_auto_map = tokenizer_config["auto_map"]
|
| 652 |
+
else:
|
| 653 |
+
tokenizer_auto_map = tokenizer_config["auto_map"].get("AutoTokenizer", None)
|
| 654 |
+
|
| 655 |
+
# If that did not work, let's try to use the config.
|
| 656 |
+
if config_tokenizer_class is None:
|
| 657 |
+
if not isinstance(config, PretrainedConfig):
|
| 658 |
+
config = AutoConfig.from_pretrained(
|
| 659 |
+
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
|
| 660 |
+
)
|
| 661 |
+
config_tokenizer_class = config.tokenizer_class
|
| 662 |
+
if hasattr(config, "auto_map") and "AutoTokenizer" in config.auto_map:
|
| 663 |
+
tokenizer_auto_map = config.auto_map["AutoTokenizer"]
|
| 664 |
+
|
| 665 |
+
# If we have the tokenizer class from the tokenizer config or the model config we're good!
|
| 666 |
+
if config_tokenizer_class is not None:
|
| 667 |
+
tokenizer_class = None
|
| 668 |
+
if tokenizer_auto_map is not None:
|
| 669 |
+
if not trust_remote_code:
|
| 670 |
+
raise ValueError(
|
| 671 |
+
f"Loading {pretrained_model_name_or_path} requires you to execute the tokenizer file in that"
|
| 672 |
+
" repo on your local machine. Make sure you have read the code there to avoid malicious use,"
|
| 673 |
+
" then set the option `trust_remote_code=True` to remove this error."
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
if use_fast and tokenizer_auto_map[1] is not None:
|
| 677 |
+
class_ref = tokenizer_auto_map[1]
|
| 678 |
+
else:
|
| 679 |
+
class_ref = tokenizer_auto_map[0]
|
| 680 |
+
tokenizer_class = get_class_from_dynamic_module(class_ref, pretrained_model_name_or_path, **kwargs)
|
| 681 |
+
|
| 682 |
+
elif use_fast and not config_tokenizer_class.endswith("Fast"):
|
| 683 |
+
tokenizer_class_candidate = f"{config_tokenizer_class}Fast"
|
| 684 |
+
tokenizer_class = tokenizer_class_from_name(tokenizer_class_candidate)
|
| 685 |
+
if tokenizer_class is None:
|
| 686 |
+
tokenizer_class_candidate = config_tokenizer_class
|
| 687 |
+
tokenizer_class = tokenizer_class_from_name(tokenizer_class_candidate)
|
| 688 |
+
|
| 689 |
+
if tokenizer_class is None:
|
| 690 |
+
raise ValueError(
|
| 691 |
+
f"Tokenizer class {tokenizer_class_candidate} does not exist or is not currently imported."
|
| 692 |
+
)
|
| 693 |
+
return tokenizer_class.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
|
| 694 |
+
|
| 695 |
+
# Otherwise we have to be creative.
|
| 696 |
+
# if model is an encoder decoder, the encoder tokenizer class is used by default
|
| 697 |
+
if isinstance(config, EncoderDecoderConfig):
|
| 698 |
+
if type(config.decoder) is not type(config.encoder): # noqa: E721
|
| 699 |
+
logger.warning(
|
| 700 |
+
f"The encoder model config class: {config.encoder.__class__} is different from the decoder model "
|
| 701 |
+
f"config class: {config.decoder.__class__}. It is not recommended to use the "
|
| 702 |
+
"`AutoTokenizer.from_pretrained()` method in this case. Please use the encoder and decoder "
|
| 703 |
+
"specific tokenizer classes."
|
| 704 |
+
)
|
| 705 |
+
config = config.encoder
|
| 706 |
+
|
| 707 |
+
model_type = config_class_to_model_type(type(config).__name__)
|
| 708 |
+
if model_type is not None:
|
| 709 |
+
tokenizer_class_py, tokenizer_class_fast = TOKENIZER_MAPPING[type(config)]
|
| 710 |
+
if tokenizer_class_fast and (use_fast or tokenizer_class_py is None):
|
| 711 |
+
return tokenizer_class_fast.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
|
| 712 |
+
else:
|
| 713 |
+
if tokenizer_class_py is not None:
|
| 714 |
+
return tokenizer_class_py.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
|
| 715 |
+
else:
|
| 716 |
+
raise ValueError(
|
| 717 |
+
"This tokenizer cannot be instantiated. Please make sure you have `sentencepiece` installed "
|
| 718 |
+
"in order to use this tokenizer."
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
raise ValueError(
|
| 722 |
+
f"Unrecognized configuration class {config.__class__} to build an AutoTokenizer.\n"
|
| 723 |
+
f"Model type should be one of {', '.join(c.__name__ for c in TOKENIZER_MAPPING.keys())}."
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
def register(config_class, slow_tokenizer_class=None, fast_tokenizer_class=None):
|
| 727 |
+
"""
|
| 728 |
+
Register a new tokenizer in this mapping.
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
Args:
|
| 732 |
+
config_class ([`PretrainedConfig`]):
|
| 733 |
+
The configuration corresponding to the model to register.
|
| 734 |
+
slow_tokenizer_class ([`PretrainedTokenizer`], *optional*):
|
| 735 |
+
The slow tokenizer to register.
|
| 736 |
+
slow_tokenizer_class ([`PretrainedTokenizerFast`], *optional*):
|
| 737 |
+
The fast tokenizer to register.
|
| 738 |
+
"""
|
| 739 |
+
if slow_tokenizer_class is None and fast_tokenizer_class is None:
|
| 740 |
+
raise ValueError("You need to pass either a `slow_tokenizer_class` or a `fast_tokenizer_class")
|
| 741 |
+
if slow_tokenizer_class is not None and issubclass(slow_tokenizer_class, PreTrainedTokenizerFast):
|
| 742 |
+
raise ValueError("You passed a fast tokenizer in the `slow_tokenizer_class`.")
|
| 743 |
+
if fast_tokenizer_class is not None and issubclass(fast_tokenizer_class, PreTrainedTokenizer):
|
| 744 |
+
raise ValueError("You passed a slow tokenizer in the `fast_tokenizer_class`.")
|
| 745 |
+
|
| 746 |
+
if (
|
| 747 |
+
slow_tokenizer_class is not None
|
| 748 |
+
and fast_tokenizer_class is not None
|
| 749 |
+
and issubclass(fast_tokenizer_class, PreTrainedTokenizerFast)
|
| 750 |
+
and fast_tokenizer_class.slow_tokenizer_class != slow_tokenizer_class
|
| 751 |
+
):
|
| 752 |
+
raise ValueError(
|
| 753 |
+
"The fast tokenizer class you are passing has a `slow_tokenizer_class` attribute that is not "
|
| 754 |
+
"consistent with the slow tokenizer class you passed (fast tokenizer has "
|
| 755 |
+
f"{fast_tokenizer_class.slow_tokenizer_class} and you passed {slow_tokenizer_class}. Fix one of those "
|
| 756 |
+
"so they match!"
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
# Avoid resetting a set slow/fast tokenizer if we are passing just the other ones.
|
| 760 |
+
if config_class in TOKENIZER_MAPPING._extra_content:
|
| 761 |
+
existing_slow, existing_fast = TOKENIZER_MAPPING[config_class]
|
| 762 |
+
if slow_tokenizer_class is None:
|
| 763 |
+
slow_tokenizer_class = existing_slow
|
| 764 |
+
if fast_tokenizer_class is None:
|
| 765 |
+
fast_tokenizer_class = existing_fast
|
| 766 |
+
|
| 767 |
+
TOKENIZER_MAPPING.register(config_class, (slow_tokenizer_class, fast_tokenizer_class))
|