ZTWHHH commited on
Commit
bbd4a0d
·
verified ·
1 Parent(s): c4ca40c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. pllava/lib/python3.10/site-packages/transformers/models/dpt/__init__.py +76 -0
  2. pllava/lib/python3.10/site-packages/transformers/models/fnet/__init__.py +107 -0
  3. pllava/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/configuration_fnet.cpython-310.pyc +0 -0
  4. pllava/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/modeling_fnet.cpython-310.pyc +0 -0
  5. pllava/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet.cpython-310.pyc +0 -0
  6. pllava/lib/python3.10/site-packages/transformers/models/fnet/configuration_fnet.py +122 -0
  7. pllava/lib/python3.10/site-packages/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py +157 -0
  8. pllava/lib/python3.10/site-packages/transformers/models/fnet/modeling_fnet.py +1185 -0
  9. pllava/lib/python3.10/site-packages/transformers/models/fnet/tokenization_fnet.py +351 -0
  10. pllava/lib/python3.10/site-packages/transformers/models/fnet/tokenization_fnet_fast.py +204 -0
  11. pllava/lib/python3.10/site-packages/transformers/models/kosmos2/__init__.py +64 -0
  12. pllava/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/__init__.cpython-310.pyc +0 -0
  13. pllava/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/configuration_kosmos2.cpython-310.pyc +0 -0
  14. pllava/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  15. pllava/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/modeling_kosmos2.cpython-310.pyc +0 -0
  16. pllava/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/processing_kosmos2.cpython-310.pyc +0 -0
  17. pllava/lib/python3.10/site-packages/transformers/models/kosmos2/configuration_kosmos2.py +299 -0
  18. pllava/lib/python3.10/site-packages/transformers/models/kosmos2/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.py +77 -0
  19. pllava/lib/python3.10/site-packages/transformers/models/kosmos2/modeling_kosmos2.py +2056 -0
  20. pllava/lib/python3.10/site-packages/transformers/models/kosmos2/processing_kosmos2.py +666 -0
  21. pllava/lib/python3.10/site-packages/transformers/models/mgp_str/__init__.py +62 -0
  22. pllava/lib/python3.10/site-packages/transformers/models/mgp_str/__pycache__/__init__.cpython-310.pyc +0 -0
  23. pllava/lib/python3.10/site-packages/transformers/models/mgp_str/__pycache__/configuration_mgp_str.cpython-310.pyc +0 -0
  24. pllava/lib/python3.10/site-packages/transformers/models/mgp_str/__pycache__/processing_mgp_str.cpython-310.pyc +0 -0
  25. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/__init__.cpython-310.pyc +0 -0
  26. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/configuration_mobilebert.cpython-310.pyc +0 -0
  27. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/convert_mobilebert_original_tf_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  28. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/modeling_mobilebert.cpython-310.pyc +0 -0
  29. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/modeling_tf_mobilebert.cpython-310.pyc +0 -0
  30. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/tokenization_mobilebert.cpython-310.pyc +0 -0
  31. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/tokenization_mobilebert_fast.cpython-310.pyc +0 -0
  32. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/configuration_mobilebert.py +188 -0
  33. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/convert_mobilebert_original_tf_checkpoint_to_pytorch.py +58 -0
  34. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/modeling_mobilebert.py +1617 -0
  35. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/modeling_tf_mobilebert.py +1973 -0
  36. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/tokenization_mobilebert.py +518 -0
  37. pllava/lib/python3.10/site-packages/transformers/models/mobilebert/tokenization_mobilebert_fast.py +189 -0
  38. pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/__init__.py +68 -0
  39. pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/__pycache__/__init__.cpython-310.pyc +0 -0
  40. pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/__pycache__/configuration_nllb_moe.cpython-310.pyc +0 -0
  41. pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/__pycache__/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  42. pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/__pycache__/modeling_nllb_moe.cpython-310.pyc +0 -0
  43. pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/configuration_nllb_moe.py +219 -0
  44. pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.py +160 -0
  45. pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/modeling_nllb_moe.py +1794 -0
  46. pllava/lib/python3.10/site-packages/transformers/models/qdqbert/__init__.py +71 -0
  47. pllava/lib/python3.10/site-packages/transformers/models/qdqbert/__pycache__/__init__.cpython-310.pyc +0 -0
  48. pllava/lib/python3.10/site-packages/transformers/models/qdqbert/__pycache__/configuration_qdqbert.cpython-310.pyc +0 -0
  49. pllava/lib/python3.10/site-packages/transformers/models/qdqbert/__pycache__/modeling_qdqbert.cpython-310.pyc +0 -0
  50. pllava/lib/python3.10/site-packages/transformers/models/qdqbert/configuration_qdqbert.py +125 -0
pllava/lib/python3.10/site-packages/transformers/models/dpt/__init__.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available
17
+ from ...utils import OptionalDependencyNotAvailable
18
+
19
+
20
+ _import_structure = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]}
21
+
22
+ try:
23
+ if not is_vision_available():
24
+ raise OptionalDependencyNotAvailable()
25
+ except OptionalDependencyNotAvailable:
26
+ pass
27
+ else:
28
+ _import_structure["feature_extraction_dpt"] = ["DPTFeatureExtractor"]
29
+ _import_structure["image_processing_dpt"] = ["DPTImageProcessor"]
30
+
31
+ try:
32
+ if not is_torch_available():
33
+ raise OptionalDependencyNotAvailable()
34
+ except OptionalDependencyNotAvailable:
35
+ pass
36
+ else:
37
+ _import_structure["modeling_dpt"] = [
38
+ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST",
39
+ "DPTForDepthEstimation",
40
+ "DPTForSemanticSegmentation",
41
+ "DPTModel",
42
+ "DPTPreTrainedModel",
43
+ ]
44
+
45
+
46
+ if TYPE_CHECKING:
47
+ from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig
48
+
49
+ try:
50
+ if not is_vision_available():
51
+ raise OptionalDependencyNotAvailable()
52
+ except OptionalDependencyNotAvailable:
53
+ pass
54
+ else:
55
+ from .feature_extraction_dpt import DPTFeatureExtractor
56
+ from .image_processing_dpt import DPTImageProcessor
57
+
58
+ try:
59
+ if not is_torch_available():
60
+ raise OptionalDependencyNotAvailable()
61
+ except OptionalDependencyNotAvailable:
62
+ pass
63
+ else:
64
+ from .modeling_dpt import (
65
+ DPT_PRETRAINED_MODEL_ARCHIVE_LIST,
66
+ DPTForDepthEstimation,
67
+ DPTForSemanticSegmentation,
68
+ DPTModel,
69
+ DPTPreTrainedModel,
70
+ )
71
+
72
+
73
+ else:
74
+ import sys
75
+
76
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
pllava/lib/python3.10/site-packages/transformers/models/fnet/__init__.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_sentencepiece_available,
20
+ is_tokenizers_available,
21
+ is_torch_available,
22
+ )
23
+
24
+
25
+ _import_structure = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]}
26
+
27
+ try:
28
+ if not is_sentencepiece_available():
29
+ raise OptionalDependencyNotAvailable()
30
+ except OptionalDependencyNotAvailable:
31
+ pass
32
+ else:
33
+ _import_structure["tokenization_fnet"] = ["FNetTokenizer"]
34
+
35
+ try:
36
+ if not is_tokenizers_available():
37
+ raise OptionalDependencyNotAvailable()
38
+ except OptionalDependencyNotAvailable:
39
+ pass
40
+ else:
41
+ _import_structure["tokenization_fnet_fast"] = ["FNetTokenizerFast"]
42
+
43
+ try:
44
+ if not is_torch_available():
45
+ raise OptionalDependencyNotAvailable()
46
+ except OptionalDependencyNotAvailable:
47
+ pass
48
+ else:
49
+ _import_structure["modeling_fnet"] = [
50
+ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST",
51
+ "FNetForMaskedLM",
52
+ "FNetForMultipleChoice",
53
+ "FNetForNextSentencePrediction",
54
+ "FNetForPreTraining",
55
+ "FNetForQuestionAnswering",
56
+ "FNetForSequenceClassification",
57
+ "FNetForTokenClassification",
58
+ "FNetLayer",
59
+ "FNetModel",
60
+ "FNetPreTrainedModel",
61
+ ]
62
+
63
+
64
+ if TYPE_CHECKING:
65
+ from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig
66
+
67
+ try:
68
+ if not is_sentencepiece_available():
69
+ raise OptionalDependencyNotAvailable()
70
+ except OptionalDependencyNotAvailable:
71
+ pass
72
+ else:
73
+ from .tokenization_fnet import FNetTokenizer
74
+
75
+ try:
76
+ if not is_tokenizers_available():
77
+ raise OptionalDependencyNotAvailable()
78
+ except OptionalDependencyNotAvailable:
79
+ pass
80
+ else:
81
+ from .tokenization_fnet_fast import FNetTokenizerFast
82
+
83
+ try:
84
+ if not is_torch_available():
85
+ raise OptionalDependencyNotAvailable()
86
+ except OptionalDependencyNotAvailable:
87
+ pass
88
+ else:
89
+ from .modeling_fnet import (
90
+ FNET_PRETRAINED_MODEL_ARCHIVE_LIST,
91
+ FNetForMaskedLM,
92
+ FNetForMultipleChoice,
93
+ FNetForNextSentencePrediction,
94
+ FNetForPreTraining,
95
+ FNetForQuestionAnswering,
96
+ FNetForSequenceClassification,
97
+ FNetForTokenClassification,
98
+ FNetLayer,
99
+ FNetModel,
100
+ FNetPreTrainedModel,
101
+ )
102
+
103
+
104
+ else:
105
+ import sys
106
+
107
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
pllava/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/configuration_fnet.cpython-310.pyc ADDED
Binary file (5.08 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/modeling_fnet.cpython-310.pyc ADDED
Binary file (35.9 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet.cpython-310.pyc ADDED
Binary file (12.9 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/fnet/configuration_fnet.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 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
+ """ FNet model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ FNET_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/config.json",
25
+ "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/config.json",
26
+ # See all FNet models at https://huggingface.co/models?filter=fnet
27
+ }
28
+
29
+
30
+ class FNetConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`FNetModel`]. It is used to instantiate an FNet
33
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
34
+ defaults will yield a similar configuration to that of the FNet
35
+ [google/fnet-base](https://huggingface.co/google/fnet-base) architecture.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32000):
43
+ Vocabulary size of the FNet model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`FNetModel`] or [`TFFNetModel`].
45
+ hidden_size (`int`, *optional*, defaults to 768):
46
+ Dimension of the encoder layers and the pooler layer.
47
+ num_hidden_layers (`int`, *optional*, defaults to 12):
48
+ Number of hidden layers in the Transformer encoder.
49
+ intermediate_size (`int`, *optional*, defaults to 3072):
50
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
51
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
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 probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
56
+ max_position_embeddings (`int`, *optional*, defaults to 512):
57
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
58
+ just in case (e.g., 512 or 1024 or 2048).
59
+ type_vocab_size (`int`, *optional*, defaults to 4):
60
+ The vocabulary size of the `token_type_ids` passed when calling [`FNetModel`] or [`TFFNetModel`].
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
64
+ The epsilon used by the layer normalization layers.
65
+ use_tpu_fourier_optimizations (`bool`, *optional*, defaults to `False`):
66
+ Determines whether to use TPU optimized FFTs. If `True`, the model will favor axis-wise FFTs transforms.
67
+ Set to `False` for GPU/CPU hardware, in which case n-dimensional FFTs are used.
68
+ tpu_short_seq_length (`int`, *optional*, defaults to 512):
69
+ The sequence length that is expected by the model when using TPUs. This will be used to initialize the DFT
70
+ matrix only when *use_tpu_fourier_optimizations* is set to `True` and the input sequence is shorter than or
71
+ equal to 4096 tokens.
72
+
73
+ Example:
74
+
75
+ ```python
76
+ >>> from transformers import FNetConfig, FNetModel
77
+
78
+ >>> # Initializing a FNet fnet-base style configuration
79
+ >>> configuration = FNetConfig()
80
+
81
+ >>> # Initializing a model (with random weights) from the fnet-base style configuration
82
+ >>> model = FNetModel(configuration)
83
+
84
+ >>> # Accessing the model configuration
85
+ >>> configuration = model.config
86
+ ```"""
87
+
88
+ model_type = "fnet"
89
+
90
+ def __init__(
91
+ self,
92
+ vocab_size=32000,
93
+ hidden_size=768,
94
+ num_hidden_layers=12,
95
+ intermediate_size=3072,
96
+ hidden_act="gelu_new",
97
+ hidden_dropout_prob=0.1,
98
+ max_position_embeddings=512,
99
+ type_vocab_size=4,
100
+ initializer_range=0.02,
101
+ layer_norm_eps=1e-12,
102
+ use_tpu_fourier_optimizations=False,
103
+ tpu_short_seq_length=512,
104
+ pad_token_id=3,
105
+ bos_token_id=1,
106
+ eos_token_id=2,
107
+ **kwargs,
108
+ ):
109
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
110
+
111
+ self.vocab_size = vocab_size
112
+ self.max_position_embeddings = max_position_embeddings
113
+ self.hidden_size = hidden_size
114
+ self.num_hidden_layers = num_hidden_layers
115
+ self.intermediate_size = intermediate_size
116
+ self.hidden_act = hidden_act
117
+ self.hidden_dropout_prob = hidden_dropout_prob
118
+ self.initializer_range = initializer_range
119
+ self.type_vocab_size = type_vocab_size
120
+ self.layer_norm_eps = layer_norm_eps
121
+ self.use_tpu_fourier_optimizations = use_tpu_fourier_optimizations
122
+ self.tpu_short_seq_length = tpu_short_seq_length
pllava/lib/python3.10/site-packages/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert FNet checkpoint."""
16
+
17
+
18
+ import argparse
19
+
20
+ import torch
21
+ from flax.training.checkpoints import restore_checkpoint
22
+
23
+ from transformers import FNetConfig, FNetForPreTraining
24
+ from transformers.utils import logging
25
+
26
+
27
+ logging.set_verbosity_info()
28
+
29
+
30
+ def convert_flax_checkpoint_to_pytorch(flax_checkpoint_path, fnet_config_file, save_path):
31
+ # Initialise PyTorch model
32
+ config = FNetConfig.from_json_file(fnet_config_file)
33
+ print(f"Building PyTorch model from configuration: {config}")
34
+ fnet_pretraining_model = FNetForPreTraining(config)
35
+
36
+ checkpoint_dict = restore_checkpoint(flax_checkpoint_path, None)
37
+ pretrained_model_params = checkpoint_dict["target"]
38
+
39
+ # Embeddings
40
+ # Position IDs
41
+ state_dict = fnet_pretraining_model.state_dict()
42
+
43
+ position_ids = state_dict["fnet.embeddings.position_ids"]
44
+ new_state_dict = {"fnet.embeddings.position_ids": position_ids}
45
+ # Embedding Layers
46
+ new_state_dict["fnet.embeddings.word_embeddings.weight"] = torch.tensor(
47
+ pretrained_model_params["encoder"]["embedder"]["word"]["embedding"]
48
+ )
49
+ new_state_dict["fnet.embeddings.position_embeddings.weight"] = torch.tensor(
50
+ pretrained_model_params["encoder"]["embedder"]["position"]["embedding"][0]
51
+ )
52
+ new_state_dict["fnet.embeddings.token_type_embeddings.weight"] = torch.tensor(
53
+ pretrained_model_params["encoder"]["embedder"]["type"]["embedding"]
54
+ )
55
+ new_state_dict["fnet.embeddings.projection.weight"] = torch.tensor(
56
+ pretrained_model_params["encoder"]["embedder"]["hidden_mapping_in"]["kernel"]
57
+ ).T
58
+ new_state_dict["fnet.embeddings.projection.bias"] = torch.tensor(
59
+ pretrained_model_params["encoder"]["embedder"]["hidden_mapping_in"]["bias"]
60
+ )
61
+ new_state_dict["fnet.embeddings.LayerNorm.weight"] = torch.tensor(
62
+ pretrained_model_params["encoder"]["embedder"]["layer_norm"]["scale"]
63
+ )
64
+ new_state_dict["fnet.embeddings.LayerNorm.bias"] = torch.tensor(
65
+ pretrained_model_params["encoder"]["embedder"]["layer_norm"]["bias"]
66
+ )
67
+
68
+ # Encoder Layers
69
+ for layer in range(config.num_hidden_layers):
70
+ new_state_dict[f"fnet.encoder.layer.{layer}.fourier.output.LayerNorm.weight"] = torch.tensor(
71
+ pretrained_model_params["encoder"][f"encoder_{layer}"]["mixing_layer_norm"]["scale"]
72
+ )
73
+ new_state_dict[f"fnet.encoder.layer.{layer}.fourier.output.LayerNorm.bias"] = torch.tensor(
74
+ pretrained_model_params["encoder"][f"encoder_{layer}"]["mixing_layer_norm"]["bias"]
75
+ )
76
+
77
+ new_state_dict[f"fnet.encoder.layer.{layer}.intermediate.dense.weight"] = torch.tensor(
78
+ pretrained_model_params["encoder"][f"feed_forward_{layer}"]["intermediate"]["kernel"]
79
+ ).T
80
+ new_state_dict[f"fnet.encoder.layer.{layer}.intermediate.dense.bias"] = torch.tensor(
81
+ pretrained_model_params["encoder"][f"feed_forward_{layer}"]["intermediate"]["bias"]
82
+ )
83
+
84
+ new_state_dict[f"fnet.encoder.layer.{layer}.output.dense.weight"] = torch.tensor(
85
+ pretrained_model_params["encoder"][f"feed_forward_{layer}"]["output"]["kernel"]
86
+ ).T
87
+ new_state_dict[f"fnet.encoder.layer.{layer}.output.dense.bias"] = torch.tensor(
88
+ pretrained_model_params["encoder"][f"feed_forward_{layer}"]["output"]["bias"]
89
+ )
90
+
91
+ new_state_dict[f"fnet.encoder.layer.{layer}.output.LayerNorm.weight"] = torch.tensor(
92
+ pretrained_model_params["encoder"][f"encoder_{layer}"]["output_layer_norm"]["scale"]
93
+ )
94
+ new_state_dict[f"fnet.encoder.layer.{layer}.output.LayerNorm.bias"] = torch.tensor(
95
+ pretrained_model_params["encoder"][f"encoder_{layer}"]["output_layer_norm"]["bias"]
96
+ )
97
+
98
+ # Pooler Layers
99
+ new_state_dict["fnet.pooler.dense.weight"] = torch.tensor(pretrained_model_params["encoder"]["pooler"]["kernel"]).T
100
+ new_state_dict["fnet.pooler.dense.bias"] = torch.tensor(pretrained_model_params["encoder"]["pooler"]["bias"])
101
+
102
+ # Masked LM Layers
103
+ new_state_dict["cls.predictions.transform.dense.weight"] = torch.tensor(
104
+ pretrained_model_params["predictions_dense"]["kernel"]
105
+ ).T
106
+ new_state_dict["cls.predictions.transform.dense.bias"] = torch.tensor(
107
+ pretrained_model_params["predictions_dense"]["bias"]
108
+ )
109
+ new_state_dict["cls.predictions.transform.LayerNorm.weight"] = torch.tensor(
110
+ pretrained_model_params["predictions_layer_norm"]["scale"]
111
+ )
112
+ new_state_dict["cls.predictions.transform.LayerNorm.bias"] = torch.tensor(
113
+ pretrained_model_params["predictions_layer_norm"]["bias"]
114
+ )
115
+ new_state_dict["cls.predictions.decoder.weight"] = torch.tensor(
116
+ pretrained_model_params["encoder"]["embedder"]["word"]["embedding"]
117
+ )
118
+ new_state_dict["cls.predictions.decoder.bias"] = torch.tensor(
119
+ pretrained_model_params["predictions_output"]["output_bias"]
120
+ )
121
+ new_state_dict["cls.predictions.bias"] = torch.tensor(pretrained_model_params["predictions_output"]["output_bias"])
122
+
123
+ # Seq Relationship Layers
124
+ new_state_dict["cls.seq_relationship.weight"] = torch.tensor(
125
+ pretrained_model_params["classification"]["output_kernel"]
126
+ )
127
+ new_state_dict["cls.seq_relationship.bias"] = torch.tensor(
128
+ pretrained_model_params["classification"]["output_bias"]
129
+ )
130
+
131
+ # Load State Dict
132
+ fnet_pretraining_model.load_state_dict(new_state_dict)
133
+
134
+ # Save PreTrained
135
+ print(f"Saving pretrained model to {save_path}")
136
+ fnet_pretraining_model.save_pretrained(save_path)
137
+
138
+
139
+ if __name__ == "__main__":
140
+ parser = argparse.ArgumentParser()
141
+ # Required parameters
142
+ parser.add_argument(
143
+ "--flax_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
144
+ )
145
+ parser.add_argument(
146
+ "--fnet_config_file",
147
+ default=None,
148
+ type=str,
149
+ required=True,
150
+ help=(
151
+ "The config json file corresponding to the pre-trained FNet model. \n"
152
+ "This specifies the model architecture."
153
+ ),
154
+ )
155
+ parser.add_argument("--save_path", default=None, type=str, required=True, help="Path to the output model.")
156
+ args = parser.parse_args()
157
+ convert_flax_checkpoint_to_pytorch(args.flax_checkpoint_path, args.fnet_config_file, args.save_path)
pllava/lib/python3.10/site-packages/transformers/models/fnet/modeling_fnet.py ADDED
@@ -0,0 +1,1185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google Research and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch FNet model."""
16
+
17
+ import warnings
18
+ from dataclasses import dataclass
19
+ from functools import partial
20
+ from typing import Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ...utils import is_scipy_available
28
+
29
+
30
+ if is_scipy_available():
31
+ from scipy import linalg
32
+
33
+ from ...activations import ACT2FN
34
+ from ...modeling_outputs import (
35
+ BaseModelOutput,
36
+ BaseModelOutputWithPooling,
37
+ MaskedLMOutput,
38
+ ModelOutput,
39
+ MultipleChoiceModelOutput,
40
+ NextSentencePredictorOutput,
41
+ QuestionAnsweringModelOutput,
42
+ SequenceClassifierOutput,
43
+ TokenClassifierOutput,
44
+ )
45
+ from ...modeling_utils import PreTrainedModel
46
+ from ...pytorch_utils import apply_chunking_to_forward
47
+ from ...utils import (
48
+ add_code_sample_docstrings,
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ logging,
52
+ replace_return_docstrings,
53
+ )
54
+ from .configuration_fnet import FNetConfig
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+ _CHECKPOINT_FOR_DOC = "google/fnet-base"
60
+ _CONFIG_FOR_DOC = "FNetConfig"
61
+
62
+ FNET_PRETRAINED_MODEL_ARCHIVE_LIST = [
63
+ "google/fnet-base",
64
+ "google/fnet-large",
65
+ # See all FNet models at https://huggingface.co/models?filter=fnet
66
+ ]
67
+
68
+
69
+ # Adapted from https://github.com/google-research/google-research/blob/master/f_net/fourier.py
70
+ def _two_dim_matmul(x, matrix_dim_one, matrix_dim_two):
71
+ """Applies 2D matrix multiplication to 3D input arrays."""
72
+ seq_length = x.shape[1]
73
+ matrix_dim_one = matrix_dim_one[:seq_length, :seq_length]
74
+ x = x.type(torch.complex64)
75
+ return torch.einsum("bij,jk,ni->bnk", x, matrix_dim_two, matrix_dim_one)
76
+
77
+
78
+ # # Adapted from https://github.com/google-research/google-research/blob/master/f_net/fourier.py
79
+ def two_dim_matmul(x, matrix_dim_one, matrix_dim_two):
80
+ return _two_dim_matmul(x, matrix_dim_one, matrix_dim_two)
81
+
82
+
83
+ # Adapted from https://github.com/google-research/google-research/blob/master/f_net/fourier.py
84
+ def fftn(x):
85
+ """
86
+ Applies n-dimensional Fast Fourier Transform (FFT) to input array.
87
+
88
+ Args:
89
+ x: Input n-dimensional array.
90
+
91
+ Returns:
92
+ n-dimensional Fourier transform of input n-dimensional array.
93
+ """
94
+ out = x
95
+ for axis in reversed(range(x.ndim)[1:]): # We don't need to apply FFT to last axis
96
+ out = torch.fft.fft(out, axis=axis)
97
+ return out
98
+
99
+
100
+ class FNetEmbeddings(nn.Module):
101
+ """Construct the embeddings from word, position and token_type embeddings."""
102
+
103
+ def __init__(self, config):
104
+ super().__init__()
105
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
106
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
107
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
108
+
109
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
110
+ # any TensorFlow checkpoint file
111
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
112
+ # NOTE: This is the project layer and will be needed. The original code allows for different embedding and different model dimensions.
113
+ self.projection = nn.Linear(config.hidden_size, config.hidden_size)
114
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
115
+
116
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
117
+ self.register_buffer(
118
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
119
+ )
120
+
121
+ self.register_buffer(
122
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
123
+ )
124
+
125
+ def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
126
+ if input_ids is not None:
127
+ input_shape = input_ids.size()
128
+ else:
129
+ input_shape = inputs_embeds.size()[:-1]
130
+
131
+ seq_length = input_shape[1]
132
+
133
+ if position_ids is None:
134
+ position_ids = self.position_ids[:, :seq_length]
135
+
136
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
137
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
138
+ # issue #5664
139
+ if token_type_ids is None:
140
+ if hasattr(self, "token_type_ids"):
141
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
142
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
143
+ token_type_ids = buffered_token_type_ids_expanded
144
+ else:
145
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
146
+
147
+ if inputs_embeds is None:
148
+ inputs_embeds = self.word_embeddings(input_ids)
149
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
150
+
151
+ embeddings = inputs_embeds + token_type_embeddings
152
+
153
+ position_embeddings = self.position_embeddings(position_ids)
154
+ embeddings += position_embeddings
155
+ embeddings = self.LayerNorm(embeddings)
156
+ embeddings = self.projection(embeddings)
157
+ embeddings = self.dropout(embeddings)
158
+ return embeddings
159
+
160
+
161
+ class FNetBasicFourierTransform(nn.Module):
162
+ def __init__(self, config):
163
+ super().__init__()
164
+ self._init_fourier_transform(config)
165
+
166
+ def _init_fourier_transform(self, config):
167
+ if not config.use_tpu_fourier_optimizations:
168
+ self.fourier_transform = partial(torch.fft.fftn, dim=(1, 2))
169
+ elif config.max_position_embeddings <= 4096:
170
+ if is_scipy_available():
171
+ self.register_buffer(
172
+ "dft_mat_hidden", torch.tensor(linalg.dft(config.hidden_size), dtype=torch.complex64)
173
+ )
174
+ self.register_buffer(
175
+ "dft_mat_seq", torch.tensor(linalg.dft(config.tpu_short_seq_length), dtype=torch.complex64)
176
+ )
177
+ self.fourier_transform = partial(
178
+ two_dim_matmul, matrix_dim_one=self.dft_mat_seq, matrix_dim_two=self.dft_mat_hidden
179
+ )
180
+ else:
181
+ logging.warning(
182
+ "SciPy is needed for DFT matrix calculation and is not found. Using TPU optimized fast fourier"
183
+ " transform instead."
184
+ )
185
+ self.fourier_transform = fftn
186
+ else:
187
+ self.fourier_transform = fftn
188
+
189
+ def forward(self, hidden_states):
190
+ # NOTE: We do not use torch.vmap as it is not integrated into PyTorch stable versions.
191
+ # Interested users can modify the code to use vmap from the nightly versions, getting the vmap from here:
192
+ # https://pytorch.org/docs/master/generated/torch.vmap.html. Note that fourier transform methods will need
193
+ # change accordingly.
194
+
195
+ outputs = self.fourier_transform(hidden_states).real
196
+ return (outputs,)
197
+
198
+
199
+ class FNetBasicOutput(nn.Module):
200
+ def __init__(self, config):
201
+ super().__init__()
202
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
203
+
204
+ def forward(self, hidden_states, input_tensor):
205
+ hidden_states = self.LayerNorm(input_tensor + hidden_states)
206
+ return hidden_states
207
+
208
+
209
+ class FNetFourierTransform(nn.Module):
210
+ def __init__(self, config):
211
+ super().__init__()
212
+ self.self = FNetBasicFourierTransform(config)
213
+ self.output = FNetBasicOutput(config)
214
+
215
+ def forward(self, hidden_states):
216
+ self_outputs = self.self(hidden_states)
217
+ fourier_output = self.output(self_outputs[0], hidden_states)
218
+ outputs = (fourier_output,)
219
+ return outputs
220
+
221
+
222
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->FNet
223
+ class FNetIntermediate(nn.Module):
224
+ def __init__(self, config):
225
+ super().__init__()
226
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
227
+ if isinstance(config.hidden_act, str):
228
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
229
+ else:
230
+ self.intermediate_act_fn = config.hidden_act
231
+
232
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
233
+ hidden_states = self.dense(hidden_states)
234
+ hidden_states = self.intermediate_act_fn(hidden_states)
235
+ return hidden_states
236
+
237
+
238
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->FNet
239
+ class FNetOutput(nn.Module):
240
+ def __init__(self, config):
241
+ super().__init__()
242
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
243
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
244
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
245
+
246
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
247
+ hidden_states = self.dense(hidden_states)
248
+ hidden_states = self.dropout(hidden_states)
249
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
250
+ return hidden_states
251
+
252
+
253
+ class FNetLayer(nn.Module):
254
+ def __init__(self, config):
255
+ super().__init__()
256
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
257
+ self.seq_len_dim = 1 # The dimension which has the sequence length
258
+ self.fourier = FNetFourierTransform(config)
259
+ self.intermediate = FNetIntermediate(config)
260
+ self.output = FNetOutput(config)
261
+
262
+ def forward(self, hidden_states):
263
+ self_fourier_outputs = self.fourier(hidden_states)
264
+ fourier_output = self_fourier_outputs[0]
265
+
266
+ layer_output = apply_chunking_to_forward(
267
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, fourier_output
268
+ )
269
+
270
+ outputs = (layer_output,)
271
+
272
+ return outputs
273
+
274
+ def feed_forward_chunk(self, fourier_output):
275
+ intermediate_output = self.intermediate(fourier_output)
276
+ layer_output = self.output(intermediate_output, fourier_output)
277
+ return layer_output
278
+
279
+
280
+ class FNetEncoder(nn.Module):
281
+ def __init__(self, config):
282
+ super().__init__()
283
+ self.config = config
284
+ self.layer = nn.ModuleList([FNetLayer(config) for _ in range(config.num_hidden_layers)])
285
+ self.gradient_checkpointing = False
286
+
287
+ def forward(self, hidden_states, output_hidden_states=False, return_dict=True):
288
+ all_hidden_states = () if output_hidden_states else None
289
+
290
+ for i, layer_module in enumerate(self.layer):
291
+ if output_hidden_states:
292
+ all_hidden_states = all_hidden_states + (hidden_states,)
293
+
294
+ if self.gradient_checkpointing and self.training:
295
+ layer_outputs = self._gradient_checkpointing_func(layer_module.__call__, hidden_states)
296
+ else:
297
+ layer_outputs = layer_module(hidden_states)
298
+
299
+ hidden_states = layer_outputs[0]
300
+
301
+ if output_hidden_states:
302
+ all_hidden_states = all_hidden_states + (hidden_states,)
303
+
304
+ if not return_dict:
305
+ return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
306
+
307
+ return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
308
+
309
+
310
+ # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->FNet
311
+ class FNetPooler(nn.Module):
312
+ def __init__(self, config):
313
+ super().__init__()
314
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
315
+ self.activation = nn.Tanh()
316
+
317
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
318
+ # We "pool" the model by simply taking the hidden state corresponding
319
+ # to the first token.
320
+ first_token_tensor = hidden_states[:, 0]
321
+ pooled_output = self.dense(first_token_tensor)
322
+ pooled_output = self.activation(pooled_output)
323
+ return pooled_output
324
+
325
+
326
+ # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->FNet
327
+ class FNetPredictionHeadTransform(nn.Module):
328
+ def __init__(self, config):
329
+ super().__init__()
330
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
331
+ if isinstance(config.hidden_act, str):
332
+ self.transform_act_fn = ACT2FN[config.hidden_act]
333
+ else:
334
+ self.transform_act_fn = config.hidden_act
335
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
336
+
337
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
338
+ hidden_states = self.dense(hidden_states)
339
+ hidden_states = self.transform_act_fn(hidden_states)
340
+ hidden_states = self.LayerNorm(hidden_states)
341
+ return hidden_states
342
+
343
+
344
+ class FNetLMPredictionHead(nn.Module):
345
+ def __init__(self, config):
346
+ super().__init__()
347
+ self.transform = FNetPredictionHeadTransform(config)
348
+
349
+ # The output weights are the same as the input embeddings, but there is
350
+ # an output-only bias for each token.
351
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
352
+
353
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
354
+ self.decoder.bias = self.bias
355
+
356
+ def forward(self, hidden_states):
357
+ hidden_states = self.transform(hidden_states)
358
+ hidden_states = self.decoder(hidden_states)
359
+ return hidden_states
360
+
361
+ def _tie_weights(self):
362
+ # To tie those two weights if they get disconnected (on TPU or when the bias is resized)
363
+ self.bias = self.decoder.bias
364
+
365
+
366
+ class FNetOnlyMLMHead(nn.Module):
367
+ def __init__(self, config):
368
+ super().__init__()
369
+ self.predictions = FNetLMPredictionHead(config)
370
+
371
+ def forward(self, sequence_output):
372
+ prediction_scores = self.predictions(sequence_output)
373
+ return prediction_scores
374
+
375
+
376
+ # Copied from transformers.models.bert.modeling_bert.BertOnlyNSPHead with Bert->FNet
377
+ class FNetOnlyNSPHead(nn.Module):
378
+ def __init__(self, config):
379
+ super().__init__()
380
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
381
+
382
+ def forward(self, pooled_output):
383
+ seq_relationship_score = self.seq_relationship(pooled_output)
384
+ return seq_relationship_score
385
+
386
+
387
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert->FNet
388
+ class FNetPreTrainingHeads(nn.Module):
389
+ def __init__(self, config):
390
+ super().__init__()
391
+ self.predictions = FNetLMPredictionHead(config)
392
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
393
+
394
+ def forward(self, sequence_output, pooled_output):
395
+ prediction_scores = self.predictions(sequence_output)
396
+ seq_relationship_score = self.seq_relationship(pooled_output)
397
+ return prediction_scores, seq_relationship_score
398
+
399
+
400
+ class FNetPreTrainedModel(PreTrainedModel):
401
+ """
402
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
403
+ models.
404
+ """
405
+
406
+ config_class = FNetConfig
407
+ base_model_prefix = "fnet"
408
+ supports_gradient_checkpointing = True
409
+
410
+ def _init_weights(self, module):
411
+ """Initialize the weights"""
412
+ if isinstance(module, nn.Linear):
413
+ # Slightly different from the TF version which uses truncated_normal for initialization
414
+ # cf https://github.com/pytorch/pytorch/pull/5617
415
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
416
+ # NOTE: Original code uses same initialization as weights for biases as well.
417
+ if module.bias is not None:
418
+ module.bias.data.zero_()
419
+ elif isinstance(module, nn.Embedding):
420
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
421
+ if module.padding_idx is not None:
422
+ module.weight.data[module.padding_idx].zero_()
423
+ elif isinstance(module, nn.LayerNorm):
424
+ module.bias.data.zero_()
425
+ module.weight.data.fill_(1.0)
426
+
427
+
428
+ @dataclass
429
+ class FNetForPreTrainingOutput(ModelOutput):
430
+ """
431
+ Output type of [`FNetForPreTraining`].
432
+
433
+ Args:
434
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
435
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
436
+ (classification) loss.
437
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
438
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
439
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
440
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
441
+ before SoftMax).
442
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
443
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
444
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
445
+ plus the initial embedding outputs.
446
+ """
447
+
448
+ loss: Optional[torch.FloatTensor] = None
449
+ prediction_logits: torch.FloatTensor = None
450
+ seq_relationship_logits: torch.FloatTensor = None
451
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
452
+
453
+
454
+ FNET_START_DOCSTRING = r"""
455
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
456
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
457
+ behavior.
458
+
459
+ Parameters:
460
+ config ([`FNetConfig`]): Model configuration class with all the parameters of the model.
461
+ Initializing with a config file does not load the weights associated with the model, only the
462
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
463
+ """
464
+
465
+ FNET_INPUTS_DOCSTRING = r"""
466
+ Args:
467
+ input_ids (`torch.LongTensor` of shape `({0})`):
468
+ Indices of input sequence tokens in the vocabulary.
469
+
470
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
471
+ [`PreTrainedTokenizer.__call__`] for details.
472
+
473
+ [What are input IDs?](../glossary#input-ids)
474
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
475
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
476
+ 1]`:
477
+
478
+ - 0 corresponds to a *sentence A* token,
479
+ - 1 corresponds to a *sentence B* token.
480
+
481
+ [What are token type IDs?](../glossary#token-type-ids)
482
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
483
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
484
+ config.max_position_embeddings - 1]`.
485
+
486
+ [What are position IDs?](../glossary#position-ids)
487
+
488
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
489
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
490
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
491
+ model's internal embedding lookup matrix.
492
+ output_hidden_states (`bool`, *optional*):
493
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
494
+ more detail.
495
+ return_dict (`bool`, *optional*):
496
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
497
+ """
498
+
499
+
500
+ @add_start_docstrings(
501
+ "The bare FNet Model transformer outputting raw hidden-states without any specific head on top.",
502
+ FNET_START_DOCSTRING,
503
+ )
504
+ class FNetModel(FNetPreTrainedModel):
505
+ """
506
+
507
+ The model can behave as an encoder, following the architecture described in [FNet: Mixing Tokens with Fourier
508
+ Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
509
+
510
+ """
511
+
512
+ def __init__(self, config, add_pooling_layer=True):
513
+ super().__init__(config)
514
+ self.config = config
515
+
516
+ self.embeddings = FNetEmbeddings(config)
517
+ self.encoder = FNetEncoder(config)
518
+
519
+ self.pooler = FNetPooler(config) if add_pooling_layer else None
520
+
521
+ # Initialize weights and apply final processing
522
+ self.post_init()
523
+
524
+ def get_input_embeddings(self):
525
+ return self.embeddings.word_embeddings
526
+
527
+ def set_input_embeddings(self, value):
528
+ self.embeddings.word_embeddings = value
529
+
530
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
531
+ @add_code_sample_docstrings(
532
+ checkpoint=_CHECKPOINT_FOR_DOC,
533
+ output_type=BaseModelOutput,
534
+ config_class=_CONFIG_FOR_DOC,
535
+ )
536
+ def forward(
537
+ self,
538
+ input_ids: Optional[torch.LongTensor] = None,
539
+ token_type_ids: Optional[torch.LongTensor] = None,
540
+ position_ids: Optional[torch.LongTensor] = None,
541
+ inputs_embeds: Optional[torch.FloatTensor] = None,
542
+ output_hidden_states: Optional[bool] = None,
543
+ return_dict: Optional[bool] = None,
544
+ ) -> Union[tuple, BaseModelOutput]:
545
+ output_hidden_states = (
546
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
547
+ )
548
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
549
+
550
+ if input_ids is not None and inputs_embeds is not None:
551
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
552
+ elif input_ids is not None:
553
+ input_shape = input_ids.size()
554
+ batch_size, seq_length = input_shape
555
+ elif inputs_embeds is not None:
556
+ input_shape = inputs_embeds.size()[:-1]
557
+ batch_size, seq_length = input_shape
558
+ else:
559
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
560
+
561
+ if (
562
+ self.config.use_tpu_fourier_optimizations
563
+ and seq_length <= 4096
564
+ and self.config.tpu_short_seq_length != seq_length
565
+ ):
566
+ raise ValueError(
567
+ "The `tpu_short_seq_length` in FNetConfig should be set equal to the sequence length being passed to"
568
+ " the model when using TPU optimizations."
569
+ )
570
+
571
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
572
+
573
+ if token_type_ids is None:
574
+ if hasattr(self.embeddings, "token_type_ids"):
575
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
576
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
577
+ token_type_ids = buffered_token_type_ids_expanded
578
+ else:
579
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
580
+
581
+ embedding_output = self.embeddings(
582
+ input_ids=input_ids,
583
+ position_ids=position_ids,
584
+ token_type_ids=token_type_ids,
585
+ inputs_embeds=inputs_embeds,
586
+ )
587
+ encoder_outputs = self.encoder(
588
+ embedding_output,
589
+ output_hidden_states=output_hidden_states,
590
+ return_dict=return_dict,
591
+ )
592
+ sequence_output = encoder_outputs[0]
593
+
594
+ pooler_output = self.pooler(sequence_output) if self.pooler is not None else None
595
+
596
+ if not return_dict:
597
+ return (sequence_output, pooler_output) + encoder_outputs[1:]
598
+
599
+ return BaseModelOutputWithPooling(
600
+ last_hidden_state=sequence_output,
601
+ pooler_output=pooler_output,
602
+ hidden_states=encoder_outputs.hidden_states,
603
+ )
604
+
605
+
606
+ @add_start_docstrings(
607
+ """
608
+ FNet Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
609
+ sentence prediction (classification)` head.
610
+ """,
611
+ FNET_START_DOCSTRING,
612
+ )
613
+ class FNetForPreTraining(FNetPreTrainedModel):
614
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
615
+
616
+ def __init__(self, config):
617
+ super().__init__(config)
618
+
619
+ self.fnet = FNetModel(config)
620
+ self.cls = FNetPreTrainingHeads(config)
621
+
622
+ # Initialize weights and apply final processing
623
+ self.post_init()
624
+
625
+ def get_output_embeddings(self):
626
+ return self.cls.predictions.decoder
627
+
628
+ def set_output_embeddings(self, new_embeddings):
629
+ self.cls.predictions.decoder = new_embeddings
630
+
631
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
632
+ @replace_return_docstrings(output_type=FNetForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
633
+ def forward(
634
+ self,
635
+ input_ids: Optional[torch.Tensor] = None,
636
+ token_type_ids: Optional[torch.Tensor] = None,
637
+ position_ids: Optional[torch.Tensor] = None,
638
+ inputs_embeds: Optional[torch.Tensor] = None,
639
+ labels: Optional[torch.Tensor] = None,
640
+ next_sentence_label: Optional[torch.Tensor] = None,
641
+ output_hidden_states: Optional[bool] = None,
642
+ return_dict: Optional[bool] = None,
643
+ ) -> Union[Tuple, FNetForPreTrainingOutput]:
644
+ r"""
645
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
646
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
647
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
648
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
649
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
650
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
651
+ (see `input_ids` docstring) Indices should be in `[0, 1]`:
652
+
653
+ - 0 indicates sequence B is a continuation of sequence A,
654
+ - 1 indicates sequence B is a random sequence.
655
+ kwargs (`Dict[str, any]`, optional, defaults to *{}*):
656
+ Used to hide legacy arguments that have been deprecated.
657
+
658
+ Returns:
659
+
660
+ Example:
661
+
662
+ ```python
663
+ >>> from transformers import AutoTokenizer, FNetForPreTraining
664
+ >>> import torch
665
+
666
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/fnet-base")
667
+ >>> model = FNetForPreTraining.from_pretrained("google/fnet-base")
668
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
669
+ >>> outputs = model(**inputs)
670
+ >>> prediction_logits = outputs.prediction_logits
671
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
672
+ ```"""
673
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
674
+
675
+ outputs = self.fnet(
676
+ input_ids,
677
+ token_type_ids=token_type_ids,
678
+ position_ids=position_ids,
679
+ inputs_embeds=inputs_embeds,
680
+ output_hidden_states=output_hidden_states,
681
+ return_dict=return_dict,
682
+ )
683
+
684
+ sequence_output, pooled_output = outputs[:2]
685
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
686
+
687
+ total_loss = None
688
+ if labels is not None and next_sentence_label is not None:
689
+ loss_fct = CrossEntropyLoss()
690
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
691
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
692
+ total_loss = masked_lm_loss + next_sentence_loss
693
+
694
+ if not return_dict:
695
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
696
+ return ((total_loss,) + output) if total_loss is not None else output
697
+
698
+ return FNetForPreTrainingOutput(
699
+ loss=total_loss,
700
+ prediction_logits=prediction_scores,
701
+ seq_relationship_logits=seq_relationship_score,
702
+ hidden_states=outputs.hidden_states,
703
+ )
704
+
705
+
706
+ @add_start_docstrings("""FNet Model with a `language modeling` head on top.""", FNET_START_DOCSTRING)
707
+ class FNetForMaskedLM(FNetPreTrainedModel):
708
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
709
+
710
+ def __init__(self, config):
711
+ super().__init__(config)
712
+
713
+ self.fnet = FNetModel(config)
714
+ self.cls = FNetOnlyMLMHead(config)
715
+
716
+ # Initialize weights and apply final processing
717
+ self.post_init()
718
+
719
+ def get_output_embeddings(self):
720
+ return self.cls.predictions.decoder
721
+
722
+ def set_output_embeddings(self, new_embeddings):
723
+ self.cls.predictions.decoder = new_embeddings
724
+
725
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
726
+ @add_code_sample_docstrings(
727
+ checkpoint=_CHECKPOINT_FOR_DOC,
728
+ output_type=MaskedLMOutput,
729
+ config_class=_CONFIG_FOR_DOC,
730
+ )
731
+ def forward(
732
+ self,
733
+ input_ids: Optional[torch.Tensor] = None,
734
+ token_type_ids: Optional[torch.Tensor] = None,
735
+ position_ids: Optional[torch.Tensor] = None,
736
+ inputs_embeds: Optional[torch.Tensor] = None,
737
+ labels: Optional[torch.Tensor] = None,
738
+ output_hidden_states: Optional[bool] = None,
739
+ return_dict: Optional[bool] = None,
740
+ ) -> Union[Tuple, MaskedLMOutput]:
741
+ r"""
742
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
743
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
744
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
745
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
746
+ """
747
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
748
+
749
+ outputs = self.fnet(
750
+ input_ids,
751
+ token_type_ids=token_type_ids,
752
+ position_ids=position_ids,
753
+ inputs_embeds=inputs_embeds,
754
+ output_hidden_states=output_hidden_states,
755
+ return_dict=return_dict,
756
+ )
757
+
758
+ sequence_output = outputs[0]
759
+ prediction_scores = self.cls(sequence_output)
760
+
761
+ masked_lm_loss = None
762
+ if labels is not None:
763
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
764
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
765
+
766
+ if not return_dict:
767
+ output = (prediction_scores,) + outputs[2:]
768
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
769
+
770
+ return MaskedLMOutput(loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states)
771
+
772
+
773
+ @add_start_docstrings(
774
+ """FNet Model with a `next sentence prediction (classification)` head on top.""",
775
+ FNET_START_DOCSTRING,
776
+ )
777
+ class FNetForNextSentencePrediction(FNetPreTrainedModel):
778
+ def __init__(self, config):
779
+ super().__init__(config)
780
+
781
+ self.fnet = FNetModel(config)
782
+ self.cls = FNetOnlyNSPHead(config)
783
+
784
+ # Initialize weights and apply final processing
785
+ self.post_init()
786
+
787
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
788
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
789
+ def forward(
790
+ self,
791
+ input_ids: Optional[torch.Tensor] = None,
792
+ token_type_ids: Optional[torch.Tensor] = None,
793
+ position_ids: Optional[torch.Tensor] = None,
794
+ inputs_embeds: Optional[torch.Tensor] = None,
795
+ labels: Optional[torch.Tensor] = None,
796
+ output_hidden_states: Optional[bool] = None,
797
+ return_dict: Optional[bool] = None,
798
+ **kwargs,
799
+ ) -> Union[Tuple, NextSentencePredictorOutput]:
800
+ r"""
801
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
802
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
803
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
804
+
805
+ - 0 indicates sequence B is a continuation of sequence A,
806
+ - 1 indicates sequence B is a random sequence.
807
+
808
+ Returns:
809
+
810
+ Example:
811
+
812
+ ```python
813
+ >>> from transformers import AutoTokenizer, FNetForNextSentencePrediction
814
+ >>> import torch
815
+
816
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/fnet-base")
817
+ >>> model = FNetForNextSentencePrediction.from_pretrained("google/fnet-base")
818
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
819
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
820
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
821
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
822
+ >>> logits = outputs.logits
823
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
824
+ ```"""
825
+
826
+ if "next_sentence_label" in kwargs:
827
+ warnings.warn(
828
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
829
+ " `labels` instead.",
830
+ FutureWarning,
831
+ )
832
+ labels = kwargs.pop("next_sentence_label")
833
+
834
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
835
+
836
+ outputs = self.fnet(
837
+ input_ids,
838
+ token_type_ids=token_type_ids,
839
+ position_ids=position_ids,
840
+ inputs_embeds=inputs_embeds,
841
+ output_hidden_states=output_hidden_states,
842
+ return_dict=return_dict,
843
+ )
844
+
845
+ pooled_output = outputs[1]
846
+
847
+ seq_relationship_scores = self.cls(pooled_output)
848
+
849
+ next_sentence_loss = None
850
+ if labels is not None:
851
+ loss_fct = CrossEntropyLoss()
852
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
853
+
854
+ if not return_dict:
855
+ output = (seq_relationship_scores,) + outputs[2:]
856
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
857
+
858
+ return NextSentencePredictorOutput(
859
+ loss=next_sentence_loss,
860
+ logits=seq_relationship_scores,
861
+ hidden_states=outputs.hidden_states,
862
+ )
863
+
864
+
865
+ @add_start_docstrings(
866
+ """
867
+ FNet Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
868
+ output) e.g. for GLUE tasks.
869
+ """,
870
+ FNET_START_DOCSTRING,
871
+ )
872
+ class FNetForSequenceClassification(FNetPreTrainedModel):
873
+ def __init__(self, config):
874
+ super().__init__(config)
875
+ self.num_labels = config.num_labels
876
+ self.fnet = FNetModel(config)
877
+
878
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
879
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
880
+
881
+ # Initialize weights and apply final processing
882
+ self.post_init()
883
+
884
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
885
+ @add_code_sample_docstrings(
886
+ checkpoint=_CHECKPOINT_FOR_DOC,
887
+ output_type=SequenceClassifierOutput,
888
+ config_class=_CONFIG_FOR_DOC,
889
+ )
890
+ def forward(
891
+ self,
892
+ input_ids: Optional[torch.Tensor] = None,
893
+ token_type_ids: Optional[torch.Tensor] = None,
894
+ position_ids: Optional[torch.Tensor] = None,
895
+ inputs_embeds: Optional[torch.Tensor] = None,
896
+ labels: Optional[torch.Tensor] = None,
897
+ output_hidden_states: Optional[bool] = None,
898
+ return_dict: Optional[bool] = None,
899
+ ) -> Union[Tuple, SequenceClassifierOutput]:
900
+ r"""
901
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
902
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
903
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
904
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
905
+ """
906
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
907
+
908
+ outputs = self.fnet(
909
+ input_ids,
910
+ token_type_ids=token_type_ids,
911
+ position_ids=position_ids,
912
+ inputs_embeds=inputs_embeds,
913
+ output_hidden_states=output_hidden_states,
914
+ return_dict=return_dict,
915
+ )
916
+
917
+ pooled_output = outputs[1]
918
+ pooled_output = self.dropout(pooled_output)
919
+ logits = self.classifier(pooled_output)
920
+
921
+ loss = None
922
+ if labels is not None:
923
+ if self.config.problem_type is None:
924
+ if self.num_labels == 1:
925
+ self.config.problem_type = "regression"
926
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
927
+ self.config.problem_type = "single_label_classification"
928
+ else:
929
+ self.config.problem_type = "multi_label_classification"
930
+
931
+ if self.config.problem_type == "regression":
932
+ loss_fct = MSELoss()
933
+ if self.num_labels == 1:
934
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
935
+ else:
936
+ loss = loss_fct(logits, labels)
937
+ elif self.config.problem_type == "single_label_classification":
938
+ loss_fct = CrossEntropyLoss()
939
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
940
+ elif self.config.problem_type == "multi_label_classification":
941
+ loss_fct = BCEWithLogitsLoss()
942
+ loss = loss_fct(logits, labels)
943
+ if not return_dict:
944
+ output = (logits,) + outputs[2:]
945
+ return ((loss,) + output) if loss is not None else output
946
+
947
+ return SequenceClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
948
+
949
+
950
+ @add_start_docstrings(
951
+ """
952
+ FNet Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
953
+ softmax) e.g. for RocStories/SWAG tasks.
954
+ """,
955
+ FNET_START_DOCSTRING,
956
+ )
957
+ class FNetForMultipleChoice(FNetPreTrainedModel):
958
+ def __init__(self, config):
959
+ super().__init__(config)
960
+
961
+ self.fnet = FNetModel(config)
962
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
963
+ self.classifier = nn.Linear(config.hidden_size, 1)
964
+
965
+ # Initialize weights and apply final processing
966
+ self.post_init()
967
+
968
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
969
+ @add_code_sample_docstrings(
970
+ checkpoint=_CHECKPOINT_FOR_DOC,
971
+ output_type=MultipleChoiceModelOutput,
972
+ config_class=_CONFIG_FOR_DOC,
973
+ )
974
+ def forward(
975
+ self,
976
+ input_ids: Optional[torch.Tensor] = None,
977
+ token_type_ids: Optional[torch.Tensor] = None,
978
+ position_ids: Optional[torch.Tensor] = None,
979
+ inputs_embeds: Optional[torch.Tensor] = None,
980
+ labels: Optional[torch.Tensor] = None,
981
+ output_hidden_states: Optional[bool] = None,
982
+ return_dict: Optional[bool] = None,
983
+ ) -> Union[Tuple, MultipleChoiceModelOutput]:
984
+ r"""
985
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
986
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
987
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
988
+ `input_ids` above)
989
+ """
990
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
991
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
992
+
993
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
994
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
995
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
996
+ inputs_embeds = (
997
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
998
+ if inputs_embeds is not None
999
+ else None
1000
+ )
1001
+
1002
+ outputs = self.fnet(
1003
+ input_ids,
1004
+ token_type_ids=token_type_ids,
1005
+ position_ids=position_ids,
1006
+ inputs_embeds=inputs_embeds,
1007
+ output_hidden_states=output_hidden_states,
1008
+ return_dict=return_dict,
1009
+ )
1010
+
1011
+ pooled_output = outputs[1]
1012
+
1013
+ pooled_output = self.dropout(pooled_output)
1014
+ logits = self.classifier(pooled_output)
1015
+ reshaped_logits = logits.view(-1, num_choices)
1016
+
1017
+ loss = None
1018
+ if labels is not None:
1019
+ loss_fct = CrossEntropyLoss()
1020
+ loss = loss_fct(reshaped_logits, labels)
1021
+
1022
+ if not return_dict:
1023
+ output = (reshaped_logits,) + outputs[2:]
1024
+ return ((loss,) + output) if loss is not None else output
1025
+
1026
+ return MultipleChoiceModelOutput(loss=loss, logits=reshaped_logits, hidden_states=outputs.hidden_states)
1027
+
1028
+
1029
+ @add_start_docstrings(
1030
+ """
1031
+ FNet Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1032
+ Named-Entity-Recognition (NER) tasks.
1033
+ """,
1034
+ FNET_START_DOCSTRING,
1035
+ )
1036
+ class FNetForTokenClassification(FNetPreTrainedModel):
1037
+ def __init__(self, config):
1038
+ super().__init__(config)
1039
+ self.num_labels = config.num_labels
1040
+
1041
+ self.fnet = FNetModel(config)
1042
+
1043
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1044
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1045
+
1046
+ # Initialize weights and apply final processing
1047
+ self.post_init()
1048
+
1049
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1050
+ @add_code_sample_docstrings(
1051
+ checkpoint=_CHECKPOINT_FOR_DOC,
1052
+ output_type=TokenClassifierOutput,
1053
+ config_class=_CONFIG_FOR_DOC,
1054
+ )
1055
+ def forward(
1056
+ self,
1057
+ input_ids: Optional[torch.Tensor] = None,
1058
+ token_type_ids: Optional[torch.Tensor] = None,
1059
+ position_ids: Optional[torch.Tensor] = None,
1060
+ inputs_embeds: Optional[torch.Tensor] = None,
1061
+ labels: Optional[torch.Tensor] = None,
1062
+ output_hidden_states: Optional[bool] = None,
1063
+ return_dict: Optional[bool] = None,
1064
+ ) -> Union[Tuple, TokenClassifierOutput]:
1065
+ r"""
1066
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1067
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1068
+ """
1069
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1070
+
1071
+ outputs = self.fnet(
1072
+ input_ids,
1073
+ token_type_ids=token_type_ids,
1074
+ position_ids=position_ids,
1075
+ inputs_embeds=inputs_embeds,
1076
+ output_hidden_states=output_hidden_states,
1077
+ return_dict=return_dict,
1078
+ )
1079
+
1080
+ sequence_output = outputs[0]
1081
+
1082
+ sequence_output = self.dropout(sequence_output)
1083
+ logits = self.classifier(sequence_output)
1084
+
1085
+ loss = None
1086
+ if labels is not None:
1087
+ loss_fct = CrossEntropyLoss()
1088
+ # Only keep active parts of the loss
1089
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1090
+
1091
+ if not return_dict:
1092
+ output = (logits,) + outputs[2:]
1093
+ return ((loss,) + output) if loss is not None else output
1094
+
1095
+ return TokenClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
1096
+
1097
+
1098
+ @add_start_docstrings(
1099
+ """
1100
+ FNet Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1101
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1102
+ """,
1103
+ FNET_START_DOCSTRING,
1104
+ )
1105
+ class FNetForQuestionAnswering(FNetPreTrainedModel):
1106
+ def __init__(self, config):
1107
+ super().__init__(config)
1108
+
1109
+ self.num_labels = config.num_labels
1110
+
1111
+ self.fnet = FNetModel(config)
1112
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1113
+
1114
+ # Initialize weights and apply final processing
1115
+ self.post_init()
1116
+
1117
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1118
+ @add_code_sample_docstrings(
1119
+ checkpoint=_CHECKPOINT_FOR_DOC,
1120
+ output_type=QuestionAnsweringModelOutput,
1121
+ config_class=_CONFIG_FOR_DOC,
1122
+ )
1123
+ def forward(
1124
+ self,
1125
+ input_ids: Optional[torch.Tensor] = None,
1126
+ token_type_ids: Optional[torch.Tensor] = None,
1127
+ position_ids: Optional[torch.Tensor] = None,
1128
+ inputs_embeds: Optional[torch.Tensor] = None,
1129
+ start_positions: Optional[torch.Tensor] = None,
1130
+ end_positions: Optional[torch.Tensor] = None,
1131
+ output_hidden_states: Optional[bool] = None,
1132
+ return_dict: Optional[bool] = None,
1133
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1134
+ r"""
1135
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1136
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1137
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1138
+ are not taken into account for computing the loss.
1139
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1140
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1141
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1142
+ are not taken into account for computing the loss.
1143
+ """
1144
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1145
+
1146
+ outputs = self.fnet(
1147
+ input_ids,
1148
+ token_type_ids=token_type_ids,
1149
+ position_ids=position_ids,
1150
+ inputs_embeds=inputs_embeds,
1151
+ output_hidden_states=output_hidden_states,
1152
+ return_dict=return_dict,
1153
+ )
1154
+
1155
+ sequence_output = outputs[0]
1156
+
1157
+ logits = self.qa_outputs(sequence_output)
1158
+ start_logits, end_logits = logits.split(1, dim=-1)
1159
+ start_logits = start_logits.squeeze(-1).contiguous()
1160
+ end_logits = end_logits.squeeze(-1).contiguous()
1161
+
1162
+ total_loss = None
1163
+ if start_positions is not None and end_positions is not None:
1164
+ # If we are on multi-GPU, split add a dimension
1165
+ if len(start_positions.size()) > 1:
1166
+ start_positions = start_positions.squeeze(-1)
1167
+ if len(end_positions.size()) > 1:
1168
+ end_positions = end_positions.squeeze(-1)
1169
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1170
+ ignored_index = start_logits.size(1)
1171
+ start_positions = start_positions.clamp(0, ignored_index)
1172
+ end_positions = end_positions.clamp(0, ignored_index)
1173
+
1174
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1175
+ start_loss = loss_fct(start_logits, start_positions)
1176
+ end_loss = loss_fct(end_logits, end_positions)
1177
+ total_loss = (start_loss + end_loss) / 2
1178
+
1179
+ if not return_dict:
1180
+ output = (start_logits, end_logits) + outputs[2:]
1181
+ return ((total_loss,) + output) if total_loss is not None else output
1182
+
1183
+ return QuestionAnsweringModelOutput(
1184
+ loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states
1185
+ )
pllava/lib/python3.10/site-packages/transformers/models/fnet/tokenization_fnet.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google Research, Google AI, Google Brain and the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Tokenization classes for FNet model."""
16
+
17
+ import os
18
+ import unicodedata
19
+ from shutil import copyfile
20
+ from typing import Any, Dict, List, Optional, Tuple
21
+
22
+ import sentencepiece as spm
23
+
24
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
25
+ from ...utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
30
+
31
+ PRETRAINED_VOCAB_FILES_MAP = {
32
+ "vocab_file": {
33
+ "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/spiece.model",
34
+ "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/spiece.model",
35
+ },
36
+ }
37
+
38
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
39
+ "google/fnet-base": 512,
40
+ "google/fnet-large": 512,
41
+ }
42
+
43
+ SPIECE_UNDERLINE = "▁"
44
+
45
+
46
+ class FNetTokenizer(PreTrainedTokenizer):
47
+ """
48
+ Construct an FNet tokenizer. Adapted from [`AlbertTokenizer`]. Based on
49
+ [SentencePiece](https://github.com/google/sentencepiece). This tokenizer inherits from [`PreTrainedTokenizer`]
50
+ which contains most of the main methods. Users should refer to this superclass for more information regarding those
51
+ methods.
52
+
53
+ Args:
54
+ vocab_file (`str`):
55
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
56
+ contains the vocabulary necessary to instantiate a tokenizer.
57
+ do_lower_case (`bool`, *optional*, defaults to `False`):
58
+ Whether or not to lowercase the input when tokenizing.
59
+ remove_space (`bool`, *optional*, defaults to `True`):
60
+ Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
61
+ keep_accents (`bool`, *optional*, defaults to `True`):
62
+ Whether or not to keep accents when tokenizing.
63
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
64
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
65
+ token instead.
66
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
67
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
68
+ sequence classification or for a text and a question for question answering. It is also used as the last
69
+ token of a sequence built with special tokens.
70
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
71
+ The token used for padding, for example when batching sequences of different lengths.
72
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
73
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
74
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
75
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
76
+ The token used for masking values. This is the token used when training this model with masked language
77
+ modeling. This is the token which the model will try to predict.
78
+ sp_model_kwargs (`dict`, *optional*):
79
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
80
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
81
+ to set:
82
+
83
+ - `enable_sampling`: Enable subword regularization.
84
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
85
+
86
+ - `nbest_size = {0,1}`: No sampling is performed.
87
+ - `nbest_size > 1`: samples from the nbest_size results.
88
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
89
+ using forward-filtering-and-backward-sampling algorithm.
90
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
91
+ BPE-dropout.
92
+
93
+ Attributes:
94
+ sp_model (`SentencePieceProcessor`):
95
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
96
+ """
97
+
98
+ vocab_files_names = VOCAB_FILES_NAMES
99
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
100
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
101
+ model_input_names = ["input_ids", "token_type_ids"]
102
+
103
+ def __init__(
104
+ self,
105
+ vocab_file,
106
+ do_lower_case=False,
107
+ remove_space=True,
108
+ keep_accents=True,
109
+ unk_token="<unk>",
110
+ sep_token="[SEP]",
111
+ pad_token="<pad>",
112
+ cls_token="[CLS]",
113
+ mask_token="[MASK]",
114
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
115
+ **kwargs,
116
+ ) -> None:
117
+ # Mask token behave like a normal word, i.e. include the space before it and
118
+ # is included in the raw text, there should be a match in a non-normalized sentence.
119
+ mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
120
+ cls_token = AddedToken(cls_token, special=True) if isinstance(cls_token, str) else cls_token
121
+ sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
122
+ mask_token = AddedToken(mask_token, special=True) if isinstance(mask_token, str) else mask_token
123
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
124
+
125
+ self.do_lower_case = do_lower_case
126
+ self.remove_space = remove_space
127
+ self.keep_accents = keep_accents
128
+ self.vocab_file = vocab_file
129
+
130
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
131
+ self.sp_model.Load(vocab_file)
132
+
133
+ super().__init__(
134
+ do_lower_case=do_lower_case,
135
+ remove_space=remove_space,
136
+ keep_accents=keep_accents,
137
+ unk_token=unk_token,
138
+ sep_token=sep_token,
139
+ pad_token=pad_token,
140
+ cls_token=cls_token,
141
+ mask_token=mask_token,
142
+ sp_model_kwargs=self.sp_model_kwargs,
143
+ **kwargs,
144
+ )
145
+
146
+ @property
147
+ def vocab_size(self):
148
+ return len(self.sp_model)
149
+
150
+ def get_vocab(self):
151
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
152
+ vocab.update(self.added_tokens_encoder)
153
+ return vocab
154
+
155
+ def __getstate__(self):
156
+ state = self.__dict__.copy()
157
+ state["sp_model"] = None
158
+ return state
159
+
160
+ def __setstate__(self, d):
161
+ self.__dict__ = d
162
+
163
+ # for backward compatibility
164
+ if not hasattr(self, "sp_model_kwargs"):
165
+ self.sp_model_kwargs = {}
166
+
167
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
168
+ self.sp_model.Load(self.vocab_file)
169
+
170
+ def preprocess_text(self, inputs):
171
+ if self.remove_space:
172
+ outputs = " ".join(inputs.strip().split())
173
+ else:
174
+ outputs = inputs
175
+ outputs = outputs.replace("``", '"').replace("''", '"')
176
+
177
+ if not self.keep_accents:
178
+ outputs = unicodedata.normalize("NFKD", outputs)
179
+ outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
180
+ if self.do_lower_case:
181
+ outputs = outputs.lower()
182
+
183
+ return outputs
184
+
185
+ def _tokenize(self, text: str) -> List[str]:
186
+ """Tokenize a string."""
187
+ text = self.preprocess_text(text)
188
+ pieces = self.sp_model.encode(text, out_type=str)
189
+ new_pieces = []
190
+ for piece in pieces:
191
+ if len(piece) > 1 and piece[-1] == str(",") and piece[-2].isdigit():
192
+ cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
193
+ if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
194
+ if len(cur_pieces[0]) == 1:
195
+ cur_pieces = cur_pieces[1:]
196
+ else:
197
+ cur_pieces[0] = cur_pieces[0][1:]
198
+ cur_pieces.append(piece[-1])
199
+ new_pieces.extend(cur_pieces)
200
+ else:
201
+ new_pieces.append(piece)
202
+
203
+ return new_pieces
204
+
205
+ def _convert_token_to_id(self, token):
206
+ """Converts a token (str) in an id using the vocab."""
207
+ return self.sp_model.PieceToId(token)
208
+
209
+ def _convert_id_to_token(self, index):
210
+ """Converts an index (integer) in a token (str) using the vocab."""
211
+ return self.sp_model.IdToPiece(index)
212
+
213
+ # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.convert_tokens_to_string
214
+ def convert_tokens_to_string(self, tokens):
215
+ """Converts a sequence of tokens (string) in a single string."""
216
+ current_sub_tokens = []
217
+ out_string = ""
218
+ prev_is_special = False
219
+ for token in tokens:
220
+ # make sure that special tokens are not decoded using sentencepiece model
221
+ if token in self.all_special_tokens:
222
+ if not prev_is_special:
223
+ out_string += " "
224
+ out_string += self.sp_model.decode(current_sub_tokens) + token
225
+ prev_is_special = True
226
+ current_sub_tokens = []
227
+ else:
228
+ current_sub_tokens.append(token)
229
+ prev_is_special = False
230
+ out_string += self.sp_model.decode(current_sub_tokens)
231
+ return out_string.strip()
232
+
233
+ def _decode(
234
+ self,
235
+ token_ids: List[int],
236
+ skip_special_tokens: bool = False,
237
+ clean_up_tokenization_spaces: bool = None,
238
+ spaces_between_special_tokens: bool = False,
239
+ **kwargs,
240
+ ) -> str:
241
+ text = super()._decode(
242
+ token_ids=token_ids,
243
+ skip_special_tokens=skip_special_tokens,
244
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
245
+ spaces_between_special_tokens=spaces_between_special_tokens,
246
+ **kwargs,
247
+ )
248
+ # Mimic the behavior of the Rust tokenizer:
249
+ # No space after <unk>
250
+ if not spaces_between_special_tokens:
251
+ text = text.replace("<unk> ", "<unk>")
252
+ return text
253
+
254
+ def build_inputs_with_special_tokens(
255
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
256
+ ) -> List[int]:
257
+ """
258
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
259
+ adding special tokens. An FNet sequence has the following format:
260
+
261
+ - single sequence: `[CLS] X [SEP]`
262
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
263
+
264
+ Args:
265
+ token_ids_0 (`List[int]`):
266
+ List of IDs to which the special tokens will be added.
267
+ token_ids_1 (`List[int]`, *optional*):
268
+ Optional second list of IDs for sequence pairs.
269
+
270
+ Returns:
271
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
272
+ """
273
+ sep = [self.sep_token_id]
274
+ cls = [self.cls_token_id]
275
+ if token_ids_1 is None:
276
+ return cls + token_ids_0 + sep
277
+ return cls + token_ids_0 + sep + token_ids_1 + sep
278
+
279
+ def get_special_tokens_mask(
280
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
281
+ ) -> List[int]:
282
+ """
283
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
284
+ special tokens using the tokenizer `prepare_for_model` method.
285
+
286
+ Args:
287
+ token_ids_0 (`List[int]`):
288
+ List of IDs.
289
+ token_ids_1 (`List[int]`, *optional*):
290
+ Optional second list of IDs for sequence pairs.
291
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
292
+ Whether or not the token list is already formatted with special tokens for the model.
293
+
294
+ Returns:
295
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
296
+ """
297
+
298
+ if already_has_special_tokens:
299
+ return super().get_special_tokens_mask(
300
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
301
+ )
302
+
303
+ if token_ids_1 is not None:
304
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
305
+ return [1] + ([0] * len(token_ids_0)) + [1]
306
+
307
+ def create_token_type_ids_from_sequences(
308
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
309
+ ) -> List[int]:
310
+ """
311
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An FNet sequence
312
+ pair mask has the following format: :
313
+
314
+ ```
315
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence |
316
+ ```
317
+
318
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
319
+
320
+ Args:
321
+ token_ids_0 (`List[int]`):
322
+ List of IDs.
323
+ token_ids_1 (`List[int]`, *optional*):
324
+ Optional second list of IDs for sequence pairs.
325
+
326
+ Returns:
327
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
328
+ """
329
+ sep = [self.sep_token_id]
330
+ cls = [self.cls_token_id]
331
+
332
+ if token_ids_1 is None:
333
+ return len(cls + token_ids_0 + sep) * [0]
334
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
335
+
336
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
337
+ if not os.path.isdir(save_directory):
338
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
339
+ return
340
+ out_vocab_file = os.path.join(
341
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
342
+ )
343
+
344
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
345
+ copyfile(self.vocab_file, out_vocab_file)
346
+ elif not os.path.isfile(self.vocab_file):
347
+ with open(out_vocab_file, "wb") as fi:
348
+ content_spiece_model = self.sp_model.serialized_model_proto()
349
+ fi.write(content_spiece_model)
350
+
351
+ return (out_vocab_file,)
pllava/lib/python3.10/site-packages/transformers/models/fnet/tokenization_fnet_fast.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google AI, Google Brain and the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Tokenization classes for FNet model."""
16
+
17
+
18
+ import os
19
+ from shutil import copyfile
20
+ from typing import List, Optional, Tuple
21
+
22
+ from ...tokenization_utils import AddedToken
23
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
24
+ from ...utils import is_sentencepiece_available, logging
25
+
26
+
27
+ if is_sentencepiece_available():
28
+ from .tokenization_fnet import FNetTokenizer
29
+ else:
30
+ FNetTokenizer = None
31
+
32
+ logger = logging.get_logger(__name__)
33
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
34
+
35
+ PRETRAINED_VOCAB_FILES_MAP = {
36
+ "vocab_file": {
37
+ "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/spiece.model",
38
+ "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/spiece.model",
39
+ },
40
+ "tokenizer_file": {
41
+ "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json",
42
+ "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json",
43
+ },
44
+ }
45
+
46
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
47
+ "google/fnet-base": 512,
48
+ "google/fnet-large": 512,
49
+ }
50
+
51
+ SPIECE_UNDERLINE = "▁"
52
+
53
+
54
+ class FNetTokenizerFast(PreTrainedTokenizerFast):
55
+ """
56
+ Construct a "fast" FNetTokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
57
+ [`AlbertTokenizerFast`]. Based on
58
+ [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This
59
+ tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to
60
+ this superclass for more information regarding those methods
61
+
62
+ Args:
63
+ vocab_file (`str`):
64
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
65
+ contains the vocabulary necessary to instantiate a tokenizer.
66
+ do_lower_case (`bool`, *optional*, defaults to `False`):
67
+ Whether or not to lowercase the input when tokenizing.
68
+ remove_space (`bool`, *optional*, defaults to `True`):
69
+ Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
70
+ keep_accents (`bool`, *optional*, defaults to `True`):
71
+ Whether or not to keep accents when tokenizing.
72
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
73
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
74
+ token instead.
75
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
76
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
77
+ sequence classification or for a text and a question for question answering. It is also used as the last
78
+ token of a sequence built with special tokens.
79
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
80
+ The token used for padding, for example when batching sequences of different lengths.
81
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
82
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
83
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
84
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
85
+ The token used for masking values. This is the token used when training this model with masked language
86
+ modeling. This is the token which the model will try to predict.
87
+ """
88
+
89
+ vocab_files_names = VOCAB_FILES_NAMES
90
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
91
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
92
+ model_input_names = ["input_ids", "token_type_ids"]
93
+ slow_tokenizer_class = FNetTokenizer
94
+
95
+ def __init__(
96
+ self,
97
+ vocab_file=None,
98
+ tokenizer_file=None,
99
+ do_lower_case=False,
100
+ remove_space=True,
101
+ keep_accents=True,
102
+ unk_token="<unk>",
103
+ sep_token="[SEP]",
104
+ pad_token="<pad>",
105
+ cls_token="[CLS]",
106
+ mask_token="[MASK]",
107
+ **kwargs,
108
+ ):
109
+ # Mask token behave like a normal word, i.e. include the space before it and
110
+ # is included in the raw text, there should be a match in a non-normalized sentence.
111
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
112
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
113
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
114
+
115
+ super().__init__(
116
+ vocab_file,
117
+ tokenizer_file=tokenizer_file,
118
+ do_lower_case=do_lower_case,
119
+ remove_space=remove_space,
120
+ keep_accents=keep_accents,
121
+ unk_token=unk_token,
122
+ sep_token=sep_token,
123
+ pad_token=pad_token,
124
+ cls_token=cls_token,
125
+ mask_token=mask_token,
126
+ **kwargs,
127
+ )
128
+
129
+ self.do_lower_case = do_lower_case
130
+ self.remove_space = remove_space
131
+ self.keep_accents = keep_accents
132
+ self.vocab_file = vocab_file
133
+
134
+ @property
135
+ def can_save_slow_tokenizer(self) -> bool:
136
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
137
+
138
+ def build_inputs_with_special_tokens(
139
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
140
+ ) -> List[int]:
141
+ """
142
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
143
+ adding special tokens. An FNet sequence has the following format:
144
+
145
+ - single sequence: `[CLS] X [SEP]`
146
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
147
+
148
+ Args:
149
+ token_ids_0 (`List[int]`):
150
+ List of IDs to which the special tokens will be added
151
+ token_ids_1 (`List[int]`, *optional*):
152
+ Optional second list of IDs for sequence pairs.
153
+
154
+ Returns:
155
+ `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
156
+ """
157
+ sep = [self.sep_token_id]
158
+ cls = [self.cls_token_id]
159
+ if token_ids_1 is None:
160
+ return cls + token_ids_0 + sep
161
+ return cls + token_ids_0 + sep + token_ids_1 + sep
162
+
163
+ def create_token_type_ids_from_sequences(
164
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
165
+ ) -> List[int]:
166
+ """
167
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An FNet
168
+ sequence pair mask has the following format:
169
+
170
+ ```
171
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
172
+ | first sequence | second sequence |
173
+ ```
174
+
175
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
176
+
177
+ Args:
178
+ token_ids_0 (`List[int]`):
179
+ List of ids.
180
+ token_ids_1 (`List[int]`, *optional*):
181
+ Optional second list of IDs for sequence pairs.
182
+
183
+ Returns:
184
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
185
+ """
186
+ sep = [self.sep_token_id]
187
+ cls = [self.cls_token_id]
188
+
189
+ if token_ids_1 is None:
190
+ return len(cls + token_ids_0 + sep) * [0]
191
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
192
+
193
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
194
+ if not os.path.isdir(save_directory):
195
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
196
+ return
197
+ out_vocab_file = os.path.join(
198
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
199
+ )
200
+
201
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
202
+ copyfile(self.vocab_file, out_vocab_file)
203
+
204
+ return (out_vocab_file,)
pllava/lib/python3.10/site-packages/transformers/models/kosmos2/__init__.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_torch_available,
21
+ is_vision_available,
22
+ )
23
+
24
+
25
+ _import_structure = {
26
+ "configuration_kosmos2": ["KOSMOS2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Kosmos2Config"],
27
+ "processing_kosmos2": ["Kosmos2Processor"],
28
+ }
29
+
30
+ try:
31
+ if not is_torch_available():
32
+ raise OptionalDependencyNotAvailable()
33
+ except OptionalDependencyNotAvailable:
34
+ pass
35
+ else:
36
+ _import_structure["modeling_kosmos2"] = [
37
+ "KOSMOS2_PRETRAINED_MODEL_ARCHIVE_LIST",
38
+ "Kosmos2ForConditionalGeneration",
39
+ "Kosmos2Model",
40
+ "Kosmos2PreTrainedModel",
41
+ ]
42
+
43
+
44
+ if TYPE_CHECKING:
45
+ from .configuration_kosmos2 import KOSMOS2_PRETRAINED_CONFIG_ARCHIVE_MAP, Kosmos2Config
46
+ from .processing_kosmos2 import Kosmos2Processor
47
+
48
+ try:
49
+ if not is_torch_available():
50
+ raise OptionalDependencyNotAvailable()
51
+ except OptionalDependencyNotAvailable:
52
+ pass
53
+ else:
54
+ from .modeling_kosmos2 import (
55
+ KOSMOS2_PRETRAINED_MODEL_ARCHIVE_LIST,
56
+ Kosmos2ForConditionalGeneration,
57
+ Kosmos2Model,
58
+ Kosmos2PreTrainedModel,
59
+ )
60
+
61
+ else:
62
+ import sys
63
+
64
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)
pllava/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (994 Bytes). View file
 
pllava/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/configuration_kosmos2.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (2.31 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/modeling_kosmos2.cpython-310.pyc ADDED
Binary file (64.3 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/processing_kosmos2.cpython-310.pyc ADDED
Binary file (21 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/kosmos2/configuration_kosmos2.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ KOSMOS-2 model configuration"""
16
+
17
+ import os
18
+ from typing import Union
19
+
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ KOSMOS2_PRETRAINED_CONFIG_ARCHIVE_MAP = {
27
+ "microsoft/kosmos-2-patch14-224": (
28
+ "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/config.json"
29
+ ),
30
+ # See all KOSMOS-2 models at https://huggingface.co/models?filter=kosmos-2
31
+ }
32
+
33
+
34
+ class Kosmos2TextConfig(PretrainedConfig):
35
+ r"""
36
+ This is the configuration class to store the configuration of a [`Kosmos2TextModel`]. It is used to instantiate a
37
+ KOSMOS-2 text decoder according to the specified arguments, defining the model architecture. Instantiating a
38
+ configuration with the defaults will yield a similar configuration to that of the text decoder of the KOSMOS-2
39
+ [microsoft/kosmos-2-patch14-224](https://huggingface.co/microsoft/kosmos-2-patch14-224) architecture.
40
+
41
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
42
+ documentation from [`PretrainedConfig`] for more information.
43
+
44
+ Args:
45
+ vocab_size (`int`, *optional*, defaults to 65037):
46
+ Vocabulary size of the Kosmos2 model. Defines the number of different tokens that can be represented by the
47
+ `inputs_ids` passed when calling [`Kosmos2Model`].
48
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
49
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
50
+ just in case (e.g., 512 or 1024 or 2048).
51
+ embed_dim (`int`, *optional*, defaults to 2048):
52
+ Dimensionality of the layers and the pooler layer.
53
+ layers (`int`, *optional*, defaults to 24):
54
+ Number of hidden layers in the Transformer encoder.
55
+ ffn_dim (`int`, *optional*, defaults to 8192):
56
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
57
+ attention_heads (`int`, *optional*, defaults to 32):
58
+ Number of attention heads for each attention layer in the Transformer encoder.
59
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
60
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
61
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
62
+ dropout (`float`, *optional*, defaults to 0.1):
63
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
64
+ attention_dropout (`float`, *optional*, defaults to 0.1):
65
+ The dropout ratio for the attention probabilities.
66
+ activation_dropout (`float`, *optional*, defaults to 0.0):
67
+ The dropout ratio for activations inside the fully connected layer.
68
+ layerdrop (`float`, *optional*, defaults to 0.0):
69
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
70
+ for more details.
71
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
72
+ The epsilon used by the layer normalization layers.
73
+ init_std (`float`, *optional*, defaults to 0.02):
74
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
75
+ scale_embedding (`bool`, *optional*, defaults to `True`):
76
+ Scale embeddings by diving by sqrt(embed_dim).
77
+ use_cache (`bool`, *optional*, defaults to `True`):
78
+ Whether or not the model should return the last key/values attentions (not used by all models).
79
+ ```"""
80
+
81
+ model_type = "kosmos_2_text_model"
82
+ keys_to_ignore_at_inference = ["past_key_values"]
83
+ attribute_map = {
84
+ "num_attention_heads": "attention_heads",
85
+ "hidden_size": "embed_dim",
86
+ "num_hidden_layers": "layers",
87
+ }
88
+
89
+ def __init__(
90
+ self,
91
+ vocab_size=65037,
92
+ max_position_embeddings=2048,
93
+ embed_dim=2048,
94
+ layers=24,
95
+ ffn_dim=8192,
96
+ attention_heads=32,
97
+ activation_function="gelu",
98
+ dropout=0.1,
99
+ attention_dropout=0.1,
100
+ activation_dropout=0.0,
101
+ layerdrop=0.0,
102
+ layer_norm_eps=1e-5,
103
+ init_std=0.02,
104
+ scale_embedding=True,
105
+ use_cache=True,
106
+ pad_token_id=1,
107
+ bos_token_id=0,
108
+ eos_token_id=2,
109
+ **kwargs,
110
+ ):
111
+ super().__init__(
112
+ pad_token_id=pad_token_id,
113
+ bos_token_id=bos_token_id,
114
+ eos_token_id=eos_token_id,
115
+ **kwargs,
116
+ )
117
+
118
+ self.vocab_size = vocab_size
119
+ self.max_position_embeddings = max_position_embeddings
120
+ self.embed_dim = embed_dim
121
+ self.layers = layers
122
+ self.ffn_dim = ffn_dim
123
+ self.attention_heads = attention_heads
124
+ self.activation_function = activation_function
125
+ self.dropout = dropout
126
+ self.attention_dropout = attention_dropout
127
+ self.activation_dropout = activation_dropout
128
+ self.layerdrop = layerdrop
129
+ self.layer_norm_eps = layer_norm_eps
130
+ self.init_std = init_std
131
+ self.scale_embedding = scale_embedding
132
+ self.use_cache = use_cache
133
+
134
+ @classmethod
135
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
136
+ cls._set_token_in_kwargs(kwargs)
137
+
138
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
139
+
140
+ # get the text config dict if we are loading from Kosmos2Config
141
+ if config_dict.get("model_type") == "kosmos-2":
142
+ config_dict = config_dict["text_config"]
143
+
144
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
145
+ logger.warning(
146
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
147
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
148
+ )
149
+
150
+ return cls.from_dict(config_dict, **kwargs)
151
+
152
+
153
+ class Kosmos2VisionConfig(PretrainedConfig):
154
+ r"""
155
+ This is the configuration class to store the configuration of a [`Kosmos2VisionModel`]. It is used to instantiate a
156
+ KOSMOS-2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a
157
+ configuration with the defaults will yield a similar configuration to that of the vision encoder of the KOSMOS-2
158
+ [microsoft/kosmos-2-patch14-224](https://huggingface.co/microsoft/kosmos-2-patch14-224) architecture.
159
+
160
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
161
+ documentation from [`PretrainedConfig`] for more information.
162
+
163
+ Args:
164
+ hidden_size (`int`, *optional*, defaults to 1024):
165
+ Dimensionality of the encoder layers and the pooler layer.
166
+ intermediate_size (`int`, *optional*, defaults to 4096):
167
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
168
+ num_hidden_layers (`int`, *optional*, defaults to 24):
169
+ Number of hidden layers in the Transformer encoder.
170
+ num_attention_heads (`int`, *optional*, defaults to 16):
171
+ Number of attention heads for each attention layer in the Transformer encoder.
172
+ num_channels (`int`, *optional*, defaults to 3):
173
+ The number of input channels.
174
+ image_size (`int`, *optional*, defaults to 224):
175
+ The size (resolution) of each image.
176
+ patch_size (`int`, *optional*, defaults to 14):
177
+ The size (resolution) of each patch.
178
+ hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
179
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
180
+ `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
181
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
182
+ The epsilon used by the layer normalization layers.
183
+ attention_dropout (`float`, *optional*, defaults to 0.0):
184
+ The dropout ratio for the attention probabilities.
185
+ initializer_range (`float`, *optional*, defaults to 0.02):
186
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
187
+ initializer_factor (`float`, *optional*, defaults to 1):
188
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
189
+ testing).
190
+ ```"""
191
+
192
+ model_type = "kosmos_2_vision_model"
193
+
194
+ def __init__(
195
+ self,
196
+ hidden_size=1024,
197
+ intermediate_size=4096,
198
+ num_hidden_layers=24,
199
+ num_attention_heads=16,
200
+ num_channels=3,
201
+ image_size=224,
202
+ patch_size=14,
203
+ hidden_act="quick_gelu",
204
+ layer_norm_eps=1e-5,
205
+ attention_dropout=0.0,
206
+ initializer_range=0.02,
207
+ initializer_factor=1.0,
208
+ **kwargs,
209
+ ):
210
+ super().__init__(**kwargs)
211
+
212
+ self.hidden_size = hidden_size
213
+ self.intermediate_size = intermediate_size
214
+ self.num_hidden_layers = num_hidden_layers
215
+ self.num_attention_heads = num_attention_heads
216
+ self.num_channels = num_channels
217
+ self.patch_size = patch_size
218
+ self.image_size = image_size
219
+ self.initializer_range = initializer_range
220
+ self.initializer_factor = initializer_factor
221
+ self.attention_dropout = attention_dropout
222
+ self.layer_norm_eps = layer_norm_eps
223
+ self.hidden_act = hidden_act
224
+
225
+ @classmethod
226
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
227
+ cls._set_token_in_kwargs(kwargs)
228
+
229
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
230
+
231
+ # get the vision config dict if we are loading from Kosmos2Config
232
+ if config_dict.get("model_type") == "kosmos-2":
233
+ config_dict = config_dict["vision_config"]
234
+
235
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
236
+ logger.warning(
237
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
238
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
239
+ )
240
+
241
+ return cls.from_dict(config_dict, **kwargs)
242
+
243
+
244
+ class Kosmos2Config(PretrainedConfig):
245
+ r"""
246
+ This is the configuration class to store the configuration of a [`Kosmos2Model`]. It is used to instantiate a
247
+ KOSMOS-2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
248
+ with the defaults will yield a similar configuration to that of the KOSMOS-2
249
+ [microsoft/kosmos-2-patch14-224](https://huggingface.co/microsoft/kosmos-2-patch14-224) architecture.
250
+
251
+ Args:
252
+ text_config (`dict`, *optional*):
253
+ Dictionary of configuration options used to initialize [`Kosmos2TextConfig`].
254
+ vision_config (`dict`, *optional*):
255
+ Dictionary of configuration options used to initialize [`Kosmos2VisionConfig`].
256
+ latent_query_num (`int`, *optional*, defaults to 64):
257
+ The number of latent query tokens that represent the image features used in the text decoder component.
258
+ kwargs (*optional*):
259
+ Dictionary of keyword arguments.
260
+
261
+ Example:
262
+
263
+ ```python
264
+ >>> from transformers import Kosmos2Config, Kosmos2Model
265
+
266
+ >>> # Initializing a Kosmos-2 kosmos-2-patch14-224 style configuration
267
+ >>> configuration = Kosmos2Config()
268
+
269
+ >>> # Initializing a model (with random weights) from the kosmos-2-patch14-224 style configuration
270
+ >>> model = Kosmos2Model(configuration)
271
+
272
+ >>> # Accessing the model configuration
273
+ >>> configuration = model.config
274
+ ```"""
275
+
276
+ model_type = "kosmos-2"
277
+ is_composition = True
278
+
279
+ def __init__(
280
+ self,
281
+ text_config=None,
282
+ vision_config=None,
283
+ latent_query_num=64,
284
+ **kwargs,
285
+ ):
286
+ super().__init__(**kwargs)
287
+
288
+ if text_config is None:
289
+ text_config = {}
290
+ logger.info("`text_config` is `None`. Initializing the `Kosmos2TextConfig` with default values.")
291
+
292
+ if vision_config is None:
293
+ vision_config = {}
294
+ logger.info("`vision_config` is `None`. Initializing the `Kosmos2VisionConfig` with default values.")
295
+
296
+ self.text_config = Kosmos2TextConfig(**text_config)
297
+ self.vision_config = Kosmos2VisionConfig(**vision_config)
298
+
299
+ self.latent_query_num = latent_query_num
pllava/lib/python3.10/site-packages/transformers/models/kosmos2/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ from fairseq.checkpoint_utils import load_checkpoint_to_cpu
4
+
5
+ from transformers import Kosmos2Config, Kosmos2ForConditionalGeneration
6
+
7
+
8
+ KEYS_TO_MODIFY_MAPPING = {
9
+ "gpt_model.decoder.output_projection": "text_model.lm_head",
10
+ "gpt_model.decoder": "text_model.model",
11
+ "img_connector": "image_to_text_projection",
12
+ "img_model.visual.class_embedding": "vision_model.model.embeddings.class_embedding",
13
+ "img_model.visual.positional_embedding": "vision_model.model.embeddings.position_embedding.weight",
14
+ "img_model.visual.conv1": "vision_model.model.embeddings.patch_embedding",
15
+ "img_model.visual": "vision_model.model",
16
+ "ln_pre": "pre_layrnorm",
17
+ "ln_post": "post_layernorm",
18
+ "transformer.resblocks": "encoder.layers",
19
+ "ts_attn": "self_attn",
20
+ "ln_1": "layer_norm1",
21
+ "ln_2": "layer_norm2",
22
+ "c_fc": "fc1",
23
+ "c_proj": "fc2",
24
+ }
25
+
26
+
27
+ KEYS_TO_IGNORE = [
28
+ # this buffer in the original code is only used to send weights to the desired device
29
+ "gpt_model.decoder.embed_positions._float_tensor",
30
+ # this weight is never used in the forward in the original KOSMOS-2)
31
+ "gpt_model.decoder.self_attn_sope.scale",
32
+ ]
33
+
34
+
35
+ def rename_key(key):
36
+ for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
37
+ if key_to_modify in key:
38
+ key = key.replace(key_to_modify, new_key)
39
+
40
+ return key
41
+
42
+
43
+ def convert_kosmos2_checkpoint_to_pytorch(checkpoint_path, pytorch_dump_folder_path):
44
+ state = load_checkpoint_to_cpu(checkpoint_path)
45
+ state_dict = state["model"]
46
+ state_dict_keys = list(state_dict.keys())
47
+
48
+ config = Kosmos2Config()
49
+ # This is necessary to match the results given by the original demo
50
+ config.text_config.no_repeat_ngram_size = 3
51
+ model = Kosmos2ForConditionalGeneration(config)
52
+
53
+ # convert (by renaming keys)
54
+ converted_state_dict = {}
55
+ for key in state_dict_keys:
56
+ if key in KEYS_TO_IGNORE:
57
+ continue
58
+ renamed_key = rename_key(key)
59
+ converted_state_dict[renamed_key] = state_dict[key]
60
+
61
+ # check weight loading
62
+ model.load_state_dict(converted_state_dict, strict=True)
63
+ # save the result
64
+ model.save_pretrained(pytorch_dump_folder_path)
65
+
66
+
67
+ if __name__ == "__main__":
68
+ parser = argparse.ArgumentParser()
69
+ # Required parameters
70
+ parser.add_argument(
71
+ "--kosmos2_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump."
72
+ )
73
+ parser.add_argument(
74
+ "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
75
+ )
76
+ args = parser.parse_args()
77
+ convert_kosmos2_checkpoint_to_pytorch(args.kosmos2_checkpoint_path, args.pytorch_dump_folder_path)
pllava/lib/python3.10/site-packages/transformers/models/kosmos2/modeling_kosmos2.py ADDED
@@ -0,0 +1,2056 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch KOSMOS-2 model."""
16
+
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Any, List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...modeling_outputs import (
29
+ BaseModelOutput,
30
+ BaseModelOutputWithPastAndCrossAttentions,
31
+ BaseModelOutputWithPooling,
32
+ CausalLMOutputWithCrossAttentions,
33
+ )
34
+ from ...modeling_utils import PreTrainedModel
35
+ from ...utils import (
36
+ ModelOutput,
37
+ add_start_docstrings,
38
+ add_start_docstrings_to_model_forward,
39
+ logging,
40
+ replace_return_docstrings,
41
+ )
42
+ from .configuration_kosmos2 import Kosmos2Config, Kosmos2TextConfig, Kosmos2VisionConfig
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _CONFIG_FOR_DOC = Kosmos2Config
48
+
49
+ KOSMOS2_PRETRAINED_MODEL_ARCHIVE_LIST = [
50
+ "microsoft/kosmos-2-patch14-224",
51
+ # See all KOSMOS-2 models at https://huggingface.co/models?filter=kosmos-2
52
+ ]
53
+
54
+
55
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
56
+ """
57
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
58
+ """
59
+ bsz, src_len = mask.size()
60
+ tgt_len = tgt_len if tgt_len is not None else src_len
61
+
62
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
63
+
64
+ inverted_mask = 1.0 - expanded_mask
65
+
66
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
67
+
68
+
69
+ def _make_causal_mask(
70
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
71
+ ):
72
+ """
73
+ Make causal mask used for bi-directional self-attention.
74
+ """
75
+ bsz, tgt_len = input_ids_shape
76
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
77
+ mask_cond = torch.arange(mask.size(-1), device=device)
78
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
79
+ mask = mask.to(dtype)
80
+
81
+ if past_key_values_length > 0:
82
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
83
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
84
+
85
+
86
+ # Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
87
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
88
+ """
89
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
90
+ are ignored. This is modified from fairseq's `utils.make_positions`.
91
+
92
+ Args:
93
+ x: torch.Tensor x:
94
+
95
+ Returns: torch.Tensor
96
+ """
97
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
98
+ mask = input_ids.ne(padding_idx).int()
99
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
100
+ return incremental_indices.long() + padding_idx
101
+
102
+
103
+ KOSMOS2_START_DOCSTRING = r"""
104
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
105
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
106
+ etc.)
107
+
108
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
109
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
110
+ and behavior.
111
+
112
+ Parameters:
113
+ config ([`Kosmos2Config`]): Model configuration class with all the parameters of the model.
114
+ Initializing with a config file does not load the weights associated with the model, only the
115
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
116
+ """
117
+
118
+ KOSMOS2_VISION_INPUTS_DOCSTRING = r"""
119
+ Args:
120
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
121
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
122
+ [`CLIPImageProcessor.__call__`] for details.
123
+ output_attentions (`bool`, *optional*):
124
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
125
+ tensors for more detail.
126
+ output_hidden_states (`bool`, *optional*):
127
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
128
+ more detail.
129
+ return_dict (`bool`, *optional*):
130
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
131
+ """
132
+
133
+ KOSMOS2_TEXT_INPUTS_DOCSTRING = r"""
134
+ Args:
135
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
136
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
137
+ it.
138
+
139
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
140
+ [`PreTrainedTokenizer.__call__`] for details.
141
+
142
+ [What are input IDs?](../glossary#input-ids)
143
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
144
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
145
+
146
+ - 1 for tokens that are **not masked**,
147
+ - 0 for tokens that are **masked**.
148
+
149
+ [What are attention masks?](../glossary#attention-mask)
150
+ image_embeds: (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
151
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
152
+ image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
153
+ Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
154
+ 1]`:
155
+
156
+ - 1 for places where to put the image features,
157
+ - 0 for places that are not for image features (i.e. for text tokens).
158
+
159
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
160
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
161
+ the model is configured as a decoder.
162
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
163
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
164
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
165
+
166
+ - 1 for tokens that are **not masked**,
167
+ - 0 for tokens that are **masked**.
168
+
169
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
170
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
171
+
172
+ - 1 indicates the head is **not masked**,
173
+ - 0 indicates the head is **masked**.
174
+
175
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
176
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
177
+
178
+ - 1 indicates the head is **not masked**,
179
+ - 0 indicates the head is **masked**.
180
+
181
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
182
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
183
+
184
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
185
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
186
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
187
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
188
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
189
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
190
+ model's internal embedding lookup matrix.
191
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
192
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
193
+ config.max_position_embeddings - 1]`.
194
+
195
+ [What are position IDs?](../glossary#position-ids)
196
+ use_cache (`bool`, *optional*):
197
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
198
+ `past_key_values`).
199
+ output_attentions (`bool`, *optional*):
200
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
201
+ tensors for more detail.
202
+ output_hidden_states (`bool`, *optional*):
203
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
204
+ more detail.
205
+ return_dict (`bool`, *optional*):
206
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
207
+ """
208
+
209
+ KOSMOS2_INPUTS_DOCSTRING = r"""
210
+ Args:
211
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
212
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
213
+ [`CLIPImageProcessor.__call__`] for details.
214
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
215
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
216
+ it.
217
+
218
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
219
+ [`PreTrainedTokenizer.__call__`] for details.
220
+
221
+ [What are input IDs?](../glossary#input-ids)
222
+ image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
223
+ Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
224
+ 1]`:
225
+
226
+ - 1 for places where to put the image features,
227
+ - 0 for places that are not for image features (i.e. for text tokens).
228
+
229
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
230
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
231
+
232
+ - 1 for tokens that are **not masked**,
233
+ - 0 for tokens that are **masked**.
234
+
235
+ [What are attention masks?](../glossary#attention-mask)
236
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
237
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
238
+
239
+ - 1 indicates the head is **not masked**,
240
+ - 0 indicates the head is **masked**.
241
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
242
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
243
+
244
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
245
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
246
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
247
+ image_embeds: (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
248
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
249
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
250
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
251
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
252
+ model's internal embedding lookup matrix.
253
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
254
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
255
+ config.max_position_embeddings - 1]`.
256
+
257
+ [What are position IDs?](../glossary#position-ids)
258
+ use_cache (`bool`, *optional*):
259
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
260
+ `past_key_values`).
261
+ output_attentions (`bool`, *optional*):
262
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
263
+ tensors for more detail.
264
+ output_hidden_states (`bool`, *optional*):
265
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
266
+ more detail.
267
+ return_dict (`bool`, *optional*):
268
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
269
+ """
270
+
271
+
272
+ @dataclass
273
+ class Kosmos2ModelOutput(ModelOutput):
274
+ """
275
+ Base class for text model's outputs that also contains a pooling of the last hidden states.
276
+
277
+ Args:
278
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
279
+ Sequence of hidden-states at the output of the last layer of the model.
280
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
281
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
282
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
283
+
284
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
285
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
286
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
287
+ sequence_length)`.
288
+
289
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
290
+ heads.
291
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
292
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
293
+ projection_attentions (`tuple(torch.FloatTensor)`, *optional*):
294
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
295
+ sequence_length)`.
296
+
297
+ Attentions weights given by `Kosmos2ImageToTextProjection`, after the attention softmax, used to compute
298
+ the weighted average in the self-attention heads.
299
+ vision_model_output(`BaseModelOutputWithPooling`, *optional*):
300
+ The output of the [`Kosmos2VisionModel`].
301
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
302
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
303
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
304
+ `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
305
+ encoder_sequence_length, embed_size_per_head)`.
306
+
307
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
308
+ `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
309
+ input) to speed up sequential decoding.
310
+ """
311
+
312
+ last_hidden_state: torch.FloatTensor = None
313
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
314
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
315
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
316
+ image_embeds: Optional[torch.FloatTensor] = None
317
+ projection_attentions: Optional[Tuple[torch.FloatTensor]] = None
318
+ vision_model_output: BaseModelOutputWithPooling = None
319
+
320
+ def to_tuple(self) -> Tuple[Any]:
321
+ return tuple(
322
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
323
+ for k in self.keys()
324
+ )
325
+
326
+
327
+ @dataclass
328
+ class Kosmos2ForConditionalGenerationModelOutput(ModelOutput):
329
+ """
330
+ Model output class for `Kosmos2ForConditionalGeneration`.
331
+
332
+ Args:
333
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
334
+ Language modeling loss (for next-token prediction).
335
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
336
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
337
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
338
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
339
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
340
+
341
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
342
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
343
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
344
+ sequence_length)`.
345
+
346
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
347
+ heads.
348
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
349
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
350
+ projection_attentions (`tuple(torch.FloatTensor)`, *optional*):
351
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
352
+ sequence_length)`.
353
+
354
+ Attentions weights given by `Kosmos2ImageToTextProjection`, after the attention softmax, used to compute
355
+ the weighted average in the self-attention heads.
356
+ vision_model_output(`BaseModelOutputWithPooling`, *optional*):
357
+ The output of the [`Kosmos2VisionModel`].
358
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
359
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
360
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
361
+ `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
362
+ encoder_sequence_length, embed_size_per_head)`.
363
+
364
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
365
+ `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
366
+ input) to speed up sequential decoding.
367
+ """
368
+
369
+ loss: Optional[torch.FloatTensor] = None
370
+ logits: torch.FloatTensor = None
371
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
372
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
373
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
374
+ image_embeds: Optional[torch.FloatTensor] = None
375
+ projection_attentions: Optional[Tuple[torch.FloatTensor]] = None
376
+ vision_model_output: BaseModelOutputWithPooling = None
377
+
378
+ def to_tuple(self) -> Tuple[Any]:
379
+ return tuple(
380
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
381
+ for k in self.keys()
382
+ )
383
+
384
+
385
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->Kosmos2
386
+ class Kosmos2VisionEmbeddings(nn.Module):
387
+ def __init__(self, config: Kosmos2VisionConfig):
388
+ super().__init__()
389
+ self.config = config
390
+ self.embed_dim = config.hidden_size
391
+ self.image_size = config.image_size
392
+ self.patch_size = config.patch_size
393
+
394
+ self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
395
+
396
+ self.patch_embedding = nn.Conv2d(
397
+ in_channels=config.num_channels,
398
+ out_channels=self.embed_dim,
399
+ kernel_size=self.patch_size,
400
+ stride=self.patch_size,
401
+ bias=False,
402
+ )
403
+
404
+ self.num_patches = (self.image_size // self.patch_size) ** 2
405
+ self.num_positions = self.num_patches + 1
406
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
407
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
408
+
409
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
410
+ batch_size = pixel_values.shape[0]
411
+ target_dtype = self.patch_embedding.weight.dtype
412
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
413
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
414
+
415
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1)
416
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
417
+ embeddings = embeddings + self.position_embedding(self.position_ids)
418
+ return embeddings
419
+
420
+
421
+ # Copied from transformers.models.clip.modeling_clip.CLIPAttention with CLIP->Kosmos2Vision
422
+ class Kosmos2VisionAttention(nn.Module):
423
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
424
+
425
+ def __init__(self, config):
426
+ super().__init__()
427
+ self.config = config
428
+ self.embed_dim = config.hidden_size
429
+ self.num_heads = config.num_attention_heads
430
+ self.head_dim = self.embed_dim // self.num_heads
431
+ if self.head_dim * self.num_heads != self.embed_dim:
432
+ raise ValueError(
433
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
434
+ f" {self.num_heads})."
435
+ )
436
+ self.scale = self.head_dim**-0.5
437
+ self.dropout = config.attention_dropout
438
+
439
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
440
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
441
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
442
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
443
+
444
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
445
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
446
+
447
+ def forward(
448
+ self,
449
+ hidden_states: torch.Tensor,
450
+ attention_mask: Optional[torch.Tensor] = None,
451
+ causal_attention_mask: Optional[torch.Tensor] = None,
452
+ output_attentions: Optional[bool] = False,
453
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
454
+ """Input shape: Batch x Time x Channel"""
455
+
456
+ bsz, tgt_len, embed_dim = hidden_states.size()
457
+
458
+ # get query proj
459
+ query_states = self.q_proj(hidden_states) * self.scale
460
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
461
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
462
+
463
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
464
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
465
+ key_states = key_states.view(*proj_shape)
466
+ value_states = value_states.view(*proj_shape)
467
+
468
+ src_len = key_states.size(1)
469
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
470
+
471
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
472
+ raise ValueError(
473
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
474
+ f" {attn_weights.size()}"
475
+ )
476
+
477
+ # apply the causal_attention_mask first
478
+ if causal_attention_mask is not None:
479
+ if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
480
+ raise ValueError(
481
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
482
+ f" {causal_attention_mask.size()}"
483
+ )
484
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
485
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
486
+
487
+ if attention_mask is not None:
488
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
489
+ raise ValueError(
490
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
491
+ )
492
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
493
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
494
+
495
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
496
+
497
+ if output_attentions:
498
+ # this operation is a bit akward, but it's required to
499
+ # make sure that attn_weights keeps its gradient.
500
+ # In order to do so, attn_weights have to reshaped
501
+ # twice and have to be reused in the following
502
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
503
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
504
+ else:
505
+ attn_weights_reshaped = None
506
+
507
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
508
+
509
+ attn_output = torch.bmm(attn_probs, value_states)
510
+
511
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
512
+ raise ValueError(
513
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
514
+ f" {attn_output.size()}"
515
+ )
516
+
517
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
518
+ attn_output = attn_output.transpose(1, 2)
519
+ attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
520
+
521
+ attn_output = self.out_proj(attn_output)
522
+
523
+ return attn_output, attn_weights_reshaped
524
+
525
+
526
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Kosmos2Vision
527
+ class Kosmos2VisionMLP(nn.Module):
528
+ def __init__(self, config):
529
+ super().__init__()
530
+ self.config = config
531
+ self.activation_fn = ACT2FN[config.hidden_act]
532
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
533
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
534
+
535
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
536
+ hidden_states = self.fc1(hidden_states)
537
+ hidden_states = self.activation_fn(hidden_states)
538
+ hidden_states = self.fc2(hidden_states)
539
+ return hidden_states
540
+
541
+
542
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Kosmos2Vision
543
+ class Kosmos2VisionEncoderLayer(nn.Module):
544
+ def __init__(self, config: Kosmos2VisionConfig):
545
+ super().__init__()
546
+ self.embed_dim = config.hidden_size
547
+ self.self_attn = Kosmos2VisionAttention(config)
548
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
549
+ self.mlp = Kosmos2VisionMLP(config)
550
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
551
+
552
+ def forward(
553
+ self,
554
+ hidden_states: torch.Tensor,
555
+ attention_mask: torch.Tensor,
556
+ causal_attention_mask: torch.Tensor,
557
+ output_attentions: Optional[bool] = False,
558
+ ) -> Tuple[torch.FloatTensor]:
559
+ """
560
+ Args:
561
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
562
+ attention_mask (`torch.FloatTensor`): attention mask of size
563
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
564
+ `(config.encoder_attention_heads,)`.
565
+ output_attentions (`bool`, *optional*):
566
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
567
+ returned tensors for more detail.
568
+ """
569
+ residual = hidden_states
570
+
571
+ hidden_states = self.layer_norm1(hidden_states)
572
+ hidden_states, attn_weights = self.self_attn(
573
+ hidden_states=hidden_states,
574
+ attention_mask=attention_mask,
575
+ causal_attention_mask=causal_attention_mask,
576
+ output_attentions=output_attentions,
577
+ )
578
+ hidden_states = residual + hidden_states
579
+
580
+ residual = hidden_states
581
+ hidden_states = self.layer_norm2(hidden_states)
582
+ hidden_states = self.mlp(hidden_states)
583
+ hidden_states = residual + hidden_states
584
+
585
+ outputs = (hidden_states,)
586
+
587
+ if output_attentions:
588
+ outputs += (attn_weights,)
589
+
590
+ return outputs
591
+
592
+
593
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Kosmos2Vision
594
+ class Kosmos2VisionEncoder(nn.Module):
595
+ """
596
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
597
+ [`Kosmos2VisionEncoderLayer`].
598
+
599
+ Args:
600
+ config: Kosmos2VisionConfig
601
+ """
602
+
603
+ def __init__(self, config: Kosmos2VisionConfig):
604
+ super().__init__()
605
+ self.config = config
606
+ self.layers = nn.ModuleList([Kosmos2VisionEncoderLayer(config) for _ in range(config.num_hidden_layers)])
607
+ self.gradient_checkpointing = False
608
+
609
+ def forward(
610
+ self,
611
+ inputs_embeds,
612
+ attention_mask: Optional[torch.Tensor] = None,
613
+ causal_attention_mask: Optional[torch.Tensor] = None,
614
+ output_attentions: Optional[bool] = None,
615
+ output_hidden_states: Optional[bool] = None,
616
+ return_dict: Optional[bool] = None,
617
+ ) -> Union[Tuple, BaseModelOutput]:
618
+ r"""
619
+ Args:
620
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
621
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
622
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
623
+ than the model's internal embedding lookup matrix.
624
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
625
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
626
+
627
+ - 1 for tokens that are **not masked**,
628
+ - 0 for tokens that are **masked**.
629
+
630
+ [What are attention masks?](../glossary#attention-mask)
631
+ causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
632
+ Causal mask for the text model. Mask values selected in `[0, 1]`:
633
+
634
+ - 1 for tokens that are **not masked**,
635
+ - 0 for tokens that are **masked**.
636
+
637
+ [What are attention masks?](../glossary#attention-mask)
638
+ output_attentions (`bool`, *optional*):
639
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
640
+ returned tensors for more detail.
641
+ output_hidden_states (`bool`, *optional*):
642
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
643
+ for more detail.
644
+ return_dict (`bool`, *optional*):
645
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
646
+ """
647
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
648
+ output_hidden_states = (
649
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
650
+ )
651
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
652
+
653
+ encoder_states = () if output_hidden_states else None
654
+ all_attentions = () if output_attentions else None
655
+
656
+ hidden_states = inputs_embeds
657
+ for idx, encoder_layer in enumerate(self.layers):
658
+ if output_hidden_states:
659
+ encoder_states = encoder_states + (hidden_states,)
660
+ if self.gradient_checkpointing and self.training:
661
+ layer_outputs = self._gradient_checkpointing_func(
662
+ encoder_layer.__call__,
663
+ hidden_states,
664
+ attention_mask,
665
+ causal_attention_mask,
666
+ output_attentions,
667
+ )
668
+ else:
669
+ layer_outputs = encoder_layer(
670
+ hidden_states,
671
+ attention_mask,
672
+ causal_attention_mask,
673
+ output_attentions=output_attentions,
674
+ )
675
+
676
+ hidden_states = layer_outputs[0]
677
+
678
+ if output_attentions:
679
+ all_attentions = all_attentions + (layer_outputs[1],)
680
+
681
+ if output_hidden_states:
682
+ encoder_states = encoder_states + (hidden_states,)
683
+
684
+ if not return_dict:
685
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
686
+ return BaseModelOutput(
687
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
688
+ )
689
+
690
+
691
+ # Similar to `transformers.models.clip.modeling_clip.CLIPVisionTransformer` but without docstring for `forward`
692
+ class Kosmos2VisionTransformer(nn.Module):
693
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionTransformer.__init__ with CLIPVision->Kosmos2Vision,CLIP_VISION->KOSMOS2_VISION,CLIP->Kosmos2Vision
694
+ def __init__(self, config: Kosmos2VisionConfig):
695
+ super().__init__()
696
+ self.config = config
697
+ embed_dim = config.hidden_size
698
+
699
+ self.embeddings = Kosmos2VisionEmbeddings(config)
700
+ self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
701
+ self.encoder = Kosmos2VisionEncoder(config)
702
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
703
+
704
+ def forward(
705
+ self,
706
+ pixel_values: Optional[torch.FloatTensor] = None,
707
+ output_attentions: Optional[bool] = None,
708
+ output_hidden_states: Optional[bool] = None,
709
+ return_dict: Optional[bool] = None,
710
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
711
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
712
+ output_hidden_states = (
713
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
714
+ )
715
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
716
+
717
+ if pixel_values is None:
718
+ raise ValueError("You have to specify pixel_values")
719
+
720
+ hidden_states = self.embeddings(pixel_values)
721
+ hidden_states = self.pre_layrnorm(hidden_states)
722
+
723
+ encoder_outputs = self.encoder(
724
+ inputs_embeds=hidden_states,
725
+ output_attentions=output_attentions,
726
+ output_hidden_states=output_hidden_states,
727
+ return_dict=return_dict,
728
+ )
729
+
730
+ last_hidden_state = encoder_outputs[0]
731
+ pooled_output = last_hidden_state[:, 0, :]
732
+ pooled_output = self.post_layernorm(pooled_output)
733
+
734
+ if not return_dict:
735
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
736
+
737
+ return BaseModelOutputWithPooling(
738
+ last_hidden_state=last_hidden_state,
739
+ pooler_output=pooled_output,
740
+ hidden_states=encoder_outputs.hidden_states,
741
+ attentions=encoder_outputs.attentions,
742
+ )
743
+
744
+
745
+ # Similar to `transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding` but allowing to pass `position_ids`
746
+ class Kosmos2TextSinusoidalPositionalEmbedding(nn.Module):
747
+ """This module produces sinusoidal positional embeddings of any length."""
748
+
749
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.__init__
750
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
751
+ super().__init__()
752
+ self.offset = 2
753
+ self.embedding_dim = embedding_dim
754
+ self.padding_idx = padding_idx
755
+ self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
756
+
757
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.make_weights
758
+ def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
759
+ emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
760
+ if hasattr(self, "weights"):
761
+ # in forward put the weights on the correct dtype and device of the param
762
+ emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
763
+
764
+ self.register_buffer("weights", emb_weights, persistent=False)
765
+
766
+ @staticmethod
767
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.get_embedding
768
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
769
+ """
770
+ Build sinusoidal embeddings.
771
+
772
+ This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
773
+ "Attention Is All You Need".
774
+ """
775
+ half_dim = embedding_dim // 2
776
+ emb = math.log(10000) / (half_dim - 1)
777
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb)
778
+ emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0)
779
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
780
+ if embedding_dim % 2 == 1:
781
+ # zero pad
782
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
783
+ if padding_idx is not None:
784
+ emb[padding_idx, :] = 0
785
+
786
+ return emb.to(torch.get_default_dtype())
787
+
788
+ @torch.no_grad()
789
+ def forward(
790
+ self,
791
+ input_ids: torch.Tensor = None,
792
+ inputs_embeds: torch.Tensor = None,
793
+ past_key_values_length: int = 0,
794
+ position_ids: torch.Tensor = None,
795
+ ):
796
+ if input_ids is not None:
797
+ bsz, seq_len = input_ids.size()
798
+ if position_ids is None:
799
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
800
+ position_ids = create_position_ids_from_input_ids(
801
+ input_ids, self.padding_idx, past_key_values_length
802
+ ).to(input_ids.device)
803
+ else:
804
+ bsz, seq_len = inputs_embeds.size()[:-1]
805
+ if position_ids is None:
806
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, past_key_values_length)
807
+
808
+ # expand embeddings if needed
809
+ max_pos = self.padding_idx + 1 + seq_len + past_key_values_length
810
+ if max_pos > self.weights.size(0):
811
+ self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
812
+
813
+ return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach()
814
+
815
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.create_position_ids_from_inputs_embeds
816
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds, past_key_values_length):
817
+ """
818
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
819
+
820
+ Args:
821
+ inputs_embeds: torch.Tensor
822
+
823
+ Returns: torch.Tensor
824
+ """
825
+ input_shape = inputs_embeds.size()[:-1]
826
+ sequence_length = input_shape[1]
827
+
828
+ position_ids = torch.arange(
829
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
830
+ )
831
+ return position_ids.unsqueeze(0).expand(input_shape).contiguous() + past_key_values_length
832
+
833
+
834
+ class KosmosTextAttention(nn.Module):
835
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
836
+
837
+ # Similar to transformers.models.bart.modeling_bart.BartAttention.__init__ except an additional `inner_attn_ln`.
838
+ def __init__(
839
+ self,
840
+ config,
841
+ embed_dim: int,
842
+ num_heads: int,
843
+ dropout: float = 0.0,
844
+ is_decoder: bool = False,
845
+ add_inner_attn_layernorm: bool = False,
846
+ bias: bool = True,
847
+ ):
848
+ super().__init__()
849
+ self.embed_dim = embed_dim
850
+ self.num_heads = num_heads
851
+ self.dropout = dropout
852
+ self.head_dim = embed_dim // num_heads
853
+
854
+ if (self.head_dim * num_heads) != self.embed_dim:
855
+ raise ValueError(
856
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
857
+ f" and `num_heads`: {num_heads})."
858
+ )
859
+ self.scaling = self.head_dim**-0.5
860
+ self.is_decoder = is_decoder
861
+
862
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
863
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
864
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
865
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
866
+
867
+ # End opy
868
+ self.inner_attn_ln = None
869
+ if add_inner_attn_layernorm:
870
+ self.inner_attn_ln = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
871
+
872
+ def _shape(self, projection: torch.Tensor) -> torch.Tensor:
873
+ new_projection_shape = projection.size()[:-1] + (self.num_heads, self.head_dim)
874
+ # move heads to 2nd position (B, T, H * D) -> (B, T, H, D) -> (B, H, T, D)
875
+ new_projection = projection.view(new_projection_shape).permute(0, 2, 1, 3)
876
+ return new_projection
877
+
878
+ def forward(
879
+ self,
880
+ hidden_states: torch.Tensor,
881
+ encoder_hidden_states: Optional[torch.Tensor] = None,
882
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
883
+ attention_mask: Optional[torch.Tensor] = None,
884
+ layer_head_mask: Optional[torch.Tensor] = None,
885
+ output_attentions: bool = False,
886
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
887
+ """Input shape: Batch x Time x Channel"""
888
+
889
+ # if key_value_states are provided this layer is used as a cross-attention layer
890
+ # for the decoder
891
+ is_cross_attention = encoder_hidden_states is not None
892
+ batch_size, seq_length = hidden_states.shape[:2]
893
+
894
+ # use encoder_hidden_states if cross attention
895
+ current_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
896
+ # checking that the `sequence_length` of the `past_key_value` is the same as the he provided
897
+ # `encoder_hidden_states` to support prefix tuning
898
+ if is_cross_attention and past_key_value and past_key_value[0].shape[2] == current_states.shape[1]:
899
+ # reuse k,v, cross_attentions
900
+ key_states = past_key_value[0]
901
+ value_states = past_key_value[1]
902
+ else:
903
+ key_states = self._shape(self.k_proj(current_states))
904
+ value_states = self._shape(self.v_proj(current_states))
905
+ if past_key_value is not None and not is_cross_attention:
906
+ # reuse k, v, self_attention
907
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
908
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
909
+
910
+ query_states = self._shape(self.q_proj(hidden_states) * self.scaling)
911
+ attn_weights = torch.matmul(query_states, key_states.transpose(-1, -2))
912
+
913
+ if self.is_decoder:
914
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
915
+ # Further calls to cross_attention layer can then reuse all cross-attention
916
+ # key/value_states (first "if" case)
917
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
918
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
919
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
920
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
921
+ past_key_value = (key_states, value_states)
922
+
923
+ src_len = key_states.size(2)
924
+
925
+ if attention_mask is not None:
926
+ if attention_mask.size() != (batch_size, 1, seq_length, src_len):
927
+ raise ValueError(
928
+ f"Attention mask should be of size {(batch_size, 1, seq_length, src_len)}, but is {attention_mask.size()}"
929
+ )
930
+ attn_weights = attn_weights + attention_mask
931
+
932
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
933
+
934
+ # Mask heads if we want to
935
+ if layer_head_mask is not None:
936
+ attn_weights = attn_weights * layer_head_mask
937
+
938
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
939
+
940
+ # attn_output = torch.bmm(attn_probs, value_states) ?
941
+ context_states = torch.matmul(attn_weights, value_states)
942
+ # attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) ?
943
+ context_states = context_states.permute(0, 2, 1, 3).contiguous().view(batch_size, seq_length, -1)
944
+
945
+ if self.inner_attn_ln is not None:
946
+ context_states = self.inner_attn_ln(context_states)
947
+
948
+ attn_output = self.out_proj(context_states)
949
+
950
+ return attn_output, attn_weights, past_key_value
951
+
952
+
953
+ class Kosmos2TextFFN(nn.Module):
954
+ def __init__(self, config: Kosmos2TextConfig):
955
+ super().__init__()
956
+
957
+ self.dropout = config.dropout
958
+ self.activation_fn = ACT2FN[config.activation_function]
959
+ self.activation_dropout = config.activation_dropout
960
+
961
+ self.fc1 = nn.Linear(config.embed_dim, config.ffn_dim)
962
+ self.fc2 = nn.Linear(config.ffn_dim, config.embed_dim)
963
+
964
+ self.ffn_layernorm = nn.LayerNorm(config.ffn_dim, eps=config.layer_norm_eps)
965
+
966
+ def forward(self, hidden_states):
967
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
968
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
969
+ hidden_states = self.ffn_layernorm(hidden_states)
970
+ hidden_states = self.fc2(hidden_states)
971
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
972
+
973
+ return hidden_states
974
+
975
+
976
+ class Kosmos2TextBlock(nn.Module):
977
+ def __init__(self, config: Kosmos2TextConfig):
978
+ super().__init__()
979
+ self.embed_dim = config.embed_dim
980
+
981
+ self.self_attn = KosmosTextAttention(
982
+ config,
983
+ embed_dim=self.embed_dim,
984
+ num_heads=config.attention_heads,
985
+ dropout=config.attention_dropout,
986
+ is_decoder=True,
987
+ add_inner_attn_layernorm=True,
988
+ )
989
+ self.dropout = config.dropout
990
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
991
+
992
+ if config.add_cross_attention:
993
+ self.encoder_attn = KosmosTextAttention(
994
+ config,
995
+ embed_dim=self.embed_dim,
996
+ num_heads=config.attention_heads,
997
+ dropout=config.attention_dropout,
998
+ is_decoder=True,
999
+ add_inner_attn_layernorm=False,
1000
+ )
1001
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
1002
+
1003
+ self.ffn = Kosmos2TextFFN(config)
1004
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
1005
+
1006
+ def forward(
1007
+ self,
1008
+ hidden_states: torch.Tensor,
1009
+ attention_mask: Optional[torch.Tensor] = None,
1010
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1011
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1012
+ layer_head_mask: Optional[torch.Tensor] = None,
1013
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
1014
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1015
+ output_attentions: Optional[bool] = False,
1016
+ use_cache: Optional[bool] = True,
1017
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1018
+ residual = hidden_states
1019
+
1020
+ # Self Attention
1021
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
1022
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
1023
+
1024
+ hidden_states = self.self_attn_layer_norm(hidden_states)
1025
+
1026
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
1027
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1028
+ hidden_states=hidden_states,
1029
+ past_key_value=self_attn_past_key_value,
1030
+ attention_mask=attention_mask,
1031
+ layer_head_mask=layer_head_mask,
1032
+ output_attentions=output_attentions,
1033
+ )
1034
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1035
+ hidden_states = residual + hidden_states
1036
+
1037
+ # Cross-Attention Block
1038
+ cross_attn_present_key_value = None
1039
+ cross_attn_weights = None
1040
+ if encoder_hidden_states is not None:
1041
+ if not hasattr(self, "encoder_attn"):
1042
+ raise ValueError(
1043
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
1044
+ " by setting `config.add_cross_attention=True`"
1045
+ )
1046
+
1047
+ residual = hidden_states
1048
+
1049
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
1050
+
1051
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
1052
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
1053
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
1054
+ hidden_states=hidden_states,
1055
+ encoder_hidden_states=encoder_hidden_states,
1056
+ attention_mask=encoder_attention_mask,
1057
+ layer_head_mask=cross_attn_layer_head_mask,
1058
+ past_key_value=cross_attn_past_key_value,
1059
+ output_attentions=output_attentions,
1060
+ )
1061
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1062
+ hidden_states = residual + hidden_states
1063
+
1064
+ # add cross-attn to positions 3,4 of present_key_value tuple
1065
+ present_key_value = present_key_value + cross_attn_present_key_value
1066
+
1067
+ # Fully Connected
1068
+ residual = hidden_states
1069
+
1070
+ hidden_states = self.final_layer_norm(hidden_states)
1071
+
1072
+ # FFN
1073
+ hidden_states = self.ffn(hidden_states)
1074
+ hidden_states = residual + hidden_states
1075
+
1076
+ outputs = (hidden_states,)
1077
+
1078
+ if output_attentions:
1079
+ outputs += (self_attn_weights, cross_attn_weights)
1080
+
1081
+ if use_cache:
1082
+ outputs += (present_key_value,)
1083
+
1084
+ return outputs
1085
+
1086
+
1087
+ class Kosmos2TextTransformer(nn.Module):
1088
+ """
1089
+ Transformer decoder consisting of `config.layers` layers. Each layer is a [`Kosmos2TextBlock`].
1090
+
1091
+ Args:
1092
+ config: Kosmos2TextConfig
1093
+ """
1094
+
1095
+ def __init__(self, config: Kosmos2TextConfig):
1096
+ super().__init__()
1097
+ self.config = config
1098
+ self.dropout = config.dropout
1099
+ self.layerdrop = config.layerdrop
1100
+
1101
+ self.embed_scale = math.sqrt(config.embed_dim) if config.scale_embedding else 1.0
1102
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.embed_dim, padding_idx=config.pad_token_id)
1103
+
1104
+ self.embed_positions = Kosmos2TextSinusoidalPositionalEmbedding(
1105
+ num_positions=config.max_position_embeddings,
1106
+ embedding_dim=config.embed_dim,
1107
+ padding_idx=config.pad_token_id,
1108
+ )
1109
+
1110
+ self.layers = nn.ModuleList([Kosmos2TextBlock(config) for _ in range(config.layers)])
1111
+ self.layer_norm = nn.LayerNorm(config.embed_dim, config.layer_norm_eps)
1112
+
1113
+ self.gradient_checkpointing = False
1114
+
1115
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
1116
+ # create causal mask
1117
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1118
+ combined_attention_mask = None
1119
+ if input_shape[-1] > 1:
1120
+ combined_attention_mask = _make_causal_mask(
1121
+ input_shape,
1122
+ inputs_embeds.dtype,
1123
+ device=inputs_embeds.device,
1124
+ past_key_values_length=past_key_values_length,
1125
+ )
1126
+
1127
+ if attention_mask is not None:
1128
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1129
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
1130
+ inputs_embeds.device
1131
+ )
1132
+ combined_attention_mask = (
1133
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
1134
+ )
1135
+
1136
+ return combined_attention_mask
1137
+
1138
+ def forward_embedding(
1139
+ self,
1140
+ input_ids,
1141
+ inputs_embeds: torch.Tensor = None,
1142
+ image_embeds: torch.Tensor = None,
1143
+ img_input_mask: torch.Tensor = None,
1144
+ past_key_values_length: int = 0,
1145
+ position_ids: torch.Tensor = None,
1146
+ ):
1147
+ # The argument `inputs_embeds` should be the one without being multiplied by `self.embed_scale`.
1148
+ if inputs_embeds is None:
1149
+ inputs_embeds = self.embed_tokens(input_ids)
1150
+
1151
+ if image_embeds is not None:
1152
+ inputs_embeds[img_input_mask.to(dtype=torch.bool)] = image_embeds.to(inputs_embeds.device).view(
1153
+ -1, image_embeds.size(-1)
1154
+ )
1155
+
1156
+ inputs_embeds = inputs_embeds * self.embed_scale
1157
+
1158
+ # embed positions
1159
+ positions = self.embed_positions(
1160
+ input_ids=input_ids,
1161
+ inputs_embeds=inputs_embeds,
1162
+ past_key_values_length=past_key_values_length,
1163
+ position_ids=position_ids,
1164
+ )
1165
+ positions = positions.to(inputs_embeds.device)
1166
+
1167
+ hidden_states = inputs_embeds + positions
1168
+
1169
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1170
+
1171
+ return hidden_states
1172
+
1173
+ def forward(
1174
+ self,
1175
+ input_ids: Optional[torch.Tensor] = None,
1176
+ attention_mask: Optional[torch.Tensor] = None,
1177
+ image_embeds: Optional[torch.Tensor] = None,
1178
+ image_embeds_position_mask: Optional[torch.Tensor] = None,
1179
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1180
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1181
+ head_mask: Optional[torch.Tensor] = None,
1182
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1183
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1184
+ inputs_embeds: Optional[torch.Tensor] = None,
1185
+ position_ids: Optional[torch.Tensor] = None,
1186
+ use_cache: Optional[bool] = None,
1187
+ output_attentions: Optional[bool] = None,
1188
+ output_hidden_states: Optional[bool] = None,
1189
+ return_dict: Optional[bool] = None,
1190
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
1191
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1192
+ output_hidden_states = (
1193
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1194
+ )
1195
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1196
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1197
+
1198
+ if input_ids is not None and inputs_embeds is not None:
1199
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1200
+ elif input_ids is not None:
1201
+ input_shape = input_ids.shape
1202
+ input_ids = input_ids.view(-1, input_shape[-1])
1203
+ elif inputs_embeds is not None:
1204
+ input_shape = inputs_embeds.size()[:-1]
1205
+ else:
1206
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1207
+
1208
+ # past_key_values_length
1209
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1210
+
1211
+ # We don't need img info. when `past_key_values_length` > 0
1212
+ if past_key_values_length > 0:
1213
+ image_embeds = None
1214
+ image_embeds_position_mask = None
1215
+
1216
+ hidden_states = self.forward_embedding(
1217
+ input_ids=input_ids,
1218
+ inputs_embeds=inputs_embeds,
1219
+ image_embeds=image_embeds,
1220
+ img_input_mask=image_embeds_position_mask,
1221
+ past_key_values_length=past_key_values_length,
1222
+ position_ids=position_ids,
1223
+ )
1224
+
1225
+ attention_mask = self._prepare_decoder_attention_mask(
1226
+ attention_mask, input_shape, hidden_states, past_key_values_length
1227
+ )
1228
+
1229
+ # expand encoder attention mask
1230
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1231
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1232
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
1233
+
1234
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1235
+
1236
+ if self.gradient_checkpointing and self.training:
1237
+ if use_cache:
1238
+ logger.warning_once(
1239
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1240
+ )
1241
+ use_cache = False
1242
+
1243
+ # decoder layers
1244
+ all_hidden_states = () if output_hidden_states else None
1245
+ all_self_attns = () if output_attentions else None
1246
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
1247
+ present_key_value_states = () if use_cache else None
1248
+
1249
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
1250
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
1251
+ if attn_mask is not None:
1252
+ if attn_mask.size()[0] != (len(self.layers)):
1253
+ raise ValueError(
1254
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
1255
+ f" {head_mask.size()[0]}."
1256
+ )
1257
+
1258
+ for idx, decoder_layer in enumerate(self.layers):
1259
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1260
+ if output_hidden_states:
1261
+ all_hidden_states += (hidden_states,)
1262
+ if self.training:
1263
+ dropout_probability = torch.rand([])
1264
+ if dropout_probability < self.layerdrop:
1265
+ continue
1266
+
1267
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1268
+
1269
+ if self.gradient_checkpointing and self.training:
1270
+ layer_outputs = self._gradient_checkpointing_func(
1271
+ decoder_layer.__call__,
1272
+ hidden_states,
1273
+ attention_mask,
1274
+ encoder_hidden_states,
1275
+ encoder_attention_mask,
1276
+ head_mask[idx] if head_mask is not None else None,
1277
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
1278
+ None,
1279
+ output_attentions,
1280
+ use_cache,
1281
+ )
1282
+ else:
1283
+ layer_outputs = decoder_layer(
1284
+ hidden_states,
1285
+ attention_mask=attention_mask,
1286
+ encoder_hidden_states=encoder_hidden_states,
1287
+ encoder_attention_mask=encoder_attention_mask,
1288
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1289
+ cross_attn_layer_head_mask=(
1290
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
1291
+ ),
1292
+ past_key_value=past_key_value,
1293
+ output_attentions=output_attentions,
1294
+ use_cache=use_cache,
1295
+ )
1296
+ hidden_states = layer_outputs[0]
1297
+
1298
+ if use_cache:
1299
+ present_key_value_states += (layer_outputs[3 if output_attentions else 1],)
1300
+
1301
+ if output_attentions:
1302
+ all_self_attns += (layer_outputs[1],)
1303
+
1304
+ if encoder_hidden_states is not None:
1305
+ all_cross_attentions += (layer_outputs[2],)
1306
+
1307
+ # add final layer norm
1308
+ hidden_states = self.layer_norm(hidden_states)
1309
+
1310
+ # add hidden states from the last decoder layer
1311
+ if output_hidden_states:
1312
+ all_hidden_states += (hidden_states,)
1313
+
1314
+ if not return_dict:
1315
+ return tuple(
1316
+ v
1317
+ for v in [
1318
+ hidden_states,
1319
+ present_key_value_states,
1320
+ all_hidden_states,
1321
+ all_self_attns,
1322
+ all_cross_attentions,
1323
+ ]
1324
+ if v is not None
1325
+ )
1326
+ return BaseModelOutputWithPastAndCrossAttentions(
1327
+ last_hidden_state=hidden_states,
1328
+ past_key_values=present_key_value_states,
1329
+ hidden_states=all_hidden_states,
1330
+ attentions=all_self_attns,
1331
+ cross_attentions=all_cross_attentions,
1332
+ )
1333
+
1334
+
1335
+ class Kosmos2PreTrainedModel(PreTrainedModel):
1336
+ """
1337
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1338
+ models.
1339
+ """
1340
+
1341
+ config_class = Kosmos2Config
1342
+ supports_gradient_checkpointing = True
1343
+ _no_split_modules = ["Kosmos2VisionEncoderLayer", "Kosmos2TextBlock"]
1344
+
1345
+ def _init_weights(self, module):
1346
+ """Initialize the weights"""
1347
+ if isinstance(self, Kosmos2VisionModel):
1348
+ factor = self.config.initializer_factor
1349
+ elif isinstance(self, (Kosmos2Model, Kosmos2ForConditionalGeneration)):
1350
+ factor = self.config.vision_config.initializer_factor
1351
+
1352
+ if isinstance(self, (Kosmos2TextModel, Kosmos2TextForCausalLM)):
1353
+ std = self.config.init_std
1354
+ elif isinstance(self, (Kosmos2Model, Kosmos2ForConditionalGeneration)):
1355
+ std = self.config.text_config.init_std
1356
+
1357
+ if isinstance(module, Kosmos2VisionEmbeddings):
1358
+ nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
1359
+ nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
1360
+ nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
1361
+ elif isinstance(module, Kosmos2VisionAttention):
1362
+ in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
1363
+ out_proj_std = (module.embed_dim**-0.5) * factor
1364
+ nn.init.normal_(module.q_proj.weight, std=in_proj_std)
1365
+ nn.init.normal_(module.k_proj.weight, std=in_proj_std)
1366
+ nn.init.normal_(module.v_proj.weight, std=in_proj_std)
1367
+ nn.init.normal_(module.out_proj.weight, std=out_proj_std)
1368
+ if module.q_proj.bias is not None:
1369
+ module.q_proj.bias.data.zero_()
1370
+ if module.k_proj.bias is not None:
1371
+ module.k_proj.bias.data.zero_()
1372
+ if module.v_proj.bias is not None:
1373
+ module.v_proj.bias.data.zero_()
1374
+ if module.out_proj.bias is not None:
1375
+ module.out_proj.bias.data.zero_()
1376
+ elif isinstance(module, Kosmos2VisionMLP):
1377
+ in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
1378
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
1379
+ nn.init.normal_(module.fc1.weight, std=fc_std)
1380
+ nn.init.normal_(module.fc2.weight, std=in_proj_std)
1381
+ if module.fc1.bias is not None:
1382
+ module.fc1.bias.data.zero_()
1383
+ if module.fc2.bias is not None:
1384
+ module.fc2.bias.data.zero_()
1385
+ elif isinstance(module, Kosmos2VisionEncoderLayer):
1386
+ module.layer_norm1.bias.data.zero_()
1387
+ module.layer_norm1.weight.data.fill_(1.0)
1388
+ module.layer_norm2.bias.data.zero_()
1389
+ module.layer_norm2.weight.data.fill_(1.0)
1390
+ elif isinstance(module, Kosmos2VisionTransformer):
1391
+ module.pre_layrnorm.bias.data.zero_()
1392
+ module.pre_layrnorm.weight.data.fill_(1.0)
1393
+ module.post_layernorm.bias.data.zero_()
1394
+ module.post_layernorm.weight.data.fill_(1.0)
1395
+ elif isinstance(module, KosmosTextAttention):
1396
+ nn.init.normal_(module.q_proj.weight, std=std)
1397
+ nn.init.normal_(module.k_proj.weight, std=std)
1398
+ nn.init.normal_(module.v_proj.weight, std=std)
1399
+ nn.init.normal_(module.out_proj.weight, std=std)
1400
+ if module.q_proj.bias is not None:
1401
+ module.q_proj.bias.data.zero_()
1402
+ if module.k_proj.bias is not None:
1403
+ module.k_proj.bias.data.zero_()
1404
+ if module.v_proj.bias is not None:
1405
+ module.v_proj.bias.data.zero_()
1406
+ if module.out_proj.bias is not None:
1407
+ module.out_proj.bias.data.zero_()
1408
+ elif isinstance(module, Kosmos2TextFFN):
1409
+ nn.init.normal_(module.fc1.weight, std=std)
1410
+ nn.init.normal_(module.fc2.weight, std=std)
1411
+ if module.fc1.bias is not None:
1412
+ module.fc1.bias.data.zero_()
1413
+ if module.fc2.bias is not None:
1414
+ module.fc2.bias.data.zero_()
1415
+ elif isinstance(module, Kosmos2TextForCausalLM):
1416
+ nn.init.normal_(module.lm_head.weight, std=std)
1417
+ if module.lm_head.bias is not None:
1418
+ module.lm_head.bias.data.zero_()
1419
+ elif isinstance(module, Kosmos2ImageToTextProjection):
1420
+ nn.init.normal_(module.dense.weight, std=std)
1421
+ if module.dense.bias is not None:
1422
+ module.dense.bias.data.zero_()
1423
+ elif isinstance(module, Kosmos2TextTransformer):
1424
+ module.embed_tokens.weight.data.normal_(mean=0.0, std=std)
1425
+ if module.embed_tokens.padding_idx is not None:
1426
+ module.embed_tokens.weight.data[module.embed_tokens.padding_idx].zero_()
1427
+
1428
+
1429
+ class Kosmos2VisionModel(Kosmos2PreTrainedModel):
1430
+ config_class = Kosmos2VisionConfig
1431
+ main_input_name = "pixel_values"
1432
+
1433
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModel.__init__ with CLIP_VISION->KOSMOS2_VISION,CLIP->Kosmos2,self.vision_model->self.model
1434
+ def __init__(self, config: Kosmos2VisionConfig):
1435
+ super().__init__(config)
1436
+ self.model = Kosmos2VisionTransformer(config)
1437
+ # Initialize weights and apply final processing
1438
+ self.post_init()
1439
+
1440
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModel.get_input_embeddings with CLIP_VISION->KOSMOS2_VISION,CLIP->Kosmos2,self.vision_model->self.model
1441
+ def get_input_embeddings(self) -> nn.Module:
1442
+ return self.model.embeddings.patch_embedding
1443
+
1444
+ @add_start_docstrings_to_model_forward(KOSMOS2_VISION_INPUTS_DOCSTRING)
1445
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=Kosmos2VisionConfig)
1446
+ def forward(
1447
+ self,
1448
+ pixel_values: Optional[torch.FloatTensor] = None,
1449
+ output_attentions: Optional[bool] = None,
1450
+ output_hidden_states: Optional[bool] = None,
1451
+ return_dict: Optional[bool] = None,
1452
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1453
+ r"""
1454
+ Returns:
1455
+
1456
+ """
1457
+ return self.model(
1458
+ pixel_values=pixel_values,
1459
+ output_attentions=output_attentions,
1460
+ output_hidden_states=output_hidden_states,
1461
+ return_dict=return_dict,
1462
+ )
1463
+
1464
+
1465
+ class Kosmos2TextModel(Kosmos2PreTrainedModel):
1466
+ config_class = Kosmos2TextConfig
1467
+
1468
+ def __init__(self, config: Kosmos2TextConfig):
1469
+ super().__init__(config)
1470
+ self.model = Kosmos2TextTransformer(config)
1471
+ # Initialize weights and apply final processing
1472
+ self.post_init()
1473
+
1474
+ def get_input_embeddings(self) -> nn.Module:
1475
+ return self.model.embed_tokens
1476
+
1477
+ def set_input_embeddings(self, value):
1478
+ self.model.embed_tokens = value
1479
+
1480
+ @add_start_docstrings_to_model_forward(KOSMOS2_TEXT_INPUTS_DOCSTRING)
1481
+ @replace_return_docstrings(output_type=BaseModelOutputWithPastAndCrossAttentions, config_class=Kosmos2TextConfig)
1482
+ def forward(
1483
+ self,
1484
+ input_ids: Optional[torch.Tensor] = None,
1485
+ attention_mask: Optional[torch.Tensor] = None,
1486
+ image_embeds: Optional[torch.Tensor] = None,
1487
+ image_embeds_position_mask: Optional[torch.Tensor] = None,
1488
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1489
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1490
+ head_mask: Optional[torch.Tensor] = None,
1491
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1492
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1493
+ inputs_embeds: Optional[torch.Tensor] = None,
1494
+ position_ids: Optional[torch.Tensor] = None,
1495
+ use_cache: Optional[bool] = None,
1496
+ output_attentions: Optional[bool] = None,
1497
+ output_hidden_states: Optional[bool] = None,
1498
+ return_dict: Optional[bool] = None,
1499
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
1500
+ r"""
1501
+ Returns:
1502
+
1503
+ """
1504
+ return self.model(
1505
+ input_ids=input_ids,
1506
+ attention_mask=attention_mask,
1507
+ image_embeds=image_embeds,
1508
+ image_embeds_position_mask=image_embeds_position_mask,
1509
+ encoder_hidden_states=encoder_hidden_states,
1510
+ encoder_attention_mask=encoder_attention_mask,
1511
+ head_mask=head_mask,
1512
+ cross_attn_head_mask=cross_attn_head_mask,
1513
+ past_key_values=past_key_values,
1514
+ inputs_embeds=inputs_embeds,
1515
+ position_ids=position_ids,
1516
+ use_cache=use_cache,
1517
+ output_attentions=output_attentions,
1518
+ output_hidden_states=output_hidden_states,
1519
+ return_dict=return_dict,
1520
+ )
1521
+
1522
+
1523
+ @add_start_docstrings(
1524
+ """
1525
+ The text model from KOSMOS-2 with a language modeling head on top (linear layer with weights tied to the input
1526
+ embeddings).
1527
+ """,
1528
+ KOSMOS2_START_DOCSTRING,
1529
+ )
1530
+ class Kosmos2TextForCausalLM(Kosmos2PreTrainedModel):
1531
+ config_class = Kosmos2TextConfig
1532
+ _tied_weights_keys = ["lm_head.weight"]
1533
+
1534
+ def __init__(self, config: Kosmos2TextConfig):
1535
+ super().__init__(config)
1536
+
1537
+ self.model = Kosmos2TextTransformer(config)
1538
+ self.lm_head = nn.Linear(in_features=config.embed_dim, out_features=config.vocab_size, bias=False)
1539
+
1540
+ # Initialize weights and apply final processing
1541
+ self.post_init()
1542
+
1543
+ def get_input_embeddings(self) -> nn.Module:
1544
+ return self.model.embed_tokens
1545
+
1546
+ def set_input_embeddings(self, value):
1547
+ self.model.embed_tokens = value
1548
+
1549
+ def get_output_embeddings(self) -> nn.Module:
1550
+ return self.lm_head
1551
+
1552
+ def set_output_embeddings(self, new_embeddings):
1553
+ self.lm_head = new_embeddings
1554
+
1555
+ @add_start_docstrings_to_model_forward(KOSMOS2_TEXT_INPUTS_DOCSTRING)
1556
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=Kosmos2TextConfig)
1557
+ def forward(
1558
+ self,
1559
+ input_ids: Optional[torch.Tensor] = None,
1560
+ attention_mask: Optional[torch.Tensor] = None,
1561
+ image_embeds: Optional[torch.Tensor] = None,
1562
+ image_embeds_position_mask: Optional[torch.Tensor] = None,
1563
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1564
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1565
+ head_mask: Optional[torch.Tensor] = None,
1566
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1567
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1568
+ inputs_embeds: Optional[torch.Tensor] = None,
1569
+ position_ids: Optional[torch.Tensor] = None,
1570
+ labels: Optional[torch.LongTensor] = None,
1571
+ use_cache: Optional[bool] = None,
1572
+ output_attentions: Optional[bool] = None,
1573
+ output_hidden_states: Optional[bool] = None,
1574
+ return_dict: Optional[bool] = None,
1575
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1576
+ r"""
1577
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1578
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1579
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1580
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1581
+
1582
+ Returns:
1583
+
1584
+ """
1585
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1586
+
1587
+ if labels is not None:
1588
+ if use_cache:
1589
+ logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
1590
+ use_cache = False
1591
+
1592
+ outputs = self.model(
1593
+ input_ids=input_ids,
1594
+ attention_mask=attention_mask,
1595
+ image_embeds=image_embeds,
1596
+ image_embeds_position_mask=image_embeds_position_mask,
1597
+ encoder_hidden_states=encoder_hidden_states,
1598
+ encoder_attention_mask=encoder_attention_mask,
1599
+ head_mask=head_mask,
1600
+ cross_attn_head_mask=cross_attn_head_mask,
1601
+ past_key_values=past_key_values,
1602
+ inputs_embeds=inputs_embeds,
1603
+ position_ids=position_ids,
1604
+ use_cache=use_cache,
1605
+ output_attentions=output_attentions,
1606
+ output_hidden_states=output_hidden_states,
1607
+ return_dict=return_dict,
1608
+ )
1609
+ lm_logits = self.lm_head(outputs[0])
1610
+
1611
+ loss = None
1612
+ if labels is not None:
1613
+ # move labels to correct device to enable model parallelism
1614
+ labels = labels.to(lm_logits.device)
1615
+ # Shift so that tokens < n predict n
1616
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1617
+ shift_labels = labels[..., 1:].contiguous()
1618
+ batch_size, seq_length, vocab_size = shift_logits.shape
1619
+ # Flatten the tokens
1620
+ loss_fct = CrossEntropyLoss()
1621
+ loss = loss_fct(
1622
+ shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)
1623
+ )
1624
+
1625
+ if not return_dict:
1626
+ output = (lm_logits,) + outputs[1:]
1627
+ return (loss,) + output if loss is not None else output
1628
+
1629
+ return CausalLMOutputWithCrossAttentions(
1630
+ loss=loss,
1631
+ logits=lm_logits,
1632
+ past_key_values=outputs.past_key_values,
1633
+ hidden_states=outputs.hidden_states,
1634
+ attentions=outputs.attentions,
1635
+ cross_attentions=outputs.cross_attentions,
1636
+ )
1637
+
1638
+ def prepare_inputs_for_generation(
1639
+ self,
1640
+ input_ids,
1641
+ image_embeds=None,
1642
+ image_embeds_position_mask=None,
1643
+ past_key_values=None,
1644
+ attention_mask=None,
1645
+ use_cache=None,
1646
+ **model_kwargs,
1647
+ ):
1648
+ input_shape = input_ids.shape
1649
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1650
+ if attention_mask is None:
1651
+ attention_mask = input_ids.new_ones(input_shape)
1652
+
1653
+ position_ids = None
1654
+
1655
+ # cut input_ids if past_key_values is used
1656
+ if past_key_values is not None:
1657
+ position_ids = create_position_ids_from_input_ids(
1658
+ input_ids,
1659
+ padding_idx=self.config.pad_token_id,
1660
+ past_key_values_length=0,
1661
+ )[:, -1:]
1662
+
1663
+ input_ids = input_ids[:, -1:]
1664
+ # the image info. is already encoded into the past keys/values
1665
+ image_embeds = None
1666
+ image_embeds_position_mask = None
1667
+ elif image_embeds_position_mask is not None:
1668
+ # appending `False` to `image_embeds_position_mask` (because `input_ids` grows during generation)
1669
+ batch_size, seq_len = input_ids.size()
1670
+ mask_len = image_embeds_position_mask.size()[-1]
1671
+ image_embeds_position_mask = torch.cat(
1672
+ (
1673
+ image_embeds_position_mask,
1674
+ torch.zeros(size=(batch_size, seq_len - mask_len), dtype=torch.bool, device=input_ids.device),
1675
+ ),
1676
+ dim=1,
1677
+ )
1678
+
1679
+ return {
1680
+ "input_ids": input_ids,
1681
+ "image_embeds": image_embeds,
1682
+ "image_embeds_position_mask": image_embeds_position_mask,
1683
+ "past_key_values": past_key_values,
1684
+ "attention_mask": attention_mask,
1685
+ "position_ids": position_ids,
1686
+ "use_cache": use_cache,
1687
+ }
1688
+
1689
+ @staticmethod
1690
+ # Copied from transformers.models.umt5.modeling_umt5.UMT5ForConditionalGeneration._reorder_cache
1691
+ def _reorder_cache(past_key_values, beam_idx):
1692
+ reordered_past = ()
1693
+ for layer_past in past_key_values:
1694
+ reordered_past += (
1695
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1696
+ )
1697
+ return reordered_past
1698
+
1699
+
1700
+ class Kosmos2ImageToTextProjection(nn.Module):
1701
+ """The layer that transforms the image model's output to part of the text model's input (namely, image features)"""
1702
+
1703
+ def __init__(self, config: Kosmos2Config):
1704
+ super().__init__()
1705
+ self.dense = nn.Linear(config.vision_config.hidden_size, config.text_config.embed_dim)
1706
+ self.latent_query = nn.Parameter(torch.randn(config.latent_query_num, config.text_config.embed_dim))
1707
+
1708
+ self.x_attn = KosmosTextAttention(
1709
+ config.text_config,
1710
+ config.text_config.embed_dim,
1711
+ config.text_config.attention_heads,
1712
+ dropout=config.text_config.attention_dropout,
1713
+ is_decoder=False,
1714
+ add_inner_attn_layernorm=False,
1715
+ )
1716
+
1717
+ def forward(self, features):
1718
+ hidden_states = self.dense(features)
1719
+
1720
+ # shape = [batch, latent_query_num, h_dim]
1721
+ latent_query = self.latent_query.unsqueeze(0).expand(hidden_states.size(0), -1, -1)
1722
+ key_value_states = torch.cat([hidden_states, latent_query], dim=1)
1723
+
1724
+ hidden_states, attn_weights, _ = self.x_attn(
1725
+ hidden_states=latent_query,
1726
+ encoder_hidden_states=key_value_states,
1727
+ past_key_value=None,
1728
+ attention_mask=None,
1729
+ output_attentions=None,
1730
+ )
1731
+
1732
+ return hidden_states, attn_weights
1733
+
1734
+
1735
+ @add_start_docstrings(
1736
+ """
1737
+ KOSMOS-2 Model for generating text and image features. The model consists of a vision encoder and a language model.
1738
+ """,
1739
+ KOSMOS2_START_DOCSTRING,
1740
+ )
1741
+ class Kosmos2Model(Kosmos2PreTrainedModel):
1742
+ config_class = Kosmos2Config
1743
+ main_input_name = "pixel_values"
1744
+
1745
+ def __init__(self, config: Kosmos2Config):
1746
+ super().__init__(config)
1747
+
1748
+ self.text_model = Kosmos2TextModel(config.text_config)
1749
+ self.vision_model = Kosmos2VisionModel(config.vision_config)
1750
+ self.image_to_text_projection = Kosmos2ImageToTextProjection(config)
1751
+
1752
+ # Initialize weights and apply final processing
1753
+ self.post_init()
1754
+
1755
+ def get_input_embeddings(self) -> nn.Module:
1756
+ return self.text_model.model.embed_tokens
1757
+
1758
+ def set_input_embeddings(self, value):
1759
+ self.text_model.model.embed_tokens = value
1760
+
1761
+ @add_start_docstrings_to_model_forward(KOSMOS2_INPUTS_DOCSTRING)
1762
+ @replace_return_docstrings(output_type=Kosmos2ModelOutput, config_class=_CONFIG_FOR_DOC)
1763
+ def forward(
1764
+ self,
1765
+ pixel_values: Optional[torch.Tensor] = None,
1766
+ input_ids: Optional[torch.Tensor] = None,
1767
+ image_embeds_position_mask: Optional[torch.Tensor] = None,
1768
+ attention_mask: Optional[torch.Tensor] = None,
1769
+ head_mask: Optional[torch.Tensor] = None,
1770
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1771
+ image_embeds: Optional[torch.Tensor] = None,
1772
+ inputs_embeds: Optional[torch.Tensor] = None,
1773
+ position_ids: Optional[torch.Tensor] = None,
1774
+ use_cache: Optional[bool] = None,
1775
+ output_attentions: Optional[bool] = None,
1776
+ output_hidden_states: Optional[bool] = None,
1777
+ return_dict: Optional[bool] = None,
1778
+ ) -> Union[Tuple, Kosmos2ModelOutput]:
1779
+ r"""
1780
+ Returns:
1781
+
1782
+ Examples:
1783
+
1784
+ ```python
1785
+ >>> from PIL import Image
1786
+ >>> import requests
1787
+ >>> from transformers import AutoProcessor, Kosmos2Model
1788
+
1789
+ >>> model = Kosmos2Model.from_pretrained("microsoft/kosmos-2-patch14-224")
1790
+ >>> processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224")
1791
+
1792
+ >>> url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
1793
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1794
+
1795
+ >>> text = (
1796
+ ... "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863>"
1797
+ ... "</object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911>"
1798
+ ... "</object>"
1799
+ ... )
1800
+
1801
+ >>> inputs = processor(text=text, images=image, return_tensors="pt", add_eos_token=True)
1802
+
1803
+ >>> last_hidden_state = model(
1804
+ ... pixel_values=inputs["pixel_values"],
1805
+ ... input_ids=inputs["input_ids"],
1806
+ ... attention_mask=inputs["attention_mask"],
1807
+ ... image_embeds_position_mask=inputs["image_embeds_position_mask"],
1808
+ ... ).last_hidden_state
1809
+ >>> list(last_hidden_state.shape)
1810
+ [1, 91, 2048]
1811
+ ```"""
1812
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1813
+ output_hidden_states = (
1814
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1815
+ )
1816
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1817
+
1818
+ vision_model_output = None
1819
+ projection_attentions = None
1820
+ if image_embeds is None:
1821
+ if pixel_values is None:
1822
+ raise ValueError("You have to specify either `pixel_values` or `image_embeds`.")
1823
+
1824
+ vision_model_output = self.vision_model(
1825
+ pixel_values=pixel_values,
1826
+ output_attentions=output_attentions,
1827
+ output_hidden_states=output_hidden_states,
1828
+ return_dict=return_dict,
1829
+ )
1830
+ # The whole `last_hidden_state` through `post_layernorm` instead of just `pooled_output`.
1831
+ image_embeds = self.vision_model.model.post_layernorm(vision_model_output[0])
1832
+ # normalized features
1833
+ image_embeds = nn.functional.normalize(image_embeds, dim=-1)
1834
+ image_embeds, projection_attentions = self.image_to_text_projection(image_embeds)
1835
+
1836
+ outputs = self.text_model(
1837
+ input_ids=input_ids,
1838
+ attention_mask=attention_mask,
1839
+ image_embeds=image_embeds,
1840
+ image_embeds_position_mask=image_embeds_position_mask,
1841
+ head_mask=head_mask,
1842
+ past_key_values=past_key_values,
1843
+ inputs_embeds=inputs_embeds,
1844
+ position_ids=position_ids,
1845
+ use_cache=use_cache,
1846
+ output_attentions=output_attentions,
1847
+ output_hidden_states=output_hidden_states,
1848
+ return_dict=return_dict,
1849
+ )
1850
+
1851
+ if not return_dict:
1852
+ outputs = outputs + (image_embeds, projection_attentions, vision_model_output)
1853
+ return tuple(output for output in outputs if output is not None)
1854
+
1855
+ return Kosmos2ModelOutput(
1856
+ last_hidden_state=outputs.last_hidden_state,
1857
+ past_key_values=outputs.past_key_values,
1858
+ hidden_states=outputs.hidden_states,
1859
+ attentions=outputs.attentions,
1860
+ image_embeds=image_embeds,
1861
+ projection_attentions=projection_attentions,
1862
+ vision_model_output=vision_model_output,
1863
+ )
1864
+
1865
+
1866
+ @add_start_docstrings(
1867
+ """
1868
+ KOSMOS-2 Model for generating text and bounding boxes given an image. The model consists of a vision encoder and a
1869
+ language model.
1870
+ """,
1871
+ KOSMOS2_START_DOCSTRING,
1872
+ )
1873
+ class Kosmos2ForConditionalGeneration(Kosmos2PreTrainedModel):
1874
+ config_class = Kosmos2Config
1875
+ main_input_name = "pixel_values"
1876
+ _tied_weights_keys = ["text_model.lm_head.weight"]
1877
+
1878
+ def __init__(self, config: Kosmos2Config):
1879
+ super().__init__(config)
1880
+
1881
+ self.text_model = Kosmos2TextForCausalLM(config.text_config)
1882
+ self.vision_model = Kosmos2VisionModel(config.vision_config)
1883
+
1884
+ self.image_to_text_projection = Kosmos2ImageToTextProjection(config)
1885
+
1886
+ # Initialize weights and apply final processing
1887
+ self.post_init()
1888
+
1889
+ def get_input_embeddings(self) -> nn.Module:
1890
+ return self.text_model.model.embed_tokens
1891
+
1892
+ def set_input_embeddings(self, value):
1893
+ self.text_model.model.embed_tokens = value
1894
+
1895
+ def get_output_embeddings(self) -> nn.Module:
1896
+ return self.text_model.get_output_embeddings()
1897
+
1898
+ def set_output_embeddings(self, new_embeddings):
1899
+ self.text_model.set_output_embeddings(new_embeddings)
1900
+
1901
+ @add_start_docstrings_to_model_forward(KOSMOS2_INPUTS_DOCSTRING)
1902
+ @replace_return_docstrings(output_type=Kosmos2ForConditionalGenerationModelOutput, config_class=_CONFIG_FOR_DOC)
1903
+ def forward(
1904
+ self,
1905
+ pixel_values: Optional[torch.Tensor] = None,
1906
+ input_ids: Optional[torch.Tensor] = None,
1907
+ image_embeds_position_mask: Optional[torch.Tensor] = None,
1908
+ attention_mask: Optional[torch.Tensor] = None,
1909
+ head_mask: Optional[torch.Tensor] = None,
1910
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1911
+ image_embeds: Optional[torch.Tensor] = None,
1912
+ inputs_embeds: Optional[torch.Tensor] = None,
1913
+ position_ids: Optional[torch.Tensor] = None,
1914
+ labels: Optional[torch.LongTensor] = None,
1915
+ use_cache: Optional[bool] = None,
1916
+ output_attentions: Optional[bool] = None,
1917
+ output_hidden_states: Optional[bool] = None,
1918
+ return_dict: Optional[bool] = None,
1919
+ ) -> Union[Tuple, Kosmos2ForConditionalGenerationModelOutput]:
1920
+ r"""
1921
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1922
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1923
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1924
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1925
+
1926
+ Returns:
1927
+
1928
+ Examples:
1929
+
1930
+ ```python
1931
+ >>> from PIL import Image
1932
+ >>> import requests
1933
+ >>> from transformers import AutoProcessor, Kosmos2ForConditionalGeneration
1934
+
1935
+ >>> model = Kosmos2ForConditionalGeneration.from_pretrained("microsoft/kosmos-2-patch14-224")
1936
+ >>> processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224")
1937
+
1938
+ >>> url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
1939
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1940
+
1941
+ >>> prompt = "<grounding> An image of"
1942
+
1943
+ >>> inputs = processor(text=prompt, images=image, return_tensors="pt")
1944
+
1945
+ >>> generated_ids = model.generate(
1946
+ ... pixel_values=inputs["pixel_values"],
1947
+ ... input_ids=inputs["input_ids"],
1948
+ ... attention_mask=inputs["attention_mask"],
1949
+ ... image_embeds=None,
1950
+ ... image_embeds_position_mask=inputs["image_embeds_position_mask"],
1951
+ ... use_cache=True,
1952
+ ... max_new_tokens=64,
1953
+ ... )
1954
+ >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
1955
+ >>> processed_text = processor.post_process_generation(generated_text, cleanup_and_extract=False)
1956
+ >>> processed_text
1957
+ '<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>.'
1958
+
1959
+ >>> caption, entities = processor.post_process_generation(generated_text)
1960
+ >>> caption
1961
+ 'An image of a snowman warming himself by a fire.'
1962
+
1963
+ >>> entities
1964
+ [('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]
1965
+ ```"""
1966
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1967
+ output_hidden_states = (
1968
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1969
+ )
1970
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1971
+
1972
+ vision_model_output = None
1973
+ projection_attentions = None
1974
+ if image_embeds is None:
1975
+ if pixel_values is None:
1976
+ raise ValueError("You have to specify either `pixel_values` or `image_embeds`.")
1977
+
1978
+ vision_model_output = self.vision_model(
1979
+ pixel_values=pixel_values,
1980
+ output_attentions=output_attentions,
1981
+ output_hidden_states=output_hidden_states,
1982
+ return_dict=return_dict,
1983
+ )
1984
+ # The whole `last_hidden_state` through `post_layernorm` instead of just `pooled_output`.
1985
+ image_embeds = self.vision_model.model.post_layernorm(vision_model_output[0])
1986
+ # normalized features
1987
+ image_embeds = nn.functional.normalize(image_embeds, dim=-1)
1988
+ image_embeds, projection_attentions = self.image_to_text_projection(image_embeds)
1989
+
1990
+ lm_outputs = self.text_model(
1991
+ input_ids=input_ids,
1992
+ attention_mask=attention_mask,
1993
+ image_embeds=image_embeds,
1994
+ image_embeds_position_mask=image_embeds_position_mask,
1995
+ head_mask=head_mask,
1996
+ past_key_values=past_key_values,
1997
+ inputs_embeds=inputs_embeds,
1998
+ position_ids=position_ids,
1999
+ labels=labels,
2000
+ use_cache=use_cache,
2001
+ output_attentions=output_attentions,
2002
+ output_hidden_states=output_hidden_states,
2003
+ return_dict=return_dict,
2004
+ )
2005
+
2006
+ if not return_dict:
2007
+ outputs = lm_outputs + (image_embeds, projection_attentions, vision_model_output)
2008
+ return tuple(output for output in outputs if output is not None)
2009
+
2010
+ return Kosmos2ForConditionalGenerationModelOutput(
2011
+ loss=lm_outputs.loss,
2012
+ logits=lm_outputs.logits,
2013
+ past_key_values=lm_outputs.past_key_values,
2014
+ hidden_states=lm_outputs.hidden_states,
2015
+ attentions=lm_outputs.attentions,
2016
+ image_embeds=image_embeds,
2017
+ projection_attentions=projection_attentions,
2018
+ vision_model_output=vision_model_output,
2019
+ )
2020
+
2021
+ def generate(
2022
+ self,
2023
+ pixel_values: Optional[torch.Tensor] = None,
2024
+ image_embeds_position_mask: Optional[torch.Tensor] = None,
2025
+ input_ids: Optional[torch.Tensor] = None,
2026
+ attention_mask: Optional[torch.Tensor] = None,
2027
+ image_embeds: Optional[torch.Tensor] = None,
2028
+ **kwargs,
2029
+ ):
2030
+ # in order to allow `inputs` argument (as in `GenerationMixin`)
2031
+ inputs = kwargs.pop("inputs", None)
2032
+ if pixel_values is not None and inputs is not None:
2033
+ raise ValueError(
2034
+ f"`inputs`: {inputs} were passed alongside `pixel_values` which is not allowed."
2035
+ f"Make sure to either pass `inputs` or pixel_values=..."
2036
+ )
2037
+ if pixel_values is None and inputs is not None:
2038
+ pixel_values = inputs
2039
+
2040
+ if image_embeds is None:
2041
+ vision_model_output = self.vision_model(pixel_values)
2042
+ # The whole `last_hidden_state` through `post_layernorm` instead of just `pooled_output`.
2043
+ image_embeds = self.vision_model.model.post_layernorm(vision_model_output[0])
2044
+ # normalized features
2045
+ image_embeds = nn.functional.normalize(image_embeds, dim=-1)
2046
+ image_embeds, projection_attentions = self.image_to_text_projection(image_embeds)
2047
+
2048
+ output = self.text_model.generate(
2049
+ input_ids=input_ids,
2050
+ attention_mask=attention_mask,
2051
+ image_embeds=image_embeds,
2052
+ image_embeds_position_mask=image_embeds_position_mask,
2053
+ **kwargs,
2054
+ )
2055
+
2056
+ return output
pllava/lib/python3.10/site-packages/transformers/models/kosmos2/processing_kosmos2.py ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Processor class for KOSMOS-2."""
16
+
17
+ import copy
18
+ import math
19
+ import re
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ from ...image_processing_utils import BatchFeature
23
+ from ...image_utils import ImageInput, is_batched
24
+ from ...processing_utils import ProcessorMixin
25
+ from ...tokenization_utils import AddedToken
26
+ from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, TextInput, TruncationStrategy
27
+ from ...utils import TensorType
28
+
29
+
30
+ BboxInput = Union[
31
+ List[Tuple[int, int]],
32
+ List[Tuple[float, float, float, float]],
33
+ List[List[Tuple[int, int]]],
34
+ List[List[Tuple[float, float, float]]],
35
+ ]
36
+
37
+
38
+ class Kosmos2Processor(ProcessorMixin):
39
+ r"""
40
+ Constructs an KOSMOS-2 processor which wraps a KOSMOS-2 image processor and a KOSMOS-2 tokenizer into a single
41
+ processor.
42
+
43
+ [`Kosmos2Processor`] offers all the functionalities of [`CLIPImageProcessor`] and some functionalities of
44
+ [`XLMRobertaTokenizerFast`]. See the docstring of [`~Kosmos2Processor.__call__`] and [`~Kosmos2Processor.decode`]
45
+ for more information.
46
+
47
+ Args:
48
+ image_processor (`CLIPImageProcessor`):
49
+ An instance of [`CLIPImageProcessor`]. The image processor is a required input.
50
+ tokenizer (`XLMRobertaTokenizerFast`):
51
+ An instance of ['XLMRobertaTokenizerFast`]. The tokenizer is a required input.
52
+ num_patch_index_tokens (`int`, *optional*, defaults to 1024):
53
+ The number of tokens that represent patch indices.
54
+ """
55
+
56
+ attributes = ["image_processor", "tokenizer"]
57
+ image_processor_class = "CLIPImageProcessor"
58
+ tokenizer_class = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")
59
+
60
+ def __init__(self, image_processor, tokenizer, num_patch_index_tokens=1024):
61
+ tokenizer.return_token_type_ids = False
62
+
63
+ self.eod_token = "</doc>"
64
+
65
+ self.boi_token = "<image>"
66
+ self.eoi_token = "</image>"
67
+
68
+ self.eoc_token = "</chunk>"
69
+ self.eol_token = "</line>"
70
+
71
+ self.bop_token = "<phrase>"
72
+ self.eop_token = "</phrase>"
73
+
74
+ self.boo_token = "<object>"
75
+ self.eoo_token = "</object>"
76
+
77
+ self.dom_token = "</delimiter_of_multi_objects/>"
78
+
79
+ self.grd_token = "<grounding>"
80
+
81
+ self.tag_tokens = [
82
+ self.eod_token,
83
+ self.boi_token,
84
+ self.eoi_token,
85
+ self.eoc_token,
86
+ self.eol_token,
87
+ self.bop_token,
88
+ self.eop_token,
89
+ self.boo_token,
90
+ self.eoo_token,
91
+ self.dom_token,
92
+ self.grd_token,
93
+ ]
94
+
95
+ self.num_patch_index_tokens = num_patch_index_tokens
96
+ patch_index_tokens = [f"<patch_index_{str(x).zfill(4)}>" for x in range(self.num_patch_index_tokens)]
97
+
98
+ tokens_to_add = []
99
+ for token in self.tag_tokens + patch_index_tokens:
100
+ tokens_to_add.append(AddedToken(token, lstrip=True, rstrip=False, normalized=False))
101
+ tokenizer.add_tokens(tokens_to_add)
102
+
103
+ super().__init__(image_processor, tokenizer)
104
+
105
+ def __call__(
106
+ self,
107
+ images: ImageInput = None,
108
+ text: Union[TextInput, List[TextInput]] = None,
109
+ bboxes: BboxInput = None,
110
+ num_image_tokens: Optional[int] = 64,
111
+ first_image_token_id: Optional[int] = None,
112
+ add_special_tokens: bool = True,
113
+ add_eos_token: bool = False,
114
+ padding: Union[bool, str, PaddingStrategy] = False,
115
+ truncation: Union[bool, str, TruncationStrategy] = None,
116
+ max_length: Optional[int] = None,
117
+ pad_to_multiple_of: Optional[int] = None,
118
+ return_attention_mask: Optional[bool] = None,
119
+ return_length: bool = False,
120
+ verbose: bool = True,
121
+ return_tensors: Optional[Union[str, TensorType]] = None,
122
+ **kwargs,
123
+ ) -> BatchFeature:
124
+ """
125
+ This method uses [`CLIPImageProcessor.__call__`] method to prepare image(s) for the model, and
126
+ [`XLMRobertaTokenizerFast.__call__`] to prepare text for the model.
127
+
128
+ Please refer to the docstring of the above two methods for more information.
129
+
130
+ The rest of this documentation shows the arguments specific to `Kosmos2Processor`.
131
+
132
+ Args:
133
+ bboxes (`Union[List[Tuple[int]], List[Tuple[float]], List[List[Tuple[int]]], List[List[Tuple[float]]]]`, *optional*):
134
+ The bounding bboxes associated to `texts`.
135
+ num_image_tokens (`int`, defaults to 64):
136
+ The number of (consecutive) places that are used to mark the placeholders to store image information.
137
+ This should be the same as `latent_query_num` in the instance of `Kosmos2Config` you are using.
138
+ first_image_token_id (`int`, *optional*):
139
+ The token id that will be used for the first place of the subsequence that is reserved to store image
140
+ information. If unset, will default to `self.tokenizer.unk_token_id + 1`.
141
+ add_eos_token (`bool`, defaults to `False`):
142
+ Whether or not to include `EOS` token id in the encoding when `add_special_tokens=True`.
143
+ """
144
+ if images is None and text is None:
145
+ raise ValueError("You have to specify either images or text.")
146
+
147
+ encoding = BatchFeature()
148
+
149
+ if images is not None:
150
+ image_encoding = self.image_processor(images, return_tensors=return_tensors)
151
+ encoding.update(image_encoding)
152
+
153
+ if text is not None:
154
+ text = self.preprocess_examples(text, images, bboxes, num_image_tokens=num_image_tokens)
155
+
156
+ if add_special_tokens and not add_eos_token:
157
+ if isinstance(text, str):
158
+ text = f"{self.tokenizer.bos_token}{text}"
159
+ elif isinstance(text, list):
160
+ text = [f"{self.tokenizer.bos_token}{s}" for s in text]
161
+
162
+ text_encoding = self.tokenizer(
163
+ text=text,
164
+ add_special_tokens=(add_special_tokens and add_eos_token),
165
+ padding=padding and images is None,
166
+ truncation=truncation,
167
+ max_length=max_length,
168
+ pad_to_multiple_of=pad_to_multiple_of if images is None else pad_to_multiple_of,
169
+ return_attention_mask=return_attention_mask,
170
+ verbose=verbose,
171
+ return_tensors=return_tensors if images is None else None,
172
+ **kwargs,
173
+ )
174
+ encoding.update(text_encoding)
175
+
176
+ if text is not None and images is not None:
177
+ # Use the id of the first token after <unk>
178
+ if first_image_token_id is None:
179
+ first_image_token_id = self.tokenizer.unk_token_id + 1
180
+
181
+ # To see if we need one more `0` (for `<s>`) at the beginning of `image_embeds_position_mask`.
182
+ with_bos = add_special_tokens
183
+
184
+ # The first (actual) `<image>` token is always at the 1st or 2nd place (after `<s>` if any). Here we look
185
+ # for the second `<image>` token (which indicate the first image token).
186
+ start_index = int(with_bos) + 1
187
+
188
+ # Add `image_embeds_position_mask`: the leading and trailing `0` are for `boi` and `eoi` tokens. The `1` indicates
189
+ # the places of image tokens.
190
+ image_token_ids = list(range(first_image_token_id, first_image_token_id + num_image_tokens))
191
+ base_image_embeds_position_mask = [0] + [1] * num_image_tokens + [0]
192
+
193
+ # loop over `encoding["input_ids"]`
194
+ input_ids = []
195
+ image_embeds_position_mask = []
196
+ all_input_ids = encoding["input_ids"]
197
+ # not batched -> (changed to) batch of size 1
198
+ if isinstance(text, str):
199
+ all_input_ids = [all_input_ids]
200
+ encoding["attention_mask"] = [encoding["attention_mask"]]
201
+ for text_ids in all_input_ids:
202
+ # change the ids for the fake `<image>` tokens in `input_ids`
203
+ text_ids = text_ids[:start_index] + image_token_ids + text_ids[start_index + num_image_tokens :]
204
+ input_ids.append(text_ids)
205
+
206
+ mask = copy.copy(base_image_embeds_position_mask)
207
+ if with_bos:
208
+ # for `<s>`
209
+ mask = [0] + mask
210
+ # trailing part (which are not related to the image)
211
+ mask += [0] * (len(text_ids) - len(mask))
212
+ image_embeds_position_mask.append(mask)
213
+
214
+ if isinstance(text, list):
215
+ sorted_length = sorted(
216
+ [(idx, len(x)) for idx, x in enumerate(text_encoding.input_ids)], key=lambda x: x[-1]
217
+ )
218
+ _, min_len_not_padded = sorted_length[0]
219
+ idx, _ = sorted_length[-1]
220
+
221
+ text_encoding = self.tokenizer(
222
+ text=[text[idx]],
223
+ add_special_tokens=(add_special_tokens and add_eos_token),
224
+ padding=padding,
225
+ truncation=truncation,
226
+ max_length=max_length,
227
+ pad_to_multiple_of=pad_to_multiple_of,
228
+ verbose=verbose,
229
+ return_tensors=None,
230
+ **kwargs,
231
+ )
232
+ max_len_padded = len(text_encoding.input_ids[0])
233
+
234
+ if min_len_not_padded != max_len_padded:
235
+ if self.tokenizer.padding_side == "right":
236
+ input_ids = [x + [self.tokenizer.pad_token_id] * (max_len_padded - len(x)) for x in input_ids]
237
+ image_embeds_position_mask = [
238
+ x + [0] * (max_len_padded - len(x)) for x in image_embeds_position_mask
239
+ ]
240
+ encoding["attention_mask"] = [
241
+ x + [0] * (max_len_padded - len(x)) for x in encoding["attention_mask"]
242
+ ]
243
+ elif self.tokenizer.padding_side == "left":
244
+ input_ids = [[self.tokenizer.pad_token_id] * (max_len_padded - len(x)) + x for x in input_ids]
245
+ image_embeds_position_mask = [
246
+ [0] * (max_len_padded - len(x)) + x for x in image_embeds_position_mask
247
+ ]
248
+ encoding["attention_mask"] = [
249
+ [0] * (max_len_padded - len(x)) + x for x in encoding["attention_mask"]
250
+ ]
251
+
252
+ # un-batch if necessary
253
+ if isinstance(text, str) and return_tensors is None:
254
+ input_ids = input_ids[0]
255
+ encoding["attention_mask"] = encoding["attention_mask"][0]
256
+ image_embeds_position_mask = image_embeds_position_mask[0]
257
+
258
+ # update (with the target tensor type if specified)
259
+ encoding.update(
260
+ BatchEncoding(
261
+ data={
262
+ "input_ids": input_ids,
263
+ "attention_mask": encoding["attention_mask"],
264
+ "image_embeds_position_mask": image_embeds_position_mask,
265
+ },
266
+ tensor_type=return_tensors,
267
+ )
268
+ )
269
+
270
+ return encoding
271
+
272
+ def _check_bboxes_for_single_text(self, bboxes):
273
+ """
274
+ Check `bboxes` for a single text example. It could be
275
+ - `None`: no bounding box associated to a text.
276
+ - A list with each element being the bounding boxes associated to one `<phrase> ... </phrase>` pair found
277
+ in a text. This could be:
278
+ - `None`: no bounding box associated to a `<phrase> ... </phrase>` pair.
279
+ - A tuple of 2 integers: A single bounding box specified by patch indices.
280
+ - A tuple of 4 float point number: A single bounding box specified by (normalized) coordinates.
281
+ - A list containing the above 2 tuple types: Multiple bounding boxes for a
282
+ `<phrase> ... </phrase>` pair.
283
+ """
284
+ if bboxes is None:
285
+ return
286
+ elif not isinstance(bboxes, list):
287
+ raise ValueError("`bboxes` (for a single text example) should be `None` or a list.")
288
+
289
+ # `bbox` is the bounding boxes for a single <phrase> </phrase> pair
290
+ for bbox in bboxes:
291
+ if bbox is None:
292
+ continue
293
+ elif not isinstance(bbox, list):
294
+ bbox = [bbox]
295
+ for element in bbox:
296
+ if not isinstance(element, tuple) or not (
297
+ (len(element) == 2 and all(isinstance(x, int) for x in element))
298
+ or (len(element) == 4 and all(isinstance(x, float) for x in element))
299
+ ):
300
+ raise ValueError(
301
+ "Each element in `bboxes` (for a single text example) should be either `None`, a tuple containing "
302
+ "2 integers or 4 float point numbers, or a list containing such tuples. Also "
303
+ "make sure the arguments `texts` and `bboxes` passed to `preprocess_text` are both in "
304
+ "batches or both for a single example."
305
+ )
306
+
307
+ def _preprocess_single_example(self, text, image, bboxes, img_info_tokens):
308
+ text = text.strip()
309
+ if image is not None:
310
+ # Add `<image> ... (fake) image tokens ... </image>`
311
+ text = f"{img_info_tokens} {text}"
312
+
313
+ # Add `<object> <patch_idx_xxxx> <patch_idx_yyy> </object>` after `<phrase> phrase text </phrase>`
314
+ text = self._insert_patch_index_tokens(text, bboxes)
315
+ return text
316
+
317
+ def preprocess_examples(
318
+ self,
319
+ texts: Union[TextInput, List[TextInput]],
320
+ images: ImageInput = None,
321
+ bboxes: BboxInput = None,
322
+ num_image_tokens: Optional[int] = 64,
323
+ ) -> Union[str, List[str]]:
324
+ """Add image and bounding box information to `texts` as image and patch index tokens.
325
+
326
+ Args:
327
+ texts (`Union[TextInput, List[TextInput]]`): The texts to be processed.
328
+ images (`ImageInput`, *optional*): The images associated to `texts`.
329
+ bboxes (`Union[List[Tuple[int]], List[Tuple[float]], List[List[Tuple[int]]], List[List[Tuple[float]]]]`, *optional*):
330
+ The bounding bboxes associated to `texts`.
331
+ num_image_tokens (`int`, *optional*, defaults to 64):
332
+ The number of image tokens (used as latent queries). This should corresponds to the `latent_query_num`
333
+ attribute in `Kosmos2Config`.
334
+
335
+ Returns:
336
+ `Union[TextInput, List[TextInput]]`: The processed texts with image and patch index tokens.
337
+ """
338
+ # These are fake `<image>` tokens enclosed between (the actual) `<image>` token and `</image>`.
339
+ img_tokens = [self.boi_token] * num_image_tokens
340
+ img_info_tokens = " ".join([self.boi_token] + img_tokens + [self.eoi_token])
341
+
342
+ # make batch to simplify processing logic
343
+ batched = True
344
+ if isinstance(texts, str):
345
+ batched = False
346
+ texts = [texts]
347
+
348
+ if images is None:
349
+ images = [None] * len(texts)
350
+ elif not is_batched(images):
351
+ images = [images]
352
+ if len(texts) != len(images):
353
+ raise ValueError(
354
+ f"The number of examples in `texts` and `images` should be the same. Got {len(texts)} v.s. {len(images)} instead."
355
+ )
356
+
357
+ if not batched:
358
+ self._check_bboxes_for_single_text(bboxes)
359
+ bboxes = [bboxes]
360
+ elif bboxes is not None:
361
+ if not isinstance(bboxes, list):
362
+ raise ValueError("`bboxes` should be `None` or a list (as a batch) when `texts` is passed as a batch.")
363
+ for x in bboxes:
364
+ self._check_bboxes_for_single_text(x)
365
+ else:
366
+ bboxes = [None] * len(texts)
367
+
368
+ if len(bboxes) != len(texts):
369
+ raise ValueError(
370
+ f"The number of examples in `texts` and `bboxes` should be the same. Got {len(texts)} v.s. {len(bboxes)} instead."
371
+ )
372
+
373
+ result = [
374
+ self._preprocess_single_example(text, image, bbox, img_info_tokens)
375
+ for text, image, bbox in zip(texts, images, bboxes)
376
+ ]
377
+ # un-batch if necessary
378
+ if not batched:
379
+ result = result[0]
380
+
381
+ return result
382
+
383
+ # Copied from transformers.models.blip.processing_blip.BlipProcessor.batch_decode with BertTokenizerFast->PreTrainedTokenizer
384
+ def batch_decode(self, *args, **kwargs):
385
+ """
386
+ This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
387
+ refer to the docstring of this method for more information.
388
+ """
389
+ return self.tokenizer.batch_decode(*args, **kwargs)
390
+
391
+ # Copied from transformers.models.blip.processing_blip.BlipProcessor.decode with BertTokenizerFast->PreTrainedTokenizer
392
+ def decode(self, *args, **kwargs):
393
+ """
394
+ This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
395
+ the docstring of this method for more information.
396
+ """
397
+ return self.tokenizer.decode(*args, **kwargs)
398
+
399
+ def post_process_generation(self, text, cleanup_and_extract=True):
400
+ caption = text.split(self.eoi_token)[-1]
401
+ if cleanup_and_extract:
402
+ return clean_text_and_extract_entities_with_bboxes(caption)
403
+ return caption
404
+
405
+ @property
406
+ # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
407
+ def model_input_names(self):
408
+ tokenizer_input_names = self.tokenizer.model_input_names
409
+ image_processor_input_names = self.image_processor.model_input_names
410
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
411
+
412
+ def _insert_patch_index_tokens(self, text: str, bboxes: Union[List[Tuple[int]], List[Tuple[float]]]) -> str:
413
+ if bboxes is None or len(bboxes) == 0:
414
+ return text
415
+
416
+ matched_phrases = list(re.finditer(r"<phrase>.+?</phrase>", string=text))
417
+ if len(matched_phrases) != len(bboxes):
418
+ raise ValueError(
419
+ f"The number of elements in `bboxes` should be the same as the number of `<phrase> ... </phrase>` pairs in `text`. Got {len(matched_phrases)} v.s. {len(bboxes)} instead."
420
+ )
421
+
422
+ # insert object's patch index tokens
423
+ # the found `<phrase> ... </phrase>` pairs.
424
+ curr_pos = 0
425
+ buffer = []
426
+ for matched, bbox in zip(matched_phrases, bboxes):
427
+ _, end = matched.span()
428
+ buffer.append(text[curr_pos:end])
429
+ curr_pos = end
430
+ # A phrase without bbox
431
+ if bbox is None:
432
+ continue
433
+ # A phrase with a single bbox
434
+ if isinstance(bbox, tuple):
435
+ bbox = [bbox]
436
+ patch_index_strings = []
437
+ # A phrase could have multiple bboxes
438
+ if not all(box is not None for box in bbox):
439
+ raise ValueError(
440
+ "The multiple bounding boxes for a single phrase should not contain any `None` value."
441
+ )
442
+ for box in bbox:
443
+ patch_index_1, patch_index_2 = self._convert_bbox_to_patch_index_tokens(box)
444
+ patch_index_strings.append(f"{patch_index_1} {patch_index_2}")
445
+ # `bbox` being an empty list
446
+ if len(patch_index_strings) == 0:
447
+ continue
448
+ position_str = " </delimiter_of_multi_objects/> ".join(patch_index_strings)
449
+ buffer.append(f"<object> {position_str} </object>")
450
+ # remaining
451
+ if curr_pos < len(text):
452
+ buffer.append(text[curr_pos:])
453
+
454
+ text = "".join(buffer)
455
+ return text
456
+
457
+ def _convert_bbox_to_patch_index_tokens(
458
+ self, bbox: Union[Tuple[int, int], Tuple[float, float, float, float]]
459
+ ) -> Tuple[str, str]:
460
+ # already computed patch indices
461
+ if len(bbox) == 2:
462
+ idx_1, idx_2 = bbox
463
+ # bbox specified with (normalized) coordinates
464
+ else:
465
+ # use `self.tokenizer` to get `num_patches_per_side`
466
+ num_patches_per_side = int(math.sqrt(self.num_patch_index_tokens))
467
+ idx_1, idx_2 = coordinate_to_patch_index(bbox, num_patches_per_side)
468
+
469
+ token_1 = f"<patch_index_{str(idx_1).zfill(4)}>"
470
+ token_2 = f"<patch_index_{str(idx_2).zfill(4)}>"
471
+
472
+ return token_1, token_2
473
+
474
+
475
+ def coordinate_to_patch_index(bbox: Tuple[float, float, float, float], num_patches_per_side: int) -> Tuple[int, int]:
476
+ """Convert a bounding box to a pair of patch indices.
477
+
478
+ Args:
479
+ bbox (`Tuple[float, float, float, float]`):
480
+ The 4 coordinates of the bounding box, with the format being (x1, y1, x2, y2) specifying the upper-left and
481
+ lower-right corners of the box. It should have x2 > x1 and y2 > y1.
482
+ num_patches_per_side (`int`): the number of patches along each side.
483
+
484
+ Returns:
485
+ `Tuple[int, int]`: A pair of patch indices representing the upper-left patch and lower-right patch.
486
+ """
487
+ (x1, y1, x2, y2) = bbox
488
+
489
+ if not (x2 > x1 and y2 > y1):
490
+ raise ValueError("The coordinates in `bbox` should be `(x1, y1, x2, y2)` with `x2 > x1` and `y2 > y1`.")
491
+
492
+ ul_x = math.floor(x1 * num_patches_per_side)
493
+ ul_y = math.floor(y1 * num_patches_per_side)
494
+
495
+ lr_x = math.ceil(x2 * num_patches_per_side - 1)
496
+ lr_y = math.ceil(y2 * num_patches_per_side - 1)
497
+
498
+ ul_idx = ul_y * num_patches_per_side + ul_x
499
+ lr_idx = lr_y * num_patches_per_side + lr_x
500
+
501
+ return ul_idx, lr_idx
502
+
503
+
504
+ # copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L35C1-L75C38
505
+ # (with format modifications)
506
+ def patch_index_to_coordinate(ul_idx: int, lr_idx: int, num_patches_per_side: int):
507
+ """
508
+ Given a grid of length `num_patches_per_side` and the indices of the upper-left and lower-right corners of a
509
+ bounding box, returns the normalized coordinates of the bounding box, in the form (x1, y1, x2, y2).
510
+
511
+ Args:
512
+ ul_idx (`int`): the index of the grid cell that corresponds to the upper-left corner of the bounding box.
513
+ lr_idx (`int`): the index of the grid cell that corresponds to the lower-right corner of the bounding box.
514
+ num_patches_per_side (`int`): the number of patches along each side.
515
+
516
+ Returns:
517
+ `Tuple[float]`: the normalized coordinates of the bounding box, in the form (x1, y1, x2, y2).
518
+ """
519
+ # Compute the size of each cell in the grid
520
+ cell_size = 1.0 / num_patches_per_side
521
+
522
+ # Compute the x and y indices of the upper-left and lower-right corners of the bounding box
523
+ ul_x = ul_idx % num_patches_per_side
524
+ ul_y = ul_idx // num_patches_per_side
525
+
526
+ lr_x = lr_idx % num_patches_per_side
527
+ lr_y = lr_idx // num_patches_per_side
528
+
529
+ # Compute the normalized coordinates of the bounding box
530
+ if ul_idx == lr_idx:
531
+ x1 = ul_x * cell_size
532
+ y1 = ul_y * cell_size
533
+ x2 = lr_x * cell_size + cell_size
534
+ y2 = lr_y * cell_size + cell_size
535
+ elif ul_x == lr_x or ul_y == lr_y:
536
+ x1 = ul_x * cell_size
537
+ y1 = ul_y * cell_size
538
+ x2 = lr_x * cell_size + cell_size
539
+ y2 = lr_y * cell_size + cell_size
540
+ else:
541
+ x1 = ul_x * cell_size + cell_size / 2
542
+ y1 = ul_y * cell_size + cell_size / 2
543
+ x2 = lr_x * cell_size + cell_size / 2
544
+ y2 = lr_y * cell_size + cell_size / 2
545
+
546
+ return x1, y1, x2, y2
547
+
548
+
549
+ # copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L4-L33
550
+ # (with format modifications)
551
+ def extract_entities_with_patch_indices(text):
552
+ """Extract entities contained in `text`. The bounding bboxes is given in the form of patch indices.
553
+
554
+ This functioin is only intended to be used within `clean_text_and_extract_entities_with_bboxes` where further
555
+ processing happens, including converting to normalized coordinates and whitespace character cleaning up.
556
+
557
+ Examples:
558
+
559
+ ```python
560
+ >>> text = "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>."
561
+ >>> entities = extract_entities_with_patch_indices(text)
562
+ >>> entities
563
+ [(' a snowman', (31, 41), [(44, 863)]), (' a fire', (130, 137), [(5, 911)])]
564
+ ```"""
565
+ # The regular expression pattern for matching the required formats
566
+ pattern = r"(?:(<phrase>([^<]+)</phrase>))?<object>((?:<patch_index_\d+><patch_index_\d+></delimiter_of_multi_objects/>)*<patch_index_\d+><patch_index_\d+>)</object>"
567
+
568
+ # Find all matches in the given string
569
+ matches = re.finditer(pattern, text)
570
+
571
+ # Initialize an empty list to store the valid patch_index combinations
572
+ entities_with_patch_indices = []
573
+
574
+ for match in matches:
575
+ # span of a `phrase` that is between <phrase> and </phrase>
576
+ span = match.span(2)
577
+ phrase_tag, phrase, match_content = match.groups()
578
+ if not phrase_tag:
579
+ phrase = None
580
+ # We take the starting position of `<object>`
581
+ span = (match.span(0)[0], match.span(0)[0])
582
+
583
+ # Split the match_content by the delimiter to get individual patch_index pairs
584
+ patch_index_pairs = match_content.split("</delimiter_of_multi_objects/>")
585
+
586
+ entity_bboxes = []
587
+ for pair in patch_index_pairs:
588
+ # Extract the xxxx and yyyy values from the patch_index pair
589
+ x = re.search(r"<patch_index_(\d+)>", pair)
590
+ y = re.search(r"<patch_index_(\d+)>", pair[1:])
591
+
592
+ if x and y:
593
+ if phrase:
594
+ entity_bboxes.append((int(x.group(1)), int(y.group(1))))
595
+ else:
596
+ entity_bboxes.append((int(x.group(1)), int(y.group(1))))
597
+
598
+ if phrase:
599
+ entities_with_patch_indices.append((phrase, span, entity_bboxes))
600
+ else:
601
+ for bbox in entity_bboxes:
602
+ # fake entity name
603
+ entity = f"<patch_index_{bbox[0]}><patch_index_{bbox[1]}>"
604
+ entities_with_patch_indices.append((entity, span, [bbox]))
605
+
606
+ return entities_with_patch_indices
607
+
608
+
609
+ def adjust_entity_positions(entity, text):
610
+ """Adjust the positions of the entities in `text` to be relative to the text with special fields removed."""
611
+ entity_name, (start, end) = entity
612
+ # computed the length of strings with special fields (tag tokens, patch index tokens, etc.) removed
613
+ adjusted_start = len(re.sub("<.*?>", "", text[:start]))
614
+ adjusted_end = len(re.sub("<.*?>", "", text[:end]))
615
+ adjusted_entity = (entity_name, (adjusted_start, adjusted_end))
616
+ return adjusted_entity
617
+
618
+
619
+ def _cleanup_spaces(text, entities):
620
+ """Remove the spaces around the text and the entities in it."""
621
+ new_text = text.strip()
622
+ leading_spaces = len(text) - len(text.lstrip())
623
+
624
+ new_entities = []
625
+ for entity_name, (start, end), bboxes in entities:
626
+ entity_name_leading_spaces = len(entity_name) - len(entity_name.lstrip())
627
+ entity_name_trailing_spaces = len(entity_name) - len(entity_name.rstrip())
628
+
629
+ start = start - leading_spaces + entity_name_leading_spaces
630
+ end = end - leading_spaces - entity_name_trailing_spaces
631
+ entity_name = entity_name.strip()
632
+
633
+ new_entities.append((entity_name, (start, end), bboxes))
634
+
635
+ return new_text, new_entities
636
+
637
+
638
+ # copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L77-L87
639
+ # (with format modifications)
640
+ def clean_text_and_extract_entities_with_bboxes(text, num_patches_per_side=32):
641
+ """Remove the tag tokens from `text`, extract entities in it with some cleaning up of white characters.
642
+
643
+ Examples:
644
+
645
+ ```python
646
+ >>> text = "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>."
647
+ >>> clean_text, entities = clean_text_and_extract_entities_with_bboxes(text)
648
+ >>> clean_text
649
+ 'An image of a snowman warming himself by a fire.'
650
+
651
+ >>> entities
652
+ [('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]
653
+ ```"""
654
+ # remove special fields (tag tokens, patch index tokens, etc.)
655
+ processed_text = re.sub("<.*?>", "", text)
656
+
657
+ entities_with_patch_indices = extract_entities_with_patch_indices(text)
658
+ entities = []
659
+ for item in entities_with_patch_indices:
660
+ entity, bboxes = item[0:2], item[2]
661
+ adjusted_entity = adjust_entity_positions(entity, text)
662
+ bboxes_in_coords = [patch_index_to_coordinate(bbox[0], bbox[1], num_patches_per_side) for bbox in bboxes]
663
+
664
+ entities.append(adjusted_entity + (bboxes_in_coords,))
665
+
666
+ return _cleanup_spaces(processed_text, entities)
pllava/lib/python3.10/site-packages/transformers/models/mgp_str/__init__.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+ # There's no way to ignore "F401 '...' imported but unused" warnings in this
3
+ # module, but to preserve other warnings. So, don't check this module at all.
4
+
5
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ from typing import TYPE_CHECKING
19
+
20
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
21
+
22
+
23
+ _import_structure = {
24
+ "configuration_mgp_str": ["MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP", "MgpstrConfig"],
25
+ "processing_mgp_str": ["MgpstrProcessor"],
26
+ "tokenization_mgp_str": ["MgpstrTokenizer"],
27
+ }
28
+
29
+ try:
30
+ if not is_torch_available():
31
+ raise OptionalDependencyNotAvailable()
32
+ except OptionalDependencyNotAvailable:
33
+ pass
34
+ else:
35
+ _import_structure["modeling_mgp_str"] = [
36
+ "MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST",
37
+ "MgpstrModel",
38
+ "MgpstrPreTrainedModel",
39
+ "MgpstrForSceneTextRecognition",
40
+ ]
41
+
42
+ if TYPE_CHECKING:
43
+ from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig
44
+ from .processing_mgp_str import MgpstrProcessor
45
+ from .tokenization_mgp_str import MgpstrTokenizer
46
+
47
+ try:
48
+ if not is_torch_available():
49
+ raise OptionalDependencyNotAvailable()
50
+ except OptionalDependencyNotAvailable:
51
+ pass
52
+ else:
53
+ from .modeling_mgp_str import (
54
+ MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST,
55
+ MgpstrForSceneTextRecognition,
56
+ MgpstrModel,
57
+ MgpstrPreTrainedModel,
58
+ )
59
+ else:
60
+ import sys
61
+
62
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
pllava/lib/python3.10/site-packages/transformers/models/mgp_str/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.09 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/mgp_str/__pycache__/configuration_mgp_str.cpython-310.pyc ADDED
Binary file (5.08 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/mgp_str/__pycache__/processing_mgp_str.cpython-310.pyc ADDED
Binary file (8.01 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.21 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/configuration_mobilebert.cpython-310.pyc ADDED
Binary file (7.34 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/convert_mobilebert_original_tf_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (1.41 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/modeling_mobilebert.cpython-310.pyc ADDED
Binary file (48.4 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/modeling_tf_mobilebert.cpython-310.pyc ADDED
Binary file (56.5 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/tokenization_mobilebert.cpython-310.pyc ADDED
Binary file (17.4 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/tokenization_mobilebert_fast.cpython-310.pyc ADDED
Binary file (7.26 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/configuration_mobilebert.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
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
+ """ MobileBERT model configuration"""
16
+ from collections import OrderedDict
17
+ from typing import Mapping
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...onnx import OnnxConfig
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
27
+ "google/mobilebert-uncased": "https://huggingface.co/google/mobilebert-uncased/resolve/main/config.json"
28
+ }
29
+
30
+
31
+ class MobileBertConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`MobileBertModel`] or a [`TFMobileBertModel`]. It
34
+ is used to instantiate a MobileBERT model according to the specified arguments, defining the model architecture.
35
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the MobileBERT
36
+ [google/mobilebert-uncased](https://huggingface.co/google/mobilebert-uncased) architecture.
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+
42
+ Args:
43
+ vocab_size (`int`, *optional*, defaults to 30522):
44
+ Vocabulary size of the MobileBERT model. Defines the number of different tokens that can be represented by
45
+ the `inputs_ids` passed when calling [`MobileBertModel`] or [`TFMobileBertModel`].
46
+ hidden_size (`int`, *optional*, defaults to 512):
47
+ Dimensionality of the encoder layers and the pooler layer.
48
+ num_hidden_layers (`int`, *optional*, defaults to 24):
49
+ Number of hidden layers in the Transformer encoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 4):
51
+ Number of attention heads for each attention layer in the Transformer encoder.
52
+ intermediate_size (`int`, *optional*, defaults to 512):
53
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"relu"`):
55
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
56
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
57
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
58
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
59
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
60
+ The dropout ratio for the attention probabilities.
61
+ max_position_embeddings (`int`, *optional*, defaults to 512):
62
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
63
+ just in case (e.g., 512 or 1024 or 2048).
64
+ type_vocab_size (`int`, *optional*, defaults to 2):
65
+ The vocabulary size of the `token_type_ids` passed when calling [`MobileBertModel`] or
66
+ [`TFMobileBertModel`].
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-12):
70
+ The epsilon used by the layer normalization layers.
71
+
72
+ pad_token_id (`int`, *optional*, defaults to 0):
73
+ The ID of the token in the word embedding to use as padding.
74
+ embedding_size (`int`, *optional*, defaults to 128):
75
+ The dimension of the word embedding vectors.
76
+ trigram_input (`bool`, *optional*, defaults to `True`):
77
+ Use a convolution of trigram as input.
78
+ use_bottleneck (`bool`, *optional*, defaults to `True`):
79
+ Whether to use bottleneck in BERT.
80
+ intra_bottleneck_size (`int`, *optional*, defaults to 128):
81
+ Size of bottleneck layer output.
82
+ use_bottleneck_attention (`bool`, *optional*, defaults to `False`):
83
+ Whether to use attention inputs from the bottleneck transformation.
84
+ key_query_shared_bottleneck (`bool`, *optional*, defaults to `True`):
85
+ Whether to use the same linear transformation for query&key in the bottleneck.
86
+ num_feedforward_networks (`int`, *optional*, defaults to 4):
87
+ Number of FFNs in a block.
88
+ normalization_type (`str`, *optional*, defaults to `"no_norm"`):
89
+ The normalization type in MobileBERT.
90
+ classifier_dropout (`float`, *optional*):
91
+ The dropout ratio for the classification head.
92
+
93
+ Examples:
94
+
95
+ ```python
96
+ >>> from transformers import MobileBertConfig, MobileBertModel
97
+
98
+ >>> # Initializing a MobileBERT configuration
99
+ >>> configuration = MobileBertConfig()
100
+
101
+ >>> # Initializing a model (with random weights) from the configuration above
102
+ >>> model = MobileBertModel(configuration)
103
+
104
+ >>> # Accessing the model configuration
105
+ >>> configuration = model.config
106
+ ```
107
+
108
+ Attributes: pretrained_config_archive_map (Dict[str, str]): A dictionary containing all the available pre-trained
109
+ checkpoints.
110
+ """
111
+
112
+ pretrained_config_archive_map = MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP
113
+ model_type = "mobilebert"
114
+
115
+ def __init__(
116
+ self,
117
+ vocab_size=30522,
118
+ hidden_size=512,
119
+ num_hidden_layers=24,
120
+ num_attention_heads=4,
121
+ intermediate_size=512,
122
+ hidden_act="relu",
123
+ hidden_dropout_prob=0.0,
124
+ attention_probs_dropout_prob=0.1,
125
+ max_position_embeddings=512,
126
+ type_vocab_size=2,
127
+ initializer_range=0.02,
128
+ layer_norm_eps=1e-12,
129
+ pad_token_id=0,
130
+ embedding_size=128,
131
+ trigram_input=True,
132
+ use_bottleneck=True,
133
+ intra_bottleneck_size=128,
134
+ use_bottleneck_attention=False,
135
+ key_query_shared_bottleneck=True,
136
+ num_feedforward_networks=4,
137
+ normalization_type="no_norm",
138
+ classifier_activation=True,
139
+ classifier_dropout=None,
140
+ **kwargs,
141
+ ):
142
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
143
+
144
+ self.vocab_size = vocab_size
145
+ self.hidden_size = hidden_size
146
+ self.num_hidden_layers = num_hidden_layers
147
+ self.num_attention_heads = num_attention_heads
148
+ self.hidden_act = hidden_act
149
+ self.intermediate_size = intermediate_size
150
+ self.hidden_dropout_prob = hidden_dropout_prob
151
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
152
+ self.max_position_embeddings = max_position_embeddings
153
+ self.type_vocab_size = type_vocab_size
154
+ self.initializer_range = initializer_range
155
+ self.layer_norm_eps = layer_norm_eps
156
+ self.embedding_size = embedding_size
157
+ self.trigram_input = trigram_input
158
+ self.use_bottleneck = use_bottleneck
159
+ self.intra_bottleneck_size = intra_bottleneck_size
160
+ self.use_bottleneck_attention = use_bottleneck_attention
161
+ self.key_query_shared_bottleneck = key_query_shared_bottleneck
162
+ self.num_feedforward_networks = num_feedforward_networks
163
+ self.normalization_type = normalization_type
164
+ self.classifier_activation = classifier_activation
165
+
166
+ if self.use_bottleneck:
167
+ self.true_hidden_size = intra_bottleneck_size
168
+ else:
169
+ self.true_hidden_size = hidden_size
170
+
171
+ self.classifier_dropout = classifier_dropout
172
+
173
+
174
+ # Copied from transformers.models.bert.configuration_bert.BertOnnxConfig with Bert->MobileBert
175
+ class MobileBertOnnxConfig(OnnxConfig):
176
+ @property
177
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
178
+ if self.task == "multiple-choice":
179
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
180
+ else:
181
+ dynamic_axis = {0: "batch", 1: "sequence"}
182
+ return OrderedDict(
183
+ [
184
+ ("input_ids", dynamic_axis),
185
+ ("attention_mask", dynamic_axis),
186
+ ("token_type_ids", dynamic_axis),
187
+ ]
188
+ )
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/convert_mobilebert_original_tf_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse
16
+
17
+ import torch
18
+
19
+ from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert
20
+ from transformers.utils import logging
21
+
22
+
23
+ logging.set_verbosity_info()
24
+
25
+
26
+ def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, mobilebert_config_file, pytorch_dump_path):
27
+ # Initialise PyTorch model
28
+ config = MobileBertConfig.from_json_file(mobilebert_config_file)
29
+ print(f"Building PyTorch model from configuration: {config}")
30
+ model = MobileBertForPreTraining(config)
31
+ # Load weights from tf checkpoint
32
+ model = load_tf_weights_in_mobilebert(model, config, tf_checkpoint_path)
33
+ # Save pytorch-model
34
+ print(f"Save PyTorch model to {pytorch_dump_path}")
35
+ torch.save(model.state_dict(), pytorch_dump_path)
36
+
37
+
38
+ if __name__ == "__main__":
39
+ parser = argparse.ArgumentParser()
40
+ # Required parameters
41
+ parser.add_argument(
42
+ "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
43
+ )
44
+ parser.add_argument(
45
+ "--mobilebert_config_file",
46
+ default=None,
47
+ type=str,
48
+ required=True,
49
+ help=(
50
+ "The config json file corresponding to the pre-trained MobileBERT model. \n"
51
+ "This specifies the model architecture."
52
+ ),
53
+ )
54
+ parser.add_argument(
55
+ "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
56
+ )
57
+ args = parser.parse_args()
58
+ convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/modeling_mobilebert.py ADDED
@@ -0,0 +1,1617 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License
2
+ #
3
+ # Copyright (c) 2020 The Google AI Language Team Authors, The HuggingFace Inc. team and github/lonePatient
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in all
13
+ # copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ # SOFTWARE.
22
+
23
+ import math
24
+ import os
25
+ import warnings
26
+ from dataclasses import dataclass
27
+ from typing import Optional, Tuple, Union
28
+
29
+ import torch
30
+ from torch import nn
31
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
32
+
33
+ from ...activations import ACT2FN
34
+ from ...modeling_outputs import (
35
+ BaseModelOutput,
36
+ BaseModelOutputWithPooling,
37
+ MaskedLMOutput,
38
+ MultipleChoiceModelOutput,
39
+ NextSentencePredictorOutput,
40
+ QuestionAnsweringModelOutput,
41
+ SequenceClassifierOutput,
42
+ TokenClassifierOutput,
43
+ )
44
+ from ...modeling_utils import PreTrainedModel
45
+ from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
46
+ from ...utils import (
47
+ ModelOutput,
48
+ add_code_sample_docstrings,
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ logging,
52
+ replace_return_docstrings,
53
+ )
54
+ from .configuration_mobilebert import MobileBertConfig
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+ _CHECKPOINT_FOR_DOC = "google/mobilebert-uncased"
60
+ _CONFIG_FOR_DOC = "MobileBertConfig"
61
+
62
+ # TokenClassification docstring
63
+ _CHECKPOINT_FOR_TOKEN_CLASSIFICATION = "mrm8488/mobilebert-finetuned-ner"
64
+ _TOKEN_CLASS_EXPECTED_OUTPUT = "['I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC']"
65
+ _TOKEN_CLASS_EXPECTED_LOSS = 0.03
66
+
67
+ # QuestionAnswering docstring
68
+ _CHECKPOINT_FOR_QA = "csarron/mobilebert-uncased-squad-v2"
69
+ _QA_EXPECTED_OUTPUT = "'a nice puppet'"
70
+ _QA_EXPECTED_LOSS = 3.98
71
+ _QA_TARGET_START_INDEX = 12
72
+ _QA_TARGET_END_INDEX = 13
73
+
74
+ # SequenceClassification docstring
75
+ _CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "lordtt13/emo-mobilebert"
76
+ _SEQ_CLASS_EXPECTED_OUTPUT = "'others'"
77
+ _SEQ_CLASS_EXPECTED_LOSS = "4.72"
78
+
79
+ MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST = ["google/mobilebert-uncased"]
80
+
81
+
82
+ def load_tf_weights_in_mobilebert(model, config, tf_checkpoint_path):
83
+ """Load tf checkpoints in a pytorch model."""
84
+ try:
85
+ import re
86
+
87
+ import numpy as np
88
+ import tensorflow as tf
89
+ except ImportError:
90
+ logger.error(
91
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
92
+ "https://www.tensorflow.org/install/ for installation instructions."
93
+ )
94
+ raise
95
+ tf_path = os.path.abspath(tf_checkpoint_path)
96
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
97
+ # Load weights from TF model
98
+ init_vars = tf.train.list_variables(tf_path)
99
+ names = []
100
+ arrays = []
101
+ for name, shape in init_vars:
102
+ logger.info(f"Loading TF weight {name} with shape {shape}")
103
+ array = tf.train.load_variable(tf_path, name)
104
+ names.append(name)
105
+ arrays.append(array)
106
+
107
+ for name, array in zip(names, arrays):
108
+ name = name.replace("ffn_layer", "ffn")
109
+ name = name.replace("FakeLayerNorm", "LayerNorm")
110
+ name = name.replace("extra_output_weights", "dense/kernel")
111
+ name = name.replace("bert", "mobilebert")
112
+ name = name.split("/")
113
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
114
+ # which are not required for using pretrained model
115
+ if any(
116
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
117
+ for n in name
118
+ ):
119
+ logger.info(f"Skipping {'/'.join(name)}")
120
+ continue
121
+ pointer = model
122
+ for m_name in name:
123
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
124
+ scope_names = re.split(r"_(\d+)", m_name)
125
+ else:
126
+ scope_names = [m_name]
127
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
128
+ pointer = getattr(pointer, "weight")
129
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
130
+ pointer = getattr(pointer, "bias")
131
+ elif scope_names[0] == "output_weights":
132
+ pointer = getattr(pointer, "weight")
133
+ elif scope_names[0] == "squad":
134
+ pointer = getattr(pointer, "classifier")
135
+ else:
136
+ try:
137
+ pointer = getattr(pointer, scope_names[0])
138
+ except AttributeError:
139
+ logger.info(f"Skipping {'/'.join(name)}")
140
+ continue
141
+ if len(scope_names) >= 2:
142
+ num = int(scope_names[1])
143
+ pointer = pointer[num]
144
+ if m_name[-11:] == "_embeddings":
145
+ pointer = getattr(pointer, "weight")
146
+ elif m_name == "kernel":
147
+ array = np.transpose(array)
148
+ try:
149
+ assert (
150
+ pointer.shape == array.shape
151
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
152
+ except AssertionError as e:
153
+ e.args += (pointer.shape, array.shape)
154
+ raise
155
+ logger.info(f"Initialize PyTorch weight {name}")
156
+ pointer.data = torch.from_numpy(array)
157
+ return model
158
+
159
+
160
+ class NoNorm(nn.Module):
161
+ def __init__(self, feat_size, eps=None):
162
+ super().__init__()
163
+ self.bias = nn.Parameter(torch.zeros(feat_size))
164
+ self.weight = nn.Parameter(torch.ones(feat_size))
165
+
166
+ def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
167
+ return input_tensor * self.weight + self.bias
168
+
169
+
170
+ NORM2FN = {"layer_norm": nn.LayerNorm, "no_norm": NoNorm}
171
+
172
+
173
+ class MobileBertEmbeddings(nn.Module):
174
+ """Construct the embeddings from word, position and token_type embeddings."""
175
+
176
+ def __init__(self, config):
177
+ super().__init__()
178
+ self.trigram_input = config.trigram_input
179
+ self.embedding_size = config.embedding_size
180
+ self.hidden_size = config.hidden_size
181
+
182
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
183
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
184
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
185
+
186
+ embed_dim_multiplier = 3 if self.trigram_input else 1
187
+ embedded_input_size = self.embedding_size * embed_dim_multiplier
188
+ self.embedding_transformation = nn.Linear(embedded_input_size, config.hidden_size)
189
+
190
+ self.LayerNorm = NORM2FN[config.normalization_type](config.hidden_size)
191
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
192
+
193
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
194
+ self.register_buffer(
195
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
196
+ )
197
+
198
+ def forward(
199
+ self,
200
+ input_ids: Optional[torch.LongTensor] = None,
201
+ token_type_ids: Optional[torch.LongTensor] = None,
202
+ position_ids: Optional[torch.LongTensor] = None,
203
+ inputs_embeds: Optional[torch.FloatTensor] = None,
204
+ ) -> torch.Tensor:
205
+ if input_ids is not None:
206
+ input_shape = input_ids.size()
207
+ else:
208
+ input_shape = inputs_embeds.size()[:-1]
209
+
210
+ seq_length = input_shape[1]
211
+
212
+ if position_ids is None:
213
+ position_ids = self.position_ids[:, :seq_length]
214
+
215
+ if token_type_ids is None:
216
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
217
+ if inputs_embeds is None:
218
+ inputs_embeds = self.word_embeddings(input_ids)
219
+
220
+ if self.trigram_input:
221
+ # From the paper MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited
222
+ # Devices (https://arxiv.org/abs/2004.02984)
223
+ #
224
+ # The embedding table in BERT models accounts for a substantial proportion of model size. To compress
225
+ # the embedding layer, we reduce the embedding dimension to 128 in MobileBERT.
226
+ # Then, we apply a 1D convolution with kernel size 3 on the raw token embedding to produce a 512
227
+ # dimensional output.
228
+ inputs_embeds = torch.cat(
229
+ [
230
+ nn.functional.pad(inputs_embeds[:, 1:], [0, 0, 0, 1, 0, 0], value=0.0),
231
+ inputs_embeds,
232
+ nn.functional.pad(inputs_embeds[:, :-1], [0, 0, 1, 0, 0, 0], value=0.0),
233
+ ],
234
+ dim=2,
235
+ )
236
+ if self.trigram_input or self.embedding_size != self.hidden_size:
237
+ inputs_embeds = self.embedding_transformation(inputs_embeds)
238
+
239
+ # Add positional embeddings and token type embeddings, then layer
240
+ # normalize and perform dropout.
241
+ position_embeddings = self.position_embeddings(position_ids)
242
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
243
+ embeddings = inputs_embeds + position_embeddings + token_type_embeddings
244
+ embeddings = self.LayerNorm(embeddings)
245
+ embeddings = self.dropout(embeddings)
246
+ return embeddings
247
+
248
+
249
+ class MobileBertSelfAttention(nn.Module):
250
+ def __init__(self, config):
251
+ super().__init__()
252
+ self.num_attention_heads = config.num_attention_heads
253
+ self.attention_head_size = int(config.true_hidden_size / config.num_attention_heads)
254
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
255
+
256
+ self.query = nn.Linear(config.true_hidden_size, self.all_head_size)
257
+ self.key = nn.Linear(config.true_hidden_size, self.all_head_size)
258
+ self.value = nn.Linear(
259
+ config.true_hidden_size if config.use_bottleneck_attention else config.hidden_size, self.all_head_size
260
+ )
261
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
262
+
263
+ def transpose_for_scores(self, x):
264
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
265
+ x = x.view(new_x_shape)
266
+ return x.permute(0, 2, 1, 3)
267
+
268
+ def forward(
269
+ self,
270
+ query_tensor: torch.Tensor,
271
+ key_tensor: torch.Tensor,
272
+ value_tensor: torch.Tensor,
273
+ attention_mask: Optional[torch.FloatTensor] = None,
274
+ head_mask: Optional[torch.FloatTensor] = None,
275
+ output_attentions: Optional[bool] = None,
276
+ ) -> Tuple[torch.Tensor]:
277
+ mixed_query_layer = self.query(query_tensor)
278
+ mixed_key_layer = self.key(key_tensor)
279
+ mixed_value_layer = self.value(value_tensor)
280
+
281
+ query_layer = self.transpose_for_scores(mixed_query_layer)
282
+ key_layer = self.transpose_for_scores(mixed_key_layer)
283
+ value_layer = self.transpose_for_scores(mixed_value_layer)
284
+
285
+ # Take the dot product between "query" and "key" to get the raw attention scores.
286
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
287
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
288
+ if attention_mask is not None:
289
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
290
+ attention_scores = attention_scores + attention_mask
291
+ # Normalize the attention scores to probabilities.
292
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
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.dropout(attention_probs)
296
+ # Mask heads if we want to
297
+ if head_mask is not None:
298
+ attention_probs = attention_probs * head_mask
299
+ context_layer = torch.matmul(attention_probs, value_layer)
300
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
301
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
302
+ context_layer = context_layer.view(new_context_layer_shape)
303
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
304
+ return outputs
305
+
306
+
307
+ class MobileBertSelfOutput(nn.Module):
308
+ def __init__(self, config):
309
+ super().__init__()
310
+ self.use_bottleneck = config.use_bottleneck
311
+ self.dense = nn.Linear(config.true_hidden_size, config.true_hidden_size)
312
+ self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size, eps=config.layer_norm_eps)
313
+ if not self.use_bottleneck:
314
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
315
+
316
+ def forward(self, hidden_states: torch.Tensor, residual_tensor: torch.Tensor) -> torch.Tensor:
317
+ layer_outputs = self.dense(hidden_states)
318
+ if not self.use_bottleneck:
319
+ layer_outputs = self.dropout(layer_outputs)
320
+ layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
321
+ return layer_outputs
322
+
323
+
324
+ class MobileBertAttention(nn.Module):
325
+ def __init__(self, config):
326
+ super().__init__()
327
+ self.self = MobileBertSelfAttention(config)
328
+ self.output = MobileBertSelfOutput(config)
329
+ self.pruned_heads = set()
330
+
331
+ def prune_heads(self, heads):
332
+ if len(heads) == 0:
333
+ return
334
+ heads, index = find_pruneable_heads_and_indices(
335
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
336
+ )
337
+
338
+ # Prune linear layers
339
+ self.self.query = prune_linear_layer(self.self.query, index)
340
+ self.self.key = prune_linear_layer(self.self.key, index)
341
+ self.self.value = prune_linear_layer(self.self.value, index)
342
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
343
+
344
+ # Update hyper params and store pruned heads
345
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
346
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
347
+ self.pruned_heads = self.pruned_heads.union(heads)
348
+
349
+ def forward(
350
+ self,
351
+ query_tensor: torch.Tensor,
352
+ key_tensor: torch.Tensor,
353
+ value_tensor: torch.Tensor,
354
+ layer_input: torch.Tensor,
355
+ attention_mask: Optional[torch.FloatTensor] = None,
356
+ head_mask: Optional[torch.FloatTensor] = None,
357
+ output_attentions: Optional[bool] = None,
358
+ ) -> Tuple[torch.Tensor]:
359
+ self_outputs = self.self(
360
+ query_tensor,
361
+ key_tensor,
362
+ value_tensor,
363
+ attention_mask,
364
+ head_mask,
365
+ output_attentions,
366
+ )
367
+ # Run a linear projection of `hidden_size` then add a residual
368
+ # with `layer_input`.
369
+ attention_output = self.output(self_outputs[0], layer_input)
370
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
371
+ return outputs
372
+
373
+
374
+ class MobileBertIntermediate(nn.Module):
375
+ def __init__(self, config):
376
+ super().__init__()
377
+ self.dense = nn.Linear(config.true_hidden_size, config.intermediate_size)
378
+ if isinstance(config.hidden_act, str):
379
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
380
+ else:
381
+ self.intermediate_act_fn = config.hidden_act
382
+
383
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
384
+ hidden_states = self.dense(hidden_states)
385
+ hidden_states = self.intermediate_act_fn(hidden_states)
386
+ return hidden_states
387
+
388
+
389
+ class OutputBottleneck(nn.Module):
390
+ def __init__(self, config):
391
+ super().__init__()
392
+ self.dense = nn.Linear(config.true_hidden_size, config.hidden_size)
393
+ self.LayerNorm = NORM2FN[config.normalization_type](config.hidden_size, eps=config.layer_norm_eps)
394
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
395
+
396
+ def forward(self, hidden_states: torch.Tensor, residual_tensor: torch.Tensor) -> torch.Tensor:
397
+ layer_outputs = self.dense(hidden_states)
398
+ layer_outputs = self.dropout(layer_outputs)
399
+ layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
400
+ return layer_outputs
401
+
402
+
403
+ class MobileBertOutput(nn.Module):
404
+ def __init__(self, config):
405
+ super().__init__()
406
+ self.use_bottleneck = config.use_bottleneck
407
+ self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size)
408
+ self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size)
409
+ if not self.use_bottleneck:
410
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
411
+ else:
412
+ self.bottleneck = OutputBottleneck(config)
413
+
414
+ def forward(
415
+ self, intermediate_states: torch.Tensor, residual_tensor_1: torch.Tensor, residual_tensor_2: torch.Tensor
416
+ ) -> torch.Tensor:
417
+ layer_output = self.dense(intermediate_states)
418
+ if not self.use_bottleneck:
419
+ layer_output = self.dropout(layer_output)
420
+ layer_output = self.LayerNorm(layer_output + residual_tensor_1)
421
+ else:
422
+ layer_output = self.LayerNorm(layer_output + residual_tensor_1)
423
+ layer_output = self.bottleneck(layer_output, residual_tensor_2)
424
+ return layer_output
425
+
426
+
427
+ class BottleneckLayer(nn.Module):
428
+ def __init__(self, config):
429
+ super().__init__()
430
+ self.dense = nn.Linear(config.hidden_size, config.intra_bottleneck_size)
431
+ self.LayerNorm = NORM2FN[config.normalization_type](config.intra_bottleneck_size, eps=config.layer_norm_eps)
432
+
433
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
434
+ layer_input = self.dense(hidden_states)
435
+ layer_input = self.LayerNorm(layer_input)
436
+ return layer_input
437
+
438
+
439
+ class Bottleneck(nn.Module):
440
+ def __init__(self, config):
441
+ super().__init__()
442
+ self.key_query_shared_bottleneck = config.key_query_shared_bottleneck
443
+ self.use_bottleneck_attention = config.use_bottleneck_attention
444
+ self.input = BottleneckLayer(config)
445
+ if self.key_query_shared_bottleneck:
446
+ self.attention = BottleneckLayer(config)
447
+
448
+ def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor]:
449
+ # This method can return three different tuples of values. These different values make use of bottlenecks,
450
+ # which are linear layers used to project the hidden states to a lower-dimensional vector, reducing memory
451
+ # usage. These linear layer have weights that are learned during training.
452
+ #
453
+ # If `config.use_bottleneck_attention`, it will return the result of the bottleneck layer four times for the
454
+ # key, query, value, and "layer input" to be used by the attention layer.
455
+ # This bottleneck is used to project the hidden. This last layer input will be used as a residual tensor
456
+ # in the attention self output, after the attention scores have been computed.
457
+ #
458
+ # If not `config.use_bottleneck_attention` and `config.key_query_shared_bottleneck`, this will return
459
+ # four values, three of which have been passed through a bottleneck: the query and key, passed through the same
460
+ # bottleneck, and the residual layer to be applied in the attention self output, through another bottleneck.
461
+ #
462
+ # Finally, in the last case, the values for the query, key and values are the hidden states without bottleneck,
463
+ # and the residual layer will be this value passed through a bottleneck.
464
+
465
+ bottlenecked_hidden_states = self.input(hidden_states)
466
+ if self.use_bottleneck_attention:
467
+ return (bottlenecked_hidden_states,) * 4
468
+ elif self.key_query_shared_bottleneck:
469
+ shared_attention_input = self.attention(hidden_states)
470
+ return (shared_attention_input, shared_attention_input, hidden_states, bottlenecked_hidden_states)
471
+ else:
472
+ return (hidden_states, hidden_states, hidden_states, bottlenecked_hidden_states)
473
+
474
+
475
+ class FFNOutput(nn.Module):
476
+ def __init__(self, config):
477
+ super().__init__()
478
+ self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size)
479
+ self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size, eps=config.layer_norm_eps)
480
+
481
+ def forward(self, hidden_states: torch.Tensor, residual_tensor: torch.Tensor) -> torch.Tensor:
482
+ layer_outputs = self.dense(hidden_states)
483
+ layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
484
+ return layer_outputs
485
+
486
+
487
+ class FFNLayer(nn.Module):
488
+ def __init__(self, config):
489
+ super().__init__()
490
+ self.intermediate = MobileBertIntermediate(config)
491
+ self.output = FFNOutput(config)
492
+
493
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
494
+ intermediate_output = self.intermediate(hidden_states)
495
+ layer_outputs = self.output(intermediate_output, hidden_states)
496
+ return layer_outputs
497
+
498
+
499
+ class MobileBertLayer(nn.Module):
500
+ def __init__(self, config):
501
+ super().__init__()
502
+ self.use_bottleneck = config.use_bottleneck
503
+ self.num_feedforward_networks = config.num_feedforward_networks
504
+
505
+ self.attention = MobileBertAttention(config)
506
+ self.intermediate = MobileBertIntermediate(config)
507
+ self.output = MobileBertOutput(config)
508
+ if self.use_bottleneck:
509
+ self.bottleneck = Bottleneck(config)
510
+ if config.num_feedforward_networks > 1:
511
+ self.ffn = nn.ModuleList([FFNLayer(config) for _ in range(config.num_feedforward_networks - 1)])
512
+
513
+ def forward(
514
+ self,
515
+ hidden_states: torch.Tensor,
516
+ attention_mask: Optional[torch.FloatTensor] = None,
517
+ head_mask: Optional[torch.FloatTensor] = None,
518
+ output_attentions: Optional[bool] = None,
519
+ ) -> Tuple[torch.Tensor]:
520
+ if self.use_bottleneck:
521
+ query_tensor, key_tensor, value_tensor, layer_input = self.bottleneck(hidden_states)
522
+ else:
523
+ query_tensor, key_tensor, value_tensor, layer_input = [hidden_states] * 4
524
+
525
+ self_attention_outputs = self.attention(
526
+ query_tensor,
527
+ key_tensor,
528
+ value_tensor,
529
+ layer_input,
530
+ attention_mask,
531
+ head_mask,
532
+ output_attentions=output_attentions,
533
+ )
534
+ attention_output = self_attention_outputs[0]
535
+ s = (attention_output,)
536
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
537
+
538
+ if self.num_feedforward_networks != 1:
539
+ for i, ffn_module in enumerate(self.ffn):
540
+ attention_output = ffn_module(attention_output)
541
+ s += (attention_output,)
542
+
543
+ intermediate_output = self.intermediate(attention_output)
544
+ layer_output = self.output(intermediate_output, attention_output, hidden_states)
545
+ outputs = (
546
+ (layer_output,)
547
+ + outputs
548
+ + (
549
+ torch.tensor(1000),
550
+ query_tensor,
551
+ key_tensor,
552
+ value_tensor,
553
+ layer_input,
554
+ attention_output,
555
+ intermediate_output,
556
+ )
557
+ + s
558
+ )
559
+ return outputs
560
+
561
+
562
+ class MobileBertEncoder(nn.Module):
563
+ def __init__(self, config):
564
+ super().__init__()
565
+ self.layer = nn.ModuleList([MobileBertLayer(config) for _ in range(config.num_hidden_layers)])
566
+
567
+ def forward(
568
+ self,
569
+ hidden_states: torch.Tensor,
570
+ attention_mask: Optional[torch.FloatTensor] = None,
571
+ head_mask: Optional[torch.FloatTensor] = None,
572
+ output_attentions: Optional[bool] = False,
573
+ output_hidden_states: Optional[bool] = False,
574
+ return_dict: Optional[bool] = True,
575
+ ) -> Union[Tuple, BaseModelOutput]:
576
+ all_hidden_states = () if output_hidden_states else None
577
+ all_attentions = () if output_attentions else None
578
+ for i, layer_module in enumerate(self.layer):
579
+ if output_hidden_states:
580
+ all_hidden_states = all_hidden_states + (hidden_states,)
581
+
582
+ layer_outputs = layer_module(
583
+ hidden_states,
584
+ attention_mask,
585
+ head_mask[i],
586
+ output_attentions,
587
+ )
588
+ hidden_states = layer_outputs[0]
589
+
590
+ if output_attentions:
591
+ all_attentions = all_attentions + (layer_outputs[1],)
592
+
593
+ # Add last layer
594
+ if output_hidden_states:
595
+ all_hidden_states = all_hidden_states + (hidden_states,)
596
+
597
+ if not return_dict:
598
+ return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
599
+ return BaseModelOutput(
600
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
601
+ )
602
+
603
+
604
+ class MobileBertPooler(nn.Module):
605
+ def __init__(self, config):
606
+ super().__init__()
607
+ self.do_activate = config.classifier_activation
608
+ if self.do_activate:
609
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
610
+
611
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
612
+ # We "pool" the model by simply taking the hidden state corresponding
613
+ # to the first token.
614
+ first_token_tensor = hidden_states[:, 0]
615
+ if not self.do_activate:
616
+ return first_token_tensor
617
+ else:
618
+ pooled_output = self.dense(first_token_tensor)
619
+ pooled_output = torch.tanh(pooled_output)
620
+ return pooled_output
621
+
622
+
623
+ class MobileBertPredictionHeadTransform(nn.Module):
624
+ def __init__(self, config):
625
+ super().__init__()
626
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
627
+ if isinstance(config.hidden_act, str):
628
+ self.transform_act_fn = ACT2FN[config.hidden_act]
629
+ else:
630
+ self.transform_act_fn = config.hidden_act
631
+ self.LayerNorm = NORM2FN["layer_norm"](config.hidden_size, eps=config.layer_norm_eps)
632
+
633
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
634
+ hidden_states = self.dense(hidden_states)
635
+ hidden_states = self.transform_act_fn(hidden_states)
636
+ hidden_states = self.LayerNorm(hidden_states)
637
+ return hidden_states
638
+
639
+
640
+ class MobileBertLMPredictionHead(nn.Module):
641
+ def __init__(self, config):
642
+ super().__init__()
643
+ self.transform = MobileBertPredictionHeadTransform(config)
644
+ # The output weights are the same as the input embeddings, but there is
645
+ # an output-only bias for each token.
646
+ self.dense = nn.Linear(config.vocab_size, config.hidden_size - config.embedding_size, bias=False)
647
+ self.decoder = nn.Linear(config.embedding_size, config.vocab_size, bias=False)
648
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
649
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
650
+ self.decoder.bias = self.bias
651
+
652
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
653
+ hidden_states = self.transform(hidden_states)
654
+ hidden_states = hidden_states.matmul(torch.cat([self.decoder.weight.t(), self.dense.weight], dim=0))
655
+ hidden_states += self.decoder.bias
656
+ return hidden_states
657
+
658
+
659
+ class MobileBertOnlyMLMHead(nn.Module):
660
+ def __init__(self, config):
661
+ super().__init__()
662
+ self.predictions = MobileBertLMPredictionHead(config)
663
+
664
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
665
+ prediction_scores = self.predictions(sequence_output)
666
+ return prediction_scores
667
+
668
+
669
+ class MobileBertPreTrainingHeads(nn.Module):
670
+ def __init__(self, config):
671
+ super().__init__()
672
+ self.predictions = MobileBertLMPredictionHead(config)
673
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
674
+
675
+ def forward(self, sequence_output: torch.Tensor, pooled_output: torch.Tensor) -> Tuple[torch.Tensor]:
676
+ prediction_scores = self.predictions(sequence_output)
677
+ seq_relationship_score = self.seq_relationship(pooled_output)
678
+ return prediction_scores, seq_relationship_score
679
+
680
+
681
+ class MobileBertPreTrainedModel(PreTrainedModel):
682
+ """
683
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
684
+ models.
685
+ """
686
+
687
+ config_class = MobileBertConfig
688
+ pretrained_model_archive_map = MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST
689
+ load_tf_weights = load_tf_weights_in_mobilebert
690
+ base_model_prefix = "mobilebert"
691
+
692
+ def _init_weights(self, module):
693
+ """Initialize the weights"""
694
+ if isinstance(module, nn.Linear):
695
+ # Slightly different from the TF version which uses truncated_normal for initialization
696
+ # cf https://github.com/pytorch/pytorch/pull/5617
697
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
698
+ if module.bias is not None:
699
+ module.bias.data.zero_()
700
+ elif isinstance(module, nn.Embedding):
701
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
702
+ if module.padding_idx is not None:
703
+ module.weight.data[module.padding_idx].zero_()
704
+ elif isinstance(module, (nn.LayerNorm, NoNorm)):
705
+ module.bias.data.zero_()
706
+ module.weight.data.fill_(1.0)
707
+
708
+
709
+ @dataclass
710
+ class MobileBertForPreTrainingOutput(ModelOutput):
711
+ """
712
+ Output type of [`MobileBertForPreTraining`].
713
+
714
+ Args:
715
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
716
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
717
+ (classification) loss.
718
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
719
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
720
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
721
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
722
+ before SoftMax).
723
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
724
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
725
+ shape `(batch_size, sequence_length, hidden_size)`.
726
+
727
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
728
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
729
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
730
+ sequence_length)`.
731
+
732
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
733
+ heads.
734
+ """
735
+
736
+ loss: Optional[torch.FloatTensor] = None
737
+ prediction_logits: torch.FloatTensor = None
738
+ seq_relationship_logits: torch.FloatTensor = None
739
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
740
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
741
+
742
+
743
+ MOBILEBERT_START_DOCSTRING = r"""
744
+
745
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
746
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
747
+ etc.)
748
+
749
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
750
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
751
+ and behavior.
752
+
753
+ Parameters:
754
+ config ([`MobileBertConfig`]): Model configuration class with all the parameters of the model.
755
+ Initializing with a config file does not load the weights associated with the model, only the
756
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
757
+ """
758
+
759
+ MOBILEBERT_INPUTS_DOCSTRING = r"""
760
+ Args:
761
+ input_ids (`torch.LongTensor` of shape `({0})`):
762
+ Indices of input sequence tokens in the vocabulary.
763
+
764
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
765
+ [`PreTrainedTokenizer.__call__`] for details.
766
+
767
+ [What are input IDs?](../glossary#input-ids)
768
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
769
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
770
+
771
+ - 1 for tokens that are **not masked**,
772
+ - 0 for tokens that are **masked**.
773
+
774
+ [What are attention masks?](../glossary#attention-mask)
775
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
776
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
777
+ 1]`:
778
+
779
+ - 0 corresponds to a *sentence A* token,
780
+ - 1 corresponds to a *sentence B* token.
781
+
782
+ [What are token type IDs?](../glossary#token-type-ids)
783
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
784
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
785
+ config.max_position_embeddings - 1]`.
786
+
787
+ [What are position IDs?](../glossary#position-ids)
788
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
789
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
790
+
791
+ - 1 indicates the head is **not masked**,
792
+ - 0 indicates the head is **masked**.
793
+
794
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
795
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
796
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
797
+ model's internal embedding lookup matrix.
798
+ output_attentions (`bool`, *optional*):
799
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
800
+ tensors for more detail.
801
+ output_hidden_states (`bool`, *optional*):
802
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
803
+ more detail.
804
+ return_dict (`bool`, *optional*):
805
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
806
+ """
807
+
808
+
809
+ @add_start_docstrings(
810
+ "The bare MobileBert Model transformer outputting raw hidden-states without any specific head on top.",
811
+ MOBILEBERT_START_DOCSTRING,
812
+ )
813
+ class MobileBertModel(MobileBertPreTrainedModel):
814
+ """
815
+ https://arxiv.org/pdf/2004.02984.pdf
816
+ """
817
+
818
+ def __init__(self, config, add_pooling_layer=True):
819
+ super().__init__(config)
820
+ self.config = config
821
+ self.embeddings = MobileBertEmbeddings(config)
822
+ self.encoder = MobileBertEncoder(config)
823
+
824
+ self.pooler = MobileBertPooler(config) if add_pooling_layer else None
825
+
826
+ # Initialize weights and apply final processing
827
+ self.post_init()
828
+
829
+ def get_input_embeddings(self):
830
+ return self.embeddings.word_embeddings
831
+
832
+ def set_input_embeddings(self, value):
833
+ self.embeddings.word_embeddings = value
834
+
835
+ def _prune_heads(self, heads_to_prune):
836
+ """
837
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
838
+ class PreTrainedModel
839
+ """
840
+ for layer, heads in heads_to_prune.items():
841
+ self.encoder.layer[layer].attention.prune_heads(heads)
842
+
843
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
844
+ @add_code_sample_docstrings(
845
+ checkpoint=_CHECKPOINT_FOR_DOC,
846
+ output_type=BaseModelOutputWithPooling,
847
+ config_class=_CONFIG_FOR_DOC,
848
+ )
849
+ def forward(
850
+ self,
851
+ input_ids: Optional[torch.LongTensor] = None,
852
+ attention_mask: Optional[torch.FloatTensor] = None,
853
+ token_type_ids: Optional[torch.LongTensor] = None,
854
+ position_ids: Optional[torch.LongTensor] = None,
855
+ head_mask: Optional[torch.FloatTensor] = None,
856
+ inputs_embeds: Optional[torch.FloatTensor] = None,
857
+ output_hidden_states: Optional[bool] = None,
858
+ output_attentions: Optional[bool] = None,
859
+ return_dict: Optional[bool] = None,
860
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
861
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
862
+ output_hidden_states = (
863
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
864
+ )
865
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
866
+
867
+ if input_ids is not None and inputs_embeds is not None:
868
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
869
+ elif input_ids is not None:
870
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
871
+ input_shape = input_ids.size()
872
+ elif inputs_embeds is not None:
873
+ input_shape = inputs_embeds.size()[:-1]
874
+ else:
875
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
876
+
877
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
878
+
879
+ if attention_mask is None:
880
+ attention_mask = torch.ones(input_shape, device=device)
881
+ if token_type_ids is None:
882
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
883
+
884
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
885
+ # ourselves in which case we just need to make it broadcastable to all heads.
886
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
887
+
888
+ # Prepare head mask if needed
889
+ # 1.0 in head_mask indicate we keep the head
890
+ # attention_probs has shape bsz x n_heads x N x N
891
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
892
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
893
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
894
+
895
+ embedding_output = self.embeddings(
896
+ input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
897
+ )
898
+ encoder_outputs = self.encoder(
899
+ embedding_output,
900
+ attention_mask=extended_attention_mask,
901
+ head_mask=head_mask,
902
+ output_attentions=output_attentions,
903
+ output_hidden_states=output_hidden_states,
904
+ return_dict=return_dict,
905
+ )
906
+ sequence_output = encoder_outputs[0]
907
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
908
+
909
+ if not return_dict:
910
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
911
+
912
+ return BaseModelOutputWithPooling(
913
+ last_hidden_state=sequence_output,
914
+ pooler_output=pooled_output,
915
+ hidden_states=encoder_outputs.hidden_states,
916
+ attentions=encoder_outputs.attentions,
917
+ )
918
+
919
+
920
+ @add_start_docstrings(
921
+ """
922
+ MobileBert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
923
+ `next sentence prediction (classification)` head.
924
+ """,
925
+ MOBILEBERT_START_DOCSTRING,
926
+ )
927
+ class MobileBertForPreTraining(MobileBertPreTrainedModel):
928
+ _tied_weights_keys = ["cls.predictions.decoder.weight", "cls.predictions.decoder.bias"]
929
+
930
+ def __init__(self, config):
931
+ super().__init__(config)
932
+ self.mobilebert = MobileBertModel(config)
933
+ self.cls = MobileBertPreTrainingHeads(config)
934
+
935
+ # Initialize weights and apply final processing
936
+ self.post_init()
937
+
938
+ def get_output_embeddings(self):
939
+ return self.cls.predictions.decoder
940
+
941
+ def set_output_embeddings(self, new_embeddigs):
942
+ self.cls.predictions.decoder = new_embeddigs
943
+
944
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding:
945
+ # resize dense output embedings at first
946
+ self.cls.predictions.dense = self._get_resized_lm_head(
947
+ self.cls.predictions.dense, new_num_tokens=new_num_tokens, transposed=True
948
+ )
949
+
950
+ return super().resize_token_embeddings(new_num_tokens=new_num_tokens)
951
+
952
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
953
+ @replace_return_docstrings(output_type=MobileBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
954
+ def forward(
955
+ self,
956
+ input_ids: Optional[torch.LongTensor] = None,
957
+ attention_mask: Optional[torch.FloatTensor] = None,
958
+ token_type_ids: Optional[torch.LongTensor] = None,
959
+ position_ids: Optional[torch.LongTensor] = None,
960
+ head_mask: Optional[torch.FloatTensor] = None,
961
+ inputs_embeds: Optional[torch.FloatTensor] = None,
962
+ labels: Optional[torch.LongTensor] = None,
963
+ next_sentence_label: Optional[torch.LongTensor] = None,
964
+ output_attentions: Optional[torch.FloatTensor] = None,
965
+ output_hidden_states: Optional[torch.FloatTensor] = None,
966
+ return_dict: Optional[torch.FloatTensor] = None,
967
+ ) -> Union[Tuple, MobileBertForPreTrainingOutput]:
968
+ r"""
969
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
970
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
971
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
972
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
973
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
974
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
975
+ (see `input_ids` docstring) Indices should be in `[0, 1]`:
976
+
977
+ - 0 indicates sequence B is a continuation of sequence A,
978
+ - 1 indicates sequence B is a random sequence.
979
+
980
+ Returns:
981
+
982
+ Examples:
983
+
984
+ ```python
985
+ >>> from transformers import AutoTokenizer, MobileBertForPreTraining
986
+ >>> import torch
987
+
988
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mobilebert-uncased")
989
+ >>> model = MobileBertForPreTraining.from_pretrained("google/mobilebert-uncased")
990
+
991
+ >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)
992
+ >>> # Batch size 1
993
+ >>> outputs = model(input_ids)
994
+
995
+ >>> prediction_logits = outputs.prediction_logits
996
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
997
+ ```"""
998
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
999
+
1000
+ outputs = self.mobilebert(
1001
+ input_ids,
1002
+ attention_mask=attention_mask,
1003
+ token_type_ids=token_type_ids,
1004
+ position_ids=position_ids,
1005
+ head_mask=head_mask,
1006
+ inputs_embeds=inputs_embeds,
1007
+ output_attentions=output_attentions,
1008
+ output_hidden_states=output_hidden_states,
1009
+ return_dict=return_dict,
1010
+ )
1011
+ sequence_output, pooled_output = outputs[:2]
1012
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
1013
+
1014
+ total_loss = None
1015
+ if labels is not None and next_sentence_label is not None:
1016
+ loss_fct = CrossEntropyLoss()
1017
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1018
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
1019
+ total_loss = masked_lm_loss + next_sentence_loss
1020
+
1021
+ if not return_dict:
1022
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1023
+ return ((total_loss,) + output) if total_loss is not None else output
1024
+
1025
+ return MobileBertForPreTrainingOutput(
1026
+ loss=total_loss,
1027
+ prediction_logits=prediction_scores,
1028
+ seq_relationship_logits=seq_relationship_score,
1029
+ hidden_states=outputs.hidden_states,
1030
+ attentions=outputs.attentions,
1031
+ )
1032
+
1033
+
1034
+ @add_start_docstrings("""MobileBert Model with a `language modeling` head on top.""", MOBILEBERT_START_DOCSTRING)
1035
+ class MobileBertForMaskedLM(MobileBertPreTrainedModel):
1036
+ _tied_weights_keys = ["cls.predictions.decoder.weight", "cls.predictions.decoder.bias"]
1037
+
1038
+ def __init__(self, config):
1039
+ super().__init__(config)
1040
+ self.mobilebert = MobileBertModel(config, add_pooling_layer=False)
1041
+ self.cls = MobileBertOnlyMLMHead(config)
1042
+ self.config = config
1043
+
1044
+ # Initialize weights and apply final processing
1045
+ self.post_init()
1046
+
1047
+ def get_output_embeddings(self):
1048
+ return self.cls.predictions.decoder
1049
+
1050
+ def set_output_embeddings(self, new_embeddigs):
1051
+ self.cls.predictions.decoder = new_embeddigs
1052
+
1053
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding:
1054
+ # resize dense output embedings at first
1055
+ self.cls.predictions.dense = self._get_resized_lm_head(
1056
+ self.cls.predictions.dense, new_num_tokens=new_num_tokens, transposed=True
1057
+ )
1058
+ return super().resize_token_embeddings(new_num_tokens=new_num_tokens)
1059
+
1060
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1061
+ @add_code_sample_docstrings(
1062
+ checkpoint=_CHECKPOINT_FOR_DOC,
1063
+ output_type=MaskedLMOutput,
1064
+ config_class=_CONFIG_FOR_DOC,
1065
+ expected_output="'paris'",
1066
+ expected_loss=0.57,
1067
+ )
1068
+ def forward(
1069
+ self,
1070
+ input_ids: Optional[torch.LongTensor] = None,
1071
+ attention_mask: Optional[torch.FloatTensor] = None,
1072
+ token_type_ids: Optional[torch.LongTensor] = None,
1073
+ position_ids: Optional[torch.LongTensor] = None,
1074
+ head_mask: Optional[torch.FloatTensor] = None,
1075
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1076
+ labels: Optional[torch.LongTensor] = None,
1077
+ output_attentions: Optional[bool] = None,
1078
+ output_hidden_states: Optional[bool] = None,
1079
+ return_dict: Optional[bool] = None,
1080
+ ) -> Union[Tuple, MaskedLMOutput]:
1081
+ r"""
1082
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1083
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1084
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1085
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1086
+ """
1087
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1088
+
1089
+ outputs = self.mobilebert(
1090
+ input_ids,
1091
+ attention_mask=attention_mask,
1092
+ token_type_ids=token_type_ids,
1093
+ position_ids=position_ids,
1094
+ head_mask=head_mask,
1095
+ inputs_embeds=inputs_embeds,
1096
+ output_attentions=output_attentions,
1097
+ output_hidden_states=output_hidden_states,
1098
+ return_dict=return_dict,
1099
+ )
1100
+
1101
+ sequence_output = outputs[0]
1102
+ prediction_scores = self.cls(sequence_output)
1103
+
1104
+ masked_lm_loss = None
1105
+ if labels is not None:
1106
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1107
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1108
+
1109
+ if not return_dict:
1110
+ output = (prediction_scores,) + outputs[2:]
1111
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1112
+
1113
+ return MaskedLMOutput(
1114
+ loss=masked_lm_loss,
1115
+ logits=prediction_scores,
1116
+ hidden_states=outputs.hidden_states,
1117
+ attentions=outputs.attentions,
1118
+ )
1119
+
1120
+
1121
+ class MobileBertOnlyNSPHead(nn.Module):
1122
+ def __init__(self, config):
1123
+ super().__init__()
1124
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
1125
+
1126
+ def forward(self, pooled_output: torch.Tensor) -> torch.Tensor:
1127
+ seq_relationship_score = self.seq_relationship(pooled_output)
1128
+ return seq_relationship_score
1129
+
1130
+
1131
+ @add_start_docstrings(
1132
+ """MobileBert Model with a `next sentence prediction (classification)` head on top.""",
1133
+ MOBILEBERT_START_DOCSTRING,
1134
+ )
1135
+ class MobileBertForNextSentencePrediction(MobileBertPreTrainedModel):
1136
+ def __init__(self, config):
1137
+ super().__init__(config)
1138
+
1139
+ self.mobilebert = MobileBertModel(config)
1140
+ self.cls = MobileBertOnlyNSPHead(config)
1141
+
1142
+ # Initialize weights and apply final processing
1143
+ self.post_init()
1144
+
1145
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1146
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
1147
+ def forward(
1148
+ self,
1149
+ input_ids: Optional[torch.LongTensor] = None,
1150
+ attention_mask: Optional[torch.FloatTensor] = None,
1151
+ token_type_ids: Optional[torch.LongTensor] = None,
1152
+ position_ids: Optional[torch.LongTensor] = None,
1153
+ head_mask: Optional[torch.FloatTensor] = None,
1154
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1155
+ labels: Optional[torch.LongTensor] = None,
1156
+ output_attentions: Optional[bool] = None,
1157
+ output_hidden_states: Optional[bool] = None,
1158
+ return_dict: Optional[bool] = None,
1159
+ **kwargs,
1160
+ ) -> Union[Tuple, NextSentencePredictorOutput]:
1161
+ r"""
1162
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1163
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1164
+ (see `input_ids` docstring) Indices should be in `[0, 1]`.
1165
+
1166
+ - 0 indicates sequence B is a continuation of sequence A,
1167
+ - 1 indicates sequence B is a random sequence.
1168
+
1169
+ Returns:
1170
+
1171
+ Examples:
1172
+
1173
+ ```python
1174
+ >>> from transformers import AutoTokenizer, MobileBertForNextSentencePrediction
1175
+ >>> import torch
1176
+
1177
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mobilebert-uncased")
1178
+ >>> model = MobileBertForNextSentencePrediction.from_pretrained("google/mobilebert-uncased")
1179
+
1180
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1181
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1182
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
1183
+
1184
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
1185
+ >>> loss = outputs.loss
1186
+ >>> logits = outputs.logits
1187
+ ```"""
1188
+
1189
+ if "next_sentence_label" in kwargs:
1190
+ warnings.warn(
1191
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
1192
+ " `labels` instead.",
1193
+ FutureWarning,
1194
+ )
1195
+ labels = kwargs.pop("next_sentence_label")
1196
+
1197
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1198
+
1199
+ outputs = self.mobilebert(
1200
+ input_ids,
1201
+ attention_mask=attention_mask,
1202
+ token_type_ids=token_type_ids,
1203
+ position_ids=position_ids,
1204
+ head_mask=head_mask,
1205
+ inputs_embeds=inputs_embeds,
1206
+ output_attentions=output_attentions,
1207
+ output_hidden_states=output_hidden_states,
1208
+ return_dict=return_dict,
1209
+ )
1210
+
1211
+ pooled_output = outputs[1]
1212
+ seq_relationship_score = self.cls(pooled_output)
1213
+
1214
+ next_sentence_loss = None
1215
+ if labels is not None:
1216
+ loss_fct = CrossEntropyLoss()
1217
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), labels.view(-1))
1218
+
1219
+ if not return_dict:
1220
+ output = (seq_relationship_score,) + outputs[2:]
1221
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1222
+
1223
+ return NextSentencePredictorOutput(
1224
+ loss=next_sentence_loss,
1225
+ logits=seq_relationship_score,
1226
+ hidden_states=outputs.hidden_states,
1227
+ attentions=outputs.attentions,
1228
+ )
1229
+
1230
+
1231
+ @add_start_docstrings(
1232
+ """
1233
+ MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
1234
+ pooled output) e.g. for GLUE tasks.
1235
+ """,
1236
+ MOBILEBERT_START_DOCSTRING,
1237
+ )
1238
+ # Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification with Bert->MobileBert all-casing
1239
+ class MobileBertForSequenceClassification(MobileBertPreTrainedModel):
1240
+ def __init__(self, config):
1241
+ super().__init__(config)
1242
+ self.num_labels = config.num_labels
1243
+ self.config = config
1244
+
1245
+ self.mobilebert = MobileBertModel(config)
1246
+ classifier_dropout = (
1247
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1248
+ )
1249
+ self.dropout = nn.Dropout(classifier_dropout)
1250
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1251
+
1252
+ # Initialize weights and apply final processing
1253
+ self.post_init()
1254
+
1255
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1256
+ @add_code_sample_docstrings(
1257
+ checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
1258
+ output_type=SequenceClassifierOutput,
1259
+ config_class=_CONFIG_FOR_DOC,
1260
+ expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
1261
+ expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
1262
+ )
1263
+ def forward(
1264
+ self,
1265
+ input_ids: Optional[torch.Tensor] = None,
1266
+ attention_mask: Optional[torch.Tensor] = None,
1267
+ token_type_ids: Optional[torch.Tensor] = None,
1268
+ position_ids: Optional[torch.Tensor] = None,
1269
+ head_mask: Optional[torch.Tensor] = None,
1270
+ inputs_embeds: Optional[torch.Tensor] = None,
1271
+ labels: Optional[torch.Tensor] = None,
1272
+ output_attentions: Optional[bool] = None,
1273
+ output_hidden_states: Optional[bool] = None,
1274
+ return_dict: Optional[bool] = None,
1275
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1276
+ r"""
1277
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1278
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1279
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1280
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1281
+ """
1282
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1283
+
1284
+ outputs = self.mobilebert(
1285
+ input_ids,
1286
+ attention_mask=attention_mask,
1287
+ token_type_ids=token_type_ids,
1288
+ position_ids=position_ids,
1289
+ head_mask=head_mask,
1290
+ inputs_embeds=inputs_embeds,
1291
+ output_attentions=output_attentions,
1292
+ output_hidden_states=output_hidden_states,
1293
+ return_dict=return_dict,
1294
+ )
1295
+
1296
+ pooled_output = outputs[1]
1297
+
1298
+ pooled_output = self.dropout(pooled_output)
1299
+ logits = self.classifier(pooled_output)
1300
+
1301
+ loss = None
1302
+ if labels is not None:
1303
+ if self.config.problem_type is None:
1304
+ if self.num_labels == 1:
1305
+ self.config.problem_type = "regression"
1306
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1307
+ self.config.problem_type = "single_label_classification"
1308
+ else:
1309
+ self.config.problem_type = "multi_label_classification"
1310
+
1311
+ if self.config.problem_type == "regression":
1312
+ loss_fct = MSELoss()
1313
+ if self.num_labels == 1:
1314
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1315
+ else:
1316
+ loss = loss_fct(logits, labels)
1317
+ elif self.config.problem_type == "single_label_classification":
1318
+ loss_fct = CrossEntropyLoss()
1319
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1320
+ elif self.config.problem_type == "multi_label_classification":
1321
+ loss_fct = BCEWithLogitsLoss()
1322
+ loss = loss_fct(logits, labels)
1323
+ if not return_dict:
1324
+ output = (logits,) + outputs[2:]
1325
+ return ((loss,) + output) if loss is not None else output
1326
+
1327
+ return SequenceClassifierOutput(
1328
+ loss=loss,
1329
+ logits=logits,
1330
+ hidden_states=outputs.hidden_states,
1331
+ attentions=outputs.attentions,
1332
+ )
1333
+
1334
+
1335
+ @add_start_docstrings(
1336
+ """
1337
+ MobileBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
1338
+ linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1339
+ """,
1340
+ MOBILEBERT_START_DOCSTRING,
1341
+ )
1342
+ # Copied from transformers.models.bert.modeling_bert.BertForQuestionAnswering with Bert->MobileBert all-casing
1343
+ class MobileBertForQuestionAnswering(MobileBertPreTrainedModel):
1344
+ def __init__(self, config):
1345
+ super().__init__(config)
1346
+ self.num_labels = config.num_labels
1347
+
1348
+ self.mobilebert = MobileBertModel(config, add_pooling_layer=False)
1349
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1350
+
1351
+ # Initialize weights and apply final processing
1352
+ self.post_init()
1353
+
1354
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1355
+ @add_code_sample_docstrings(
1356
+ checkpoint=_CHECKPOINT_FOR_QA,
1357
+ output_type=QuestionAnsweringModelOutput,
1358
+ config_class=_CONFIG_FOR_DOC,
1359
+ qa_target_start_index=_QA_TARGET_START_INDEX,
1360
+ qa_target_end_index=_QA_TARGET_END_INDEX,
1361
+ expected_output=_QA_EXPECTED_OUTPUT,
1362
+ expected_loss=_QA_EXPECTED_LOSS,
1363
+ )
1364
+ def forward(
1365
+ self,
1366
+ input_ids: Optional[torch.Tensor] = None,
1367
+ attention_mask: Optional[torch.Tensor] = None,
1368
+ token_type_ids: Optional[torch.Tensor] = None,
1369
+ position_ids: Optional[torch.Tensor] = None,
1370
+ head_mask: Optional[torch.Tensor] = None,
1371
+ inputs_embeds: Optional[torch.Tensor] = None,
1372
+ start_positions: Optional[torch.Tensor] = None,
1373
+ end_positions: Optional[torch.Tensor] = None,
1374
+ output_attentions: Optional[bool] = None,
1375
+ output_hidden_states: Optional[bool] = None,
1376
+ return_dict: Optional[bool] = None,
1377
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1378
+ r"""
1379
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1380
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1381
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1382
+ are not taken into account for computing the loss.
1383
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1384
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1385
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1386
+ are not taken into account for computing the loss.
1387
+ """
1388
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1389
+
1390
+ outputs = self.mobilebert(
1391
+ input_ids,
1392
+ attention_mask=attention_mask,
1393
+ token_type_ids=token_type_ids,
1394
+ position_ids=position_ids,
1395
+ head_mask=head_mask,
1396
+ inputs_embeds=inputs_embeds,
1397
+ output_attentions=output_attentions,
1398
+ output_hidden_states=output_hidden_states,
1399
+ return_dict=return_dict,
1400
+ )
1401
+
1402
+ sequence_output = outputs[0]
1403
+
1404
+ logits = self.qa_outputs(sequence_output)
1405
+ start_logits, end_logits = logits.split(1, dim=-1)
1406
+ start_logits = start_logits.squeeze(-1).contiguous()
1407
+ end_logits = end_logits.squeeze(-1).contiguous()
1408
+
1409
+ total_loss = None
1410
+ if start_positions is not None and end_positions is not None:
1411
+ # If we are on multi-GPU, split add a dimension
1412
+ if len(start_positions.size()) > 1:
1413
+ start_positions = start_positions.squeeze(-1)
1414
+ if len(end_positions.size()) > 1:
1415
+ end_positions = end_positions.squeeze(-1)
1416
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1417
+ ignored_index = start_logits.size(1)
1418
+ start_positions = start_positions.clamp(0, ignored_index)
1419
+ end_positions = end_positions.clamp(0, ignored_index)
1420
+
1421
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1422
+ start_loss = loss_fct(start_logits, start_positions)
1423
+ end_loss = loss_fct(end_logits, end_positions)
1424
+ total_loss = (start_loss + end_loss) / 2
1425
+
1426
+ if not return_dict:
1427
+ output = (start_logits, end_logits) + outputs[2:]
1428
+ return ((total_loss,) + output) if total_loss is not None else output
1429
+
1430
+ return QuestionAnsweringModelOutput(
1431
+ loss=total_loss,
1432
+ start_logits=start_logits,
1433
+ end_logits=end_logits,
1434
+ hidden_states=outputs.hidden_states,
1435
+ attentions=outputs.attentions,
1436
+ )
1437
+
1438
+
1439
+ @add_start_docstrings(
1440
+ """
1441
+ MobileBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
1442
+ a softmax) e.g. for RocStories/SWAG tasks.
1443
+ """,
1444
+ MOBILEBERT_START_DOCSTRING,
1445
+ )
1446
+ # Copied from transformers.models.bert.modeling_bert.BertForMultipleChoice with Bert->MobileBert all-casing
1447
+ class MobileBertForMultipleChoice(MobileBertPreTrainedModel):
1448
+ def __init__(self, config):
1449
+ super().__init__(config)
1450
+
1451
+ self.mobilebert = MobileBertModel(config)
1452
+ classifier_dropout = (
1453
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1454
+ )
1455
+ self.dropout = nn.Dropout(classifier_dropout)
1456
+ self.classifier = nn.Linear(config.hidden_size, 1)
1457
+
1458
+ # Initialize weights and apply final processing
1459
+ self.post_init()
1460
+
1461
+ @add_start_docstrings_to_model_forward(
1462
+ MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1463
+ )
1464
+ @add_code_sample_docstrings(
1465
+ checkpoint=_CHECKPOINT_FOR_DOC,
1466
+ output_type=MultipleChoiceModelOutput,
1467
+ config_class=_CONFIG_FOR_DOC,
1468
+ )
1469
+ def forward(
1470
+ self,
1471
+ input_ids: Optional[torch.Tensor] = None,
1472
+ attention_mask: Optional[torch.Tensor] = None,
1473
+ token_type_ids: Optional[torch.Tensor] = None,
1474
+ position_ids: Optional[torch.Tensor] = None,
1475
+ head_mask: Optional[torch.Tensor] = None,
1476
+ inputs_embeds: Optional[torch.Tensor] = None,
1477
+ labels: Optional[torch.Tensor] = None,
1478
+ output_attentions: Optional[bool] = None,
1479
+ output_hidden_states: Optional[bool] = None,
1480
+ return_dict: Optional[bool] = None,
1481
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
1482
+ r"""
1483
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1484
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1485
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1486
+ `input_ids` above)
1487
+ """
1488
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1489
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1490
+
1491
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1492
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1493
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1494
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1495
+ inputs_embeds = (
1496
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1497
+ if inputs_embeds is not None
1498
+ else None
1499
+ )
1500
+
1501
+ outputs = self.mobilebert(
1502
+ input_ids,
1503
+ attention_mask=attention_mask,
1504
+ token_type_ids=token_type_ids,
1505
+ position_ids=position_ids,
1506
+ head_mask=head_mask,
1507
+ inputs_embeds=inputs_embeds,
1508
+ output_attentions=output_attentions,
1509
+ output_hidden_states=output_hidden_states,
1510
+ return_dict=return_dict,
1511
+ )
1512
+
1513
+ pooled_output = outputs[1]
1514
+
1515
+ pooled_output = self.dropout(pooled_output)
1516
+ logits = self.classifier(pooled_output)
1517
+ reshaped_logits = logits.view(-1, num_choices)
1518
+
1519
+ loss = None
1520
+ if labels is not None:
1521
+ loss_fct = CrossEntropyLoss()
1522
+ loss = loss_fct(reshaped_logits, labels)
1523
+
1524
+ if not return_dict:
1525
+ output = (reshaped_logits,) + outputs[2:]
1526
+ return ((loss,) + output) if loss is not None else output
1527
+
1528
+ return MultipleChoiceModelOutput(
1529
+ loss=loss,
1530
+ logits=reshaped_logits,
1531
+ hidden_states=outputs.hidden_states,
1532
+ attentions=outputs.attentions,
1533
+ )
1534
+
1535
+
1536
+ @add_start_docstrings(
1537
+ """
1538
+ MobileBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
1539
+ for Named-Entity-Recognition (NER) tasks.
1540
+ """,
1541
+ MOBILEBERT_START_DOCSTRING,
1542
+ )
1543
+ # Copied from transformers.models.bert.modeling_bert.BertForTokenClassification with Bert->MobileBert all-casing
1544
+ class MobileBertForTokenClassification(MobileBertPreTrainedModel):
1545
+ def __init__(self, config):
1546
+ super().__init__(config)
1547
+ self.num_labels = config.num_labels
1548
+
1549
+ self.mobilebert = MobileBertModel(config, add_pooling_layer=False)
1550
+ classifier_dropout = (
1551
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1552
+ )
1553
+ self.dropout = nn.Dropout(classifier_dropout)
1554
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1555
+
1556
+ # Initialize weights and apply final processing
1557
+ self.post_init()
1558
+
1559
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1560
+ @add_code_sample_docstrings(
1561
+ checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
1562
+ output_type=TokenClassifierOutput,
1563
+ config_class=_CONFIG_FOR_DOC,
1564
+ expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
1565
+ expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
1566
+ )
1567
+ def forward(
1568
+ self,
1569
+ input_ids: Optional[torch.Tensor] = None,
1570
+ attention_mask: Optional[torch.Tensor] = None,
1571
+ token_type_ids: Optional[torch.Tensor] = None,
1572
+ position_ids: Optional[torch.Tensor] = None,
1573
+ head_mask: Optional[torch.Tensor] = None,
1574
+ inputs_embeds: Optional[torch.Tensor] = None,
1575
+ labels: Optional[torch.Tensor] = None,
1576
+ output_attentions: Optional[bool] = None,
1577
+ output_hidden_states: Optional[bool] = None,
1578
+ return_dict: Optional[bool] = None,
1579
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1580
+ r"""
1581
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1582
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1583
+ """
1584
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1585
+
1586
+ outputs = self.mobilebert(
1587
+ input_ids,
1588
+ attention_mask=attention_mask,
1589
+ token_type_ids=token_type_ids,
1590
+ position_ids=position_ids,
1591
+ head_mask=head_mask,
1592
+ inputs_embeds=inputs_embeds,
1593
+ output_attentions=output_attentions,
1594
+ output_hidden_states=output_hidden_states,
1595
+ return_dict=return_dict,
1596
+ )
1597
+
1598
+ sequence_output = outputs[0]
1599
+
1600
+ sequence_output = self.dropout(sequence_output)
1601
+ logits = self.classifier(sequence_output)
1602
+
1603
+ loss = None
1604
+ if labels is not None:
1605
+ loss_fct = CrossEntropyLoss()
1606
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1607
+
1608
+ if not return_dict:
1609
+ output = (logits,) + outputs[2:]
1610
+ return ((loss,) + output) if loss is not None else output
1611
+
1612
+ return TokenClassifierOutput(
1613
+ loss=loss,
1614
+ logits=logits,
1615
+ hidden_states=outputs.hidden_states,
1616
+ attentions=outputs.attentions,
1617
+ )
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/modeling_tf_mobilebert.py ADDED
@@ -0,0 +1,1973 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ TF 2.0 MobileBERT model."""
17
+
18
+
19
+ from __future__ import annotations
20
+
21
+ import warnings
22
+ from dataclasses import dataclass
23
+ from typing import Optional, Tuple, Union
24
+
25
+ import numpy as np
26
+ import tensorflow as tf
27
+
28
+ from ...activations_tf import get_tf_activation
29
+ from ...modeling_tf_outputs import (
30
+ TFBaseModelOutput,
31
+ TFBaseModelOutputWithPooling,
32
+ TFMaskedLMOutput,
33
+ TFMultipleChoiceModelOutput,
34
+ TFNextSentencePredictorOutput,
35
+ TFQuestionAnsweringModelOutput,
36
+ TFSequenceClassifierOutput,
37
+ TFTokenClassifierOutput,
38
+ )
39
+ from ...modeling_tf_utils import (
40
+ TFMaskedLanguageModelingLoss,
41
+ TFModelInputType,
42
+ TFMultipleChoiceLoss,
43
+ TFNextSentencePredictionLoss,
44
+ TFPreTrainedModel,
45
+ TFQuestionAnsweringLoss,
46
+ TFSequenceClassificationLoss,
47
+ TFTokenClassificationLoss,
48
+ get_initializer,
49
+ keras_serializable,
50
+ unpack_inputs,
51
+ )
52
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
53
+ from ...utils import (
54
+ ModelOutput,
55
+ add_code_sample_docstrings,
56
+ add_start_docstrings,
57
+ add_start_docstrings_to_model_forward,
58
+ logging,
59
+ replace_return_docstrings,
60
+ )
61
+ from .configuration_mobilebert import MobileBertConfig
62
+
63
+
64
+ logger = logging.get_logger(__name__)
65
+
66
+ _CHECKPOINT_FOR_DOC = "google/mobilebert-uncased"
67
+ _CONFIG_FOR_DOC = "MobileBertConfig"
68
+
69
+ # TokenClassification docstring
70
+ _CHECKPOINT_FOR_TOKEN_CLASSIFICATION = "vumichien/mobilebert-finetuned-ner"
71
+ _TOKEN_CLASS_EXPECTED_OUTPUT = "['I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC']"
72
+ _TOKEN_CLASS_EXPECTED_LOSS = 0.03
73
+
74
+ # QuestionAnswering docstring
75
+ _CHECKPOINT_FOR_QA = "vumichien/mobilebert-uncased-squad-v2"
76
+ _QA_EXPECTED_OUTPUT = "'a nice puppet'"
77
+ _QA_EXPECTED_LOSS = 3.98
78
+ _QA_TARGET_START_INDEX = 12
79
+ _QA_TARGET_END_INDEX = 13
80
+
81
+ # SequenceClassification docstring
82
+ _CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "vumichien/emo-mobilebert"
83
+ _SEQ_CLASS_EXPECTED_OUTPUT = "'others'"
84
+ _SEQ_CLASS_EXPECTED_LOSS = "4.72"
85
+
86
+ TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
87
+ "google/mobilebert-uncased",
88
+ # See all MobileBERT models at https://huggingface.co/models?filter=mobilebert
89
+ ]
90
+
91
+
92
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertPreTrainingLoss
93
+ class TFMobileBertPreTrainingLoss:
94
+ """
95
+ Loss function suitable for BERT-like pretraining, that is, the task of pretraining a language model by combining
96
+ NSP + MLM. .. note:: Any label of -100 will be ignored (along with the corresponding logits) in the loss
97
+ computation.
98
+ """
99
+
100
+ def hf_compute_loss(self, labels: tf.Tensor, logits: tf.Tensor) -> tf.Tensor:
101
+ loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(
102
+ from_logits=True, reduction=tf.keras.losses.Reduction.NONE
103
+ )
104
+
105
+ # Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
106
+ unmasked_lm_losses = loss_fn(y_true=tf.nn.relu(labels["labels"]), y_pred=logits[0])
107
+ # make sure only labels that are not equal to -100
108
+ # are taken into account for the loss computation
109
+ lm_loss_mask = tf.cast(labels["labels"] != -100, dtype=unmasked_lm_losses.dtype)
110
+ masked_lm_losses = unmasked_lm_losses * lm_loss_mask
111
+ reduced_masked_lm_loss = tf.reduce_sum(masked_lm_losses) / tf.reduce_sum(lm_loss_mask)
112
+
113
+ # Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
114
+ unmasked_ns_loss = loss_fn(y_true=tf.nn.relu(labels["next_sentence_label"]), y_pred=logits[1])
115
+ ns_loss_mask = tf.cast(labels["next_sentence_label"] != -100, dtype=unmasked_ns_loss.dtype)
116
+ masked_ns_loss = unmasked_ns_loss * ns_loss_mask
117
+
118
+ reduced_masked_ns_loss = tf.reduce_sum(masked_ns_loss) / tf.reduce_sum(ns_loss_mask)
119
+
120
+ return tf.reshape(reduced_masked_lm_loss + reduced_masked_ns_loss, (1,))
121
+
122
+
123
+ class TFMobileBertIntermediate(tf.keras.layers.Layer):
124
+ def __init__(self, config, **kwargs):
125
+ super().__init__(**kwargs)
126
+
127
+ self.dense = tf.keras.layers.Dense(config.intermediate_size, name="dense")
128
+
129
+ if isinstance(config.hidden_act, str):
130
+ self.intermediate_act_fn = get_tf_activation(config.hidden_act)
131
+ else:
132
+ self.intermediate_act_fn = config.hidden_act
133
+ self.config = config
134
+
135
+ def call(self, hidden_states):
136
+ hidden_states = self.dense(hidden_states)
137
+ hidden_states = self.intermediate_act_fn(hidden_states)
138
+
139
+ return hidden_states
140
+
141
+ def build(self, input_shape=None):
142
+ if self.built:
143
+ return
144
+ self.built = True
145
+ if getattr(self, "dense", None) is not None:
146
+ with tf.name_scope(self.dense.name):
147
+ self.dense.build([None, None, self.config.true_hidden_size])
148
+
149
+
150
+ class TFLayerNorm(tf.keras.layers.LayerNormalization):
151
+ def __init__(self, feat_size, *args, **kwargs):
152
+ self.feat_size = feat_size
153
+ super().__init__(*args, **kwargs)
154
+
155
+ def build(self, input_shape=None):
156
+ super().build([None, None, self.feat_size])
157
+
158
+
159
+ class TFNoNorm(tf.keras.layers.Layer):
160
+ def __init__(self, feat_size, epsilon=None, **kwargs):
161
+ super().__init__(**kwargs)
162
+ self.feat_size = feat_size
163
+
164
+ def build(self, input_shape):
165
+ self.bias = self.add_weight("bias", shape=[self.feat_size], initializer="zeros")
166
+ self.weight = self.add_weight("weight", shape=[self.feat_size], initializer="ones")
167
+ super().build(input_shape)
168
+
169
+ def call(self, inputs: tf.Tensor):
170
+ return inputs * self.weight + self.bias
171
+
172
+
173
+ NORM2FN = {"layer_norm": TFLayerNorm, "no_norm": TFNoNorm}
174
+
175
+
176
+ class TFMobileBertEmbeddings(tf.keras.layers.Layer):
177
+ """Construct the embeddings from word, position and token_type embeddings."""
178
+
179
+ def __init__(self, config, **kwargs):
180
+ super().__init__(**kwargs)
181
+
182
+ self.trigram_input = config.trigram_input
183
+ self.embedding_size = config.embedding_size
184
+ self.config = config
185
+ self.hidden_size = config.hidden_size
186
+ self.max_position_embeddings = config.max_position_embeddings
187
+ self.initializer_range = config.initializer_range
188
+ self.embedding_transformation = tf.keras.layers.Dense(config.hidden_size, name="embedding_transformation")
189
+
190
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
191
+ # any TensorFlow checkpoint file
192
+ self.LayerNorm = NORM2FN[config.normalization_type](
193
+ config.hidden_size, epsilon=config.layer_norm_eps, name="LayerNorm"
194
+ )
195
+ self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
196
+ self.embedded_input_size = self.embedding_size * (3 if self.trigram_input else 1)
197
+
198
+ def build(self, input_shape=None):
199
+ with tf.name_scope("word_embeddings"):
200
+ self.weight = self.add_weight(
201
+ name="weight",
202
+ shape=[self.config.vocab_size, self.embedding_size],
203
+ initializer=get_initializer(initializer_range=self.initializer_range),
204
+ )
205
+
206
+ with tf.name_scope("token_type_embeddings"):
207
+ self.token_type_embeddings = self.add_weight(
208
+ name="embeddings",
209
+ shape=[self.config.type_vocab_size, self.hidden_size],
210
+ initializer=get_initializer(initializer_range=self.initializer_range),
211
+ )
212
+
213
+ with tf.name_scope("position_embeddings"):
214
+ self.position_embeddings = self.add_weight(
215
+ name="embeddings",
216
+ shape=[self.max_position_embeddings, self.hidden_size],
217
+ initializer=get_initializer(initializer_range=self.initializer_range),
218
+ )
219
+
220
+ if self.built:
221
+ return
222
+ self.built = True
223
+ if getattr(self, "embedding_transformation", None) is not None:
224
+ with tf.name_scope(self.embedding_transformation.name):
225
+ self.embedding_transformation.build([None, None, self.embedded_input_size])
226
+ if getattr(self, "LayerNorm", None) is not None:
227
+ with tf.name_scope(self.LayerNorm.name):
228
+ self.LayerNorm.build(None)
229
+
230
+ def call(self, input_ids=None, position_ids=None, token_type_ids=None, inputs_embeds=None, training=False):
231
+ """
232
+ Applies embedding based on inputs tensor.
233
+
234
+ Returns:
235
+ final_embeddings (`tf.Tensor`): output embedding tensor.
236
+ """
237
+ assert not (input_ids is None and inputs_embeds is None)
238
+
239
+ if input_ids is not None:
240
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
241
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
242
+
243
+ input_shape = shape_list(inputs_embeds)[:-1]
244
+
245
+ if token_type_ids is None:
246
+ token_type_ids = tf.fill(dims=input_shape, value=0)
247
+
248
+ if self.trigram_input:
249
+ # From the paper MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited
250
+ # Devices (https://arxiv.org/abs/2004.02984)
251
+ #
252
+ # The embedding table in BERT models accounts for a substantial proportion of model size. To compress
253
+ # the embedding layer, we reduce the embedding dimension to 128 in MobileBERT.
254
+ # Then, we apply a 1D convolution with kernel size 3 on the raw token embedding to produce a 512
255
+ # dimensional output.
256
+ inputs_embeds = tf.concat(
257
+ [
258
+ tf.pad(inputs_embeds[:, 1:], ((0, 0), (0, 1), (0, 0))),
259
+ inputs_embeds,
260
+ tf.pad(inputs_embeds[:, :-1], ((0, 0), (1, 0), (0, 0))),
261
+ ],
262
+ axis=2,
263
+ )
264
+
265
+ if self.trigram_input or self.embedding_size != self.hidden_size:
266
+ inputs_embeds = self.embedding_transformation(inputs_embeds)
267
+
268
+ if position_ids is None:
269
+ position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
270
+
271
+ position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
272
+ token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
273
+ final_embeddings = inputs_embeds + position_embeds + token_type_embeds
274
+ final_embeddings = self.LayerNorm(inputs=final_embeddings)
275
+ final_embeddings = self.dropout(inputs=final_embeddings, training=training)
276
+
277
+ return final_embeddings
278
+
279
+
280
+ class TFMobileBertSelfAttention(tf.keras.layers.Layer):
281
+ def __init__(self, config, **kwargs):
282
+ super().__init__(**kwargs)
283
+ if config.hidden_size % config.num_attention_heads != 0:
284
+ raise ValueError(
285
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
286
+ f"heads ({config.num_attention_heads}"
287
+ )
288
+
289
+ self.num_attention_heads = config.num_attention_heads
290
+ self.output_attentions = config.output_attentions
291
+ assert config.hidden_size % config.num_attention_heads == 0
292
+ self.attention_head_size = int(config.true_hidden_size / config.num_attention_heads)
293
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
294
+
295
+ self.query = tf.keras.layers.Dense(
296
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
297
+ )
298
+ self.key = tf.keras.layers.Dense(
299
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
300
+ )
301
+ self.value = tf.keras.layers.Dense(
302
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
303
+ )
304
+
305
+ self.dropout = tf.keras.layers.Dropout(config.attention_probs_dropout_prob)
306
+ self.config = config
307
+
308
+ def transpose_for_scores(self, x, batch_size):
309
+ # Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
310
+ x = tf.reshape(x, (batch_size, -1, self.num_attention_heads, self.attention_head_size))
311
+ return tf.transpose(x, perm=[0, 2, 1, 3])
312
+
313
+ def call(
314
+ self, query_tensor, key_tensor, value_tensor, attention_mask, head_mask, output_attentions, training=False
315
+ ):
316
+ batch_size = shape_list(attention_mask)[0]
317
+ mixed_query_layer = self.query(query_tensor)
318
+ mixed_key_layer = self.key(key_tensor)
319
+ mixed_value_layer = self.value(value_tensor)
320
+ query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
321
+ key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)
322
+ value_layer = self.transpose_for_scores(mixed_value_layer, batch_size)
323
+
324
+ # Take the dot product between "query" and "key" to get the raw attention scores.
325
+ attention_scores = tf.matmul(
326
+ query_layer, key_layer, transpose_b=True
327
+ ) # (batch size, num_heads, seq_len_q, seq_len_k)
328
+ dk = tf.cast(shape_list(key_layer)[-1], dtype=attention_scores.dtype) # scale attention_scores
329
+ attention_scores = attention_scores / tf.math.sqrt(dk)
330
+
331
+ if attention_mask is not None:
332
+ # Apply the attention mask is (precomputed for all layers in TFMobileBertModel call() function)
333
+ attention_mask = tf.cast(attention_mask, dtype=attention_scores.dtype)
334
+ attention_scores = attention_scores + attention_mask
335
+
336
+ # Normalize the attention scores to probabilities.
337
+ attention_probs = stable_softmax(attention_scores, axis=-1)
338
+
339
+ # This is actually dropping out entire tokens to attend to, which might
340
+ # seem a bit unusual, but is taken from the original Transformer paper.
341
+ attention_probs = self.dropout(attention_probs, training=training)
342
+
343
+ # Mask heads if we want to
344
+ if head_mask is not None:
345
+ attention_probs = attention_probs * head_mask
346
+
347
+ context_layer = tf.matmul(attention_probs, value_layer)
348
+
349
+ context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])
350
+ context_layer = tf.reshape(
351
+ context_layer, (batch_size, -1, self.all_head_size)
352
+ ) # (batch_size, seq_len_q, all_head_size)
353
+
354
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
355
+
356
+ return outputs
357
+
358
+ def build(self, input_shape=None):
359
+ if self.built:
360
+ return
361
+ self.built = True
362
+ if getattr(self, "query", None) is not None:
363
+ with tf.name_scope(self.query.name):
364
+ self.query.build([None, None, self.config.true_hidden_size])
365
+ if getattr(self, "key", None) is not None:
366
+ with tf.name_scope(self.key.name):
367
+ self.key.build([None, None, self.config.true_hidden_size])
368
+ if getattr(self, "value", None) is not None:
369
+ with tf.name_scope(self.value.name):
370
+ self.value.build(
371
+ [
372
+ None,
373
+ None,
374
+ self.config.true_hidden_size
375
+ if self.config.use_bottleneck_attention
376
+ else self.config.hidden_size,
377
+ ]
378
+ )
379
+
380
+
381
+ class TFMobileBertSelfOutput(tf.keras.layers.Layer):
382
+ def __init__(self, config, **kwargs):
383
+ super().__init__(**kwargs)
384
+ self.use_bottleneck = config.use_bottleneck
385
+ self.dense = tf.keras.layers.Dense(
386
+ config.true_hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
387
+ )
388
+ self.LayerNorm = NORM2FN[config.normalization_type](
389
+ config.true_hidden_size, epsilon=config.layer_norm_eps, name="LayerNorm"
390
+ )
391
+ if not self.use_bottleneck:
392
+ self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)
393
+ self.config = config
394
+
395
+ def call(self, hidden_states, residual_tensor, training=False):
396
+ hidden_states = self.dense(hidden_states)
397
+ if not self.use_bottleneck:
398
+ hidden_states = self.dropout(hidden_states, training=training)
399
+ hidden_states = self.LayerNorm(hidden_states + residual_tensor)
400
+ return hidden_states
401
+
402
+ def build(self, input_shape=None):
403
+ if self.built:
404
+ return
405
+ self.built = True
406
+ if getattr(self, "dense", None) is not None:
407
+ with tf.name_scope(self.dense.name):
408
+ self.dense.build([None, None, self.config.true_hidden_size])
409
+ if getattr(self, "LayerNorm", None) is not None:
410
+ with tf.name_scope(self.LayerNorm.name):
411
+ self.LayerNorm.build(None)
412
+
413
+
414
+ class TFMobileBertAttention(tf.keras.layers.Layer):
415
+ def __init__(self, config, **kwargs):
416
+ super().__init__(**kwargs)
417
+ self.self = TFMobileBertSelfAttention(config, name="self")
418
+ self.mobilebert_output = TFMobileBertSelfOutput(config, name="output")
419
+
420
+ def prune_heads(self, heads):
421
+ raise NotImplementedError
422
+
423
+ def call(
424
+ self,
425
+ query_tensor,
426
+ key_tensor,
427
+ value_tensor,
428
+ layer_input,
429
+ attention_mask,
430
+ head_mask,
431
+ output_attentions,
432
+ training=False,
433
+ ):
434
+ self_outputs = self.self(
435
+ query_tensor, key_tensor, value_tensor, attention_mask, head_mask, output_attentions, training=training
436
+ )
437
+
438
+ attention_output = self.mobilebert_output(self_outputs[0], layer_input, training=training)
439
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
440
+ return outputs
441
+
442
+ def build(self, input_shape=None):
443
+ if self.built:
444
+ return
445
+ self.built = True
446
+ if getattr(self, "self", None) is not None:
447
+ with tf.name_scope(self.self.name):
448
+ self.self.build(None)
449
+ if getattr(self, "mobilebert_output", None) is not None:
450
+ with tf.name_scope(self.mobilebert_output.name):
451
+ self.mobilebert_output.build(None)
452
+
453
+
454
+ class TFOutputBottleneck(tf.keras.layers.Layer):
455
+ def __init__(self, config, **kwargs):
456
+ super().__init__(**kwargs)
457
+ self.dense = tf.keras.layers.Dense(config.hidden_size, name="dense")
458
+ self.LayerNorm = NORM2FN[config.normalization_type](
459
+ config.hidden_size, epsilon=config.layer_norm_eps, name="LayerNorm"
460
+ )
461
+ self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)
462
+ self.config = config
463
+
464
+ def call(self, hidden_states, residual_tensor, training=False):
465
+ layer_outputs = self.dense(hidden_states)
466
+ layer_outputs = self.dropout(layer_outputs, training=training)
467
+ layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
468
+ return layer_outputs
469
+
470
+ def build(self, input_shape=None):
471
+ if self.built:
472
+ return
473
+ self.built = True
474
+ if getattr(self, "dense", None) is not None:
475
+ with tf.name_scope(self.dense.name):
476
+ self.dense.build([None, None, self.config.true_hidden_size])
477
+ if getattr(self, "LayerNorm", None) is not None:
478
+ with tf.name_scope(self.LayerNorm.name):
479
+ self.LayerNorm.build(None)
480
+
481
+
482
+ class TFMobileBertOutput(tf.keras.layers.Layer):
483
+ def __init__(self, config, **kwargs):
484
+ super().__init__(**kwargs)
485
+ self.use_bottleneck = config.use_bottleneck
486
+ self.dense = tf.keras.layers.Dense(
487
+ config.true_hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
488
+ )
489
+ self.LayerNorm = NORM2FN[config.normalization_type](
490
+ config.true_hidden_size, epsilon=config.layer_norm_eps, name="LayerNorm"
491
+ )
492
+ if not self.use_bottleneck:
493
+ self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)
494
+ else:
495
+ self.bottleneck = TFOutputBottleneck(config, name="bottleneck")
496
+ self.config = config
497
+
498
+ def call(self, hidden_states, residual_tensor_1, residual_tensor_2, training=False):
499
+ hidden_states = self.dense(hidden_states)
500
+ if not self.use_bottleneck:
501
+ hidden_states = self.dropout(hidden_states, training=training)
502
+ hidden_states = self.LayerNorm(hidden_states + residual_tensor_1)
503
+ else:
504
+ hidden_states = self.LayerNorm(hidden_states + residual_tensor_1)
505
+ hidden_states = self.bottleneck(hidden_states, residual_tensor_2)
506
+ return hidden_states
507
+
508
+ def build(self, input_shape=None):
509
+ if self.built:
510
+ return
511
+ self.built = True
512
+ if getattr(self, "dense", None) is not None:
513
+ with tf.name_scope(self.dense.name):
514
+ self.dense.build([None, None, self.config.intermediate_size])
515
+ if getattr(self, "LayerNorm", None) is not None:
516
+ with tf.name_scope(self.LayerNorm.name):
517
+ self.LayerNorm.build(None)
518
+ if getattr(self, "bottleneck", None) is not None:
519
+ with tf.name_scope(self.bottleneck.name):
520
+ self.bottleneck.build(None)
521
+
522
+
523
+ class TFBottleneckLayer(tf.keras.layers.Layer):
524
+ def __init__(self, config, **kwargs):
525
+ super().__init__(**kwargs)
526
+ self.dense = tf.keras.layers.Dense(config.intra_bottleneck_size, name="dense")
527
+ self.LayerNorm = NORM2FN[config.normalization_type](
528
+ config.intra_bottleneck_size, epsilon=config.layer_norm_eps, name="LayerNorm"
529
+ )
530
+ self.config = config
531
+
532
+ def call(self, inputs):
533
+ hidden_states = self.dense(inputs)
534
+ hidden_states = self.LayerNorm(hidden_states)
535
+ return hidden_states
536
+
537
+ def build(self, input_shape=None):
538
+ if self.built:
539
+ return
540
+ self.built = True
541
+ if getattr(self, "dense", None) is not None:
542
+ with tf.name_scope(self.dense.name):
543
+ self.dense.build([None, None, self.config.hidden_size])
544
+ if getattr(self, "LayerNorm", None) is not None:
545
+ with tf.name_scope(self.LayerNorm.name):
546
+ self.LayerNorm.build(None)
547
+
548
+
549
+ class TFBottleneck(tf.keras.layers.Layer):
550
+ def __init__(self, config, **kwargs):
551
+ super().__init__(**kwargs)
552
+ self.key_query_shared_bottleneck = config.key_query_shared_bottleneck
553
+ self.use_bottleneck_attention = config.use_bottleneck_attention
554
+ self.bottleneck_input = TFBottleneckLayer(config, name="input")
555
+ if self.key_query_shared_bottleneck:
556
+ self.attention = TFBottleneckLayer(config, name="attention")
557
+
558
+ def call(self, hidden_states):
559
+ # This method can return three different tuples of values. These different values make use of bottlenecks,
560
+ # which are linear layers used to project the hidden states to a lower-dimensional vector, reducing memory
561
+ # usage. These linear layer have weights that are learned during training.
562
+ #
563
+ # If `config.use_bottleneck_attention`, it will return the result of the bottleneck layer four times for the
564
+ # key, query, value, and "layer input" to be used by the attention layer.
565
+ # This bottleneck is used to project the hidden. This last layer input will be used as a residual tensor
566
+ # in the attention self output, after the attention scores have been computed.
567
+ #
568
+ # If not `config.use_bottleneck_attention` and `config.key_query_shared_bottleneck`, this will return
569
+ # four values, three of which have been passed through a bottleneck: the query and key, passed through the same
570
+ # bottleneck, and the residual layer to be applied in the attention self output, through another bottleneck.
571
+ #
572
+ # Finally, in the last case, the values for the query, key and values are the hidden states without bottleneck,
573
+ # and the residual layer will be this value passed through a bottleneck.
574
+
575
+ bottlenecked_hidden_states = self.bottleneck_input(hidden_states)
576
+ if self.use_bottleneck_attention:
577
+ return (bottlenecked_hidden_states,) * 4
578
+ elif self.key_query_shared_bottleneck:
579
+ shared_attention_input = self.attention(hidden_states)
580
+ return (shared_attention_input, shared_attention_input, hidden_states, bottlenecked_hidden_states)
581
+ else:
582
+ return (hidden_states, hidden_states, hidden_states, bottlenecked_hidden_states)
583
+
584
+ def build(self, input_shape=None):
585
+ if self.built:
586
+ return
587
+ self.built = True
588
+ if getattr(self, "bottleneck_input", None) is not None:
589
+ with tf.name_scope(self.bottleneck_input.name):
590
+ self.bottleneck_input.build(None)
591
+ if getattr(self, "attention", None) is not None:
592
+ with tf.name_scope(self.attention.name):
593
+ self.attention.build(None)
594
+
595
+
596
+ class TFFFNOutput(tf.keras.layers.Layer):
597
+ def __init__(self, config, **kwargs):
598
+ super().__init__(**kwargs)
599
+ self.dense = tf.keras.layers.Dense(config.true_hidden_size, name="dense")
600
+ self.LayerNorm = NORM2FN[config.normalization_type](
601
+ config.true_hidden_size, epsilon=config.layer_norm_eps, name="LayerNorm"
602
+ )
603
+ self.config = config
604
+
605
+ def call(self, hidden_states, residual_tensor):
606
+ hidden_states = self.dense(hidden_states)
607
+ hidden_states = self.LayerNorm(hidden_states + residual_tensor)
608
+ return hidden_states
609
+
610
+ def build(self, input_shape=None):
611
+ if self.built:
612
+ return
613
+ self.built = True
614
+ if getattr(self, "dense", None) is not None:
615
+ with tf.name_scope(self.dense.name):
616
+ self.dense.build([None, None, self.config.intermediate_size])
617
+ if getattr(self, "LayerNorm", None) is not None:
618
+ with tf.name_scope(self.LayerNorm.name):
619
+ self.LayerNorm.build(None)
620
+
621
+
622
+ class TFFFNLayer(tf.keras.layers.Layer):
623
+ def __init__(self, config, **kwargs):
624
+ super().__init__(**kwargs)
625
+ self.intermediate = TFMobileBertIntermediate(config, name="intermediate")
626
+ self.mobilebert_output = TFFFNOutput(config, name="output")
627
+
628
+ def call(self, hidden_states):
629
+ intermediate_output = self.intermediate(hidden_states)
630
+ layer_outputs = self.mobilebert_output(intermediate_output, hidden_states)
631
+ return layer_outputs
632
+
633
+ def build(self, input_shape=None):
634
+ if self.built:
635
+ return
636
+ self.built = True
637
+ if getattr(self, "intermediate", None) is not None:
638
+ with tf.name_scope(self.intermediate.name):
639
+ self.intermediate.build(None)
640
+ if getattr(self, "mobilebert_output", None) is not None:
641
+ with tf.name_scope(self.mobilebert_output.name):
642
+ self.mobilebert_output.build(None)
643
+
644
+
645
+ class TFMobileBertLayer(tf.keras.layers.Layer):
646
+ def __init__(self, config, **kwargs):
647
+ super().__init__(**kwargs)
648
+ self.use_bottleneck = config.use_bottleneck
649
+ self.num_feedforward_networks = config.num_feedforward_networks
650
+ self.attention = TFMobileBertAttention(config, name="attention")
651
+ self.intermediate = TFMobileBertIntermediate(config, name="intermediate")
652
+ self.mobilebert_output = TFMobileBertOutput(config, name="output")
653
+
654
+ if self.use_bottleneck:
655
+ self.bottleneck = TFBottleneck(config, name="bottleneck")
656
+ if config.num_feedforward_networks > 1:
657
+ self.ffn = [TFFFNLayer(config, name=f"ffn.{i}") for i in range(config.num_feedforward_networks - 1)]
658
+
659
+ def call(self, hidden_states, attention_mask, head_mask, output_attentions, training=False):
660
+ if self.use_bottleneck:
661
+ query_tensor, key_tensor, value_tensor, layer_input = self.bottleneck(hidden_states)
662
+ else:
663
+ query_tensor, key_tensor, value_tensor, layer_input = [hidden_states] * 4
664
+
665
+ attention_outputs = self.attention(
666
+ query_tensor,
667
+ key_tensor,
668
+ value_tensor,
669
+ layer_input,
670
+ attention_mask,
671
+ head_mask,
672
+ output_attentions,
673
+ training=training,
674
+ )
675
+
676
+ attention_output = attention_outputs[0]
677
+ s = (attention_output,)
678
+
679
+ if self.num_feedforward_networks != 1:
680
+ for i, ffn_module in enumerate(self.ffn):
681
+ attention_output = ffn_module(attention_output)
682
+ s += (attention_output,)
683
+
684
+ intermediate_output = self.intermediate(attention_output)
685
+ layer_output = self.mobilebert_output(intermediate_output, attention_output, hidden_states, training=training)
686
+
687
+ outputs = (
688
+ (layer_output,)
689
+ + attention_outputs[1:]
690
+ + (
691
+ tf.constant(0),
692
+ query_tensor,
693
+ key_tensor,
694
+ value_tensor,
695
+ layer_input,
696
+ attention_output,
697
+ intermediate_output,
698
+ )
699
+ + s
700
+ ) # add attentions if we output them
701
+
702
+ return outputs
703
+
704
+ def build(self, input_shape=None):
705
+ if self.built:
706
+ return
707
+ self.built = True
708
+ if getattr(self, "attention", None) is not None:
709
+ with tf.name_scope(self.attention.name):
710
+ self.attention.build(None)
711
+ if getattr(self, "intermediate", None) is not None:
712
+ with tf.name_scope(self.intermediate.name):
713
+ self.intermediate.build(None)
714
+ if getattr(self, "mobilebert_output", None) is not None:
715
+ with tf.name_scope(self.mobilebert_output.name):
716
+ self.mobilebert_output.build(None)
717
+ if getattr(self, "bottleneck", None) is not None:
718
+ with tf.name_scope(self.bottleneck.name):
719
+ self.bottleneck.build(None)
720
+ if getattr(self, "ffn", None) is not None:
721
+ for layer in self.ffn:
722
+ with tf.name_scope(layer.name):
723
+ layer.build(None)
724
+
725
+
726
+ class TFMobileBertEncoder(tf.keras.layers.Layer):
727
+ def __init__(self, config, **kwargs):
728
+ super().__init__(**kwargs)
729
+ self.output_attentions = config.output_attentions
730
+ self.output_hidden_states = config.output_hidden_states
731
+ self.layer = [TFMobileBertLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
732
+
733
+ def call(
734
+ self,
735
+ hidden_states,
736
+ attention_mask,
737
+ head_mask,
738
+ output_attentions,
739
+ output_hidden_states,
740
+ return_dict,
741
+ training=False,
742
+ ):
743
+ all_hidden_states = () if output_hidden_states else None
744
+ all_attentions = () if output_attentions else None
745
+ for i, layer_module in enumerate(self.layer):
746
+ if output_hidden_states:
747
+ all_hidden_states = all_hidden_states + (hidden_states,)
748
+
749
+ layer_outputs = layer_module(
750
+ hidden_states, attention_mask, head_mask[i], output_attentions, training=training
751
+ )
752
+
753
+ hidden_states = layer_outputs[0]
754
+
755
+ if output_attentions:
756
+ all_attentions = all_attentions + (layer_outputs[1],)
757
+
758
+ # Add last layer
759
+ if output_hidden_states:
760
+ all_hidden_states = all_hidden_states + (hidden_states,)
761
+
762
+ if not return_dict:
763
+ return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
764
+ return TFBaseModelOutput(
765
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
766
+ )
767
+
768
+ def build(self, input_shape=None):
769
+ if self.built:
770
+ return
771
+ self.built = True
772
+ if getattr(self, "layer", None) is not None:
773
+ for layer in self.layer:
774
+ with tf.name_scope(layer.name):
775
+ layer.build(None)
776
+
777
+
778
+ class TFMobileBertPooler(tf.keras.layers.Layer):
779
+ def __init__(self, config, **kwargs):
780
+ super().__init__(**kwargs)
781
+ self.do_activate = config.classifier_activation
782
+ if self.do_activate:
783
+ self.dense = tf.keras.layers.Dense(
784
+ config.hidden_size,
785
+ kernel_initializer=get_initializer(config.initializer_range),
786
+ activation="tanh",
787
+ name="dense",
788
+ )
789
+ self.config = config
790
+
791
+ def call(self, hidden_states):
792
+ # We "pool" the model by simply taking the hidden state corresponding
793
+ # to the first token.
794
+ first_token_tensor = hidden_states[:, 0]
795
+ if not self.do_activate:
796
+ return first_token_tensor
797
+ else:
798
+ pooled_output = self.dense(first_token_tensor)
799
+ return pooled_output
800
+
801
+ def build(self, input_shape=None):
802
+ if self.built:
803
+ return
804
+ self.built = True
805
+ if getattr(self, "dense", None) is not None:
806
+ with tf.name_scope(self.dense.name):
807
+ self.dense.build([None, None, self.config.hidden_size])
808
+
809
+
810
+ class TFMobileBertPredictionHeadTransform(tf.keras.layers.Layer):
811
+ def __init__(self, config, **kwargs):
812
+ super().__init__(**kwargs)
813
+ self.dense = tf.keras.layers.Dense(
814
+ config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
815
+ )
816
+ if isinstance(config.hidden_act, str):
817
+ self.transform_act_fn = get_tf_activation(config.hidden_act)
818
+ else:
819
+ self.transform_act_fn = config.hidden_act
820
+ self.LayerNorm = NORM2FN["layer_norm"](config.hidden_size, epsilon=config.layer_norm_eps, name="LayerNorm")
821
+ self.config = config
822
+
823
+ def call(self, hidden_states):
824
+ hidden_states = self.dense(hidden_states)
825
+ hidden_states = self.transform_act_fn(hidden_states)
826
+ hidden_states = self.LayerNorm(hidden_states)
827
+ return hidden_states
828
+
829
+ def build(self, input_shape=None):
830
+ if self.built:
831
+ return
832
+ self.built = True
833
+ if getattr(self, "dense", None) is not None:
834
+ with tf.name_scope(self.dense.name):
835
+ self.dense.build([None, None, self.config.hidden_size])
836
+ if getattr(self, "LayerNorm", None) is not None:
837
+ with tf.name_scope(self.LayerNorm.name):
838
+ self.LayerNorm.build(None)
839
+
840
+
841
+ class TFMobileBertLMPredictionHead(tf.keras.layers.Layer):
842
+ def __init__(self, config, **kwargs):
843
+ super().__init__(**kwargs)
844
+ self.transform = TFMobileBertPredictionHeadTransform(config, name="transform")
845
+ self.config = config
846
+
847
+ def build(self, input_shape=None):
848
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
849
+ self.dense = self.add_weight(
850
+ shape=(self.config.hidden_size - self.config.embedding_size, self.config.vocab_size),
851
+ initializer="zeros",
852
+ trainable=True,
853
+ name="dense/weight",
854
+ )
855
+ self.decoder = self.add_weight(
856
+ shape=(self.config.vocab_size, self.config.embedding_size),
857
+ initializer="zeros",
858
+ trainable=True,
859
+ name="decoder/weight",
860
+ )
861
+
862
+ if self.built:
863
+ return
864
+ self.built = True
865
+ if getattr(self, "transform", None) is not None:
866
+ with tf.name_scope(self.transform.name):
867
+ self.transform.build(None)
868
+
869
+ def get_output_embeddings(self):
870
+ return self
871
+
872
+ def set_output_embeddings(self, value):
873
+ self.decoder = value
874
+ self.config.vocab_size = shape_list(value)[0]
875
+
876
+ def get_bias(self):
877
+ return {"bias": self.bias}
878
+
879
+ def set_bias(self, value):
880
+ self.bias = value["bias"]
881
+ self.config.vocab_size = shape_list(value["bias"])[0]
882
+
883
+ def call(self, hidden_states):
884
+ hidden_states = self.transform(hidden_states)
885
+ hidden_states = tf.matmul(hidden_states, tf.concat([tf.transpose(self.decoder), self.dense], axis=0))
886
+ hidden_states = hidden_states + self.bias
887
+ return hidden_states
888
+
889
+
890
+ class TFMobileBertMLMHead(tf.keras.layers.Layer):
891
+ def __init__(self, config, **kwargs):
892
+ super().__init__(**kwargs)
893
+ self.predictions = TFMobileBertLMPredictionHead(config, name="predictions")
894
+
895
+ def call(self, sequence_output):
896
+ prediction_scores = self.predictions(sequence_output)
897
+ return prediction_scores
898
+
899
+ def build(self, input_shape=None):
900
+ if self.built:
901
+ return
902
+ self.built = True
903
+ if getattr(self, "predictions", None) is not None:
904
+ with tf.name_scope(self.predictions.name):
905
+ self.predictions.build(None)
906
+
907
+
908
+ @keras_serializable
909
+ class TFMobileBertMainLayer(tf.keras.layers.Layer):
910
+ config_class = MobileBertConfig
911
+
912
+ def __init__(self, config, add_pooling_layer=True, **kwargs):
913
+ super().__init__(**kwargs)
914
+
915
+ self.config = config
916
+ self.num_hidden_layers = config.num_hidden_layers
917
+ self.output_attentions = config.output_attentions
918
+ self.output_hidden_states = config.output_hidden_states
919
+ self.return_dict = config.use_return_dict
920
+
921
+ self.embeddings = TFMobileBertEmbeddings(config, name="embeddings")
922
+ self.encoder = TFMobileBertEncoder(config, name="encoder")
923
+ self.pooler = TFMobileBertPooler(config, name="pooler") if add_pooling_layer else None
924
+
925
+ def get_input_embeddings(self):
926
+ return self.embeddings
927
+
928
+ def set_input_embeddings(self, value):
929
+ self.embeddings.weight = value
930
+ self.embeddings.vocab_size = shape_list(value)[0]
931
+
932
+ def _prune_heads(self, heads_to_prune):
933
+ """
934
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
935
+ class PreTrainedModel
936
+ """
937
+ raise NotImplementedError
938
+
939
+ @unpack_inputs
940
+ def call(
941
+ self,
942
+ input_ids=None,
943
+ attention_mask=None,
944
+ token_type_ids=None,
945
+ position_ids=None,
946
+ head_mask=None,
947
+ inputs_embeds=None,
948
+ output_attentions=None,
949
+ output_hidden_states=None,
950
+ return_dict=None,
951
+ training=False,
952
+ ):
953
+ if input_ids is not None and inputs_embeds is not None:
954
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
955
+ elif input_ids is not None:
956
+ input_shape = shape_list(input_ids)
957
+ elif inputs_embeds is not None:
958
+ input_shape = shape_list(inputs_embeds)[:-1]
959
+ else:
960
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
961
+
962
+ if attention_mask is None:
963
+ attention_mask = tf.fill(input_shape, 1)
964
+
965
+ if token_type_ids is None:
966
+ token_type_ids = tf.fill(input_shape, 0)
967
+
968
+ embedding_output = self.embeddings(input_ids, position_ids, token_type_ids, inputs_embeds, training=training)
969
+
970
+ # We create a 3D attention mask from a 2D tensor mask.
971
+ # Sizes are [batch_size, 1, 1, to_seq_length]
972
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
973
+ # this attention mask is more simple than the triangular masking of causal attention
974
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
975
+ extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))
976
+
977
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
978
+ # masked positions, this operation will create a tensor which is 0.0 for
979
+ # positions we want to attend and -10000.0 for masked positions.
980
+ # Since we are adding it to the raw scores before the softmax, this is
981
+ # effectively the same as removing these entirely.
982
+ extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)
983
+ one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
984
+ ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
985
+ extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
986
+
987
+ # Prepare head mask if needed
988
+ # 1.0 in head_mask indicate we keep the head
989
+ # attention_probs has shape bsz x n_heads x N x N
990
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
991
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
992
+ if head_mask is not None:
993
+ raise NotImplementedError
994
+ else:
995
+ head_mask = [None] * self.num_hidden_layers
996
+
997
+ encoder_outputs = self.encoder(
998
+ embedding_output,
999
+ extended_attention_mask,
1000
+ head_mask,
1001
+ output_attentions,
1002
+ output_hidden_states,
1003
+ return_dict,
1004
+ training=training,
1005
+ )
1006
+
1007
+ sequence_output = encoder_outputs[0]
1008
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1009
+
1010
+ if not return_dict:
1011
+ return (
1012
+ sequence_output,
1013
+ pooled_output,
1014
+ ) + encoder_outputs[1:]
1015
+
1016
+ return TFBaseModelOutputWithPooling(
1017
+ last_hidden_state=sequence_output,
1018
+ pooler_output=pooled_output,
1019
+ hidden_states=encoder_outputs.hidden_states,
1020
+ attentions=encoder_outputs.attentions,
1021
+ )
1022
+
1023
+ def build(self, input_shape=None):
1024
+ if self.built:
1025
+ return
1026
+ self.built = True
1027
+ if getattr(self, "embeddings", None) is not None:
1028
+ with tf.name_scope(self.embeddings.name):
1029
+ self.embeddings.build(None)
1030
+ if getattr(self, "encoder", None) is not None:
1031
+ with tf.name_scope(self.encoder.name):
1032
+ self.encoder.build(None)
1033
+ if getattr(self, "pooler", None) is not None:
1034
+ with tf.name_scope(self.pooler.name):
1035
+ self.pooler.build(None)
1036
+
1037
+
1038
+ class TFMobileBertPreTrainedModel(TFPreTrainedModel):
1039
+ """
1040
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1041
+ models.
1042
+ """
1043
+
1044
+ config_class = MobileBertConfig
1045
+ base_model_prefix = "mobilebert"
1046
+
1047
+
1048
+ @dataclass
1049
+ class TFMobileBertForPreTrainingOutput(ModelOutput):
1050
+ """
1051
+ Output type of [`TFMobileBertForPreTraining`].
1052
+
1053
+ Args:
1054
+ prediction_logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
1055
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
1056
+ seq_relationship_logits (`tf.Tensor` of shape `(batch_size, 2)`):
1057
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
1058
+ before SoftMax).
1059
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1060
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
1061
+ `(batch_size, sequence_length, hidden_size)`.
1062
+
1063
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
1064
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
1065
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
1066
+ sequence_length)`.
1067
+
1068
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
1069
+ heads.
1070
+ """
1071
+
1072
+ loss: tf.Tensor | None = None
1073
+ prediction_logits: tf.Tensor = None
1074
+ seq_relationship_logits: tf.Tensor = None
1075
+ hidden_states: Tuple[tf.Tensor] | None = None
1076
+ attentions: Tuple[tf.Tensor] | None = None
1077
+
1078
+
1079
+ MOBILEBERT_START_DOCSTRING = r"""
1080
+
1081
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
1082
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1083
+ etc.)
1084
+
1085
+ This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
1086
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
1087
+ behavior.
1088
+
1089
+ <Tip>
1090
+
1091
+ TensorFlow models and layers in `transformers` accept two formats as input:
1092
+
1093
+ - having all inputs as keyword arguments (like PyTorch models), or
1094
+ - having all inputs as a list, tuple or dict in the first positional argument.
1095
+
1096
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
1097
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
1098
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
1099
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
1100
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
1101
+ positional argument:
1102
+
1103
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
1104
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
1105
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
1106
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
1107
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
1108
+
1109
+ Note that when creating models and layers with
1110
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
1111
+ about any of this, as you can just pass inputs like you would to any other Python function!
1112
+
1113
+ </Tip>
1114
+
1115
+ Parameters:
1116
+ config ([`MobileBertConfig`]): Model configuration class with all the parameters of the model.
1117
+ Initializing with a config file does not load the weights associated with the model, only the
1118
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1119
+ """
1120
+
1121
+ MOBILEBERT_INPUTS_DOCSTRING = r"""
1122
+ Args:
1123
+ input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
1124
+ Indices of input sequence tokens in the vocabulary.
1125
+
1126
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
1127
+ [`PreTrainedTokenizer.encode`] for details.
1128
+
1129
+ [What are input IDs?](../glossary#input-ids)
1130
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
1131
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1132
+
1133
+ - 1 for tokens that are **not masked**,
1134
+ - 0 for tokens that are **masked**.
1135
+
1136
+ [What are attention masks?](../glossary#attention-mask)
1137
+ token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
1138
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1139
+ 1]`:
1140
+
1141
+ - 0 corresponds to a *sentence A* token,
1142
+ - 1 corresponds to a *sentence B* token.
1143
+
1144
+ [What are token type IDs?](../glossary#token-type-ids)
1145
+ position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
1146
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1147
+ config.max_position_embeddings - 1]`.
1148
+
1149
+ [What are position IDs?](../glossary#position-ids)
1150
+ head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1151
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
1152
+
1153
+ - 1 indicates the head is **not masked**,
1154
+ - 0 indicates the head is **masked**.
1155
+
1156
+ inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
1157
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1158
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1159
+ model's internal embedding lookup matrix.
1160
+ output_attentions (`bool`, *optional*):
1161
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1162
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
1163
+ config will be used instead.
1164
+ output_hidden_states (`bool`, *optional*):
1165
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1166
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
1167
+ used instead.
1168
+ return_dict (`bool`, *optional*):
1169
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
1170
+ eager mode, in graph mode the value will always be set to True.
1171
+ training (`bool`, *optional*, defaults to `False`):
1172
+ Whether or not to use the model in training mode (some modules like dropout modules have different
1173
+ behaviors between training and evaluation).
1174
+ """
1175
+
1176
+
1177
+ @add_start_docstrings(
1178
+ "The bare MobileBert Model transformer outputting raw hidden-states without any specific head on top.",
1179
+ MOBILEBERT_START_DOCSTRING,
1180
+ )
1181
+ class TFMobileBertModel(TFMobileBertPreTrainedModel):
1182
+ def __init__(self, config, *inputs, **kwargs):
1183
+ super().__init__(config, *inputs, **kwargs)
1184
+ self.mobilebert = TFMobileBertMainLayer(config, name="mobilebert")
1185
+
1186
+ @unpack_inputs
1187
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1188
+ @add_code_sample_docstrings(
1189
+ checkpoint=_CHECKPOINT_FOR_DOC,
1190
+ output_type=TFBaseModelOutputWithPooling,
1191
+ config_class=_CONFIG_FOR_DOC,
1192
+ )
1193
+ def call(
1194
+ self,
1195
+ input_ids: TFModelInputType | None = None,
1196
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1197
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1198
+ position_ids: np.ndarray | tf.Tensor | None = None,
1199
+ head_mask: np.ndarray | tf.Tensor | None = None,
1200
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1201
+ output_attentions: Optional[bool] = None,
1202
+ output_hidden_states: Optional[bool] = None,
1203
+ return_dict: Optional[bool] = None,
1204
+ training: Optional[bool] = False,
1205
+ ) -> Union[Tuple, TFBaseModelOutputWithPooling]:
1206
+ outputs = self.mobilebert(
1207
+ input_ids=input_ids,
1208
+ attention_mask=attention_mask,
1209
+ token_type_ids=token_type_ids,
1210
+ position_ids=position_ids,
1211
+ head_mask=head_mask,
1212
+ inputs_embeds=inputs_embeds,
1213
+ output_attentions=output_attentions,
1214
+ output_hidden_states=output_hidden_states,
1215
+ return_dict=return_dict,
1216
+ training=training,
1217
+ )
1218
+
1219
+ return outputs
1220
+
1221
+ def build(self, input_shape=None):
1222
+ if self.built:
1223
+ return
1224
+ self.built = True
1225
+ if getattr(self, "mobilebert", None) is not None:
1226
+ with tf.name_scope(self.mobilebert.name):
1227
+ self.mobilebert.build(None)
1228
+
1229
+
1230
+ @add_start_docstrings(
1231
+ """
1232
+ MobileBert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
1233
+ `next sentence prediction (classification)` head.
1234
+ """,
1235
+ MOBILEBERT_START_DOCSTRING,
1236
+ )
1237
+ class TFMobileBertForPreTraining(TFMobileBertPreTrainedModel, TFMobileBertPreTrainingLoss):
1238
+ def __init__(self, config, *inputs, **kwargs):
1239
+ super().__init__(config, *inputs, **kwargs)
1240
+ self.mobilebert = TFMobileBertMainLayer(config, name="mobilebert")
1241
+ self.predictions = TFMobileBertMLMHead(config, name="predictions___cls")
1242
+ self.seq_relationship = TFMobileBertOnlyNSPHead(config, name="seq_relationship___cls")
1243
+
1244
+ def get_lm_head(self):
1245
+ return self.predictions.predictions
1246
+
1247
+ def get_prefix_bias_name(self):
1248
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
1249
+ return self.name + "/" + self.predictions.name + "/" + self.predictions.predictions.name
1250
+
1251
+ @unpack_inputs
1252
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1253
+ @replace_return_docstrings(output_type=TFMobileBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1254
+ def call(
1255
+ self,
1256
+ input_ids: TFModelInputType | None = None,
1257
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1258
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1259
+ position_ids: np.ndarray | tf.Tensor | None = None,
1260
+ head_mask: np.ndarray | tf.Tensor | None = None,
1261
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1262
+ output_attentions: Optional[bool] = None,
1263
+ output_hidden_states: Optional[bool] = None,
1264
+ return_dict: Optional[bool] = None,
1265
+ labels: np.ndarray | tf.Tensor | None = None,
1266
+ next_sentence_label: np.ndarray | tf.Tensor | None = None,
1267
+ training: Optional[bool] = False,
1268
+ ) -> Union[Tuple, TFMobileBertForPreTrainingOutput]:
1269
+ r"""
1270
+ Return:
1271
+
1272
+ Examples:
1273
+
1274
+ ```python
1275
+ >>> import tensorflow as tf
1276
+ >>> from transformers import AutoTokenizer, TFMobileBertForPreTraining
1277
+
1278
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mobilebert-uncased")
1279
+ >>> model = TFMobileBertForPreTraining.from_pretrained("google/mobilebert-uncased")
1280
+ >>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute"))[None, :] # Batch size 1
1281
+ >>> outputs = model(input_ids)
1282
+ >>> prediction_scores, seq_relationship_scores = outputs[:2]
1283
+ ```"""
1284
+ outputs = self.mobilebert(
1285
+ input_ids,
1286
+ attention_mask=attention_mask,
1287
+ token_type_ids=token_type_ids,
1288
+ position_ids=position_ids,
1289
+ head_mask=head_mask,
1290
+ inputs_embeds=inputs_embeds,
1291
+ output_attentions=output_attentions,
1292
+ output_hidden_states=output_hidden_states,
1293
+ return_dict=return_dict,
1294
+ training=training,
1295
+ )
1296
+
1297
+ sequence_output, pooled_output = outputs[:2]
1298
+ prediction_scores = self.predictions(sequence_output)
1299
+ seq_relationship_score = self.seq_relationship(pooled_output)
1300
+
1301
+ total_loss = None
1302
+ if labels is not None and next_sentence_label is not None:
1303
+ d_labels = {"labels": labels}
1304
+ d_labels["next_sentence_label"] = next_sentence_label
1305
+ total_loss = self.hf_compute_loss(labels=d_labels, logits=(prediction_scores, seq_relationship_score))
1306
+
1307
+ if not return_dict:
1308
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1309
+ return ((total_loss,) + output) if total_loss is not None else output
1310
+
1311
+ return TFMobileBertForPreTrainingOutput(
1312
+ loss=total_loss,
1313
+ prediction_logits=prediction_scores,
1314
+ seq_relationship_logits=seq_relationship_score,
1315
+ hidden_states=outputs.hidden_states,
1316
+ attentions=outputs.attentions,
1317
+ )
1318
+
1319
+ def build(self, input_shape=None):
1320
+ if self.built:
1321
+ return
1322
+ self.built = True
1323
+ if getattr(self, "mobilebert", None) is not None:
1324
+ with tf.name_scope(self.mobilebert.name):
1325
+ self.mobilebert.build(None)
1326
+ if getattr(self, "predictions", None) is not None:
1327
+ with tf.name_scope(self.predictions.name):
1328
+ self.predictions.build(None)
1329
+ if getattr(self, "seq_relationship", None) is not None:
1330
+ with tf.name_scope(self.seq_relationship.name):
1331
+ self.seq_relationship.build(None)
1332
+
1333
+ def tf_to_pt_weight_rename(self, tf_weight):
1334
+ if tf_weight == "cls.predictions.decoder.weight":
1335
+ return tf_weight, "mobilebert.embeddings.word_embeddings.weight"
1336
+ else:
1337
+ return (tf_weight,)
1338
+
1339
+
1340
+ @add_start_docstrings("""MobileBert Model with a `language modeling` head on top.""", MOBILEBERT_START_DOCSTRING)
1341
+ class TFMobileBertForMaskedLM(TFMobileBertPreTrainedModel, TFMaskedLanguageModelingLoss):
1342
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1343
+ _keys_to_ignore_on_load_unexpected = [
1344
+ r"pooler",
1345
+ r"seq_relationship___cls",
1346
+ r"cls.seq_relationship",
1347
+ ]
1348
+
1349
+ def __init__(self, config, *inputs, **kwargs):
1350
+ super().__init__(config, *inputs, **kwargs)
1351
+
1352
+ self.mobilebert = TFMobileBertMainLayer(config, add_pooling_layer=False, name="mobilebert")
1353
+ self.predictions = TFMobileBertMLMHead(config, name="predictions___cls")
1354
+
1355
+ def get_lm_head(self):
1356
+ return self.predictions.predictions
1357
+
1358
+ def get_prefix_bias_name(self):
1359
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
1360
+ return self.name + "/" + self.mlm.name + "/" + self.mlm.predictions.name
1361
+
1362
+ @unpack_inputs
1363
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1364
+ @add_code_sample_docstrings(
1365
+ checkpoint=_CHECKPOINT_FOR_DOC,
1366
+ output_type=TFMaskedLMOutput,
1367
+ config_class=_CONFIG_FOR_DOC,
1368
+ expected_output="'paris'",
1369
+ expected_loss=0.57,
1370
+ )
1371
+ def call(
1372
+ self,
1373
+ input_ids: TFModelInputType | None = None,
1374
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1375
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1376
+ position_ids: np.ndarray | tf.Tensor | None = None,
1377
+ head_mask: np.ndarray | tf.Tensor | None = None,
1378
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1379
+ output_attentions: Optional[bool] = None,
1380
+ output_hidden_states: Optional[bool] = None,
1381
+ return_dict: Optional[bool] = None,
1382
+ labels: np.ndarray | tf.Tensor | None = None,
1383
+ training: Optional[bool] = False,
1384
+ ) -> Union[Tuple, TFMaskedLMOutput]:
1385
+ r"""
1386
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1387
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1388
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1389
+ loss is only computed for the tokens with labels
1390
+ """
1391
+ outputs = self.mobilebert(
1392
+ input_ids,
1393
+ attention_mask=attention_mask,
1394
+ token_type_ids=token_type_ids,
1395
+ position_ids=position_ids,
1396
+ head_mask=head_mask,
1397
+ inputs_embeds=inputs_embeds,
1398
+ output_attentions=output_attentions,
1399
+ output_hidden_states=output_hidden_states,
1400
+ return_dict=return_dict,
1401
+ training=training,
1402
+ )
1403
+ sequence_output = outputs[0]
1404
+ prediction_scores = self.predictions(sequence_output, training=training)
1405
+
1406
+ loss = None if labels is None else self.hf_compute_loss(labels, prediction_scores)
1407
+
1408
+ if not return_dict:
1409
+ output = (prediction_scores,) + outputs[2:]
1410
+ return ((loss,) + output) if loss is not None else output
1411
+
1412
+ return TFMaskedLMOutput(
1413
+ loss=loss,
1414
+ logits=prediction_scores,
1415
+ hidden_states=outputs.hidden_states,
1416
+ attentions=outputs.attentions,
1417
+ )
1418
+
1419
+ def build(self, input_shape=None):
1420
+ if self.built:
1421
+ return
1422
+ self.built = True
1423
+ if getattr(self, "mobilebert", None) is not None:
1424
+ with tf.name_scope(self.mobilebert.name):
1425
+ self.mobilebert.build(None)
1426
+ if getattr(self, "predictions", None) is not None:
1427
+ with tf.name_scope(self.predictions.name):
1428
+ self.predictions.build(None)
1429
+
1430
+ def tf_to_pt_weight_rename(self, tf_weight):
1431
+ if tf_weight == "cls.predictions.decoder.weight":
1432
+ return tf_weight, "mobilebert.embeddings.word_embeddings.weight"
1433
+ else:
1434
+ return (tf_weight,)
1435
+
1436
+
1437
+ class TFMobileBertOnlyNSPHead(tf.keras.layers.Layer):
1438
+ def __init__(self, config, **kwargs):
1439
+ super().__init__(**kwargs)
1440
+ self.seq_relationship = tf.keras.layers.Dense(2, name="seq_relationship")
1441
+ self.config = config
1442
+
1443
+ def call(self, pooled_output):
1444
+ seq_relationship_score = self.seq_relationship(pooled_output)
1445
+ return seq_relationship_score
1446
+
1447
+ def build(self, input_shape=None):
1448
+ if self.built:
1449
+ return
1450
+ self.built = True
1451
+ if getattr(self, "seq_relationship", None) is not None:
1452
+ with tf.name_scope(self.seq_relationship.name):
1453
+ self.seq_relationship.build([None, None, self.config.hidden_size])
1454
+
1455
+
1456
+ @add_start_docstrings(
1457
+ """MobileBert Model with a `next sentence prediction (classification)` head on top.""",
1458
+ MOBILEBERT_START_DOCSTRING,
1459
+ )
1460
+ class TFMobileBertForNextSentencePrediction(TFMobileBertPreTrainedModel, TFNextSentencePredictionLoss):
1461
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1462
+ _keys_to_ignore_on_load_unexpected = [r"predictions___cls", r"cls.predictions"]
1463
+
1464
+ def __init__(self, config, *inputs, **kwargs):
1465
+ super().__init__(config, *inputs, **kwargs)
1466
+
1467
+ self.mobilebert = TFMobileBertMainLayer(config, name="mobilebert")
1468
+ self.cls = TFMobileBertOnlyNSPHead(config, name="seq_relationship___cls")
1469
+
1470
+ @unpack_inputs
1471
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1472
+ @replace_return_docstrings(output_type=TFNextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
1473
+ def call(
1474
+ self,
1475
+ input_ids: TFModelInputType | None = None,
1476
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1477
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1478
+ position_ids: np.ndarray | tf.Tensor | None = None,
1479
+ head_mask: np.ndarray | tf.Tensor | None = None,
1480
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1481
+ output_attentions: Optional[bool] = None,
1482
+ output_hidden_states: Optional[bool] = None,
1483
+ return_dict: Optional[bool] = None,
1484
+ next_sentence_label: np.ndarray | tf.Tensor | None = None,
1485
+ training: Optional[bool] = False,
1486
+ ) -> Union[Tuple, TFNextSentencePredictorOutput]:
1487
+ r"""
1488
+ Return:
1489
+
1490
+ Examples:
1491
+
1492
+ ```python
1493
+ >>> import tensorflow as tf
1494
+ >>> from transformers import AutoTokenizer, TFMobileBertForNextSentencePrediction
1495
+
1496
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mobilebert-uncased")
1497
+ >>> model = TFMobileBertForNextSentencePrediction.from_pretrained("google/mobilebert-uncased")
1498
+
1499
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1500
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1501
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="tf")
1502
+
1503
+ >>> logits = model(encoding["input_ids"], token_type_ids=encoding["token_type_ids"])[0]
1504
+ ```"""
1505
+ outputs = self.mobilebert(
1506
+ input_ids,
1507
+ attention_mask=attention_mask,
1508
+ token_type_ids=token_type_ids,
1509
+ position_ids=position_ids,
1510
+ head_mask=head_mask,
1511
+ inputs_embeds=inputs_embeds,
1512
+ output_attentions=output_attentions,
1513
+ output_hidden_states=output_hidden_states,
1514
+ return_dict=return_dict,
1515
+ training=training,
1516
+ )
1517
+ pooled_output = outputs[1]
1518
+ seq_relationship_scores = self.cls(pooled_output)
1519
+
1520
+ next_sentence_loss = (
1521
+ None
1522
+ if next_sentence_label is None
1523
+ else self.hf_compute_loss(labels=next_sentence_label, logits=seq_relationship_scores)
1524
+ )
1525
+
1526
+ if not return_dict:
1527
+ output = (seq_relationship_scores,) + outputs[2:]
1528
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1529
+
1530
+ return TFNextSentencePredictorOutput(
1531
+ loss=next_sentence_loss,
1532
+ logits=seq_relationship_scores,
1533
+ hidden_states=outputs.hidden_states,
1534
+ attentions=outputs.attentions,
1535
+ )
1536
+
1537
+ def build(self, input_shape=None):
1538
+ if self.built:
1539
+ return
1540
+ self.built = True
1541
+ if getattr(self, "mobilebert", None) is not None:
1542
+ with tf.name_scope(self.mobilebert.name):
1543
+ self.mobilebert.build(None)
1544
+ if getattr(self, "cls", None) is not None:
1545
+ with tf.name_scope(self.cls.name):
1546
+ self.cls.build(None)
1547
+
1548
+
1549
+ @add_start_docstrings(
1550
+ """
1551
+ MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
1552
+ pooled output) e.g. for GLUE tasks.
1553
+ """,
1554
+ MOBILEBERT_START_DOCSTRING,
1555
+ )
1556
+ class TFMobileBertForSequenceClassification(TFMobileBertPreTrainedModel, TFSequenceClassificationLoss):
1557
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1558
+ _keys_to_ignore_on_load_unexpected = [
1559
+ r"predictions___cls",
1560
+ r"seq_relationship___cls",
1561
+ r"cls.predictions",
1562
+ r"cls.seq_relationship",
1563
+ ]
1564
+ _keys_to_ignore_on_load_missing = [r"dropout"]
1565
+
1566
+ def __init__(self, config, *inputs, **kwargs):
1567
+ super().__init__(config, *inputs, **kwargs)
1568
+ self.num_labels = config.num_labels
1569
+
1570
+ self.mobilebert = TFMobileBertMainLayer(config, name="mobilebert")
1571
+ classifier_dropout = (
1572
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1573
+ )
1574
+ self.dropout = tf.keras.layers.Dropout(classifier_dropout)
1575
+ self.classifier = tf.keras.layers.Dense(
1576
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1577
+ )
1578
+ self.config = config
1579
+
1580
+ @unpack_inputs
1581
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1582
+ @add_code_sample_docstrings(
1583
+ checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
1584
+ output_type=TFSequenceClassifierOutput,
1585
+ config_class=_CONFIG_FOR_DOC,
1586
+ expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
1587
+ expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
1588
+ )
1589
+ def call(
1590
+ self,
1591
+ input_ids: TFModelInputType | None = None,
1592
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1593
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1594
+ position_ids: np.ndarray | tf.Tensor | None = None,
1595
+ head_mask: np.ndarray | tf.Tensor | None = None,
1596
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1597
+ output_attentions: Optional[bool] = None,
1598
+ output_hidden_states: Optional[bool] = None,
1599
+ return_dict: Optional[bool] = None,
1600
+ labels: np.ndarray | tf.Tensor | None = None,
1601
+ training: Optional[bool] = False,
1602
+ ) -> Union[Tuple, TFSequenceClassifierOutput]:
1603
+ r"""
1604
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1605
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1606
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1607
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1608
+ """
1609
+ outputs = self.mobilebert(
1610
+ input_ids,
1611
+ attention_mask=attention_mask,
1612
+ token_type_ids=token_type_ids,
1613
+ position_ids=position_ids,
1614
+ head_mask=head_mask,
1615
+ inputs_embeds=inputs_embeds,
1616
+ output_attentions=output_attentions,
1617
+ output_hidden_states=output_hidden_states,
1618
+ return_dict=return_dict,
1619
+ training=training,
1620
+ )
1621
+ pooled_output = outputs[1]
1622
+
1623
+ pooled_output = self.dropout(pooled_output, training=training)
1624
+ logits = self.classifier(pooled_output)
1625
+
1626
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1627
+
1628
+ if not return_dict:
1629
+ output = (logits,) + outputs[2:]
1630
+ return ((loss,) + output) if loss is not None else output
1631
+
1632
+ return TFSequenceClassifierOutput(
1633
+ loss=loss,
1634
+ logits=logits,
1635
+ hidden_states=outputs.hidden_states,
1636
+ attentions=outputs.attentions,
1637
+ )
1638
+
1639
+ def build(self, input_shape=None):
1640
+ if self.built:
1641
+ return
1642
+ self.built = True
1643
+ if getattr(self, "mobilebert", None) is not None:
1644
+ with tf.name_scope(self.mobilebert.name):
1645
+ self.mobilebert.build(None)
1646
+ if getattr(self, "classifier", None) is not None:
1647
+ with tf.name_scope(self.classifier.name):
1648
+ self.classifier.build([None, None, self.config.hidden_size])
1649
+
1650
+
1651
+ @add_start_docstrings(
1652
+ """
1653
+ MobileBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
1654
+ linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1655
+ """,
1656
+ MOBILEBERT_START_DOCSTRING,
1657
+ )
1658
+ class TFMobileBertForQuestionAnswering(TFMobileBertPreTrainedModel, TFQuestionAnsweringLoss):
1659
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1660
+ _keys_to_ignore_on_load_unexpected = [
1661
+ r"pooler",
1662
+ r"predictions___cls",
1663
+ r"seq_relationship___cls",
1664
+ r"cls.predictions",
1665
+ r"cls.seq_relationship",
1666
+ ]
1667
+
1668
+ def __init__(self, config, *inputs, **kwargs):
1669
+ super().__init__(config, *inputs, **kwargs)
1670
+ self.num_labels = config.num_labels
1671
+
1672
+ self.mobilebert = TFMobileBertMainLayer(config, add_pooling_layer=False, name="mobilebert")
1673
+ self.qa_outputs = tf.keras.layers.Dense(
1674
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
1675
+ )
1676
+ self.config = config
1677
+
1678
+ @unpack_inputs
1679
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1680
+ @add_code_sample_docstrings(
1681
+ checkpoint=_CHECKPOINT_FOR_QA,
1682
+ output_type=TFQuestionAnsweringModelOutput,
1683
+ config_class=_CONFIG_FOR_DOC,
1684
+ qa_target_start_index=_QA_TARGET_START_INDEX,
1685
+ qa_target_end_index=_QA_TARGET_END_INDEX,
1686
+ expected_output=_QA_EXPECTED_OUTPUT,
1687
+ expected_loss=_QA_EXPECTED_LOSS,
1688
+ )
1689
+ def call(
1690
+ self,
1691
+ input_ids: TFModelInputType | None = None,
1692
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1693
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1694
+ position_ids: np.ndarray | tf.Tensor | None = None,
1695
+ head_mask: np.ndarray | tf.Tensor | None = None,
1696
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1697
+ output_attentions: Optional[bool] = None,
1698
+ output_hidden_states: Optional[bool] = None,
1699
+ return_dict: Optional[bool] = None,
1700
+ start_positions: np.ndarray | tf.Tensor | None = None,
1701
+ end_positions: np.ndarray | tf.Tensor | None = None,
1702
+ training: Optional[bool] = False,
1703
+ ) -> Union[Tuple, TFQuestionAnsweringModelOutput]:
1704
+ r"""
1705
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1706
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1707
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1708
+ are not taken into account for computing the loss.
1709
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1710
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1711
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1712
+ are not taken into account for computing the loss.
1713
+ """
1714
+ outputs = self.mobilebert(
1715
+ input_ids,
1716
+ attention_mask=attention_mask,
1717
+ token_type_ids=token_type_ids,
1718
+ position_ids=position_ids,
1719
+ head_mask=head_mask,
1720
+ inputs_embeds=inputs_embeds,
1721
+ output_attentions=output_attentions,
1722
+ output_hidden_states=output_hidden_states,
1723
+ return_dict=return_dict,
1724
+ training=training,
1725
+ )
1726
+ sequence_output = outputs[0]
1727
+
1728
+ logits = self.qa_outputs(sequence_output)
1729
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
1730
+ start_logits = tf.squeeze(start_logits, axis=-1)
1731
+ end_logits = tf.squeeze(end_logits, axis=-1)
1732
+
1733
+ loss = None
1734
+ if start_positions is not None and end_positions is not None:
1735
+ labels = {"start_position": start_positions, "end_position": end_positions}
1736
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
1737
+
1738
+ if not return_dict:
1739
+ output = (start_logits, end_logits) + outputs[2:]
1740
+ return ((loss,) + output) if loss is not None else output
1741
+
1742
+ return TFQuestionAnsweringModelOutput(
1743
+ loss=loss,
1744
+ start_logits=start_logits,
1745
+ end_logits=end_logits,
1746
+ hidden_states=outputs.hidden_states,
1747
+ attentions=outputs.attentions,
1748
+ )
1749
+
1750
+ def build(self, input_shape=None):
1751
+ if self.built:
1752
+ return
1753
+ self.built = True
1754
+ if getattr(self, "mobilebert", None) is not None:
1755
+ with tf.name_scope(self.mobilebert.name):
1756
+ self.mobilebert.build(None)
1757
+ if getattr(self, "qa_outputs", None) is not None:
1758
+ with tf.name_scope(self.qa_outputs.name):
1759
+ self.qa_outputs.build([None, None, self.config.hidden_size])
1760
+
1761
+
1762
+ @add_start_docstrings(
1763
+ """
1764
+ MobileBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
1765
+ a softmax) e.g. for RocStories/SWAG tasks.
1766
+ """,
1767
+ MOBILEBERT_START_DOCSTRING,
1768
+ )
1769
+ class TFMobileBertForMultipleChoice(TFMobileBertPreTrainedModel, TFMultipleChoiceLoss):
1770
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1771
+ _keys_to_ignore_on_load_unexpected = [
1772
+ r"predictions___cls",
1773
+ r"seq_relationship___cls",
1774
+ r"cls.predictions",
1775
+ r"cls.seq_relationship",
1776
+ ]
1777
+ _keys_to_ignore_on_load_missing = [r"dropout"]
1778
+
1779
+ def __init__(self, config, *inputs, **kwargs):
1780
+ super().__init__(config, *inputs, **kwargs)
1781
+
1782
+ self.mobilebert = TFMobileBertMainLayer(config, name="mobilebert")
1783
+ self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)
1784
+ self.classifier = tf.keras.layers.Dense(
1785
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1786
+ )
1787
+ self.config = config
1788
+
1789
+ @unpack_inputs
1790
+ @add_start_docstrings_to_model_forward(
1791
+ MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1792
+ )
1793
+ @add_code_sample_docstrings(
1794
+ checkpoint=_CHECKPOINT_FOR_DOC,
1795
+ output_type=TFMultipleChoiceModelOutput,
1796
+ config_class=_CONFIG_FOR_DOC,
1797
+ )
1798
+ def call(
1799
+ self,
1800
+ input_ids: TFModelInputType | None = None,
1801
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1802
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1803
+ position_ids: np.ndarray | tf.Tensor | None = None,
1804
+ head_mask: np.ndarray | tf.Tensor | None = None,
1805
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1806
+ output_attentions: Optional[bool] = None,
1807
+ output_hidden_states: Optional[bool] = None,
1808
+ return_dict: Optional[bool] = None,
1809
+ labels: np.ndarray | tf.Tensor | None = None,
1810
+ training: Optional[bool] = False,
1811
+ ) -> Union[Tuple, TFMultipleChoiceModelOutput]:
1812
+ r"""
1813
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1814
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1815
+ where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
1816
+ """
1817
+ if input_ids is not None:
1818
+ num_choices = shape_list(input_ids)[1]
1819
+ seq_length = shape_list(input_ids)[2]
1820
+ else:
1821
+ num_choices = shape_list(inputs_embeds)[1]
1822
+ seq_length = shape_list(inputs_embeds)[2]
1823
+
1824
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
1825
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
1826
+ flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None
1827
+ flat_position_ids = tf.reshape(position_ids, (-1, seq_length)) if position_ids is not None else None
1828
+ flat_inputs_embeds = (
1829
+ tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
1830
+ if inputs_embeds is not None
1831
+ else None
1832
+ )
1833
+ outputs = self.mobilebert(
1834
+ flat_input_ids,
1835
+ flat_attention_mask,
1836
+ flat_token_type_ids,
1837
+ flat_position_ids,
1838
+ head_mask,
1839
+ flat_inputs_embeds,
1840
+ output_attentions,
1841
+ output_hidden_states,
1842
+ return_dict=return_dict,
1843
+ training=training,
1844
+ )
1845
+ pooled_output = outputs[1]
1846
+ pooled_output = self.dropout(pooled_output, training=training)
1847
+ logits = self.classifier(pooled_output)
1848
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
1849
+
1850
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
1851
+
1852
+ if not return_dict:
1853
+ output = (reshaped_logits,) + outputs[2:]
1854
+ return ((loss,) + output) if loss is not None else output
1855
+
1856
+ return TFMultipleChoiceModelOutput(
1857
+ loss=loss,
1858
+ logits=reshaped_logits,
1859
+ hidden_states=outputs.hidden_states,
1860
+ attentions=outputs.attentions,
1861
+ )
1862
+
1863
+ def build(self, input_shape=None):
1864
+ if self.built:
1865
+ return
1866
+ self.built = True
1867
+ if getattr(self, "mobilebert", None) is not None:
1868
+ with tf.name_scope(self.mobilebert.name):
1869
+ self.mobilebert.build(None)
1870
+ if getattr(self, "classifier", None) is not None:
1871
+ with tf.name_scope(self.classifier.name):
1872
+ self.classifier.build([None, None, self.config.hidden_size])
1873
+
1874
+
1875
+ @add_start_docstrings(
1876
+ """
1877
+ MobileBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
1878
+ for Named-Entity-Recognition (NER) tasks.
1879
+ """,
1880
+ MOBILEBERT_START_DOCSTRING,
1881
+ )
1882
+ class TFMobileBertForTokenClassification(TFMobileBertPreTrainedModel, TFTokenClassificationLoss):
1883
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1884
+ _keys_to_ignore_on_load_unexpected = [
1885
+ r"pooler",
1886
+ r"predictions___cls",
1887
+ r"seq_relationship___cls",
1888
+ r"cls.predictions",
1889
+ r"cls.seq_relationship",
1890
+ ]
1891
+ _keys_to_ignore_on_load_missing = [r"dropout"]
1892
+
1893
+ def __init__(self, config, *inputs, **kwargs):
1894
+ super().__init__(config, *inputs, **kwargs)
1895
+ self.num_labels = config.num_labels
1896
+
1897
+ self.mobilebert = TFMobileBertMainLayer(config, add_pooling_layer=False, name="mobilebert")
1898
+ classifier_dropout = (
1899
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1900
+ )
1901
+ self.dropout = tf.keras.layers.Dropout(classifier_dropout)
1902
+ self.classifier = tf.keras.layers.Dense(
1903
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1904
+ )
1905
+ self.config = config
1906
+
1907
+ @unpack_inputs
1908
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1909
+ @add_code_sample_docstrings(
1910
+ checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
1911
+ output_type=TFTokenClassifierOutput,
1912
+ config_class=_CONFIG_FOR_DOC,
1913
+ expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
1914
+ expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
1915
+ )
1916
+ def call(
1917
+ self,
1918
+ input_ids: TFModelInputType | None = None,
1919
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1920
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1921
+ position_ids: np.ndarray | tf.Tensor | None = None,
1922
+ head_mask: np.ndarray | tf.Tensor | None = None,
1923
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1924
+ output_attentions: Optional[bool] = None,
1925
+ output_hidden_states: Optional[bool] = None,
1926
+ return_dict: Optional[bool] = None,
1927
+ labels: np.ndarray | tf.Tensor | None = None,
1928
+ training: Optional[bool] = False,
1929
+ ) -> Union[Tuple, TFTokenClassifierOutput]:
1930
+ r"""
1931
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1932
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1933
+ """
1934
+ outputs = self.mobilebert(
1935
+ input_ids,
1936
+ attention_mask=attention_mask,
1937
+ token_type_ids=token_type_ids,
1938
+ position_ids=position_ids,
1939
+ head_mask=head_mask,
1940
+ inputs_embeds=inputs_embeds,
1941
+ output_attentions=output_attentions,
1942
+ output_hidden_states=output_hidden_states,
1943
+ return_dict=return_dict,
1944
+ training=training,
1945
+ )
1946
+ sequence_output = outputs[0]
1947
+
1948
+ sequence_output = self.dropout(sequence_output, training=training)
1949
+ logits = self.classifier(sequence_output)
1950
+
1951
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1952
+
1953
+ if not return_dict:
1954
+ output = (logits,) + outputs[2:]
1955
+ return ((loss,) + output) if loss is not None else output
1956
+
1957
+ return TFTokenClassifierOutput(
1958
+ loss=loss,
1959
+ logits=logits,
1960
+ hidden_states=outputs.hidden_states,
1961
+ attentions=outputs.attentions,
1962
+ )
1963
+
1964
+ def build(self, input_shape=None):
1965
+ if self.built:
1966
+ return
1967
+ self.built = True
1968
+ if getattr(self, "mobilebert", None) is not None:
1969
+ with tf.name_scope(self.mobilebert.name):
1970
+ self.mobilebert.build(None)
1971
+ if getattr(self, "classifier", None) is not None:
1972
+ with tf.name_scope(self.classifier.name):
1973
+ self.classifier.build([None, None, self.config.hidden_size])
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/tokenization_mobilebert.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ #
3
+ # Copyright 2020 The HuggingFace Team. 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
+ """Tokenization classes for MobileBERT."""
17
+
18
+
19
+ import collections
20
+ import os
21
+ import unicodedata
22
+ from typing import List, Optional, Tuple
23
+
24
+ from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
25
+ from ...utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
31
+
32
+ PRETRAINED_VOCAB_FILES_MAP = {
33
+ "vocab_file": {"mobilebert-uncased": "https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt"}
34
+ }
35
+
36
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {"mobilebert-uncased": 512}
37
+
38
+
39
+ PRETRAINED_INIT_CONFIGURATION = {}
40
+
41
+
42
+ # Copied from transformers.models.bert.tokenization_bert.load_vocab
43
+ def load_vocab(vocab_file):
44
+ """Loads a vocabulary file into a dictionary."""
45
+ vocab = collections.OrderedDict()
46
+ with open(vocab_file, "r", encoding="utf-8") as reader:
47
+ tokens = reader.readlines()
48
+ for index, token in enumerate(tokens):
49
+ token = token.rstrip("\n")
50
+ vocab[token] = index
51
+ return vocab
52
+
53
+
54
+ # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
55
+ def whitespace_tokenize(text):
56
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
57
+ text = text.strip()
58
+ if not text:
59
+ return []
60
+ tokens = text.split()
61
+ return tokens
62
+
63
+
64
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer with BERT->MobileBERT,Bert->MobileBert
65
+ class MobileBertTokenizer(PreTrainedTokenizer):
66
+ r"""
67
+ Construct a MobileBERT tokenizer. Based on WordPiece.
68
+
69
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
70
+ this superclass for more information regarding those methods.
71
+
72
+ Args:
73
+ vocab_file (`str`):
74
+ File containing the vocabulary.
75
+ do_lower_case (`bool`, *optional*, defaults to `True`):
76
+ Whether or not to lowercase the input when tokenizing.
77
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
78
+ Whether or not to do basic tokenization before WordPiece.
79
+ never_split (`Iterable`, *optional*):
80
+ Collection of tokens which will never be split during tokenization. Only has an effect when
81
+ `do_basic_tokenize=True`
82
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
83
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
84
+ token instead.
85
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
86
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
87
+ sequence classification or for a text and a question for question answering. It is also used as the last
88
+ token of a sequence built with special tokens.
89
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
90
+ The token used for padding, for example when batching sequences of different lengths.
91
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
92
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
93
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
94
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
95
+ The token used for masking values. This is the token used when training this model with masked language
96
+ modeling. This is the token which the model will try to predict.
97
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
98
+ Whether or not to tokenize Chinese characters.
99
+
100
+ This should likely be deactivated for Japanese (see this
101
+ [issue](https://github.com/huggingface/transformers/issues/328)).
102
+ strip_accents (`bool`, *optional*):
103
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
104
+ value for `lowercase` (as in the original MobileBERT).
105
+ """
106
+
107
+ vocab_files_names = VOCAB_FILES_NAMES
108
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
109
+ pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
110
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
111
+
112
+ def __init__(
113
+ self,
114
+ vocab_file,
115
+ do_lower_case=True,
116
+ do_basic_tokenize=True,
117
+ never_split=None,
118
+ unk_token="[UNK]",
119
+ sep_token="[SEP]",
120
+ pad_token="[PAD]",
121
+ cls_token="[CLS]",
122
+ mask_token="[MASK]",
123
+ tokenize_chinese_chars=True,
124
+ strip_accents=None,
125
+ **kwargs,
126
+ ):
127
+ if not os.path.isfile(vocab_file):
128
+ raise ValueError(
129
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
130
+ " model use `tokenizer = MobileBertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
131
+ )
132
+ self.vocab = load_vocab(vocab_file)
133
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
134
+ self.do_basic_tokenize = do_basic_tokenize
135
+ if do_basic_tokenize:
136
+ self.basic_tokenizer = BasicTokenizer(
137
+ do_lower_case=do_lower_case,
138
+ never_split=never_split,
139
+ tokenize_chinese_chars=tokenize_chinese_chars,
140
+ strip_accents=strip_accents,
141
+ )
142
+
143
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
144
+
145
+ super().__init__(
146
+ do_lower_case=do_lower_case,
147
+ do_basic_tokenize=do_basic_tokenize,
148
+ never_split=never_split,
149
+ unk_token=unk_token,
150
+ sep_token=sep_token,
151
+ pad_token=pad_token,
152
+ cls_token=cls_token,
153
+ mask_token=mask_token,
154
+ tokenize_chinese_chars=tokenize_chinese_chars,
155
+ strip_accents=strip_accents,
156
+ **kwargs,
157
+ )
158
+
159
+ @property
160
+ def do_lower_case(self):
161
+ return self.basic_tokenizer.do_lower_case
162
+
163
+ @property
164
+ def vocab_size(self):
165
+ return len(self.vocab)
166
+
167
+ def get_vocab(self):
168
+ return dict(self.vocab, **self.added_tokens_encoder)
169
+
170
+ def _tokenize(self, text, split_special_tokens=False):
171
+ split_tokens = []
172
+ if self.do_basic_tokenize:
173
+ for token in self.basic_tokenizer.tokenize(
174
+ text, never_split=self.all_special_tokens if not split_special_tokens else None
175
+ ):
176
+ # If the token is part of the never_split set
177
+ if token in self.basic_tokenizer.never_split:
178
+ split_tokens.append(token)
179
+ else:
180
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
181
+ else:
182
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
183
+ return split_tokens
184
+
185
+ def _convert_token_to_id(self, token):
186
+ """Converts a token (str) in an id using the vocab."""
187
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
188
+
189
+ def _convert_id_to_token(self, index):
190
+ """Converts an index (integer) in a token (str) using the vocab."""
191
+ return self.ids_to_tokens.get(index, self.unk_token)
192
+
193
+ def convert_tokens_to_string(self, tokens):
194
+ """Converts a sequence of tokens (string) in a single string."""
195
+ out_string = " ".join(tokens).replace(" ##", "").strip()
196
+ return out_string
197
+
198
+ def build_inputs_with_special_tokens(
199
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
200
+ ) -> List[int]:
201
+ """
202
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
203
+ adding special tokens. A MobileBERT sequence has the following format:
204
+
205
+ - single sequence: `[CLS] X [SEP]`
206
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
207
+
208
+ Args:
209
+ token_ids_0 (`List[int]`):
210
+ List of IDs to which the special tokens will be added.
211
+ token_ids_1 (`List[int]`, *optional*):
212
+ Optional second list of IDs for sequence pairs.
213
+
214
+ Returns:
215
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
216
+ """
217
+ if token_ids_1 is None:
218
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
219
+ cls = [self.cls_token_id]
220
+ sep = [self.sep_token_id]
221
+ return cls + token_ids_0 + sep + token_ids_1 + sep
222
+
223
+ def get_special_tokens_mask(
224
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
225
+ ) -> List[int]:
226
+ """
227
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
228
+ special tokens using the tokenizer `prepare_for_model` method.
229
+
230
+ Args:
231
+ token_ids_0 (`List[int]`):
232
+ List of IDs.
233
+ token_ids_1 (`List[int]`, *optional*):
234
+ Optional second list of IDs for sequence pairs.
235
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
236
+ Whether or not the token list is already formatted with special tokens for the model.
237
+
238
+ Returns:
239
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
240
+ """
241
+
242
+ if already_has_special_tokens:
243
+ return super().get_special_tokens_mask(
244
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
245
+ )
246
+
247
+ if token_ids_1 is not None:
248
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
249
+ return [1] + ([0] * len(token_ids_0)) + [1]
250
+
251
+ def create_token_type_ids_from_sequences(
252
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
253
+ ) -> List[int]:
254
+ """
255
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A MobileBERT sequence
256
+ pair mask has the following format:
257
+
258
+ ```
259
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
260
+ | first sequence | second sequence |
261
+ ```
262
+
263
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
264
+
265
+ Args:
266
+ token_ids_0 (`List[int]`):
267
+ List of IDs.
268
+ token_ids_1 (`List[int]`, *optional*):
269
+ Optional second list of IDs for sequence pairs.
270
+
271
+ Returns:
272
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
273
+ """
274
+ sep = [self.sep_token_id]
275
+ cls = [self.cls_token_id]
276
+ if token_ids_1 is None:
277
+ return len(cls + token_ids_0 + sep) * [0]
278
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
279
+
280
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
281
+ index = 0
282
+ if os.path.isdir(save_directory):
283
+ vocab_file = os.path.join(
284
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
285
+ )
286
+ else:
287
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
288
+ with open(vocab_file, "w", encoding="utf-8") as writer:
289
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
290
+ if index != token_index:
291
+ logger.warning(
292
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
293
+ " Please check that the vocabulary is not corrupted!"
294
+ )
295
+ index = token_index
296
+ writer.write(token + "\n")
297
+ index += 1
298
+ return (vocab_file,)
299
+
300
+
301
+ # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
302
+ class BasicTokenizer(object):
303
+ """
304
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
305
+
306
+ Args:
307
+ do_lower_case (`bool`, *optional*, defaults to `True`):
308
+ Whether or not to lowercase the input when tokenizing.
309
+ never_split (`Iterable`, *optional*):
310
+ Collection of tokens which will never be split during tokenization. Only has an effect when
311
+ `do_basic_tokenize=True`
312
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
313
+ Whether or not to tokenize Chinese characters.
314
+
315
+ This should likely be deactivated for Japanese (see this
316
+ [issue](https://github.com/huggingface/transformers/issues/328)).
317
+ strip_accents (`bool`, *optional*):
318
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
319
+ value for `lowercase` (as in the original BERT).
320
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
321
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
322
+ the full context of the words, such as contractions.
323
+ """
324
+
325
+ def __init__(
326
+ self,
327
+ do_lower_case=True,
328
+ never_split=None,
329
+ tokenize_chinese_chars=True,
330
+ strip_accents=None,
331
+ do_split_on_punc=True,
332
+ ):
333
+ if never_split is None:
334
+ never_split = []
335
+ self.do_lower_case = do_lower_case
336
+ self.never_split = set(never_split)
337
+ self.tokenize_chinese_chars = tokenize_chinese_chars
338
+ self.strip_accents = strip_accents
339
+ self.do_split_on_punc = do_split_on_punc
340
+
341
+ def tokenize(self, text, never_split=None):
342
+ """
343
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
344
+
345
+ Args:
346
+ never_split (`List[str]`, *optional*)
347
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
348
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
349
+ """
350
+ # union() returns a new set by concatenating the two sets.
351
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
352
+ text = self._clean_text(text)
353
+
354
+ # This was added on November 1st, 2018 for the multilingual and Chinese
355
+ # models. This is also applied to the English models now, but it doesn't
356
+ # matter since the English models were not trained on any Chinese data
357
+ # and generally don't have any Chinese data in them (there are Chinese
358
+ # characters in the vocabulary because Wikipedia does have some Chinese
359
+ # words in the English Wikipedia.).
360
+ if self.tokenize_chinese_chars:
361
+ text = self._tokenize_chinese_chars(text)
362
+ # prevents treating the same character with different unicode codepoints as different characters
363
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
364
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
365
+ split_tokens = []
366
+ for token in orig_tokens:
367
+ if token not in never_split:
368
+ if self.do_lower_case:
369
+ token = token.lower()
370
+ if self.strip_accents is not False:
371
+ token = self._run_strip_accents(token)
372
+ elif self.strip_accents:
373
+ token = self._run_strip_accents(token)
374
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
375
+
376
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
377
+ return output_tokens
378
+
379
+ def _run_strip_accents(self, text):
380
+ """Strips accents from a piece of text."""
381
+ text = unicodedata.normalize("NFD", text)
382
+ output = []
383
+ for char in text:
384
+ cat = unicodedata.category(char)
385
+ if cat == "Mn":
386
+ continue
387
+ output.append(char)
388
+ return "".join(output)
389
+
390
+ def _run_split_on_punc(self, text, never_split=None):
391
+ """Splits punctuation on a piece of text."""
392
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
393
+ return [text]
394
+ chars = list(text)
395
+ i = 0
396
+ start_new_word = True
397
+ output = []
398
+ while i < len(chars):
399
+ char = chars[i]
400
+ if _is_punctuation(char):
401
+ output.append([char])
402
+ start_new_word = True
403
+ else:
404
+ if start_new_word:
405
+ output.append([])
406
+ start_new_word = False
407
+ output[-1].append(char)
408
+ i += 1
409
+
410
+ return ["".join(x) for x in output]
411
+
412
+ def _tokenize_chinese_chars(self, text):
413
+ """Adds whitespace around any CJK character."""
414
+ output = []
415
+ for char in text:
416
+ cp = ord(char)
417
+ if self._is_chinese_char(cp):
418
+ output.append(" ")
419
+ output.append(char)
420
+ output.append(" ")
421
+ else:
422
+ output.append(char)
423
+ return "".join(output)
424
+
425
+ def _is_chinese_char(self, cp):
426
+ """Checks whether CP is the codepoint of a CJK character."""
427
+ # This defines a "chinese character" as anything in the CJK Unicode block:
428
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
429
+ #
430
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
431
+ # despite its name. The modern Korean Hangul alphabet is a different block,
432
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
433
+ # space-separated words, so they are not treated specially and handled
434
+ # like the all of the other languages.
435
+ if (
436
+ (cp >= 0x4E00 and cp <= 0x9FFF)
437
+ or (cp >= 0x3400 and cp <= 0x4DBF) #
438
+ or (cp >= 0x20000 and cp <= 0x2A6DF) #
439
+ or (cp >= 0x2A700 and cp <= 0x2B73F) #
440
+ or (cp >= 0x2B740 and cp <= 0x2B81F) #
441
+ or (cp >= 0x2B820 and cp <= 0x2CEAF) #
442
+ or (cp >= 0xF900 and cp <= 0xFAFF)
443
+ or (cp >= 0x2F800 and cp <= 0x2FA1F) #
444
+ ): #
445
+ return True
446
+
447
+ return False
448
+
449
+ def _clean_text(self, text):
450
+ """Performs invalid character removal and whitespace cleanup on text."""
451
+ output = []
452
+ for char in text:
453
+ cp = ord(char)
454
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
455
+ continue
456
+ if _is_whitespace(char):
457
+ output.append(" ")
458
+ else:
459
+ output.append(char)
460
+ return "".join(output)
461
+
462
+
463
+ # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
464
+ class WordpieceTokenizer(object):
465
+ """Runs WordPiece tokenization."""
466
+
467
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
468
+ self.vocab = vocab
469
+ self.unk_token = unk_token
470
+ self.max_input_chars_per_word = max_input_chars_per_word
471
+
472
+ def tokenize(self, text):
473
+ """
474
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
475
+ tokenization using the given vocabulary.
476
+
477
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
478
+
479
+ Args:
480
+ text: A single token or whitespace separated tokens. This should have
481
+ already been passed through *BasicTokenizer*.
482
+
483
+ Returns:
484
+ A list of wordpiece tokens.
485
+ """
486
+
487
+ output_tokens = []
488
+ for token in whitespace_tokenize(text):
489
+ chars = list(token)
490
+ if len(chars) > self.max_input_chars_per_word:
491
+ output_tokens.append(self.unk_token)
492
+ continue
493
+
494
+ is_bad = False
495
+ start = 0
496
+ sub_tokens = []
497
+ while start < len(chars):
498
+ end = len(chars)
499
+ cur_substr = None
500
+ while start < end:
501
+ substr = "".join(chars[start:end])
502
+ if start > 0:
503
+ substr = "##" + substr
504
+ if substr in self.vocab:
505
+ cur_substr = substr
506
+ break
507
+ end -= 1
508
+ if cur_substr is None:
509
+ is_bad = True
510
+ break
511
+ sub_tokens.append(cur_substr)
512
+ start = end
513
+
514
+ if is_bad:
515
+ output_tokens.append(self.unk_token)
516
+ else:
517
+ output_tokens.extend(sub_tokens)
518
+ return output_tokens
pllava/lib/python3.10/site-packages/transformers/models/mobilebert/tokenization_mobilebert_fast.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ #
3
+ # Copyright 2020 The HuggingFace Team. 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
+ """Tokenization classes for MobileBERT."""
17
+
18
+ import json
19
+ from typing import List, Optional, Tuple
20
+
21
+ from tokenizers import normalizers
22
+
23
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
24
+ from ...utils import logging
25
+ from .tokenization_mobilebert import MobileBertTokenizer
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
31
+
32
+ PRETRAINED_VOCAB_FILES_MAP = {
33
+ "vocab_file": {"mobilebert-uncased": "https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt"},
34
+ "tokenizer_file": {
35
+ "mobilebert-uncased": "https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json"
36
+ },
37
+ }
38
+
39
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {"mobilebert-uncased": 512}
40
+
41
+
42
+ PRETRAINED_INIT_CONFIGURATION = {}
43
+
44
+
45
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast with BERT->MobileBERT,Bert->MobileBert
46
+ class MobileBertTokenizerFast(PreTrainedTokenizerFast):
47
+ r"""
48
+ Construct a "fast" MobileBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
49
+
50
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
51
+ refer to this superclass for more information regarding those methods.
52
+
53
+ Args:
54
+ vocab_file (`str`):
55
+ File containing the vocabulary.
56
+ do_lower_case (`bool`, *optional*, defaults to `True`):
57
+ Whether or not to lowercase the input when tokenizing.
58
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
59
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
60
+ token instead.
61
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
62
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
63
+ sequence classification or for a text and a question for question answering. It is also used as the last
64
+ token of a sequence built with special tokens.
65
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
66
+ The token used for padding, for example when batching sequences of different lengths.
67
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
68
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
69
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
70
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
71
+ The token used for masking values. This is the token used when training this model with masked language
72
+ modeling. This is the token which the model will try to predict.
73
+ clean_text (`bool`, *optional*, defaults to `True`):
74
+ Whether or not to clean the text before tokenization by removing any control characters and replacing all
75
+ whitespaces by the classic one.
76
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
77
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
78
+ issue](https://github.com/huggingface/transformers/issues/328)).
79
+ strip_accents (`bool`, *optional*):
80
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
81
+ value for `lowercase` (as in the original MobileBERT).
82
+ wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
83
+ The prefix for subwords.
84
+ """
85
+
86
+ vocab_files_names = VOCAB_FILES_NAMES
87
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
88
+ pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
89
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
90
+ slow_tokenizer_class = MobileBertTokenizer
91
+
92
+ def __init__(
93
+ self,
94
+ vocab_file=None,
95
+ tokenizer_file=None,
96
+ do_lower_case=True,
97
+ unk_token="[UNK]",
98
+ sep_token="[SEP]",
99
+ pad_token="[PAD]",
100
+ cls_token="[CLS]",
101
+ mask_token="[MASK]",
102
+ tokenize_chinese_chars=True,
103
+ strip_accents=None,
104
+ **kwargs,
105
+ ):
106
+ super().__init__(
107
+ vocab_file,
108
+ tokenizer_file=tokenizer_file,
109
+ do_lower_case=do_lower_case,
110
+ unk_token=unk_token,
111
+ sep_token=sep_token,
112
+ pad_token=pad_token,
113
+ cls_token=cls_token,
114
+ mask_token=mask_token,
115
+ tokenize_chinese_chars=tokenize_chinese_chars,
116
+ strip_accents=strip_accents,
117
+ **kwargs,
118
+ )
119
+
120
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
121
+ if (
122
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
123
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
124
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
125
+ ):
126
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
127
+ normalizer_state["lowercase"] = do_lower_case
128
+ normalizer_state["strip_accents"] = strip_accents
129
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
130
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
131
+
132
+ self.do_lower_case = do_lower_case
133
+
134
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
135
+ """
136
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
137
+ adding special tokens. A MobileBERT sequence has the following format:
138
+
139
+ - single sequence: `[CLS] X [SEP]`
140
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
141
+
142
+ Args:
143
+ token_ids_0 (`List[int]`):
144
+ List of IDs to which the special tokens will be added.
145
+ token_ids_1 (`List[int]`, *optional*):
146
+ Optional second list of IDs for sequence pairs.
147
+
148
+ Returns:
149
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
150
+ """
151
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
152
+
153
+ if token_ids_1 is not None:
154
+ output += token_ids_1 + [self.sep_token_id]
155
+
156
+ return output
157
+
158
+ def create_token_type_ids_from_sequences(
159
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
160
+ ) -> List[int]:
161
+ """
162
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A MobileBERT sequence
163
+ pair mask has the following format:
164
+
165
+ ```
166
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
167
+ | first sequence | second sequence |
168
+ ```
169
+
170
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
171
+
172
+ Args:
173
+ token_ids_0 (`List[int]`):
174
+ List of IDs.
175
+ token_ids_1 (`List[int]`, *optional*):
176
+ Optional second list of IDs for sequence pairs.
177
+
178
+ Returns:
179
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
180
+ """
181
+ sep = [self.sep_token_id]
182
+ cls = [self.cls_token_id]
183
+ if token_ids_1 is None:
184
+ return len(cls + token_ids_0 + sep) * [0]
185
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
186
+
187
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
188
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
189
+ return tuple(files)
pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/__init__.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
18
+
19
+
20
+ _import_structure = {
21
+ "configuration_nllb_moe": [
22
+ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP",
23
+ "NllbMoeConfig",
24
+ ]
25
+ }
26
+
27
+ try:
28
+ if not is_torch_available():
29
+ raise OptionalDependencyNotAvailable()
30
+ except OptionalDependencyNotAvailable:
31
+ pass
32
+ else:
33
+ _import_structure["modeling_nllb_moe"] = [
34
+ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST",
35
+ "NllbMoeForConditionalGeneration",
36
+ "NllbMoeModel",
37
+ "NllbMoePreTrainedModel",
38
+ "NllbMoeTop2Router",
39
+ "NllbMoeSparseMLP",
40
+ ]
41
+
42
+
43
+ if TYPE_CHECKING:
44
+ from .configuration_nllb_moe import (
45
+ NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP,
46
+ NllbMoeConfig,
47
+ )
48
+
49
+ try:
50
+ if not is_torch_available():
51
+ raise OptionalDependencyNotAvailable()
52
+ except OptionalDependencyNotAvailable:
53
+ pass
54
+ else:
55
+ from .modeling_nllb_moe import (
56
+ NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST,
57
+ NllbMoeForConditionalGeneration,
58
+ NllbMoeModel,
59
+ NllbMoePreTrainedModel,
60
+ NllbMoeSparseMLP,
61
+ NllbMoeTop2Router,
62
+ )
63
+
64
+
65
+ else:
66
+ import sys
67
+
68
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.01 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/__pycache__/configuration_nllb_moe.cpython-310.pyc ADDED
Binary file (9.52 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/__pycache__/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (4.44 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/__pycache__/modeling_nllb_moe.cpython-310.pyc ADDED
Binary file (56.5 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/configuration_nllb_moe.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023, HuggingFace Inc.
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
+ """ NLLB-MoE model configuration"""
16
+ from ...configuration_utils import PretrainedConfig
17
+ from ...utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+ NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP = {
23
+ "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json",
24
+ }
25
+
26
+
27
+ class NllbMoeConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`NllbMoeModel`]. It is used to instantiate an
30
+ NLLB-MoE model according to the specified arguments, defining the model architecture. Instantiating a configuration
31
+ with the defaults will yield a similar configuration to that of the NLLB-MoE
32
+ [facebook/nllb-moe-54b](https://huggingface.co/facebook/nllb-moe-54b) architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 50265):
40
+ Vocabulary size of the NllbMoe model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`NllbMoeModel`] or
42
+ d_model (`int`, *optional*, defaults to 1024):
43
+ Dimensionality of the layers and the pooler layer.
44
+ encoder_layers (`int`, *optional*, defaults to 12):
45
+ Number of encoder layers.
46
+ decoder_layers (`int`, *optional*, defaults to 12):
47
+ Number of decoder layers.
48
+ encoder_attention_heads (`int`, *optional*, defaults to 16):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
51
+ Number of attention heads for each attention layer in the Transformer decoder.
52
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
53
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
54
+ encoder_ffn_dim (`int`, *optional*, defaults to 4096):
55
+ Dimensionality of the "intermediate" (often named feed-forward) layer in encoder.
56
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
57
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
58
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
59
+ dropout (`float`, *optional*, defaults to 0.1):
60
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
61
+ attention_dropout (`float`, *optional*, defaults to 0.0):
62
+ The dropout ratio for the attention probabilities.
63
+ activation_dropout (`float`, *optional*, defaults to 0.0):
64
+ The dropout ratio for activations inside the fully connected layer.
65
+ classifier_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio for classifier.
67
+ max_position_embeddings (`int`, *optional*, defaults to 1024):
68
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
69
+ just in case (e.g., 512 or 1024 or 2048).
70
+ init_std (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
73
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
74
+ for more details.
75
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
76
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
77
+ for more details.
78
+ second_expert_policy ( `str`, *optional*, default to `"all"`):
79
+ The policy used for the sampling the probability of being sampled to a second expert for each token.
80
+ normalize_router_prob_before_dropping (`bool`, *optional*, defaults to `True`):
81
+ Whether or not to normalize the router probabilities before applying a mask based on the experts capacity
82
+ (capacity dropping).
83
+ batch_prioritized_routing (`bool`, *optional*, defaults to `True`):
84
+ Whether or not to orders the tokens by their router probabilities before capacity dropping. This means that
85
+ the tokens that have the highest probabilities will be routed before other tokens that might be further in
86
+ the sequence.
87
+ moe_eval_capacity_token_fraction (`float`, *optional*, defaults to 1.0):
88
+ Fraction of tokens as capacity during validation, if set to negative, uses the same as training. Should be
89
+ in range: (0.0, 1.0].
90
+ num_experts (`int`, *optional*, defaults to 128):
91
+ Number of experts for each NllbMoeSparseMlp layer.
92
+ expert_capacity (`int`, *optional*, defaults to 64):
93
+ Number of tokens that can be stored in each expert.
94
+ encoder_sparse_step (`int`, *optional*, defaults to 4):
95
+ Frequency of the sparse layers in the encoder. 4 means that one out of 4 layers will be sparse.
96
+ decoder_sparse_step (`int`, *optional*, defaults to 4):
97
+ Frequency of the sparse layers in the decoder. 4 means that one out of 4 layers will be sparse.
98
+ router_dtype (`str`, *optional*, default to `"float32"`):
99
+ The `dtype` used for the routers. It is preferable to keep the `dtype` to `"float32"` as specified in the
100
+ *selective precision* discussion in [the paper](https://arxiv.org/abs/2101.03961).
101
+ router_ignore_padding_tokens (`bool`, *optional*, defaults to `False`):
102
+ Whether to ignore padding tokens when routing. if `False`, the padding tokens are not routed to any
103
+ experts.
104
+ router_bias (`bool`, *optional*, defaults to `False`):
105
+ Whether or not the classifier of the router should have a bias.
106
+ moe_token_dropout (`float`, *optional*, defualt ot 0.2):
107
+ Masking rate for MoE expert output masking (EOM), which is implemented via a Dropout2d on the expert
108
+ outputs.
109
+ output_router_logits (`bool`, *optional*, defaults to `False`):
110
+ Whether or not to return the router logits. Only set to `True` to get the auxiliary loss when training.
111
+ use_cache (`bool`, *optional*, defaults to `True`):
112
+ Whether or not the model should return the last key/values attentions (not used by all models).
113
+
114
+ Example:
115
+
116
+ ```python
117
+ >>> from transformers import NllbMoeModel, NllbMoeConfig
118
+
119
+ >>> # Initializing a NllbMoe facebook/nllb-moe-54b style configuration
120
+ >>> configuration = NllbMoeConfig()
121
+
122
+ >>> # Initializing a model from the facebook/nllb-moe-54b style configuration
123
+ >>> model = NllbMoeModel(configuration)
124
+
125
+ >>> # Accessing the model configuration
126
+ >>> configuration = model.config
127
+ ```"""
128
+
129
+ model_type = "nllb-moe"
130
+ keys_to_ignore_at_inference = ["past_key_values"]
131
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
132
+
133
+ def __init__(
134
+ self,
135
+ vocab_size=128112,
136
+ max_position_embeddings=1024,
137
+ encoder_layers=12,
138
+ encoder_ffn_dim=4096,
139
+ encoder_attention_heads=16,
140
+ decoder_layers=12,
141
+ decoder_ffn_dim=4096,
142
+ decoder_attention_heads=16,
143
+ encoder_layerdrop=0.05,
144
+ decoder_layerdrop=0.05,
145
+ use_cache=True,
146
+ is_encoder_decoder=True,
147
+ activation_function="relu",
148
+ d_model=1024,
149
+ dropout=0.1,
150
+ attention_dropout=0.1,
151
+ activation_dropout=0.0,
152
+ init_std=0.02,
153
+ decoder_start_token_id=2,
154
+ scale_embedding=True,
155
+ router_bias=False,
156
+ router_dtype="float32",
157
+ router_ignore_padding_tokens=False,
158
+ num_experts=128,
159
+ expert_capacity=64,
160
+ encoder_sparse_step=4,
161
+ decoder_sparse_step=4,
162
+ router_z_loss_coef=0.001,
163
+ router_aux_loss_coef=0.001,
164
+ second_expert_policy="all",
165
+ normalize_router_prob_before_dropping=False,
166
+ batch_prioritized_routing=False,
167
+ moe_eval_capacity_token_fraction=1.0,
168
+ moe_token_dropout=0.2,
169
+ pad_token_id=1,
170
+ bos_token_id=0,
171
+ eos_token_id=2,
172
+ output_router_logits=False,
173
+ **kwargs,
174
+ ):
175
+ self.vocab_size = vocab_size
176
+ self.max_position_embeddings = max_position_embeddings
177
+ self.d_model = d_model
178
+ self.encoder_ffn_dim = encoder_ffn_dim
179
+ self.encoder_layers = encoder_layers
180
+ self.encoder_attention_heads = encoder_attention_heads
181
+ self.decoder_ffn_dim = decoder_ffn_dim
182
+ self.decoder_layers = decoder_layers
183
+ self.decoder_attention_heads = decoder_attention_heads
184
+ self.dropout = dropout
185
+ self.attention_dropout = attention_dropout
186
+ self.activation_dropout = activation_dropout
187
+ self.activation_function = activation_function
188
+ self.init_std = init_std
189
+ self.encoder_layerdrop = encoder_layerdrop
190
+ self.decoder_layerdrop = decoder_layerdrop
191
+ self.use_cache = use_cache
192
+ self.num_hidden_layers = encoder_layers
193
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
194
+ self.router_z_loss_coef = router_z_loss_coef
195
+ self.router_aux_loss_coef = router_aux_loss_coef
196
+ self.decoder_sparse_step = decoder_sparse_step
197
+ self.encoder_sparse_step = encoder_sparse_step
198
+ self.num_experts = num_experts
199
+ self.expert_capacity = expert_capacity
200
+ self.router_bias = router_bias
201
+ if router_dtype not in ["float32", "float16", "bfloat16"]:
202
+ raise ValueError(f"`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}")
203
+ self.router_dtype = router_dtype
204
+
205
+ self.router_ignore_padding_tokens = router_ignore_padding_tokens
206
+ self.batch_prioritized_routing = batch_prioritized_routing
207
+ self.second_expert_policy = second_expert_policy
208
+ self.normalize_router_prob_before_dropping = normalize_router_prob_before_dropping
209
+ self.moe_eval_capacity_token_fraction = moe_eval_capacity_token_fraction
210
+ self.moe_token_dropout = moe_token_dropout
211
+ self.output_router_logits = output_router_logits
212
+ super().__init__(
213
+ pad_token_id=pad_token_id,
214
+ bos_token_id=bos_token_id,
215
+ eos_token_id=eos_token_id,
216
+ is_encoder_decoder=is_encoder_decoder,
217
+ decoder_start_token_id=decoder_start_token_id,
218
+ **kwargs,
219
+ )
pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import argparse
15
+ import json
16
+ import os
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from transformers import NllbMoeConfig, NllbMoeModel
22
+ from transformers.modeling_utils import dtype_byte_size
23
+ from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME
24
+
25
+
26
+ def remove_ignore_keys_(state_dict):
27
+ ignore_keys = [
28
+ "encoder.version",
29
+ "decoder.version",
30
+ "model.encoder.version",
31
+ "model.decoder.version",
32
+ "decoder.output_projection.weight",
33
+ "_float_tensor",
34
+ "encoder.embed_positions._float_tensor",
35
+ "decoder.embed_positions._float_tensor",
36
+ ]
37
+ for k in ignore_keys:
38
+ state_dict.pop(k, None)
39
+
40
+
41
+ def make_linear_from_emb(emb):
42
+ vocab_size, emb_size = emb.weight.shape
43
+ lin_layer = nn.Linear(vocab_size, emb_size, bias=False)
44
+ lin_layer.weight.data = emb.weight.data
45
+ return lin_layer
46
+
47
+
48
+ def rename_fairseq_keys(state_dict, expert_idx=None):
49
+ new_dict = {}
50
+ for old_key in state_dict.keys():
51
+ key = old_key
52
+ if "moe_layer.experts." in key:
53
+ if expert_idx is not None:
54
+ key = key.replace("moe_layer.experts.0", f"ffn.experts.expert_{expert_idx}")
55
+ else:
56
+ key = key.replace("moe_layer.experts.", "ffn.experts.expert_")
57
+ if "gate" in key:
58
+ key = key.replace(".moe_layer.gate.wg", ".ffn.router.classifier")
59
+ if "fc2" and "experts" not in key:
60
+ key = key.replace(".fc2.", ".ffn.fc2.")
61
+ if "fc1" and "experts" not in key:
62
+ key = key.replace(".fc1.", ".ffn.fc1.")
63
+ if ".encoder_attn." in key:
64
+ key = key.replace(".encoder_attn.", ".cross_attention.")
65
+ if "encoder_attn_layer_norm" in key:
66
+ key = key.replace("encoder_attn_layer_norm", "cross_attention_layer_norm")
67
+ if "final_layer_norm" in key:
68
+ key = key.replace("final_layer_norm", "ff_layer_norm")
69
+ new_dict[key] = state_dict[old_key]
70
+ return new_dict
71
+
72
+
73
+ def shard_on_the_fly(switch_checkpoint_path, dump_path, num_experts, dtype, weights_name: str = WEIGHTS_NAME):
74
+ sharded_state_dicts = []
75
+ total_size = 0
76
+ os.makedirs(dump_path, exist_ok=True)
77
+
78
+ for expert in range(num_experts):
79
+ expert_path = switch_checkpoint_path + f"-rank-{expert}.pt"
80
+ if os.path.isfile(expert_path):
81
+ expert_state = torch.load(expert_path)["model"]
82
+ remove_ignore_keys_(expert_state)
83
+ expert_state = rename_fairseq_keys(expert_state, expert)
84
+ save_path = os.path.join(
85
+ dump_path, weights_name.replace(".bin", f"-{len(sharded_state_dicts)+1:05d}-of-???.bin")
86
+ )
87
+ torch.save(expert_state, save_path)
88
+ sharded_state_dicts.append(expert_state.keys())
89
+ total_size += sum([value.numel() for key, value in expert_state.items()]) * dtype_byte_size(
90
+ expert_state[list(expert_state)[0]].dtype
91
+ )
92
+
93
+ # Add the last block
94
+ save_path = os.path.join(dump_path, weights_name.replace(".bin", f"-{len(sharded_state_dicts)+1:05d}-of-???.bin"))
95
+ shared_weights = torch.load(switch_checkpoint_path + "-shared.pt")["model"]
96
+ remove_ignore_keys_(shared_weights)
97
+ shared_weights = rename_fairseq_keys(shared_weights, None)
98
+ shared_weights["shared.weight"] = shared_weights["decoder.embed_tokens.weight"]
99
+ sharded_state_dicts.append(shared_weights.keys())
100
+
101
+ # If we only have the shared weights (dummy model/experts saved on the same file)
102
+ if len(sharded_state_dicts) == 1:
103
+ save_path = os.path.join(dump_path, weights_name)
104
+ torch.save(shared_weights, save_path)
105
+ return {weights_name: sharded_state_dicts[0]}, None
106
+ else:
107
+ torch.save(shared_weights, save_path)
108
+ # Otherwise, let's build the index
109
+ weight_map = {}
110
+ for idx, shard in enumerate(sharded_state_dicts):
111
+ shard_file = weights_name.replace(".bin", f"-{idx+1:05d}-of-{len(sharded_state_dicts):05d}.bin")
112
+ temp_filename = os.path.join(dump_path, weights_name.replace(".bin", f"-{idx+1:05d}-of-???.bin"))
113
+ os.rename(temp_filename, os.path.join(dump_path, shard_file))
114
+ for key in shard:
115
+ weight_map[key] = shard_file
116
+
117
+ # Add the metadata
118
+ metadata = {"total_size": total_size}
119
+ index = {"metadata": metadata, "weight_map": weight_map}
120
+
121
+ with open(os.path.join(dump_path, WEIGHTS_INDEX_NAME), "w", encoding="utf-8") as f:
122
+ content = json.dumps(index, indent=2, sort_keys=True) + "\n"
123
+ f.write(content)
124
+
125
+ return metadata, index
126
+
127
+
128
+ if __name__ == "__main__":
129
+ parser = argparse.ArgumentParser()
130
+ # Required parameters
131
+ parser.add_argument(
132
+ "--nllb_moe_checkpoint_path",
133
+ default="/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000",
134
+ type=str,
135
+ required=False,
136
+ help="Path to a directory containing a folder per layer. Follows the original Google format.",
137
+ )
138
+ parser.add_argument("--dtype", default="float32", type=str, required=False, help="dtype of the saved model")
139
+ parser.add_argument(
140
+ "--pytorch_dump_folder_path",
141
+ default="/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b",
142
+ type=str,
143
+ required=False,
144
+ help="Path to the output pytorch model.",
145
+ )
146
+ args = parser.parse_args()
147
+ metadata, index = shard_on_the_fly(
148
+ args.nllb_moe_checkpoint_path,
149
+ args.pytorch_dump_folder_path,
150
+ 128,
151
+ args.dtype,
152
+ )
153
+
154
+ config = NllbMoeConfig.from_pretrained(
155
+ "facebook/nllb-200-3.3B", encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128
156
+ )
157
+ config.save_pretrained(args.pytorch_dump_folder_path)
158
+ model = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path)
159
+ print("Done")
160
+ model.save_pretrained(args.pytorch_dump_folder_path)
pllava/lib/python3.10/site-packages/transformers/models/nllb_moe/modeling_nllb_moe.py ADDED
@@ -0,0 +1,1794 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 NllbMoe Authors and HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch NLLB-MoE model."""
16
+
17
+
18
+ import math
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ from torch.nn import CrossEntropyLoss
24
+
25
+ from ...activations import ACT2FN
26
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
27
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
28
+ from ...modeling_outputs import (
29
+ MoEModelOutput,
30
+ MoEModelOutputWithPastAndCrossAttentions,
31
+ Seq2SeqMoEModelOutput,
32
+ Seq2SeqMoEOutput,
33
+ )
34
+ from ...modeling_utils import PreTrainedModel
35
+ from ...utils import (
36
+ add_end_docstrings,
37
+ add_start_docstrings,
38
+ add_start_docstrings_to_model_forward,
39
+ logging,
40
+ replace_return_docstrings,
41
+ )
42
+ from .configuration_nllb_moe import NllbMoeConfig
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _CONFIG_FOR_DOC = "NllbMoeConfig"
48
+ _CHECKPOINT_FOR_DOC = "hf-internal-testing/dummy-nllb-moe-2-experts"
49
+ _REAL_CHECKPOINT_FOR_DOC = "facebook/nllb-moe-54b"
50
+
51
+
52
+ ####################################################
53
+ # This dict contains ids and associated url
54
+ # for the pretrained weights provided with the models
55
+ ####################################################
56
+ NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST = [
57
+ "facebook/nllb-moe-54b",
58
+ # See all NLLB-MOE models at https://huggingface.co/models?filter=nllb-moe
59
+ ]
60
+
61
+
62
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
63
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
64
+ """
65
+ Shift input ids one token to the right.
66
+ """
67
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
68
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
69
+ shifted_input_ids[:, 0] = decoder_start_token_id
70
+
71
+ if pad_token_id is None:
72
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
73
+ # replace possible -100 values in labels by `pad_token_id`
74
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
75
+
76
+ return shifted_input_ids
77
+
78
+
79
+ # Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
80
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
81
+ """
82
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
83
+ are ignored. This is modified from fairseq's `utils.make_positions`.
84
+
85
+ Args:
86
+ x: torch.Tensor x:
87
+
88
+ Returns: torch.Tensor
89
+ """
90
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
91
+ mask = input_ids.ne(padding_idx).int()
92
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
93
+ return incremental_indices.long() + padding_idx
94
+
95
+
96
+ def load_balancing_loss_func(router_probs: torch.Tensor, expert_indices: torch.Tensor) -> float:
97
+ r"""
98
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
99
+
100
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
101
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
102
+ experts is too unbalanced.
103
+
104
+ Args:
105
+ router_probs (`torch.Tensor`):
106
+ Probability assigned to each expert per token. Shape: [batch_size, seqeunce_length, num_experts].
107
+ expert_indices (`torch.Tensor`):
108
+ Indices tensor of shape [batch_size, seqeunce_length] identifying the selected expert for a given token.
109
+
110
+ Returns:
111
+ The auxiliary loss.
112
+ """
113
+ if router_probs is None:
114
+ return 0
115
+
116
+ num_experts = router_probs.shape[-1]
117
+
118
+ # cast the expert indices to int64, otherwise one-hot encoding will fail
119
+ if expert_indices.dtype != torch.int64:
120
+ expert_indices = expert_indices.to(torch.int64)
121
+
122
+ if len(expert_indices.shape) == 2:
123
+ expert_indices = expert_indices.unsqueeze(2)
124
+
125
+ expert_mask = torch.nn.functional.one_hot(expert_indices, num_experts)
126
+
127
+ # For a given token, determine if it was routed to a given expert.
128
+ expert_mask = torch.max(expert_mask, axis=-2).values
129
+
130
+ # cast to float32 otherwise mean will fail
131
+ expert_mask = expert_mask.to(torch.float32)
132
+ tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
133
+
134
+ router_prob_per_group_and_expert = torch.mean(router_probs, axis=-2)
135
+ return torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert) * (num_experts**2)
136
+
137
+
138
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding
139
+ class NllbMoeSinusoidalPositionalEmbedding(nn.Module):
140
+ """This module produces sinusoidal positional embeddings of any length."""
141
+
142
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
143
+ super().__init__()
144
+ self.offset = 2
145
+ self.embedding_dim = embedding_dim
146
+ self.padding_idx = padding_idx
147
+ self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
148
+
149
+ def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
150
+ emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
151
+ if hasattr(self, "weights"):
152
+ # in forward put the weights on the correct dtype and device of the param
153
+ emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
154
+
155
+ self.register_buffer("weights", emb_weights, persistent=False)
156
+
157
+ @staticmethod
158
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
159
+ """
160
+ Build sinusoidal embeddings.
161
+
162
+ This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
163
+ "Attention Is All You Need".
164
+ """
165
+ half_dim = embedding_dim // 2
166
+ emb = math.log(10000) / (half_dim - 1)
167
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb)
168
+ emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0)
169
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
170
+ if embedding_dim % 2 == 1:
171
+ # zero pad
172
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
173
+ if padding_idx is not None:
174
+ emb[padding_idx, :] = 0
175
+
176
+ return emb.to(torch.get_default_dtype())
177
+
178
+ @torch.no_grad()
179
+ def forward(
180
+ self, input_ids: torch.Tensor = None, inputs_embeds: torch.Tensor = None, past_key_values_length: int = 0
181
+ ):
182
+ if input_ids is not None:
183
+ bsz, seq_len = input_ids.size()
184
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
185
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length).to(
186
+ input_ids.device
187
+ )
188
+ else:
189
+ bsz, seq_len = inputs_embeds.size()[:-1]
190
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, past_key_values_length)
191
+
192
+ # expand embeddings if needed
193
+ max_pos = self.padding_idx + 1 + seq_len + past_key_values_length
194
+ if max_pos > self.weights.size(0):
195
+ self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
196
+
197
+ return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach()
198
+
199
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds, past_key_values_length):
200
+ """
201
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
202
+
203
+ Args:
204
+ inputs_embeds: torch.Tensor
205
+
206
+ Returns: torch.Tensor
207
+ """
208
+ input_shape = inputs_embeds.size()[:-1]
209
+ sequence_length = input_shape[1]
210
+
211
+ position_ids = torch.arange(
212
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
213
+ )
214
+ return position_ids.unsqueeze(0).expand(input_shape).contiguous() + past_key_values_length
215
+
216
+
217
+ class NllbMoeTop2Router(nn.Module):
218
+ """
219
+ Router using tokens choose top-2 experts assignment.
220
+
221
+ This router uses the same mechanism as in NLLB-MoE from the fairseq repository. Items are sorted by router_probs
222
+ and then routed to their choice of expert until the expert's expert_capacity is reached. **There is no guarantee
223
+ that each token is processed by an expert**, or that each expert receives at least one token.
224
+
225
+ The router combining weights are also returned to make sure that the states that are not updated will be masked.
226
+
227
+ """
228
+
229
+ def __init__(self, config: NllbMoeConfig):
230
+ super().__init__()
231
+ self.num_experts = config.num_experts
232
+ self.expert_capacity = config.expert_capacity
233
+ self.classifier = nn.Linear(config.hidden_size, self.num_experts, bias=config.router_bias)
234
+ self.router_ignore_padding_tokens = config.router_ignore_padding_tokens
235
+ self.dtype = getattr(torch, config.router_dtype)
236
+
237
+ self.second_expert_policy = config.second_expert_policy
238
+ self.normalize_router_prob_before_dropping = config.normalize_router_prob_before_dropping
239
+ self.batch_prioritized_routing = config.batch_prioritized_routing
240
+ self.moe_eval_capacity_token_fraction = config.moe_eval_capacity_token_fraction
241
+
242
+ def _cast_classifier(self):
243
+ r"""
244
+ `bitsandbytes` `Linear8bitLt` layers does not support manual casting Therefore we need to check if they are an
245
+ instance of the `Linear8bitLt` class by checking special attributes.
246
+ """
247
+ if not (hasattr(self.classifier, "SCB") or hasattr(self.classifier, "CB")):
248
+ self.classifier = self.classifier.to(self.dtype)
249
+
250
+ def normalize_router_probabilities(self, router_probs, top_1_mask, top_2_mask):
251
+ top_1_max_probs = (router_probs * top_1_mask).sum(dim=1)
252
+ top_2_max_probs = (router_probs * top_2_mask).sum(dim=1)
253
+ denom_s = torch.clamp(top_1_max_probs + top_2_max_probs, min=torch.finfo(router_probs.dtype).eps)
254
+ top_1_max_probs = top_1_max_probs / denom_s
255
+ top_2_max_probs = top_2_max_probs / denom_s
256
+ return top_1_max_probs, top_2_max_probs
257
+
258
+ def route_tokens(
259
+ self,
260
+ router_logits: torch.Tensor,
261
+ input_dtype: torch.dtype = torch.float32,
262
+ padding_mask: Optional[torch.LongTensor] = None,
263
+ ) -> Tuple:
264
+ """
265
+ Computes the `dispatch_mask` and the `dispatch_weights` for each experts. The masks are adapted to the expert
266
+ capacity.
267
+ """
268
+ nb_tokens = router_logits.shape[0]
269
+ # Apply Softmax and cast back to the original `dtype`
270
+ router_probs = nn.functional.softmax(router_logits, dim=-1, dtype=self.dtype).to(input_dtype)
271
+ top_1_expert_index = torch.argmax(router_probs, dim=-1)
272
+ top_1_mask = torch.nn.functional.one_hot(top_1_expert_index, num_classes=self.num_experts)
273
+
274
+ if self.second_expert_policy == "sampling":
275
+ gumbel = torch.distributions.gumbel.Gumbel(0, 1).rsample
276
+ router_logits += gumbel(router_logits.shape).to(router_logits.device)
277
+
278
+ # replace top_1_expert_index with min values
279
+ logits_except_top_1 = router_logits.masked_fill(top_1_mask.bool(), float("-inf"))
280
+ top_2_expert_index = torch.argmax(logits_except_top_1, dim=-1)
281
+ top_2_mask = torch.nn.functional.one_hot(top_2_expert_index, num_classes=self.num_experts)
282
+
283
+ if self.normalize_router_prob_before_dropping:
284
+ top_1_max_probs, top_2_max_probs = self.normalize_router_probabilities(
285
+ router_probs, top_1_mask, top_2_mask
286
+ )
287
+
288
+ if self.second_expert_policy == "random":
289
+ top_2_max_probs = (router_probs * top_2_mask).sum(dim=1)
290
+ sampled = (2 * top_2_max_probs) > torch.rand_like(top_2_max_probs.float())
291
+ top_2_mask = top_2_mask * sampled.repeat(self.num_experts, 1).transpose(1, 0)
292
+
293
+ if padding_mask is not None and not self.router_ignore_padding_tokens:
294
+ if len(padding_mask.shape) == 4:
295
+ # only get the last causal mask
296
+ padding_mask = padding_mask[:, :, -1, :].reshape(-1)[-nb_tokens:]
297
+ non_padding = ~padding_mask.bool()
298
+ top_1_mask = top_1_mask * non_padding.unsqueeze(-1).to(top_1_mask.dtype)
299
+ top_2_mask = top_2_mask * non_padding.unsqueeze(-1).to(top_1_mask.dtype)
300
+
301
+ if self.batch_prioritized_routing:
302
+ # sort tokens based on their routing probability
303
+ # to make sure important tokens are routed, first
304
+ importance_scores = -1 * router_probs.max(dim=1)[0]
305
+ sorted_top_1_mask = top_1_mask[importance_scores.argsort(dim=0)]
306
+ sorted_cumsum1 = (torch.cumsum(sorted_top_1_mask, dim=0) - 1) * sorted_top_1_mask
307
+ locations1 = sorted_cumsum1[importance_scores.argsort(dim=0).argsort(dim=0)]
308
+
309
+ sorted_top_2_mask = top_2_mask[importance_scores.argsort(dim=0)]
310
+ sorted_cumsum2 = (torch.cumsum(sorted_top_2_mask, dim=0) - 1) * sorted_top_2_mask
311
+ locations2 = sorted_cumsum2[importance_scores.argsort(dim=0).argsort(dim=0)]
312
+ # Update 2nd's location by accounting for locations of 1st
313
+ locations2 += torch.sum(top_1_mask, dim=0, keepdim=True)
314
+
315
+ else:
316
+ locations1 = torch.cumsum(top_1_mask, dim=0) - 1
317
+ locations2 = torch.cumsum(top_2_mask, dim=0) - 1
318
+ # Update 2nd's location by accounting for locations of 1st
319
+ locations2 += torch.sum(top_1_mask, dim=0, keepdim=True)
320
+
321
+ if not self.training and self.moe_eval_capacity_token_fraction > 0:
322
+ self.expert_capacity = math.ceil(self.moe_eval_capacity_token_fraction * nb_tokens)
323
+ else:
324
+ capacity = 2 * math.ceil(nb_tokens / self.num_experts)
325
+ self.expert_capacity = capacity if self.expert_capacity is None else self.expert_capacity
326
+
327
+ # Remove locations outside capacity from ( cumsum < capacity = False will not be routed)
328
+ top_1_mask = top_1_mask * torch.lt(locations1, self.expert_capacity)
329
+ top_2_mask = top_2_mask * torch.lt(locations2, self.expert_capacity)
330
+
331
+ if not self.normalize_router_prob_before_dropping:
332
+ top_1_max_probs, top_2_max_probs = self.normalize_router_probabilities(
333
+ router_probs, top_1_mask, top_2_mask
334
+ )
335
+
336
+ # Calculate combine_weights and dispatch_mask
337
+ gates1 = top_1_max_probs[:, None] * top_1_mask
338
+ gates2 = top_2_max_probs[:, None] * top_2_mask
339
+ router_probs = gates1 + gates2
340
+
341
+ return top_1_mask, router_probs
342
+
343
+ def forward(self, hidden_states: torch.Tensor, padding_mask: Optional[torch.LongTensor] = None) -> Tuple:
344
+ r"""
345
+ The hidden states are reshaped to simplify the computation of the router probabilities (combining weights for
346
+ each experts.)
347
+
348
+ Args:
349
+ hidden_states (`torch.Tensor`):
350
+ (batch_size, sequence_length, hidden_dim) from which router probabilities are computed.
351
+ Returns:
352
+ top_1_mask (`torch.Tensor` of shape (batch_size, sequence_length)):
353
+ Index tensor of shape [batch_size, sequence_length] corresponding to the expert selected for each token
354
+ using the top1 probabilities of the router.
355
+ router_probabilities (`torch.Tensor` of shape (batch_size, sequence_length, nump_experts)):
356
+ Tensor of shape (batch_size, sequence_length, num_experts) corresponding to the probabilities for each
357
+ token and expert. Used for routing tokens to experts.
358
+ router_logits (`torch.Tensor` of shape (batch_size, sequence_length))):
359
+ Logits tensor of shape (batch_size, sequence_length, num_experts) corresponding to raw router logits.
360
+ This is used later for computing router z-loss.
361
+ """
362
+ self.input_dtype = hidden_states.dtype
363
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
364
+ hidden_states = hidden_states.reshape((batch_size * sequence_length), hidden_dim)
365
+ hidden_states = hidden_states.to(self.dtype)
366
+ self._cast_classifier()
367
+ router_logits = self.classifier(hidden_states)
368
+ top_1_mask, router_probs = self.route_tokens(router_logits, self.input_dtype, padding_mask)
369
+ return top_1_mask, router_probs
370
+
371
+
372
+ class NllbMoeDenseActDense(nn.Module):
373
+ def __init__(self, config: NllbMoeConfig, ffn_dim: int):
374
+ super().__init__()
375
+ self.fc1 = nn.Linear(config.d_model, ffn_dim)
376
+ self.fc2 = nn.Linear(ffn_dim, config.d_model)
377
+ self.dropout = nn.Dropout(config.activation_dropout)
378
+ self.act = ACT2FN[config.activation_function]
379
+
380
+ def forward(self, hidden_states):
381
+ hidden_states = self.fc1(hidden_states)
382
+ hidden_states = self.act(hidden_states)
383
+ hidden_states = self.dropout(hidden_states)
384
+ if (
385
+ isinstance(self.fc2.weight, torch.Tensor)
386
+ and hidden_states.dtype != self.fc2.weight.dtype
387
+ and (self.fc2.weight.dtype != torch.int8 and self.fc2.weight.dtype != torch.uint8)
388
+ ):
389
+ hidden_states = hidden_states.to(self.fc2.weight.dtype)
390
+ hidden_states = self.fc2(hidden_states)
391
+ return hidden_states
392
+
393
+
394
+ class NllbMoeSparseMLP(nn.Module):
395
+ r"""
396
+ Implementation of the NLLB-MoE sparse MLP module.
397
+ """
398
+
399
+ def __init__(self, config: NllbMoeConfig, ffn_dim: int, expert_class: nn.Module = NllbMoeDenseActDense):
400
+ super().__init__()
401
+ self.router = NllbMoeTop2Router(config)
402
+ self.moe_token_dropout = config.moe_token_dropout
403
+ self.token_dropout = nn.Dropout(self.moe_token_dropout)
404
+ self.num_experts = config.num_experts
405
+
406
+ self.experts = nn.ModuleDict()
407
+ for idx in range(self.num_experts):
408
+ self.experts[f"expert_{idx}"] = expert_class(config, ffn_dim)
409
+
410
+ def forward(self, hidden_states: torch.Tensor, padding_mask: Optional[torch.Tensor] = False):
411
+ r"""
412
+ The goal of this forward pass is to have the same number of operation as the equivalent `NllbMoeDenseActDense`
413
+ (mlp) layer. This means that all of the hidden states should be processed at most twice ( since we are using a
414
+ top_2 gating mecanism). This means that we keep the complexity to O(batch_size x sequence_length x hidden_dim)
415
+ instead of O(num_experts x batch_size x sequence_length x hidden_dim).
416
+
417
+ 1- Get the `router_probs` from the `router`. The shape of the `router_mask` is `(batch_size X sequence_length,
418
+ num_expert)` and corresponds to the boolean version of the `router_probs`. The inputs are masked using the
419
+ `router_mask`.
420
+
421
+ 2- Dispatch the hidden_states to its associated experts. The router probabilities are used to weight the
422
+ contribution of each experts when updating the masked hidden states.
423
+
424
+ Args:
425
+ hidden_states (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_dim)`):
426
+ The hidden states
427
+ padding_mask (`torch.Tensor`, *optional*, defaults to `False`):
428
+ Attention mask. Can be in the causal form or not.
429
+
430
+ Returns:
431
+ hidden_states (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_dim)`):
432
+ Updated hidden states
433
+ router_logits (`torch.Tensor` of shape `(batch_size, sequence_length, num_experts)`):
434
+ Needed for computing the loss
435
+
436
+ """
437
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
438
+
439
+ top_1_mask, router_probs = self.router(hidden_states, padding_mask)
440
+ router_mask = router_probs.bool()
441
+ hidden_states = hidden_states.reshape((batch_size * sequence_length), hidden_dim)
442
+ masked_hidden_states = torch.einsum("bm,be->ebm", hidden_states, router_mask)
443
+ for idx, expert in enumerate(self.experts.values()):
444
+ token_indices = router_mask[:, idx]
445
+ combining_weights = router_probs[token_indices, idx]
446
+ expert_output = expert(masked_hidden_states[idx, token_indices])
447
+ if self.moe_token_dropout > 0:
448
+ if self.training:
449
+ expert_output = self.token_dropout(expert_output)
450
+ else:
451
+ expert_output *= 1 - self.moe_token_dropout
452
+ masked_hidden_states[idx, token_indices] = torch.einsum("b,be->be", combining_weights, expert_output)
453
+ hidden_states = masked_hidden_states.sum(dim=0).reshape(batch_size, sequence_length, hidden_dim)
454
+
455
+ top_1_expert_index = torch.argmax(top_1_mask, dim=-1)
456
+ return hidden_states, (router_probs, top_1_expert_index)
457
+
458
+
459
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->NllbMoe,key_value_states->encoder_hidden_states
460
+ class NllbMoeAttention(nn.Module):
461
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
462
+
463
+ def __init__(
464
+ self,
465
+ embed_dim: int,
466
+ num_heads: int,
467
+ dropout: float = 0.0,
468
+ is_decoder: bool = False,
469
+ bias: bool = True,
470
+ is_causal: bool = False,
471
+ config: Optional[NllbMoeConfig] = None,
472
+ ):
473
+ super().__init__()
474
+ self.embed_dim = embed_dim
475
+ self.num_heads = num_heads
476
+ self.dropout = dropout
477
+ self.head_dim = embed_dim // num_heads
478
+ self.config = config
479
+
480
+ if (self.head_dim * num_heads) != self.embed_dim:
481
+ raise ValueError(
482
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
483
+ f" and `num_heads`: {num_heads})."
484
+ )
485
+ self.scaling = self.head_dim**-0.5
486
+ self.is_decoder = is_decoder
487
+ self.is_causal = is_causal
488
+
489
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
490
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
491
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
492
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
493
+
494
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
495
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
496
+
497
+ def forward(
498
+ self,
499
+ hidden_states: torch.Tensor,
500
+ encoder_hidden_states: Optional[torch.Tensor] = None,
501
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
502
+ attention_mask: Optional[torch.Tensor] = None,
503
+ layer_head_mask: Optional[torch.Tensor] = None,
504
+ output_attentions: bool = False,
505
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
506
+ """Input shape: Batch x Time x Channel"""
507
+
508
+ # if encoder_hidden_states are provided this layer is used as a cross-attention layer
509
+ # for the decoder
510
+ is_cross_attention = encoder_hidden_states is not None
511
+
512
+ bsz, tgt_len, _ = hidden_states.size()
513
+
514
+ # get query proj
515
+ query_states = self.q_proj(hidden_states) * self.scaling
516
+ # get key, value proj
517
+ # `past_key_value[0].shape[2] == encoder_hidden_states.shape[1]`
518
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
519
+ # the provided `encoder_hidden_states` to support prefix tuning
520
+ if (
521
+ is_cross_attention
522
+ and past_key_value is not None
523
+ and past_key_value[0].shape[2] == encoder_hidden_states.shape[1]
524
+ ):
525
+ # reuse k,v, cross_attentions
526
+ key_states = past_key_value[0]
527
+ value_states = past_key_value[1]
528
+ elif is_cross_attention:
529
+ # cross_attentions
530
+ key_states = self._shape(self.k_proj(encoder_hidden_states), -1, bsz)
531
+ value_states = self._shape(self.v_proj(encoder_hidden_states), -1, bsz)
532
+ elif past_key_value is not None:
533
+ # reuse k, v, self_attention
534
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
535
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
536
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
537
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
538
+ else:
539
+ # self_attention
540
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
541
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
542
+
543
+ if self.is_decoder:
544
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
545
+ # Further calls to cross_attention layer can then reuse all cross-attention
546
+ # key/value_states (first "if" case)
547
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
548
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
549
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
550
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
551
+ past_key_value = (key_states, value_states)
552
+
553
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
554
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
555
+ key_states = key_states.reshape(*proj_shape)
556
+ value_states = value_states.reshape(*proj_shape)
557
+
558
+ src_len = key_states.size(1)
559
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
560
+
561
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
562
+ raise ValueError(
563
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
564
+ f" {attn_weights.size()}"
565
+ )
566
+
567
+ if attention_mask is not None:
568
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
569
+ raise ValueError(
570
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
571
+ )
572
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
573
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
574
+
575
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
576
+
577
+ if layer_head_mask is not None:
578
+ if layer_head_mask.size() != (self.num_heads,):
579
+ raise ValueError(
580
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
581
+ f" {layer_head_mask.size()}"
582
+ )
583
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
584
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
585
+
586
+ if output_attentions:
587
+ # this operation is a bit awkward, but it's required to
588
+ # make sure that attn_weights keeps its gradient.
589
+ # In order to do so, attn_weights have to be reshaped
590
+ # twice and have to be reused in the following
591
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
592
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
593
+ else:
594
+ attn_weights_reshaped = None
595
+
596
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
597
+
598
+ attn_output = torch.bmm(attn_probs, value_states)
599
+
600
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
601
+ raise ValueError(
602
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
603
+ f" {attn_output.size()}"
604
+ )
605
+
606
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
607
+ attn_output = attn_output.transpose(1, 2)
608
+
609
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
610
+ # partitioned across GPUs when using tensor-parallelism.
611
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
612
+
613
+ attn_output = self.out_proj(attn_output)
614
+
615
+ return attn_output, attn_weights_reshaped, past_key_value
616
+
617
+
618
+ class NllbMoeEncoderLayer(nn.Module):
619
+ def __init__(self, config: NllbMoeConfig, is_sparse: bool = False):
620
+ super().__init__()
621
+ self.embed_dim = config.d_model
622
+ self.is_sparse = is_sparse
623
+ self.self_attn = NllbMoeAttention(
624
+ embed_dim=self.embed_dim,
625
+ num_heads=config.encoder_attention_heads,
626
+ dropout=config.attention_dropout,
627
+ )
628
+ self.attn_dropout = nn.Dropout(config.dropout)
629
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
630
+ if not self.is_sparse:
631
+ self.ffn = NllbMoeDenseActDense(config, ffn_dim=config.encoder_ffn_dim)
632
+ else:
633
+ self.ffn = NllbMoeSparseMLP(config, ffn_dim=config.encoder_ffn_dim)
634
+ self.ff_layer_norm = nn.LayerNorm(config.d_model)
635
+ self.ff_dropout = nn.Dropout(config.activation_dropout)
636
+
637
+ def forward(
638
+ self,
639
+ hidden_states: torch.Tensor,
640
+ attention_mask: torch.Tensor,
641
+ layer_head_mask: torch.Tensor,
642
+ output_attentions: bool = False,
643
+ output_router_logits: bool = False,
644
+ ) -> torch.Tensor:
645
+ """
646
+ Args:
647
+ hidden_states (`torch.FloatTensor`):
648
+ input to the layer of shape `(batch, seq_len, embed_dim)`
649
+ attention_mask (`torch.FloatTensor`):
650
+ attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very
651
+ large negative values.
652
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
653
+ `(encoder_attention_heads,)`.
654
+ output_attentions (`bool`, *optional*):
655
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
656
+ returned tensors for more detail.
657
+ """
658
+ residual = hidden_states
659
+ hidden_states = self.self_attn_layer_norm(hidden_states)
660
+ hidden_states, attn_weights, _ = self.self_attn(
661
+ hidden_states=hidden_states,
662
+ attention_mask=attention_mask,
663
+ layer_head_mask=layer_head_mask,
664
+ output_attentions=output_attentions,
665
+ )
666
+ hidden_states = self.attn_dropout(hidden_states)
667
+ hidden_states = residual + hidden_states
668
+
669
+ residual = hidden_states
670
+
671
+ hidden_states = self.ff_layer_norm(hidden_states)
672
+ if self.is_sparse:
673
+ hidden_states, router_states = self.ffn(hidden_states, attention_mask)
674
+ else:
675
+ # router_states set to None to track which layers have None gradients.
676
+ hidden_states, router_states = self.ffn(hidden_states), None
677
+
678
+ hidden_states = self.ff_dropout(hidden_states)
679
+
680
+ hidden_states = residual + hidden_states
681
+
682
+ if hidden_states.dtype == torch.float16 and (
683
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
684
+ ):
685
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
686
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
687
+
688
+ outputs = (hidden_states,)
689
+
690
+ if output_attentions:
691
+ outputs += (attn_weights,)
692
+
693
+ if output_router_logits:
694
+ outputs += (router_states,)
695
+
696
+ return outputs
697
+
698
+
699
+ class NllbMoeDecoderLayer(nn.Module):
700
+ def __init__(self, config: NllbMoeConfig, is_sparse: bool = False):
701
+ super().__init__()
702
+ self.embed_dim = config.d_model
703
+ self.is_sparse = is_sparse
704
+ self.self_attn = NllbMoeAttention(
705
+ embed_dim=self.embed_dim,
706
+ num_heads=config.decoder_attention_heads,
707
+ dropout=config.attention_dropout,
708
+ is_decoder=True,
709
+ )
710
+ self.dropout = config.dropout
711
+ self.activation_fn = ACT2FN[config.activation_function]
712
+ self.attn_dropout = nn.Dropout(config.dropout)
713
+
714
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
715
+ self.cross_attention = NllbMoeAttention(
716
+ self.embed_dim, config.decoder_attention_heads, config.attention_dropout, is_decoder=True
717
+ )
718
+ self.cross_attention_layer_norm = nn.LayerNorm(self.embed_dim)
719
+ if not self.is_sparse:
720
+ self.ffn = NllbMoeDenseActDense(config, ffn_dim=config.decoder_ffn_dim)
721
+ else:
722
+ self.ffn = NllbMoeSparseMLP(config, ffn_dim=config.decoder_ffn_dim)
723
+ self.ff_layer_norm = nn.LayerNorm(config.d_model)
724
+ self.ff_dropout = nn.Dropout(config.activation_dropout)
725
+
726
+ def forward(
727
+ self,
728
+ hidden_states: torch.Tensor,
729
+ attention_mask: Optional[torch.Tensor] = None,
730
+ encoder_hidden_states: Optional[torch.Tensor] = None,
731
+ encoder_attention_mask: Optional[torch.Tensor] = None,
732
+ layer_head_mask: Optional[torch.Tensor] = None,
733
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
734
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
735
+ output_attentions: Optional[bool] = False,
736
+ output_router_logits: Optional[bool] = False,
737
+ use_cache: Optional[bool] = True,
738
+ ) -> torch.Tensor:
739
+ """
740
+ Args:
741
+ hidden_states (`torch.FloatTensor`):
742
+ input to the layer of shape `(batch, seq_len, embed_dim)`
743
+ attention_mask (`torch.FloatTensor`):
744
+ attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very
745
+ large negative values.
746
+ encoder_hidden_states (`torch.FloatTensor`):
747
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
748
+ encoder_attention_mask (`torch.FloatTensor`):
749
+ encoder attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by
750
+ very large negative values.
751
+ layer_head_mask (`torch.FloatTensor`):
752
+ mask for attention heads in a given layer of size `(encoder_attention_heads,)`.
753
+ cross_attn_layer_head_mask (`torch.FloatTensor`):
754
+ mask for cross-attention heads in a given layer of size `(decoder_attention_heads,)`.
755
+ past_key_value (`Tuple(torch.FloatTensor)`):
756
+ cached past key and value projection states
757
+ output_attentions (`bool`, *optional*):
758
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
759
+ returned tensors for more detail.
760
+ """
761
+ residual = hidden_states
762
+ hidden_states = self.self_attn_layer_norm(hidden_states)
763
+
764
+ # Self Attention
765
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
766
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
767
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
768
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
769
+ hidden_states=hidden_states,
770
+ past_key_value=self_attn_past_key_value,
771
+ attention_mask=attention_mask,
772
+ layer_head_mask=layer_head_mask,
773
+ output_attentions=output_attentions,
774
+ )
775
+ hidden_states = self.attn_dropout(hidden_states)
776
+ hidden_states = residual + hidden_states
777
+
778
+ # Cross-Attention Block
779
+ cross_attn_present_key_value = None
780
+ cross_attn_weights = None
781
+ if encoder_hidden_states is not None:
782
+ residual = hidden_states
783
+ hidden_states = self.cross_attention_layer_norm(hidden_states)
784
+
785
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
786
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
787
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.cross_attention(
788
+ hidden_states=hidden_states,
789
+ encoder_hidden_states=encoder_hidden_states,
790
+ past_key_value=cross_attn_past_key_value,
791
+ attention_mask=encoder_attention_mask,
792
+ layer_head_mask=cross_attn_layer_head_mask,
793
+ output_attentions=output_attentions,
794
+ )
795
+ hidden_states = self.attn_dropout(hidden_states)
796
+ hidden_states = residual + hidden_states
797
+
798
+ # add cross-attn to positions 3,4 of present_key_value tuple
799
+ present_key_value += cross_attn_present_key_value
800
+
801
+ # Fully Connected
802
+ residual = hidden_states
803
+
804
+ hidden_states = self.ff_layer_norm(hidden_states)
805
+ if self.is_sparse:
806
+ hidden_states, router_states = self.ffn(hidden_states, attention_mask)
807
+ else:
808
+ hidden_states, router_states = self.ffn(hidden_states), None
809
+
810
+ hidden_states = self.ff_dropout(hidden_states)
811
+
812
+ hidden_states = residual + hidden_states
813
+
814
+ # clamp inf values to enable fp16 training
815
+ if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
816
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
817
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
818
+
819
+ outputs = (hidden_states, present_key_value)
820
+
821
+ if output_attentions:
822
+ outputs += (self_attn_weights, cross_attn_weights)
823
+
824
+ if output_router_logits:
825
+ outputs += (router_states,)
826
+
827
+ return outputs
828
+
829
+
830
+ class NllbMoePreTrainedModel(PreTrainedModel):
831
+ config_class = NllbMoeConfig
832
+ base_model_prefix = "model"
833
+ supports_gradient_checkpointing = True
834
+ _no_split_modules = ["NllbMoeEncoderLayer", "NllbMoeDecoderLayer"]
835
+
836
+ def _init_weights(self, module):
837
+ """Initialize the weights"""
838
+ std = self.config.init_std
839
+ if isinstance(module, nn.Linear):
840
+ module.weight.data.normal_(mean=0.0, std=std)
841
+ if module.bias is not None:
842
+ module.bias.data.zero_()
843
+ elif isinstance(module, nn.Embedding):
844
+ module.weight.data.normal_(mean=0.0, std=std)
845
+ if module.padding_idx is not None:
846
+ module.weight.data[module.padding_idx].zero_()
847
+
848
+
849
+ NLLB_MOE_START_DOCSTRING = r"""
850
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
851
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
852
+ etc.)
853
+
854
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
855
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
856
+ and behavior.
857
+
858
+ Parameters:
859
+ config ([`NllbMoeConfig`]):
860
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
861
+ load the weights associated with the model, only the configuration. Check out the
862
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
863
+ """
864
+
865
+ NLLB_MOE_GENERATION_EXAMPLE = r"""
866
+ Translation example:
867
+
868
+ ```python
869
+ >>> from transformers import AutoTokenizer, NllbMoeForConditionalGeneration
870
+
871
+ >>> model = NllbMoeForConditionalGeneration.from_pretrained("facebook/nllb-moe-54b")
872
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/nllb-moe-54b")
873
+
874
+ >>> text_to_translate = "Life is like a box of chocolates"
875
+ >>> model_inputs = tokenizer(text_to_translate, return_tensors="pt")
876
+
877
+ >>> # translate to French
878
+ >>> gen_tokens = model.generate(**model_inputs, forced_bos_token_id=tokenizer.get_lang_id("eng_Latn"))
879
+ >>> print(tokenizer.batch_decode(gen_tokens, skip_special_tokens=True))
880
+ ```
881
+ """
882
+
883
+ NLLB_MOE_INPUTS_DOCSTRING = r"""
884
+ Args:
885
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
886
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
887
+ it.
888
+
889
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
890
+ [`PreTrainedTokenizer.__call__`] for details.
891
+
892
+ [What are input IDs?](../glossary#input-ids)
893
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
894
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
895
+
896
+ - 1 for tokens that are **not masked**,
897
+ - 0 for tokens that are **masked**.
898
+
899
+ [What are attention masks?](../glossary#attention-mask)
900
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
901
+ Indices of decoder input sequence tokens in the vocabulary.
902
+
903
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
904
+ [`PreTrainedTokenizer.__call__`] for details.
905
+
906
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
907
+
908
+ NllbMoe uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If
909
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
910
+ `past_key_values`).
911
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
912
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
913
+ be used by default.
914
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
915
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
916
+
917
+ - 1 indicates the head is **not masked**,
918
+ - 0 indicates the head is **masked**.
919
+
920
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
921
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
922
+
923
+ - 1 indicates the head is **not masked**,
924
+ - 0 indicates the head is **masked**.
925
+
926
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
927
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
928
+ 1]`:
929
+
930
+ - 1 indicates the head is **not masked**,
931
+ - 0 indicates the head is **masked**.
932
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
933
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
934
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
935
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
936
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
937
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
938
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
939
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
940
+
941
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
942
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
943
+
944
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
945
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
946
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
947
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
948
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
949
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
950
+ than the model's internal embedding lookup matrix.
951
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
952
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
953
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
954
+ input (see `past_key_values`). This is useful if you want more control over how to convert
955
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
956
+
957
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
958
+ of `inputs_embeds`.
959
+ use_cache (`bool`, *optional*):
960
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
961
+ `past_key_values`).
962
+ output_attentions (`bool`, *optional*):
963
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
964
+ tensors for more detail.
965
+ output_hidden_states (`bool`, *optional*):
966
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
967
+ more detail.
968
+ output_router_logits (`bool`, *optional*):
969
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
970
+ should not be returned during inference.
971
+ return_dict (`bool`, *optional*):
972
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
973
+ """
974
+
975
+
976
+ class NllbMoeEncoder(NllbMoePreTrainedModel):
977
+ """
978
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
979
+ [`NllbMoeEncoderLayer`].
980
+
981
+ Args:
982
+ config:
983
+ NllbMoeConfig
984
+ embed_tokens (nn.Embedding):
985
+ output embedding
986
+ """
987
+
988
+ def __init__(self, config: NllbMoeConfig, embed_tokens: Optional[nn.Embedding] = None):
989
+ super().__init__(config)
990
+
991
+ self.dropout = config.dropout
992
+ self.layerdrop = config.encoder_layerdrop
993
+
994
+ embed_dim = config.d_model
995
+ self.padding_idx = config.pad_token_id
996
+ self.max_source_positions = config.max_position_embeddings
997
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
998
+
999
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
1000
+
1001
+ if embed_tokens is not None:
1002
+ self.embed_tokens.weight = embed_tokens.weight
1003
+
1004
+ self.embed_positions = NllbMoeSinusoidalPositionalEmbedding(
1005
+ config.max_position_embeddings,
1006
+ embed_dim,
1007
+ self.padding_idx,
1008
+ )
1009
+ sparse_step = config.encoder_sparse_step
1010
+ self.layers = nn.ModuleList()
1011
+ for i in range(config.encoder_layers):
1012
+ is_sparse = (i + 1) % sparse_step == 0 if sparse_step > 0 else False
1013
+ self.layers.append(NllbMoeEncoderLayer(config, is_sparse))
1014
+
1015
+ self.layer_norm = nn.LayerNorm(config.d_model)
1016
+
1017
+ self.gradient_checkpointing = False
1018
+ # Initialize weights and apply final processing
1019
+ self.post_init()
1020
+
1021
+ def forward(
1022
+ self,
1023
+ input_ids: Optional[torch.Tensor] = None,
1024
+ attention_mask: Optional[torch.Tensor] = None,
1025
+ head_mask: Optional[torch.Tensor] = None,
1026
+ inputs_embeds: Optional[torch.Tensor] = None,
1027
+ output_attentions: Optional[bool] = None,
1028
+ output_hidden_states: Optional[bool] = None,
1029
+ output_router_logits: Optional[bool] = None,
1030
+ return_dict: Optional[bool] = None,
1031
+ ):
1032
+ r"""
1033
+ Args:
1034
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1035
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1036
+ provide it.
1037
+
1038
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1039
+ [`PreTrainedTokenizer.__call__`] for details.
1040
+
1041
+ [What are input IDs?](../glossary#input-ids)
1042
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1043
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1044
+
1045
+ - 1 for tokens that are **not masked**,
1046
+ - 0 for tokens that are **masked**.
1047
+
1048
+ [What are attention masks?](../glossary#attention-mask)
1049
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
1050
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1051
+
1052
+ - 1 indicates the head is **not masked**,
1053
+ - 0 indicates the head is **masked**.
1054
+
1055
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1056
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1057
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1058
+ than the model's internal embedding lookup matrix.
1059
+ output_attentions (`bool`, *optional*):
1060
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1061
+ returned tensors for more detail.
1062
+ output_hidden_states (`bool`, *optional*):
1063
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1064
+ for more detail.
1065
+ output_router_logits (`bool`, *optional*):
1066
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
1067
+ and should not be returned during inference.
1068
+ return_dict (`bool`, *optional*):
1069
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1070
+ """
1071
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1072
+ output_hidden_states = (
1073
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1074
+ )
1075
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1076
+
1077
+ # retrieve input_ids and inputs_embeds
1078
+ if input_ids is not None and inputs_embeds is not None:
1079
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1080
+ elif input_ids is not None:
1081
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1082
+ input_shape = input_ids.size()
1083
+ input_ids = input_ids.view(-1, input_shape[-1])
1084
+ elif inputs_embeds is not None:
1085
+ input_shape = inputs_embeds.size()[:-1]
1086
+ else:
1087
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1088
+
1089
+ if inputs_embeds is None:
1090
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
1091
+
1092
+ embed_pos = self.embed_positions(input_ids, inputs_embeds)
1093
+ embed_pos = embed_pos.to(inputs_embeds.device)
1094
+
1095
+ hidden_states = inputs_embeds + embed_pos
1096
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1097
+
1098
+ # expand attention_mask
1099
+ if attention_mask is not None:
1100
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1101
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
1102
+
1103
+ encoder_states = () if output_hidden_states else None
1104
+ all_router_probs = () if output_router_logits else None
1105
+ all_attentions = () if output_attentions else None
1106
+
1107
+ # check if head_mask has a correct number of layers specified if desired
1108
+ if head_mask is not None:
1109
+ if head_mask.size()[0] != len(self.layers):
1110
+ raise ValueError(
1111
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
1112
+ f" {head_mask.size()[0]}."
1113
+ )
1114
+
1115
+ for idx, encoder_layer in enumerate(self.layers):
1116
+ if output_hidden_states:
1117
+ encoder_states = encoder_states + (hidden_states,)
1118
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1119
+ dropout_probability = torch.rand([])
1120
+ if self.training and (dropout_probability < self.layerdrop): # skip the layer
1121
+ layer_outputs = (None, None, None)
1122
+ else:
1123
+ if self.gradient_checkpointing and self.training:
1124
+ layer_outputs = self._gradient_checkpointing_func(
1125
+ encoder_layer.__call__,
1126
+ hidden_states,
1127
+ attention_mask,
1128
+ (head_mask[idx] if head_mask is not None else None),
1129
+ output_attentions,
1130
+ )
1131
+ else:
1132
+ layer_outputs = encoder_layer(
1133
+ hidden_states,
1134
+ attention_mask,
1135
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1136
+ output_attentions=output_attentions,
1137
+ output_router_logits=output_router_logits,
1138
+ )
1139
+
1140
+ hidden_states = layer_outputs[0]
1141
+
1142
+ if output_attentions:
1143
+ all_attentions += (layer_outputs[1],)
1144
+
1145
+ if output_router_logits:
1146
+ all_router_probs += (layer_outputs[-1],)
1147
+
1148
+ last_hidden_state = self.layer_norm(hidden_states)
1149
+
1150
+ if output_hidden_states:
1151
+ encoder_states += (last_hidden_state,)
1152
+
1153
+ if not return_dict:
1154
+ return tuple(
1155
+ v for v in [last_hidden_state, encoder_states, all_attentions, all_router_probs] if v is not None
1156
+ )
1157
+
1158
+ return MoEModelOutput(
1159
+ last_hidden_state=last_hidden_state,
1160
+ hidden_states=encoder_states,
1161
+ attentions=all_attentions,
1162
+ router_probs=all_router_probs,
1163
+ )
1164
+
1165
+
1166
+ class NllbMoeDecoder(NllbMoePreTrainedModel):
1167
+ """
1168
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`NllbMoeDecoderLayer`]
1169
+
1170
+ Args:
1171
+ config:
1172
+ NllbMoeConfig
1173
+ embed_tokens (nn.Embedding):
1174
+ output embedding
1175
+ """
1176
+
1177
+ def __init__(self, config: NllbMoeConfig, embed_tokens: Optional[nn.Embedding] = None):
1178
+ super().__init__(config)
1179
+ self.dropout = config.dropout
1180
+ self.layerdrop = config.decoder_layerdrop
1181
+ self.padding_idx = config.pad_token_id
1182
+ self.max_target_positions = config.max_position_embeddings
1183
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
1184
+
1185
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
1186
+
1187
+ if embed_tokens is not None:
1188
+ self.embed_tokens.weight = embed_tokens.weight
1189
+
1190
+ self.embed_positions = NllbMoeSinusoidalPositionalEmbedding(
1191
+ config.max_position_embeddings,
1192
+ config.d_model,
1193
+ self.padding_idx,
1194
+ )
1195
+
1196
+ sparse_step = config.decoder_sparse_step
1197
+ self.layers = nn.ModuleList()
1198
+ for i in range(config.decoder_layers):
1199
+ is_sparse = (i + 1) % sparse_step == 0 if sparse_step > 0 else False
1200
+ self.layers.append(NllbMoeDecoderLayer(config, is_sparse))
1201
+
1202
+ self.layer_norm = nn.LayerNorm(config.d_model)
1203
+
1204
+ self.gradient_checkpointing = False
1205
+ # Initialize weights and apply final processing
1206
+ self.post_init()
1207
+
1208
+ def forward(
1209
+ self,
1210
+ input_ids: Optional[torch.Tensor] = None,
1211
+ attention_mask: Optional[torch.Tensor] = None,
1212
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1213
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1214
+ head_mask: Optional[torch.Tensor] = None,
1215
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1216
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1217
+ inputs_embeds: Optional[torch.Tensor] = None,
1218
+ use_cache: Optional[bool] = None,
1219
+ output_attentions: Optional[bool] = None,
1220
+ output_hidden_states: Optional[bool] = None,
1221
+ output_router_logits: Optional[bool] = None,
1222
+ return_dict: Optional[bool] = None,
1223
+ ):
1224
+ r"""
1225
+ Args:
1226
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1227
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1228
+ provide it.
1229
+
1230
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1231
+ [`PreTrainedTokenizer.__call__`] for details.
1232
+
1233
+ [What are input IDs?](../glossary#input-ids)
1234
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1235
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1236
+
1237
+ - 1 for tokens that are **not masked**,
1238
+ - 0 for tokens that are **masked**.
1239
+
1240
+ [What are attention masks?](../glossary#attention-mask)
1241
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
1242
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1243
+ of the decoder.
1244
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
1245
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
1246
+ selected in `[0, 1]`:
1247
+
1248
+ - 1 for tokens that are **not masked**,
1249
+ - 0 for tokens that are **masked**.
1250
+
1251
+ [What are attention masks?](../glossary#attention-mask)
1252
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1253
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1254
+
1255
+ - 1 indicates the head is **not masked**,
1256
+ - 0 indicates the head is **masked**.
1257
+
1258
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1259
+ Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
1260
+ cross-attention on hidden heads. Mask values selected in `[0, 1]`:
1261
+
1262
+ - 1 indicates the head is **not masked**,
1263
+ - 0 indicates the head is **masked**.
1264
+
1265
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1266
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1267
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1268
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
1269
+
1270
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1271
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1272
+
1273
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1274
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1275
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1276
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1277
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1278
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1279
+ than the model's internal embedding lookup matrix.
1280
+ output_attentions (`bool`, *optional*):
1281
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1282
+ returned tensors for more detail.
1283
+ output_hidden_states (`bool`, *optional*):
1284
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1285
+ for more detail.
1286
+ output_router_logits (`bool`, *optional*):
1287
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
1288
+ and should not be returned during inference.
1289
+ return_dict (`bool`, *optional*):
1290
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
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
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1297
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1298
+
1299
+ # retrieve input_ids and inputs_embeds
1300
+ if input_ids is not None and inputs_embeds is not None:
1301
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1302
+ elif input_ids is not None:
1303
+ input_shape = input_ids.size()
1304
+ input_ids = input_ids.view(-1, input_shape[-1])
1305
+ elif inputs_embeds is not None:
1306
+ input_shape = inputs_embeds.size()[:-1]
1307
+ else:
1308
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1309
+
1310
+ # past_key_values_length
1311
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1312
+
1313
+ if inputs_embeds is None:
1314
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
1315
+
1316
+ # create causal mask
1317
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1318
+ combined_attention_mask = _prepare_4d_causal_attention_mask(
1319
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
1320
+ )
1321
+
1322
+ # expand encoder attention mask
1323
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1324
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1325
+ encoder_attention_mask = _prepare_4d_attention_mask(
1326
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
1327
+ )
1328
+
1329
+ # embed positions
1330
+ positions = self.embed_positions(input_ids, inputs_embeds, past_key_values_length)
1331
+ positions = positions.to(inputs_embeds.device)
1332
+
1333
+ hidden_states = inputs_embeds + positions
1334
+
1335
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1336
+
1337
+ if self.gradient_checkpointing and self.training:
1338
+ if use_cache:
1339
+ logger.warning_once(
1340
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting" " `use_cache=False`..."
1341
+ )
1342
+ use_cache = False
1343
+
1344
+ # decoder layers
1345
+ all_hidden_states = () if output_hidden_states else None
1346
+ all_self_attns = () if output_attentions else None
1347
+ all_router_probs = () if output_router_logits else None
1348
+ all_cross_attentions = () if output_attentions else None
1349
+ present_key_value_states = () if use_cache else None
1350
+
1351
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
1352
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
1353
+ if attn_mask is not None:
1354
+ if attn_mask.size()[0] != len(self.layers):
1355
+ raise ValueError(
1356
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
1357
+ f" {head_mask.size()[0]}."
1358
+ )
1359
+ deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()
1360
+
1361
+ for idx, decoder_layer in enumerate(self.layers):
1362
+ if output_hidden_states:
1363
+ all_hidden_states += (hidden_states,)
1364
+
1365
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1366
+ dropout_probability = torch.rand([])
1367
+
1368
+ skip_the_layer = True if self.training and (dropout_probability < self.layerdrop) else False
1369
+ if not skip_the_layer or deepspeed_zero3_is_enabled:
1370
+ layer_head_mask = head_mask[idx] if head_mask is not None else None
1371
+ cross_attn_layer_head_mask = cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
1372
+
1373
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1374
+
1375
+ # under deepspeed zero3 all gpus must run in sync
1376
+ if self.gradient_checkpointing and self.training:
1377
+ if use_cache:
1378
+ logger.warning_once(
1379
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1380
+ )
1381
+ use_cache = False
1382
+ layer_outputs = self._gradient_checkpointing_func(
1383
+ decoder_layer.forward,
1384
+ hidden_states,
1385
+ combined_attention_mask,
1386
+ encoder_hidden_states,
1387
+ encoder_attention_mask,
1388
+ layer_head_mask,
1389
+ cross_attn_layer_head_mask,
1390
+ None, # past_key_value is always None with gradient checkpointing
1391
+ use_cache,
1392
+ output_attentions,
1393
+ )
1394
+ else:
1395
+ layer_outputs = decoder_layer(
1396
+ hidden_states,
1397
+ attention_mask=combined_attention_mask,
1398
+ encoder_hidden_states=encoder_hidden_states,
1399
+ encoder_attention_mask=encoder_attention_mask,
1400
+ layer_head_mask=layer_head_mask,
1401
+ cross_attn_layer_head_mask=cross_attn_layer_head_mask,
1402
+ past_key_value=past_key_value,
1403
+ use_cache=use_cache,
1404
+ output_attentions=output_attentions,
1405
+ output_router_logits=output_router_logits,
1406
+ )
1407
+
1408
+ hidden_states = layer_outputs[0]
1409
+
1410
+ if skip_the_layer:
1411
+ continue
1412
+
1413
+ if use_cache:
1414
+ present_key_value_states += (layer_outputs[1],)
1415
+
1416
+ if output_attentions:
1417
+ all_self_attns += (layer_outputs[2],)
1418
+ all_cross_attentions += (layer_outputs[3],)
1419
+
1420
+ if output_router_logits:
1421
+ all_router_probs += (layer_outputs[-1],)
1422
+
1423
+ hidden_states = self.layer_norm(hidden_states)
1424
+
1425
+ # Add last layer
1426
+ if output_hidden_states:
1427
+ all_hidden_states += (hidden_states,)
1428
+
1429
+ if not return_dict:
1430
+ return tuple(
1431
+ v
1432
+ for v in [
1433
+ hidden_states,
1434
+ present_key_value_states,
1435
+ all_hidden_states,
1436
+ all_self_attns,
1437
+ all_cross_attentions,
1438
+ all_router_probs,
1439
+ ]
1440
+ if v is not None
1441
+ )
1442
+ return MoEModelOutputWithPastAndCrossAttentions(
1443
+ last_hidden_state=hidden_states,
1444
+ past_key_values=present_key_value_states,
1445
+ hidden_states=all_hidden_states,
1446
+ attentions=all_self_attns,
1447
+ cross_attentions=all_cross_attentions,
1448
+ router_probs=all_router_probs,
1449
+ )
1450
+
1451
+
1452
+ @add_start_docstrings(
1453
+ "The bare NllbMoe Model outputting raw hidden-states without any specific head on top.",
1454
+ NLLB_MOE_START_DOCSTRING,
1455
+ )
1456
+ class NllbMoeModel(NllbMoePreTrainedModel):
1457
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1458
+
1459
+ def __init__(self, config: NllbMoeConfig):
1460
+ super().__init__(config)
1461
+
1462
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
1463
+ self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
1464
+
1465
+ self.encoder = NllbMoeEncoder(config, self.shared)
1466
+ self.decoder = NllbMoeDecoder(config, self.shared)
1467
+
1468
+ # Initialize weights and apply final processing
1469
+ self.post_init()
1470
+
1471
+ def get_input_embeddings(self):
1472
+ return self.shared
1473
+
1474
+ def set_input_embeddings(self, value):
1475
+ self.shared = value
1476
+ self.encoder.embed_tokens = self.shared
1477
+ self.decoder.embed_tokens = self.shared
1478
+
1479
+ def _tie_weights(self):
1480
+ if self.config.tie_word_embeddings:
1481
+ self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared)
1482
+ self._tie_or_clone_weights(self.decoder.embed_tokens, self.shared)
1483
+
1484
+ def get_encoder(self):
1485
+ return self.encoder
1486
+
1487
+ def get_decoder(self):
1488
+ return self.decoder
1489
+
1490
+ @add_start_docstrings_to_model_forward(NLLB_MOE_INPUTS_DOCSTRING)
1491
+ @add_start_docstrings_to_model_forward(NLLB_MOE_INPUTS_DOCSTRING)
1492
+ @replace_return_docstrings(output_type=Seq2SeqMoEModelOutput, config_class=_CONFIG_FOR_DOC)
1493
+ def forward(
1494
+ self,
1495
+ input_ids: Optional[torch.LongTensor] = None,
1496
+ attention_mask: Optional[torch.Tensor] = None,
1497
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1498
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1499
+ head_mask: Optional[torch.Tensor] = None,
1500
+ decoder_head_mask: Optional[torch.Tensor] = None,
1501
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1502
+ encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1503
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1504
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1505
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1506
+ use_cache: Optional[bool] = None,
1507
+ output_attentions: Optional[bool] = None,
1508
+ output_hidden_states: Optional[bool] = None,
1509
+ output_router_logits: Optional[bool] = None,
1510
+ return_dict: Optional[bool] = None,
1511
+ ) -> Union[Tuple[torch.Tensor], Seq2SeqMoEModelOutput]:
1512
+ r"""
1513
+ Returns:
1514
+
1515
+ Example:
1516
+
1517
+ ```python
1518
+ >>> from transformers import AutoTokenizer, NllbMoeModel
1519
+
1520
+ >>> tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/random-nllb-moe-2-experts")
1521
+ >>> model = SwitchTransformersModel.from_pretrained("hf-internal-testing/random-nllb-moe-2-experts")
1522
+
1523
+ >>> input_ids = tokenizer(
1524
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
1525
+ ... ).input_ids # Batch size 1
1526
+ >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1
1527
+
1528
+ >>> # preprocess: Prepend decoder_input_ids with start token which is pad token for NllbMoeModel
1529
+ >>> decoder_input_ids = model._shift_right(decoder_input_ids)
1530
+
1531
+ >>> # forward pass
1532
+ >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
1533
+ >>> last_hidden_states = outputs.last_hidden_state
1534
+ ```"""
1535
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1536
+ if encoder_outputs is None:
1537
+ encoder_outputs = self.encoder(
1538
+ input_ids=input_ids,
1539
+ attention_mask=attention_mask,
1540
+ head_mask=head_mask,
1541
+ inputs_embeds=inputs_embeds,
1542
+ output_attentions=output_attentions,
1543
+ output_hidden_states=output_hidden_states,
1544
+ output_router_logits=output_router_logits,
1545
+ return_dict=return_dict,
1546
+ )
1547
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1548
+ elif return_dict and not isinstance(encoder_outputs, MoEModelOutput):
1549
+ encoder_outputs = MoEModelOutput(
1550
+ last_hidden_state=encoder_outputs[0],
1551
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1552
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1553
+ router_probs=encoder_outputs[3] if len(encoder_outputs) > 3 else None,
1554
+ )
1555
+
1556
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
1557
+ decoder_outputs = self.decoder(
1558
+ input_ids=decoder_input_ids,
1559
+ attention_mask=decoder_attention_mask,
1560
+ encoder_hidden_states=encoder_outputs[0],
1561
+ encoder_attention_mask=attention_mask,
1562
+ head_mask=decoder_head_mask,
1563
+ cross_attn_head_mask=cross_attn_head_mask,
1564
+ past_key_values=past_key_values,
1565
+ inputs_embeds=decoder_inputs_embeds,
1566
+ use_cache=use_cache,
1567
+ output_attentions=output_attentions,
1568
+ output_hidden_states=output_hidden_states,
1569
+ output_router_logits=output_router_logits,
1570
+ return_dict=return_dict,
1571
+ )
1572
+
1573
+ if not return_dict:
1574
+ return decoder_outputs + encoder_outputs
1575
+
1576
+ return Seq2SeqMoEModelOutput(
1577
+ past_key_values=decoder_outputs.past_key_values,
1578
+ cross_attentions=decoder_outputs.cross_attentions,
1579
+ last_hidden_state=decoder_outputs.last_hidden_state,
1580
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1581
+ encoder_hidden_states=encoder_outputs.hidden_states,
1582
+ decoder_hidden_states=decoder_outputs.hidden_states,
1583
+ encoder_attentions=encoder_outputs.attentions,
1584
+ decoder_attentions=decoder_outputs.attentions,
1585
+ encoder_router_logits=encoder_outputs.router_probs,
1586
+ decoder_router_logits=decoder_outputs.router_probs,
1587
+ )
1588
+
1589
+
1590
+ @add_start_docstrings(
1591
+ "The NllbMoe Model with a language modeling head. Can be used for summarization.", NLLB_MOE_START_DOCSTRING
1592
+ )
1593
+ class NllbMoeForConditionalGeneration(NllbMoePreTrainedModel):
1594
+ base_model_prefix = "model"
1595
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight", "lm_head.weight"]
1596
+
1597
+ def __init__(self, config: NllbMoeConfig):
1598
+ super().__init__(config)
1599
+ self.model = NllbMoeModel(config)
1600
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
1601
+
1602
+ self.router_z_loss_coef = config.router_z_loss_coef
1603
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1604
+ # Initialize weights and apply final processing
1605
+ self.post_init()
1606
+
1607
+ def get_encoder(self):
1608
+ return self.model.get_encoder()
1609
+
1610
+ def get_decoder(self):
1611
+ return self.model.get_decoder()
1612
+
1613
+ def get_output_embeddings(self):
1614
+ return self.lm_head
1615
+
1616
+ def set_output_embeddings(self, new_embeddings):
1617
+ self.lm_head = new_embeddings
1618
+
1619
+ @add_start_docstrings_to_model_forward(NLLB_MOE_INPUTS_DOCSTRING)
1620
+ @replace_return_docstrings(output_type=Seq2SeqMoEOutput, config_class=_CONFIG_FOR_DOC)
1621
+ @add_end_docstrings(NLLB_MOE_GENERATION_EXAMPLE)
1622
+ def forward(
1623
+ self,
1624
+ input_ids: Optional[torch.LongTensor] = None,
1625
+ attention_mask: Optional[torch.Tensor] = None,
1626
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1627
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1628
+ head_mask: Optional[torch.Tensor] = None,
1629
+ decoder_head_mask: Optional[torch.Tensor] = None,
1630
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1631
+ encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1632
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1633
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1634
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1635
+ labels: Optional[torch.LongTensor] = None,
1636
+ use_cache: Optional[bool] = None,
1637
+ output_attentions: Optional[bool] = None,
1638
+ output_hidden_states: Optional[bool] = None,
1639
+ output_router_logits: Optional[bool] = None,
1640
+ return_dict: Optional[bool] = None,
1641
+ ) -> Union[Tuple[torch.Tensor], Seq2SeqMoEOutput]:
1642
+ r"""
1643
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1644
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1645
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1646
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1647
+
1648
+ Returns:
1649
+ """
1650
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1651
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1652
+ output_router_logits = (
1653
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1654
+ )
1655
+ if labels is not None:
1656
+ if decoder_input_ids is None:
1657
+ decoder_input_ids = shift_tokens_right(
1658
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1659
+ )
1660
+
1661
+ outputs = self.model(
1662
+ input_ids,
1663
+ attention_mask=attention_mask,
1664
+ decoder_input_ids=decoder_input_ids,
1665
+ encoder_outputs=encoder_outputs,
1666
+ decoder_attention_mask=decoder_attention_mask,
1667
+ head_mask=head_mask,
1668
+ decoder_head_mask=decoder_head_mask,
1669
+ cross_attn_head_mask=cross_attn_head_mask,
1670
+ past_key_values=past_key_values,
1671
+ inputs_embeds=inputs_embeds,
1672
+ decoder_inputs_embeds=decoder_inputs_embeds,
1673
+ use_cache=use_cache,
1674
+ output_attentions=output_attentions,
1675
+ output_hidden_states=output_hidden_states,
1676
+ output_router_logits=output_router_logits,
1677
+ return_dict=return_dict,
1678
+ )
1679
+ lm_logits = self.lm_head(outputs[0])
1680
+
1681
+ loss = None
1682
+ encoder_aux_loss = None
1683
+ decoder_aux_loss = None
1684
+
1685
+ if labels is not None:
1686
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1687
+ # todo check in the config if router loss enables
1688
+
1689
+ if output_router_logits:
1690
+ encoder_router_logits = outputs[-1]
1691
+ decoder_router_logits = outputs[3 if output_attentions else 4]
1692
+
1693
+ # Compute the router loss (z_loss + auxiliary loss) for each router in the encoder and decoder
1694
+ encoder_router_logits, encoder_expert_indexes = self._unpack_router_logits(encoder_router_logits)
1695
+ encoder_aux_loss = load_balancing_loss_func(encoder_router_logits, encoder_expert_indexes)
1696
+
1697
+ decoder_router_logits, decoder_expert_indexes = self._unpack_router_logits(decoder_router_logits)
1698
+ decoder_aux_loss = load_balancing_loss_func(decoder_router_logits, decoder_expert_indexes)
1699
+
1700
+ loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
1701
+
1702
+ if output_router_logits and labels is not None:
1703
+ aux_loss = self.router_aux_loss_coef * (encoder_aux_loss + decoder_aux_loss)
1704
+ loss = loss + aux_loss
1705
+
1706
+ output = (loss,) if loss is not None else ()
1707
+ if not return_dict:
1708
+ output += (lm_logits,)
1709
+ if output_router_logits: # only return the loss if they are not None
1710
+ output += (
1711
+ encoder_aux_loss,
1712
+ decoder_aux_loss,
1713
+ *outputs[1:],
1714
+ )
1715
+ else:
1716
+ output += outputs[1:]
1717
+
1718
+ return output
1719
+
1720
+ return Seq2SeqMoEOutput(
1721
+ loss=loss,
1722
+ logits=lm_logits,
1723
+ past_key_values=outputs.past_key_values,
1724
+ cross_attentions=outputs.cross_attentions,
1725
+ encoder_aux_loss=encoder_aux_loss,
1726
+ decoder_aux_loss=decoder_aux_loss,
1727
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1728
+ encoder_hidden_states=outputs.encoder_hidden_states,
1729
+ decoder_hidden_states=outputs.decoder_hidden_states,
1730
+ encoder_attentions=outputs.encoder_attentions,
1731
+ decoder_attentions=outputs.decoder_attentions,
1732
+ encoder_router_logits=outputs.encoder_router_logits,
1733
+ decoder_router_logits=outputs.decoder_router_logits,
1734
+ )
1735
+
1736
+ def _unpack_router_logits(self, router_outputs):
1737
+ total_router_logits = []
1738
+ total_expert_indexes = []
1739
+ for router_output in router_outputs:
1740
+ if router_output is not None:
1741
+ router_logits, expert_indexes = router_output
1742
+ total_router_logits.append(router_logits)
1743
+ total_expert_indexes.append(expert_indexes)
1744
+
1745
+ total_router_logits = torch.cat(total_router_logits, dim=1) if len(total_router_logits) > 0 else None
1746
+ total_expert_indexes = torch.stack(total_expert_indexes, dim=1) if len(total_expert_indexes) > 0 else None
1747
+ return total_router_logits, total_expert_indexes
1748
+
1749
+ # Copied from transfomers.models.switch_transformers.SwitchTransformersForConditionalGeneration.prepare_inputs_for_generation
1750
+ def prepare_inputs_for_generation(
1751
+ self,
1752
+ decoder_input_ids,
1753
+ past_key_values=None,
1754
+ attention_mask=None,
1755
+ head_mask=None,
1756
+ decoder_head_mask=None,
1757
+ cross_attn_head_mask=None,
1758
+ use_cache=None,
1759
+ encoder_outputs=None,
1760
+ **kwargs,
1761
+ ):
1762
+ # cut decoder_input_ids if past is used
1763
+ if past_key_values is not None:
1764
+ past_length = past_key_values[0][0].shape[2]
1765
+
1766
+ # Some generation methods already pass only the last input ID
1767
+ if decoder_input_ids.shape[1] > past_length:
1768
+ remove_prefix_length = past_length
1769
+ else:
1770
+ # Default to old behavior: keep only final ID
1771
+ remove_prefix_length = decoder_input_ids.shape[1] - 1
1772
+
1773
+ decoder_input_ids = decoder_input_ids[:, remove_prefix_length:]
1774
+
1775
+ return {
1776
+ "input_ids": None, # encoder_outputs is defined. input_ids not needed
1777
+ "encoder_outputs": encoder_outputs,
1778
+ "past_key_values": past_key_values,
1779
+ "decoder_input_ids": decoder_input_ids,
1780
+ "attention_mask": attention_mask,
1781
+ "head_mask": head_mask,
1782
+ "decoder_head_mask": decoder_head_mask,
1783
+ "cross_attn_head_mask": cross_attn_head_mask,
1784
+ "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
1785
+ }
1786
+
1787
+ @staticmethod
1788
+ def _reorder_cache(past_key_values, beam_idx):
1789
+ reordered_past = ()
1790
+ for layer_past in past_key_values:
1791
+ reordered_past += (
1792
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1793
+ )
1794
+ return reordered_past
pllava/lib/python3.10/site-packages/transformers/models/qdqbert/__init__.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 NVIDIA Corporation and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
17
+
18
+
19
+ _import_structure = {"configuration_qdqbert": ["QDQBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "QDQBertConfig"]}
20
+
21
+ try:
22
+ if not is_torch_available():
23
+ raise OptionalDependencyNotAvailable()
24
+ except OptionalDependencyNotAvailable:
25
+ pass
26
+ else:
27
+ _import_structure["modeling_qdqbert"] = [
28
+ "QDQBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
29
+ "QDQBertForMaskedLM",
30
+ "QDQBertForMultipleChoice",
31
+ "QDQBertForNextSentencePrediction",
32
+ "QDQBertForQuestionAnswering",
33
+ "QDQBertForSequenceClassification",
34
+ "QDQBertForTokenClassification",
35
+ "QDQBertLayer",
36
+ "QDQBertLMHeadModel",
37
+ "QDQBertModel",
38
+ "QDQBertPreTrainedModel",
39
+ "load_tf_weights_in_qdqbert",
40
+ ]
41
+
42
+
43
+ if TYPE_CHECKING:
44
+ from .configuration_qdqbert import QDQBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, QDQBertConfig
45
+
46
+ try:
47
+ if not is_torch_available():
48
+ raise OptionalDependencyNotAvailable()
49
+ except OptionalDependencyNotAvailable:
50
+ pass
51
+ else:
52
+ from .modeling_qdqbert import (
53
+ QDQBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
54
+ QDQBertForMaskedLM,
55
+ QDQBertForMultipleChoice,
56
+ QDQBertForNextSentencePrediction,
57
+ QDQBertForQuestionAnswering,
58
+ QDQBertForSequenceClassification,
59
+ QDQBertForTokenClassification,
60
+ QDQBertLayer,
61
+ QDQBertLMHeadModel,
62
+ QDQBertModel,
63
+ QDQBertPreTrainedModel,
64
+ load_tf_weights_in_qdqbert,
65
+ )
66
+
67
+
68
+ else:
69
+ import sys
70
+
71
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
pllava/lib/python3.10/site-packages/transformers/models/qdqbert/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.19 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/qdqbert/__pycache__/configuration_qdqbert.cpython-310.pyc ADDED
Binary file (5.07 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/qdqbert/__pycache__/modeling_qdqbert.cpython-310.pyc ADDED
Binary file (48.7 kB). View file
 
pllava/lib/python3.10/site-packages/transformers/models/qdqbert/configuration_qdqbert.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 NVIDIA Corporation 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
+ """ QDQBERT model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ QDQBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/config.json",
25
+ # QDQBERT models can be loaded from any BERT checkpoint, available at https://huggingface.co/models?filter=bert
26
+ }
27
+
28
+
29
+ class QDQBertConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`QDQBertModel`]. It is used to instantiate an
32
+ QDQBERT model according to the specified arguments, defining the model architecture. Instantiating a configuration
33
+ with the defaults will yield a similar configuration to that of the BERT
34
+ [bert-base-uncased](https://huggingface.co/bert-base-uncased) architecture.
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 30522):
42
+ Vocabulary size of the QDQBERT model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`QDQBertModel`].
44
+ hidden_size (`int`, *optional*, defaults to 768):
45
+ Dimension of the encoder layers and the pooler layer.
46
+ num_hidden_layers (`int`, *optional*, defaults to 12):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 12):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ intermediate_size (`int`, *optional*, defaults to 3072):
51
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
52
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
53
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
55
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
56
+ The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
57
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
58
+ The dropout ratio for the attention probabilities.
59
+ max_position_embeddings (`int`, *optional*, defaults to 512):
60
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
61
+ just in case (e.g., 512 or 1024 or 2048).
62
+ type_vocab_size (`int`, *optional*, defaults to 2):
63
+ The vocabulary size of the `token_type_ids` passed when calling [`QDQBertModel`].
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
67
+ The epsilon used by the layer normalization layers.
68
+ is_decoder (`bool`, *optional*, defaults to `False`):
69
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
70
+ use_cache (`bool`, *optional*, defaults to `True`):
71
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
72
+ relevant if `config.is_decoder=True`.
73
+
74
+ Examples:
75
+
76
+ ```python
77
+ >>> from transformers import QDQBertModel, QDQBertConfig
78
+
79
+ >>> # Initializing a QDQBERT bert-base-uncased style configuration
80
+ >>> configuration = QDQBertConfig()
81
+
82
+ >>> # Initializing a model from the bert-base-uncased style configuration
83
+ >>> model = QDQBertModel(configuration)
84
+
85
+ >>> # Accessing the model configuration
86
+ >>> configuration = model.config
87
+ ```"""
88
+
89
+ model_type = "qdqbert"
90
+
91
+ def __init__(
92
+ self,
93
+ vocab_size=30522,
94
+ hidden_size=768,
95
+ num_hidden_layers=12,
96
+ num_attention_heads=12,
97
+ intermediate_size=3072,
98
+ hidden_act="gelu",
99
+ hidden_dropout_prob=0.1,
100
+ attention_probs_dropout_prob=0.1,
101
+ max_position_embeddings=512,
102
+ type_vocab_size=2,
103
+ initializer_range=0.02,
104
+ layer_norm_eps=1e-12,
105
+ use_cache=True,
106
+ pad_token_id=1,
107
+ bos_token_id=0,
108
+ eos_token_id=2,
109
+ **kwargs,
110
+ ):
111
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
112
+
113
+ self.vocab_size = vocab_size
114
+ self.max_position_embeddings = max_position_embeddings
115
+ self.hidden_size = hidden_size
116
+ self.num_hidden_layers = num_hidden_layers
117
+ self.num_attention_heads = num_attention_heads
118
+ self.intermediate_size = intermediate_size
119
+ self.hidden_act = hidden_act
120
+ self.hidden_dropout_prob = hidden_dropout_prob
121
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
122
+ self.initializer_range = initializer_range
123
+ self.type_vocab_size = type_vocab_size
124
+ self.layer_norm_eps = layer_norm_eps
125
+ self.use_cache = use_cache