assassinlike commited on
Commit
2b4ce58
·
verified ·
1 Parent(s): 587969a

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. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/__pycache__/__init__.cpython-310.pyc +0 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/__pycache__/configuration_colpali.cpython-310.pyc +0 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/__pycache__/modeling_colpali.cpython-310.pyc +0 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/__pycache__/modular_colpali.cpython-310.pyc +0 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/__pycache__/processing_colpali.cpython-310.pyc +0 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/cpm/__pycache__/__init__.cpython-310.pyc +0 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm.cpython-310.pyc +0 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm_fast.cpython-310.pyc +0 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/bort/__init__.py +0 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/efficientformer/__init__.py +29 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/efficientformer/configuration_efficientformer.py +170 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/efficientformer/image_processing_efficientformer.py +324 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/efficientformer/modeling_efficientformer.py +786 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/efficientformer/modeling_tf_efficientformer.py +1198 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/ernie_m/__init__.py +28 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/ernie_m/configuration_ernie_m.py +112 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/ernie_m/modeling_ernie_m.py +1061 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/ernie_m/tokenization_ernie_m.py +409 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/gptsan_japanese/configuration_gptsan_japanese.py +157 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/gptsan_japanese/modeling_gptsan_japanese.py +1331 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/gptsan_japanese/tokenization_gptsan_japanese.py +518 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/graphormer/__init__.py +27 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/graphormer/algos_graphormer.pyx +107 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/graphormer/collating_graphormer.py +135 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/graphormer/configuration_graphormer.py +220 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/graphormer/modeling_graphormer.py +912 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mctct/__init__.py +29 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mctct/configuration_mctct.py +184 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mctct/feature_extraction_mctct.py +291 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mctct/modeling_mctct.py +778 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mctct/processing_mctct.py +139 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mega/__init__.py +27 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mega/configuration_mega.py +243 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mega/modeling_mega.py +0 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/nezha/__init__.py +27 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/nezha/configuration_nezha.py +105 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/nezha/modeling_nezha.py +1689 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/open_llama/__init__.py +27 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/open_llama/configuration_open_llama.py +169 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/open_llama/modeling_open_llama.py +940 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/qdqbert/__init__.py +27 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/qdqbert/configuration_qdqbert.py +123 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/qdqbert/modeling_qdqbert.py +1736 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/retribert/__init__.py +29 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/retribert/configuration_retribert.py +108 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/retribert/modeling_retribert.py +217 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/retribert/tokenization_retribert.py +475 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/retribert/tokenization_retribert_fast.py +150 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/__init__.py +29 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/configuration_speech_to_text_2.py +134 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (593 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/__pycache__/configuration_colpali.cpython-310.pyc ADDED
Binary file (3.44 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/__pycache__/modeling_colpali.cpython-310.pyc ADDED
Binary file (7.34 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/__pycache__/modular_colpali.cpython-310.pyc ADDED
Binary file (13.8 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/colpali/__pycache__/processing_colpali.cpython-310.pyc ADDED
Binary file (16.2 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/cpm/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (559 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm_fast.cpython-310.pyc ADDED
Binary file (9.12 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/bort/__init__.py ADDED
File without changes
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/efficientformer/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ....utils import _LazyModule
17
+ from ....utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_efficientformer import *
22
+ from .image_processing_efficientformer import *
23
+ from .modeling_efficientformer import *
24
+ from .modeling_tf_efficientformer import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/efficientformer/configuration_efficientformer.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """EfficientFormer model configuration"""
16
+
17
+ from ....configuration_utils import PretrainedConfig
18
+ from ....utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class EfficientFormerConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of an [`EfficientFormerModel`]. It is used to
27
+ instantiate an EfficientFormer model according to the specified arguments, defining the model architecture.
28
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the EfficientFormer
29
+ [snap-research/efficientformer-l1](https://huggingface.co/snap-research/efficientformer-l1) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ depths (`List(int)`, *optional*, defaults to `[3, 2, 6, 4]`)
36
+ Depth of each stage.
37
+ hidden_sizes (`List(int)`, *optional*, defaults to `[48, 96, 224, 448]`)
38
+ Dimensionality of each stage.
39
+ downsamples (`List(bool)`, *optional*, defaults to `[True, True, True, True]`)
40
+ Whether or not to downsample inputs between two stages.
41
+ dim (`int`, *optional*, defaults to 448):
42
+ Number of channels in Meta3D layers
43
+ key_dim (`int`, *optional*, defaults to 32):
44
+ The size of the key in meta3D block.
45
+ attention_ratio (`int`, *optional*, defaults to 4):
46
+ Ratio of the dimension of the query and value to the dimension of the key in MSHA block
47
+ resolution (`int`, *optional*, defaults to 7)
48
+ Size of each patch
49
+ num_hidden_layers (`int`, *optional*, defaults to 5):
50
+ Number of hidden layers in the Transformer encoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 8):
52
+ Number of attention heads for each attention layer in the 3D MetaBlock.
53
+ mlp_expansion_ratio (`int`, *optional*, defaults to 4):
54
+ Ratio of size of the hidden dimensionality of an MLP to the dimensionality of its input.
55
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
56
+ The dropout probability for all fully connected layers in the embeddings and encoder.
57
+ patch_size (`int`, *optional*, defaults to 16):
58
+ The size (resolution) of each patch.
59
+ num_channels (`int`, *optional*, defaults to 3):
60
+ The number of input channels.
61
+ pool_size (`int`, *optional*, defaults to 3):
62
+ Kernel size of pooling layers.
63
+ downsample_patch_size (`int`, *optional*, defaults to 3):
64
+ The size of patches in downsampling layers.
65
+ downsample_stride (`int`, *optional*, defaults to 2):
66
+ The stride of convolution kernels in downsampling layers.
67
+ downsample_pad (`int`, *optional*, defaults to 1):
68
+ Padding in downsampling layers.
69
+ drop_path_rate (`int`, *optional*, defaults to 0):
70
+ Rate at which to increase dropout probability in DropPath.
71
+ num_meta3d_blocks (`int`, *optional*, defaults to 1):
72
+ The number of 3D MetaBlocks in the last stage.
73
+ distillation (`bool`, *optional*, defaults to `True`):
74
+ Whether to add a distillation head.
75
+ use_layer_scale (`bool`, *optional*, defaults to `True`):
76
+ Whether to scale outputs from token mixers.
77
+ layer_scale_init_value (`float`, *optional*, defaults to 1e-5):
78
+ Factor by which outputs from token mixers are scaled.
79
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
80
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
81
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
82
+ initializer_range (`float`, *optional*, defaults to 0.02):
83
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
84
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
85
+ The epsilon used by the layer normalization layers.
86
+ image_size (`int`, *optional*, defaults to `224`):
87
+ The size (resolution) of each image.
88
+
89
+ Example:
90
+
91
+ ```python
92
+ >>> from transformers import EfficientFormerConfig, EfficientFormerModel
93
+
94
+ >>> # Initializing a EfficientFormer efficientformer-l1 style configuration
95
+ >>> configuration = EfficientFormerConfig()
96
+
97
+ >>> # Initializing a EfficientFormerModel (with random weights) from the efficientformer-l3 style configuration
98
+ >>> model = EfficientFormerModel(configuration)
99
+
100
+ >>> # Accessing the model configuration
101
+ >>> configuration = model.config
102
+ ```"""
103
+
104
+ model_type = "efficientformer"
105
+
106
+ def __init__(
107
+ self,
108
+ depths: list[int] = [3, 2, 6, 4],
109
+ hidden_sizes: list[int] = [48, 96, 224, 448],
110
+ downsamples: list[bool] = [True, True, True, True],
111
+ dim: int = 448,
112
+ key_dim: int = 32,
113
+ attention_ratio: int = 4,
114
+ resolution: int = 7,
115
+ num_hidden_layers: int = 5,
116
+ num_attention_heads: int = 8,
117
+ mlp_expansion_ratio: int = 4,
118
+ hidden_dropout_prob: float = 0.0,
119
+ patch_size: int = 16,
120
+ num_channels: int = 3,
121
+ pool_size: int = 3,
122
+ downsample_patch_size: int = 3,
123
+ downsample_stride: int = 2,
124
+ downsample_pad: int = 1,
125
+ drop_path_rate: float = 0.0,
126
+ num_meta3d_blocks: int = 1,
127
+ distillation: bool = True,
128
+ use_layer_scale: bool = True,
129
+ layer_scale_init_value: float = 1e-5,
130
+ hidden_act: str = "gelu",
131
+ initializer_range: float = 0.02,
132
+ layer_norm_eps: float = 1e-12,
133
+ image_size: int = 224,
134
+ batch_norm_eps: float = 1e-05,
135
+ **kwargs,
136
+ ) -> None:
137
+ super().__init__(**kwargs)
138
+
139
+ self.hidden_act = hidden_act
140
+ self.hidden_dropout_prob = hidden_dropout_prob
141
+ self.hidden_sizes = hidden_sizes
142
+ self.num_hidden_layers = num_hidden_layers
143
+ self.num_attention_heads = num_attention_heads
144
+ self.initializer_range = initializer_range
145
+ self.layer_norm_eps = layer_norm_eps
146
+ self.patch_size = patch_size
147
+ self.num_channels = num_channels
148
+ self.depths = depths
149
+ self.mlp_expansion_ratio = mlp_expansion_ratio
150
+ self.downsamples = downsamples
151
+ self.dim = dim
152
+ self.key_dim = key_dim
153
+ self.attention_ratio = attention_ratio
154
+ self.resolution = resolution
155
+ self.pool_size = pool_size
156
+ self.downsample_patch_size = downsample_patch_size
157
+ self.downsample_stride = downsample_stride
158
+ self.downsample_pad = downsample_pad
159
+ self.drop_path_rate = drop_path_rate
160
+ self.num_meta3d_blocks = num_meta3d_blocks
161
+ self.distillation = distillation
162
+ self.use_layer_scale = use_layer_scale
163
+ self.layer_scale_init_value = layer_scale_init_value
164
+ self.image_size = image_size
165
+ self.batch_norm_eps = batch_norm_eps
166
+
167
+
168
+ __all__ = [
169
+ "EfficientFormerConfig",
170
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/efficientformer/image_processing_efficientformer.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Image processor class for EfficientFormer."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ....image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ....image_transforms import (
23
+ get_resize_output_image_size,
24
+ resize,
25
+ to_channel_dimension_format,
26
+ )
27
+ from ....image_utils import (
28
+ IMAGENET_DEFAULT_MEAN,
29
+ IMAGENET_DEFAULT_STD,
30
+ ChannelDimension,
31
+ ImageInput,
32
+ PILImageResampling,
33
+ infer_channel_dimension_format,
34
+ is_batched,
35
+ is_scaled_image,
36
+ to_numpy_array,
37
+ valid_images,
38
+ validate_kwargs,
39
+ validate_preprocess_arguments,
40
+ )
41
+ from ....utils import TensorType, logging
42
+
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+
47
+ class EfficientFormerImageProcessor(BaseImageProcessor):
48
+ r"""
49
+ Constructs a EfficientFormer image processor.
50
+
51
+ Args:
52
+ do_resize (`bool`, *optional*, defaults to `True`):
53
+ Whether to resize the image's (height, width) dimensions to the specified `(size["height"],
54
+ size["width"])`. Can be overridden by the `do_resize` parameter in the `preprocess` method.
55
+ size (`dict`, *optional*, defaults to `{"height": 224, "width": 224}`):
56
+ Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
57
+ method.
58
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
59
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
60
+ `preprocess` method.
61
+ do_center_crop (`bool`, *optional*, defaults to `True`):
62
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
63
+ `preprocess` method.
64
+ crop_size (`dict[str, int]` *optional*, defaults to 224):
65
+ Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
66
+ method.
67
+ do_rescale (`bool`, *optional*, defaults to `True`):
68
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
69
+ parameter in the `preprocess` method.
70
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
71
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
72
+ `preprocess` method.
73
+ do_normalize:
74
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
75
+ method.
76
+ image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
77
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
78
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
79
+ image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
80
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
81
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
82
+ """
83
+
84
+ model_input_names = ["pixel_values"]
85
+
86
+ def __init__(
87
+ self,
88
+ do_resize: bool = True,
89
+ size: Optional[dict[str, int]] = None,
90
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
91
+ do_center_crop: bool = True,
92
+ do_rescale: bool = True,
93
+ rescale_factor: Union[int, float] = 1 / 255,
94
+ crop_size: Optional[dict[str, int]] = None,
95
+ do_normalize: bool = True,
96
+ image_mean: Optional[Union[float, list[float]]] = None,
97
+ image_std: Optional[Union[float, list[float]]] = None,
98
+ **kwargs,
99
+ ) -> None:
100
+ super().__init__(**kwargs)
101
+ size = size if size is not None else {"height": 224, "width": 224}
102
+ size = get_size_dict(size)
103
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
104
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
105
+
106
+ self.do_resize = do_resize
107
+ self.do_rescale = do_rescale
108
+ self.do_normalize = do_normalize
109
+ self.do_center_crop = do_center_crop
110
+ self.crop_size = crop_size
111
+ self.size = size
112
+ self.resample = resample
113
+ self.rescale_factor = rescale_factor
114
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
115
+ self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
116
+ self._valid_processor_keys = [
117
+ "images",
118
+ "do_resize",
119
+ "size",
120
+ "resample",
121
+ "do_center_crop",
122
+ "crop_size",
123
+ "do_rescale",
124
+ "rescale_factor",
125
+ "do_normalize",
126
+ "image_mean",
127
+ "image_std",
128
+ "return_tensors",
129
+ "data_format",
130
+ "input_data_format",
131
+ ]
132
+
133
+ def resize(
134
+ self,
135
+ image: np.ndarray,
136
+ size: dict[str, int],
137
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
138
+ data_format: Optional[Union[str, ChannelDimension]] = None,
139
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
140
+ **kwargs,
141
+ ) -> np.ndarray:
142
+ """
143
+ Resize an image to `(size["height"], size["width"])`.
144
+
145
+ Args:
146
+ image (`np.ndarray`):
147
+ Image to resize.
148
+ size (`dict[str, int]`):
149
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
150
+ resample:
151
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
152
+ data_format (`ChannelDimension` or `str`, *optional*):
153
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
154
+ image is used. Can be one of:
155
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
156
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
157
+ input_data_format (`ChannelDimension` or `str`, *optional*):
158
+ The channel dimension format of the input image. If not provided, it will be inferred.
159
+
160
+ Returns:
161
+ `np.ndarray`: The resized image.
162
+ """
163
+ size = get_size_dict(size)
164
+
165
+ if "shortest_edge" in size:
166
+ size = get_resize_output_image_size(
167
+ image, size=size["shortest_edge"], default_to_square=False, input_data_format=input_data_format
168
+ )
169
+ # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
170
+ elif "height" in size and "width" in size:
171
+ size = (size["height"], size["width"])
172
+ else:
173
+ raise ValueError(f"Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}")
174
+ return resize(
175
+ image, size=size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs
176
+ )
177
+
178
+ def preprocess(
179
+ self,
180
+ images: ImageInput,
181
+ do_resize: Optional[bool] = None,
182
+ size: Optional[dict[str, int]] = None,
183
+ resample: Optional[PILImageResampling] = None,
184
+ do_center_crop: Optional[bool] = None,
185
+ crop_size: Optional[int] = None,
186
+ do_rescale: Optional[bool] = None,
187
+ rescale_factor: Optional[float] = None,
188
+ do_normalize: Optional[bool] = None,
189
+ image_mean: Optional[Union[float, list[float]]] = None,
190
+ image_std: Optional[Union[float, list[float]]] = None,
191
+ return_tensors: Optional[Union[str, TensorType]] = None,
192
+ data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
193
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
194
+ **kwargs,
195
+ ) -> BatchFeature:
196
+ """
197
+ Preprocess an image or batch of images.
198
+
199
+ Args:
200
+ images (`ImageInput`):
201
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
202
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
203
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
204
+ Whether to resize the image.
205
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
206
+ Dictionary in the format `{"height": h, "width": w}` specifying the size of the output image after
207
+ resizing.
208
+ resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):
209
+ `PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
210
+ an effect if `do_resize` is set to `True`.
211
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
212
+ Whether to center crop the image.
213
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
214
+ Whether to rescale the image values between [0 - 1].
215
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
216
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
217
+ crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
218
+ Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
219
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
220
+ Whether to normalize the image.
221
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
222
+ Image mean to use if `do_normalize` is set to `True`.
223
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
224
+ Image standard deviation to use if `do_normalize` is set to `True`.
225
+ return_tensors (`str` or `TensorType`, *optional*):
226
+ The type of tensors to return. Can be one of:
227
+ - Unset: Return a list of `np.ndarray`.
228
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
229
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
230
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
231
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
232
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
233
+ The channel dimension format for the output image. Can be one of:
234
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
235
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
236
+ - Unset: Use the channel dimension format of the input image.
237
+ input_data_format (`ChannelDimension` or `str`, *optional*):
238
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
239
+ from the input image. Can be one of:
240
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
241
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
242
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
243
+ """
244
+ do_resize = do_resize if do_resize is not None else self.do_resize
245
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
246
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
247
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
248
+ crop_size = crop_size if crop_size is not None else self.crop_size
249
+ crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
250
+ resample = resample if resample is not None else self.resample
251
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
252
+ image_mean = image_mean if image_mean is not None else self.image_mean
253
+ image_std = image_std if image_std is not None else self.image_std
254
+
255
+ size = size if size is not None else self.size
256
+ size_dict = get_size_dict(size)
257
+
258
+ validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
259
+
260
+ if not is_batched(images):
261
+ images = [images]
262
+
263
+ if not valid_images(images):
264
+ raise ValueError(
265
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
266
+ "torch.Tensor, tf.Tensor or jax.ndarray."
267
+ )
268
+ validate_preprocess_arguments(
269
+ do_rescale=do_rescale,
270
+ rescale_factor=rescale_factor,
271
+ do_normalize=do_normalize,
272
+ image_mean=image_mean,
273
+ image_std=image_std,
274
+ do_center_crop=do_center_crop,
275
+ crop_size=crop_size,
276
+ do_resize=do_resize,
277
+ size=size,
278
+ resample=resample,
279
+ )
280
+ # All transformations expect numpy arrays.
281
+ images = [to_numpy_array(image) for image in images]
282
+
283
+ if do_rescale and is_scaled_image(images[0]):
284
+ logger.warning_once(
285
+ "It looks like you are trying to rescale already rescaled images. If the input"
286
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
287
+ )
288
+
289
+ if input_data_format is None:
290
+ # We assume that all images have the same channel dimension format.
291
+ input_data_format = infer_channel_dimension_format(images[0])
292
+
293
+ if do_resize:
294
+ images = [
295
+ self.resize(image=image, size=size_dict, resample=resample, input_data_format=input_data_format)
296
+ for image in images
297
+ ]
298
+
299
+ if do_center_crop:
300
+ images = [
301
+ self.center_crop(image=image, size=crop_size, input_data_format=input_data_format) for image in images
302
+ ]
303
+
304
+ if do_rescale:
305
+ images = [
306
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
307
+ for image in images
308
+ ]
309
+
310
+ if do_normalize:
311
+ images = [
312
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
313
+ for image in images
314
+ ]
315
+
316
+ images = [
317
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
318
+ ]
319
+
320
+ data = {"pixel_values": images}
321
+ return BatchFeature(data=data, tensor_type=return_tensors)
322
+
323
+
324
+ __all__ = ["EfficientFormerImageProcessor"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/efficientformer/modeling_efficientformer.py ADDED
@@ -0,0 +1,786 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Snapchat 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 EfficientFormer model."""
16
+
17
+ import itertools
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Union
20
+
21
+ import torch
22
+ from torch import nn
23
+
24
+ from ....activations import ACT2FN
25
+ from ....modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
26
+ from ....modeling_utils import PreTrainedModel
27
+ from ....utils import (
28
+ ModelOutput,
29
+ add_code_sample_docstrings,
30
+ add_start_docstrings,
31
+ add_start_docstrings_to_model_forward,
32
+ logging,
33
+ )
34
+ from .configuration_efficientformer import EfficientFormerConfig
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ # General docstring
40
+ _CONFIG_FOR_DOC = "EfficientFormerConfig"
41
+
42
+ # Base docstring
43
+ _CHECKPOINT_FOR_DOC = "snap-research/efficientformer-l1-300"
44
+ _EXPECTED_OUTPUT_SHAPE = [1, 49, 448]
45
+
46
+ # Image classification docstring
47
+ _IMAGE_CLASS_CHECKPOINT = "snap-research/efficientformer-l1-300"
48
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "Egyptian cat"
49
+
50
+
51
+ class EfficientFormerPatchEmbeddings(nn.Module):
52
+ """
53
+ This class performs downsampling between two stages. For the input tensor with the shape [batch_size, num_channels,
54
+ height, width] it produces output tensor with the shape [batch_size, num_channels, height/stride, width/stride]
55
+ """
56
+
57
+ def __init__(self, config: EfficientFormerConfig, num_channels: int, embed_dim: int, apply_norm: bool = True):
58
+ super().__init__()
59
+ self.num_channels = num_channels
60
+
61
+ self.projection = nn.Conv2d(
62
+ num_channels,
63
+ embed_dim,
64
+ kernel_size=config.downsample_patch_size,
65
+ stride=config.downsample_stride,
66
+ padding=config.downsample_pad,
67
+ )
68
+ self.norm = nn.BatchNorm2d(embed_dim, eps=config.batch_norm_eps) if apply_norm else nn.Identity()
69
+
70
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
71
+ batch_size, num_channels, height, width = pixel_values.shape
72
+ if num_channels != self.num_channels:
73
+ raise ValueError(
74
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
75
+ )
76
+
77
+ embeddings = self.projection(pixel_values)
78
+ embeddings = self.norm(embeddings)
79
+
80
+ return embeddings
81
+
82
+
83
+ class EfficientFormerSelfAttention(nn.Module):
84
+ def __init__(self, dim: int, key_dim: int, num_heads: int, attention_ratio: int, resolution: int):
85
+ super().__init__()
86
+
87
+ self.num_heads = num_heads
88
+ self.key_dim = key_dim
89
+ self.attention_ratio = attention_ratio
90
+ self.scale = key_dim**-0.5
91
+ self.total_key_dim = key_dim * num_heads
92
+ self.expanded_key_dim = int(attention_ratio * key_dim)
93
+ self.total_expanded_key_dim = int(self.expanded_key_dim * num_heads)
94
+ hidden_size = self.total_expanded_key_dim + self.total_key_dim * 2
95
+ self.qkv = nn.Linear(dim, hidden_size)
96
+ self.projection = nn.Linear(self.total_expanded_key_dim, dim)
97
+ points = list(itertools.product(range(resolution), range(resolution)))
98
+ num_points = len(points)
99
+ attention_offsets = {}
100
+ idxs = []
101
+ for point_1 in points:
102
+ for point_2 in points:
103
+ offset = (abs(point_1[0] - point_2[0]), abs(point_1[1] - point_2[1]))
104
+ if offset not in attention_offsets:
105
+ attention_offsets[offset] = len(attention_offsets)
106
+ idxs.append(attention_offsets[offset])
107
+ self.attention_biases = torch.nn.Parameter(torch.zeros(num_heads, len(attention_offsets)))
108
+ self.register_buffer("attention_bias_idxs", torch.LongTensor(idxs).view(num_points, num_points))
109
+
110
+ @torch.no_grad()
111
+ def train(self, mode=True):
112
+ super().train(mode)
113
+ if mode and hasattr(self, "ab"):
114
+ del self.ab
115
+ else:
116
+ self.ab = self.attention_biases[:, self.attention_bias_idxs]
117
+
118
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> tuple[torch.Tensor]:
119
+ batch_size, sequence_length, num_channels = hidden_states.shape
120
+ qkv = self.qkv(hidden_states)
121
+ query_layer, key_layer, value_layer = qkv.reshape(batch_size, sequence_length, self.num_heads, -1).split(
122
+ [self.key_dim, self.key_dim, self.expanded_key_dim], dim=3
123
+ )
124
+ query_layer = query_layer.permute(0, 2, 1, 3)
125
+ key_layer = key_layer.permute(0, 2, 1, 3)
126
+ value_layer = value_layer.permute(0, 2, 1, 3)
127
+
128
+ # set `model.to(torch_device)` won't change `self.ab.device`, if there is no follow-up `train` or `eval` call.
129
+ # Let's do it manually here, so users won't have to do this everytime.
130
+ if not self.training:
131
+ self.ab = self.ab.to(self.attention_biases.device)
132
+ attention_probs = (torch.matmul(query_layer, key_layer.transpose(-2, -1))) * self.scale + (
133
+ self.attention_biases[:, self.attention_bias_idxs] if self.training else self.ab
134
+ )
135
+
136
+ attention_probs = attention_probs.softmax(dim=-1)
137
+
138
+ context_layer = torch.matmul(attention_probs, value_layer).transpose(1, 2)
139
+ context_layer = context_layer.reshape(batch_size, sequence_length, self.total_expanded_key_dim)
140
+ context_layer = self.projection(context_layer)
141
+
142
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
143
+
144
+ return outputs
145
+
146
+
147
+ class EfficientFormerConvStem(nn.Module):
148
+ def __init__(self, config: EfficientFormerConfig, out_channels: int):
149
+ super().__init__()
150
+
151
+ self.convolution1 = nn.Conv2d(config.num_channels, out_channels // 2, kernel_size=3, stride=2, padding=1)
152
+ self.batchnorm_before = nn.BatchNorm2d(out_channels // 2, eps=config.batch_norm_eps)
153
+
154
+ self.convolution2 = nn.Conv2d(out_channels // 2, out_channels, kernel_size=3, stride=2, padding=1)
155
+ self.batchnorm_after = nn.BatchNorm2d(out_channels, eps=config.batch_norm_eps)
156
+
157
+ self.activation = nn.ReLU()
158
+
159
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
160
+ features = self.batchnorm_before(self.convolution1(pixel_values))
161
+ features = self.activation(features)
162
+ features = self.batchnorm_after(self.convolution2(features))
163
+ features = self.activation(features)
164
+
165
+ return features
166
+
167
+
168
+ class EfficientFormerPooling(nn.Module):
169
+ def __init__(self, pool_size: int):
170
+ super().__init__()
171
+ self.pool = nn.AvgPool2d(pool_size, stride=1, padding=pool_size // 2, count_include_pad=False)
172
+
173
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
174
+ output = self.pool(hidden_states) - hidden_states
175
+ return output
176
+
177
+
178
+ class EfficientFormerDenseMlp(nn.Module):
179
+ def __init__(
180
+ self,
181
+ config: EfficientFormerConfig,
182
+ in_features: int,
183
+ hidden_features: Optional[int] = None,
184
+ out_features: Optional[int] = None,
185
+ ):
186
+ super().__init__()
187
+ out_features = out_features or in_features
188
+ hidden_features = hidden_features or in_features
189
+
190
+ self.linear_in = nn.Linear(in_features, hidden_features)
191
+ self.activation = ACT2FN[config.hidden_act]
192
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
193
+ self.linear_out = nn.Linear(hidden_features, out_features)
194
+
195
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
196
+ hidden_states = self.linear_in(hidden_states)
197
+ hidden_states = self.activation(hidden_states)
198
+ hidden_states = self.dropout(hidden_states)
199
+ hidden_states = self.linear_out(hidden_states)
200
+ hidden_states = self.dropout(hidden_states)
201
+
202
+ return hidden_states
203
+
204
+
205
+ class EfficientFormerConvMlp(nn.Module):
206
+ def __init__(
207
+ self,
208
+ config: EfficientFormerConfig,
209
+ in_features: int,
210
+ hidden_features: Optional[int] = None,
211
+ out_features: Optional[int] = None,
212
+ drop: float = 0.0,
213
+ ):
214
+ super().__init__()
215
+ out_features = out_features or in_features
216
+ hidden_features = hidden_features or in_features
217
+
218
+ self.convolution1 = nn.Conv2d(in_features, hidden_features, 1)
219
+ self.activation = ACT2FN[config.hidden_act]
220
+ self.convolution2 = nn.Conv2d(hidden_features, out_features, 1)
221
+ self.dropout = nn.Dropout(drop)
222
+
223
+ self.batchnorm_before = nn.BatchNorm2d(hidden_features, eps=config.batch_norm_eps)
224
+ self.batchnorm_after = nn.BatchNorm2d(out_features, eps=config.batch_norm_eps)
225
+
226
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
227
+ hidden_state = self.convolution1(hidden_state)
228
+ hidden_state = self.batchnorm_before(hidden_state)
229
+
230
+ hidden_state = self.activation(hidden_state)
231
+ hidden_state = self.dropout(hidden_state)
232
+ hidden_state = self.convolution2(hidden_state)
233
+
234
+ hidden_state = self.batchnorm_after(hidden_state)
235
+ hidden_state = self.dropout(hidden_state)
236
+
237
+ return hidden_state
238
+
239
+
240
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
241
+ """
242
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
243
+
244
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
245
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
246
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
247
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
248
+ argument.
249
+ """
250
+ if drop_prob == 0.0 or not training:
251
+ return input
252
+ keep_prob = 1 - drop_prob
253
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
254
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
255
+ random_tensor.floor_() # binarize
256
+ output = input.div(keep_prob) * random_tensor
257
+ return output
258
+
259
+
260
+ class EfficientFormerDropPath(nn.Module):
261
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
262
+
263
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
264
+ super().__init__()
265
+ self.drop_prob = drop_prob
266
+
267
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
268
+ return drop_path(hidden_states, self.drop_prob, self.training)
269
+
270
+ def extra_repr(self) -> str:
271
+ return f"p={self.drop_prob}"
272
+
273
+
274
+ class EfficientFormerFlat(nn.Module):
275
+ def __init__(self):
276
+ super().__init__()
277
+
278
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor]:
279
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
280
+ return hidden_states
281
+
282
+
283
+ class EfficientFormerMeta3D(nn.Module):
284
+ def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0):
285
+ super().__init__()
286
+
287
+ self.token_mixer = EfficientFormerSelfAttention(
288
+ dim=config.dim,
289
+ key_dim=config.key_dim,
290
+ num_heads=config.num_attention_heads,
291
+ attention_ratio=config.attention_ratio,
292
+ resolution=config.resolution,
293
+ )
294
+
295
+ self.layernorm1 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
296
+ self.layernorm2 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
297
+
298
+ mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
299
+ self.mlp = EfficientFormerDenseMlp(config, in_features=dim, hidden_features=mlp_hidden_dim)
300
+
301
+ self.drop_path = EfficientFormerDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
302
+ self.use_layer_scale = config.use_layer_scale
303
+ if config.use_layer_scale:
304
+ self.layer_scale_1 = nn.Parameter(config.layer_scale_init_value * torch.ones(dim), requires_grad=True)
305
+ self.layer_scale_2 = nn.Parameter(config.layer_scale_init_value * torch.ones(dim), requires_grad=True)
306
+
307
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> tuple[torch.Tensor]:
308
+ self_attention_outputs = self.token_mixer(self.layernorm1(hidden_states), output_attentions)
309
+ attention_output = self_attention_outputs[0]
310
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
311
+
312
+ if self.use_layer_scale:
313
+ layer_output = hidden_states + self.drop_path(
314
+ self.layer_scale_1.unsqueeze(0).unsqueeze(0) * attention_output
315
+ )
316
+ layer_output = layer_output + self.drop_path(
317
+ self.layer_scale_2.unsqueeze(0).unsqueeze(0) * self.mlp(self.layernorm2(layer_output))
318
+ )
319
+ else:
320
+ layer_output = hidden_states + self.drop_path(attention_output)
321
+ layer_output = layer_output + self.drop_path(self.mlp(self.layernorm2(layer_output)))
322
+
323
+ outputs = (layer_output,) + outputs
324
+
325
+ return outputs
326
+
327
+
328
+ class EfficientFormerMeta3DLayers(nn.Module):
329
+ def __init__(self, config: EfficientFormerConfig):
330
+ super().__init__()
331
+ drop_paths = [
332
+ config.drop_path_rate * (block_idx + sum(config.depths[:-1]))
333
+ for block_idx in range(config.num_meta3d_blocks)
334
+ ]
335
+ self.blocks = nn.ModuleList(
336
+ [EfficientFormerMeta3D(config, config.hidden_sizes[-1], drop_path=drop_path) for drop_path in drop_paths]
337
+ )
338
+
339
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> tuple[torch.Tensor]:
340
+ all_attention_outputs = () if output_attentions else None
341
+
342
+ for layer_module in self.blocks:
343
+ if isinstance(hidden_states, tuple):
344
+ hidden_states = hidden_states[0]
345
+
346
+ hidden_states = layer_module(hidden_states, output_attentions)
347
+
348
+ if output_attentions:
349
+ all_attention_outputs = all_attention_outputs + (hidden_states[1],)
350
+
351
+ if output_attentions:
352
+ outputs = (hidden_states[0],) + all_attention_outputs
353
+ return outputs
354
+
355
+ return hidden_states
356
+
357
+
358
+ class EfficientFormerMeta4D(nn.Module):
359
+ def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0):
360
+ super().__init__()
361
+ pool_size = config.pool_size if config.pool_size is not None else 3
362
+ self.token_mixer = EfficientFormerPooling(pool_size=pool_size)
363
+ mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
364
+ self.mlp = EfficientFormerConvMlp(
365
+ config, in_features=dim, hidden_features=mlp_hidden_dim, drop=config.hidden_dropout_prob
366
+ )
367
+
368
+ self.drop_path = EfficientFormerDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
369
+ self.use_layer_scale = config.use_layer_scale
370
+ if config.use_layer_scale:
371
+ self.layer_scale_1 = nn.Parameter(config.layer_scale_init_value * torch.ones(dim), requires_grad=True)
372
+ self.layer_scale_2 = nn.Parameter(config.layer_scale_init_value * torch.ones(dim), requires_grad=True)
373
+
374
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor]:
375
+ outputs = self.token_mixer(hidden_states)
376
+
377
+ if self.use_layer_scale:
378
+ layer_output = hidden_states + self.drop_path(self.layer_scale_1.unsqueeze(-1).unsqueeze(-1) * outputs)
379
+
380
+ layer_output = layer_output + self.drop_path(
381
+ self.layer_scale_2.unsqueeze(-1).unsqueeze(-1) * self.mlp(layer_output)
382
+ )
383
+ else:
384
+ layer_output = hidden_states + self.drop_path(outputs)
385
+ layer_output = layer_output + self.drop_path(self.mlp(layer_output))
386
+
387
+ return layer_output
388
+
389
+
390
+ class EfficientFormerMeta4DLayers(nn.Module):
391
+ def __init__(self, config: EfficientFormerConfig, stage_idx: int):
392
+ super().__init__()
393
+ num_layers = (
394
+ config.depths[stage_idx] if stage_idx != -1 else config.depths[stage_idx] - config.num_meta3d_blocks
395
+ )
396
+ drop_paths = [
397
+ config.drop_path_rate * (block_idx + sum(config.depths[:stage_idx])) for block_idx in range(num_layers)
398
+ ]
399
+
400
+ self.blocks = nn.ModuleList(
401
+ [
402
+ EfficientFormerMeta4D(config, config.hidden_sizes[stage_idx], drop_path=drop_path)
403
+ for drop_path in drop_paths
404
+ ]
405
+ )
406
+
407
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor]:
408
+ for layer_module in self.blocks:
409
+ hidden_states = layer_module(hidden_states)
410
+ return hidden_states
411
+
412
+
413
+ class EfficientFormerIntermediateStage(nn.Module):
414
+ def __init__(self, config: EfficientFormerConfig, index: int):
415
+ super().__init__()
416
+ self.meta4D_layers = EfficientFormerMeta4DLayers(config, index)
417
+
418
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor]:
419
+ hidden_states = self.meta4D_layers(hidden_states)
420
+ return hidden_states
421
+
422
+
423
+ class EfficientFormerLastStage(nn.Module):
424
+ def __init__(self, config: EfficientFormerConfig):
425
+ super().__init__()
426
+ self.meta4D_layers = EfficientFormerMeta4DLayers(config, -1)
427
+ self.flat = EfficientFormerFlat()
428
+ self.meta3D_layers = EfficientFormerMeta3DLayers(config)
429
+
430
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> tuple[torch.Tensor]:
431
+ hidden_states = self.meta4D_layers(hidden_states)
432
+ hidden_states = self.flat(hidden_states)
433
+ hidden_states = self.meta3D_layers(hidden_states, output_attentions)
434
+
435
+ return hidden_states
436
+
437
+
438
+ class EfficientFormerEncoder(nn.Module):
439
+ def __init__(self, config: EfficientFormerConfig):
440
+ super().__init__()
441
+ self.config = config
442
+ num_intermediate_stages = len(config.depths) - 1
443
+ downsamples = [
444
+ config.downsamples[i] or config.hidden_sizes[i] != config.hidden_sizes[i + 1]
445
+ for i in range(num_intermediate_stages)
446
+ ]
447
+ intermediate_stages = []
448
+
449
+ for i in range(num_intermediate_stages):
450
+ intermediate_stages.append(EfficientFormerIntermediateStage(config, i))
451
+ if downsamples[i]:
452
+ intermediate_stages.append(
453
+ EfficientFormerPatchEmbeddings(config, config.hidden_sizes[i], config.hidden_sizes[i + 1])
454
+ )
455
+
456
+ self.intermediate_stages = nn.ModuleList(intermediate_stages)
457
+ self.last_stage = EfficientFormerLastStage(config)
458
+
459
+ def forward(
460
+ self,
461
+ hidden_states: torch.Tensor,
462
+ output_hidden_states: bool = False,
463
+ output_attentions: bool = False,
464
+ return_dict: bool = True,
465
+ ) -> BaseModelOutput:
466
+ all_hidden_states = () if output_hidden_states else None
467
+ all_self_attentions = () if output_attentions else None
468
+
469
+ if output_hidden_states:
470
+ all_hidden_states = all_hidden_states + (hidden_states,)
471
+
472
+ for layer_module in self.intermediate_stages:
473
+ hidden_states = layer_module(hidden_states)
474
+ if output_hidden_states:
475
+ all_hidden_states = all_hidden_states + (hidden_states,)
476
+
477
+ layer_output = self.last_stage(hidden_states, output_attentions=output_attentions)
478
+
479
+ if output_attentions:
480
+ all_self_attentions = all_self_attentions + layer_output[1:]
481
+
482
+ if output_hidden_states:
483
+ all_hidden_states = all_hidden_states + (layer_output[0],)
484
+
485
+ if not return_dict:
486
+ return tuple(v for v in [layer_output[0], all_hidden_states, all_self_attentions] if v is not None)
487
+
488
+ return BaseModelOutput(
489
+ last_hidden_state=layer_output[0],
490
+ hidden_states=all_hidden_states,
491
+ attentions=all_self_attentions,
492
+ )
493
+
494
+
495
+ class EfficientFormerPreTrainedModel(PreTrainedModel):
496
+ """
497
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
498
+ models.
499
+ """
500
+
501
+ config: EfficientFormerConfig
502
+ base_model_prefix = "efficientformer"
503
+ main_input_name = "pixel_values"
504
+ supports_gradient_checkpointing = False
505
+
506
+ def _init_weights(self, module: nn.Module):
507
+ """Initialize the weights"""
508
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
509
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
510
+ if module.bias is not None:
511
+ module.bias.data.zero_()
512
+ elif isinstance(module, nn.LayerNorm):
513
+ module.bias.data.zero_()
514
+ module.weight.data.fill_(1.0)
515
+
516
+
517
+ EFFICIENTFORMER_START_DOCSTRING = r"""
518
+ This model is a PyTorch [nn.Module](https://pytorch.org/docs/stable/nn.html#nn.Module) subclass. Use it as a
519
+ regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
520
+
521
+ Parameters:
522
+ config ([`EfficientFormerConfig`]): Model configuration class with all the parameters of the model.
523
+ Initializing with a config file does not load the weights associated with the model, only the
524
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
525
+ """
526
+
527
+ EFFICIENTFORMER_INPUTS_DOCSTRING = r"""
528
+ Args:
529
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
530
+ Pixel values. Pixel values can be obtained using [`ViTImageProcessor`]. See
531
+ [`ViTImageProcessor.preprocess`] for details.
532
+ output_attentions (`bool`, *optional*):
533
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
534
+ tensors for more detail.
535
+ output_hidden_states (`bool`, *optional*):
536
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
537
+ more detail.
538
+ return_dict (`bool`, *optional*):
539
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
540
+ """
541
+
542
+
543
+ @add_start_docstrings(
544
+ "The bare EfficientFormer Model transformer outputting raw hidden-states without any specific head on top.",
545
+ EFFICIENTFORMER_START_DOCSTRING,
546
+ )
547
+ class EfficientFormerModel(EfficientFormerPreTrainedModel):
548
+ def __init__(self, config: EfficientFormerConfig):
549
+ super().__init__(config)
550
+ self.config = config
551
+ _no_split_modules = ["EfficientFormerMeta4D"]
552
+
553
+ self.patch_embed = EfficientFormerConvStem(config, config.hidden_sizes[0])
554
+ self.encoder = EfficientFormerEncoder(config)
555
+ self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
556
+
557
+ # Initialize weights and apply final processing
558
+ self.post_init()
559
+
560
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
561
+ @add_code_sample_docstrings(
562
+ checkpoint=_CHECKPOINT_FOR_DOC,
563
+ output_type=BaseModelOutputWithPooling,
564
+ config_class=_CONFIG_FOR_DOC,
565
+ modality="vision",
566
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
567
+ )
568
+ def forward(
569
+ self,
570
+ pixel_values: Optional[torch.Tensor] = None,
571
+ output_attentions: Optional[bool] = None,
572
+ output_hidden_states: Optional[bool] = None,
573
+ return_dict: Optional[bool] = None,
574
+ ) -> Union[tuple, BaseModelOutput]:
575
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
576
+ output_hidden_states = (
577
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
578
+ )
579
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
580
+
581
+ if pixel_values is None:
582
+ raise ValueError("You have to specify pixel_values")
583
+
584
+ embedding_output = self.patch_embed(pixel_values)
585
+ encoder_outputs = self.encoder(
586
+ embedding_output, output_attentions=output_attentions, output_hidden_states=output_hidden_states
587
+ )
588
+
589
+ sequence_output = encoder_outputs[0]
590
+ sequence_output = self.layernorm(sequence_output)
591
+
592
+ if not return_dict:
593
+ head_outputs = (sequence_output,)
594
+ return head_outputs + encoder_outputs[1:]
595
+
596
+ return BaseModelOutput(
597
+ last_hidden_state=sequence_output,
598
+ hidden_states=encoder_outputs.hidden_states,
599
+ attentions=encoder_outputs.attentions,
600
+ )
601
+
602
+
603
+ @add_start_docstrings(
604
+ """
605
+ EfficientFormer Model transformer with an image classification head on top (a linear layer on top of the final
606
+ hidden state of the [CLS] token) e.g. for ImageNet.
607
+ """,
608
+ EFFICIENTFORMER_START_DOCSTRING,
609
+ )
610
+ class EfficientFormerForImageClassification(EfficientFormerPreTrainedModel):
611
+ def __init__(self, config: EfficientFormerConfig):
612
+ super().__init__(config)
613
+
614
+ self.num_labels = config.num_labels
615
+ self.efficientformer = EfficientFormerModel(config)
616
+
617
+ # Classifier head
618
+ self.classifier = (
619
+ nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
620
+ )
621
+
622
+ # Initialize weights and apply final processing
623
+ self.post_init()
624
+
625
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
626
+ @add_code_sample_docstrings(
627
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
628
+ output_type=ImageClassifierOutput,
629
+ config_class=_CONFIG_FOR_DOC,
630
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
631
+ )
632
+ def forward(
633
+ self,
634
+ pixel_values: Optional[torch.Tensor] = None,
635
+ labels: Optional[torch.Tensor] = None,
636
+ output_attentions: Optional[bool] = None,
637
+ output_hidden_states: Optional[bool] = None,
638
+ return_dict: Optional[bool] = None,
639
+ ) -> Union[tuple, ImageClassifierOutput]:
640
+ r"""
641
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
642
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
643
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
644
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
645
+ """
646
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
647
+
648
+ outputs = self.efficientformer(
649
+ pixel_values,
650
+ output_attentions=output_attentions,
651
+ output_hidden_states=output_hidden_states,
652
+ return_dict=return_dict,
653
+ )
654
+
655
+ sequence_output = outputs[0]
656
+
657
+ logits = self.classifier(sequence_output.mean(-2))
658
+
659
+ loss = None
660
+ if labels is not None:
661
+ loss = self.loss_function(labels, logits, self.config)
662
+
663
+ if not return_dict:
664
+ output = (logits,) + outputs[1:]
665
+ return ((loss,) + output) if loss is not None else output
666
+
667
+ return ImageClassifierOutput(
668
+ loss=loss,
669
+ logits=logits,
670
+ hidden_states=outputs.hidden_states,
671
+ attentions=outputs.attentions,
672
+ )
673
+
674
+
675
+ @dataclass
676
+ class EfficientFormerForImageClassificationWithTeacherOutput(ModelOutput):
677
+ """
678
+ Output type of [`EfficientFormerForImageClassificationWithTeacher`].
679
+
680
+ Args:
681
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
682
+ Prediction scores as the average of the cls_logits and distillation logits.
683
+ cls_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
684
+ Prediction scores of the classification head (i.e. the linear layer on top of the final hidden state of the
685
+ class token).
686
+ distillation_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
687
+ Prediction scores of the distillation head (i.e. the linear layer on top of the final hidden state of the
688
+ distillation token).
689
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
690
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
691
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
692
+ plus the initial embedding outputs.
693
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
694
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
695
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
696
+ the self-attention heads.
697
+ """
698
+
699
+ logits: Optional[torch.FloatTensor] = None
700
+ cls_logits: Optional[torch.FloatTensor] = None
701
+ distillation_logits: Optional[torch.FloatTensor] = None
702
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
703
+ attentions: Optional[tuple[torch.FloatTensor]] = None
704
+
705
+
706
+ @add_start_docstrings(
707
+ """
708
+ EfficientFormer Model transformer with image classification heads on top (a linear layer on top of the final hidden
709
+ state of the [CLS] token and a linear layer on top of the final hidden state of the distillation token) e.g. for
710
+ ImageNet.
711
+
712
+ <Tip warning={true}>
713
+
714
+ This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
715
+ supported.
716
+
717
+ </Tip>
718
+ """,
719
+ EFFICIENTFORMER_START_DOCSTRING,
720
+ )
721
+ class EfficientFormerForImageClassificationWithTeacher(EfficientFormerPreTrainedModel):
722
+ def __init__(self, config: EfficientFormerConfig):
723
+ super().__init__(config)
724
+
725
+ self.num_labels = config.num_labels
726
+ self.efficientformer = EfficientFormerModel(config)
727
+
728
+ # Classifier head
729
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
730
+ # Distillation head
731
+ self.distillation_classifier = (
732
+ nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
733
+ )
734
+
735
+ # Initialize weights and apply final processing
736
+ self.post_init()
737
+
738
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
739
+ @add_code_sample_docstrings(
740
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
741
+ output_type=EfficientFormerForImageClassificationWithTeacherOutput,
742
+ config_class=_CONFIG_FOR_DOC,
743
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
744
+ )
745
+ def forward(
746
+ self,
747
+ pixel_values: Optional[torch.Tensor] = None,
748
+ output_attentions: Optional[bool] = None,
749
+ output_hidden_states: Optional[bool] = None,
750
+ return_dict: Optional[bool] = None,
751
+ ) -> Union[tuple, EfficientFormerForImageClassificationWithTeacherOutput]:
752
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
753
+ outputs = self.efficientformer(
754
+ pixel_values,
755
+ output_attentions=output_attentions,
756
+ output_hidden_states=output_hidden_states,
757
+ return_dict=return_dict,
758
+ )
759
+
760
+ sequence_output = outputs[0]
761
+
762
+ cls_logits = self.classifier(sequence_output.mean(-2))
763
+ distillation_logits = self.distillation_classifier(sequence_output.mean(-2))
764
+
765
+ # during inference, return the average of both classifier predictions
766
+ logits = (cls_logits + distillation_logits) / 2
767
+
768
+ if not return_dict:
769
+ output = (logits, cls_logits, distillation_logits) + outputs[1:]
770
+ return output
771
+
772
+ return EfficientFormerForImageClassificationWithTeacherOutput(
773
+ logits=logits,
774
+ cls_logits=cls_logits,
775
+ distillation_logits=distillation_logits,
776
+ hidden_states=outputs.hidden_states,
777
+ attentions=outputs.attentions,
778
+ )
779
+
780
+
781
+ __all__ = [
782
+ "EfficientFormerForImageClassification",
783
+ "EfficientFormerForImageClassificationWithTeacher",
784
+ "EfficientFormerModel",
785
+ "EfficientFormerPreTrainedModel",
786
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/efficientformer/modeling_tf_efficientformer.py ADDED
@@ -0,0 +1,1198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Snapchat 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
+ """TensorFlow EfficientFormer model."""
16
+
17
+ import itertools
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Union
20
+
21
+ import tensorflow as tf
22
+
23
+ from ....activations_tf import ACT2FN
24
+ from ....modeling_tf_outputs import (
25
+ TFBaseModelOutput,
26
+ TFBaseModelOutputWithPooling,
27
+ TFImageClassifierOutput,
28
+ )
29
+ from ....modeling_tf_utils import (
30
+ TFPreTrainedModel,
31
+ TFSequenceClassificationLoss,
32
+ get_initializer,
33
+ keras,
34
+ keras_serializable,
35
+ unpack_inputs,
36
+ )
37
+ from ....tf_utils import shape_list, stable_softmax
38
+ from ....utils import (
39
+ ModelOutput,
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ logging,
44
+ )
45
+ from .configuration_efficientformer import EfficientFormerConfig
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+ # General docstring
51
+ _CONFIG_FOR_DOC = "EfficientFormerConfig"
52
+
53
+ # Base docstring
54
+ _CHECKPOINT_FOR_DOC = "snap-research/efficientformer-l1-300"
55
+ _EXPECTED_OUTPUT_SHAPE = [1, 49, 448]
56
+
57
+ # Image classification docstring
58
+ _IMAGE_CLASS_CHECKPOINT = "snap-research/efficientformer-l1-300"
59
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "LABEL_281"
60
+
61
+
62
+ class TFEfficientFormerPatchEmbeddings(keras.layers.Layer):
63
+ """
64
+ This class performs downsampling between two stages. For the input tensor with the shape [batch_size, num_channels,
65
+ height, width] it produces output tensor with the shape [batch_size, num_channels, height/stride, width/stride]
66
+ """
67
+
68
+ def __init__(
69
+ self, config: EfficientFormerConfig, num_channels: int, embed_dim: int, apply_norm: bool = True, **kwargs
70
+ ) -> None:
71
+ super().__init__(**kwargs)
72
+ self.num_channels = num_channels
73
+
74
+ self.padding = keras.layers.ZeroPadding2D(padding=config.downsample_pad)
75
+ self.projection = keras.layers.Conv2D(
76
+ filters=embed_dim,
77
+ kernel_size=config.downsample_patch_size,
78
+ strides=config.downsample_stride,
79
+ padding="valid",
80
+ name="projection",
81
+ )
82
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
83
+ self.norm = (
84
+ keras.layers.BatchNormalization(axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="norm")
85
+ if apply_norm
86
+ else tf.identity
87
+ )
88
+ self.embed_dim = embed_dim
89
+
90
+ def call(self, pixel_values: tf.Tensor, training: bool = False) -> tf.Tensor:
91
+ tf.debugging.assert_shapes(
92
+ [(pixel_values, (..., None, None, self.num_channels))],
93
+ message="Make sure that the channel dimension of the pixel values match with the one set in the configuration.",
94
+ )
95
+ embeddings = self.projection(self.padding(pixel_values))
96
+ embeddings = self.norm(embeddings, training=training)
97
+ return embeddings
98
+
99
+ def build(self, input_shape=None):
100
+ if self.built:
101
+ return
102
+ self.built = True
103
+ if getattr(self, "projection", None) is not None:
104
+ with tf.name_scope(self.projection.name):
105
+ self.projection.build([None, None, None, self.num_channels])
106
+ if getattr(self, "norm", None) is not None:
107
+ if hasattr(self.norm, "name"):
108
+ with tf.name_scope(self.norm.name):
109
+ self.norm.build([None, None, None, self.embed_dim])
110
+
111
+
112
+ class TFEfficientFormerSelfAttention(keras.layers.Layer):
113
+ def __init__(
114
+ self,
115
+ dim: int,
116
+ key_dim: int,
117
+ num_heads: int,
118
+ attention_ratio: int,
119
+ resolution: int,
120
+ config: EfficientFormerConfig,
121
+ **kwargs,
122
+ ):
123
+ super().__init__(**kwargs)
124
+
125
+ self.num_heads = num_heads
126
+ self.key_dim = key_dim
127
+ self.attention_ratio = attention_ratio
128
+ self.scale = key_dim**-0.5
129
+ self.total_key_dim = key_dim * num_heads
130
+ self.expanded_key_dim = int(attention_ratio * key_dim)
131
+ self.total_expanded_key_dim = int(self.expanded_key_dim * num_heads)
132
+ hidden_size = self.total_expanded_key_dim + self.total_key_dim * 2
133
+
134
+ self.qkv = keras.layers.Dense(
135
+ units=hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="qkv"
136
+ )
137
+ self.projection = keras.layers.Dense(
138
+ units=dim, kernel_initializer=get_initializer(config.initializer_range), name="projection"
139
+ )
140
+ self.resolution = resolution
141
+ self.dim = dim
142
+
143
+ def build(self, input_shape: tf.TensorShape) -> None:
144
+ points = list(itertools.product(range(self.resolution), range(self.resolution)))
145
+ num_points = len(points)
146
+ attention_offsets = {}
147
+
148
+ idxs = []
149
+
150
+ for point_1 in points:
151
+ for point_2 in points:
152
+ offset = (abs(point_1[0] - point_2[0]), abs(point_1[1] - point_2[1]))
153
+ if offset not in attention_offsets:
154
+ attention_offsets[offset] = len(attention_offsets)
155
+ idxs.append(attention_offsets[offset])
156
+
157
+ self.attention_biases = self.add_weight(
158
+ shape=(self.num_heads, len(attention_offsets)),
159
+ initializer=keras.initializers.zeros(),
160
+ trainable=True,
161
+ name="attention_biases",
162
+ )
163
+ self.attention_bias_idxs = self.add_weight(
164
+ shape=(num_points, num_points),
165
+ trainable=False,
166
+ dtype=tf.int32,
167
+ name="attention_bias_idxs",
168
+ )
169
+
170
+ self.attention_bias_idxs.assign(tf.reshape(tf.cast(idxs, dtype=tf.int32), (num_points, num_points)))
171
+
172
+ if self.built:
173
+ return
174
+ self.built = True
175
+ if getattr(self, "qkv", None) is not None:
176
+ with tf.name_scope(self.qkv.name):
177
+ self.qkv.build([None, None, self.dim])
178
+ if getattr(self, "projection", None) is not None:
179
+ with tf.name_scope(self.projection.name):
180
+ self.projection.build([None, None, self.total_expanded_key_dim])
181
+
182
+ def call(
183
+ self, hidden_states: tf.Tensor, output_attentions: bool = False, training: bool = False
184
+ ) -> tuple[tf.Tensor]:
185
+ batch_size, sequence_length, *_ = shape_list(hidden_states)
186
+ qkv = self.qkv(inputs=hidden_states)
187
+
188
+ query_layer, key_layer, value_layer = tf.split(
189
+ tf.reshape(tensor=qkv, shape=(batch_size, sequence_length, self.num_heads, -1)),
190
+ num_or_size_splits=[self.key_dim, self.key_dim, self.expanded_key_dim],
191
+ axis=3,
192
+ )
193
+
194
+ query_layer = tf.transpose(query_layer, perm=[0, 2, 1, 3])
195
+ key_layer = tf.transpose(key_layer, perm=[0, 2, 1, 3])
196
+ value_layer = tf.transpose(value_layer, perm=[0, 2, 1, 3])
197
+
198
+ attention_probs = tf.matmul(query_layer, tf.transpose(key_layer, perm=[0, 1, 3, 2]))
199
+ scale = tf.cast(self.scale, dtype=attention_probs.dtype)
200
+ attention_probs = tf.multiply(attention_probs, scale)
201
+
202
+ attention_biases = tf.gather(params=self.attention_biases, indices=self.attention_bias_idxs, axis=1)
203
+ attention_probs = attention_probs + attention_biases
204
+ attention_probs = stable_softmax(logits=attention_probs, axis=-1)
205
+
206
+ context_layer = tf.matmul(attention_probs, value_layer)
207
+ context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])
208
+
209
+ context_layer = tf.reshape(
210
+ tensor=context_layer, shape=(batch_size, sequence_length, self.total_expanded_key_dim)
211
+ )
212
+ context_layer = self.projection(context_layer)
213
+
214
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
215
+
216
+ return outputs
217
+
218
+
219
+ class TFEfficientFormerConvStem(keras.layers.Layer):
220
+ def __init__(self, config: EfficientFormerConfig, out_channels: int, **kwargs):
221
+ super().__init__(**kwargs)
222
+
223
+ self.padding = keras.layers.ZeroPadding2D(padding=1)
224
+ self.convolution1 = keras.layers.Conv2D(
225
+ filters=out_channels // 2, kernel_size=3, strides=2, padding="valid", name="convolution1"
226
+ )
227
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
228
+ self.batchnorm_before = keras.layers.BatchNormalization(
229
+ axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="batchnorm_before"
230
+ )
231
+
232
+ self.convolution2 = keras.layers.Conv2D(
233
+ filters=out_channels,
234
+ kernel_size=3,
235
+ strides=2,
236
+ padding="valid",
237
+ name="convolution2",
238
+ )
239
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
240
+ self.batchnorm_after = keras.layers.BatchNormalization(
241
+ axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="batchnorm_after"
242
+ )
243
+
244
+ self.activation = keras.layers.Activation(activation=keras.activations.relu, name="activation")
245
+ self.out_channels = out_channels
246
+ self.config = config
247
+
248
+ def call(self, pixel_values: tf.Tensor, training: bool = False) -> tf.Tensor:
249
+ features = self.batchnorm_before(self.convolution1(self.padding(pixel_values)), training=training)
250
+ features = self.activation(features)
251
+ features = self.batchnorm_after(self.convolution2(self.padding(features)), training=training)
252
+ features = self.activation(features)
253
+ return features
254
+
255
+ def build(self, input_shape=None):
256
+ if self.built:
257
+ return
258
+ self.built = True
259
+ if getattr(self, "convolution1", None) is not None:
260
+ with tf.name_scope(self.convolution1.name):
261
+ self.convolution1.build([None, None, None, self.config.num_channels])
262
+ if getattr(self, "batchnorm_before", None) is not None:
263
+ with tf.name_scope(self.batchnorm_before.name):
264
+ self.batchnorm_before.build([None, None, None, self.out_channels // 2])
265
+ if getattr(self, "convolution2", None) is not None:
266
+ with tf.name_scope(self.convolution2.name):
267
+ self.convolution2.build([None, None, None, self.out_channels // 2])
268
+ if getattr(self, "batchnorm_after", None) is not None:
269
+ with tf.name_scope(self.batchnorm_after.name):
270
+ self.batchnorm_after.build([None, None, None, self.out_channels])
271
+ if getattr(self, "activation", None) is not None:
272
+ with tf.name_scope(self.activation.name):
273
+ self.activation.build(None)
274
+
275
+
276
+ class TFEfficientFormerPooling(keras.layers.Layer):
277
+ def __init__(self, pool_size: int, **kwargs):
278
+ super().__init__(**kwargs)
279
+ self.pool = keras.layers.AveragePooling2D(pool_size=pool_size, strides=1, padding="same")
280
+
281
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
282
+ output = self.pool(hidden_states)
283
+ output = output - hidden_states
284
+ return output
285
+
286
+
287
+ class TFEfficientFormerDenseMlp(keras.layers.Layer):
288
+ def __init__(
289
+ self,
290
+ config: EfficientFormerConfig,
291
+ in_features: int,
292
+ hidden_features: Optional[int] = None,
293
+ out_features: Optional[int] = None,
294
+ **kwargs,
295
+ ):
296
+ super().__init__(**kwargs)
297
+ out_features = out_features or in_features
298
+ hidden_features = hidden_features or in_features
299
+
300
+ self.linear_in = keras.layers.Dense(
301
+ units=hidden_features, kernel_initializer=get_initializer(config.initializer_range), name="linear_in"
302
+ )
303
+ self.activation = ACT2FN[config.hidden_act]
304
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
305
+
306
+ self.linear_out = keras.layers.Dense(
307
+ units=out_features, kernel_initializer=get_initializer(config.initializer_range), name="linear_out"
308
+ )
309
+ self.hidden_features = hidden_features
310
+ self.in_features = in_features
311
+
312
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> tf.Tensor:
313
+ hidden_states = self.linear_in(inputs=hidden_states)
314
+ hidden_states = self.activation(hidden_states)
315
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
316
+ hidden_states = self.linear_out(inputs=hidden_states)
317
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
318
+
319
+ return hidden_states
320
+
321
+ def build(self, input_shape=None):
322
+ if self.built:
323
+ return
324
+ self.built = True
325
+ if getattr(self, "linear_in", None) is not None:
326
+ with tf.name_scope(self.linear_in.name):
327
+ self.linear_in.build([None, None, self.in_features])
328
+ if getattr(self, "linear_out", None) is not None:
329
+ with tf.name_scope(self.linear_out.name):
330
+ self.linear_out.build([None, None, self.hidden_features])
331
+
332
+
333
+ class TFEfficientFormerConvMlp(keras.layers.Layer):
334
+ def __init__(
335
+ self,
336
+ config: EfficientFormerConfig,
337
+ in_features: int,
338
+ hidden_features: Optional[int] = None,
339
+ out_features: Optional[int] = None,
340
+ drop: float = 0.0,
341
+ **kwargs,
342
+ ):
343
+ super().__init__(**kwargs)
344
+ out_features = out_features or in_features
345
+ hidden_features = hidden_features or in_features
346
+
347
+ self.convolution1 = keras.layers.Conv2D(
348
+ filters=hidden_features,
349
+ kernel_size=1,
350
+ name="convolution1",
351
+ padding="valid",
352
+ )
353
+
354
+ self.activation = ACT2FN[config.hidden_act]
355
+
356
+ self.convolution2 = keras.layers.Conv2D(
357
+ filters=out_features,
358
+ kernel_size=1,
359
+ name="convolution2",
360
+ padding="valid",
361
+ )
362
+
363
+ self.dropout = keras.layers.Dropout(rate=drop)
364
+
365
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
366
+ self.batchnorm_before = keras.layers.BatchNormalization(
367
+ axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="batchnorm_before"
368
+ )
369
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
370
+ self.batchnorm_after = keras.layers.BatchNormalization(
371
+ axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="batchnorm_after"
372
+ )
373
+ self.hidden_features = hidden_features
374
+ self.in_features = in_features
375
+ self.out_features = out_features
376
+
377
+ def call(self, hidden_state: tf.Tensor, training: bool = False) -> tf.Tensor:
378
+ hidden_state = self.convolution1(hidden_state)
379
+ hidden_state = self.batchnorm_before(hidden_state, training=training)
380
+ hidden_state = self.activation(hidden_state)
381
+ hidden_state = self.dropout(hidden_state, training=training)
382
+ hidden_state = self.convolution2(hidden_state)
383
+ hidden_state = self.batchnorm_after(hidden_state, training=training)
384
+ hidden_state = self.dropout(hidden_state, training=training)
385
+ return hidden_state
386
+
387
+ def build(self, input_shape=None):
388
+ if self.built:
389
+ return
390
+ self.built = True
391
+ if getattr(self, "convolution1", None) is not None:
392
+ with tf.name_scope(self.convolution1.name):
393
+ self.convolution1.build([None, None, None, self.in_features])
394
+ if getattr(self, "convolution2", None) is not None:
395
+ with tf.name_scope(self.convolution2.name):
396
+ self.convolution2.build([None, None, None, self.hidden_features])
397
+ if getattr(self, "batchnorm_before", None) is not None:
398
+ with tf.name_scope(self.batchnorm_before.name):
399
+ self.batchnorm_before.build([None, None, None, self.hidden_features])
400
+ if getattr(self, "batchnorm_after", None) is not None:
401
+ with tf.name_scope(self.batchnorm_after.name):
402
+ self.batchnorm_after.build([None, None, None, self.out_features])
403
+
404
+
405
+ # Copied from transformers.models.convnext.modeling_tf_convnext.TFConvNextDropPath with ConvNext->EfficientFormer
406
+ class TFEfficientFormerDropPath(keras.layers.Layer):
407
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
408
+ References:
409
+ (1) github.com:rwightman/pytorch-image-models
410
+ """
411
+
412
+ def __init__(self, drop_path: float, **kwargs):
413
+ super().__init__(**kwargs)
414
+ self.drop_path = drop_path
415
+
416
+ def call(self, x: tf.Tensor, training=None):
417
+ if training:
418
+ keep_prob = 1 - self.drop_path
419
+ shape = (tf.shape(x)[0],) + (1,) * (len(tf.shape(x)) - 1)
420
+ random_tensor = keep_prob + tf.random.uniform(shape, 0, 1)
421
+ random_tensor = tf.floor(random_tensor)
422
+ return (x / keep_prob) * random_tensor
423
+ return x
424
+
425
+
426
+ class TFEfficientFormerFlat(keras.layers.Layer):
427
+ def __init__(self, **kwargs):
428
+ super().__init__(**kwargs)
429
+
430
+ def call(self, hidden_states: tf.Tensor) -> tuple[tf.Tensor]:
431
+ batch_size, _, _, in_channels = shape_list(hidden_states)
432
+ hidden_states = tf.reshape(hidden_states, shape=[batch_size, -1, in_channels])
433
+ return hidden_states
434
+
435
+
436
+ class TFEfficientFormerMeta3D(keras.layers.Layer):
437
+ def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0, **kwargs):
438
+ super().__init__(**kwargs)
439
+
440
+ self.token_mixer = TFEfficientFormerSelfAttention(
441
+ dim=config.dim,
442
+ key_dim=config.key_dim,
443
+ num_heads=config.num_attention_heads,
444
+ attention_ratio=config.attention_ratio,
445
+ resolution=config.resolution,
446
+ name="token_mixer",
447
+ config=config,
448
+ )
449
+ self.dim = dim
450
+ self.config = config
451
+
452
+ self.layernorm1 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm1")
453
+ self.layernorm2 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm2")
454
+ mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
455
+ self.mlp = TFEfficientFormerDenseMlp(config, in_features=dim, hidden_features=mlp_hidden_dim, name="mlp")
456
+
457
+ # Using `layers.Activation` instead of `tf.identity` to better control `training' behavior.
458
+ self.drop_path = (
459
+ TFEfficientFormerDropPath(drop_path)
460
+ if drop_path > 0.0
461
+ else keras.layers.Activation("linear", name="drop_path")
462
+ )
463
+ self.config = config
464
+
465
+ def build(self, input_shape=None):
466
+ self.layer_scale_1 = None
467
+ self.layer_scale_2 = None
468
+
469
+ if self.config.use_layer_scale:
470
+ self.layer_scale_1 = self.add_weight(
471
+ shape=(self.dim,),
472
+ initializer=keras.initializers.Constant(value=self.config.layer_scale_init_value),
473
+ trainable=True,
474
+ name="layer_scale_1",
475
+ )
476
+ self.layer_scale_2 = self.add_weight(
477
+ shape=(self.dim,),
478
+ initializer=keras.initializers.Constant(value=self.config.layer_scale_init_value),
479
+ trainable=True,
480
+ name="layer_scale_2",
481
+ )
482
+
483
+ if self.built:
484
+ return
485
+ self.built = True
486
+ if getattr(self, "token_mixer", None) is not None:
487
+ with tf.name_scope(self.token_mixer.name):
488
+ self.token_mixer.build(None)
489
+ if getattr(self, "layernorm1", None) is not None:
490
+ with tf.name_scope(self.layernorm1.name):
491
+ self.layernorm1.build([None, None, self.dim])
492
+ if getattr(self, "layernorm2", None) is not None:
493
+ with tf.name_scope(self.layernorm2.name):
494
+ self.layernorm2.build([None, None, self.dim])
495
+ if getattr(self, "mlp", None) is not None:
496
+ with tf.name_scope(self.mlp.name):
497
+ self.mlp.build(None)
498
+ if getattr(self, "drop_path", None) is not None:
499
+ with tf.name_scope(self.drop_path.name):
500
+ self.drop_path.build(None)
501
+
502
+ def call(
503
+ self, hidden_states: tf.Tensor, output_attentions: bool = False, training: bool = False
504
+ ) -> tuple[tf.Tensor]:
505
+ self_attention_outputs = self.token_mixer(
506
+ hidden_states=self.layernorm1(hidden_states, training=training),
507
+ output_attentions=output_attentions,
508
+ training=training,
509
+ )
510
+
511
+ attention_output = self_attention_outputs[0]
512
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
513
+
514
+ if self.config.use_layer_scale:
515
+ layer_output = hidden_states + self.drop_path(
516
+ tf.expand_dims(tf.expand_dims(self.layer_scale_1, 0), 0) * attention_output,
517
+ training=training,
518
+ )
519
+ layer_output = layer_output + self.drop_path(
520
+ tf.expand_dims(tf.expand_dims(self.layer_scale_2, 0), 0)
521
+ * self.mlp(hidden_states=self.layernorm2(inputs=layer_output, training=training), training=training),
522
+ training=training,
523
+ )
524
+ else:
525
+ layer_output = hidden_states + self.drop_path(attention_output, training=training)
526
+ layer_output = layer_output + self.drop_path(
527
+ self.mlp(hidden_states=self.layernorm2(inputs=layer_output, training=training), training=training),
528
+ training=training,
529
+ )
530
+
531
+ outputs = (layer_output,) + outputs
532
+
533
+ return outputs
534
+
535
+
536
+ class TFEfficientFormerMeta3DLayers(keras.layers.Layer):
537
+ def __init__(self, config: EfficientFormerConfig, **kwargs):
538
+ super().__init__(**kwargs)
539
+ drop_paths = [
540
+ config.drop_path_rate * (block_idx + sum(config.depths[:-1]))
541
+ for block_idx in range(config.num_meta3d_blocks)
542
+ ]
543
+ self.blocks = [
544
+ TFEfficientFormerMeta3D(config, config.hidden_sizes[-1], drop_path=drop_path, name=f"blocks.{i}")
545
+ for i, drop_path in enumerate(drop_paths)
546
+ ]
547
+
548
+ def call(
549
+ self, hidden_states: tf.Tensor, output_attentions: bool = False, training: bool = False
550
+ ) -> tuple[tf.Tensor]:
551
+ all_attention_outputs = () if output_attentions else None
552
+
553
+ for i, layer_module in enumerate(self.blocks):
554
+ if isinstance(hidden_states, tuple):
555
+ hidden_states = hidden_states[0]
556
+
557
+ hidden_states = layer_module(
558
+ hidden_states=hidden_states, output_attentions=output_attentions, training=training
559
+ )
560
+ if output_attentions:
561
+ all_attention_outputs = all_attention_outputs + (hidden_states[1],)
562
+
563
+ if output_attentions:
564
+ outputs = (hidden_states[0],) + all_attention_outputs
565
+ return outputs
566
+
567
+ return hidden_states
568
+
569
+ def build(self, input_shape=None):
570
+ if self.built:
571
+ return
572
+ self.built = True
573
+ if getattr(self, "blocks", None) is not None:
574
+ for layer in self.blocks:
575
+ with tf.name_scope(layer.name):
576
+ layer.build(None)
577
+
578
+
579
+ class TFEfficientFormerMeta4D(keras.layers.Layer):
580
+ def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0, **kwargs):
581
+ super().__init__(**kwargs)
582
+ pool_size = config.pool_size if config.pool_size is not None else 3
583
+ self.token_mixer = TFEfficientFormerPooling(pool_size=pool_size, name="token_mixer")
584
+ self.dim = dim
585
+ mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
586
+ self.mlp = TFEfficientFormerConvMlp(
587
+ config=config, in_features=dim, hidden_features=mlp_hidden_dim, drop=config.hidden_dropout_prob, name="mlp"
588
+ )
589
+
590
+ self.drop_path = (
591
+ TFEfficientFormerDropPath(drop_path, name="drop_path")
592
+ if drop_path > 0.0
593
+ else keras.layers.Activation("linear", name="drop_path")
594
+ )
595
+ self.config = config
596
+
597
+ def build(self, input_shape=None):
598
+ self.layer_scale_1 = None
599
+ self.layer_scale_2 = None
600
+
601
+ if self.config.use_layer_scale:
602
+ self.layer_scale_1 = self.add_weight(
603
+ shape=(self.dim),
604
+ initializer=keras.initializers.Constant(value=self.config.layer_scale_init_value),
605
+ trainable=True,
606
+ name="layer_scale_1",
607
+ )
608
+ self.layer_scale_2 = self.add_weight(
609
+ shape=(self.dim),
610
+ initializer=keras.initializers.Constant(value=self.config.layer_scale_init_value),
611
+ trainable=True,
612
+ name="layer_scale_2",
613
+ )
614
+
615
+ if self.built:
616
+ return
617
+ self.built = True
618
+ if getattr(self, "token_mixer", None) is not None:
619
+ with tf.name_scope(self.token_mixer.name):
620
+ self.token_mixer.build(None)
621
+ if getattr(self, "mlp", None) is not None:
622
+ with tf.name_scope(self.mlp.name):
623
+ self.mlp.build(None)
624
+ if getattr(self, "drop_path", None) is not None:
625
+ with tf.name_scope(self.drop_path.name):
626
+ self.drop_path.build(None)
627
+
628
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> tuple[tf.Tensor]:
629
+ outputs = self.token_mixer(hidden_states)
630
+
631
+ if self.config.use_layer_scale:
632
+ layer_output = hidden_states + self.drop_path(
633
+ tf.expand_dims(tf.expand_dims(self.layer_scale_1, 0), 0) * outputs,
634
+ training=training,
635
+ )
636
+
637
+ layer_output = layer_output + self.drop_path(
638
+ tf.expand_dims(tf.expand_dims(self.layer_scale_2, 0), 0)
639
+ * self.mlp(hidden_state=layer_output, training=training),
640
+ training=training,
641
+ )
642
+
643
+ else:
644
+ layer_output = hidden_states + self.drop_path(outputs, training=training)
645
+ layer_output = layer_output + self.drop_path(
646
+ self.mlp(hidden_state=layer_output, training=training), training=training
647
+ )
648
+
649
+ return layer_output
650
+
651
+
652
+ class TFEfficientFormerMeta4DLayers(keras.layers.Layer):
653
+ def __init__(self, config: EfficientFormerConfig, stage_idx: int, **kwargs):
654
+ super().__init__(**kwargs)
655
+ num_layers = (
656
+ config.depths[stage_idx] if stage_idx != -1 else config.depths[stage_idx] - config.num_meta3d_blocks
657
+ )
658
+ drop_paths = [
659
+ config.drop_path_rate * (block_idx + sum(config.depths[:stage_idx])) for block_idx in range(num_layers)
660
+ ]
661
+
662
+ self.blocks = [
663
+ TFEfficientFormerMeta4D(
664
+ config=config, dim=config.hidden_sizes[stage_idx], drop_path=drop_paths[i], name=f"blocks.{i}"
665
+ )
666
+ for i in range(len(drop_paths))
667
+ ]
668
+
669
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> tuple[tf.Tensor]:
670
+ for layer_module in self.blocks:
671
+ hidden_states = layer_module(hidden_states=hidden_states, training=training)
672
+ return hidden_states
673
+
674
+ def build(self, input_shape=None):
675
+ if self.built:
676
+ return
677
+ self.built = True
678
+ if getattr(self, "blocks", None) is not None:
679
+ for layer in self.blocks:
680
+ with tf.name_scope(layer.name):
681
+ layer.build(None)
682
+
683
+
684
+ class TFEfficientFormerIntermediateStage(keras.layers.Layer):
685
+ def __init__(self, config: EfficientFormerConfig, index: int, **kwargs):
686
+ super().__init__(**kwargs)
687
+ self.meta4D_layers = TFEfficientFormerMeta4DLayers(config=config, stage_idx=index, name="meta4D_layers")
688
+
689
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> tuple[tf.Tensor]:
690
+ hidden_states = self.meta4D_layers(hidden_states=hidden_states, training=training)
691
+ return hidden_states
692
+
693
+ def build(self, input_shape=None):
694
+ if self.built:
695
+ return
696
+ self.built = True
697
+ if getattr(self, "meta4D_layers", None) is not None:
698
+ with tf.name_scope(self.meta4D_layers.name):
699
+ self.meta4D_layers.build(None)
700
+
701
+
702
+ class TFEfficientFormerLastStage(keras.layers.Layer):
703
+ def __init__(self, config: EfficientFormerConfig, **kwargs):
704
+ super().__init__(**kwargs)
705
+ self.meta4D_layers = TFEfficientFormerMeta4DLayers(config=config, stage_idx=-1, name="meta4D_layers")
706
+ self.flat = TFEfficientFormerFlat(name="flat")
707
+ self.meta3D_layers = TFEfficientFormerMeta3DLayers(config, name="meta3D_layers")
708
+
709
+ def call(
710
+ self, hidden_states: tf.Tensor, output_attentions: bool = False, training: bool = False
711
+ ) -> tuple[tf.Tensor]:
712
+ hidden_states = self.meta4D_layers(hidden_states=hidden_states, training=training)
713
+ hidden_states = self.flat(hidden_states=hidden_states)
714
+ hidden_states = self.meta3D_layers(
715
+ hidden_states=hidden_states, output_attentions=output_attentions, training=training
716
+ )
717
+
718
+ return hidden_states
719
+
720
+ def build(self, input_shape=None):
721
+ if self.built:
722
+ return
723
+ self.built = True
724
+ if getattr(self, "meta4D_layers", None) is not None:
725
+ with tf.name_scope(self.meta4D_layers.name):
726
+ self.meta4D_layers.build(None)
727
+ if getattr(self, "flat", None) is not None:
728
+ with tf.name_scope(self.flat.name):
729
+ self.flat.build(None)
730
+ if getattr(self, "meta3D_layers", None) is not None:
731
+ with tf.name_scope(self.meta3D_layers.name):
732
+ self.meta3D_layers.build(None)
733
+
734
+
735
+ class TFEfficientFormerEncoder(keras.layers.Layer):
736
+ def __init__(self, config: EfficientFormerConfig, **kwargs):
737
+ super().__init__(**kwargs)
738
+
739
+ self.config = config
740
+ num_intermediate_stages = len(config.depths) - 1
741
+ downsamples = [
742
+ config.downsamples[i] or config.hidden_sizes[i] != config.hidden_sizes[i + 1]
743
+ for i in range(num_intermediate_stages)
744
+ ]
745
+
746
+ intermediate_stages = []
747
+ layer_count = -1
748
+ for i in range(num_intermediate_stages):
749
+ layer_count += 1
750
+ intermediate_stages.append(
751
+ TFEfficientFormerIntermediateStage(config, i, name=f"intermediate_stages.{layer_count}")
752
+ )
753
+ if downsamples[i]:
754
+ layer_count += 1
755
+ intermediate_stages.append(
756
+ TFEfficientFormerPatchEmbeddings(
757
+ config,
758
+ config.hidden_sizes[i],
759
+ config.hidden_sizes[i + 1],
760
+ name=f"intermediate_stages.{layer_count}",
761
+ )
762
+ )
763
+ self.intermediate_stages = intermediate_stages
764
+ self.last_stage = TFEfficientFormerLastStage(config, name="last_stage")
765
+
766
+ def call(
767
+ self,
768
+ hidden_states: tf.Tensor,
769
+ output_hidden_states: bool,
770
+ output_attentions: bool,
771
+ return_dict: bool,
772
+ training: bool = False,
773
+ ) -> TFBaseModelOutput:
774
+ all_hidden_states = () if output_hidden_states else None
775
+ all_self_attentions = () if output_attentions else None
776
+
777
+ if output_hidden_states:
778
+ all_hidden_states = all_hidden_states + (hidden_states,)
779
+
780
+ for layer_module in self.intermediate_stages:
781
+ hidden_states = layer_module(hidden_states, training=training)
782
+
783
+ if output_hidden_states:
784
+ all_hidden_states = all_hidden_states + (hidden_states,)
785
+
786
+ layer_output = self.last_stage(hidden_states, output_attentions=output_attentions, training=training)
787
+
788
+ if output_attentions:
789
+ all_self_attentions = all_self_attentions + layer_output[1:]
790
+
791
+ if output_hidden_states:
792
+ all_hidden_states = all_hidden_states + (layer_output[0],)
793
+
794
+ if not return_dict:
795
+ return tuple(v for v in [layer_output[0], all_hidden_states, all_self_attentions] if v is not None)
796
+
797
+ return TFBaseModelOutput(
798
+ last_hidden_state=layer_output[0],
799
+ hidden_states=all_hidden_states,
800
+ attentions=all_self_attentions,
801
+ )
802
+
803
+ def build(self, input_shape=None):
804
+ if self.built:
805
+ return
806
+ self.built = True
807
+ if getattr(self, "last_stage", None) is not None:
808
+ with tf.name_scope(self.last_stage.name):
809
+ self.last_stage.build(None)
810
+ for layer in self.intermediate_stages:
811
+ with tf.name_scope(layer.name):
812
+ layer.build(None)
813
+
814
+
815
+ @keras_serializable
816
+ class TFEfficientFormerMainLayer(keras.layers.Layer):
817
+ config_class = EfficientFormerConfig
818
+
819
+ def __init__(self, config: EfficientFormerConfig, **kwargs) -> None:
820
+ super().__init__(**kwargs)
821
+ self.config = config
822
+
823
+ self.patch_embed = TFEfficientFormerConvStem(config, config.hidden_sizes[0], name="patch_embed")
824
+ self.encoder = TFEfficientFormerEncoder(config, name="encoder")
825
+ self.layernorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm")
826
+
827
+ @unpack_inputs
828
+ def call(
829
+ self,
830
+ pixel_values: Optional[tf.Tensor] = None,
831
+ output_attentions: Optional[tf.Tensor] = None,
832
+ output_hidden_states: Optional[tf.Tensor] = None,
833
+ return_dict: Optional[bool] = None,
834
+ training: bool = False,
835
+ ) -> Union[TFBaseModelOutput, tuple[tf.Tensor, ...]]:
836
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
837
+
838
+ output_hidden_states = (
839
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
840
+ )
841
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
842
+
843
+ if pixel_values is None:
844
+ raise ValueError("You have to specify pixel_values")
845
+
846
+ # When running on CPU, keras.layers.Conv2D and keras.layers.AveragePool2D do not
847
+ # support channels first NCHW format. A number of blocks contain both.
848
+ # So change the input format from (batch_size, num_channels, height, width) to
849
+ # (batch_size, height, width, num_channels) here.
850
+ # shape = (batch_size, in_height, in_width, in_channels=num_channels)
851
+ pixel_values = tf.transpose(pixel_values, perm=(0, 2, 3, 1))
852
+ embedding_output = self.patch_embed(pixel_values, training=training)
853
+
854
+ encoder_outputs = self.encoder(
855
+ hidden_states=embedding_output,
856
+ output_attentions=output_attentions,
857
+ output_hidden_states=output_hidden_states,
858
+ return_dict=return_dict,
859
+ training=training,
860
+ )
861
+
862
+ sequence_output = encoder_outputs[0]
863
+ sequence_output = self.layernorm(sequence_output, training=training)
864
+
865
+ # Change the hidden states from (batch_size, height, width, num_channels) to
866
+ # (batch_size, num_channels, height, width).
867
+ # The hidden states are in (batch_size, height, width, num_channels)
868
+ # shape after all stages except the MB3D blocks.
869
+ if output_hidden_states:
870
+ hidden_states = tuple(tf.transpose(h, perm=(0, 3, 1, 2)) for h in encoder_outputs[1][:-1]) + (
871
+ encoder_outputs[1][-1],
872
+ )
873
+
874
+ if not return_dict:
875
+ head_outputs = (sequence_output,)
876
+ return head_outputs + encoder_outputs[1:]
877
+
878
+ return TFBaseModelOutput(
879
+ last_hidden_state=sequence_output,
880
+ hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states,
881
+ attentions=encoder_outputs.attentions,
882
+ )
883
+
884
+ def build(self, input_shape=None):
885
+ if self.built:
886
+ return
887
+ self.built = True
888
+ if getattr(self, "patch_embed", None) is not None:
889
+ with tf.name_scope(self.patch_embed.name):
890
+ self.patch_embed.build(None)
891
+ if getattr(self, "encoder", None) is not None:
892
+ with tf.name_scope(self.encoder.name):
893
+ self.encoder.build(None)
894
+ if getattr(self, "layernorm", None) is not None:
895
+ with tf.name_scope(self.layernorm.name):
896
+ self.layernorm.build([None, None, self.config.hidden_sizes[-1]])
897
+
898
+
899
+ class TFEfficientFormerPreTrainedModel(TFPreTrainedModel):
900
+ """
901
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
902
+ models.
903
+ """
904
+
905
+ config_class = EfficientFormerConfig
906
+ base_model_prefix = "efficientformer"
907
+ main_input_name = "pixel_values"
908
+
909
+
910
+ EFFICIENTFORMER_START_DOCSTRING = r"""
911
+ This model is a TensorFlow
912
+ [keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer). Use it as a regular
913
+ TensorFlow Module and refer to the TensorFlow documentation for all matter related to general usage and behavior.
914
+
915
+
916
+ Parameters:
917
+ config ([`EfficientFormerConfig`]): Model configuration class with all the parameters of the model.
918
+ Initializing with a config file does not load the weights associated with the model, only the
919
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
920
+ """
921
+
922
+ EFFICIENTFORMER_INPUTS_DOCSTRING = r"""
923
+ Args:
924
+ pixel_values ((`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
925
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
926
+ [`EfficientFormerImageProcessor.__call__`] for details.
927
+ output_attentions (`bool`, *optional*):
928
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
929
+ tensors for more detail.
930
+ output_hidden_states (`bool`, *optional*):
931
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
932
+ more detail.
933
+ return_dict (`bool`, *optional*):
934
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
935
+ """
936
+
937
+
938
+ @add_start_docstrings(
939
+ "The bare EfficientFormer Model transformer outputting raw hidden-states without any specific head on top.",
940
+ EFFICIENTFORMER_START_DOCSTRING,
941
+ )
942
+ class TFEfficientFormerModel(TFEfficientFormerPreTrainedModel):
943
+ def __init__(self, config: EfficientFormerConfig, **kwargs) -> None:
944
+ super().__init__(config, **kwargs)
945
+
946
+ self.efficientformer = TFEfficientFormerMainLayer(config, name="efficientformer")
947
+
948
+ @unpack_inputs
949
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
950
+ @add_code_sample_docstrings(
951
+ checkpoint=_CHECKPOINT_FOR_DOC,
952
+ output_type=TFBaseModelOutputWithPooling,
953
+ config_class=_CONFIG_FOR_DOC,
954
+ modality="vision",
955
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
956
+ )
957
+ def call(
958
+ self,
959
+ pixel_values: Optional[tf.Tensor] = None,
960
+ output_attentions: Optional[bool] = None,
961
+ output_hidden_states: Optional[bool] = None,
962
+ return_dict: Optional[bool] = None,
963
+ training: bool = False,
964
+ ) -> Union[tuple, TFBaseModelOutput]:
965
+ outputs = self.efficientformer(
966
+ pixel_values=pixel_values,
967
+ output_attentions=output_attentions,
968
+ output_hidden_states=output_hidden_states,
969
+ return_dict=return_dict,
970
+ training=training,
971
+ )
972
+ return outputs
973
+
974
+ def build(self, input_shape=None):
975
+ if self.built:
976
+ return
977
+ self.built = True
978
+ if getattr(self, "efficientformer", None) is not None:
979
+ with tf.name_scope(self.efficientformer.name):
980
+ self.efficientformer.build(None)
981
+
982
+
983
+ @add_start_docstrings(
984
+ """
985
+ EfficientFormer Model transformer with an image classification head on top of pooled last hidden state, e.g. for
986
+ ImageNet.
987
+ """,
988
+ EFFICIENTFORMER_START_DOCSTRING,
989
+ )
990
+ class TFEfficientFormerForImageClassification(TFEfficientFormerPreTrainedModel, TFSequenceClassificationLoss):
991
+ def __init__(self, config: EfficientFormerConfig):
992
+ super().__init__(config)
993
+
994
+ self.num_labels = config.num_labels
995
+ self.efficientformer = TFEfficientFormerMainLayer(config, name="efficientformer")
996
+
997
+ # Classifier head
998
+ self.classifier = (
999
+ keras.layers.Dense(config.num_labels, name="classifier")
1000
+ if config.num_labels > 0
1001
+ else keras.layers.Activation("linear", name="classifier")
1002
+ )
1003
+ self.config = config
1004
+
1005
+ @unpack_inputs
1006
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
1007
+ @add_code_sample_docstrings(
1008
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
1009
+ output_type=TFImageClassifierOutput,
1010
+ config_class=_CONFIG_FOR_DOC,
1011
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
1012
+ )
1013
+ def call(
1014
+ self,
1015
+ pixel_values: Optional[tf.Tensor] = None,
1016
+ labels: Optional[tf.Tensor] = None,
1017
+ output_attentions: Optional[bool] = None,
1018
+ output_hidden_states: Optional[bool] = None,
1019
+ return_dict: Optional[bool] = None,
1020
+ training: bool = False,
1021
+ ) -> Union[tf.Tensor, TFImageClassifierOutput]:
1022
+ r"""
1023
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1024
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
1025
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1026
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1027
+ """
1028
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1029
+
1030
+ outputs = self.efficientformer(
1031
+ pixel_values=pixel_values,
1032
+ output_attentions=output_attentions,
1033
+ output_hidden_states=output_hidden_states,
1034
+ return_dict=return_dict,
1035
+ training=training,
1036
+ )
1037
+
1038
+ sequence_output = outputs[0]
1039
+
1040
+ logits = self.classifier(tf.reduce_mean(sequence_output, axis=-2))
1041
+
1042
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1043
+
1044
+ if not return_dict:
1045
+ output = (logits,) + outputs[1:]
1046
+ return ((loss,) + output) if loss is not None else output
1047
+
1048
+ return TFImageClassifierOutput(
1049
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
1050
+ )
1051
+
1052
+ def build(self, input_shape=None):
1053
+ if self.built:
1054
+ return
1055
+ self.built = True
1056
+ if getattr(self, "efficientformer", None) is not None:
1057
+ with tf.name_scope(self.efficientformer.name):
1058
+ self.efficientformer.build(None)
1059
+ if getattr(self, "classifier", None) is not None:
1060
+ if hasattr(self.classifier, "name"):
1061
+ with tf.name_scope(self.classifier.name):
1062
+ self.classifier.build([None, None, self.config.hidden_sizes[-1]])
1063
+
1064
+
1065
+ @dataclass
1066
+ class TFEfficientFormerForImageClassificationWithTeacherOutput(ModelOutput):
1067
+ """
1068
+ Args:
1069
+ Output type of [`EfficientFormerForImageClassificationWithTeacher`].
1070
+ logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
1071
+ Prediction scores as the average of the cls_logits and distillation logits.
1072
+ cls_logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
1073
+ Prediction scores of the classification head (i.e. the linear layer on top of the final hidden state of the
1074
+ class token).
1075
+ distillation_logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
1076
+ Prediction scores of the distillation head (i.e. the linear layer on top of the final hidden state of the
1077
+ distillation token).
1078
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when
1079
+ `config.output_hidden_states=True`):
1080
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
1081
+ `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus
1082
+ the initial embedding outputs.
1083
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when
1084
+ `config.output_attentions=True`):
1085
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
1086
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
1087
+ the self-attention heads.
1088
+ """
1089
+
1090
+ logits: Optional[tf.Tensor] = None
1091
+ cls_logits: Optional[tf.Tensor] = None
1092
+ distillation_logits: Optional[tf.Tensor] = None
1093
+ hidden_states: Optional[tuple[tf.Tensor]] = None
1094
+ attentions: Optional[tuple[tf.Tensor]] = None
1095
+
1096
+
1097
+ @add_start_docstrings(
1098
+ """
1099
+ EfficientFormer Model transformer with image classification heads on top (a linear layer on top of the final hidden
1100
+ state and a linear layer on top of the final hidden state of the distillation token) e.g. for ImageNet.
1101
+
1102
+ .. warning::
1103
+ This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
1104
+ supported.
1105
+ """,
1106
+ EFFICIENTFORMER_START_DOCSTRING,
1107
+ )
1108
+ class TFEfficientFormerForImageClassificationWithTeacher(TFEfficientFormerPreTrainedModel):
1109
+ def __init__(self, config: EfficientFormerConfig) -> None:
1110
+ super().__init__(config)
1111
+
1112
+ self.num_labels = config.num_labels
1113
+ self.efficientformer = TFEfficientFormerMainLayer(config, name="efficientformer")
1114
+
1115
+ # Classifier heads
1116
+ self.classifier = (
1117
+ keras.layers.Dense(config.num_labels, name="classifier")
1118
+ if config.num_labels > 0
1119
+ else keras.layers.Activation("linear", name="classifier")
1120
+ )
1121
+ self.distillation_classifier = (
1122
+ keras.layers.Dense(config.num_labels, name="distillation_classifier")
1123
+ if config.num_labels > 0
1124
+ else keras.layers.Activation("linear", name="distillation_classifier")
1125
+ )
1126
+
1127
+ @unpack_inputs
1128
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
1129
+ @add_code_sample_docstrings(
1130
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
1131
+ output_type=TFEfficientFormerForImageClassificationWithTeacherOutput,
1132
+ config_class=_CONFIG_FOR_DOC,
1133
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
1134
+ )
1135
+ def call(
1136
+ self,
1137
+ pixel_values: Optional[tf.Tensor] = None,
1138
+ output_attentions: Optional[bool] = None,
1139
+ output_hidden_states: Optional[bool] = None,
1140
+ return_dict: Optional[bool] = None,
1141
+ training: bool = False,
1142
+ ) -> Union[tuple, TFEfficientFormerForImageClassificationWithTeacherOutput]:
1143
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1144
+
1145
+ if training:
1146
+ raise Exception(
1147
+ "This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet supported."
1148
+ )
1149
+
1150
+ outputs = self.efficientformer(
1151
+ pixel_values=pixel_values,
1152
+ output_attentions=output_attentions,
1153
+ output_hidden_states=output_hidden_states,
1154
+ return_dict=return_dict,
1155
+ training=training,
1156
+ )
1157
+
1158
+ sequence_output = outputs[0]
1159
+
1160
+ cls_logits = self.classifier(tf.reduce_mean(sequence_output, axis=-2))
1161
+ distillation_logits = self.distillation_classifier(tf.reduce_mean(sequence_output, axis=-2))
1162
+ logits = (cls_logits + distillation_logits) / 2
1163
+
1164
+ if not return_dict:
1165
+ output = (logits, cls_logits, distillation_logits) + outputs[1:]
1166
+ return output
1167
+
1168
+ return TFEfficientFormerForImageClassificationWithTeacherOutput(
1169
+ logits=logits,
1170
+ cls_logits=cls_logits,
1171
+ distillation_logits=distillation_logits,
1172
+ hidden_states=outputs.hidden_states,
1173
+ attentions=outputs.attentions,
1174
+ )
1175
+
1176
+ def build(self, input_shape=None):
1177
+ if self.built:
1178
+ return
1179
+ self.built = True
1180
+ if getattr(self, "efficientformer", None) is not None:
1181
+ with tf.name_scope(self.efficientformer.name):
1182
+ self.efficientformer.build(None)
1183
+ if getattr(self, "classifier", None) is not None:
1184
+ if hasattr(self.classifier, "name"):
1185
+ with tf.name_scope(self.classifier.name):
1186
+ self.classifier.build([None, None, self.config.hidden_sizes[-1]])
1187
+ if getattr(self, "distillation_classifier", None) is not None:
1188
+ if hasattr(self.distillation_classifier, "name"):
1189
+ with tf.name_scope(self.distillation_classifier.name):
1190
+ self.distillation_classifier.build([None, None, self.config.hidden_sizes[-1]])
1191
+
1192
+
1193
+ __all__ = [
1194
+ "TFEfficientFormerForImageClassification",
1195
+ "TFEfficientFormerForImageClassificationWithTeacher",
1196
+ "TFEfficientFormerModel",
1197
+ "TFEfficientFormerPreTrainedModel",
1198
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/ernie_m/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace and Baidu Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ....utils import _LazyModule
17
+ from ....utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_ernie_m import *
22
+ from .modeling_ernie_m import *
23
+ from .tokenization_ernie_m import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/ernie_m/configuration_ernie_m.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Xuan Ouyang, Shuohuan Wang, Chao Pang, Yu Sun, Hao Tian, Hua Wu, Haifeng Wang 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
+ """ErnieM model configuration"""
16
+ # Adapted from original paddlenlp repository.(https://github.com/PaddlePaddle/PaddleNLP/blob/develop/paddlenlp/transformers/ernie_m/configuration.py)
17
+
18
+ from __future__ import annotations
19
+
20
+ from ....configuration_utils import PretrainedConfig
21
+
22
+
23
+ class ErnieMConfig(PretrainedConfig):
24
+ r"""
25
+ This is the configuration class to store the configuration of a [`ErnieMModel`]. It is used to instantiate a
26
+ Ernie-M model according to the specified arguments, defining the model architecture. Instantiating a configuration
27
+ with the defaults will yield a similar configuration to that of the `Ernie-M`
28
+ [susnato/ernie-m-base_pytorch](https://huggingface.co/susnato/ernie-m-base_pytorch) architecture.
29
+
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 250002):
36
+ Vocabulary size of `inputs_ids` in [`ErnieMModel`]. Also is the vocab size of token embedding matrix.
37
+ Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling
38
+ [`ErnieMModel`].
39
+ hidden_size (`int`, *optional*, defaults to 768):
40
+ Dimensionality of the embedding layer, encoder layers and pooler layer.
41
+ num_hidden_layers (`int`, *optional*, defaults to 12):
42
+ Number of hidden layers in the Transformer encoder.
43
+ num_attention_heads (`int`, *optional*, defaults to 12):
44
+ Number of attention heads for each attention layer in the Transformer encoder.
45
+ intermediate_size (`int`, *optional*, defaults to 3072):
46
+ Dimensionality of the feed-forward (ff) layer in the encoder. Input tensors to feed-forward layers are
47
+ firstly projected from hidden_size to intermediate_size, and then projected back to hidden_size. Typically
48
+ intermediate_size is larger than hidden_size.
49
+ hidden_act (`str`, *optional*, defaults to `"gelu"`):
50
+ The non-linear activation function in the feed-forward layer. `"gelu"`, `"relu"` and any other torch
51
+ supported activation functions are supported.
52
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
53
+ The dropout probability for all fully connected layers in the embeddings and encoder.
54
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
55
+ The dropout probability used in `MultiHeadAttention` in all encoder layers to drop some attention target.
56
+ max_position_embeddings (`int`, *optional*, defaults to 514):
57
+ The maximum value of the dimensionality of position encoding, which dictates the maximum supported length
58
+ of an input sequence.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the normal initializer for initializing all weight matrices. The index of padding
61
+ token in the token vocabulary.
62
+ pad_token_id (`int`, *optional*, defaults to 1):
63
+ Padding token id.
64
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
65
+ The epsilon used by the layer normalization layers.
66
+ classifier_dropout (`float`, *optional*):
67
+ The dropout ratio for the classification head.
68
+ act_dropout (`float`, *optional*, defaults to 0.0):
69
+ This dropout probability is used in `ErnieMEncoderLayer` after activation.
70
+
71
+ A normal_initializer initializes weight matrices as normal distributions. See
72
+ `ErnieMPretrainedModel._init_weights()` for how weights are initialized in `ErnieMModel`.
73
+ """
74
+
75
+ model_type = "ernie_m"
76
+ attribute_map: dict[str, str] = {"dropout": "classifier_dropout", "num_classes": "num_labels"}
77
+
78
+ def __init__(
79
+ self,
80
+ vocab_size: int = 250002,
81
+ hidden_size: int = 768,
82
+ num_hidden_layers: int = 12,
83
+ num_attention_heads: int = 12,
84
+ intermediate_size: int = 3072,
85
+ hidden_act: str = "gelu",
86
+ hidden_dropout_prob: float = 0.1,
87
+ attention_probs_dropout_prob: float = 0.1,
88
+ max_position_embeddings: int = 514,
89
+ initializer_range: float = 0.02,
90
+ pad_token_id: int = 1,
91
+ layer_norm_eps: float = 1e-05,
92
+ classifier_dropout=None,
93
+ act_dropout=0.0,
94
+ **kwargs,
95
+ ):
96
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
97
+ self.vocab_size = vocab_size
98
+ self.hidden_size = hidden_size
99
+ self.num_hidden_layers = num_hidden_layers
100
+ self.num_attention_heads = num_attention_heads
101
+ self.intermediate_size = intermediate_size
102
+ self.hidden_act = hidden_act
103
+ self.hidden_dropout_prob = hidden_dropout_prob
104
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
105
+ self.max_position_embeddings = max_position_embeddings
106
+ self.initializer_range = initializer_range
107
+ self.layer_norm_eps = layer_norm_eps
108
+ self.classifier_dropout = classifier_dropout
109
+ self.act_dropout = act_dropout
110
+
111
+
112
+ __all__ = ["ErnieMConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/ernie_m/modeling_ernie_m.py ADDED
@@ -0,0 +1,1061 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Xuan Ouyang, Shuohuan Wang, Chao Pang, Yu Sun, Hao Tian, Hua Wu, Haifeng Wang 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 ErnieM model."""
16
+
17
+ import math
18
+ from typing import Optional, Union
19
+
20
+ import torch
21
+ from torch import nn, tensor
22
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
23
+
24
+ from ....activations import ACT2FN
25
+ from ....cache_utils import Cache
26
+ from ....modeling_outputs import (
27
+ BaseModelOutputWithPastAndCrossAttentions,
28
+ BaseModelOutputWithPoolingAndCrossAttentions,
29
+ MultipleChoiceModelOutput,
30
+ QuestionAnsweringModelOutput,
31
+ SequenceClassifierOutput,
32
+ TokenClassifierOutput,
33
+ )
34
+ from ....modeling_utils import PreTrainedModel
35
+ from ....pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
36
+ from ....utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
37
+ from ....utils.deprecation import deprecate_kwarg
38
+ from .configuration_ernie_m import ErnieMConfig
39
+
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+ _CHECKPOINT_FOR_DOC = "susnato/ernie-m-base_pytorch"
44
+ _CONFIG_FOR_DOC = "ErnieMConfig"
45
+ _TOKENIZER_FOR_DOC = "ErnieMTokenizer"
46
+
47
+
48
+ # Adapted from paddlenlp.transformers.ernie_m.modeling.ErnieEmbeddings
49
+ class ErnieMEmbeddings(nn.Module):
50
+ """Construct the embeddings from word and position embeddings."""
51
+
52
+ def __init__(self, config):
53
+ super().__init__()
54
+ self.hidden_size = config.hidden_size
55
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
56
+ self.position_embeddings = nn.Embedding(
57
+ config.max_position_embeddings, config.hidden_size, padding_idx=config.pad_token_id
58
+ )
59
+ self.layer_norm = nn.LayerNorm(normalized_shape=config.hidden_size, eps=config.layer_norm_eps)
60
+ self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
61
+ self.padding_idx = config.pad_token_id
62
+
63
+ def forward(
64
+ self,
65
+ input_ids: Optional[torch.LongTensor] = None,
66
+ position_ids: Optional[torch.LongTensor] = None,
67
+ inputs_embeds: Optional[torch.LongTensor] = None,
68
+ past_key_values_length: int = 0,
69
+ ) -> torch.Tensor:
70
+ if inputs_embeds is None:
71
+ inputs_embeds = self.word_embeddings(input_ids)
72
+ if position_ids is None:
73
+ input_shape = inputs_embeds.size()[:-1]
74
+ ones = torch.ones(input_shape, dtype=torch.int64, device=inputs_embeds.device)
75
+ seq_length = torch.cumsum(ones, dim=1)
76
+ position_ids = seq_length - ones
77
+
78
+ if past_key_values_length > 0:
79
+ position_ids = position_ids + past_key_values_length
80
+ # to mimic paddlenlp implementation
81
+ position_ids += 2
82
+ position_embeddings = self.position_embeddings(position_ids)
83
+ embeddings = inputs_embeds + position_embeddings
84
+ embeddings = self.layer_norm(embeddings)
85
+ embeddings = self.dropout(embeddings)
86
+
87
+ return embeddings
88
+
89
+
90
+ class ErnieMSelfAttention(nn.Module):
91
+ def __init__(self, config, position_embedding_type=None):
92
+ super().__init__()
93
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
94
+ raise ValueError(
95
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
96
+ f"heads ({config.num_attention_heads})"
97
+ )
98
+
99
+ self.num_attention_heads = config.num_attention_heads
100
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
101
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
102
+
103
+ self.q_proj = nn.Linear(config.hidden_size, self.all_head_size)
104
+ self.k_proj = nn.Linear(config.hidden_size, self.all_head_size)
105
+ self.v_proj = nn.Linear(config.hidden_size, self.all_head_size)
106
+
107
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
108
+ self.position_embedding_type = position_embedding_type or getattr(
109
+ config, "position_embedding_type", "absolute"
110
+ )
111
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
112
+ self.max_position_embeddings = config.max_position_embeddings
113
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
114
+
115
+ self.is_decoder = config.is_decoder
116
+
117
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
118
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
119
+ x = x.view(new_x_shape)
120
+ return x.permute(0, 2, 1, 3)
121
+
122
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
123
+ def forward(
124
+ self,
125
+ hidden_states: torch.Tensor,
126
+ attention_mask: Optional[torch.FloatTensor] = None,
127
+ head_mask: Optional[torch.FloatTensor] = None,
128
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
129
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
130
+ past_key_values: Optional[Cache] = None,
131
+ output_attentions: Optional[bool] = False,
132
+ ) -> tuple[torch.Tensor]:
133
+ mixed_query_layer = self.q_proj(hidden_states)
134
+
135
+ # If this is instantiated as a cross-attention module, the keys
136
+ # and values come from an encoder; the attention mask needs to be
137
+ # such that the encoder's padding tokens are not attended to.
138
+ is_cross_attention = encoder_hidden_states is not None
139
+
140
+ if is_cross_attention and past_key_values is not None:
141
+ # reuse k,v, cross_attentions
142
+ key_layer = past_key_values[0]
143
+ value_layer = past_key_values[1]
144
+ attention_mask = encoder_attention_mask
145
+ elif is_cross_attention:
146
+ key_layer = self.transpose_for_scores(self.k_proj(encoder_hidden_states))
147
+ value_layer = self.transpose_for_scores(self.v_proj(encoder_hidden_states))
148
+ attention_mask = encoder_attention_mask
149
+ elif past_key_values is not None:
150
+ key_layer = self.transpose_for_scores(self.k_proj(hidden_states))
151
+ value_layer = self.transpose_for_scores(self.v_proj(hidden_states))
152
+ key_layer = torch.cat([past_key_values[0], key_layer], dim=2)
153
+ value_layer = torch.cat([past_key_values[1], value_layer], dim=2)
154
+ else:
155
+ key_layer = self.transpose_for_scores(self.k_proj(hidden_states))
156
+ value_layer = self.transpose_for_scores(self.v_proj(hidden_states))
157
+
158
+ query_layer = self.transpose_for_scores(mixed_query_layer)
159
+
160
+ use_cache = past_key_values is not None
161
+ if self.is_decoder:
162
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
163
+ # Further calls to cross_attention layer can then reuse all cross-attention
164
+ # key/value_states (first "if" case)
165
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
166
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
167
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
168
+ # if encoder bi-directional self-attention `past_key_values` is always `None`
169
+ past_key_values = (key_layer, value_layer)
170
+
171
+ # Take the dot product between "query" and "key" to get the raw attention scores.
172
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
173
+
174
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
175
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
176
+ if use_cache:
177
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
178
+ -1, 1
179
+ )
180
+ else:
181
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
182
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
183
+ distance = position_ids_l - position_ids_r
184
+
185
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
186
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
187
+
188
+ if self.position_embedding_type == "relative_key":
189
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
190
+ attention_scores = attention_scores + relative_position_scores
191
+ elif self.position_embedding_type == "relative_key_query":
192
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
193
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
194
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
195
+
196
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
197
+ if attention_mask is not None:
198
+ # Apply the attention mask is (precomputed for all layers in ErnieMModel forward() function)
199
+ attention_scores = attention_scores + attention_mask
200
+
201
+ # Normalize the attention scores to probabilities.
202
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
203
+
204
+ # This is actually dropping out entire tokens to attend to, which might
205
+ # seem a bit unusual, but is taken from the original Transformer paper.
206
+ attention_probs = self.dropout(attention_probs)
207
+
208
+ # Mask heads if we want to
209
+ if head_mask is not None:
210
+ attention_probs = attention_probs * head_mask
211
+
212
+ context_layer = torch.matmul(attention_probs, value_layer)
213
+
214
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
215
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
216
+ context_layer = context_layer.view(new_context_layer_shape)
217
+
218
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
219
+
220
+ if self.is_decoder:
221
+ outputs = outputs + (past_key_values,)
222
+ return outputs
223
+
224
+
225
+ class ErnieMAttention(nn.Module):
226
+ def __init__(self, config, position_embedding_type=None):
227
+ super().__init__()
228
+ self.self_attn = ErnieMSelfAttention(config, position_embedding_type=position_embedding_type)
229
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size)
230
+ self.pruned_heads = set()
231
+
232
+ def prune_heads(self, heads):
233
+ if len(heads) == 0:
234
+ return
235
+ heads, index = find_pruneable_heads_and_indices(
236
+ heads, self.self_attn.num_attention_heads, self.self_attn.attention_head_size, self.pruned_heads
237
+ )
238
+
239
+ # Prune linear layers
240
+ self.self_attn.q_proj = prune_linear_layer(self.self_attn.q_proj, index)
241
+ self.self_attn.k_proj = prune_linear_layer(self.self_attn.k_proj, index)
242
+ self.self_attn.v_proj = prune_linear_layer(self.self_attn.v_proj, index)
243
+ self.out_proj = prune_linear_layer(self.out_proj, index, dim=1)
244
+
245
+ # Update hyper params and store pruned heads
246
+ self.self_attn.num_attention_heads = self.self_attn.num_attention_heads - len(heads)
247
+ self.self_attn.all_head_size = self.self_attn.attention_head_size * self.self_attn.num_attention_heads
248
+ self.pruned_heads = self.pruned_heads.union(heads)
249
+
250
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
251
+ def forward(
252
+ self,
253
+ hidden_states: torch.Tensor,
254
+ attention_mask: Optional[torch.FloatTensor] = None,
255
+ head_mask: Optional[torch.FloatTensor] = None,
256
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
257
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
258
+ past_key_values: Optional[Cache] = None,
259
+ output_attentions: Optional[bool] = False,
260
+ ) -> tuple[torch.Tensor]:
261
+ self_outputs = self.self_attn(
262
+ hidden_states,
263
+ attention_mask,
264
+ head_mask,
265
+ encoder_hidden_states,
266
+ encoder_attention_mask,
267
+ past_key_values,
268
+ output_attentions,
269
+ )
270
+ attention_output = self.out_proj(self_outputs[0])
271
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
272
+ return outputs
273
+
274
+
275
+ class ErnieMEncoderLayer(nn.Module):
276
+ def __init__(self, config):
277
+ super().__init__()
278
+ # to mimic paddlenlp implementation
279
+ dropout = 0.1 if config.hidden_dropout_prob is None else config.hidden_dropout_prob
280
+ act_dropout = config.hidden_dropout_prob if config.act_dropout is None else config.act_dropout
281
+
282
+ self.self_attn = ErnieMAttention(config)
283
+ self.linear1 = nn.Linear(config.hidden_size, config.intermediate_size)
284
+ self.dropout = nn.Dropout(act_dropout)
285
+ self.linear2 = nn.Linear(config.intermediate_size, config.hidden_size)
286
+ self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
287
+ self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
288
+ self.dropout1 = nn.Dropout(dropout)
289
+ self.dropout2 = nn.Dropout(dropout)
290
+ if isinstance(config.hidden_act, str):
291
+ self.activation = ACT2FN[config.hidden_act]
292
+ else:
293
+ self.activation = config.hidden_act
294
+
295
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
296
+ def forward(
297
+ self,
298
+ hidden_states: torch.Tensor,
299
+ attention_mask: Optional[torch.FloatTensor] = None,
300
+ head_mask: Optional[torch.FloatTensor] = None,
301
+ past_key_values: Optional[Cache] = None,
302
+ output_attentions: Optional[bool] = True,
303
+ ):
304
+ residual = hidden_states
305
+ if output_attentions:
306
+ hidden_states, attention_opt_weights = self.self_attn(
307
+ hidden_states=hidden_states,
308
+ attention_mask=attention_mask,
309
+ head_mask=head_mask,
310
+ past_key_values=past_key_values,
311
+ output_attentions=output_attentions,
312
+ )
313
+
314
+ else:
315
+ hidden_states = self.self_attn(
316
+ hidden_states=hidden_states,
317
+ attention_mask=attention_mask,
318
+ head_mask=head_mask,
319
+ past_key_values=past_key_values,
320
+ output_attentions=output_attentions,
321
+ )
322
+ hidden_states = residual + self.dropout1(hidden_states)
323
+ hidden_states = self.norm1(hidden_states)
324
+ residual = hidden_states
325
+
326
+ hidden_states = self.linear1(hidden_states)
327
+ hidden_states = self.activation(hidden_states)
328
+ hidden_states = self.dropout(hidden_states)
329
+ hidden_states = self.linear2(hidden_states)
330
+ hidden_states = residual + self.dropout2(hidden_states)
331
+ hidden_states = self.norm2(hidden_states)
332
+
333
+ if output_attentions:
334
+ return hidden_states, attention_opt_weights
335
+ else:
336
+ return hidden_states
337
+
338
+
339
+ class ErnieMEncoder(nn.Module):
340
+ def __init__(self, config):
341
+ super().__init__()
342
+ self.config = config
343
+ self.layers = nn.ModuleList([ErnieMEncoderLayer(config) for _ in range(config.num_hidden_layers)])
344
+
345
+ def forward(
346
+ self,
347
+ input_embeds: torch.Tensor,
348
+ attention_mask: Optional[torch.FloatTensor] = None,
349
+ head_mask: Optional[torch.FloatTensor] = None,
350
+ past_key_values: Optional[Cache] = None,
351
+ output_attentions: Optional[bool] = False,
352
+ output_hidden_states: Optional[bool] = False,
353
+ return_dict: Optional[bool] = True,
354
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
355
+ hidden_states = () if output_hidden_states else None
356
+ attentions = () if output_attentions else None
357
+
358
+ output = input_embeds
359
+ if output_hidden_states:
360
+ hidden_states = hidden_states + (output,)
361
+ for i, layer in enumerate(self.layers):
362
+ layer_head_mask = head_mask[i] if head_mask is not None else None
363
+
364
+ output, opt_attn_weights = layer(
365
+ hidden_states=output,
366
+ attention_mask=attention_mask,
367
+ head_mask=layer_head_mask,
368
+ past_key_values=past_key_values[i] if past_key_values is not None else None,
369
+ )
370
+
371
+ if output_hidden_states:
372
+ hidden_states = hidden_states + (output,)
373
+ if output_attentions:
374
+ attentions = attentions + (opt_attn_weights,)
375
+
376
+ last_hidden_state = output
377
+ if not return_dict:
378
+ return tuple(v for v in [last_hidden_state, hidden_states, attentions] if v is not None)
379
+
380
+ return BaseModelOutputWithPastAndCrossAttentions(
381
+ last_hidden_state=last_hidden_state, hidden_states=hidden_states, attentions=attentions
382
+ )
383
+
384
+
385
+ class ErnieMPooler(nn.Module):
386
+ def __init__(self, config):
387
+ super().__init__()
388
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
389
+ self.activation = nn.Tanh()
390
+
391
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
392
+ # We "pool" the model by simply taking the hidden state corresponding
393
+ # to the first token.
394
+ first_token_tensor = hidden_states[:, 0]
395
+ pooled_output = self.dense(first_token_tensor)
396
+ pooled_output = self.activation(pooled_output)
397
+ return pooled_output
398
+
399
+
400
+ class ErnieMPreTrainedModel(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: ErnieMConfig
407
+ base_model_prefix = "ernie_m"
408
+
409
+ def _init_weights(self, module):
410
+ """Initialize the weights"""
411
+ if isinstance(module, nn.Linear):
412
+ # Slightly different from the TF version which uses truncated_normal for initialization
413
+ # cf https://github.com/pytorch/pytorch/pull/5617
414
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
415
+ if module.bias is not None:
416
+ module.bias.data.zero_()
417
+ elif isinstance(module, nn.Embedding):
418
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
419
+ if module.padding_idx is not None:
420
+ module.weight.data[module.padding_idx].zero_()
421
+ elif isinstance(module, nn.LayerNorm):
422
+ module.bias.data.zero_()
423
+ module.weight.data.fill_(1.0)
424
+
425
+
426
+ ERNIE_M_START_DOCSTRING = r"""
427
+
428
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
429
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
430
+ etc.)
431
+
432
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
433
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
434
+ behavior.
435
+
436
+ Parameters:
437
+ config ([`ErnieMConfig`]): Model configuration class with all the parameters of the model.
438
+ Initializing with a config file does not load the weights associated with the model, only the
439
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
440
+ """
441
+
442
+ ERNIE_M_INPUTS_DOCSTRING = r"""
443
+ Args:
444
+ input_ids (`torch.LongTensor` of shape `({0})`):
445
+ Indices of input sequence tokens in the vocabulary.
446
+
447
+ Indices can be obtained using [`ErnieMTokenizer`]. See [`PreTrainedTokenizer.encode`] and
448
+ [`PreTrainedTokenizer.__call__`] for details.
449
+
450
+ [What are input IDs?](../glossary#input-ids)
451
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
452
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
453
+
454
+ - 1 for tokens that are **not masked**,
455
+ - 0 for tokens that are **masked**.
456
+
457
+ [What are attention masks?](../glossary#attention-mask)
458
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
459
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
460
+ config.max_position_embeddings - 1]`.
461
+
462
+ [What are position IDs?](../glossary#position-ids)
463
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
464
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
465
+
466
+ - 1 indicates the head is **not masked**,
467
+ - 0 indicates the head is **masked**.
468
+
469
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
470
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
471
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
472
+ model's internal embedding lookup matrix.
473
+ output_attentions (`bool`, *optional*):
474
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
475
+ tensors for more detail.
476
+ output_hidden_states (`bool`, *optional*):
477
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
478
+ more detail.
479
+ return_dict (`bool`, *optional*):
480
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
481
+ """
482
+
483
+
484
+ @add_start_docstrings(
485
+ "The bare ErnieM Model transformer outputting raw hidden-states without any specific head on top.",
486
+ ERNIE_M_START_DOCSTRING,
487
+ )
488
+ class ErnieMModel(ErnieMPreTrainedModel):
489
+ def __init__(self, config, add_pooling_layer=True):
490
+ super().__init__(config)
491
+ self.initializer_range = config.initializer_range
492
+ self.embeddings = ErnieMEmbeddings(config)
493
+ self.encoder = ErnieMEncoder(config)
494
+ self.pooler = ErnieMPooler(config) if add_pooling_layer else None
495
+ self.post_init()
496
+
497
+ def get_input_embeddings(self):
498
+ return self.embeddings.word_embeddings
499
+
500
+ def set_input_embeddings(self, value):
501
+ self.embeddings.word_embeddings = value
502
+
503
+ def _prune_heads(self, heads_to_prune):
504
+ """
505
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
506
+ class PreTrainedModel
507
+ """
508
+ for layer, heads in heads_to_prune.items():
509
+ self.encoder.layers[layer].self_attn.prune_heads(heads)
510
+
511
+ @add_start_docstrings_to_model_forward(ERNIE_M_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
512
+ @add_code_sample_docstrings(
513
+ processor_class=_TOKENIZER_FOR_DOC,
514
+ checkpoint=_CHECKPOINT_FOR_DOC,
515
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
516
+ config_class=_CONFIG_FOR_DOC,
517
+ )
518
+ def forward(
519
+ self,
520
+ input_ids: Optional[tensor] = None,
521
+ position_ids: Optional[tensor] = None,
522
+ attention_mask: Optional[tensor] = None,
523
+ head_mask: Optional[tensor] = None,
524
+ inputs_embeds: Optional[tensor] = None,
525
+ past_key_values: Optional[tuple[tuple[tensor]]] = None,
526
+ use_cache: Optional[bool] = None,
527
+ output_hidden_states: Optional[bool] = None,
528
+ output_attentions: Optional[bool] = None,
529
+ return_dict: Optional[bool] = None,
530
+ ) -> Union[tuple[torch.FloatTensor], BaseModelOutputWithPoolingAndCrossAttentions]:
531
+ if input_ids is not None and inputs_embeds is not None:
532
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time.")
533
+
534
+ # init the default bool value
535
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
536
+ output_hidden_states = (
537
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
538
+ )
539
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
540
+
541
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
542
+
543
+ past_key_values_length = 0
544
+ if past_key_values is not None:
545
+ past_key_values_length = past_key_values.get_seq_length()
546
+
547
+ # Adapted from paddlenlp.transformers.ernie_m.ErnieMModel
548
+ if attention_mask is None:
549
+ attention_mask = (input_ids == self.config.pad_token_id).to(torch.float32)
550
+ attention_mask *= torch.finfo(attention_mask.dtype).min
551
+ if past_key_values is not None:
552
+ batch_size = past_key_values[0][0].shape[0]
553
+ past_mask = torch.zeros([batch_size, 1, 1, past_key_values_length], dtype=attention_mask.dtype)
554
+ attention_mask = torch.concat([past_mask, attention_mask], dim=-1)
555
+ # For 2D attention_mask from tokenizer
556
+ elif attention_mask.ndim == 2:
557
+ attention_mask = attention_mask.to(torch.float32)
558
+ attention_mask = 1.0 - attention_mask
559
+ attention_mask *= torch.finfo(attention_mask.dtype).min
560
+
561
+ extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(1)
562
+
563
+ embedding_output = self.embeddings(
564
+ input_ids=input_ids,
565
+ position_ids=position_ids,
566
+ inputs_embeds=inputs_embeds,
567
+ past_key_values_length=past_key_values_length,
568
+ )
569
+ encoder_outputs = self.encoder(
570
+ embedding_output,
571
+ attention_mask=extended_attention_mask,
572
+ head_mask=head_mask,
573
+ past_key_values=past_key_values,
574
+ output_attentions=output_attentions,
575
+ output_hidden_states=output_hidden_states,
576
+ return_dict=return_dict,
577
+ )
578
+
579
+ if not return_dict:
580
+ sequence_output = encoder_outputs[0]
581
+ pooler_output = self.pooler(sequence_output) if self.pooler is not None else None
582
+ return (sequence_output, pooler_output) + encoder_outputs[1:]
583
+
584
+ sequence_output = encoder_outputs["last_hidden_state"]
585
+ pooler_output = self.pooler(sequence_output) if self.pooler is not None else None
586
+ hidden_states = None if not output_hidden_states else encoder_outputs["hidden_states"]
587
+ attentions = None if not output_attentions else encoder_outputs["attentions"]
588
+
589
+ return BaseModelOutputWithPoolingAndCrossAttentions(
590
+ last_hidden_state=sequence_output,
591
+ pooler_output=pooler_output,
592
+ hidden_states=hidden_states,
593
+ attentions=attentions,
594
+ )
595
+
596
+
597
+ @add_start_docstrings(
598
+ """ErnieM Model transformer with a sequence classification/regression head on top (a linear layer on top of
599
+ the pooled output) e.g. for GLUE tasks.""",
600
+ ERNIE_M_START_DOCSTRING,
601
+ )
602
+ class ErnieMForSequenceClassification(ErnieMPreTrainedModel):
603
+ def __init__(self, config):
604
+ super().__init__(config)
605
+ self.num_labels = config.num_labels
606
+ self.config = config
607
+
608
+ self.ernie_m = ErnieMModel(config)
609
+ classifier_dropout = (
610
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
611
+ )
612
+ self.dropout = nn.Dropout(classifier_dropout)
613
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
614
+
615
+ # Initialize weights and apply final processing
616
+ self.post_init()
617
+
618
+ @add_start_docstrings_to_model_forward(ERNIE_M_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
619
+ @add_code_sample_docstrings(
620
+ processor_class=_TOKENIZER_FOR_DOC,
621
+ checkpoint=_CHECKPOINT_FOR_DOC,
622
+ output_type=SequenceClassifierOutput,
623
+ config_class=_CONFIG_FOR_DOC,
624
+ )
625
+ def forward(
626
+ self,
627
+ input_ids: Optional[torch.Tensor] = None,
628
+ attention_mask: Optional[torch.Tensor] = None,
629
+ position_ids: Optional[torch.Tensor] = None,
630
+ head_mask: Optional[torch.Tensor] = None,
631
+ inputs_embeds: Optional[torch.Tensor] = None,
632
+ past_key_values: Optional[Cache] = None,
633
+ use_cache: Optional[bool] = None,
634
+ output_hidden_states: Optional[bool] = None,
635
+ output_attentions: Optional[bool] = None,
636
+ return_dict: Optional[bool] = True,
637
+ labels: Optional[torch.Tensor] = None,
638
+ ) -> Union[tuple[torch.FloatTensor], SequenceClassifierOutput]:
639
+ r"""
640
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
641
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
642
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
643
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
644
+ """
645
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
646
+
647
+ outputs = self.ernie_m(
648
+ input_ids,
649
+ attention_mask=attention_mask,
650
+ position_ids=position_ids,
651
+ head_mask=head_mask,
652
+ inputs_embeds=inputs_embeds,
653
+ past_key_values=past_key_values,
654
+ output_hidden_states=output_hidden_states,
655
+ output_attentions=output_attentions,
656
+ return_dict=return_dict,
657
+ )
658
+
659
+ pooled_output = outputs[1]
660
+
661
+ pooled_output = self.dropout(pooled_output)
662
+ logits = self.classifier(pooled_output)
663
+
664
+ loss = None
665
+ if labels is not None:
666
+ if self.config.problem_type is None:
667
+ if self.num_labels == 1:
668
+ self.config.problem_type = "regression"
669
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
670
+ self.config.problem_type = "single_label_classification"
671
+ else:
672
+ self.config.problem_type = "multi_label_classification"
673
+
674
+ if self.config.problem_type == "regression":
675
+ loss_fct = MSELoss()
676
+ if self.num_labels == 1:
677
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
678
+ else:
679
+ loss = loss_fct(logits, labels)
680
+ elif self.config.problem_type == "single_label_classification":
681
+ loss_fct = CrossEntropyLoss()
682
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
683
+ elif self.config.problem_type == "multi_label_classification":
684
+ loss_fct = BCEWithLogitsLoss()
685
+ loss = loss_fct(logits, labels)
686
+ if not return_dict:
687
+ output = (logits,) + outputs[2:]
688
+ return ((loss,) + output) if loss is not None else output
689
+
690
+ return SequenceClassifierOutput(
691
+ loss=loss,
692
+ logits=logits,
693
+ hidden_states=outputs.hidden_states,
694
+ attentions=outputs.attentions,
695
+ )
696
+
697
+
698
+ @add_start_docstrings(
699
+ """ErnieM Model with a multiple choice classification head on top (a linear layer on top of
700
+ the pooled output and a softmax) e.g. for RocStories/SWAG tasks.""",
701
+ ERNIE_M_START_DOCSTRING,
702
+ )
703
+ class ErnieMForMultipleChoice(ErnieMPreTrainedModel):
704
+ def __init__(self, config):
705
+ super().__init__(config)
706
+
707
+ self.ernie_m = ErnieMModel(config)
708
+ classifier_dropout = (
709
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
710
+ )
711
+ self.dropout = nn.Dropout(classifier_dropout)
712
+ self.classifier = nn.Linear(config.hidden_size, 1)
713
+
714
+ # Initialize weights and apply final processing
715
+ self.post_init()
716
+
717
+ @add_start_docstrings_to_model_forward(ERNIE_M_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
718
+ @add_code_sample_docstrings(
719
+ checkpoint=_CHECKPOINT_FOR_DOC,
720
+ output_type=MultipleChoiceModelOutput,
721
+ config_class=_CONFIG_FOR_DOC,
722
+ )
723
+ def forward(
724
+ self,
725
+ input_ids: Optional[torch.Tensor] = None,
726
+ attention_mask: Optional[torch.Tensor] = None,
727
+ position_ids: Optional[torch.Tensor] = None,
728
+ head_mask: Optional[torch.Tensor] = None,
729
+ inputs_embeds: Optional[torch.Tensor] = None,
730
+ labels: Optional[torch.Tensor] = None,
731
+ output_attentions: Optional[bool] = None,
732
+ output_hidden_states: Optional[bool] = None,
733
+ return_dict: Optional[bool] = True,
734
+ ) -> Union[tuple[torch.FloatTensor], MultipleChoiceModelOutput]:
735
+ r"""
736
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
737
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
738
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
739
+ `input_ids` above)
740
+ """
741
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
742
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
743
+
744
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
745
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
746
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
747
+ inputs_embeds = (
748
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
749
+ if inputs_embeds is not None
750
+ else None
751
+ )
752
+
753
+ outputs = self.ernie_m(
754
+ input_ids,
755
+ attention_mask=attention_mask,
756
+ position_ids=position_ids,
757
+ head_mask=head_mask,
758
+ inputs_embeds=inputs_embeds,
759
+ output_attentions=output_attentions,
760
+ output_hidden_states=output_hidden_states,
761
+ return_dict=return_dict,
762
+ )
763
+
764
+ pooled_output = outputs[1]
765
+
766
+ pooled_output = self.dropout(pooled_output)
767
+ logits = self.classifier(pooled_output)
768
+ reshaped_logits = logits.view(-1, num_choices)
769
+
770
+ loss = None
771
+ if labels is not None:
772
+ loss_fct = CrossEntropyLoss()
773
+ loss = loss_fct(reshaped_logits, labels)
774
+
775
+ if not return_dict:
776
+ output = (reshaped_logits,) + outputs[2:]
777
+ return ((loss,) + output) if loss is not None else output
778
+
779
+ return MultipleChoiceModelOutput(
780
+ loss=loss,
781
+ logits=reshaped_logits,
782
+ hidden_states=outputs.hidden_states,
783
+ attentions=outputs.attentions,
784
+ )
785
+
786
+
787
+ @add_start_docstrings(
788
+ """ErnieM Model with a token classification head on top (a linear layer on top of
789
+ the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.""",
790
+ ERNIE_M_START_DOCSTRING,
791
+ )
792
+ class ErnieMForTokenClassification(ErnieMPreTrainedModel):
793
+ def __init__(self, config):
794
+ super().__init__(config)
795
+ self.num_labels = config.num_labels
796
+
797
+ self.ernie_m = ErnieMModel(config, add_pooling_layer=False)
798
+ classifier_dropout = (
799
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
800
+ )
801
+ self.dropout = nn.Dropout(classifier_dropout)
802
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
803
+
804
+ # Initialize weights and apply final processing
805
+ self.post_init()
806
+
807
+ @add_start_docstrings_to_model_forward(ERNIE_M_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
808
+ @add_code_sample_docstrings(
809
+ processor_class=_TOKENIZER_FOR_DOC,
810
+ checkpoint=_CHECKPOINT_FOR_DOC,
811
+ output_type=TokenClassifierOutput,
812
+ config_class=_CONFIG_FOR_DOC,
813
+ )
814
+ def forward(
815
+ self,
816
+ input_ids: Optional[torch.Tensor] = None,
817
+ attention_mask: Optional[torch.Tensor] = None,
818
+ position_ids: Optional[torch.Tensor] = None,
819
+ head_mask: Optional[torch.Tensor] = None,
820
+ inputs_embeds: Optional[torch.Tensor] = None,
821
+ past_key_values: Optional[Cache] = None,
822
+ output_hidden_states: Optional[bool] = None,
823
+ output_attentions: Optional[bool] = None,
824
+ return_dict: Optional[bool] = True,
825
+ labels: Optional[torch.Tensor] = None,
826
+ ) -> Union[tuple[torch.FloatTensor], TokenClassifierOutput]:
827
+ r"""
828
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
829
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
830
+ """
831
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
832
+
833
+ outputs = self.ernie_m(
834
+ input_ids,
835
+ attention_mask=attention_mask,
836
+ position_ids=position_ids,
837
+ head_mask=head_mask,
838
+ inputs_embeds=inputs_embeds,
839
+ past_key_values=past_key_values,
840
+ output_attentions=output_attentions,
841
+ output_hidden_states=output_hidden_states,
842
+ return_dict=return_dict,
843
+ )
844
+
845
+ sequence_output = outputs[0]
846
+
847
+ sequence_output = self.dropout(sequence_output)
848
+ logits = self.classifier(sequence_output)
849
+
850
+ loss = None
851
+ if labels is not None:
852
+ loss_fct = CrossEntropyLoss()
853
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
854
+
855
+ if not return_dict:
856
+ output = (logits,) + outputs[2:]
857
+ return ((loss,) + output) if loss is not None else output
858
+
859
+ return TokenClassifierOutput(
860
+ loss=loss,
861
+ logits=logits,
862
+ hidden_states=outputs.hidden_states,
863
+ attentions=outputs.attentions,
864
+ )
865
+
866
+
867
+ @add_start_docstrings(
868
+ """ErnieM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
869
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).""",
870
+ ERNIE_M_START_DOCSTRING,
871
+ )
872
+ class ErnieMForQuestionAnswering(ErnieMPreTrainedModel):
873
+ def __init__(self, config):
874
+ super().__init__(config)
875
+ self.num_labels = config.num_labels
876
+
877
+ self.ernie_m = ErnieMModel(config, add_pooling_layer=False)
878
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
879
+
880
+ # Initialize weights and apply final processing
881
+ self.post_init()
882
+
883
+ @add_start_docstrings_to_model_forward(ERNIE_M_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
884
+ @add_code_sample_docstrings(
885
+ processor_class=_TOKENIZER_FOR_DOC,
886
+ checkpoint=_CHECKPOINT_FOR_DOC,
887
+ output_type=QuestionAnsweringModelOutput,
888
+ config_class=_CONFIG_FOR_DOC,
889
+ )
890
+ def forward(
891
+ self,
892
+ input_ids: Optional[torch.Tensor] = None,
893
+ attention_mask: Optional[torch.Tensor] = None,
894
+ position_ids: Optional[torch.Tensor] = None,
895
+ head_mask: Optional[torch.Tensor] = None,
896
+ inputs_embeds: Optional[torch.Tensor] = None,
897
+ start_positions: Optional[torch.Tensor] = None,
898
+ end_positions: Optional[torch.Tensor] = None,
899
+ output_attentions: Optional[bool] = None,
900
+ output_hidden_states: Optional[bool] = None,
901
+ return_dict: Optional[bool] = True,
902
+ ) -> Union[tuple[torch.FloatTensor], QuestionAnsweringModelOutput]:
903
+ r"""
904
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
905
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
906
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
907
+ are not taken into account for computing the loss.
908
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
909
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
910
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
911
+ are not taken into account for computing the loss.
912
+ """
913
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
914
+
915
+ outputs = self.ernie_m(
916
+ input_ids,
917
+ attention_mask=attention_mask,
918
+ position_ids=position_ids,
919
+ head_mask=head_mask,
920
+ inputs_embeds=inputs_embeds,
921
+ output_attentions=output_attentions,
922
+ output_hidden_states=output_hidden_states,
923
+ return_dict=return_dict,
924
+ )
925
+
926
+ sequence_output = outputs[0]
927
+
928
+ logits = self.qa_outputs(sequence_output)
929
+ start_logits, end_logits = logits.split(1, dim=-1)
930
+ start_logits = start_logits.squeeze(-1).contiguous()
931
+ end_logits = end_logits.squeeze(-1).contiguous()
932
+
933
+ total_loss = None
934
+ if start_positions is not None and end_positions is not None:
935
+ # If we are on multi-GPU, split add a dimension
936
+ if len(start_positions.size()) > 1:
937
+ start_positions = start_positions.squeeze(-1)
938
+ if len(end_positions.size()) > 1:
939
+ end_positions = end_positions.squeeze(-1)
940
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
941
+ ignored_index = start_logits.size(1)
942
+ start_positions = start_positions.clamp(0, ignored_index)
943
+ end_positions = end_positions.clamp(0, ignored_index)
944
+
945
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
946
+ start_loss = loss_fct(start_logits, start_positions)
947
+ end_loss = loss_fct(end_logits, end_positions)
948
+ total_loss = (start_loss + end_loss) / 2
949
+
950
+ if not return_dict:
951
+ output = (start_logits, end_logits) + outputs[2:]
952
+ return ((total_loss,) + output) if total_loss is not None else output
953
+
954
+ return QuestionAnsweringModelOutput(
955
+ loss=total_loss,
956
+ start_logits=start_logits,
957
+ end_logits=end_logits,
958
+ hidden_states=outputs.hidden_states,
959
+ attentions=outputs.attentions,
960
+ )
961
+
962
+
963
+ @add_start_docstrings(
964
+ """ErnieMForInformationExtraction is a Ernie-M Model with two linear layer on top of the hidden-states output to
965
+ compute `start_prob` and `end_prob`, designed for Universal Information Extraction.""",
966
+ ERNIE_M_START_DOCSTRING,
967
+ )
968
+ class ErnieMForInformationExtraction(ErnieMPreTrainedModel):
969
+ def __init__(self, config):
970
+ super().__init__(config)
971
+ self.ernie_m = ErnieMModel(config)
972
+ self.linear_start = nn.Linear(config.hidden_size, 1)
973
+ self.linear_end = nn.Linear(config.hidden_size, 1)
974
+ self.sigmoid = nn.Sigmoid()
975
+ self.post_init()
976
+
977
+ @add_start_docstrings_to_model_forward(ERNIE_M_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
978
+ def forward(
979
+ self,
980
+ input_ids: Optional[torch.Tensor] = None,
981
+ attention_mask: Optional[torch.Tensor] = None,
982
+ position_ids: Optional[torch.Tensor] = None,
983
+ head_mask: Optional[torch.Tensor] = None,
984
+ inputs_embeds: Optional[torch.Tensor] = None,
985
+ start_positions: Optional[torch.Tensor] = None,
986
+ end_positions: Optional[torch.Tensor] = None,
987
+ output_attentions: Optional[bool] = None,
988
+ output_hidden_states: Optional[bool] = None,
989
+ return_dict: Optional[bool] = True,
990
+ ) -> Union[tuple[torch.FloatTensor], QuestionAnsweringModelOutput]:
991
+ r"""
992
+ start_positions (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
993
+ Labels for position (index) for computing the start_positions loss. Position outside of the sequence are
994
+ not taken into account for computing the loss.
995
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
996
+ Labels for position (index) for computing the end_positions loss. Position outside of the sequence are not
997
+ taken into account for computing the loss.
998
+ """
999
+
1000
+ result = self.ernie_m(
1001
+ input_ids,
1002
+ attention_mask=attention_mask,
1003
+ position_ids=position_ids,
1004
+ head_mask=head_mask,
1005
+ inputs_embeds=inputs_embeds,
1006
+ output_attentions=output_attentions,
1007
+ output_hidden_states=output_hidden_states,
1008
+ return_dict=return_dict,
1009
+ )
1010
+ if return_dict:
1011
+ sequence_output = result.last_hidden_state
1012
+ elif not return_dict:
1013
+ sequence_output = result[0]
1014
+
1015
+ start_logits = self.linear_start(sequence_output)
1016
+ start_logits = start_logits.squeeze(-1)
1017
+ end_logits = self.linear_end(sequence_output)
1018
+ end_logits = end_logits.squeeze(-1)
1019
+
1020
+ total_loss = None
1021
+ if start_positions is not None and end_positions is not None:
1022
+ # If we are on multi-GPU, split add a dimension
1023
+ if len(start_positions.size()) > 1:
1024
+ start_positions = start_positions.squeeze(-1)
1025
+ if len(end_positions.size()) > 1:
1026
+ end_positions = end_positions.squeeze(-1)
1027
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1028
+ ignored_index = start_logits.size(1)
1029
+ start_positions = start_positions.clamp(0, ignored_index)
1030
+ end_positions = end_positions.clamp(0, ignored_index)
1031
+
1032
+ loss_fct = BCEWithLogitsLoss()
1033
+ start_loss = loss_fct(start_logits, start_positions)
1034
+ end_loss = loss_fct(end_logits, end_positions)
1035
+ total_loss = (start_loss + end_loss) / 2
1036
+
1037
+ if not return_dict:
1038
+ return tuple(
1039
+ i
1040
+ for i in [total_loss, start_logits, end_logits, result.hidden_states, result.attentions]
1041
+ if i is not None
1042
+ )
1043
+
1044
+ return QuestionAnsweringModelOutput(
1045
+ loss=total_loss,
1046
+ start_logits=start_logits,
1047
+ end_logits=end_logits,
1048
+ hidden_states=result.hidden_states,
1049
+ attentions=result.attentions,
1050
+ )
1051
+
1052
+
1053
+ __all__ = [
1054
+ "ErnieMForMultipleChoice",
1055
+ "ErnieMForQuestionAnswering",
1056
+ "ErnieMForSequenceClassification",
1057
+ "ErnieMForTokenClassification",
1058
+ "ErnieMModel",
1059
+ "ErnieMPreTrainedModel",
1060
+ "ErnieMForInformationExtraction",
1061
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/ernie_m/tokenization_ernie_m.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Xuan Ouyang, Shuohuan Wang, Chao Pang, Yu Sun, Hao Tian, Hua Wu, Haifeng Wang and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for Ernie-M."""
16
+
17
+ import os
18
+ import unicodedata
19
+ from typing import Any, Optional
20
+
21
+ import sentencepiece as spm
22
+
23
+ from ....tokenization_utils import PreTrainedTokenizer
24
+ from ....utils import logging
25
+ from ....utils.import_utils import requires
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ SPIECE_UNDERLINE = "▁"
31
+
32
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "sentencepiece_model_ckpt": "sentencepiece.bpe.model"}
33
+
34
+ RESOURCE_FILES_NAMES = {
35
+ "sentencepiece_model_file": "sentencepiece.bpe.model",
36
+ "vocab_file": "vocab.txt",
37
+ }
38
+
39
+
40
+ # Adapted from paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer
41
+ @requires(backends=("sentencepiece",))
42
+ class ErnieMTokenizer(PreTrainedTokenizer):
43
+ r"""
44
+ Constructs a Ernie-M tokenizer. It uses the `sentencepiece` tools to cut the words to sub-words.
45
+
46
+ Args:
47
+ sentencepiece_model_file (`str`):
48
+ The file path of sentencepiece model.
49
+ vocab_file (`str`, *optional*):
50
+ The file path of the vocabulary.
51
+ do_lower_case (`str`, *optional*, defaults to `True`):
52
+ Whether or not to lowercase the input when tokenizing.
53
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
54
+ A special token representing the `unknown (out-of-vocabulary)` token. An unknown token is set to be
55
+ `unk_token` inorder to be converted to an ID.
56
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
57
+ A special token separating two different sentences in the same input.
58
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
59
+ A special token used to make arrays of tokens the same size for batching purposes.
60
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
61
+ A special token used for sequence classification. It is the last token of the sequence when built with
62
+ special tokens.
63
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
64
+ A special token representing a masked token. This is the token used in the masked language modeling task
65
+ which the model tries to predict the original unmasked ones.
66
+ """
67
+
68
+ # Ernie-M model doesn't have token_type embedding.
69
+ model_input_names: list[str] = ["input_ids"]
70
+
71
+ vocab_files_names = VOCAB_FILES_NAMES
72
+ resource_files_names = RESOURCE_FILES_NAMES
73
+
74
+ def __init__(
75
+ self,
76
+ sentencepiece_model_ckpt,
77
+ vocab_file=None,
78
+ do_lower_case=False,
79
+ encoding="utf8",
80
+ unk_token="[UNK]",
81
+ sep_token="[SEP]",
82
+ pad_token="[PAD]",
83
+ cls_token="[CLS]",
84
+ mask_token="[MASK]",
85
+ sp_model_kwargs: Optional[dict[str, Any]] = None,
86
+ **kwargs,
87
+ ) -> None:
88
+ # Mask token behave like a normal word, i.e. include the space before it and
89
+ # is included in the raw text, there should be a match in a non-normalized sentence.
90
+
91
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
92
+
93
+ self.do_lower_case = do_lower_case
94
+ self.sentencepiece_model_ckpt = sentencepiece_model_ckpt
95
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
96
+ self.sp_model.Load(sentencepiece_model_ckpt)
97
+
98
+ # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
99
+ if vocab_file is not None:
100
+ self.vocab = self.load_vocab(filepath=vocab_file)
101
+ else:
102
+ self.vocab = {self.sp_model.id_to_piece(id): id for id in range(self.sp_model.get_piece_size())}
103
+ self.reverse_vocab = {v: k for k, v in self.vocab.items()}
104
+
105
+ super().__init__(
106
+ do_lower_case=do_lower_case,
107
+ unk_token=unk_token,
108
+ sep_token=sep_token,
109
+ pad_token=pad_token,
110
+ cls_token=cls_token,
111
+ mask_token=mask_token,
112
+ vocab_file=vocab_file,
113
+ encoding=encoding,
114
+ sp_model_kwargs=self.sp_model_kwargs,
115
+ **kwargs,
116
+ )
117
+
118
+ def get_offset_mapping(self, text):
119
+ if text is None:
120
+ return None
121
+
122
+ split_tokens = self.tokenize(text)
123
+ normalized_text, char_mapping = "", []
124
+
125
+ for i, ch in enumerate(text):
126
+ if ch in self.SP_CHAR_MAPPING:
127
+ ch = self.SP_CHAR_MAPPING.get(ch)
128
+ else:
129
+ ch = unicodedata.normalize("NFKC", ch)
130
+ if self.is_whitespace(ch):
131
+ continue
132
+ normalized_text += ch
133
+ char_mapping.extend([i] * len(ch))
134
+
135
+ text, token_mapping, offset = normalized_text, [], 0
136
+
137
+ if self.do_lower_case:
138
+ text = text.lower()
139
+
140
+ for token in split_tokens:
141
+ if token[:1] == "▁":
142
+ token = token[1:]
143
+ start = text[offset:].index(token) + offset
144
+ end = start + len(token)
145
+
146
+ token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1))
147
+ offset = end
148
+ return token_mapping
149
+
150
+ @property
151
+ def vocab_size(self):
152
+ return len(self.vocab)
153
+
154
+ def get_vocab(self):
155
+ return dict(self.vocab, **self.added_tokens_encoder)
156
+
157
+ def __getstate__(self):
158
+ state = self.__dict__.copy()
159
+ state["sp_model"] = None
160
+ return state
161
+
162
+ def __setstate__(self, d):
163
+ self.__dict__ = d
164
+
165
+ # for backward compatibility
166
+ if not hasattr(self, "sp_model_kwargs"):
167
+ self.sp_model_kwargs = {}
168
+
169
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
170
+ self.sp_model.Load(self.sentencepiece_model_ckpt)
171
+
172
+ def clean_text(self, text):
173
+ """Performs invalid character removal and whitespace cleanup on text."""
174
+ return "".join(self.SP_CHAR_MAPPING.get(c, c) for c in text)
175
+
176
+ def _tokenize(self, text, enable_sampling=False, nbest_size=64, alpha=0.1):
177
+ """Tokenize a string."""
178
+
179
+ if self.sp_model_kwargs.get("enable_sampling") is True:
180
+ enable_sampling = True
181
+ if self.sp_model_kwargs.get("alpha") is not None:
182
+ alpha = self.sp_model_kwargs.get("alpha")
183
+ if self.sp_model_kwargs.get("nbest_size") is not None:
184
+ nbest_size = self.sp_model_kwargs.get("nbest_size")
185
+
186
+ if not enable_sampling:
187
+ pieces = self.sp_model.EncodeAsPieces(text)
188
+ else:
189
+ pieces = self.sp_model.SampleEncodeAsPieces(text, nbest_size, alpha)
190
+ new_pieces = []
191
+ for pi, piece in enumerate(pieces):
192
+ if piece == SPIECE_UNDERLINE:
193
+ if not pieces[pi + 1].startswith(SPIECE_UNDERLINE) and pi != 0:
194
+ new_pieces.append(SPIECE_UNDERLINE)
195
+ continue
196
+ else:
197
+ continue
198
+ lst_i = 0
199
+ for i, chunk in enumerate(piece):
200
+ if chunk == SPIECE_UNDERLINE:
201
+ continue
202
+ if self.is_ch_char(chunk) or self.is_punct(chunk):
203
+ if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
204
+ new_pieces.append(piece[lst_i:i])
205
+ new_pieces.append(chunk)
206
+ lst_i = i + 1
207
+ elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
208
+ if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
209
+ new_pieces.append(piece[lst_i:i])
210
+ lst_i = i
211
+ elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
212
+ if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
213
+ new_pieces.append(piece[lst_i:i])
214
+ lst_i = i
215
+ if len(piece) > lst_i:
216
+ new_pieces.append(piece[lst_i:])
217
+ return new_pieces
218
+
219
+ def convert_tokens_to_string(self, tokens):
220
+ """Converts a sequence of tokens (strings for sub-words) in a single string."""
221
+ out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
222
+ return out_string
223
+
224
+ def convert_ids_to_string(self, ids):
225
+ """
226
+ Converts a sequence of tokens (strings for sub-words) in a single string.
227
+ """
228
+ tokens = self.convert_ids_to_tokens(ids)
229
+ out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
230
+ return out_string
231
+
232
+ # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
233
+ def _convert_token_to_id(self, token):
234
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
235
+
236
+ # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
237
+ def _convert_id_to_token(self, index):
238
+ """Converts an index (integer) in a token (str) using the vocab."""
239
+ return self.reverse_vocab.get(index, self.unk_token)
240
+
241
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
242
+ r"""
243
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
244
+ adding special tokens. An ErnieM sequence has the following format:
245
+
246
+ - single sequence: `[CLS] X [SEP]`
247
+ - pair of sequences: `[CLS] A [SEP] [SEP] B [SEP]`
248
+
249
+ Args:
250
+ token_ids_0 (`list[int]`):
251
+ List of IDs to which the special tokens will be added.
252
+ token_ids_1 (`list[int]`, *optional*):
253
+ Optional second list of IDs for sequence pairs.
254
+ Returns:
255
+ `list[int]`: List of input_id with the appropriate special tokens.
256
+ """
257
+ if token_ids_1 is None:
258
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
259
+ _cls = [self.cls_token_id]
260
+ _sep = [self.sep_token_id]
261
+ return _cls + token_ids_0 + _sep + _sep + token_ids_1 + _sep
262
+
263
+ def build_offset_mapping_with_special_tokens(self, offset_mapping_0, offset_mapping_1=None):
264
+ r"""
265
+ Build offset map from a pair of offset map by concatenating and adding offsets of special tokens. An Ernie-M
266
+ offset_mapping has the following format:
267
+
268
+ - single sequence: `(0,0) X (0,0)`
269
+ - pair of sequences: `(0,0) A (0,0) (0,0) B (0,0)`
270
+
271
+ Args:
272
+ offset_mapping_ids_0 (`list[tuple]`):
273
+ List of char offsets to which the special tokens will be added.
274
+ offset_mapping_ids_1 (`list[tuple]`, *optional*):
275
+ Optional second list of wordpiece offsets for offset mapping pairs.
276
+ Returns:
277
+ `list[tuple]`: List of wordpiece offsets with the appropriate offsets of special tokens.
278
+ """
279
+ if offset_mapping_1 is None:
280
+ return [(0, 0)] + offset_mapping_0 + [(0, 0)]
281
+
282
+ return [(0, 0)] + offset_mapping_0 + [(0, 0), (0, 0)] + offset_mapping_1 + [(0, 0)]
283
+
284
+ def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
285
+ r"""
286
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
287
+ special tokens using the tokenizer `encode` method.
288
+
289
+ Args:
290
+ token_ids_0 (`list[int]`):
291
+ List of ids of the first sequence.
292
+ token_ids_1 (`list[int]`, *optional*):
293
+ Optional second list of IDs for sequence pairs.
294
+ already_has_special_tokens (`str`, *optional*, defaults to `False`):
295
+ Whether or not the token list is already formatted with special tokens for the model.
296
+ Returns:
297
+ `list[int]`:
298
+ The list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
299
+ """
300
+
301
+ if already_has_special_tokens:
302
+ if token_ids_1 is not None:
303
+ raise ValueError(
304
+ "You should not supply a second sequence if the provided sequence of "
305
+ "ids is already formatted with special tokens for the model."
306
+ )
307
+ return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_0]
308
+
309
+ if token_ids_1 is not None:
310
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
311
+ return [1] + ([0] * len(token_ids_0)) + [1]
312
+
313
+ def create_token_type_ids_from_sequences(
314
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
315
+ ) -> list[int]:
316
+ """
317
+ Create the token type IDs corresponding to the sequences passed. [What are token type
318
+ IDs?](../glossary#token-type-ids) Should be overridden in a subclass if the model has a special way of
319
+ building: those.
320
+
321
+ Args:
322
+ token_ids_0 (`list[int]`):
323
+ The first tokenized sequence.
324
+ token_ids_1 (`list[int]`, *optional*):
325
+ The second tokenized sequence.
326
+ Returns:
327
+ `list[int]`: The token type ids.
328
+ """
329
+ # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method
330
+ if token_ids_1 is None:
331
+ # [CLS] X [SEP]
332
+ return (len(token_ids_0) + 2) * [0]
333
+
334
+ # [CLS] A [SEP] [SEP] B [SEP]
335
+ return [0] * (len(token_ids_0) + 1) + [1] * (len(token_ids_1) + 3)
336
+
337
+ def is_ch_char(self, char):
338
+ """
339
+ is_ch_char
340
+ """
341
+ if "\u4e00" <= char <= "\u9fff":
342
+ return True
343
+ return False
344
+
345
+ def is_alpha(self, char):
346
+ """
347
+ is_alpha
348
+ """
349
+ if ("a" <= char <= "z") or ("A" <= char <= "Z"):
350
+ return True
351
+ return False
352
+
353
+ def is_punct(self, char):
354
+ """
355
+ is_punct
356
+ """
357
+ if char in ",;:.?!~,;:。?!《》【】":
358
+ return True
359
+ return False
360
+
361
+ def is_whitespace(self, char):
362
+ """
363
+ is whitespace
364
+ """
365
+ if char == " " or char == "\t" or char == "\n" or char == "\r":
366
+ return True
367
+ if len(char) == 1:
368
+ cat = unicodedata.category(char)
369
+ if cat == "Zs":
370
+ return True
371
+ return False
372
+
373
+ def load_vocab(self, filepath):
374
+ token_to_idx = {}
375
+ with open(filepath, "r", encoding="utf-8") as f:
376
+ for index, line in enumerate(f):
377
+ token = line.rstrip("\n")
378
+ token_to_idx[token] = int(index)
379
+
380
+ return token_to_idx
381
+
382
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
383
+ index = 0
384
+ if os.path.isdir(save_directory):
385
+ vocab_file = os.path.join(
386
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
387
+ )
388
+ else:
389
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
390
+ with open(vocab_file, "w", encoding="utf-8") as writer:
391
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
392
+ if index != token_index:
393
+ logger.warning(
394
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
395
+ " Please check that the vocabulary is not corrupted!"
396
+ )
397
+ index = token_index
398
+ writer.write(token + "\n")
399
+ index += 1
400
+
401
+ tokenizer_model_file = os.path.join(save_directory, "sentencepiece.bpe.model")
402
+ with open(tokenizer_model_file, "wb") as fi:
403
+ content_spiece_model = self.sp_model.serialized_model_proto()
404
+ fi.write(content_spiece_model)
405
+
406
+ return (vocab_file,)
407
+
408
+
409
+ __all__ = ["ErnieMTokenizer"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/gptsan_japanese/configuration_gptsan_japanese.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """GPTSAN-japanese model configuration"""
16
+
17
+ from ....configuration_utils import PretrainedConfig
18
+ from ....utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class GPTSanJapaneseConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`GPTSanJapaneseModel`]. It is used to instantiate
27
+ a GPTSANJapanese model according to the specified arguments, defining the model architecture. Instantiating a
28
+ configuration with the defaults will yield a similar configuration to that of the GPTSANJapanese
29
+ [Tanrei/GPTSAN-japanese](https://huggingface.co/Tanrei/GPTSAN-japanese) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Arguments:
35
+ vocab_size (`int`, *optional*, defaults to 36000):
36
+ Vocabulary size of the GPTSANJapanese model. Defines the number of different tokens that can be represented
37
+ by the `inputs_ids` passed when calling [`GPTSanJapaneseModel`].
38
+ max_position_embeddings (`int`, *optional*, defaults to 1280):
39
+ The maximum sequence length that this model might ever be used with. Defaults set this to 1280.
40
+ d_model (`int`, *optional*, defaults to 1024):
41
+ Size of the encoder layers and the pooler layer.
42
+ d_ff (`int`, *optional*, defaults to 8192):
43
+ Size of the intermediate feed forward layer in each `SwitchTransformersBlock`.
44
+ d_ext (`int`, *optional*, defaults to 4096):
45
+ Size of the intermediate feed forward layer in each Extra-layers.
46
+ d_spout (`int`, *optional*, defaults to 128):
47
+ Size of the `spout` vector.
48
+ num_switch_layers (`int`, *optional*, defaults to 10):
49
+ Number of layers in the Switch Transformer layer.
50
+ num_ext_layers (`int`, *optional*, defaults to 0):
51
+ Number of layers in the Extra-layers.
52
+ num_heads (`int`, *optional*, defaults to 16):
53
+ Number of attention heads for each attention layer in the Transformer encoder.
54
+ num_experts (`int`, *optional*, defaults to 16):
55
+ Number of experts for each SwitchTransformer layer.
56
+ expert_capacity (`int`, *optional*, defaults to 128):
57
+ Number of tokens that can be stored in each expert. If set to 1, the model will behave like a regular
58
+ Transformer.
59
+ dropout_rate (`float`, *optional*, defaults to 0.0):
60
+ The ratio for all dropout layers.
61
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
62
+ The epsilon used by the layer normalization layers.
63
+ router_bias (`bool`, *optional*, defaults to `False`):
64
+ Whether to add a bias to the router.
65
+ router_jitter_noise (`float`, *optional*, defaults to 0.0):
66
+ Amount of noise to add to the router. Set it to 0.0 during prediction or set small value (usually 1e-2)
67
+ during training.
68
+ router_dtype (`str`, *optional*, default to `"float32"`):
69
+ The `dtype` used for the routers. It is preferable to keep the `dtype` to `"float32"` as specified in the
70
+ *selective precision* discussion in [the paper](https://huggingface.co/papers/2101.03961).
71
+ router_ignore_padding_tokens (`bool`, *optional*, defaults to `False`):
72
+ Whether to ignore padding tokens when routing.
73
+ output_hidden_states (`bool`, *optional*, default to `False`):
74
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
75
+ more detail.
76
+ output_attentions (`bool`, *optional*, defaults to `False`):
77
+ Whether or not to return the attentions tensors of all attention layers.
78
+ initializer_factor (`float`, *optional*, defaults to 0.002):
79
+ A factor for initializing all weight matrices.
80
+ output_router_logits (`bool`, *optional*, default to `False`):
81
+ Whether or not to return the router logits of all experts.
82
+ use_cache (`bool`, *optional*, defaults to `True`):
83
+ Whether or not the model should return the last key/values attentions (not used by all models)
84
+ """
85
+
86
+ model_type = "gptsan-japanese"
87
+ keys_to_ignore_at_inference = [
88
+ "past_key_values",
89
+ ]
90
+ attribute_map = {
91
+ "hidden_size": "d_model",
92
+ "num_attention_heads": "num_heads",
93
+ "num_hidden_layers": "num_layers",
94
+ }
95
+
96
+ def __init__(
97
+ self,
98
+ vocab_size=36000,
99
+ max_position_embeddings=1280,
100
+ d_model=1024,
101
+ d_ff=8192,
102
+ d_ext=4096,
103
+ d_spout=128,
104
+ num_switch_layers=10,
105
+ num_ext_layers=0,
106
+ num_heads=16,
107
+ num_experts=16,
108
+ expert_capacity=128,
109
+ dropout_rate=0.0,
110
+ layer_norm_epsilon=1e-5,
111
+ router_bias=False,
112
+ router_jitter_noise=0.0,
113
+ router_dtype="float32",
114
+ router_ignore_padding_tokens=False,
115
+ output_hidden_states=False,
116
+ output_attentions=False,
117
+ initializer_factor=0.002,
118
+ output_router_logits=False,
119
+ use_cache=True,
120
+ separator_token_id=35998,
121
+ pad_token_id=35995,
122
+ eos_token_id=35999,
123
+ **kwargs,
124
+ ):
125
+ self.vocab_size = vocab_size
126
+ self.max_position_embeddings = max_position_embeddings
127
+ self.d_model = d_model
128
+ self.d_ff = d_ff
129
+ self.d_ext = d_ext
130
+ self.d_spout = d_spout
131
+ self.num_switch_layers = num_switch_layers
132
+ self.num_ext_layers = num_ext_layers
133
+ self.num_layers = num_switch_layers + num_ext_layers
134
+ self.num_heads = num_heads
135
+ self.num_experts = num_experts
136
+ self.expert_capacity = expert_capacity
137
+ self.dropout_rate = dropout_rate
138
+ self.layer_norm_epsilon = layer_norm_epsilon
139
+ self.router_bias = router_bias
140
+ self.router_jitter_noise = router_jitter_noise
141
+ self.router_dtype = router_dtype
142
+ self.router_ignore_padding_tokens = router_ignore_padding_tokens
143
+ self.output_hidden_states = output_hidden_states
144
+ self.output_attentions = output_attentions
145
+ self.initializer_factor = initializer_factor
146
+ self.output_router_logits = output_router_logits
147
+ self.use_cache = use_cache
148
+
149
+ super().__init__(
150
+ separator_token_id=separator_token_id,
151
+ pad_token_id=pad_token_id,
152
+ eos_token_id=eos_token_id,
153
+ **kwargs,
154
+ )
155
+
156
+
157
+ __all__ = ["GPTSanJapaneseConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/gptsan_japanese/modeling_gptsan_japanese.py ADDED
@@ -0,0 +1,1331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Toshiyuki Sakamoto(tanreinama) 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 GPTSANJapanese model."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from ....activations import ACT2FN
23
+ from ....cache_utils import Cache
24
+ from ....modeling_outputs import MoECausalLMOutputWithPast, MoEModelOutputWithPastAndCrossAttentions
25
+ from ....modeling_utils import PreTrainedModel
26
+ from ....utils import (
27
+ DUMMY_INPUTS,
28
+ DUMMY_MASK,
29
+ add_start_docstrings,
30
+ add_start_docstrings_to_model_forward,
31
+ is_torch_fx_proxy,
32
+ logging,
33
+ )
34
+ from ....utils.deprecation import deprecate_kwarg
35
+ from .configuration_gptsan_japanese import GPTSanJapaneseConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ _CONFIG_FOR_DOC = "GPTSanJapaneseConfig"
41
+ _CHECKPOINT_FOR_DOC = "Tanrei/GPTSAN-japanese"
42
+
43
+ ####################################################
44
+ # This dict contains ids and associated url
45
+ # for the pretrained weights provided with the models
46
+ ####################################################
47
+
48
+
49
+ def router_z_loss_func(router_logits: torch.Tensor) -> float:
50
+ r"""
51
+ Compute the router z-loss implemented in PyTorch.
52
+
53
+ The router z-loss was introduced in [Designing Effective Sparse Expert Models](https://huggingface.co/papers/2202.08906).
54
+ It encourages router logits to remain small in an effort to improve stability.
55
+
56
+ Args:
57
+ router_logits (`float`):
58
+ Input logits of shape [batch_size, sequence_length, num_experts]
59
+
60
+ Returns:
61
+ Scalar router z-loss.
62
+ """
63
+ num_groups, tokens_per_group, _ = router_logits.shape
64
+ log_z = torch.logsumexp(router_logits, dim=-1)
65
+ z_loss = log_z**2
66
+ return torch.sum(z_loss) / (num_groups * tokens_per_group)
67
+
68
+
69
+ def load_balancing_loss_func(router_probs: torch.Tensor, expert_indices: torch.Tensor) -> float:
70
+ r"""
71
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
72
+
73
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
74
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
75
+ experts is too unbalanced.
76
+
77
+ Args:
78
+ router_probs (`torch.Tensor`):
79
+ Probability assigned to each expert per token. Shape: [batch_size, sequence_length, num_experts].
80
+ expert_indices (`torch.Tensor`):
81
+ Indices tensor of shape [batch_size, sequence_length] identifying the selected expert for a given token.
82
+
83
+ Returns:
84
+ The auxiliary loss.
85
+ """
86
+ num_experts = router_probs.shape[-1]
87
+
88
+ # cast the expert indices to int64, otherwise one-hot encoding will fail
89
+ if expert_indices.dtype != torch.int64:
90
+ expert_indices = expert_indices.to(torch.int64)
91
+
92
+ if len(expert_indices.shape) == 2:
93
+ expert_indices = expert_indices.unsqueeze(2)
94
+
95
+ expert_mask = torch.nn.functional.one_hot(expert_indices, num_experts)
96
+
97
+ # For a given token, determine if it was routed to a given expert.
98
+ expert_mask = torch.max(expert_mask, axis=-2).values
99
+
100
+ # cast to float32 otherwise mean will fail
101
+ expert_mask = expert_mask.to(torch.float32)
102
+ tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
103
+
104
+ router_prob_per_group_and_expert = torch.mean(router_probs, axis=-2)
105
+ return torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert) * (num_experts**2)
106
+
107
+
108
+ class GPTSanJapaneseDenseActDense(nn.Module):
109
+ """
110
+ FFN Layer for Switch Transformer and Extra layers
111
+
112
+ GPTSAN can mix Switch Transformer layers and normal Transformer layers This class is used as Expert in Switch
113
+ Transformer layers and as FFN in regular Transformer layers. RELU is used in the Switch Transformer layer, and
114
+ Swish is used in the normal Transformer layer, so there is a choice of which is used in the argument.
115
+
116
+ """
117
+
118
+ def __init__(self, config: GPTSanJapaneseConfig, ext_layer=False):
119
+ super().__init__()
120
+ d_inter = config.d_ext if ext_layer else config.d_ff
121
+ self.wi = nn.Linear(config.d_model, d_inter, bias=ext_layer)
122
+ self.wo = nn.Linear(d_inter, config.d_model, bias=ext_layer)
123
+ self.dropout = nn.Identity() if ext_layer else nn.Dropout(config.dropout_rate)
124
+ self.act = ACT2FN["swish" if ext_layer else "relu"]
125
+
126
+ def forward(self, hidden_states):
127
+ r"""
128
+ Args:
129
+ hidden_states (`torch.Tensor`) :
130
+ [num_groups, tokens_per_group, hidden_dim] inputs to send to experts.
131
+ Returns:
132
+ torch.Tensor[num_groups, tokens_per_group, hidden_dim]
133
+
134
+ """
135
+ hidden_states = self.wi(hidden_states)
136
+ hidden_states = self.act(hidden_states)
137
+ hidden_states = self.dropout(hidden_states)
138
+ hidden_states = self.wo(hidden_states)
139
+ return hidden_states
140
+
141
+
142
+ class GPTSanJapaneseTop1Router(nn.Module):
143
+ """
144
+ Router using tokens choose top-1 experts assignment.
145
+
146
+ This router uses the same mechanism as in Switch Transformer (https://huggingface.co/papers/2101.03961) and V-MoE
147
+ (https://huggingface.co/papers/2106.05974): tokens choose their top experts. Items are sorted by router_probs and then
148
+ routed to their choice of expert until the expert's expert_capacity is reached. **There is no guarantee that each
149
+ token is processed by an expert**, or that each expert receives at least one token.
150
+
151
+ """
152
+
153
+ def __init__(self, config: GPTSanJapaneseConfig):
154
+ super().__init__()
155
+ self.num_experts = config.num_experts
156
+ self.expert_capacity = config.expert_capacity
157
+ self.classifier = nn.Linear(config.hidden_size, self.num_experts, bias=config.router_bias)
158
+ self.jitter_noise = config.router_jitter_noise
159
+ self.ignore_padding_tokens = config.router_ignore_padding_tokens
160
+ self.dtype = getattr(torch, config.router_dtype)
161
+
162
+ def _compute_router_probabilities(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
163
+ r"""
164
+ Computes router probabilities from input hidden states.
165
+
166
+ Args:
167
+ hidden_states (`torch.Tensor`):
168
+ (batch_size, sequence_length, hidden_dim) from which router probabilities are computed.
169
+ Returns:
170
+ router_probabilities (`torch.Tensor`):
171
+ Tensor of shape (batch_size, sequence_length, num_experts) corresponding to the probabilities for each
172
+ token and expert. Used for routing tokens to experts.
173
+ router_logits (`torch.Tensor`):
174
+ Logits tensor of shape (batch_size, sequence_length, num_experts) corresponding to raw router logits.
175
+ This is used later for computing router z-loss.
176
+ """
177
+ # float32 is used to ensure stability. See the discussion of "selective precision" in
178
+ # https://huggingface.co/papers/2101.03961.
179
+ # We also store the previous dtype to cast back the output to the previous dtype
180
+ self.input_dtype = hidden_states.dtype
181
+ hidden_states = hidden_states.to(self.dtype)
182
+
183
+ if self.training and self.jitter_noise > 0:
184
+ # Multiply the token inputs by the uniform distribution - adding some noise
185
+ hidden_states *= torch.empty_like(hidden_states).uniform_(1.0 - self.jitter_noise, 1.0 + self.jitter_noise)
186
+
187
+ # Shape: [num_groups, tokens_per_group, num_experts]
188
+ self._cast_classifier()
189
+ router_logits = self.classifier(hidden_states)
190
+
191
+ # Apply Softmax and cast back to the original `dtype`
192
+ router_probabilities = nn.functional.softmax(router_logits, dim=-1, dtype=self.dtype).to(self.input_dtype)
193
+ return router_probabilities, router_logits
194
+
195
+ def _cast_classifier(self):
196
+ r"""
197
+ `bitsandbytes` `Linear8bitLt` layers does not support manual casting Therefore we need to check if they are an
198
+ instance of the `Linear8bitLt` class by checking special attributes.
199
+ """
200
+ if not (hasattr(self.classifier, "SCB") or hasattr(self.classifier, "CB")):
201
+ self.classifier = self.classifier.to(self.dtype)
202
+
203
+ def forward(self, hidden_states: torch.Tensor) -> tuple:
204
+ r"""
205
+ Generic forward function for every Router class. Each Router expects to have the same input hidden states
206
+ (`hidden_states`) corresponding to the hidden states for each token, the `expert_capacity` corresponding to the
207
+ number of tokens the Router will send to each expert, some Routers can send up to few tokens to each expert.
208
+
209
+ Each Router works as the following: it expects the hidden states for each token, gets the `router_probs` and
210
+ `router_logits` from the `router_weights`. This will assign for each token, the raw probability to be assigned
211
+ to an expert. Then each Router class will have to define its own `_compute_routing_instructions`.
212
+
213
+ Args:
214
+ hidden_states (`torch.Tensor`) :
215
+ [num_groups, tokens_per_group, hidden_dim] inputs to send to experts.
216
+ Returns:
217
+ tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`] Tuple containing the expert index, the router probs
218
+ and the router logits. The router probabilities and logits are required to compute the loss.
219
+ """
220
+ router_probs, router_logits = self._compute_router_probabilities(hidden_states)
221
+
222
+ expert_index = torch.argmax(router_probs, dim=-1)
223
+ expert_index = torch.nn.functional.one_hot(expert_index, num_classes=self.num_experts)
224
+
225
+ # Mask tokens outside expert capacity. Sum over each sequence
226
+ token_priority = torch.cumsum(expert_index, dim=-2)
227
+ # mask if the token routed to to the expert will overflow
228
+ expert_capacity_mask = token_priority <= self.expert_capacity
229
+ expert_index = expert_index * expert_capacity_mask
230
+
231
+ router_probs = torch.max(router_probs, dim=-1).values.unsqueeze(-1)
232
+ return expert_index, router_probs, router_logits
233
+
234
+
235
+ class GPTSanJapaneseSparseMLP(nn.Module):
236
+ r"""
237
+ Implementation of the Switch Transformers Sparse MLP module.
238
+ """
239
+
240
+ def __init__(self, config: GPTSanJapaneseConfig, expert_class: nn.Module = GPTSanJapaneseDenseActDense):
241
+ super().__init__()
242
+ # Step 1: Get the correct router according to its class
243
+ self.router = GPTSanJapaneseTop1Router(config)
244
+
245
+ # Step 2: Get the experts
246
+ self.experts = nn.ModuleDict()
247
+ for idx in range(config.num_experts):
248
+ self.experts[f"expert_{idx}"] = expert_class(config)
249
+
250
+ def forward(self, hidden_states):
251
+ r"""
252
+ Hold on, this will be slightly tricky to understand In the correct order, a MoE layer does the following:
253
+
254
+ 1- Gets the `router_mask` from the router. The shape of the mask is `(batch_size, sequence_length, num_expert)`
255
+ and corresponds to the argmax of the `router_probs`. The probabilities are needed in the computation of the
256
+ hidden states : they are broadcasted to the hidden states values (can be interpreted as a scaling factor).
257
+
258
+ 2- Dispatch the tokens to its associated experts. We do a classic for loop over the experts and assign for each
259
+ expert the corresponding hidden states.
260
+
261
+ """
262
+ # Step 1: Get the router_mask from the router as well as the probabilities
263
+ router_mask, router_probs, router_logits = self.router(hidden_states)
264
+ expert_index = torch.argmax(router_mask, dim=-1)
265
+
266
+ # The routers introduced might not always map all the tokens, to a router, which means that some hidden states
267
+ # can be unchanged from one layer to another. That is why the hidden states are cloned before updating only the selected ones.
268
+
269
+ next_states = hidden_states.clone()
270
+ for idx, expert in enumerate(self.experts.values()):
271
+ token_indices = router_mask[:, :, idx].bool()
272
+ next_states[token_indices] = expert(hidden_states[token_indices]).to(next_states.dtype)
273
+
274
+ hidden_states = router_probs * next_states
275
+ return hidden_states, (router_logits, expert_index)
276
+
277
+
278
+ class GPTSanJapaneseLayerSparseFF(nn.Module):
279
+ r"""
280
+ Switch Transformers Feed Forward layer module. This is a wrapper around the Mixture of Experts module.
281
+
282
+ Parameters:
283
+ config : ([`GPTSanJapaneseConfig`]): Model configuration class with all the parameters of the model.
284
+ Initializing with a config file does not load the weights associated with the model, only the
285
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
286
+ """
287
+
288
+ def __init__(self, config: GPTSanJapaneseConfig):
289
+ super().__init__()
290
+ self.mlp = GPTSanJapaneseSparseMLP(config)
291
+ self.soft_bypass_mlp = nn.Linear(config.d_model, config.d_model, bias=False)
292
+ self.norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
293
+
294
+ def forward(self, hidden_states, output_router_logits):
295
+ r"""
296
+ Args:
297
+ hidden_states (`torch.Tensor`) :
298
+ [num_groups, tokens_per_group, hidden_dim] inputs to send to experts.
299
+ output_router_logits (`bool`) :
300
+ output experts router output.
301
+ Returns:
302
+ torch.Tensor[num_groups, tokens_per_group, hidden_dim]
303
+
304
+ """
305
+ forwarded_states, router_tuple = self.mlp(hidden_states)
306
+ forwarded_states += torch.tanh(self.soft_bypass_mlp(hidden_states))
307
+ output = hidden_states + self.norm(forwarded_states)
308
+
309
+ if output_router_logits and router_tuple is not None:
310
+ return output, router_tuple
311
+ else:
312
+ return output
313
+
314
+
315
+ class GPTSanJapaneseLayerDenseFF(nn.Module):
316
+ r"""
317
+ Extra Transformers Feed Forward layer module.
318
+
319
+ Parameters:
320
+ config : ([`GPTSanJapaneseConfig`]): Model configuration class with all the parameters of the model.
321
+ Initializing with a config file does not load the weights associated with the model, only the
322
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
323
+ """
324
+
325
+ def __init__(self, config: GPTSanJapaneseConfig):
326
+ super().__init__()
327
+ # Check if it is a sparse layer, if not then it is a dense layer
328
+ self.mlp = GPTSanJapaneseDenseActDense(config, ext_layer=True)
329
+ self.norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
330
+
331
+ def forward(self, hidden_states):
332
+ r"""
333
+ Args:
334
+ hidden_states (`torch.Tensor`) :
335
+ [num_groups, tokens_per_group, hidden_dim] inputs to send to experts.
336
+ Returns:
337
+ torch.Tensor[num_groups, tokens_per_group, hidden_dim]
338
+
339
+ """
340
+ forwarded_states = self.mlp(hidden_states)
341
+ output = hidden_states + self.norm(forwarded_states)
342
+ return output
343
+
344
+
345
+ class GPTSanJapaneseAttention(nn.Module):
346
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
347
+
348
+ def __init__(
349
+ self,
350
+ embed_dim: int,
351
+ num_heads: int,
352
+ dropout: float = 0.0,
353
+ is_decoder: bool = False,
354
+ bias: bool = True,
355
+ is_causal: bool = False,
356
+ config: Optional[GPTSanJapaneseConfig] = None,
357
+ ):
358
+ super().__init__()
359
+ self.embed_dim = embed_dim
360
+ self.num_heads = num_heads
361
+ self.dropout = dropout
362
+ self.head_dim = embed_dim // num_heads
363
+ self.config = config
364
+
365
+ if (self.head_dim * num_heads) != self.embed_dim:
366
+ raise ValueError(
367
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
368
+ f" and `num_heads`: {num_heads})."
369
+ )
370
+ self.scaling = self.head_dim**-0.5
371
+ self.is_decoder = is_decoder
372
+ self.is_causal = is_causal
373
+
374
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
375
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
376
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
377
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
378
+
379
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
380
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
381
+
382
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
383
+ def forward(
384
+ self,
385
+ hidden_states: torch.Tensor,
386
+ key_value_states: Optional[torch.Tensor] = None,
387
+ past_key_values: Optional[Cache] = None,
388
+ attention_mask: Optional[torch.Tensor] = None,
389
+ layer_head_mask: Optional[torch.Tensor] = None,
390
+ output_attentions: bool = False,
391
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
392
+ """Input shape: Batch x Time x Channel"""
393
+
394
+ # if key_value_states are provided this layer is used as a cross-attention layer
395
+ # for the decoder
396
+ is_cross_attention = key_value_states is not None
397
+
398
+ bsz, tgt_len, _ = hidden_states.size()
399
+
400
+ # get query proj
401
+ query_states = self.q_proj(hidden_states) * self.scaling
402
+ # get key, value proj
403
+ # `past_key_values[0].shape[2] == key_value_states.shape[1]`
404
+ # is checking that the `sequence_length` of the `past_key_values` is the same as
405
+ # the provided `key_value_states` to support prefix tuning
406
+ if (
407
+ is_cross_attention
408
+ and past_key_values is not None
409
+ and past_key_values[0].shape[2] == key_value_states.shape[1]
410
+ ):
411
+ # reuse k,v, cross_attentions
412
+ key_states = past_key_values[0]
413
+ value_states = past_key_values[1]
414
+ elif is_cross_attention:
415
+ # cross_attentions
416
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
417
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
418
+ elif past_key_values is not None:
419
+ # reuse k, v, self_attention
420
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
421
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
422
+ key_states = torch.cat([past_key_values[0], key_states], dim=2)
423
+ value_states = torch.cat([past_key_values[1], value_states], dim=2)
424
+ else:
425
+ # self_attention
426
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
427
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
428
+
429
+ if self.is_decoder:
430
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
431
+ # Further calls to cross_attention layer can then reuse all cross-attention
432
+ # key/value_states (first "if" case)
433
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
434
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
435
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
436
+ # if encoder bi-directional self-attention `past_key_values` is always `None`
437
+ past_key_values = (key_states, value_states)
438
+
439
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
440
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
441
+ key_states = key_states.reshape(*proj_shape)
442
+ value_states = value_states.reshape(*proj_shape)
443
+
444
+ src_len = key_states.size(1)
445
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
446
+
447
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
448
+ raise ValueError(
449
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
450
+ f" {attn_weights.size()}"
451
+ )
452
+
453
+ if attention_mask is not None:
454
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
455
+ raise ValueError(
456
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
457
+ )
458
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
459
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
460
+
461
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
462
+
463
+ if layer_head_mask is not None:
464
+ if layer_head_mask.size() != (self.num_heads,):
465
+ raise ValueError(
466
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
467
+ f" {layer_head_mask.size()}"
468
+ )
469
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
470
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
471
+
472
+ if output_attentions:
473
+ # this operation is a bit awkward, but it's required to
474
+ # make sure that attn_weights keeps its gradient.
475
+ # In order to do so, attn_weights have to be reshaped
476
+ # twice and have to be reused in the following
477
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
478
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
479
+ else:
480
+ attn_weights_reshaped = None
481
+
482
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
483
+
484
+ attn_output = torch.bmm(attn_probs, value_states)
485
+
486
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
487
+ raise ValueError(
488
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
489
+ f" {attn_output.size()}"
490
+ )
491
+
492
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
493
+ attn_output = attn_output.transpose(1, 2)
494
+
495
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
496
+ # partitioned across GPUs when using tensor-parallelism.
497
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
498
+
499
+ attn_output = self.out_proj(attn_output)
500
+
501
+ return attn_output, attn_weights_reshaped, past_key_values
502
+
503
+
504
+ class GPTSanJapaneseLayerSelfAttention(nn.Module):
505
+ """
506
+ Self Attention and Normalization Unit
507
+ """
508
+
509
+ def __init__(self, config, has_relative_attention_bias=False):
510
+ super().__init__()
511
+ self.self_attn = GPTSanJapaneseAttention(
512
+ embed_dim=config.d_model,
513
+ num_heads=config.num_heads,
514
+ is_decoder=True,
515
+ bias=has_relative_attention_bias,
516
+ )
517
+ self.norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
518
+
519
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
520
+ def forward(
521
+ self,
522
+ hidden_states: Optional[tuple[torch.FloatTensor]],
523
+ past_key_values: Optional[Cache] = None,
524
+ attention_mask: Optional[torch.FloatTensor] = None,
525
+ head_mask: Optional[torch.FloatTensor] = None,
526
+ use_cache: Optional[bool] = False,
527
+ output_attentions: Optional[bool] = False,
528
+ ) -> tuple[Union[torch.Tensor, tuple[torch.Tensor]], ...]:
529
+ r"""
530
+ Self-attention and normalize block.
531
+
532
+ Args:
533
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
534
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
535
+ if the model is configured as a decoder.
536
+ 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)`):
537
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up
538
+ decoding. If `past_key_values` are used, the user can optionally input only the last
539
+ `decoder_input_ids` (those that don't have their past key value states given to this model) of shape
540
+ `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
541
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
542
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
543
+ in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
544
+
545
+ - 1 for tokens that are **not masked**,
546
+ - 0 for tokens that are **masked**.
547
+
548
+ head_mask (`numpy.ndarray` of shape `({0})`, `optional):
549
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
550
+
551
+ - 1 indicates the head is **not masked**,
552
+ - 0 indicates the head is **masked**.
553
+
554
+ use_cache (`bool`, *optional*):
555
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
556
+ (see `past_key_values`).
557
+ output_attentions (`bool`, *optional*):
558
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
559
+ returned tensors for more detail.
560
+ Returns:
561
+ tuple[torch.Tensor[num_groups, tokens_per_group, hidden_dim],...]
562
+ """
563
+ # Self Attention
564
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
565
+ self_attn_past_key_value = past_key_values[:2] if past_key_values is not None else None
566
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
567
+ atten_out = self.self_attn(
568
+ hidden_states=hidden_states,
569
+ past_key_values=self_attn_past_key_value,
570
+ attention_mask=(1 - attention_mask) * torch.finfo(hidden_states.dtype).min,
571
+ layer_head_mask=head_mask,
572
+ output_attentions=output_attentions,
573
+ )
574
+ if output_attentions:
575
+ attn_weights = (atten_out[1],)
576
+ else:
577
+ attn_weights = ()
578
+
579
+ attention_output = atten_out[0]
580
+
581
+ hidden = hidden_states + self.norm(attention_output)
582
+
583
+ if use_cache:
584
+ outputs = (hidden, atten_out[2]) # hidden, present, (attentions)
585
+ else:
586
+ outputs = (hidden,) # hidden, (attentions)
587
+
588
+ return outputs + attn_weights
589
+
590
+
591
+ class GPTSanJapaneseBlock(nn.Module):
592
+ """
593
+ Self Attention and FFN Unit
594
+ """
595
+
596
+ def __init__(self, config, ext_layer=False):
597
+ super().__init__()
598
+ self.self_attn = GPTSanJapaneseLayerSelfAttention(config)
599
+ self.feed_forward = GPTSanJapaneseLayerDenseFF(config) if ext_layer else GPTSanJapaneseLayerSparseFF(config)
600
+
601
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
602
+ def forward(
603
+ self,
604
+ hidden_states: Optional[tuple[torch.FloatTensor]],
605
+ past_key_values: Optional[Cache] = None,
606
+ attention_mask: Optional[torch.FloatTensor] = None,
607
+ head_mask: Optional[torch.FloatTensor] = None,
608
+ use_cache: Optional[bool] = False,
609
+ output_attentions: Optional[bool] = False,
610
+ output_router_tuple: Optional[bool] = False,
611
+ ) -> tuple[Union[torch.Tensor, tuple[torch.Tensor]], ...]:
612
+ r"""
613
+ GPTSAN transformer block.
614
+
615
+ Args:
616
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
617
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
618
+ if the model is configured as a decoder.
619
+ 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)`):
620
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up
621
+ decoding. If `past_key_values` are used, the user can optionally input only the last
622
+ `decoder_input_ids` (those that don't have their past key value states given to this model) of shape
623
+ `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
624
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
625
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
626
+ in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
627
+
628
+ - 1 for tokens that are **not masked**,
629
+ - 0 for tokens that are **masked**.
630
+
631
+ head_mask (`numpy.ndarray` of shape `({0})`, `optional):
632
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
633
+
634
+ - 1 indicates the head is **not masked**,
635
+ - 0 indicates the head is **masked**.
636
+
637
+ use_cache (`bool`, *optional*):
638
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
639
+ (see `past_key_values`).
640
+ output_attentions (`bool`) :
641
+ output attention probabirities.
642
+ output_router_tuple:
643
+ output experts router logits and expert id.
644
+ Returns:
645
+ tuple[torch.Tensor[num_groups, tokens_per_group, hidden_dim],...]
646
+ """
647
+ atten_out = self.self_attn(
648
+ hidden_states=hidden_states,
649
+ past_key_values=past_key_values,
650
+ attention_mask=attention_mask,
651
+ head_mask=head_mask,
652
+ use_cache=use_cache,
653
+ output_attentions=output_attentions,
654
+ )
655
+ attention_output = atten_out[0]
656
+
657
+ if isinstance(self.feed_forward, GPTSanJapaneseLayerSparseFF):
658
+ sparse_out = self.feed_forward(attention_output, output_router_tuple)
659
+ if output_router_tuple:
660
+ hidden, router_tuple = sparse_out
661
+ else:
662
+ hidden = sparse_out
663
+ else:
664
+ hidden = self.feed_forward(attention_output)
665
+
666
+ outputs = (hidden,) + atten_out[1:]
667
+
668
+ if isinstance(self.feed_forward, GPTSanJapaneseLayerSparseFF) and output_router_tuple:
669
+ outputs += (router_tuple,)
670
+
671
+ return outputs
672
+
673
+
674
+ class GPTSanJapanesePreTrainedModel(PreTrainedModel):
675
+ """
676
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
677
+ models.
678
+ """
679
+
680
+ config: GPTSanJapaneseConfig
681
+ base_model_prefix = "gptsan_japanese"
682
+ supports_gradient_checkpointing = False
683
+ _no_split_modules = ["GPTSanJapaneseBlock"]
684
+ _skip_keys_device_placement = "past_key_values"
685
+
686
+ @property
687
+ def dummy_inputs(self):
688
+ input_ids = torch.tensor(DUMMY_INPUTS)
689
+ input_mask = torch.tensor(DUMMY_MASK)
690
+ dummy_inputs = {
691
+ "input_ids": input_ids,
692
+ "attention_mask": input_mask,
693
+ }
694
+ return dummy_inputs
695
+
696
+ def _init_weights(self, module):
697
+ """Initialize the weights"""
698
+ factor = self.config.initializer_factor # Used for testing weights initialization
699
+ if isinstance(module, nn.LayerNorm):
700
+ module.weight.data.fill_(factor * 1.0)
701
+ module.bias.data.zero_()
702
+ elif isinstance(module, nn.Linear):
703
+ module.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
704
+ if hasattr(module, "bias") and module.bias is not None:
705
+ module.bias.data.zero_()
706
+ elif isinstance(module, nn.Embedding):
707
+ module.weight.data.normal_(mean=0.0, std=factor * 1.0)
708
+ elif isinstance(module, GPTSanJapaneseModel):
709
+ # Mesh TensorFlow embeddings initialization
710
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624
711
+ module.embed_tokens.weight.data.normal_(mean=0.0, std=factor * 1.0)
712
+ module.position_embeddings.weight.data.normal_(mean=0.0, std=factor * 1.0)
713
+ if hasattr(module, "extra_position_embeddings") and module.extra_position_embeddings is not None:
714
+ module.extra_position_embeddings.weight.data.normal_(mean=0.0, std=factor * 1.0)
715
+ elif isinstance(module, (GPTSanJapaneseModel, GPTSanJapaneseForConditionalGeneration)):
716
+ # Mesh TensorFlow embeddings initialization
717
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624
718
+ module.final_logits_bias.data.normal_(mean=0.0, std=factor * 1.0)
719
+ if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
720
+ module.lm_head.weight.data.normal_(mean=0.0, std=factor * 1.0)
721
+ elif isinstance(module, GPTSanJapaneseDenseActDense):
722
+ # Mesh TensorFlow FF initialization
723
+ # See https://github.com/tensorflow/mesh/blob/master/mesh_tensorflow/transformer/transformer_layers.py#L56
724
+ # and https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L89
725
+ module.wi.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
726
+ if hasattr(module.wi, "bias") and module.wi.bias is not None:
727
+ module.wi.bias.data.zero_()
728
+ module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
729
+ if hasattr(module.wo, "bias") and module.wo.bias is not None:
730
+ module.wo.bias.data.zero_()
731
+ elif isinstance(module, GPTSanJapaneseAttention):
732
+ # Multi-headed attention
733
+ d_model = self.config.d_model
734
+ key_value_proj_dim = self.config.d_model
735
+ n_heads = self.config.num_heads
736
+ module.k_proj.weight.data.normal_(mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
737
+ module.v_proj.weight.data.normal_(mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
738
+ module.q_proj.weight.data.normal_(mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
739
+ module.out_proj.weight.data.normal_(mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
740
+ elif isinstance(module, GPTSanJapaneseSparseMLP):
741
+ # Mesh TensorFlow attention initialization to avoid scaling before softmax
742
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/attention.py#L136
743
+ d_model = self.config.d_model
744
+ key_value_proj_dim = self.config.d_model
745
+ n_heads = self.config.num_heads
746
+ module.router.classifier.weight.data.normal_(mean=0.0, std=factor * 1)
747
+ for idx in range(self.config.num_experts):
748
+ module.experts[f"expert_{idx}"].wi.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
749
+ module.experts[f"expert_{idx}"].wo.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
750
+
751
+ def _shift_right(self, input_ids):
752
+ decoder_start_token_id = self.config.decoder_start_token_id
753
+ pad_token_id = self.config.pad_token_id
754
+
755
+ if decoder_start_token_id is None:
756
+ raise ValueError(
757
+ "self.model.config.decoder_start_token_id has to be defined. In T5 it is usually set to the pad_token_id. "
758
+ "See T5 docs for more information."
759
+ )
760
+
761
+ # shift inputs to the right
762
+ if is_torch_fx_proxy(input_ids):
763
+ # Item assignment is not supported natively for proxies.
764
+ shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), decoder_start_token_id)
765
+ shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1)
766
+ else:
767
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
768
+ shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
769
+ shifted_input_ids[..., 0] = decoder_start_token_id
770
+
771
+ if pad_token_id is None:
772
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
773
+ # replace possible -100 values in labels by `pad_token_id`
774
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
775
+
776
+ return shifted_input_ids
777
+
778
+
779
+ GPTSAN_JAPANESE_START_DOCSTRING = r"""
780
+
781
+ The [GPTSAN-japanese](https://github.com/tanreinama/GPTSAN) model was proposed in General-purpose Swich transformer
782
+ based Japanese language model
783
+
784
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
785
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
786
+ and behavior.
787
+
788
+ Parameters:
789
+ config ([`GPTSanJapaneseConfig`]): Model configuration class with all the parameters of the model.
790
+ Initializing with a config file does not load the weights associated with the model, only the
791
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
792
+ """
793
+
794
+ GPTSAN_JAPANESE_INPUTS_DOCSTRING = r"""
795
+ Args:
796
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
797
+ Indices of input sequence tokens in the vocabulary. GPTSAN-japanese is a model that generates sentence
798
+ continuations or predicts tokens at mask positions. Special tokens required for inputs to the model are
799
+ automatically appended.
800
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
801
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
802
+
803
+ - 1 for tokens that are **not masked**,
804
+ - 0 for tokens that are **masked**.
805
+
806
+ [What are attention masks?](../glossary#attention-mask)
807
+ token_type_ids (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
808
+ An input that masks the Prefix part in the Prefix-LM input. Mask values selected in `[0, 1]`:
809
+
810
+ - 1 for tokens that are **prefix** input,
811
+ - 0 for tokens that are **not-prefix** input.
812
+ spout (`torch.Tensor` of shape `(batch_size, config.d_spout)`):
813
+ This vector is transformed through an 8-layer FFN and can be used instead of `past_key_values`.
814
+ 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)`):
815
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
816
+
817
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
818
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
819
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
820
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
821
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
822
+ use_cache (`bool`, *optional*):
823
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
824
+ `past_key_values`).
825
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
826
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
827
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
828
+ model's internal embedding lookup matrix.
829
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
830
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
831
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
832
+ input (see `past_key_values`). This is useful if you want more control over how to convert
833
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
834
+ output_attentions (`bool`, *optional*):
835
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
836
+ tensors for more detail.
837
+ output_hidden_states (`bool`, *optional*):
838
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
839
+ more detail.
840
+ return_dict (`bool`, *optional*):
841
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
842
+ router_logits (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_logits=True` is passed or when `config.add_router_probs=True`):
843
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`.
844
+ Router logits of the decoder model, useful to compute the auxiliary loss for Mixture of Experts models.
845
+ """
846
+
847
+
848
+ @add_start_docstrings(
849
+ "The bare GPTSAN-japanese Model transformer outputting raw hidden-states without any specific head on top.",
850
+ GPTSAN_JAPANESE_START_DOCSTRING,
851
+ )
852
+ class GPTSanJapaneseModel(GPTSanJapanesePreTrainedModel):
853
+ def __init__(self, config: GPTSanJapaneseConfig):
854
+ super().__init__(config)
855
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.d_model)
856
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model)
857
+ self.last_project = nn.Linear(config.d_model, config.d_model, bias=True)
858
+ self.act = ACT2FN["swish"]
859
+
860
+ self.blocks = torch.nn.ModuleList([])
861
+ for _ in range(config.num_switch_layers):
862
+ self.blocks.append(GPTSanJapaneseBlock(config))
863
+ for _ in range(config.num_ext_layers):
864
+ self.blocks.append(GPTSanJapaneseBlock(config, ext_layer=True))
865
+
866
+ if config.num_ext_layers > 0:
867
+ self.extra_position_embeddings = nn.Embedding(config.max_position_embeddings, config.d_model)
868
+
869
+ if config.d_spout:
870
+ spouts = []
871
+ for _ in range(8):
872
+ spouts.append(nn.Linear(config.d_spout, config.d_spout, bias=False))
873
+ spouts.append(nn.Tanh())
874
+ spouts.append(nn.Linear(config.d_spout, config.num_layers * 2 * config.d_model, bias=False))
875
+ self.spout = nn.Sequential(*spouts)
876
+
877
+ self.post_init()
878
+
879
+ def set_input_embeddings(self, new_embeddings):
880
+ self.embed_tokens = new_embeddings
881
+
882
+ @add_start_docstrings_to_model_forward(GPTSAN_JAPANESE_INPUTS_DOCSTRING)
883
+ def forward(
884
+ self,
885
+ input_ids: Optional[torch.LongTensor] = None,
886
+ attention_mask: Optional[torch.FloatTensor] = None,
887
+ token_type_ids: Optional[torch.FloatTensor] = None,
888
+ spout: Optional[torch.FloatTensor] = None,
889
+ past_key_values: Optional[Cache] = None,
890
+ head_mask: Optional[torch.FloatTensor] = None,
891
+ use_cache: Optional[bool] = False,
892
+ inputs_embeds: Optional[torch.FloatTensor] = None,
893
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
894
+ output_attentions: Optional[bool] = None,
895
+ output_hidden_states: Optional[bool] = None,
896
+ return_dict: Optional[bool] = None,
897
+ output_router_logits: Optional[bool] = None,
898
+ num_precontext: Optional[torch.LongTensor] = None,
899
+ ) -> Union[MoEModelOutputWithPastAndCrossAttentions, tuple[torch.FloatTensor]]:
900
+ r"""
901
+ num_precontext (`torch.LongTensor` of shape `(batch_size,1)`):
902
+ length of `hybrid` input tokens in the input. Tokens up to this length refer to both front and back like
903
+ BERT, tokens after that refer only to front like GPT. see also:
904
+ https://github.com/tanreinama/GPTSAN/blob/main/report/model.md
905
+
906
+ Returns:
907
+ `MoEModelOutputWithPastAndCrossAttentions` or `tuple` if `return_dict` returns
908
+ MoEModelOutputWithPastAndCrossAttentions instead of tuple
909
+ """
910
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
911
+ device = self.position_embeddings.weight.device
912
+ if input_ids is None:
913
+ input_ids = torch.zeros([1, 1]).int().to(device) # dummy for input_ids was None
914
+ if inputs_embeds is not None:
915
+ raise NotImplementedError(
916
+ "GPTSanJapaneseModel does not use `inputs_embeds`. Make sure to pass in `input_ids` instead."
917
+ )
918
+ num_pasts_contexts = 0
919
+ num_batch = input_ids.shape[0]
920
+ pasts_or_spout_value = None
921
+ if past_key_values is not None:
922
+ num_pasts_contexts = past_key_values.get_seq_length()
923
+ elif self.config.d_spout and spout is not None:
924
+ # `spout` is a special input vector specific to GPTSAN
925
+ # This controls the output by projecting embedded information such as the class of sentences during learning.
926
+ # It should passed instead of the first past_key_values.
927
+ # See the original GPTSAN repository for details
928
+ num_pasts_contexts += 1
929
+
930
+ # If there is an attention_mask, increase first one for spout
931
+ if self.config.d_spout and spout is not None and attention_mask is not None:
932
+ attention_mask_with_spout = torch.ones(num_batch, attention_mask.shape[1] + 1, device=device)
933
+ attention_mask_with_spout[:, 1:] -= 1 - attention_mask # 1st token should be spout
934
+ attention_mask = attention_mask_with_spout # update attention_mask
935
+
936
+ if num_precontext is not None:
937
+ # `num_precontext` is the number of tokens that refer to each other in prefix-lm
938
+ # created per batch, so dimension of num_precontext should be [batch, 1]
939
+ if not (
940
+ len(num_precontext.shape) == 2 and num_precontext.shape[1] == 1
941
+ ): # num_precontext Should be [batch,1]
942
+ raise ValueError("num_precontext should be [batch, 1] size.")
943
+ num_precontext = torch.reshape(num_precontext, [-1])
944
+ else:
945
+ num_precontext = torch.zeros([num_batch]).int().to(device)
946
+
947
+ num_input_contexts = input_ids.shape[1]
948
+ num_output_contexts = num_input_contexts + num_pasts_contexts
949
+
950
+ hidden_states = self.embed_tokens(input_ids)
951
+
952
+ if past_key_values is not None:
953
+ pasts_or_spout_value = past_key_values
954
+ elif self.config.d_spout and spout is not None:
955
+ # Make vector from `spout` of GPTSAN to the same shape as past_key_values
956
+ pasts_or_spout_value = self.spout(spout) # projecting `spout` vector
957
+ pasts_or_spout_value = torch.reshape(
958
+ pasts_or_spout_value,
959
+ [
960
+ num_batch,
961
+ self.config.num_layers,
962
+ 2,
963
+ self.config.num_heads,
964
+ num_pasts_contexts,
965
+ self.config.d_model // self.config.num_heads,
966
+ ],
967
+ )
968
+ pasts_or_spout_value = torch.split(pasts_or_spout_value, [1] * self.config.num_layers, dim=1)
969
+ # make same shape as past_key_values
970
+ pasts_or_spout_value = tuple(
971
+ tuple(b.squeeze(1) for b in torch.split(a.squeeze(1), [1, 1], dim=1)) for a in pasts_or_spout_value
972
+ )
973
+ else:
974
+ pasts_or_spout_value = [None] * self.config.num_layers
975
+
976
+ # Token position considering spout and pasts
977
+ token_position = torch.arange(num_input_contexts).to(device) + num_pasts_contexts
978
+
979
+ if attention_mask is None:
980
+ attention_mask = torch.ones(num_batch, num_input_contexts, device=device)
981
+
982
+ # positions for get position_embeddings
983
+ gather_position = (
984
+ (
985
+ torch.zeros((num_batch, self.config.d_model, num_input_contexts)).to(device)
986
+ + token_position.unsqueeze(0)
987
+ )
988
+ .transpose(1, 2)
989
+ .long()
990
+ )
991
+ # When padding with padding_side="left", zeros line up on the left side of attention_mask, so position_embeddings is shifted accordingly
992
+ gather_position -= (1 - attention_mask).argmin(dim=-1).unsqueeze(1).unsqueeze(2)
993
+ gather_position = torch.clip(gather_position, num_pasts_contexts, self.config.max_position_embeddings - 1)
994
+
995
+ # attention_mask is applied per batch
996
+ for i in range(num_batch):
997
+ hidden_states[i] += torch.gather(self.position_embeddings.weight, dim=0, index=gather_position[i])
998
+
999
+ # Create a mask to be used when making the prefix Input length of Prefix-LM variable
1000
+ causal_mask = (
1001
+ torch.tril(torch.ones((num_output_contexts, num_output_contexts), dtype=torch.uint8))
1002
+ .view(1, 1, num_output_contexts, num_output_contexts)
1003
+ .to(device)
1004
+ )
1005
+ prefix_lm_mask = causal_mask[:, :, -num_input_contexts:, :]
1006
+ if token_type_ids is not None:
1007
+ token_type_ids = token_type_ids.unsqueeze(1).unsqueeze(2)
1008
+ prefix_lm_mask = ((prefix_lm_mask + token_type_ids) > 0).float()
1009
+ # Merge prefix_lm_mask and attention_mask
1010
+ extended_attention_mask = prefix_lm_mask * attention_mask.unsqueeze(1).unsqueeze(2)
1011
+
1012
+ # Prepare head mask if needed
1013
+ if head_mask is not None:
1014
+ head_mask = self.get_head_mask(
1015
+ head_mask, self.config.num_switch_layers + self.config.num_ext_layers
1016
+ ) # n_layer x batch x n_heads x N x N
1017
+
1018
+ # outputs
1019
+ present_key_value_states = () if self.config.use_cache or use_cache else None
1020
+ all_hidden_states = () if self.config.output_hidden_states or output_hidden_states else None
1021
+ all_attentions = () if self.config.output_attentions or output_attentions else None
1022
+ all_router_probs = () if self.config.output_router_logits or output_router_logits else None
1023
+
1024
+ for layer, past in enumerate(pasts_or_spout_value):
1025
+ if layer == self.config.num_switch_layers:
1026
+ if self.config.num_ext_layers > 0:
1027
+ # extra_position_embeddings are extra position embeddings that are only created when extending the model with code from the original GPTSAN repository. Not used in the default model.
1028
+ # However, it is created when you create an additional layer and partially train only that location.
1029
+ # Therefore, convert_gptsan_tf_checkpoint_to_pytorch.py is used when converting and loading models created in the original GPTSAN repository.
1030
+ for i in range(num_batch):
1031
+ hidden_states[i] += torch.gather(
1032
+ self.extra_position_embeddings.weight, dim=0, index=gather_position[i]
1033
+ )
1034
+
1035
+ output_router_tuple = (
1036
+ self.config.output_router_logits or output_router_logits
1037
+ ) and layer < self.config.num_switch_layers
1038
+ block_output = self.blocks[layer](
1039
+ hidden_states=hidden_states,
1040
+ past_key_values=past,
1041
+ attention_mask=extended_attention_mask,
1042
+ head_mask=head_mask,
1043
+ use_cache=self.config.use_cache or use_cache,
1044
+ output_attentions=self.config.output_attentions or output_attentions,
1045
+ output_router_tuple=output_router_tuple,
1046
+ )
1047
+
1048
+ outpos = 0
1049
+ hidden_states = block_output[outpos]
1050
+ if self.config.output_hidden_states or output_hidden_states:
1051
+ all_hidden_states += (hidden_states,)
1052
+ if self.config.use_cache or use_cache:
1053
+ outpos += 1
1054
+ present = block_output[outpos]
1055
+ present_key_value_states += (present,)
1056
+ if self.config.output_attentions or output_attentions:
1057
+ outpos += 1
1058
+ attention_probs = block_output[outpos]
1059
+ all_attentions += (attention_probs,)
1060
+ if output_router_tuple:
1061
+ outpos += 1
1062
+ router_tuple = block_output[outpos]
1063
+ all_router_probs.append(router_tuple[0])
1064
+
1065
+ hidden_states = self.last_project(hidden_states)
1066
+ hidden_states = self.act(hidden_states)
1067
+
1068
+ if self.config.output_hidden_states or output_hidden_states:
1069
+ all_hidden_states = all_hidden_states + (hidden_states,)
1070
+
1071
+ if not return_dict:
1072
+ return tuple(
1073
+ v
1074
+ for v in [
1075
+ hidden_states,
1076
+ present_key_value_states,
1077
+ all_hidden_states,
1078
+ all_attentions,
1079
+ all_router_probs,
1080
+ ]
1081
+ if v is not None
1082
+ )
1083
+
1084
+ return MoEModelOutputWithPastAndCrossAttentions(
1085
+ last_hidden_state=hidden_states,
1086
+ past_key_values=present_key_value_states,
1087
+ hidden_states=all_hidden_states,
1088
+ attentions=all_attentions,
1089
+ router_probs=all_router_probs,
1090
+ )
1091
+
1092
+
1093
+ @add_start_docstrings(
1094
+ "The bare GPTSAN-japanese Model with a language modeling head.",
1095
+ GPTSAN_JAPANESE_START_DOCSTRING,
1096
+ )
1097
+ class GPTSanJapaneseForConditionalGeneration(GPTSanJapanesePreTrainedModel):
1098
+ _tied_weights_keys = ["lm_head.weight"]
1099
+
1100
+ def __init__(self, config: GPTSanJapaneseConfig):
1101
+ super().__init__(config)
1102
+ self.model = GPTSanJapaneseModel(config)
1103
+ self.register_buffer("final_logits_bias", torch.zeros([1, config.vocab_size]))
1104
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
1105
+ if not self.config.torchscript:
1106
+ self.lm_head.weight = self.model.embed_tokens.weight
1107
+
1108
+ @add_start_docstrings_to_model_forward(GPTSAN_JAPANESE_INPUTS_DOCSTRING)
1109
+ def forward(
1110
+ self,
1111
+ input_ids: Optional[torch.LongTensor] = None,
1112
+ attention_mask: Optional[torch.FloatTensor] = None,
1113
+ token_type_ids: Optional[torch.FloatTensor] = None,
1114
+ spout: Optional[torch.FloatTensor] = None,
1115
+ past_key_values: Optional[Cache] = None,
1116
+ head_mask: Optional[torch.FloatTensor] = None,
1117
+ use_cache: Optional[bool] = False,
1118
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1119
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1120
+ output_attentions: Optional[bool] = None,
1121
+ output_hidden_states: Optional[bool] = None,
1122
+ return_dict: Optional[bool] = None,
1123
+ output_router_logits: Optional[bool] = None,
1124
+ labels: Optional[torch.LongTensor] = None,
1125
+ ) -> Union[tuple[torch.FloatTensor], MoECausalLMOutputWithPast]:
1126
+ r"""
1127
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1128
+ Labels for computing the sequence classification loss. Indices should be in `[-100, 0, ...,
1129
+ config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
1130
+ labels in `[0, ..., config.vocab_size]`
1131
+
1132
+ Returns:
1133
+ `MoECausalLMOutputWithPast` or `tuple` if `return_dict` returns MoECausalLMOutputWithPast instead of tuple
1134
+
1135
+ Example:
1136
+
1137
+ Text Generation with regular LM Model
1138
+ ```python
1139
+ >>> from transformers import AutoModel, AutoTokenizer, trainer_utils
1140
+
1141
+ >>> device = "cuda"
1142
+ >>> model = AutoModel.from_pretrained("Tanrei/GPTSAN-japanese").to(device)
1143
+ >>> tokenizer = AutoTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
1144
+ >>> x_token = tokenizer("織田信長は、", return_tensors="pt")
1145
+ >>> trainer_utils.set_seed(30)
1146
+ >>> input_ids = x_token.input_ids.to(device)
1147
+ >>> gen_token = model.generate(input_ids, max_new_tokens=50)
1148
+ >>> tokenizer.decode(gen_token[0])
1149
+ "織田信長は、政治・軍事の中枢まで掌握した政治家であり、日本史上類を見ない驚異的な軍事侵攻を続け..."
1150
+ ```
1151
+
1152
+ Text Generation with Prefix-LM Model
1153
+ ```python
1154
+ >>> from transformers import AutoModel, AutoTokenizer, trainer_utils
1155
+
1156
+ >>> device = "cuda"
1157
+ >>> model = AutoModel.from_pretrained("Tanrei/GPTSAN-japanese").to(device)
1158
+ >>> tokenizer = AutoTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
1159
+ >>> x_token = tokenizer("", prefix_text="織田信長は、", return_tensors="pt")
1160
+ >>> trainer_utils.set_seed(30)
1161
+ >>> input_ids = x_token.input_ids.to(device)
1162
+ >>> token_type_ids = x_token.token_type_ids.to(device)
1163
+ >>> gen_token = model.generate(input_ids, token_type_ids=token_type_ids, max_new_tokens=50)
1164
+ >>> tokenizer.decode(gen_token[0])
1165
+ "織田信長は、政治・外交で数々の戦果を上げるが、1568年からは、いわゆる本能寺の変で細川晴元に暗殺される..."
1166
+ ```
1167
+
1168
+ Simultaneously Text Generation And Masked Language Model
1169
+ ```python
1170
+ >>> from transformers import AutoModel, AutoTokenizer, trainer_utils
1171
+
1172
+ >>> device = "cuda"
1173
+ >>> model = AutoModel.from_pretrained("Tanrei/GPTSAN-japanese").to(device)
1174
+ >>> tokenizer = AutoTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
1175
+ >>> masked_sentence = "武田信玄は、<|inputmask|>時代ファンならぜひ押さえ<|inputmask|>きたい名将の一人。"
1176
+ >>> x_token = tokenizer("", prefix_text=masked_sentence, return_tensors="pt")
1177
+ >>> trainer_utils.set_seed(30)
1178
+ >>> input_ids = x_token.input_ids.to(device)
1179
+ >>> token_type_ids = x_token.token_type_ids.to(device)
1180
+ >>> out_lm_token = model.generate(input_ids, token_type_ids=token_type_ids, max_new_tokens=50)
1181
+ >>> out_mlm_token = model(input_ids, token_type_ids=token_type_ids).logits.argmax(axis=-1)
1182
+ >>> tokenizer.decode(out_mlm_token[0])
1183
+ "武田信玄は、戦国時代ファンならぜひ押さえておきたい名将の一人。"
1184
+
1185
+ >>> tokenizer.decode(out_lm_token[0][input_ids.shape[1] :])
1186
+ "武田氏の三代に渡った武田家のひとり\n甲斐市に住む、日本史上最大の戦国大名。..."
1187
+ ```"""
1188
+ SEG_TOKEN = self.config.separator_token_id
1189
+ use_cache = use_cache or self.config.use_cache
1190
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1191
+ model_return_dict = True
1192
+ num_precontext = None
1193
+ if input_ids is not None:
1194
+ num_batch = input_ids.shape[0]
1195
+ num_precontext = torch.zeros([num_batch]).int().to(input_ids.device)
1196
+ where_separators = torch.where(input_ids == SEG_TOKEN)
1197
+ num_precontext[where_separators[0]] += where_separators[1]
1198
+ num_precontext = num_precontext.unsqueeze(1)
1199
+
1200
+ outputs = self.model(
1201
+ input_ids,
1202
+ attention_mask,
1203
+ token_type_ids,
1204
+ spout,
1205
+ past_key_values,
1206
+ head_mask,
1207
+ use_cache,
1208
+ inputs_embeds,
1209
+ decoder_inputs_embeds,
1210
+ output_attentions,
1211
+ output_hidden_states,
1212
+ model_return_dict,
1213
+ output_router_logits,
1214
+ num_precontext,
1215
+ )
1216
+
1217
+ lm_logits = self.lm_head(outputs[0])
1218
+ if lm_logits.shape[-1] == self.final_logits_bias.shape[-1]:
1219
+ lm_logits = lm_logits + self.final_logits_bias
1220
+
1221
+ loss = None
1222
+ z_loss = None
1223
+ router_probs = None
1224
+ aux_loss = None
1225
+ if labels is not None:
1226
+ # move labels to correct device to enable model parallelism
1227
+ labels = labels.to(lm_logits.device)
1228
+
1229
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
1230
+
1231
+ if output_router_logits:
1232
+ # Compute the router loss (z_loss + auxiliary loss) for each router in the encoder and decoder
1233
+ router_logits, expert_indexes = self._unpack_router_logits(outputs.router_probs)
1234
+ z_loss = router_z_loss_func(router_logits)
1235
+ router_probs = nn.Softmax(dim=-1)(router_logits)
1236
+ aux_loss = load_balancing_loss_func(router_probs, expert_indexes)
1237
+
1238
+ loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
1239
+
1240
+ if not return_dict:
1241
+ return tuple(
1242
+ v
1243
+ for v in [
1244
+ loss,
1245
+ lm_logits,
1246
+ outputs.past_key_values,
1247
+ outputs.hidden_states,
1248
+ outputs.router_probs,
1249
+ z_loss,
1250
+ aux_loss,
1251
+ ]
1252
+ if v is not None
1253
+ )
1254
+
1255
+ return MoECausalLMOutputWithPast(
1256
+ loss=loss,
1257
+ logits=lm_logits,
1258
+ past_key_values=outputs.past_key_values,
1259
+ hidden_states=outputs.hidden_states,
1260
+ attentions=outputs.attentions,
1261
+ router_logits=outputs.router_probs,
1262
+ z_loss=z_loss,
1263
+ aux_loss=aux_loss,
1264
+ )
1265
+
1266
+ def prepare_inputs_for_generation(
1267
+ self,
1268
+ input_ids: torch.LongTensor,
1269
+ attention_mask: torch.FloatTensor,
1270
+ token_type_ids: Optional[torch.FloatTensor] = None,
1271
+ spout: Optional[Union[list, torch.FloatTensor]] = None,
1272
+ past_key_values: Optional[Cache] = None,
1273
+ **kwargs,
1274
+ ):
1275
+ if isinstance(spout, list):
1276
+ spout = torch.tensor(spout).float()
1277
+ if input_ids is not None:
1278
+ spout = spout.to(input_ids.device)
1279
+ if past_key_values is not None:
1280
+ return {
1281
+ "input_ids": input_ids[:, -1:] if input_ids is not None else None,
1282
+ "attention_mask": attention_mask,
1283
+ "token_type_ids": token_type_ids[:, -1:] if token_type_ids is not None else None,
1284
+ "spout": spout,
1285
+ "past_key_values": past_key_values,
1286
+ }
1287
+ return {
1288
+ "input_ids": input_ids,
1289
+ "attention_mask": attention_mask,
1290
+ "token_type_ids": token_type_ids,
1291
+ "spout": spout,
1292
+ "past_key_values": None,
1293
+ }
1294
+
1295
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
1296
+ return self._shift_right(labels)
1297
+
1298
+ def resize_token_embeddings(
1299
+ self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None, mean_resizing: bool = True
1300
+ ) -> nn.Embedding:
1301
+ new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
1302
+ self._resize_final_logits_bias(new_embeddings.weight.shape[0])
1303
+ return new_embeddings
1304
+
1305
+ def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
1306
+ old_num_tokens = self.final_logits_bias.shape[-1]
1307
+ if new_num_tokens <= old_num_tokens:
1308
+ new_bias = self.final_logits_bias[:, :new_num_tokens]
1309
+ else:
1310
+ extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
1311
+ new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
1312
+ self.register_buffer("final_logits_bias", new_bias)
1313
+
1314
+ def get_input_embeddings(self):
1315
+ return self.model.get_input_embeddings()
1316
+
1317
+ def set_input_embeddings(self, new_embeddings):
1318
+ self.model.set_input_embeddings(new_embeddings)
1319
+
1320
+ def _unpack_router_logits(self, router_outputs):
1321
+ total_router_logits = []
1322
+ total_expert_indexes = []
1323
+ for router_output in router_outputs:
1324
+ if len(router_output[0].shape) > 1:
1325
+ router_logits, expert_indexes = router_output
1326
+ total_router_logits.append(router_logits)
1327
+ total_expert_indexes.append(expert_indexes)
1328
+ return torch.cat(total_router_logits, dim=1), torch.cat(total_expert_indexes, dim=1)
1329
+
1330
+
1331
+ __all__ = ["GPTSanJapaneseForConditionalGeneration", "GPTSanJapaneseModel", "GPTSanJapanesePreTrainedModel"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/gptsan_japanese/tokenization_gptsan_japanese.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for GPTSANJapanese."""
16
+
17
+ import collections
18
+ import json
19
+ import os
20
+ import re
21
+ import sys
22
+ from typing import Optional, Union
23
+
24
+ import numpy as np
25
+
26
+ from ....tokenization_utils import PreTrainedTokenizer
27
+ from ....tokenization_utils_base import (
28
+ BatchEncoding,
29
+ PreTokenizedInput,
30
+ PreTokenizedInputPair,
31
+ TextInput,
32
+ TextInputPair,
33
+ TruncationStrategy,
34
+ )
35
+ from ....utils import PaddingStrategy, logging
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "emoji_file": "emoji.json"}
41
+
42
+
43
+ def load_vocab_and_emoji(vocab_file, emoji_file):
44
+ """Loads a vocabulary file and emoji file into a dictionary."""
45
+ with open(emoji_file, "r", encoding="utf-8") as f:
46
+ emoji = json.loads(f.read())
47
+
48
+ vocab = collections.OrderedDict()
49
+ raw_vocab = collections.OrderedDict()
50
+ ids_to_tokens = collections.OrderedDict()
51
+ with open(vocab_file, "r", encoding="utf-8") as f:
52
+ token = f.readlines()
53
+ token = [[t.rstrip("\n")] if (t == ",\n" or "," not in t) else t.rstrip("\n").split(",") for t in token]
54
+ for idx, b in enumerate(token):
55
+ ids_to_tokens[idx] = b
56
+ raw_vocab[",".join(b)] = idx
57
+ for wd in b:
58
+ vocab[wd] = idx
59
+
60
+ return vocab, raw_vocab, ids_to_tokens, emoji
61
+
62
+
63
+ class GPTSanJapaneseTokenizer(PreTrainedTokenizer):
64
+ """
65
+ This tokenizer is based on GPTNeoXJapaneseTokenizer and has the following modifications
66
+ - Decoding byte0~byte255 tokens correctly
67
+ - Added bagofword token handling
68
+ - Return token_type_ids for Prefix-LM model
69
+ The bagofword token represents a repetition of the previous token and is converted to 3 consecutive tokens when
70
+ decoding In addition, the original Japanese special Sub-Word-Encoding has been released in this repository
71
+ (https://github.com/tanreinama/Japanese-BPEEncoder_V2). The token_type_ids is a mask indicating the prefix input
72
+ position of the Prefix-LM model. To specify a prefix position, specify a prefix input for prefix_text, or specify a
73
+ sentence of the prefix part and the part after it as a text pair of batch input.
74
+
75
+ Example:
76
+
77
+ ```python
78
+ >>> from transformers import GPTSanJapaneseTokenizer
79
+
80
+ >>> tokenizer = GPTSanJapaneseTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
81
+ >>> # You can confirm both 慶応 and 慶應 are encoded to 17750
82
+ >>> tokenizer("吾輩は猫である🐯。実は慶応(慶應)大学出身")["input_ids"]
83
+ [35993, 35998, 34347, 31459, 30647, 31448, 25, 30659, 35729, 35676, 32417, 30647, 17750, 35589, 17750, 35590, 321, 1281]
84
+
85
+ >>> # Both 慶応 and 慶應 are decoded to 慶応
86
+ >>> tokenizer.decode(tokenizer("吾輩は猫である🐯。実は慶応(慶應)大学出身")["input_ids"])
87
+ '吾輩は猫である🐯。実は慶応(慶応)大学出身'
88
+ ```
89
+
90
+ Example for Prefix-LM:
91
+
92
+ ```python
93
+ >>> from transformers import GPTSanJapaneseTokenizer
94
+
95
+ >>> tokenizer = GPTSanJapaneseTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
96
+ >>> tokenizer("実は慶応(慶應)大学出身", prefix_text="吾輩は猫である🐯。")["input_ids"]
97
+ [35993, 34347, 31459, 30647, 31448, 25, 30659, 35729, 35676, 35998, 32417, 30647, 17750, 35589, 17750, 35590, 321, 1281]
98
+
99
+ >>> # Mask for Prefix-LM inputs
100
+ >>> tokenizer("実は慶応(慶應)大学出身", prefix_text="吾輩は猫である🐯。")["token_type_ids"]
101
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
102
+ ```
103
+
104
+ Example for batch encode:
105
+
106
+ ```python
107
+ >>> from transformers import GPTSanJapaneseTokenizer
108
+
109
+ >>> tokenizer = GPTSanJapaneseTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
110
+ >>> tokenizer([["武田信玄", "は、"], ["織田信長", "の配下の、"]], padding=True)["input_ids"]
111
+ [[35993, 35998, 8640, 25948, 35993, 35998, 30647, 35675, 35999, 35999], [35993, 35998, 10382, 9868, 35993, 35998, 30646, 9459, 30646, 35675]]
112
+
113
+ >>> # Mask for Prefix-LM inputs
114
+ >>> tokenizer([["武田信玄", "は、"], ["織田信長", "の配下の、"]], padding=True)["token_type_ids"]
115
+ [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
116
+
117
+ >>> # Mask for padding
118
+ >>> tokenizer([["武田信玄", "は、"], ["織田信長", "の配下の、"]], padding=True)["attention_mask"]
119
+ [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
120
+ ```
121
+
122
+ Args:
123
+ vocab_file (`str`):
124
+ File containing the vocabulary.
125
+ emoji_file (`str`):
126
+ File containing the emoji.
127
+ unk_token (`str`, *optional*, defaults to `"<|nottoken|>"`):
128
+ The token used for unknown character
129
+ pad_token (`str`, *optional*, defaults to `"<|separator|>"`):
130
+ The token used for padding
131
+ bos_token (`str`, *optional*, defaults to `"<|startoftext|>"`):
132
+ The beginning of sequence token.
133
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
134
+ The end of sequence token.
135
+ sep_token (`str`, *optional*, defaults to `"<|segmenter|>"`):
136
+ A special token to separate token to prefix part and general input part.
137
+ do_clean_text (`bool`, *optional*, defaults to `False`):
138
+ Whether or not to clean text for URL, EMAIL, TEL, Japanese DATE and Japanese PRICE.
139
+ """
140
+
141
+ vocab_files_names = VOCAB_FILES_NAMES
142
+ model_input_names = ["input_ids", "attention_mask", "token_type_ids"]
143
+
144
+ def __init__(
145
+ self,
146
+ vocab_file,
147
+ emoji_file,
148
+ unk_token="<|nottoken|>",
149
+ pad_token="<|separator|>",
150
+ bos_token="<|startoftext|>",
151
+ eos_token="<|endoftext|>",
152
+ sep_token="<|segmenter|>",
153
+ do_clean_text=False,
154
+ **kwargs,
155
+ ):
156
+ if not os.path.isfile(vocab_file):
157
+ raise ValueError(
158
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
159
+ " model use `tokenizer = GPTSanJapaneseTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
160
+ )
161
+ if not os.path.isfile(emoji_file):
162
+ raise ValueError(
163
+ f"Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google"
164
+ " pretrained model use `tokenizer = GPTSanJapaneseTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
165
+ )
166
+ self.do_clean_text = do_clean_text
167
+ self.vocab, self.raw_vocab, self.ids_to_tokens, self.emoji = load_vocab_and_emoji(vocab_file, emoji_file)
168
+ self.subword_tokenizer = SubWordJapaneseTokenizer(
169
+ vocab=self.vocab, ids_to_tokens=self.ids_to_tokens, emoji=self.emoji
170
+ )
171
+
172
+ super().__init__(
173
+ unk_token=unk_token,
174
+ pad_token=pad_token,
175
+ bos_token=bos_token,
176
+ eos_token=eos_token,
177
+ sep_token=sep_token,
178
+ do_clean_text=do_clean_text,
179
+ **kwargs,
180
+ )
181
+
182
+ @property
183
+ def vocab_size(self):
184
+ # self.vocab contains support for character fluctuation unique to Japanese, and has a large number of vocab
185
+ return len(self.raw_vocab)
186
+
187
+ def get_vocab(self):
188
+ return dict(self.raw_vocab, **self.added_tokens_encoder)
189
+
190
+ def _tokenize(self, text):
191
+ return self.subword_tokenizer.tokenize(text, clean=self.do_clean_text)
192
+
193
+ def _convert_token_to_id(self, token):
194
+ """Converts a token (str) in an id using the vocab."""
195
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
196
+
197
+ def _convert_id_to_token(self, index):
198
+ """Converts an index (integer) in a token (str) using the vocab."""
199
+ return self.subword_tokenizer.convert_id_to_token(index)
200
+
201
+ def convert_tokens_to_string(self, tokens):
202
+ """Converts a sequence of tokens (string) in a single string."""
203
+ words = []
204
+ byte_tokens = []
205
+ for word in tokens:
206
+ if word[:6] == "<|byte" and word[-2:] == "|>":
207
+ byte_tokens.append(int(word[6:-2]))
208
+ else:
209
+ if len(byte_tokens) > 0:
210
+ words.append(bytearray(byte_tokens).decode("utf-8", errors="replace"))
211
+ byte_tokens = []
212
+ if word[:7] == "<|emoji" and word[-2:] == "|>":
213
+ words.append(self.emoji["emoji_inv"][word])
214
+ elif word == "<SP>":
215
+ words.append(" ")
216
+ elif word == "<BR>":
217
+ words.append("\n")
218
+ elif word == "<TAB>":
219
+ words.append("\t")
220
+ elif word == "<BLOCK>":
221
+ words.append("▀")
222
+ elif word == "<KIGOU>":
223
+ words.append("ǀ")
224
+ elif word == "<U2000U2BFF>":
225
+ words.append("‖")
226
+ elif word == "<|bagoftoken|>":
227
+ if len(words) > 0:
228
+ words.append(words[-1])
229
+ words.append(words[-1])
230
+ words.append(words[-1])
231
+ elif word.startswith("<|") and word.endswith("|>"):
232
+ words.append("")
233
+ else:
234
+ words.append(word)
235
+ if len(byte_tokens) > 0:
236
+ words.append(bytearray(byte_tokens).decode("utf-8", errors="replace"))
237
+ text = "".join(words)
238
+ return text
239
+
240
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
241
+ index = 0
242
+ if os.path.isdir(save_directory):
243
+ vocab_file = os.path.join(
244
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
245
+ )
246
+ emoji_file = os.path.join(
247
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["emoji_file"]
248
+ )
249
+ else:
250
+ vocab_file = (
251
+ (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["vocab_file"]
252
+ )
253
+ emoji_file = (
254
+ (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["emoji_file"]
255
+ )
256
+ with open(vocab_file, "w", encoding="utf-8") as writer:
257
+ for token_index, token in self.ids_to_tokens.items():
258
+ if index != token_index:
259
+ logger.warning(
260
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
261
+ " Please check that the vocabulary is not corrupted!"
262
+ )
263
+ index = token_index
264
+ writer.write(",".join(token) + "\n")
265
+ index += 1
266
+ with open(emoji_file, "w", encoding="utf-8") as writer:
267
+ json.dump(self.emoji, writer)
268
+ return vocab_file, emoji_file
269
+
270
+ def create_token_type_ids_from_sequences(
271
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
272
+ ) -> list[int]:
273
+ # docstyle-ignore
274
+ """
275
+ The tokenizer returns token_type_ids as separators between the Prefix part and the rest.
276
+ token_type_ids is 1 for the Prefix part and 0 for the rest of the token.
277
+
278
+ Example:
279
+ ```python
280
+ >>> from transformers import GPTSanJapaneseTokenizer
281
+
282
+ >>> tokenizer = GPTSanJapaneseTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
283
+ >>> x_token = tokenizer("アイウエ")
284
+ >>> # input_ids: | SOT | SEG | ア | イ | ウ | エ |
285
+ >>> # token_type_ids: | 1 | 0 | 0 | 0 | 0 | 0 |
286
+
287
+ >>> x_token = tokenizer("", prefix_text="アイウエ")
288
+ >>> # input_ids: | SOT | ア | イ | ウ | エ | SEG |
289
+ >>> # token_type_ids: | 1 | 1 | 1 | 1 | 1 | 0 |
290
+
291
+ >>> x_token = tokenizer("ウエ", prefix_text="アイ")
292
+ >>> # input_ids: | SOT | ア | イ | SEG | ウ | エ |
293
+ >>> # token_type_ids: | 1 | 1 | 1 | 0 | 0 | 0 |
294
+ ```"""
295
+ prefix_len = 0
296
+ if self.sep_token in self.vocab:
297
+ segid = self.vocab[self.sep_token]
298
+ if segid in token_ids_0:
299
+ prefix_len = token_ids_0.index(segid)
300
+ if token_ids_1 is None:
301
+ total_len = len(token_ids_0)
302
+ else:
303
+ total_len = len(token_ids_0 + token_ids_1)
304
+ return prefix_len * [1] + (total_len - prefix_len) * [0]
305
+
306
+ def prepare_for_tokenization(self, text, prefix_text=None, add_sep_token=None, **kwargs):
307
+ # GPTSAN inserts extra SEP tokens in Prefix-LM in addition to SOT for text generation.
308
+ # SOT at the beginning of the text, and SEP at the separator between the Prefix part and the rest.
309
+ if add_sep_token is None:
310
+ add_sep_token = self.sep_token not in text # If insert un-prefix position explicitly
311
+ prepared = self.bos_token if self.bos_token in self.vocab else ""
312
+ prepared += prefix_text if prefix_text is not None else ""
313
+ if add_sep_token:
314
+ prepared += self.sep_token if self.sep_token in self.vocab else ""
315
+ prepared += text
316
+ return (prepared, kwargs)
317
+
318
+ def _batch_encode_plus(
319
+ self,
320
+ batch_text_or_text_pairs: Union[
321
+ list[TextInput], list[TextInputPair], list[PreTokenizedInput], list[PreTokenizedInputPair]
322
+ ],
323
+ add_special_tokens: bool = True,
324
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
325
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
326
+ max_length: Optional[int] = None,
327
+ stride: int = 0,
328
+ is_split_into_words: bool = False,
329
+ pad_to_multiple_of: Optional[int] = None,
330
+ return_tensors: Optional[str] = None,
331
+ return_token_type_ids: Optional[bool] = None,
332
+ return_attention_mask: Optional[bool] = None,
333
+ return_overflowing_tokens: bool = False,
334
+ return_special_tokens_mask: bool = False,
335
+ return_offsets_mapping: bool = False,
336
+ return_length: bool = False,
337
+ verbose: bool = True,
338
+ **kwargs,
339
+ ) -> BatchEncoding:
340
+ # This tokenizer converts input text pairs into Prefix input and subsequent input
341
+ if isinstance(batch_text_or_text_pairs[0], tuple) or isinstance(tuple(batch_text_or_text_pairs[0]), list):
342
+ # As a single text with an explicit un-prefix position
343
+ batch_prefix_texts = []
344
+ for pref, txt in batch_text_or_text_pairs:
345
+ batch_prefix_texts.append(pref + self.sep_token + txt)
346
+ batch_text_or_text_pairs = batch_prefix_texts
347
+
348
+ return super()._batch_encode_plus(
349
+ batch_text_or_text_pairs,
350
+ add_special_tokens,
351
+ padding_strategy,
352
+ truncation_strategy,
353
+ max_length,
354
+ stride,
355
+ is_split_into_words,
356
+ pad_to_multiple_of,
357
+ return_tensors,
358
+ return_token_type_ids,
359
+ return_attention_mask,
360
+ return_overflowing_tokens,
361
+ return_special_tokens_mask,
362
+ return_offsets_mapping,
363
+ return_length,
364
+ verbose,
365
+ **kwargs,
366
+ )
367
+
368
+
369
+ class SubWordJapaneseTokenizer:
370
+ """
371
+ This tokenizer is based on GPTNeoXJapaneseTokenizer and has the following modifications
372
+ - Decoding byte0~byte255 tokens correctly
373
+ - Added bagofword token handling
374
+
375
+ https://github.com/tanreinama/Japanese-BPEEncoder_V2 This tokenizer class is under MIT License according to the
376
+ original repository.
377
+
378
+ MIT License
379
+
380
+ Copyright (c) 2020 tanreinama
381
+
382
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
383
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
384
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
385
+ permit persons to whom the Software is furnished to do so, subject to the following conditions:
386
+
387
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of
388
+ the Software.
389
+
390
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
391
+ THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
392
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
393
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
394
+ SOFTWARE.
395
+ """
396
+
397
+ def __init__(self, vocab, ids_to_tokens, emoji):
398
+ self.vocab = vocab # same as swe
399
+ self.ids_to_tokens = ids_to_tokens # same as bpe
400
+ self.emoji = emoji
401
+ self.maxlen = np.max([len(w) for w in self.vocab])
402
+ self.content_repatter1 = re.compile(r"(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)")
403
+ self.content_repatter2 = re.compile(r"[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*")
404
+ self.content_repatter3 = re.compile(r"[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}")
405
+ self.content_repatter4 = re.compile(
406
+ r"([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"
407
+ )
408
+ self.content_repatter5 = re.compile(
409
+ r"(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"
410
+ )
411
+ # The original version of this regex displays catastrophic backtracking behaviour. We avoid this using
412
+ # possessive quantifiers in Py >= 3.11. In versions below this, we avoid the vulnerability using a slightly
413
+ # different regex that should generally have the same behaviour in most non-pathological cases.
414
+ if sys.version_info >= (3, 11):
415
+ self.content_repatter6 = re.compile(
416
+ r"(?:\d,\d{3}|[\d億])*+"
417
+ r"(?:\d,\d{3}|[\d万])*+"
418
+ r"(?:\d,\d{3}|[\d千])*+"
419
+ r"(?:千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+"
420
+ r"(?:\(税込\)|\(税抜\)|\+tax)*"
421
+ )
422
+ else:
423
+ self.content_repatter6 = re.compile(
424
+ r"(?:\d,\d{3}|[\d億万千])*"
425
+ r"(?:千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+"
426
+ r"(?:\(税込\)|\(税抜\)|\+tax)*"
427
+ )
428
+ keisen = "─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿"
429
+ blocks = "▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟"
430
+ self.content_trans1 = str.maketrans(dict.fromkeys(keisen + blocks, "<BLOCK>"))
431
+
432
+ def __len__(self):
433
+ return len(self.ids_to_tokens)
434
+
435
+ def clean_text(self, content):
436
+ content = self.content_repatter1.sub("<URL>", content)
437
+ content = self.content_repatter2.sub("<EMAIL>", content)
438
+ content = self.content_repatter3.sub("<TEL>", content)
439
+ content = self.content_repatter4.sub("<DATE>", content)
440
+ content = self.content_repatter5.sub("<DATE>", content)
441
+ content = self.content_repatter6.sub("<PRICE>", content)
442
+ content = content.translate(self.content_trans1)
443
+ while "<BLOCK><BLOCK>" in content:
444
+ content = content.replace("<BLOCK><BLOCK>", "<BLOCK>")
445
+ return content
446
+
447
+ def tokenize(self, text, clean=False):
448
+ text = text.replace(" ", "<SP>")
449
+ text = text.replace(" ", "<SP>")
450
+ text = text.replace("\r\n", "<BR>")
451
+ text = text.replace("\n", "<BR>")
452
+ text = text.replace("\r", "<BR>")
453
+ text = text.replace("\t", "<TAB>")
454
+ text = text.replace("—", "ー")
455
+ text = text.replace("−", "ー")
456
+ for k, v in self.emoji["emoji"].items():
457
+ if k in text:
458
+ text = text.replace(k, v)
459
+ if clean:
460
+ text = self.clean_text(text)
461
+
462
+ def check_simbol(x):
463
+ e = x.encode()
464
+ if len(x) == 1 and len(e) == 2:
465
+ c = (int(e[0]) << 8) + int(e[1])
466
+ if (
467
+ (c >= 0xC2A1 and c <= 0xC2BF)
468
+ or (c >= 0xC780 and c <= 0xC783)
469
+ or (c >= 0xCAB9 and c <= 0xCBBF)
470
+ or (c >= 0xCC80 and c <= 0xCDA2)
471
+ ):
472
+ return True
473
+ return False
474
+
475
+ def checku2e(x):
476
+ e = x.encode()
477
+ if len(x) == 1 and len(e) == 3:
478
+ c = (int(e[0]) << 16) + (int(e[1]) << 8) + int(e[2])
479
+ if c >= 0xE28080 and c <= 0xE2B07F:
480
+ return True
481
+ return False
482
+
483
+ pos = 0
484
+ result = []
485
+ while pos < len(text):
486
+ end = min(len(text), pos + self.maxlen + 1) if text[pos] == "<" else pos + 3
487
+ candidates = [] # (token_id, token, pos)
488
+ for e in range(end, pos, -1):
489
+ wd = text[pos:e]
490
+ if wd in self.vocab:
491
+ if wd[0] == "<" and len(wd) > 2:
492
+ candidates = [(self.vocab[wd], wd, e)]
493
+ break
494
+ else:
495
+ candidates.append((self.vocab[wd], wd, e))
496
+ if len(candidates) > 0:
497
+ # the smallest token_id is adopted
498
+ _, wd, e = min(candidates, key=lambda x: x[0])
499
+ result.append(wd)
500
+ pos = e
501
+ else:
502
+ end = pos + 1
503
+ wd = text[pos:end]
504
+ if check_simbol(wd):
505
+ result.append("<KIGOU>")
506
+ elif checku2e(wd):
507
+ result.append("<U2000U2BFF>")
508
+ else:
509
+ for i in wd.encode("utf-8"):
510
+ result.append("<|byte%d|>" % i)
511
+ pos = end
512
+ return result
513
+
514
+ def convert_id_to_token(self, index):
515
+ return self.ids_to_tokens[index][0]
516
+
517
+
518
+ __all__ = ["GPTSanJapaneseTokenizer"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/graphormer/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ....utils import _LazyModule
17
+ from ....utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_graphormer import *
22
+ from .modeling_graphormer import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/graphormer/algos_graphormer.pyx ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation and HuggingFace
2
+ # Licensed under the MIT License.
3
+
4
+ import cython
5
+
6
+ cimport numpy
7
+ from cython.parallel cimport parallel, prange
8
+
9
+ import numpy as np
10
+
11
+
12
+ # Reduce this number if matrices are too big for large graphs
13
+ UNREACHABLE_NODE_DISTANCE = 510
14
+
15
+ def floyd_warshall(adjacency_matrix):
16
+ """
17
+ Applies the Floyd-Warshall algorithm to the adjacency matrix, to compute the
18
+ shortest paths distance between all nodes, up to UNREACHABLE_NODE_DISTANCE.
19
+ """
20
+ (nrows, ncols) = adjacency_matrix.shape
21
+ assert nrows == ncols
22
+ cdef unsigned int n = nrows
23
+
24
+ adj_mat_copy = adjacency_matrix.astype(np.int32, order='C', casting='safe', copy=True)
25
+ assert adj_mat_copy.flags['C_CONTIGUOUS']
26
+ cdef numpy.ndarray[numpy.int32_t, ndim=2, mode='c'] M = adj_mat_copy
27
+ cdef numpy.ndarray[numpy.int32_t, ndim=2, mode='c'] path = -1 * np.ones([n, n], dtype=np.int32)
28
+
29
+ cdef unsigned int i, j, k
30
+ cdef numpy.int32_t M_ij, M_ik, cost_ikkj
31
+ cdef numpy.int32_t* M_ptr = &M[0,0]
32
+ cdef numpy.int32_t* M_i_ptr
33
+ cdef numpy.int32_t* M_k_ptr
34
+
35
+ # set unreachable nodes distance to UNREACHABLE_NODE_DISTANCE
36
+ for i in range(n):
37
+ for j in range(n):
38
+ if i == j:
39
+ M[i][j] = 0
40
+ elif M[i][j] == 0:
41
+ M[i][j] = UNREACHABLE_NODE_DISTANCE
42
+
43
+ # floyed algo
44
+ for k in range(n):
45
+ M_k_ptr = M_ptr + n*k
46
+ for i in range(n):
47
+ M_i_ptr = M_ptr + n*i
48
+ M_ik = M_i_ptr[k]
49
+ for j in range(n):
50
+ cost_ikkj = M_ik + M_k_ptr[j]
51
+ M_ij = M_i_ptr[j]
52
+ if M_ij > cost_ikkj:
53
+ M_i_ptr[j] = cost_ikkj
54
+ path[i][j] = k
55
+
56
+ # set unreachable path to UNREACHABLE_NODE_DISTANCE
57
+ for i in range(n):
58
+ for j in range(n):
59
+ if M[i][j] >= UNREACHABLE_NODE_DISTANCE:
60
+ path[i][j] = UNREACHABLE_NODE_DISTANCE
61
+ M[i][j] = UNREACHABLE_NODE_DISTANCE
62
+
63
+ return M, path
64
+
65
+
66
+ def get_all_edges(path, i, j):
67
+ """
68
+ Recursive function to compute all possible paths between two nodes from the graph adjacency matrix.
69
+ """
70
+ cdef int k = path[i][j]
71
+ if k == -1:
72
+ return []
73
+ else:
74
+ return get_all_edges(path, i, k) + [k] + get_all_edges(path, k, j)
75
+
76
+
77
+ def gen_edge_input(max_dist, path, edge_feat):
78
+ """
79
+ Generates the full edge feature and adjacency matrix.
80
+ Shape: num_nodes * num_nodes * max_distance_between_nodes * num_edge_features
81
+ Dim 1 is the input node, dim 2 the output node of the edge, dim 3 the depth of the edge, dim 4 the feature
82
+ """
83
+ (nrows, ncols) = path.shape
84
+ assert nrows == ncols
85
+ cdef unsigned int n = nrows
86
+ cdef unsigned int max_dist_copy = max_dist
87
+
88
+ path_copy = path.astype(long, order='C', casting='safe', copy=True)
89
+ edge_feat_copy = edge_feat.astype(long, order='C', casting='safe', copy=True)
90
+ assert path_copy.flags['C_CONTIGUOUS']
91
+ assert edge_feat_copy.flags['C_CONTIGUOUS']
92
+
93
+ cdef numpy.ndarray[numpy.int32_t, ndim=4, mode='c'] edge_fea_all = -1 * np.ones([n, n, max_dist_copy, edge_feat.shape[-1]], dtype=np.int32)
94
+ cdef unsigned int i, j, k, num_path, cur
95
+
96
+ for i in range(n):
97
+ for j in range(n):
98
+ if i == j:
99
+ continue
100
+ if path_copy[i][j] == UNREACHABLE_NODE_DISTANCE:
101
+ continue
102
+ path = [i] + get_all_edges(path_copy, i, j) + [j]
103
+ num_path = len(path) - 1
104
+ for k in range(num_path):
105
+ edge_fea_all[i, j, k, :] = edge_feat_copy[path[k], path[k+1], :]
106
+
107
+ return edge_fea_all
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/graphormer/collating_graphormer.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation and HuggingFace
2
+ # Licensed under the MIT License.
3
+
4
+ from collections.abc import Mapping
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ from ....utils import is_cython_available, requires_backends
11
+
12
+
13
+ if is_cython_available():
14
+ import pyximport
15
+
16
+ pyximport.install(setup_args={"include_dirs": np.get_include()})
17
+ from . import algos_graphormer
18
+
19
+
20
+ def convert_to_single_emb(x, offset: int = 512):
21
+ feature_num = x.shape[1] if len(x.shape) > 1 else 1
22
+ feature_offset = 1 + np.arange(0, feature_num * offset, offset, dtype=np.int64)
23
+ x = x + feature_offset
24
+ return x
25
+
26
+
27
+ def preprocess_item(item, keep_features=True):
28
+ requires_backends(preprocess_item, ["cython"])
29
+
30
+ if keep_features and "edge_attr" in item: # edge_attr
31
+ edge_attr = np.asarray(item["edge_attr"], dtype=np.int64)
32
+ else:
33
+ edge_attr = np.ones((len(item["edge_index"][0]), 1), dtype=np.int64) # same embedding for all
34
+
35
+ if keep_features and "node_feat" in item: # input_nodes
36
+ node_feature = np.asarray(item["node_feat"], dtype=np.int64)
37
+ else:
38
+ node_feature = np.ones((item["num_nodes"], 1), dtype=np.int64) # same embedding for all
39
+
40
+ edge_index = np.asarray(item["edge_index"], dtype=np.int64)
41
+
42
+ input_nodes = convert_to_single_emb(node_feature) + 1
43
+ num_nodes = item["num_nodes"]
44
+
45
+ if len(edge_attr.shape) == 1:
46
+ edge_attr = edge_attr[:, None]
47
+ attn_edge_type = np.zeros([num_nodes, num_nodes, edge_attr.shape[-1]], dtype=np.int64)
48
+ attn_edge_type[edge_index[0], edge_index[1]] = convert_to_single_emb(edge_attr) + 1
49
+
50
+ # node adj matrix [num_nodes, num_nodes] bool
51
+ adj = np.zeros([num_nodes, num_nodes], dtype=bool)
52
+ adj[edge_index[0], edge_index[1]] = True
53
+
54
+ shortest_path_result, path = algos_graphormer.floyd_warshall(adj)
55
+ max_dist = np.amax(shortest_path_result)
56
+
57
+ input_edges = algos_graphormer.gen_edge_input(max_dist, path, attn_edge_type)
58
+ attn_bias = np.zeros([num_nodes + 1, num_nodes + 1], dtype=np.single) # with graph token
59
+
60
+ # combine
61
+ item["input_nodes"] = input_nodes + 1 # we shift all indices by one for padding
62
+ item["attn_bias"] = attn_bias
63
+ item["attn_edge_type"] = attn_edge_type
64
+ item["spatial_pos"] = shortest_path_result.astype(np.int64) + 1 # we shift all indices by one for padding
65
+ item["in_degree"] = np.sum(adj, axis=1).reshape(-1) + 1 # we shift all indices by one for padding
66
+ item["out_degree"] = item["in_degree"] # for undirected graph
67
+ item["input_edges"] = input_edges + 1 # we shift all indices by one for padding
68
+ if "labels" not in item:
69
+ item["labels"] = item["y"]
70
+
71
+ return item
72
+
73
+
74
+ class GraphormerDataCollator:
75
+ def __init__(self, spatial_pos_max=20, on_the_fly_processing=False):
76
+ if not is_cython_available():
77
+ raise ImportError("Graphormer preprocessing needs Cython (pyximport)")
78
+
79
+ self.spatial_pos_max = spatial_pos_max
80
+ self.on_the_fly_processing = on_the_fly_processing
81
+
82
+ def __call__(self, features: list[dict]) -> dict[str, Any]:
83
+ if self.on_the_fly_processing:
84
+ features = [preprocess_item(i) for i in features]
85
+
86
+ if not isinstance(features[0], Mapping):
87
+ features = [vars(f) for f in features]
88
+ batch = {}
89
+
90
+ max_node_num = max(len(i["input_nodes"]) for i in features)
91
+ node_feat_size = len(features[0]["input_nodes"][0])
92
+ edge_feat_size = len(features[0]["attn_edge_type"][0][0])
93
+ max_dist = max(len(i["input_edges"][0][0]) for i in features)
94
+ edge_input_size = len(features[0]["input_edges"][0][0][0])
95
+ batch_size = len(features)
96
+
97
+ batch["attn_bias"] = torch.zeros(batch_size, max_node_num + 1, max_node_num + 1, dtype=torch.float)
98
+ batch["attn_edge_type"] = torch.zeros(batch_size, max_node_num, max_node_num, edge_feat_size, dtype=torch.long)
99
+ batch["spatial_pos"] = torch.zeros(batch_size, max_node_num, max_node_num, dtype=torch.long)
100
+ batch["in_degree"] = torch.zeros(batch_size, max_node_num, dtype=torch.long)
101
+ batch["input_nodes"] = torch.zeros(batch_size, max_node_num, node_feat_size, dtype=torch.long)
102
+ batch["input_edges"] = torch.zeros(
103
+ batch_size, max_node_num, max_node_num, max_dist, edge_input_size, dtype=torch.long
104
+ )
105
+
106
+ for ix, f in enumerate(features):
107
+ for k in ["attn_bias", "attn_edge_type", "spatial_pos", "in_degree", "input_nodes", "input_edges"]:
108
+ f[k] = torch.tensor(f[k])
109
+
110
+ if len(f["attn_bias"][1:, 1:][f["spatial_pos"] >= self.spatial_pos_max]) > 0:
111
+ f["attn_bias"][1:, 1:][f["spatial_pos"] >= self.spatial_pos_max] = float("-inf")
112
+
113
+ batch["attn_bias"][ix, : f["attn_bias"].shape[0], : f["attn_bias"].shape[1]] = f["attn_bias"]
114
+ batch["attn_edge_type"][ix, : f["attn_edge_type"].shape[0], : f["attn_edge_type"].shape[1], :] = f[
115
+ "attn_edge_type"
116
+ ]
117
+ batch["spatial_pos"][ix, : f["spatial_pos"].shape[0], : f["spatial_pos"].shape[1]] = f["spatial_pos"]
118
+ batch["in_degree"][ix, : f["in_degree"].shape[0]] = f["in_degree"]
119
+ batch["input_nodes"][ix, : f["input_nodes"].shape[0], :] = f["input_nodes"]
120
+ batch["input_edges"][
121
+ ix, : f["input_edges"].shape[0], : f["input_edges"].shape[1], : f["input_edges"].shape[2], :
122
+ ] = f["input_edges"]
123
+
124
+ batch["out_degree"] = batch["in_degree"]
125
+
126
+ sample = features[0]["labels"]
127
+ if len(sample) == 1: # one task
128
+ if isinstance(sample[0], float): # regression
129
+ batch["labels"] = torch.from_numpy(np.concatenate([i["labels"] for i in features]))
130
+ else: # binary classification
131
+ batch["labels"] = torch.from_numpy(np.concatenate([i["labels"] for i in features]))
132
+ else: # multi task classification, left to float to keep the NaNs
133
+ batch["labels"] = torch.from_numpy(np.stack([i["labels"] for i in features], axis=0))
134
+
135
+ return batch
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/graphormer/configuration_graphormer.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Microsoft, clefourrier and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Graphormer model configuration"""
16
+
17
+ from typing import Optional
18
+
19
+ from ....configuration_utils import PretrainedConfig
20
+ from ....utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class GraphormerConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`~GraphormerModel`]. It is used to instantiate an
29
+ Graphormer model according to the specified arguments, defining the model architecture. Instantiating a
30
+ configuration with the defaults will yield a similar configuration to that of the Graphormer
31
+ [graphormer-base-pcqm4mv1](https://huggingface.co/graphormer-base-pcqm4mv1) architecture.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ num_classes (`int`, *optional*, defaults to 1):
39
+ Number of target classes or labels, set to n for binary classification of n tasks.
40
+ num_atoms (`int`, *optional*, defaults to 512*9):
41
+ Number of node types in the graphs.
42
+ num_edges (`int`, *optional*, defaults to 512*3):
43
+ Number of edges types in the graph.
44
+ num_in_degree (`int`, *optional*, defaults to 512):
45
+ Number of in degrees types in the input graphs.
46
+ num_out_degree (`int`, *optional*, defaults to 512):
47
+ Number of out degrees types in the input graphs.
48
+ num_edge_dis (`int`, *optional*, defaults to 128):
49
+ Number of edge dis in the input graphs.
50
+ multi_hop_max_dist (`int`, *optional*, defaults to 20):
51
+ Maximum distance of multi hop edges between two nodes.
52
+ spatial_pos_max (`int`, *optional*, defaults to 1024):
53
+ Maximum distance between nodes in the graph attention bias matrices, used during preprocessing and
54
+ collation.
55
+ edge_type (`str`, *optional*, defaults to multihop):
56
+ Type of edge relation chosen.
57
+ max_nodes (`int`, *optional*, defaults to 512):
58
+ Maximum number of nodes which can be parsed for the input graphs.
59
+ share_input_output_embed (`bool`, *optional*, defaults to `False`):
60
+ Shares the embedding layer between encoder and decoder - careful, True is not implemented.
61
+ num_layers (`int`, *optional*, defaults to 12):
62
+ Number of layers.
63
+ embedding_dim (`int`, *optional*, defaults to 768):
64
+ Dimension of the embedding layer in encoder.
65
+ ffn_embedding_dim (`int`, *optional*, defaults to 768):
66
+ Dimension of the "intermediate" (often named feed-forward) layer in encoder.
67
+ num_attention_heads (`int`, *optional*, defaults to 32):
68
+ Number of attention heads in the encoder.
69
+ self_attention (`bool`, *optional*, defaults to `True`):
70
+ Model is self attentive (False not implemented).
71
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
72
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
73
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
74
+ dropout (`float`, *optional*, defaults to 0.1):
75
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
76
+ attention_dropout (`float`, *optional*, defaults to 0.1):
77
+ The dropout probability for the attention weights.
78
+ activation_dropout (`float`, *optional*, defaults to 0.1):
79
+ The dropout probability for the activation of the linear transformer layer.
80
+ layerdrop (`float`, *optional*, defaults to 0.0):
81
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
82
+ for more details.
83
+ bias (`bool`, *optional*, defaults to `True`):
84
+ Uses bias in the attention module - unsupported at the moment.
85
+ embed_scale(`float`, *optional*, defaults to None):
86
+ Scaling factor for the node embeddings.
87
+ num_trans_layers_to_freeze (`int`, *optional*, defaults to 0):
88
+ Number of transformer layers to freeze.
89
+ encoder_normalize_before (`bool`, *optional*, defaults to `False`):
90
+ Normalize features before encoding the graph.
91
+ pre_layernorm (`bool`, *optional*, defaults to `False`):
92
+ Apply layernorm before self attention and the feed forward network. Without this, post layernorm will be
93
+ used.
94
+ apply_graphormer_init (`bool`, *optional*, defaults to `False`):
95
+ Apply a custom graphormer initialisation to the model before training.
96
+ freeze_embeddings (`bool`, *optional*, defaults to `False`):
97
+ Freeze the embedding layer, or train it along the model.
98
+ encoder_normalize_before (`bool`, *optional*, defaults to `False`):
99
+ Apply the layer norm before each encoder block.
100
+ q_noise (`float`, *optional*, defaults to 0.0):
101
+ Amount of quantization noise (see "Training with Quantization Noise for Extreme Model Compression"). (For
102
+ more detail, see fairseq's documentation on quant_noise).
103
+ qn_block_size (`int`, *optional*, defaults to 8):
104
+ Size of the blocks for subsequent quantization with iPQ (see q_noise).
105
+ kdim (`int`, *optional*, defaults to None):
106
+ Dimension of the key in the attention, if different from the other values.
107
+ vdim (`int`, *optional*, defaults to None):
108
+ Dimension of the value in the attention, if different from the other values.
109
+ use_cache (`bool`, *optional*, defaults to `True`):
110
+ Whether or not the model should return the last key/values attentions (not used by all models).
111
+ traceable (`bool`, *optional*, defaults to `False`):
112
+ Changes return value of the encoder's inner_state to stacked tensors.
113
+
114
+ Example:
115
+ ```python
116
+ >>> from transformers import GraphormerForGraphClassification, GraphormerConfig
117
+
118
+ >>> # Initializing a Graphormer graphormer-base-pcqm4mv2 style configuration
119
+ >>> configuration = GraphormerConfig()
120
+
121
+ >>> # Initializing a model from the graphormer-base-pcqm4mv1 style configuration
122
+ >>> model = GraphormerForGraphClassification(configuration)
123
+
124
+ >>> # Accessing the model configuration
125
+ >>> configuration = model.config
126
+ ```
127
+ """
128
+
129
+ model_type = "graphormer"
130
+ keys_to_ignore_at_inference = ["past_key_values"]
131
+
132
+ def __init__(
133
+ self,
134
+ num_classes: int = 1,
135
+ num_atoms: int = 512 * 9,
136
+ num_edges: int = 512 * 3,
137
+ num_in_degree: int = 512,
138
+ num_out_degree: int = 512,
139
+ num_spatial: int = 512,
140
+ num_edge_dis: int = 128,
141
+ multi_hop_max_dist: int = 5, # sometimes is 20
142
+ spatial_pos_max: int = 1024,
143
+ edge_type: str = "multi_hop",
144
+ max_nodes: int = 512,
145
+ share_input_output_embed: bool = False,
146
+ num_hidden_layers: int = 12,
147
+ embedding_dim: int = 768,
148
+ ffn_embedding_dim: int = 768,
149
+ num_attention_heads: int = 32,
150
+ dropout: float = 0.1,
151
+ attention_dropout: float = 0.1,
152
+ activation_dropout: float = 0.1,
153
+ layerdrop: float = 0.0,
154
+ encoder_normalize_before: bool = False,
155
+ pre_layernorm: bool = False,
156
+ apply_graphormer_init: bool = False,
157
+ activation_fn: str = "gelu",
158
+ embed_scale: Optional[float] = None,
159
+ freeze_embeddings: bool = False,
160
+ num_trans_layers_to_freeze: int = 0,
161
+ traceable: bool = False,
162
+ q_noise: float = 0.0,
163
+ qn_block_size: int = 8,
164
+ kdim: Optional[int] = None,
165
+ vdim: Optional[int] = None,
166
+ bias: bool = True,
167
+ self_attention: bool = True,
168
+ pad_token_id=0,
169
+ bos_token_id=1,
170
+ eos_token_id=2,
171
+ **kwargs,
172
+ ):
173
+ self.num_classes = num_classes
174
+ self.num_atoms = num_atoms
175
+ self.num_in_degree = num_in_degree
176
+ self.num_out_degree = num_out_degree
177
+ self.num_edges = num_edges
178
+ self.num_spatial = num_spatial
179
+ self.num_edge_dis = num_edge_dis
180
+ self.edge_type = edge_type
181
+ self.multi_hop_max_dist = multi_hop_max_dist
182
+ self.spatial_pos_max = spatial_pos_max
183
+ self.max_nodes = max_nodes
184
+ self.num_hidden_layers = num_hidden_layers
185
+ self.embedding_dim = embedding_dim
186
+ self.hidden_size = embedding_dim
187
+ self.ffn_embedding_dim = ffn_embedding_dim
188
+ self.num_attention_heads = num_attention_heads
189
+ self.dropout = dropout
190
+ self.attention_dropout = attention_dropout
191
+ self.activation_dropout = activation_dropout
192
+ self.layerdrop = layerdrop
193
+ self.encoder_normalize_before = encoder_normalize_before
194
+ self.pre_layernorm = pre_layernorm
195
+ self.apply_graphormer_init = apply_graphormer_init
196
+ self.activation_fn = activation_fn
197
+ self.embed_scale = embed_scale
198
+ self.freeze_embeddings = freeze_embeddings
199
+ self.num_trans_layers_to_freeze = num_trans_layers_to_freeze
200
+ self.share_input_output_embed = share_input_output_embed
201
+ self.traceable = traceable
202
+ self.q_noise = q_noise
203
+ self.qn_block_size = qn_block_size
204
+
205
+ # These parameters are here for future extensions
206
+ # atm, the model only supports self attention
207
+ self.kdim = kdim
208
+ self.vdim = vdim
209
+ self.self_attention = self_attention
210
+ self.bias = bias
211
+
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
+ **kwargs,
217
+ )
218
+
219
+
220
+ __all__ = ["GraphormerConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/graphormer/modeling_graphormer.py ADDED
@@ -0,0 +1,912 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Microsoft, clefourrier 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 Graphormer model."""
16
+
17
+ import math
18
+ from collections.abc import Iterable, Iterator
19
+ from typing import Optional, Union
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
24
+
25
+ from ....activations import ACT2FN
26
+ from ....modeling_outputs import (
27
+ BaseModelOutputWithNoAttention,
28
+ SequenceClassifierOutput,
29
+ )
30
+ from ....modeling_utils import PreTrainedModel
31
+ from ....utils import logging
32
+ from .configuration_graphormer import GraphormerConfig
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+ _CHECKPOINT_FOR_DOC = "graphormer-base-pcqm4mv1"
38
+ _CONFIG_FOR_DOC = "GraphormerConfig"
39
+
40
+
41
+ def quant_noise(module: nn.Module, p: float, block_size: int):
42
+ """
43
+ From:
44
+ https://github.com/facebookresearch/fairseq/blob/dd0079bde7f678b0cd0715cbd0ae68d661b7226d/fairseq/modules/quant_noise.py
45
+
46
+ Wraps modules and applies quantization noise to the weights for subsequent quantization with Iterative Product
47
+ Quantization as described in "Training with Quantization Noise for Extreme Model Compression"
48
+
49
+ Args:
50
+ - module: nn.Module
51
+ - p: amount of Quantization Noise
52
+ - block_size: size of the blocks for subsequent quantization with iPQ
53
+
54
+ Remarks:
55
+ - Module weights must have the right sizes wrt the block size
56
+ - Only Linear, Embedding and Conv2d modules are supported for the moment
57
+ - For more detail on how to quantize by blocks with convolutional weights, see "And the Bit Goes Down:
58
+ Revisiting the Quantization of Neural Networks"
59
+ - We implement the simplest form of noise here as stated in the paper which consists in randomly dropping
60
+ blocks
61
+ """
62
+
63
+ # if no quantization noise, don't register hook
64
+ if p <= 0:
65
+ return module
66
+
67
+ # supported modules
68
+ if not isinstance(module, (nn.Linear, nn.Embedding, nn.Conv2d)):
69
+ raise NotImplementedError("Module unsupported for quant_noise.")
70
+
71
+ # test whether module.weight has the right sizes wrt block_size
72
+ is_conv = module.weight.ndim == 4
73
+
74
+ # 2D matrix
75
+ if not is_conv:
76
+ if module.weight.size(1) % block_size != 0:
77
+ raise AssertionError("Input features must be a multiple of block sizes")
78
+
79
+ # 4D matrix
80
+ else:
81
+ # 1x1 convolutions
82
+ if module.kernel_size == (1, 1):
83
+ if module.in_channels % block_size != 0:
84
+ raise AssertionError("Input channels must be a multiple of block sizes")
85
+ # regular convolutions
86
+ else:
87
+ k = module.kernel_size[0] * module.kernel_size[1]
88
+ if k % block_size != 0:
89
+ raise AssertionError("Kernel size must be a multiple of block size")
90
+
91
+ def _forward_pre_hook(mod, input):
92
+ # no noise for evaluation
93
+ if mod.training:
94
+ if not is_conv:
95
+ # gather weight and sizes
96
+ weight = mod.weight
97
+ in_features = weight.size(1)
98
+ out_features = weight.size(0)
99
+
100
+ # split weight matrix into blocks and randomly drop selected blocks
101
+ mask = torch.zeros(in_features // block_size * out_features, device=weight.device)
102
+ mask.bernoulli_(p)
103
+ mask = mask.repeat_interleave(block_size, -1).view(-1, in_features)
104
+
105
+ else:
106
+ # gather weight and sizes
107
+ weight = mod.weight
108
+ in_channels = mod.in_channels
109
+ out_channels = mod.out_channels
110
+
111
+ # split weight matrix into blocks and randomly drop selected blocks
112
+ if mod.kernel_size == (1, 1):
113
+ mask = torch.zeros(
114
+ int(in_channels // block_size * out_channels),
115
+ device=weight.device,
116
+ )
117
+ mask.bernoulli_(p)
118
+ mask = mask.repeat_interleave(block_size, -1).view(-1, in_channels)
119
+ else:
120
+ mask = torch.zeros(weight.size(0), weight.size(1), device=weight.device)
121
+ mask.bernoulli_(p)
122
+ mask = mask.unsqueeze(2).unsqueeze(3).repeat(1, 1, mod.kernel_size[0], mod.kernel_size[1])
123
+
124
+ # scale weights and apply mask
125
+ mask = mask.to(torch.bool) # x.bool() is not currently supported in TorchScript
126
+ s = 1 / (1 - p)
127
+ mod.weight.data = s * weight.masked_fill(mask, 0)
128
+
129
+ module.register_forward_pre_hook(_forward_pre_hook)
130
+ return module
131
+
132
+
133
+ class LayerDropModuleList(nn.ModuleList):
134
+ """
135
+ From:
136
+ https://github.com/facebookresearch/fairseq/blob/dd0079bde7f678b0cd0715cbd0ae68d661b7226d/fairseq/modules/layer_drop.py
137
+ A LayerDrop implementation based on [`torch.nn.ModuleList`]. LayerDrop as described in
138
+ https://huggingface.co/papers/1909.11556.
139
+
140
+ We refresh the choice of which layers to drop every time we iterate over the LayerDropModuleList instance. During
141
+ evaluation we always iterate over all layers.
142
+
143
+ Usage:
144
+
145
+ ```python
146
+ layers = LayerDropList(p=0.5, modules=[layer1, layer2, layer3])
147
+ for layer in layers: # this might iterate over layers 1 and 3
148
+ x = layer(x)
149
+ for layer in layers: # this might iterate over all layers
150
+ x = layer(x)
151
+ for layer in layers: # this might not iterate over any layers
152
+ x = layer(x)
153
+ ```
154
+
155
+ Args:
156
+ p (float): probability of dropping out each layer
157
+ modules (iterable, optional): an iterable of modules to add
158
+ """
159
+
160
+ def __init__(self, p: float, modules: Optional[Iterable[nn.Module]] = None):
161
+ super().__init__(modules)
162
+ self.p = p
163
+
164
+ def __iter__(self) -> Iterator[nn.Module]:
165
+ dropout_probs = torch.empty(len(self)).uniform_()
166
+ for i, m in enumerate(super().__iter__()):
167
+ if not self.training or (dropout_probs[i] > self.p):
168
+ yield m
169
+
170
+
171
+ class GraphormerGraphNodeFeature(nn.Module):
172
+ """
173
+ Compute node features for each node in the graph.
174
+ """
175
+
176
+ def __init__(self, config: GraphormerConfig):
177
+ super().__init__()
178
+ self.num_heads = config.num_attention_heads
179
+ self.num_atoms = config.num_atoms
180
+
181
+ self.atom_encoder = nn.Embedding(config.num_atoms + 1, config.hidden_size, padding_idx=config.pad_token_id)
182
+ self.in_degree_encoder = nn.Embedding(
183
+ config.num_in_degree, config.hidden_size, padding_idx=config.pad_token_id
184
+ )
185
+ self.out_degree_encoder = nn.Embedding(
186
+ config.num_out_degree, config.hidden_size, padding_idx=config.pad_token_id
187
+ )
188
+
189
+ self.graph_token = nn.Embedding(1, config.hidden_size)
190
+
191
+ def forward(
192
+ self,
193
+ input_nodes: torch.LongTensor,
194
+ in_degree: torch.LongTensor,
195
+ out_degree: torch.LongTensor,
196
+ ) -> torch.Tensor:
197
+ n_graph, n_node = input_nodes.size()[:2]
198
+
199
+ node_feature = ( # node feature + graph token
200
+ self.atom_encoder(input_nodes).sum(dim=-2) # [n_graph, n_node, n_hidden]
201
+ + self.in_degree_encoder(in_degree)
202
+ + self.out_degree_encoder(out_degree)
203
+ )
204
+
205
+ graph_token_feature = self.graph_token.weight.unsqueeze(0).repeat(n_graph, 1, 1)
206
+
207
+ graph_node_feature = torch.cat([graph_token_feature, node_feature], dim=1)
208
+
209
+ return graph_node_feature
210
+
211
+
212
+ class GraphormerGraphAttnBias(nn.Module):
213
+ """
214
+ Compute attention bias for each head.
215
+ """
216
+
217
+ def __init__(self, config: GraphormerConfig):
218
+ super().__init__()
219
+ self.num_heads = config.num_attention_heads
220
+ self.multi_hop_max_dist = config.multi_hop_max_dist
221
+
222
+ # We do not change edge feature embedding learning, as edge embeddings are represented as a combination of the original features
223
+ # + shortest path
224
+ self.edge_encoder = nn.Embedding(config.num_edges + 1, config.num_attention_heads, padding_idx=0)
225
+
226
+ self.edge_type = config.edge_type
227
+ if self.edge_type == "multi_hop":
228
+ self.edge_dis_encoder = nn.Embedding(
229
+ config.num_edge_dis * config.num_attention_heads * config.num_attention_heads,
230
+ 1,
231
+ )
232
+
233
+ self.spatial_pos_encoder = nn.Embedding(config.num_spatial, config.num_attention_heads, padding_idx=0)
234
+
235
+ self.graph_token_virtual_distance = nn.Embedding(1, config.num_attention_heads)
236
+
237
+ def forward(
238
+ self,
239
+ input_nodes: torch.LongTensor,
240
+ attn_bias: torch.Tensor,
241
+ spatial_pos: torch.LongTensor,
242
+ input_edges: torch.LongTensor,
243
+ attn_edge_type: torch.LongTensor,
244
+ ) -> torch.Tensor:
245
+ n_graph, n_node = input_nodes.size()[:2]
246
+ graph_attn_bias = attn_bias.clone()
247
+ graph_attn_bias = graph_attn_bias.unsqueeze(1).repeat(
248
+ 1, self.num_heads, 1, 1
249
+ ) # [n_graph, n_head, n_node+1, n_node+1]
250
+
251
+ # spatial pos
252
+ # [n_graph, n_node, n_node, n_head] -> [n_graph, n_head, n_node, n_node]
253
+ spatial_pos_bias = self.spatial_pos_encoder(spatial_pos).permute(0, 3, 1, 2)
254
+ graph_attn_bias[:, :, 1:, 1:] = graph_attn_bias[:, :, 1:, 1:] + spatial_pos_bias
255
+
256
+ # reset spatial pos here
257
+ t = self.graph_token_virtual_distance.weight.view(1, self.num_heads, 1)
258
+ graph_attn_bias[:, :, 1:, 0] = graph_attn_bias[:, :, 1:, 0] + t
259
+ graph_attn_bias[:, :, 0, :] = graph_attn_bias[:, :, 0, :] + t
260
+
261
+ # edge feature
262
+ if self.edge_type == "multi_hop":
263
+ spatial_pos_ = spatial_pos.clone()
264
+
265
+ spatial_pos_[spatial_pos_ == 0] = 1 # set pad to 1
266
+ # set 1 to 1, input_nodes > 1 to input_nodes - 1
267
+ spatial_pos_ = torch.where(spatial_pos_ > 1, spatial_pos_ - 1, spatial_pos_)
268
+ if self.multi_hop_max_dist > 0:
269
+ spatial_pos_ = spatial_pos_.clamp(0, self.multi_hop_max_dist)
270
+ input_edges = input_edges[:, :, :, : self.multi_hop_max_dist, :]
271
+ # [n_graph, n_node, n_node, max_dist, n_head]
272
+
273
+ input_edges = self.edge_encoder(input_edges).mean(-2)
274
+ max_dist = input_edges.size(-2)
275
+ edge_input_flat = input_edges.permute(3, 0, 1, 2, 4).reshape(max_dist, -1, self.num_heads)
276
+ edge_input_flat = torch.bmm(
277
+ edge_input_flat,
278
+ self.edge_dis_encoder.weight.reshape(-1, self.num_heads, self.num_heads)[:max_dist, :, :],
279
+ )
280
+ input_edges = edge_input_flat.reshape(max_dist, n_graph, n_node, n_node, self.num_heads).permute(
281
+ 1, 2, 3, 0, 4
282
+ )
283
+ input_edges = (input_edges.sum(-2) / (spatial_pos_.float().unsqueeze(-1))).permute(0, 3, 1, 2)
284
+ else:
285
+ # [n_graph, n_node, n_node, n_head] -> [n_graph, n_head, n_node, n_node]
286
+ input_edges = self.edge_encoder(attn_edge_type).mean(-2).permute(0, 3, 1, 2)
287
+
288
+ graph_attn_bias[:, :, 1:, 1:] = graph_attn_bias[:, :, 1:, 1:] + input_edges
289
+ graph_attn_bias = graph_attn_bias + attn_bias.unsqueeze(1) # reset
290
+
291
+ return graph_attn_bias
292
+
293
+
294
+ class GraphormerMultiheadAttention(nn.Module):
295
+ """Multi-headed attention.
296
+
297
+ See "Attention Is All You Need" for more details.
298
+ """
299
+
300
+ def __init__(self, config: GraphormerConfig):
301
+ super().__init__()
302
+ self.embedding_dim = config.embedding_dim
303
+ self.kdim = config.kdim if config.kdim is not None else config.embedding_dim
304
+ self.vdim = config.vdim if config.vdim is not None else config.embedding_dim
305
+ self.qkv_same_dim = self.kdim == config.embedding_dim and self.vdim == config.embedding_dim
306
+
307
+ self.num_heads = config.num_attention_heads
308
+ self.attention_dropout_module = torch.nn.Dropout(p=config.attention_dropout, inplace=False)
309
+
310
+ self.head_dim = config.embedding_dim // config.num_attention_heads
311
+ if not (self.head_dim * config.num_attention_heads == self.embedding_dim):
312
+ raise AssertionError("The embedding_dim must be divisible by num_heads.")
313
+ self.scaling = self.head_dim**-0.5
314
+
315
+ self.self_attention = True # config.self_attention
316
+ if not (self.self_attention):
317
+ raise NotImplementedError("The Graphormer model only supports self attention for now.")
318
+ if self.self_attention and not self.qkv_same_dim:
319
+ raise AssertionError("Self-attention requires query, key and value to be of the same size.")
320
+
321
+ self.k_proj = quant_noise(
322
+ nn.Linear(self.kdim, config.embedding_dim, bias=config.bias),
323
+ config.q_noise,
324
+ config.qn_block_size,
325
+ )
326
+ self.v_proj = quant_noise(
327
+ nn.Linear(self.vdim, config.embedding_dim, bias=config.bias),
328
+ config.q_noise,
329
+ config.qn_block_size,
330
+ )
331
+ self.q_proj = quant_noise(
332
+ nn.Linear(config.embedding_dim, config.embedding_dim, bias=config.bias),
333
+ config.q_noise,
334
+ config.qn_block_size,
335
+ )
336
+
337
+ self.out_proj = quant_noise(
338
+ nn.Linear(config.embedding_dim, config.embedding_dim, bias=config.bias),
339
+ config.q_noise,
340
+ config.qn_block_size,
341
+ )
342
+
343
+ self.onnx_trace = False
344
+
345
+ def reset_parameters(self):
346
+ if self.qkv_same_dim:
347
+ # Empirically observed the convergence to be much better with
348
+ # the scaled initialization
349
+ nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2))
350
+ nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2))
351
+ nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2))
352
+ else:
353
+ nn.init.xavier_uniform_(self.k_proj.weight)
354
+ nn.init.xavier_uniform_(self.v_proj.weight)
355
+ nn.init.xavier_uniform_(self.q_proj.weight)
356
+
357
+ nn.init.xavier_uniform_(self.out_proj.weight)
358
+ if self.out_proj.bias is not None:
359
+ nn.init.constant_(self.out_proj.bias, 0.0)
360
+
361
+ def forward(
362
+ self,
363
+ query: torch.LongTensor,
364
+ key: Optional[torch.Tensor],
365
+ value: Optional[torch.Tensor],
366
+ attn_bias: Optional[torch.Tensor],
367
+ key_padding_mask: Optional[torch.Tensor] = None,
368
+ need_weights: bool = True,
369
+ attn_mask: Optional[torch.Tensor] = None,
370
+ before_softmax: bool = False,
371
+ need_head_weights: bool = False,
372
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
373
+ """
374
+ Args:
375
+ key_padding_mask (Bytetorch.Tensor, optional): mask to exclude
376
+ keys that are pads, of shape `(batch, src_len)`, where padding elements are indicated by 1s.
377
+ need_weights (bool, optional): return the attention weights,
378
+ averaged over heads (default: False).
379
+ attn_mask (Bytetorch.Tensor, optional): typically used to
380
+ implement causal attention, where the mask prevents the attention from looking forward in time
381
+ (default: None).
382
+ before_softmax (bool, optional): return the raw attention
383
+ weights and values before the attention softmax.
384
+ need_head_weights (bool, optional): return the attention
385
+ weights for each head. Implies *need_weights*. Default: return the average attention weights over all
386
+ heads.
387
+ """
388
+ if need_head_weights:
389
+ need_weights = True
390
+
391
+ tgt_len, bsz, embedding_dim = query.size()
392
+ src_len = tgt_len
393
+ if not (embedding_dim == self.embedding_dim):
394
+ raise AssertionError(
395
+ f"The query embedding dimension {embedding_dim} is not equal to the expected embedding_dim"
396
+ f" {self.embedding_dim}."
397
+ )
398
+ if not (list(query.size()) == [tgt_len, bsz, embedding_dim]):
399
+ raise AssertionError("Query size incorrect in Graphormer, compared to model dimensions.")
400
+
401
+ if key is not None:
402
+ src_len, key_bsz, _ = key.size()
403
+ if not torch.jit.is_scripting():
404
+ if (key_bsz != bsz) or (value is None) or not (src_len, bsz == value.shape[:2]):
405
+ raise AssertionError(
406
+ "The batch shape does not match the key or value shapes provided to the attention."
407
+ )
408
+
409
+ q = self.q_proj(query)
410
+ k = self.k_proj(query)
411
+ v = self.v_proj(query)
412
+
413
+ q *= self.scaling
414
+
415
+ q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1)
416
+ if k is not None:
417
+ k = k.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1)
418
+ if v is not None:
419
+ v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1)
420
+
421
+ if (k is None) or not (k.size(1) == src_len):
422
+ raise AssertionError("The shape of the key generated in the attention is incorrect")
423
+
424
+ # This is part of a workaround to get around fork/join parallelism
425
+ # not supporting Optional types.
426
+ if key_padding_mask is not None and key_padding_mask.dim() == 0:
427
+ key_padding_mask = None
428
+
429
+ if key_padding_mask is not None:
430
+ if key_padding_mask.size(0) != bsz or key_padding_mask.size(1) != src_len:
431
+ raise AssertionError(
432
+ "The shape of the generated padding mask for the key does not match expected dimensions."
433
+ )
434
+ attn_weights = torch.bmm(q, k.transpose(1, 2))
435
+ attn_weights = self.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz)
436
+
437
+ if list(attn_weights.size()) != [bsz * self.num_heads, tgt_len, src_len]:
438
+ raise AssertionError("The attention weights generated do not match the expected dimensions.")
439
+
440
+ if attn_bias is not None:
441
+ attn_weights += attn_bias.view(bsz * self.num_heads, tgt_len, src_len)
442
+
443
+ if attn_mask is not None:
444
+ attn_mask = attn_mask.unsqueeze(0)
445
+ attn_weights += attn_mask
446
+
447
+ if key_padding_mask is not None:
448
+ # don't attend to padding symbols
449
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
450
+ attn_weights = attn_weights.masked_fill(
451
+ key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool), float("-inf")
452
+ )
453
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
454
+
455
+ if before_softmax:
456
+ return attn_weights, v
457
+
458
+ attn_weights_float = torch.nn.functional.softmax(attn_weights, dim=-1)
459
+ attn_weights = attn_weights_float.type_as(attn_weights)
460
+ attn_probs = self.attention_dropout_module(attn_weights)
461
+
462
+ if v is None:
463
+ raise AssertionError("No value generated")
464
+ attn = torch.bmm(attn_probs, v)
465
+ if list(attn.size()) != [bsz * self.num_heads, tgt_len, self.head_dim]:
466
+ raise AssertionError("The attention generated do not match the expected dimensions.")
467
+
468
+ attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embedding_dim)
469
+ attn: torch.Tensor = self.out_proj(attn)
470
+
471
+ attn_weights = None
472
+ if need_weights:
473
+ attn_weights = attn_weights_float.contiguous().view(bsz, self.num_heads, tgt_len, src_len).transpose(1, 0)
474
+ if not need_head_weights:
475
+ # average attention weights over heads
476
+ attn_weights = attn_weights.mean(dim=0)
477
+
478
+ return attn, attn_weights
479
+
480
+ def apply_sparse_mask(self, attn_weights: torch.Tensor, tgt_len: int, src_len: int, bsz: int) -> torch.Tensor:
481
+ return attn_weights
482
+
483
+
484
+ class GraphormerGraphEncoderLayer(nn.Module):
485
+ def __init__(self, config: GraphormerConfig) -> None:
486
+ super().__init__()
487
+
488
+ # Initialize parameters
489
+ self.embedding_dim = config.embedding_dim
490
+ self.num_attention_heads = config.num_attention_heads
491
+ self.q_noise = config.q_noise
492
+ self.qn_block_size = config.qn_block_size
493
+ self.pre_layernorm = config.pre_layernorm
494
+
495
+ self.dropout_module = torch.nn.Dropout(p=config.dropout, inplace=False)
496
+
497
+ self.activation_dropout_module = torch.nn.Dropout(p=config.activation_dropout, inplace=False)
498
+
499
+ # Initialize blocks
500
+ self.activation_fn = ACT2FN[config.activation_fn]
501
+ self.self_attn = GraphormerMultiheadAttention(config)
502
+
503
+ # layer norm associated with the self attention layer
504
+ self.self_attn_layer_norm = nn.LayerNorm(self.embedding_dim)
505
+
506
+ self.fc1 = self.build_fc(
507
+ self.embedding_dim,
508
+ config.ffn_embedding_dim,
509
+ q_noise=config.q_noise,
510
+ qn_block_size=config.qn_block_size,
511
+ )
512
+ self.fc2 = self.build_fc(
513
+ config.ffn_embedding_dim,
514
+ self.embedding_dim,
515
+ q_noise=config.q_noise,
516
+ qn_block_size=config.qn_block_size,
517
+ )
518
+
519
+ # layer norm associated with the position wise feed-forward NN
520
+ self.final_layer_norm = nn.LayerNorm(self.embedding_dim)
521
+
522
+ def build_fc(
523
+ self, input_dim: int, output_dim: int, q_noise: float, qn_block_size: int
524
+ ) -> Union[nn.Module, nn.Linear, nn.Embedding, nn.Conv2d]:
525
+ return quant_noise(nn.Linear(input_dim, output_dim), q_noise, qn_block_size)
526
+
527
+ def forward(
528
+ self,
529
+ input_nodes: torch.Tensor,
530
+ self_attn_bias: Optional[torch.Tensor] = None,
531
+ self_attn_mask: Optional[torch.Tensor] = None,
532
+ self_attn_padding_mask: Optional[torch.Tensor] = None,
533
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
534
+ """
535
+ nn.LayerNorm is applied either before or after the self-attention/ffn modules similar to the original
536
+ Transformer implementation.
537
+ """
538
+ residual = input_nodes
539
+ if self.pre_layernorm:
540
+ input_nodes = self.self_attn_layer_norm(input_nodes)
541
+
542
+ input_nodes, attn = self.self_attn(
543
+ query=input_nodes,
544
+ key=input_nodes,
545
+ value=input_nodes,
546
+ attn_bias=self_attn_bias,
547
+ key_padding_mask=self_attn_padding_mask,
548
+ need_weights=False,
549
+ attn_mask=self_attn_mask,
550
+ )
551
+ input_nodes = self.dropout_module(input_nodes)
552
+ input_nodes = residual + input_nodes
553
+ if not self.pre_layernorm:
554
+ input_nodes = self.self_attn_layer_norm(input_nodes)
555
+
556
+ residual = input_nodes
557
+ if self.pre_layernorm:
558
+ input_nodes = self.final_layer_norm(input_nodes)
559
+ input_nodes = self.activation_fn(self.fc1(input_nodes))
560
+ input_nodes = self.activation_dropout_module(input_nodes)
561
+ input_nodes = self.fc2(input_nodes)
562
+ input_nodes = self.dropout_module(input_nodes)
563
+ input_nodes = residual + input_nodes
564
+ if not self.pre_layernorm:
565
+ input_nodes = self.final_layer_norm(input_nodes)
566
+
567
+ return input_nodes, attn
568
+
569
+
570
+ class GraphormerGraphEncoder(nn.Module):
571
+ def __init__(self, config: GraphormerConfig):
572
+ super().__init__()
573
+
574
+ self.dropout_module = torch.nn.Dropout(p=config.dropout, inplace=False)
575
+ self.layerdrop = config.layerdrop
576
+ self.embedding_dim = config.embedding_dim
577
+ self.apply_graphormer_init = config.apply_graphormer_init
578
+ self.traceable = config.traceable
579
+
580
+ self.graph_node_feature = GraphormerGraphNodeFeature(config)
581
+ self.graph_attn_bias = GraphormerGraphAttnBias(config)
582
+
583
+ self.embed_scale = config.embed_scale
584
+
585
+ if config.q_noise > 0:
586
+ self.quant_noise = quant_noise(
587
+ nn.Linear(self.embedding_dim, self.embedding_dim, bias=False),
588
+ config.q_noise,
589
+ config.qn_block_size,
590
+ )
591
+ else:
592
+ self.quant_noise = None
593
+
594
+ if config.encoder_normalize_before:
595
+ self.emb_layer_norm = nn.LayerNorm(self.embedding_dim)
596
+ else:
597
+ self.emb_layer_norm = None
598
+
599
+ if config.pre_layernorm:
600
+ self.final_layer_norm = nn.LayerNorm(self.embedding_dim)
601
+
602
+ if self.layerdrop > 0.0:
603
+ self.layers = LayerDropModuleList(p=self.layerdrop)
604
+ else:
605
+ self.layers = nn.ModuleList([])
606
+ self.layers.extend([GraphormerGraphEncoderLayer(config) for _ in range(config.num_hidden_layers)])
607
+
608
+ # Apply initialization of model params after building the model
609
+ if config.freeze_embeddings:
610
+ raise NotImplementedError("Freezing embeddings is not implemented yet.")
611
+
612
+ for layer in range(config.num_trans_layers_to_freeze):
613
+ m = self.layers[layer]
614
+ if m is not None:
615
+ for p in m.parameters():
616
+ p.requires_grad = False
617
+
618
+ def forward(
619
+ self,
620
+ input_nodes: torch.LongTensor,
621
+ input_edges: torch.LongTensor,
622
+ attn_bias: torch.Tensor,
623
+ in_degree: torch.LongTensor,
624
+ out_degree: torch.LongTensor,
625
+ spatial_pos: torch.LongTensor,
626
+ attn_edge_type: torch.LongTensor,
627
+ perturb=None,
628
+ last_state_only: bool = False,
629
+ token_embeddings: Optional[torch.Tensor] = None,
630
+ attn_mask: Optional[torch.Tensor] = None,
631
+ ) -> tuple[Union[torch.Tensor, list[torch.LongTensor]], torch.Tensor]:
632
+ # compute padding mask. This is needed for multi-head attention
633
+ data_x = input_nodes
634
+ n_graph, n_node = data_x.size()[:2]
635
+ padding_mask = (data_x[:, :, 0]).eq(0)
636
+ padding_mask_cls = torch.zeros(n_graph, 1, device=padding_mask.device, dtype=padding_mask.dtype)
637
+ padding_mask = torch.cat((padding_mask_cls, padding_mask), dim=1)
638
+
639
+ attn_bias = self.graph_attn_bias(input_nodes, attn_bias, spatial_pos, input_edges, attn_edge_type)
640
+
641
+ if token_embeddings is not None:
642
+ input_nodes = token_embeddings
643
+ else:
644
+ input_nodes = self.graph_node_feature(input_nodes, in_degree, out_degree)
645
+
646
+ if perturb is not None:
647
+ input_nodes[:, 1:, :] += perturb
648
+
649
+ if self.embed_scale is not None:
650
+ input_nodes = input_nodes * self.embed_scale
651
+
652
+ if self.quant_noise is not None:
653
+ input_nodes = self.quant_noise(input_nodes)
654
+
655
+ if self.emb_layer_norm is not None:
656
+ input_nodes = self.emb_layer_norm(input_nodes)
657
+
658
+ input_nodes = self.dropout_module(input_nodes)
659
+
660
+ input_nodes = input_nodes.transpose(0, 1)
661
+
662
+ inner_states = []
663
+ if not last_state_only:
664
+ inner_states.append(input_nodes)
665
+
666
+ for layer in self.layers:
667
+ input_nodes, _ = layer(
668
+ input_nodes,
669
+ self_attn_padding_mask=padding_mask,
670
+ self_attn_mask=attn_mask,
671
+ self_attn_bias=attn_bias,
672
+ )
673
+ if not last_state_only:
674
+ inner_states.append(input_nodes)
675
+
676
+ graph_rep = input_nodes[0, :, :]
677
+
678
+ if last_state_only:
679
+ inner_states = [input_nodes]
680
+
681
+ if self.traceable:
682
+ return torch.stack(inner_states), graph_rep
683
+ else:
684
+ return inner_states, graph_rep
685
+
686
+
687
+ class GraphormerDecoderHead(nn.Module):
688
+ def __init__(self, embedding_dim: int, num_classes: int):
689
+ super().__init__()
690
+ """num_classes should be 1 for regression, or the number of classes for classification"""
691
+ self.lm_output_learned_bias = nn.Parameter(torch.zeros(1))
692
+ self.classifier = nn.Linear(embedding_dim, num_classes, bias=False)
693
+ self.num_classes = num_classes
694
+
695
+ def forward(self, input_nodes: torch.Tensor, **unused) -> torch.Tensor:
696
+ input_nodes = self.classifier(input_nodes)
697
+ input_nodes = input_nodes + self.lm_output_learned_bias
698
+ return input_nodes
699
+
700
+
701
+ class GraphormerPreTrainedModel(PreTrainedModel):
702
+ """
703
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
704
+ models.
705
+ """
706
+
707
+ config: GraphormerConfig
708
+ base_model_prefix = "graphormer"
709
+ main_input_name_nodes = "input_nodes"
710
+ main_input_name_edges = "input_edges"
711
+
712
+ def normal_(self, data: torch.Tensor):
713
+ # with FSDP, module params will be on CUDA, so we cast them back to CPU
714
+ # so that the RNG is consistent with and without FSDP
715
+ data.copy_(data.cpu().normal_(mean=0.0, std=0.02).to(data.device))
716
+
717
+ def init_graphormer_params(self, module: Union[nn.Linear, nn.Embedding, GraphormerMultiheadAttention]):
718
+ """
719
+ Initialize the weights specific to the Graphormer Model.
720
+ """
721
+ if isinstance(module, nn.Linear):
722
+ self.normal_(module.weight.data)
723
+ if module.bias is not None:
724
+ module.bias.data.zero_()
725
+ if isinstance(module, nn.Embedding):
726
+ self.normal_(module.weight.data)
727
+ if module.padding_idx is not None:
728
+ module.weight.data[module.padding_idx].zero_()
729
+ if isinstance(module, GraphormerMultiheadAttention):
730
+ self.normal_(module.q_proj.weight.data)
731
+ self.normal_(module.k_proj.weight.data)
732
+ self.normal_(module.v_proj.weight.data)
733
+
734
+ def _init_weights(
735
+ self,
736
+ module: Union[
737
+ nn.Linear, nn.Conv2d, nn.Embedding, nn.LayerNorm, GraphormerMultiheadAttention, GraphormerGraphEncoder
738
+ ],
739
+ ):
740
+ """
741
+ Initialize the weights
742
+ """
743
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
744
+ # We might be missing part of the Linear init, dependent on the layer num
745
+ module.weight.data.normal_(mean=0.0, std=0.02)
746
+ if module.bias is not None:
747
+ module.bias.data.zero_()
748
+ elif isinstance(module, nn.Embedding):
749
+ module.weight.data.normal_(mean=0.0, std=0.02)
750
+ if module.padding_idx is not None:
751
+ module.weight.data[module.padding_idx].zero_()
752
+ elif isinstance(module, GraphormerMultiheadAttention):
753
+ module.q_proj.weight.data.normal_(mean=0.0, std=0.02)
754
+ module.k_proj.weight.data.normal_(mean=0.0, std=0.02)
755
+ module.v_proj.weight.data.normal_(mean=0.0, std=0.02)
756
+ module.reset_parameters()
757
+ elif isinstance(module, nn.LayerNorm):
758
+ module.bias.data.zero_()
759
+ module.weight.data.fill_(1.0)
760
+ elif isinstance(module, GraphormerGraphEncoder):
761
+ if module.apply_graphormer_init:
762
+ module.apply(self.init_graphormer_params)
763
+
764
+ elif isinstance(module, nn.LayerNorm):
765
+ module.bias.data.zero_()
766
+ module.weight.data.fill_(1.0)
767
+
768
+
769
+ class GraphormerModel(GraphormerPreTrainedModel):
770
+ """The Graphormer model is a graph-encoder model.
771
+
772
+ It goes from a graph to its representation. If you want to use the model for a downstream classification task, use
773
+ GraphormerForGraphClassification instead. For any other downstream task, feel free to add a new class, or combine
774
+ this model with a downstream model of your choice, following the example in GraphormerForGraphClassification.
775
+ """
776
+
777
+ def __init__(self, config: GraphormerConfig):
778
+ super().__init__(config)
779
+ self.max_nodes = config.max_nodes
780
+
781
+ self.graph_encoder = GraphormerGraphEncoder(config)
782
+
783
+ self.share_input_output_embed = config.share_input_output_embed
784
+ self.lm_output_learned_bias = None
785
+
786
+ # Remove head is set to true during fine-tuning
787
+ self.load_softmax = not getattr(config, "remove_head", False)
788
+
789
+ self.lm_head_transform_weight = nn.Linear(config.embedding_dim, config.embedding_dim)
790
+ self.activation_fn = ACT2FN[config.activation_fn]
791
+ self.layer_norm = nn.LayerNorm(config.embedding_dim)
792
+
793
+ self.post_init()
794
+
795
+ def reset_output_layer_parameters(self):
796
+ self.lm_output_learned_bias = nn.Parameter(torch.zeros(1))
797
+
798
+ def forward(
799
+ self,
800
+ input_nodes: torch.LongTensor,
801
+ input_edges: torch.LongTensor,
802
+ attn_bias: torch.Tensor,
803
+ in_degree: torch.LongTensor,
804
+ out_degree: torch.LongTensor,
805
+ spatial_pos: torch.LongTensor,
806
+ attn_edge_type: torch.LongTensor,
807
+ perturb: Optional[torch.FloatTensor] = None,
808
+ masked_tokens: None = None,
809
+ return_dict: Optional[bool] = None,
810
+ **unused,
811
+ ) -> Union[tuple[torch.LongTensor], BaseModelOutputWithNoAttention]:
812
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
813
+
814
+ inner_states, graph_rep = self.graph_encoder(
815
+ input_nodes, input_edges, attn_bias, in_degree, out_degree, spatial_pos, attn_edge_type, perturb=perturb
816
+ )
817
+
818
+ # last inner state, then revert Batch and Graph len
819
+ input_nodes = inner_states[-1].transpose(0, 1)
820
+
821
+ # project masked tokens only
822
+ if masked_tokens is not None:
823
+ raise NotImplementedError
824
+
825
+ input_nodes = self.layer_norm(self.activation_fn(self.lm_head_transform_weight(input_nodes)))
826
+
827
+ # project back to size of vocabulary
828
+ if self.share_input_output_embed and hasattr(self.graph_encoder.embed_tokens, "weight"):
829
+ input_nodes = torch.nn.functional.linear(input_nodes, self.graph_encoder.embed_tokens.weight)
830
+
831
+ if not return_dict:
832
+ return tuple(x for x in [input_nodes, inner_states] if x is not None)
833
+ return BaseModelOutputWithNoAttention(last_hidden_state=input_nodes, hidden_states=inner_states)
834
+
835
+ def max_nodes(self):
836
+ """Maximum output length supported by the encoder."""
837
+ return self.max_nodes
838
+
839
+
840
+ class GraphormerForGraphClassification(GraphormerPreTrainedModel):
841
+ """
842
+ This model can be used for graph-level classification or regression tasks.
843
+
844
+ It can be trained on
845
+ - regression (by setting config.num_classes to 1); there should be one float-type label per graph
846
+ - one task classification (by setting config.num_classes to the number of classes); there should be one integer
847
+ label per graph
848
+ - binary multi-task classification (by setting config.num_classes to the number of labels); there should be a list
849
+ of integer labels for each graph.
850
+ """
851
+
852
+ def __init__(self, config: GraphormerConfig):
853
+ super().__init__(config)
854
+ self.encoder = GraphormerModel(config)
855
+ self.embedding_dim = config.embedding_dim
856
+ self.num_classes = config.num_classes
857
+ self.classifier = GraphormerDecoderHead(self.embedding_dim, self.num_classes)
858
+ self.is_encoder_decoder = True
859
+
860
+ # Initialize weights and apply final processing
861
+ self.post_init()
862
+
863
+ def forward(
864
+ self,
865
+ input_nodes: torch.LongTensor,
866
+ input_edges: torch.LongTensor,
867
+ attn_bias: torch.Tensor,
868
+ in_degree: torch.LongTensor,
869
+ out_degree: torch.LongTensor,
870
+ spatial_pos: torch.LongTensor,
871
+ attn_edge_type: torch.LongTensor,
872
+ labels: Optional[torch.LongTensor] = None,
873
+ return_dict: Optional[bool] = None,
874
+ **unused,
875
+ ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
876
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
877
+
878
+ encoder_outputs = self.encoder(
879
+ input_nodes,
880
+ input_edges,
881
+ attn_bias,
882
+ in_degree,
883
+ out_degree,
884
+ spatial_pos,
885
+ attn_edge_type,
886
+ return_dict=True,
887
+ )
888
+ outputs, hidden_states = encoder_outputs["last_hidden_state"], encoder_outputs["hidden_states"]
889
+
890
+ head_outputs = self.classifier(outputs)
891
+ logits = head_outputs[:, 0, :].contiguous()
892
+
893
+ loss = None
894
+ if labels is not None:
895
+ mask = ~torch.isnan(labels)
896
+
897
+ if self.num_classes == 1: # regression
898
+ loss_fct = MSELoss()
899
+ loss = loss_fct(logits[mask].squeeze(), labels[mask].squeeze().float())
900
+ elif self.num_classes > 1 and len(labels.shape) == 1: # One task classification
901
+ loss_fct = CrossEntropyLoss()
902
+ loss = loss_fct(logits[mask].view(-1, self.num_classes), labels[mask].view(-1))
903
+ else: # Binary multi-task classification
904
+ loss_fct = BCEWithLogitsLoss(reduction="sum")
905
+ loss = loss_fct(logits[mask], labels[mask])
906
+
907
+ if not return_dict:
908
+ return tuple(x for x in [loss, logits, hidden_states] if x is not None)
909
+ return SequenceClassifierOutput(loss=loss, logits=logits, hidden_states=hidden_states, attentions=None)
910
+
911
+
912
+ __all__ = ["GraphormerForGraphClassification", "GraphormerModel", "GraphormerPreTrainedModel"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mctct/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ....utils import _LazyModule
17
+ from ....utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_mctct import *
22
+ from .feature_extraction_mctct import *
23
+ from .modeling_mctct import *
24
+ from .processing_mctct import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mctct/configuration_mctct.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """M-CTC-T model configuration"""
16
+
17
+ from ....configuration_utils import PretrainedConfig
18
+ from ....utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class MCTCTConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`MCTCTModel`]. It is used to instantiate an
27
+ M-CTC-T model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the M-CTC-T
29
+ [speechbrain/m-ctc-t-large](https://huggingface.co/speechbrain/m-ctc-t-large) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 8065):
37
+ Vocabulary size of the M-CTC-T model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`MCTCTModel`].
39
+ hidden_size (`int`, *optional*, defaults to 1536):
40
+ Dimension of the encoder layers and the pooler layer.
41
+ num_hidden_layers (`int`, *optional*, defaults to 36):
42
+ Number of hidden layers in the Transformer encoder.
43
+ intermediate_size (`int`, *optional*, defaults to 6144):
44
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 4):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ attention_head_dim (`int`, *optional*, defaults to 384):
48
+ Dimensions of each attention head for each attention layer in the Transformer encoder.
49
+ max_position_embeddings (`int`, *optional*, defaults to 920):
50
+ The maximum sequence length that this model might ever be used with (after log-mel spectrogram extraction).
51
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
52
+ The epsilon used by the layer normalization layers.
53
+ layerdrop (`float`, *optional*, defaults to 0.3):
54
+ The probability of dropping an encoder layer during training. The default 0.3 value is used in the original
55
+ implementation.
56
+ hidden_act (`str` or `function`, *optional*, defaults to `"relu"`):
57
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
58
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.3):
62
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
63
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.3):
64
+ The dropout ratio for the attention probabilities.
65
+ pad_token_id (`int`, *optional*, defaults to 1):
66
+ The tokenizer index of the pad token.
67
+ bos_token_id (`int`, *optional*, defaults to 0):
68
+ The tokenizer index of the bos token.
69
+ eos_token_id (`int`, *optional*, defaults to 2):
70
+ The tokenizer index of the eos token.
71
+ conv_glu_dim (`int`, *optional*, defaults to 1):
72
+ The dimension of the output of the `Conv1dSubsampler` layer in which GLU is applied on. Though the original
73
+ Flashlight code uses the value of 2, here it's adapted to 1 due to transposition differences.
74
+ conv_dropout (`int`, *optional*, defaults to 0.3):
75
+ The probability of randomly dropping the `Conv1dSubsampler` layer during training.
76
+ num_conv_layers (`int`, *optional*, defaults to 1):
77
+ Number of convolution layers before applying transformer encoder layers.
78
+ conv_kernel (`Sequence[int]`, *optional*, defaults to `(7,)`):
79
+ The kernel size of the 1D convolution applied before transformer layers. `len(conv_kernel)` must be equal
80
+ to `num_conv_layers`.
81
+ conv_stride (`Sequence[int]`, *optional*, defaults to `(3,)`):
82
+ The stride length of the 1D convolution applied before transformer layers. `len(conv_stride)` must be equal
83
+ to `num_conv_layers`.
84
+ input_feat_per_channel (`int`, *optional*, defaults to 80):
85
+ Feature dimensions of the channels of the input to the Conv1D layer.
86
+ input_channels (`int`, *optional*, defaults to 1):
87
+ Number of input channels of the input to the Conv1D layer.
88
+ conv_channels (`list[int]`, *optional*):
89
+ Channel sizes of intermediate Conv1D layers.
90
+ ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`):
91
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
92
+ instance of [`MCTCTForCTC`].
93
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
94
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
95
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
96
+ of [`MCTCTForCTC`].
97
+
98
+ Example:
99
+
100
+ ```python
101
+ >>> from transformers import MCTCTConfig, MCTCTModel
102
+
103
+ >>> # Initializing a M-CTC-T mctct-large style configuration
104
+ >>> configuration = MCTCTConfig()
105
+
106
+ >>> # Initializing a model (with random weights) from the mctct-large style configuration
107
+ >>> model = MCTCTModel(configuration)
108
+
109
+ >>> # Accessing the model configuration
110
+ >>> configuration = model.config
111
+ ```"""
112
+
113
+ model_type = "mctct"
114
+
115
+ def __init__(
116
+ self,
117
+ vocab_size=8065,
118
+ hidden_size=1536,
119
+ num_hidden_layers=36,
120
+ intermediate_size=6144,
121
+ num_attention_heads=4,
122
+ attention_head_dim=384,
123
+ max_position_embeddings=920,
124
+ layer_norm_eps=1e-5,
125
+ layerdrop=0.3,
126
+ hidden_act="relu",
127
+ initializer_range=0.02,
128
+ hidden_dropout_prob=0.3,
129
+ attention_probs_dropout_prob=0.3,
130
+ pad_token_id=1,
131
+ bos_token_id=0,
132
+ eos_token_id=2,
133
+ conv_glu_dim=1,
134
+ conv_dropout=0.3,
135
+ num_conv_layers=1,
136
+ conv_kernel=(7,),
137
+ conv_stride=(3,),
138
+ input_feat_per_channel=80,
139
+ input_channels=1,
140
+ conv_channels=None,
141
+ ctc_loss_reduction="sum",
142
+ ctc_zero_infinity=False,
143
+ **kwargs,
144
+ ):
145
+ super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
146
+ self.vocab_size = vocab_size
147
+ self.hidden_size = hidden_size
148
+ self.num_hidden_layers = num_hidden_layers
149
+ self.intermediate_size = intermediate_size
150
+ self.num_attention_heads = num_attention_heads
151
+ self.attention_head_dim = attention_head_dim
152
+ self.max_position_embeddings = max_position_embeddings
153
+ self.layer_norm_eps = layer_norm_eps
154
+ self.layerdrop = layerdrop
155
+ self.hidden_act = hidden_act
156
+ self.initializer_range = initializer_range
157
+ self.hidden_dropout_prob = hidden_dropout_prob
158
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
159
+ self.pad_token_id = pad_token_id
160
+ self.bos_token_id = bos_token_id
161
+ self.eos_token_id = eos_token_id
162
+ self.conv_glu_dim = conv_glu_dim
163
+ self.conv_dropout = conv_dropout
164
+ self.num_conv_layers = num_conv_layers
165
+ self.input_feat_per_channel = input_feat_per_channel
166
+ self.input_channels = input_channels
167
+ self.conv_channels = conv_channels
168
+ self.ctc_loss_reduction = ctc_loss_reduction
169
+ self.ctc_zero_infinity = ctc_zero_infinity
170
+
171
+ # prevents config testing fail with exporting to json
172
+ self.conv_kernel = list(conv_kernel)
173
+ self.conv_stride = list(conv_stride)
174
+
175
+ if len(self.conv_kernel) != self.num_conv_layers:
176
+ raise ValueError(
177
+ "Configuration for convolutional module is incorrect. "
178
+ "It is required that `len(config.conv_kernel)` == `config.num_conv_layers` "
179
+ f"but is `len(config.conv_kernel) = {len(self.conv_kernel)}`, "
180
+ f"`config.num_conv_layers = {self.num_conv_layers}`."
181
+ )
182
+
183
+
184
+ __all__ = ["MCTCTConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mctct/feature_extraction_mctct.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Feature extractor class for M-CTC-T
17
+ """
18
+
19
+ from typing import Optional, Union
20
+
21
+ import numpy as np
22
+
23
+ from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
24
+ from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
25
+ from ....feature_extraction_utils import BatchFeature
26
+ from ....file_utils import PaddingStrategy, TensorType
27
+ from ....utils import logging
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ class MCTCTFeatureExtractor(SequenceFeatureExtractor):
34
+ r"""
35
+ Constructs a M-CTC-T feature extractor.
36
+
37
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
38
+ most of the main methods. Users should refer to this superclass for more information regarding those methods. This
39
+ code has been adapted from Flashlight's C++ code. For more information about the implementation, one can refer to
40
+ this [notebook](https://colab.research.google.com/drive/1GLtINkkhzms-IsdcGy_-tVCkv0qNF-Gt#scrollTo=pMCRGMmUC_an)
41
+ that takes the user step-by-step in the implementation.
42
+
43
+ Args:
44
+ feature_size (`int`, defaults to 80):
45
+ The feature dimension of the extracted features. This is the number of mel_frequency
46
+ sampling_rate (`int`, defaults to 16000):
47
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
48
+ padding_value (`float`, defaults to 0.0):
49
+ The value that is used to fill the padding values.
50
+ hop_length (`int`, defaults to 10):
51
+ Number of audio samples between windows. Otherwise referred to as "shift" in many papers.
52
+ win_length (`int`, defaults to 25):
53
+ Number of ms per window
54
+ win_function (`str`, defaults to `"hamming_window"`):
55
+ Name for the window function used for windowing, must be accessible via `torch.{win_function}`
56
+ frame_signal_scale (`float`, defaults to 32768.0):
57
+ Constant multiplied in creating the frames before applying DFT.
58
+ preemphasis_coeff (`float`, defaults to 0.97):
59
+ Constant multiplied in applying Pre-emphasis before DFT.
60
+ mel_floor (`float` defaults to 1.0):
61
+ Minimum value of mel frequency banks.
62
+ normalize_means (`bool`, *optional*, defaults to `True`):
63
+ Whether or not to zero-mean normalize the extracted features.
64
+ normalize_vars (`bool`, *optional*, defaults to `True`):
65
+ Whether or not to unit-variance normalize the extracted features.
66
+ """
67
+
68
+ model_input_names = ["input_features", "attention_mask"]
69
+
70
+ def __init__(
71
+ self,
72
+ feature_size=80,
73
+ sampling_rate=16000,
74
+ padding_value=0.0,
75
+ hop_length=10,
76
+ win_length=25,
77
+ win_function="hamming_window",
78
+ frame_signal_scale=32768.0,
79
+ preemphasis_coeff=0.97,
80
+ mel_floor=1.0,
81
+ normalize_means=True,
82
+ normalize_vars=True,
83
+ return_attention_mask=False,
84
+ **kwargs,
85
+ ):
86
+ super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
87
+
88
+ self.feature_size = feature_size
89
+ self.sampling_rate = sampling_rate
90
+ self.padding_value = padding_value
91
+ self.hop_length = hop_length
92
+ self.win_length = win_length
93
+ self.frame_signal_scale = frame_signal_scale
94
+ self.preemphasis_coeff = preemphasis_coeff
95
+ self.mel_floor = mel_floor
96
+ self.normalize_means = normalize_means
97
+ self.normalize_vars = normalize_vars
98
+ self.win_function = win_function
99
+ self.return_attention_mask = return_attention_mask
100
+
101
+ self.sample_size = win_length * sampling_rate // 1000
102
+ self.sample_stride = hop_length * sampling_rate // 1000
103
+
104
+ self.n_fft = optimal_fft_length(self.sample_size)
105
+ self.n_freqs = (self.n_fft // 2) + 1
106
+
107
+ def _extract_mfsc_features(self, one_waveform: np.ndarray) -> np.ndarray:
108
+ """
109
+ Extracts MFSC Features for one waveform vector (unbatched). Adapted from Flashlight's C++ MFSC code.
110
+ """
111
+ if self.win_function == "hamming_window":
112
+ window = window_function(window_length=self.sample_size, name=self.win_function, periodic=False)
113
+ else:
114
+ window = window_function(window_length=self.sample_size, name=self.win_function)
115
+
116
+ fbanks = mel_filter_bank(
117
+ num_frequency_bins=self.n_freqs,
118
+ num_mel_filters=self.feature_size,
119
+ min_frequency=0.0,
120
+ max_frequency=self.sampling_rate / 2.0,
121
+ sampling_rate=self.sampling_rate,
122
+ )
123
+
124
+ msfc_features = spectrogram(
125
+ one_waveform * self.frame_signal_scale,
126
+ window=window,
127
+ frame_length=self.sample_size,
128
+ hop_length=self.sample_stride,
129
+ fft_length=self.n_fft,
130
+ center=False,
131
+ preemphasis=self.preemphasis_coeff,
132
+ mel_filters=fbanks,
133
+ mel_floor=self.mel_floor,
134
+ log_mel="log",
135
+ )
136
+ return msfc_features.T
137
+
138
+ def _normalize_one(self, x, input_length, padding_value):
139
+ # make sure we normalize float32 arrays
140
+ if self.normalize_means:
141
+ mean = x[:input_length].mean(axis=0)
142
+ x = np.subtract(x, mean)
143
+ if self.normalize_vars:
144
+ std = x[:input_length].std(axis=0)
145
+ x = np.divide(x, std)
146
+
147
+ if input_length < x.shape[0]:
148
+ x[input_length:] = padding_value
149
+
150
+ # make sure array is in float32
151
+ x = x.astype(np.float32)
152
+
153
+ return x
154
+
155
+ def normalize(
156
+ self, input_features: list[np.ndarray], attention_mask: Optional[np.ndarray] = None
157
+ ) -> list[np.ndarray]:
158
+ lengths = attention_mask.sum(-1) if attention_mask is not None else [x.shape[0] for x in input_features]
159
+ return [self._normalize_one(x, n, self.padding_value) for x, n in zip(input_features, lengths)]
160
+
161
+ def __call__(
162
+ self,
163
+ raw_speech: Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]],
164
+ padding: Union[bool, str, PaddingStrategy] = False,
165
+ max_length: Optional[int] = None,
166
+ truncation: bool = False,
167
+ pad_to_multiple_of: Optional[int] = None,
168
+ return_attention_mask: Optional[bool] = None,
169
+ return_tensors: Optional[Union[str, TensorType]] = None,
170
+ sampling_rate: Optional[int] = None,
171
+ **kwargs,
172
+ ) -> BatchFeature:
173
+ """
174
+ Main method to featurize and prepare for the model one or several sequence(s). sequences. It returns the
175
+ log-mel spectrogram of the input audio, as implemented in the original Flashlight MFSC feature extraction code.
176
+
177
+ Args:
178
+ raw_speech (`torch.Tensor`, `np.ndarray`, `list[float]`, `list[torch.Tensor]`, `list[np.ndarray]`, `list[list[float]]`):
179
+ The sequence or batch of sequences to be padded. Each sequence can be a tensor, a numpy array, a list
180
+ of float values, a list of tensors, a list of numpy arrays or a list of list of float values. Must be
181
+ mono channel audio, not stereo, i.e. single float per timestep.
182
+ padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
183
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
184
+ index) among:
185
+
186
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
187
+ sequence if provided).
188
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
189
+ acceptable input length for the model if that argument is not provided.
190
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
191
+ lengths).
192
+ max_length (`int`, *optional*):
193
+ Maximum length of the returned list and optionally padding length (see above).
194
+ truncation (`bool`):
195
+ Activates truncation to cut input sequences longer than *max_length* to *max_length*.
196
+ pad_to_multiple_of (`int`, *optional*):
197
+ If set will pad the sequence to a multiple of the provided value.
198
+
199
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
200
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
201
+ return_attention_mask (`bool`, *optional*):
202
+ Whether to return the attention mask. If left to the default, will return the attention mask according
203
+ to the specific feature_extractor's default.
204
+
205
+ [What are attention masks?](../glossary#attention-mask)
206
+
207
+ return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
208
+ If set, will return tensors instead of list of python integers. Acceptable values are:
209
+
210
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
211
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
212
+ - `'np'`: Return Numpy `np.ndarray` objects.
213
+ sampling_rate (`int`, *optional*):
214
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
215
+ `sampling_rate` at the forward call to prevent silent errors.
216
+ padding_value (`float`, defaults to 0.0):
217
+ """
218
+
219
+ if sampling_rate is not None:
220
+ if sampling_rate != self.sampling_rate:
221
+ raise ValueError(
222
+ f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
223
+ f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"
224
+ f" {self.sampling_rate} and not {sampling_rate}."
225
+ )
226
+ else:
227
+ logger.warning(
228
+ "It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
229
+ "Failing to do so can result in silent errors that might be hard to debug."
230
+ )
231
+
232
+ is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
233
+ if is_batched_numpy and len(raw_speech.shape) > 2:
234
+ raise ValueError(f"Only mono-channel audio is supported for input to {self}")
235
+ is_batched = is_batched_numpy or (
236
+ isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
237
+ )
238
+
239
+ if is_batched:
240
+ raw_speech = [np.asarray(speech, dtype=np.float32) for speech in raw_speech]
241
+ elif not is_batched and not isinstance(raw_speech, np.ndarray):
242
+ raw_speech = np.asarray(raw_speech, dtype=np.float32)
243
+ elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
244
+ raw_speech = raw_speech.astype(np.float32)
245
+
246
+ # always return batch
247
+ if not is_batched:
248
+ raw_speech = [raw_speech]
249
+
250
+ # extract fbank features
251
+ features = [self._extract_mfsc_features(one_waveform) for one_waveform in raw_speech]
252
+
253
+ # convert into correct format for padding
254
+ encoded_inputs = BatchFeature({"input_features": features})
255
+
256
+ padded_inputs = self.pad(
257
+ encoded_inputs,
258
+ padding=padding,
259
+ max_length=max_length,
260
+ truncation=truncation,
261
+ pad_to_multiple_of=pad_to_multiple_of,
262
+ return_attention_mask=True,
263
+ **kwargs,
264
+ )
265
+ # make sure list is in array format
266
+ input_features = padded_inputs.get("input_features")
267
+ if isinstance(input_features[0], list):
268
+ padded_inputs["input_features"] = [np.asarray(feature, dtype=np.float32) for feature in input_features]
269
+
270
+ attention_mask = padded_inputs.get("attention_mask")
271
+ if attention_mask is not None:
272
+ padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask]
273
+
274
+ if self.normalize_means or self.normalize_vars:
275
+ attention_mask = (
276
+ np.array(attention_mask, dtype=np.int32)
277
+ if self._get_padding_strategies(padding, max_length=max_length) is not PaddingStrategy.DO_NOT_PAD
278
+ and padding
279
+ else None
280
+ )
281
+ padded_inputs["input_features"] = self.normalize(
282
+ padded_inputs["input_features"], attention_mask=attention_mask
283
+ )
284
+
285
+ if return_tensors is not None:
286
+ padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
287
+
288
+ return padded_inputs
289
+
290
+
291
+ __all__ = ["MCTCTFeatureExtractor"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mctct/modeling_mctct.py ADDED
@@ -0,0 +1,778 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch M-CTC-T model."""
16
+
17
+ import math
18
+ from typing import Optional, Union
19
+
20
+ import torch
21
+ from torch import nn
22
+
23
+ from ....activations import ACT2FN
24
+ from ....file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
25
+ from ....integrations.deepspeed import is_deepspeed_zero3_enabled
26
+ from ....integrations.fsdp import is_fsdp_managed_module
27
+ from ....modeling_attn_mask_utils import _prepare_4d_attention_mask
28
+ from ....modeling_layers import GradientCheckpointingLayer
29
+ from ....modeling_outputs import BaseModelOutput, CausalLMOutput
30
+ from ....modeling_utils import PreTrainedModel
31
+ from ....pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
32
+ from ....utils import logging
33
+ from .configuration_mctct import MCTCTConfig
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ _HIDDEN_STATES_START_POSITION = 1
39
+
40
+ _CONFIG_FOR_DOC = "MCTCTConfig"
41
+
42
+ # Base docstring
43
+ _CHECKPOINT_FOR_DOC = "speechbrain/m-ctc-t-large"
44
+ _EXPECTED_OUTPUT_SHAPE = [1, 195, 1536]
45
+
46
+ # CTC docstring
47
+ _CTC_EXPECTED_OUTPUT = '"Mr. Quilter is the apostle of the middle classes, and we\'re glad to welcome his gospel."'
48
+ _CTC_EXPECTED_LOSS = 1885.65
49
+
50
+
51
+ class MCTCTConv1dSubsampler(nn.Module):
52
+ """
53
+ Convolutional subsampler: a stack of 1D convolution (along temporal dimension) followed by non-linear activation
54
+ via gated linear units (https://huggingface.co/papers/1911.08460)
55
+ """
56
+
57
+ def __init__(self, config):
58
+ super().__init__()
59
+ self.config = config
60
+ self.glu_dim = config.conv_glu_dim
61
+
62
+ self.dropout = nn.Dropout(config.conv_dropout)
63
+
64
+ self.num_layers = config.num_conv_layers
65
+ self.in_channels = config.input_feat_per_channel * config.input_channels
66
+
67
+ if self.num_layers > 1:
68
+ if config.conv_channels is None:
69
+ raise ValueError(
70
+ "Need to specify `conv_channels` configuration in `MCTCTConfig` to use multiple convolution"
71
+ " layers."
72
+ )
73
+
74
+ self.mid_channels = config.conv_channels
75
+ else:
76
+ self.mid_channels = None
77
+
78
+ self.out_channels = config.hidden_size * 2 # considering GLU halving
79
+ self.kernel_size = config.conv_kernel
80
+ self.stride = config.conv_stride
81
+
82
+ # NOTE: MCTCT by construction only uses one convolution kernel. I've made this flexible to allow for
83
+ # multiple layers of convolutions, but not sure if this model definition should just restrict it
84
+ # to one layer. This becomes especially relevant when considering the padding like line 1 of forward().
85
+ self.conv_layers = nn.ModuleList(
86
+ nn.Conv1d(
87
+ self.in_channels if i == 0 else self.mid_channels[i],
88
+ self.mid_channels[i] if i < self.num_layers - 1 else self.out_channels,
89
+ kernel_size=k,
90
+ stride=self.stride[i],
91
+ padding="valid",
92
+ )
93
+ for i, k in enumerate(self.kernel_size)
94
+ )
95
+
96
+ def forward(self, input_features):
97
+ # NOTE: in reference to the NOTE in __init__, right now it just calculates padding as if
98
+ # there will be just one conv layer.
99
+ padding = sum(size // 2 for size in self.kernel_size) # (7, 7) -> (3, 3)
100
+
101
+ input_features = torch.nn.functional.pad(input_features, (0, 0, padding, padding), "constant", 0)
102
+ hidden_states = input_features.transpose(1, 2).contiguous() # -> Batch x Frame x Time
103
+ for conv in self.conv_layers:
104
+ hidden_states = conv(hidden_states)
105
+ hidden_states = nn.functional.glu(hidden_states, dim=self.glu_dim)
106
+ hidden_states = self.dropout(hidden_states)
107
+
108
+ hidden_states = hidden_states.transpose(1, 2).contiguous() # -> Batch x Time x Frame
109
+ return hidden_states
110
+
111
+
112
+ class MCTCTEmbeddings(nn.Module):
113
+ """Construct the embeddings from word, position and token_type embeddings."""
114
+
115
+ def __init__(self, config):
116
+ super().__init__()
117
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
118
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
119
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
120
+
121
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
122
+ # any TensorFlow checkpoint file
123
+ # self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
124
+ self.LayerNorm = MCTCTLayerNorm()
125
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
126
+
127
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
128
+ self.register_buffer(
129
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
130
+ )
131
+ self.register_buffer(
132
+ "token_type_ids",
133
+ torch.zeros(self.position_ids.size(), dtype=torch.long, device=self.position_ids.device),
134
+ persistent=False,
135
+ )
136
+
137
+ def forward(
138
+ self, input_features=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
139
+ ):
140
+ input_shape = input_features.size() if input_features is not None else inputs_embeds.size()[:-1]
141
+
142
+ seq_length = input_shape[1]
143
+
144
+ if position_ids is None:
145
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
146
+
147
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
148
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
149
+ # issue #5664
150
+ if token_type_ids is None:
151
+ if hasattr(self, "token_type_ids"):
152
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
153
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
154
+ token_type_ids = buffered_token_type_ids_expanded
155
+ else:
156
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
157
+
158
+ if inputs_embeds is None:
159
+ inputs_embeds = self.word_embeddings(input_features)
160
+
161
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
162
+
163
+ embeddings = inputs_embeds + token_type_embeddings
164
+
165
+ embeddings = self.LayerNorm(embeddings)
166
+ embeddings = self.dropout(embeddings)
167
+ return embeddings
168
+
169
+
170
+ class MCTCTSelfAttention(nn.Module):
171
+ def __init__(self, config):
172
+ super().__init__()
173
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
174
+ raise ValueError(
175
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
176
+ f"heads ({config.num_attention_heads})"
177
+ )
178
+
179
+ self.num_attention_heads = config.num_attention_heads
180
+ self.attention_head_size = config.attention_head_dim
181
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
182
+
183
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=False)
184
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=False)
185
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=False)
186
+
187
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
188
+
189
+ self.max_position_embeddings = config.max_position_embeddings
190
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
191
+
192
+ self.is_decoder = config.is_decoder
193
+
194
+ def transpose_for_scores(self, x):
195
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
196
+ x = x.view(*new_x_shape)
197
+ return x.permute(0, 2, 1, 3)
198
+
199
+ def reshape_fortran(self, x, shape):
200
+ if len(x.shape) > 0:
201
+ x = x.permute(*reversed(range(len(x.shape))))
202
+ return x.reshape(*reversed(shape)).permute(*reversed(range(len(shape))))
203
+
204
+ def relative_position_embedding_rotate(self, scores):
205
+ # NOTE: should re-evaluate whether this re-implementation was truly necessary
206
+ # or the reason why my complete re-haul worked was due to some other part
207
+ # of the code. Adding this and the reshape fortrain code seems very undesirable.
208
+ scores = scores.permute(0, 2, 3, 1) # e.g. [10, 1839, 14, 4]
209
+
210
+ batch, hidden_state, seq_len, heads = scores.shape
211
+
212
+ # e.g. [10, 1853, 14, 4]
213
+ scores = torch.cat((scores, torch.zeros((batch, seq_len, seq_len, heads), device=scores.device)), dim=1)
214
+
215
+ # e.g. [10, 25942, 1, 4]
216
+ scores = self.reshape_fortran(scores, [batch, (hidden_state + seq_len) * seq_len, 1, heads])
217
+
218
+ # e.g. [10, 25928, 1, 4]
219
+ scores = scores[:, : (seq_len + hidden_state - 1) * seq_len]
220
+
221
+ # e.g. [10, 1852, 14, 4]
222
+ scores = self.reshape_fortran(scores, [batch, hidden_state + seq_len - 1, seq_len, heads])
223
+
224
+ halfpoint = hidden_state // 2
225
+ scores = scores[:, halfpoint : halfpoint + seq_len].transpose(1, 2) # e.g. [10, 14, 14, 4]
226
+
227
+ return scores.permute(0, 3, 1, 2)
228
+
229
+ def forward(
230
+ self,
231
+ hidden_states,
232
+ attention_mask=None,
233
+ head_mask=None,
234
+ output_attentions=False,
235
+ ):
236
+ mixed_query_layer = self.query(hidden_states)
237
+ mixed_query_layer = mixed_query_layer / math.sqrt(self.attention_head_size)
238
+
239
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
240
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
241
+
242
+ query_layer = self.transpose_for_scores(mixed_query_layer)
243
+
244
+ # Take the dot product between "query" and "key" to get the raw attention scores.
245
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
246
+
247
+ # relative key position embeddings
248
+ positional_embedding = self.distance_embedding.weight
249
+ relative_position_scores = torch.einsum("lh, bche -> bcle", positional_embedding, query_layer.transpose(2, 3))
250
+
251
+ relative_position_scores = self.relative_position_embedding_rotate(relative_position_scores)
252
+ attention_scores = attention_scores + relative_position_scores
253
+
254
+ if attention_mask is not None:
255
+ # Apply the attention mask is (precomputed for all layers in MCTCTModel forward() function)
256
+ attention_scores = attention_scores + attention_mask
257
+
258
+ # Normalize the attention scores to probabilities.
259
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
260
+
261
+ # This is actually dropping out entire tokens to attend to, which might
262
+ # seem a bit unusual, but is taken from the original Transformer paper.
263
+ attention_probs = self.dropout(attention_probs)
264
+
265
+ # Mask heads if we want to
266
+ if head_mask is not None:
267
+ attention_probs = attention_probs * head_mask
268
+
269
+ context_layer = torch.matmul(attention_probs, value_layer)
270
+
271
+ context_layer = context_layer.permute(0, 2, 1, 3).flatten(start_dim=-2)
272
+
273
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
274
+
275
+ return outputs
276
+
277
+
278
+ class MCTCTLayerNorm(nn.Module):
279
+ def __init__(self):
280
+ super().__init__()
281
+ self.singleton_weight = nn.Parameter(torch.ones(1))
282
+ self.singleton_bias = nn.Parameter(torch.zeros(1))
283
+
284
+ def forward(self, hidden_states):
285
+ return (hidden_states * self.singleton_weight) + self.singleton_bias
286
+
287
+
288
+ class MCTCTSelfOutput(nn.Module):
289
+ def __init__(self, config):
290
+ super().__init__()
291
+ self.config = config
292
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
293
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
294
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
295
+
296
+ def forward(self, hidden_states, input_tensor):
297
+ hidden_states = self.dense(hidden_states)
298
+ hidden_states = self.dropout(hidden_states)
299
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
300
+ return hidden_states
301
+
302
+
303
+ class MCTCTAttention(nn.Module):
304
+ def __init__(self, config):
305
+ super().__init__()
306
+ self.self = MCTCTSelfAttention(config)
307
+ self.output = MCTCTSelfOutput(config)
308
+ self.pruned_heads = set()
309
+
310
+ def prune_heads(self, heads):
311
+ if len(heads) == 0:
312
+ return
313
+ heads, index = find_pruneable_heads_and_indices(
314
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
315
+ )
316
+
317
+ # Prune linear layers
318
+ self.self.query = prune_linear_layer(self.self.query, index)
319
+ self.self.key = prune_linear_layer(self.self.key, index)
320
+ self.self.value = prune_linear_layer(self.self.value, index)
321
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
322
+
323
+ # Update hyper params and store pruned heads
324
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
325
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
326
+ self.pruned_heads = self.pruned_heads.union(heads)
327
+
328
+ def forward(
329
+ self,
330
+ hidden_states,
331
+ attention_mask=None,
332
+ head_mask=None,
333
+ output_attentions=False,
334
+ ):
335
+ self_outputs = self.self(
336
+ hidden_states,
337
+ attention_mask,
338
+ head_mask,
339
+ output_attentions,
340
+ )
341
+ attention_output = self.output(self_outputs[0], hidden_states)
342
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
343
+
344
+ return outputs
345
+
346
+
347
+ class MCTCTIntermediate(nn.Module):
348
+ def __init__(self, config):
349
+ super().__init__()
350
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
351
+ if isinstance(config.hidden_act, str):
352
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
353
+ else:
354
+ self.intermediate_act_fn = config.hidden_act
355
+
356
+ def forward(self, hidden_states):
357
+ hidden_states = self.dense(hidden_states)
358
+ hidden_states = self.intermediate_act_fn(hidden_states)
359
+ return hidden_states
360
+
361
+
362
+ class MCTCTOutput(nn.Module):
363
+ def __init__(self, config):
364
+ super().__init__()
365
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
366
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
367
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
368
+
369
+ def forward(self, hidden_states, input_tensor):
370
+ hidden_states = self.dense(hidden_states)
371
+ hidden_states = self.dropout(hidden_states)
372
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
373
+ return hidden_states
374
+
375
+
376
+ class MCTCTLayer(GradientCheckpointingLayer):
377
+ def __init__(self, config: MCTCTConfig):
378
+ super().__init__()
379
+
380
+ self.seq_len_dim = 1
381
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
382
+
383
+ self.intermediate = MCTCTIntermediate(config)
384
+ self.attention = MCTCTAttention(config)
385
+ self.is_decoder = config.is_decoder
386
+ self.output = MCTCTOutput(config)
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states,
391
+ attention_mask=None,
392
+ head_mask=None,
393
+ output_attentions=False,
394
+ ):
395
+ self_attention_outputs = self.attention(
396
+ hidden_states, attention_mask, head_mask, output_attentions=output_attentions
397
+ )
398
+ attention_output = self_attention_outputs[0]
399
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
400
+
401
+ layer_output = apply_chunking_to_forward(
402
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
403
+ )
404
+
405
+ outputs = (layer_output,) + outputs
406
+
407
+ return outputs
408
+
409
+ def feed_forward_chunk(self, attention_output):
410
+ intermediate_output = self.intermediate(attention_output)
411
+ layer_output = self.output(intermediate_output, attention_output)
412
+ return layer_output
413
+
414
+
415
+ class MCTCTPreTrainedModel(PreTrainedModel):
416
+ """
417
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
418
+ models.
419
+ """
420
+
421
+ config: MCTCTConfig
422
+ base_model_prefix = "mctct"
423
+ main_input_name = "input_features"
424
+ supports_gradient_checkpointing = True
425
+
426
+ def _init_weights(self, module):
427
+ """Initialize the weights"""
428
+ std = self.config.initializer_range
429
+ if isinstance(module, nn.Linear):
430
+ # Slightly different from the TF version which uses truncated_normal for initialization
431
+ # cf https://github.com/pytorch/pytorch/pull/5617
432
+ module.weight.data.normal_(mean=0.0, std=std)
433
+ if module.bias is not None:
434
+ module.bias.data.zero_()
435
+ elif isinstance(module, nn.Embedding):
436
+ module.weight.data.normal_(mean=0.0, std=std)
437
+ if module.padding_idx is not None:
438
+ module.weight.data[module.padding_idx].zero_()
439
+ elif isinstance(module, nn.LayerNorm):
440
+ module.bias.data.zero_()
441
+ module.weight.data.fill_(1.0)
442
+ elif isinstance(module, MCTCTLayerNorm):
443
+ module.singleton_weight.data.fill_(1.0)
444
+ module.singleton_bias.data.zero_()
445
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
446
+ module.weight.data.normal_(mean=0.0, std=std)
447
+ if module.bias is not None:
448
+ module.bias.data.zero_()
449
+
450
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
451
+ """
452
+ Computes the output length of the convolutional layers
453
+ """
454
+ dilation = 1
455
+ for _, kernel_sz, stride in zip(
456
+ range(self.config.num_conv_layers), self.config.conv_kernel, self.config.conv_stride
457
+ ):
458
+ padding = kernel_sz // 2
459
+ input_lengths = input_lengths + 2 * padding - dilation * (kernel_sz - 1) - 1
460
+ input_lengths = torch.div(input_lengths, stride, rounding_mode="trunc") + 1
461
+
462
+ return input_lengths
463
+
464
+ def _get_feature_vector_attention_mask(self, feature_vector_length, attention_mask):
465
+ # generate creates 3D attention mask, because of the shape of input_features
466
+ # convert it to 2D if that's the case
467
+ if len(attention_mask.shape) > 2:
468
+ attention_mask = attention_mask[:, :, -1]
469
+
470
+ # subsampled_lengths = attention_mask.sum(-1)
471
+ subsampled_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1))
472
+ bsz = attention_mask.size()[0]
473
+ attention_mask = torch.zeros(
474
+ (bsz, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
475
+ )
476
+
477
+ # these two operations makes sure that all values
478
+ # before the output lengths indices are attended to
479
+ attention_mask[(torch.arange(bsz, device=attention_mask.device), subsampled_lengths - 1)] = 1
480
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).long()
481
+ return attention_mask
482
+
483
+
484
+ MCTCT_START_DOCSTRING = r"""
485
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
486
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
487
+ behavior.
488
+
489
+ Parameters:
490
+ config ([`MCTCTConfig`]): Model configuration class with all the parameters of the model.
491
+ Initializing with a config file does not load the weights associated with the model, only the
492
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
493
+ """
494
+
495
+ MCTCT_INPUTS_DOCSTRING = r"""
496
+ Args:
497
+ input_features (`torch.LongTensor` of shape `({0})`):
498
+ Indices of input sequence tokens in the vocabulary.
499
+
500
+ Indices can be obtained using [`Wav2Vec2CTCTokenizer`]. See [`PreTrainedTokenizer.encode`] and
501
+ [`PreTrainedTokenizer.__call__`] for details.
502
+
503
+ [What are input IDs?](../glossary#input-ids)
504
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
505
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
506
+
507
+ - 1 for tokens that are **not masked**,
508
+ - 0 for tokens that are **masked**.
509
+
510
+ [What are attention masks?](../glossary#attention-mask)
511
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
512
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
513
+
514
+ - 1 indicates the head is **not masked**,
515
+ - 0 indicates the head is **masked**.
516
+ output_attentions (`bool`, *optional*):
517
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
518
+ tensors for more detail.
519
+ output_hidden_states (`bool`, *optional*):
520
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
521
+ more detail.
522
+ return_dict (`bool`, *optional*):
523
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
524
+ """
525
+
526
+
527
+ class MCTCTEncoder(MCTCTPreTrainedModel):
528
+ def __init__(self, config: MCTCTConfig):
529
+ super().__init__(config)
530
+ self.hidden_dropout_prob = config.hidden_dropout_prob
531
+
532
+ self.layer_norm = MCTCTLayerNorm()
533
+ self.conv = MCTCTConv1dSubsampler(config)
534
+ self.layers = nn.ModuleList([MCTCTLayer(config) for _ in range(config.num_hidden_layers)])
535
+
536
+ self.gradient_checkpointing = False
537
+
538
+ def forward(
539
+ self,
540
+ input_features: torch.Tensor,
541
+ attention_mask: torch.Tensor,
542
+ head_mask: torch.Tensor,
543
+ output_attentions: bool = False,
544
+ output_hidden_states: bool = False,
545
+ return_dict: bool = True,
546
+ ) -> Union[tuple, BaseModelOutput]:
547
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
548
+ output_hidden_states = (
549
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
550
+ )
551
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
552
+
553
+ input_features = self.layer_norm(input_features)
554
+
555
+ inputs_embeds = self.conv(input_features)
556
+
557
+ # subsample attention mask if necessary
558
+ if attention_mask is not None:
559
+ attention_mask = self._get_feature_vector_attention_mask(inputs_embeds.shape[1], attention_mask)
560
+
561
+ hidden_states = nn.functional.dropout(inputs_embeds, p=self.hidden_dropout_prob, training=self.training)
562
+
563
+ # expand attention_mask
564
+ if attention_mask is not None:
565
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
566
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
567
+
568
+ encoder_states = () if output_hidden_states else None
569
+ all_attentions = () if output_attentions else None
570
+
571
+ # check if head_mask has a correct number of layers specified if desired
572
+ if head_mask is not None:
573
+ if head_mask.size()[0] != len(self.layers):
574
+ raise ValueError(
575
+ f"The head_mask should be specified for {len(self.layers)} layers, "
576
+ f"but it is for {head_mask.size()[0]}."
577
+ )
578
+
579
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
580
+ for idx, encoder_layer in enumerate(self.layers):
581
+ if output_hidden_states:
582
+ encoder_states = encoder_states + (hidden_states,)
583
+
584
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
585
+ dropout_probability = torch.rand([])
586
+
587
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
588
+ if not skip_the_layer or synced_gpus:
589
+ # under fsdp or deepspeed zero3 all gpus must run in sync
590
+ layer_outputs = encoder_layer(
591
+ hidden_states=hidden_states,
592
+ attention_mask=attention_mask,
593
+ output_attentions=output_attentions,
594
+ )
595
+
596
+ hidden_states = layer_outputs[0]
597
+
598
+ if skip_the_layer:
599
+ layer_outputs = (None, None)
600
+
601
+ if output_attentions:
602
+ all_attentions = all_attentions + (layer_outputs[1],)
603
+
604
+ if output_hidden_states:
605
+ encoder_states = encoder_states + (hidden_states,)
606
+
607
+ if not return_dict:
608
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
609
+ return BaseModelOutput(
610
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
611
+ )
612
+
613
+
614
+ @add_start_docstrings(
615
+ "The bare M-CTC-T Model transformer outputting raw hidden-states without any specific head on top.",
616
+ MCTCT_START_DOCSTRING,
617
+ )
618
+ class MCTCTModel(MCTCTPreTrainedModel):
619
+ def __init__(self, config):
620
+ super().__init__(config)
621
+ self.config = config
622
+
623
+ self.encoder = MCTCTEncoder(config)
624
+
625
+ # Initialize weights and apply final processing
626
+ self.post_init()
627
+
628
+ @add_start_docstrings_to_model_forward(MCTCT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
629
+ @add_code_sample_docstrings(
630
+ checkpoint=_CHECKPOINT_FOR_DOC,
631
+ output_type=BaseModelOutput,
632
+ config_class=_CONFIG_FOR_DOC,
633
+ modality="audio",
634
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
635
+ )
636
+ def forward(
637
+ self,
638
+ input_features: torch.Tensor,
639
+ attention_mask: Optional[torch.Tensor] = None,
640
+ head_mask: Optional[torch.Tensor] = None,
641
+ output_attentions: Optional[bool] = None,
642
+ output_hidden_states: Optional[bool] = None,
643
+ return_dict: Optional[bool] = None,
644
+ ) -> Union[tuple, BaseModelOutput]:
645
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
646
+ output_hidden_states = (
647
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
648
+ )
649
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
650
+
651
+ if input_features is None:
652
+ raise ValueError("You have to specify input_features.")
653
+
654
+ encoder_outputs = self.encoder(
655
+ input_features,
656
+ attention_mask=attention_mask,
657
+ head_mask=head_mask,
658
+ output_attentions=output_attentions,
659
+ output_hidden_states=output_hidden_states,
660
+ return_dict=return_dict,
661
+ )
662
+ sequence_output = encoder_outputs[0]
663
+
664
+ if not return_dict:
665
+ return (sequence_output,) + encoder_outputs[1:]
666
+
667
+ return BaseModelOutput(
668
+ last_hidden_state=sequence_output,
669
+ hidden_states=encoder_outputs.hidden_states,
670
+ attentions=encoder_outputs.attentions,
671
+ )
672
+
673
+
674
+ @add_start_docstrings(
675
+ """MCTCT Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).""",
676
+ MCTCT_START_DOCSTRING,
677
+ )
678
+ class MCTCTForCTC(MCTCTPreTrainedModel):
679
+ def __init__(self, config):
680
+ super().__init__(config)
681
+
682
+ self.mctct = MCTCTModel(config)
683
+
684
+ if config.vocab_size is None:
685
+ raise ValueError(
686
+ f"You are trying to instantiate {self.__class__} with a configuration that "
687
+ "does not define the vocabulary size of the language model head. Please "
688
+ "instantiate the model as follows: `MCTCTForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
689
+ "or define `vocab_size` of your model's configuration."
690
+ )
691
+ output_hidden_size = config.hidden_size
692
+
693
+ self.ctc_head = nn.Linear(output_hidden_size, config.vocab_size)
694
+
695
+ # Initialize weights and apply final processing
696
+ self.post_init()
697
+
698
+ @add_start_docstrings_to_model_forward(MCTCT_INPUTS_DOCSTRING)
699
+ @add_code_sample_docstrings(
700
+ checkpoint=_CHECKPOINT_FOR_DOC,
701
+ output_type=CausalLMOutput,
702
+ config_class=_CONFIG_FOR_DOC,
703
+ expected_output=_CTC_EXPECTED_OUTPUT,
704
+ expected_loss=_CTC_EXPECTED_LOSS,
705
+ )
706
+ def forward(
707
+ self,
708
+ input_features: torch.Tensor,
709
+ attention_mask: Optional[torch.Tensor] = None,
710
+ head_mask: Optional[torch.Tensor] = None,
711
+ output_attentions: Optional[bool] = None,
712
+ output_hidden_states: Optional[bool] = None,
713
+ return_dict: Optional[bool] = None,
714
+ labels: Optional[torch.LongTensor] = None,
715
+ ) -> Union[tuple, CausalLMOutput]:
716
+ r"""
717
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
718
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
719
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
720
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
721
+ config.vocab_size - 1]`.
722
+ """
723
+ if labels is not None and labels.max() >= self.config.vocab_size:
724
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
725
+
726
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
727
+ outputs = self.mctct(
728
+ input_features,
729
+ attention_mask=attention_mask,
730
+ head_mask=head_mask,
731
+ output_attentions=output_attentions,
732
+ output_hidden_states=output_hidden_states,
733
+ return_dict=return_dict,
734
+ )
735
+
736
+ hidden_states = outputs[0]
737
+
738
+ logits = self.ctc_head(hidden_states)
739
+
740
+ loss = None
741
+ if labels is not None:
742
+ # retrieve loss input_lengths from attention_mask
743
+ attention_mask = (
744
+ attention_mask
745
+ if attention_mask is not None
746
+ else torch.ones(input_features.shape[:-1], dtype=torch.long)
747
+ )
748
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
749
+ # assuming that padded tokens are filled with -100
750
+ # when not being attended to
751
+ labels_mask = labels >= 0
752
+ target_lengths = labels_mask.sum(-1)
753
+ flattened_targets = labels.masked_select(labels_mask)
754
+
755
+ # ctc_loss doesn't support fp16
756
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
757
+
758
+ with torch.backends.cudnn.flags(enabled=False):
759
+ loss = nn.functional.ctc_loss(
760
+ log_probs,
761
+ flattened_targets,
762
+ input_lengths,
763
+ target_lengths,
764
+ blank=self.config.pad_token_id,
765
+ reduction=self.config.ctc_loss_reduction,
766
+ zero_infinity=self.config.ctc_zero_infinity,
767
+ )
768
+
769
+ if not return_dict:
770
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
771
+ return ((loss,) + output) if loss is not None else output
772
+
773
+ return CausalLMOutput(
774
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
775
+ )
776
+
777
+
778
+ __all__ = ["MCTCTForCTC", "MCTCTModel", "MCTCTPreTrainedModel"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mctct/processing_mctct.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Speech processor class for M-CTC-T
17
+ """
18
+
19
+ import warnings
20
+ from contextlib import contextmanager
21
+
22
+ from ....processing_utils import ProcessorMixin
23
+
24
+
25
+ class MCTCTProcessor(ProcessorMixin):
26
+ r"""
27
+ Constructs a MCTCT processor which wraps a MCTCT feature extractor and a MCTCT tokenizer into a single processor.
28
+
29
+ [`MCTCTProcessor`] offers all the functionalities of [`MCTCTFeatureExtractor`] and [`AutoTokenizer`]. See the
30
+ [`~MCTCTProcessor.__call__`] and [`~MCTCTProcessor.decode`] for more information.
31
+
32
+ Args:
33
+ feature_extractor (`MCTCTFeatureExtractor`):
34
+ An instance of [`MCTCTFeatureExtractor`]. The feature extractor is a required input.
35
+ tokenizer (`AutoTokenizer`):
36
+ An instance of [`AutoTokenizer`]. The tokenizer is a required input.
37
+ """
38
+
39
+ feature_extractor_class = "MCTCTFeatureExtractor"
40
+ tokenizer_class = "AutoTokenizer"
41
+
42
+ def __init__(self, feature_extractor, tokenizer):
43
+ super().__init__(feature_extractor, tokenizer)
44
+ self.current_processor = self.feature_extractor
45
+ self._in_target_context_manager = False
46
+
47
+ def __call__(self, *args, **kwargs):
48
+ """
49
+ When used in normal mode, this method forwards all its arguments to MCTCTFeatureExtractor's
50
+ [`~MCTCTFeatureExtractor.__call__`] and returns its output. If used in the context
51
+ [`~MCTCTProcessor.as_target_processor`] this method forwards all its arguments to AutoTokenizer's
52
+ [`~AutoTokenizer.__call__`]. Please refer to the docstring of the above two methods for more information.
53
+ """
54
+ # For backward compatibility
55
+ if self._in_target_context_manager:
56
+ return self.current_processor(*args, **kwargs)
57
+
58
+ if "raw_speech" in kwargs:
59
+ warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.")
60
+ audio = kwargs.pop("raw_speech")
61
+ else:
62
+ audio = kwargs.pop("audio", None)
63
+ sampling_rate = kwargs.pop("sampling_rate", None)
64
+ text = kwargs.pop("text", None)
65
+ if len(args) > 0:
66
+ audio = args[0]
67
+ args = args[1:]
68
+
69
+ if audio is None and text is None:
70
+ raise ValueError("You need to specify either an `audio` or `text` input to process.")
71
+
72
+ if audio is not None:
73
+ inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
74
+ if text is not None:
75
+ encodings = self.tokenizer(text, **kwargs)
76
+
77
+ if text is None:
78
+ return inputs
79
+ elif audio is None:
80
+ return encodings
81
+ else:
82
+ inputs["labels"] = encodings["input_ids"]
83
+ return inputs
84
+
85
+ def pad(self, *args, **kwargs):
86
+ """
87
+ When used in normal mode, this method forwards all its arguments to MCTCTFeatureExtractor's
88
+ [`~MCTCTFeatureExtractor.pad`] and returns its output. If used in the context
89
+ [`~MCTCTProcessor.as_target_processor`] this method forwards all its arguments to PreTrainedTokenizer's
90
+ [`~PreTrainedTokenizer.pad`]. Please refer to the docstring of the above two methods for more information.
91
+ """
92
+ # For backward compatibility
93
+ if self._in_target_context_manager:
94
+ return self.current_processor.pad(*args, **kwargs)
95
+
96
+ input_features = kwargs.pop("input_features", None)
97
+ labels = kwargs.pop("labels", None)
98
+ if len(args) > 0:
99
+ input_features = args[0]
100
+ args = args[1:]
101
+
102
+ if input_features is not None:
103
+ input_features = self.feature_extractor.pad(input_features, *args, **kwargs)
104
+ if labels is not None:
105
+ labels = self.tokenizer.pad(labels, **kwargs)
106
+
107
+ if labels is None:
108
+ return input_features
109
+ elif input_features is None:
110
+ return labels
111
+ else:
112
+ input_features["labels"] = labels["input_ids"]
113
+ return input_features
114
+
115
+ def decode(self, *args, **kwargs):
116
+ """
117
+ This method forwards all its arguments to AutoTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to the
118
+ docstring of this method for more information.
119
+ """
120
+ return self.tokenizer.decode(*args, **kwargs)
121
+
122
+ @contextmanager
123
+ def as_target_processor(self):
124
+ """
125
+ Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning MCTCT.
126
+ """
127
+ warnings.warn(
128
+ "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
129
+ "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
130
+ "your audio inputs, or in a separate call."
131
+ )
132
+ self._in_target_context_manager = True
133
+ self.current_processor = self.tokenizer
134
+ yield
135
+ self.current_processor = self.feature_extractor
136
+ self._in_target_context_manager = False
137
+
138
+
139
+ __all__ = ["MCTCTProcessor"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mega/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ....utils import _LazyModule
17
+ from ....utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_mega import *
22
+ from .modeling_mega import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mega/configuration_mega.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Mega Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """MEGA configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from collections.abc import Mapping
19
+
20
+ from ....configuration_utils import PretrainedConfig
21
+ from ....onnx import OnnxConfig
22
+ from ....utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class MegaConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`MegaModel`]. It is used to instantiate a Mega
31
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
32
+ defaults will yield a similar configuration to that of the Mega
33
+ [mnaylor/mega-base-wikitext](https://huggingface.co/mnaylor/mega-base-wikitext) architecture.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 30522):
41
+ Vocabulary size of the Mega model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`MegaModel`].
43
+ hidden_size (`int`, *optional*, defaults to 128):
44
+ Dimensionality of the encoder layers and the pooler layer.
45
+ num_hidden_layers (`int`, *optional*, defaults to 4):
46
+ Number of hidden layers in the Mega encoder.
47
+ intermediate_size (`int`, *optional*, defaults to 256):
48
+ Dimensionality of the hidden size (self-attention value projection) within the Mega encoder
49
+ ema_projection_size (`int`, *optional*, defaults to 16):
50
+ Dimensionality of the MegaMultiDimensionDampedEma
51
+ bidirectional (`bool`, *optional*, defaults to `True`):
52
+ Whether the MegaMultiDimensionDampedEma used in Mega's self-attention should work bidirectionally (`True`)
53
+ or unidirectionally (`False`). Bidirectional EMA is incompatible with causal decoding, so this should be
54
+ False if you intend to use the model as a decoder.
55
+ shared_representation_size (`int`, *optional*, defaults to 64):
56
+ Dimensionality of the linear projection for shared representation of self-attention queries and keys
57
+ use_chunking (`bool`, *optional*, defaults to `False`):
58
+ Whether to chunk inputs for linear self-attention complexity (described as Mega-chunk in the paper)
59
+ chunk_size (`int`, *optional*, defaults to -1):
60
+ If `use_chunking` is set to `True`, determines the size of the chunks to apply to the input sequence. If
61
+ chunking is used, input sequences must be padded to a multiple of `chunk_size`
62
+ truncation (`int`, *optional*):
63
+ If specified, the sequence length for which to truncate MegaMultiDimensionDampedEma
64
+ normalize_before_mega (`bool`, *optional*, defaults to `True`):
65
+ Whether to normalize before (`True`) or after (`False`) passing through Mega encoder blocks
66
+ normalization_type (`str`, *optional*, defaults to `"scalenorm"`):
67
+ Type of normalization to use in Mega encoder blocks. Choose one of `"scalenorm"`, `"layernorm"`,
68
+ `"rmsnorm"`, `"batchnorm"`, or `"syncbatchnorm"` (GPU required for syncbatchnorm)
69
+ norm_affine (`bool`, *optional*, defaults to `True`):
70
+ If `True`, applies a parameterized affine transformation to inputs during normalization
71
+ activation (`str`, *optional*, defaults to `"silu"`):
72
+ Activation function to apply within Mega encoder blocks. Choose one of `"silu"`, `"relu"`, `"linear"`,
73
+ `"gelu"`, or `"gelu_accurate"`
74
+ attention_activation (`str`, *optional*, defaults to `"softmax"`):
75
+ Activation function to apply for single-headed self-attention (a la Transformer). Choose one of
76
+ `"softmax"`, `"laplace"`, or `"relu2"`
77
+ dropout_prob (`float`, *optional*, defaults to 0.1):
78
+ The dropout probability for EMA self-attention
79
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
80
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
81
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
82
+ The dropout ratio for the attention probabilities.
83
+ use_feature_dropout (`bool`, *optional*, defaults to `False`):
84
+ Whether to use feature-based (`True`) or standard dropout (`False`)
85
+ use_normalized_ffn (`bool`, *optional*, defaults to `True`):
86
+ Whether to use the normalized feed-forward sub-layer in Mega blocks (`True`) or pass Mega encoder output
87
+ as-is (`False`)
88
+ nffn_hidden_size (`int`, *optional*, defaults to 256):
89
+ If using the normalized feed-forward network (NFFN) layer within Mega (`use_normalized_ffn = True`), this
90
+ is the hidden size of the NFFN
91
+ normalize_before_ffn (`bool`, *optional*, defaults to `True`):
92
+ Whether to normalize before (`True`) or after (`False`) the feed-forward portion of NFFN
93
+ nffn_activation_dropout_prob (`float`, *optional*, defaults to 0.1):
94
+ The dropout ratio for the NFFN component.
95
+ max_positions (`int`, *optional*, defaults to 2048):
96
+ The maximum sequence length to use for positional representations. For `"simple"` relative positional bias,
97
+ this is a hard limit on input length; `"rotary"` relative positional bias will extrapolate to longer
98
+ sequences
99
+ add_token_type_embeddings (`bool`, *optional*, defaults to `True`):
100
+ Whether to account for token types in embeddings. Left as optional to maintain compatibility with original
101
+ implementation while adding support for token types.
102
+ type_vocab_size (`int`, *optional*, defaults to 2):
103
+ The vocabulary size of the `token_type_ids` passed when calling [`MegaModel`]. Only used if
104
+ `add_token_type_embeddings = True`
105
+ initializer_range (`float`, *optional*, defaults to 0.02):
106
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
107
+ ema_delta_alpha_range (`float`, *optional*, defaults to 0.2):
108
+ The standard deviation for initializing the delta (damping factor) and alpha (decay factor) parameters in
109
+ MegaMultiDimensionDampedEma.
110
+ ema_beta_range (`float`, *optional*, defaults to 0.02):
111
+ The standard deviation for initializing the beta parameter (expansion matrix) in
112
+ MegaMultiDimensionDampedEma.
113
+ ema_gamma_omega_range (`float`, *optional*, defaults to 1.0):
114
+ The standard deviation for initializing the gamma (projection matrix) and omega (residual weight)
115
+ parameters in MultiDimensionEMA.
116
+ relative_positional_bias (`str`, *optional*, defaults to `"rotary"`):
117
+ Type of relative positional encoding. Choose one of `"rotary"` or `"simple"`. If `"simple"` is selected,
118
+ `max_positions` is used as a limit on input size, while `"rotary"` extrapolates beyond `max_positions`.
119
+ is_decoder (`bool`, *optional*, defaults to `False`):
120
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
121
+ use_cache (`bool`, *optional*, defaults to `True`):
122
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
123
+ relevant if `config.is_decoder=True`.
124
+ classifier_dropout (`float`, *optional*):
125
+ The dropout ratio for the classification head.
126
+ add_lm_hidden_dense_layer (`bool`, *optional*, defaults to `True`):
127
+ Whether to include a hidden layer for projection between encoder outputs and LM heads (`True`) or pass
128
+ hidden states directly to LM head (`False`). Remains optional for compatibility with original
129
+ implementation
130
+
131
+ Examples:
132
+
133
+ ```python
134
+ >>> from transformers import MegaConfig, MegaModel
135
+
136
+ >>> # Initializing a Mega configuration
137
+ >>> configuration = MegaConfig()
138
+
139
+ >>> # Initializing a model (with random weights) from the configuration
140
+ >>> model = MegaModel(configuration)
141
+
142
+ >>> # Accessing the model configuration
143
+ >>> configuration = model.config
144
+ ```"""
145
+
146
+ model_type = "mega"
147
+
148
+ def __init__(
149
+ self,
150
+ vocab_size=30522,
151
+ hidden_size=128,
152
+ num_hidden_layers=4,
153
+ intermediate_size=256,
154
+ ema_projection_size=16,
155
+ bidirectional=True,
156
+ shared_representation_size=64,
157
+ use_chunking=False,
158
+ chunk_size=-1,
159
+ truncation=None,
160
+ normalize_before_mega=True,
161
+ normalization_type="scalenorm",
162
+ norm_affine=True,
163
+ activation="silu",
164
+ attention_activation="softmax",
165
+ dropout_prob=0.1,
166
+ hidden_dropout_prob=0.1,
167
+ attention_probs_dropout_prob=0.1,
168
+ use_feature_dropout=False,
169
+ use_normalized_ffn=True,
170
+ nffn_hidden_size=256,
171
+ normalize_before_ffn=True,
172
+ nffn_activation_dropout_prob=0.1,
173
+ max_positions=2048,
174
+ add_token_type_embeddings=False,
175
+ type_vocab_size=2,
176
+ initializer_range=0.02,
177
+ ema_delta_alpha_range=0.2,
178
+ ema_beta_range=0.02,
179
+ ema_gamma_omega_range=1.0,
180
+ pad_token_id=1,
181
+ bos_token_id=0,
182
+ eos_token_id=2,
183
+ relative_positional_bias="rotary",
184
+ classifier_dropout=None,
185
+ use_cache=True,
186
+ add_lm_hidden_dense_layer=True,
187
+ **kwargs,
188
+ ):
189
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
190
+
191
+ self.vocab_size = vocab_size
192
+ self.hidden_size = hidden_size
193
+ self.num_hidden_layers = num_hidden_layers
194
+ self.activation = activation
195
+ self.attention_activation = attention_activation
196
+ self.intermediate_size = intermediate_size
197
+ self.ema_projection_size = ema_projection_size
198
+ self.bidirectional = bidirectional
199
+ self.shared_representation_size = shared_representation_size
200
+ self.use_chunking = use_chunking
201
+ self.chunk_size = chunk_size
202
+ self.truncation = truncation
203
+ self.normalize_before_mega = normalize_before_mega
204
+ self.normalization_type = normalization_type
205
+ self.norm_affine = norm_affine
206
+ self.dropout_prob = dropout_prob
207
+ self.hidden_dropout_prob = hidden_dropout_prob
208
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
209
+ self.use_feature_dropout = use_feature_dropout
210
+ self.use_normalized_ffn = use_normalized_ffn
211
+ self.nffn_hidden_size = nffn_hidden_size
212
+ self.normalize_before_ffn = normalize_before_ffn
213
+ self.nffn_activation_dropout_prob = nffn_activation_dropout_prob
214
+ self.max_positions = max_positions
215
+ self.add_token_type_embeddings = add_token_type_embeddings
216
+ self.type_vocab_size = type_vocab_size
217
+ self.initializer_range = initializer_range
218
+ self.ema_delta_alpha_range = ema_delta_alpha_range
219
+ self.ema_beta_range = ema_beta_range
220
+ self.ema_gamma_omega_range = ema_gamma_omega_range
221
+ self.relative_positional_bias = relative_positional_bias
222
+ self.use_cache = use_cache
223
+ self.classifier_dropout = classifier_dropout
224
+ self.add_lm_hidden_dense_layer = add_lm_hidden_dense_layer
225
+ self.num_attention_heads = 1 # not used but required by Hugging Face
226
+
227
+
228
+ class MegaOnnxConfig(OnnxConfig):
229
+ @property
230
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
231
+ if self.task == "multiple-choice":
232
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
233
+ else:
234
+ dynamic_axis = {0: "batch", 1: "sequence"}
235
+ return OrderedDict(
236
+ [
237
+ ("input_ids", dynamic_axis),
238
+ ("attention_mask", dynamic_axis),
239
+ ]
240
+ )
241
+
242
+
243
+ __all__ = ["MegaConfig", "MegaOnnxConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/mega/modeling_mega.py ADDED
The diff for this file is too large to render. See raw diff
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/nezha/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ....utils import _LazyModule
17
+ from ....utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_nezha import *
22
+ from .modeling_nezha import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/nezha/configuration_nezha.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .... import PretrainedConfig
2
+
3
+
4
+ class NezhaConfig(PretrainedConfig):
5
+ r"""
6
+ This is the configuration class to store the configuration of an [`NezhaModel`]. It is used to instantiate an Nezha
7
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
8
+ defaults will yield a similar configuration to that of the Nezha
9
+ [sijunhe/nezha-cn-base](https://huggingface.co/sijunhe/nezha-cn-base) architecture.
10
+
11
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
12
+ documentation from [`PretrainedConfig`] for more information.
13
+
14
+
15
+ Args:
16
+ vocab_size (`int`, optional, defaults to 21128):
17
+ Vocabulary size of the NEZHA model. Defines the different tokens that can be represented by the
18
+ *inputs_ids* passed to the forward method of [`NezhaModel`].
19
+ hidden_size (`int`, optional, defaults to 768):
20
+ Dimensionality of the encoder layers and the pooler layer.
21
+ num_hidden_layers (`int`, optional, defaults to 12):
22
+ Number of hidden layers in the Transformer encoder.
23
+ num_attention_heads (`int`, optional, defaults to 12):
24
+ Number of attention heads for each attention layer in the Transformer encoder.
25
+ intermediate_size (`int`, optional, defaults to 3072):
26
+ The dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
27
+ hidden_act (`str` or `function`, optional, defaults to "gelu"):
28
+ The non-linear activation function (function or string) in the encoder and pooler.
29
+ hidden_dropout_prob (`float`, optional, defaults to 0.1):
30
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
31
+ attention_probs_dropout_prob (`float`, optional, defaults to 0.1):
32
+ The dropout ratio for the attention probabilities.
33
+ max_position_embeddings (`int`, optional, defaults to 512):
34
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
35
+ (e.g., 512 or 1024 or 2048).
36
+ type_vocab_size (`int`, optional, defaults to 2):
37
+ The vocabulary size of the *token_type_ids* passed into [`NezhaModel`].
38
+ initializer_range (`float`, optional, defaults to 0.02):
39
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
40
+ layer_norm_eps (`float`, optional, defaults to 1e-12):
41
+ The epsilon used by the layer normalization layers.
42
+ classifier_dropout (`float`, optional, defaults to 0.1):
43
+ The dropout ratio for attached classifiers.
44
+ is_decoder (`bool`, *optional*, defaults to `False`):
45
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
46
+
47
+ Example:
48
+
49
+ ```python
50
+ >>> from transformers import NezhaConfig, NezhaModel
51
+
52
+ >>> # Initializing an Nezha configuration
53
+ >>> configuration = NezhaConfig()
54
+
55
+ >>> # Initializing a model (with random weights) from the Nezha-base style configuration model
56
+ >>> model = NezhaModel(configuration)
57
+
58
+ >>> # Accessing the model configuration
59
+ >>> configuration = model.config
60
+ ```"""
61
+
62
+ model_type = "nezha"
63
+
64
+ def __init__(
65
+ self,
66
+ vocab_size=21128,
67
+ hidden_size=768,
68
+ num_hidden_layers=12,
69
+ num_attention_heads=12,
70
+ intermediate_size=3072,
71
+ hidden_act="gelu",
72
+ hidden_dropout_prob=0.1,
73
+ attention_probs_dropout_prob=0.1,
74
+ max_position_embeddings=512,
75
+ max_relative_position=64,
76
+ type_vocab_size=2,
77
+ initializer_range=0.02,
78
+ layer_norm_eps=1e-12,
79
+ classifier_dropout=0.1,
80
+ pad_token_id=0,
81
+ bos_token_id=2,
82
+ eos_token_id=3,
83
+ use_cache=True,
84
+ **kwargs,
85
+ ):
86
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
87
+
88
+ self.vocab_size = vocab_size
89
+ self.hidden_size = hidden_size
90
+ self.num_hidden_layers = num_hidden_layers
91
+ self.num_attention_heads = num_attention_heads
92
+ self.hidden_act = hidden_act
93
+ self.intermediate_size = intermediate_size
94
+ self.hidden_dropout_prob = hidden_dropout_prob
95
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
96
+ self.max_position_embeddings = max_position_embeddings
97
+ self.max_relative_position = max_relative_position
98
+ self.type_vocab_size = type_vocab_size
99
+ self.initializer_range = initializer_range
100
+ self.layer_norm_eps = layer_norm_eps
101
+ self.classifier_dropout = classifier_dropout
102
+ self.use_cache = use_cache
103
+
104
+
105
+ __all__ = ["NezhaConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/nezha/modeling_nezha.py ADDED
@@ -0,0 +1,1689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch Nezha model."""
16
+
17
+ import math
18
+ import os
19
+ import warnings
20
+ from dataclasses import dataclass
21
+ from typing import Optional, Union
22
+
23
+ import torch
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ....activations import ACT2FN
28
+ from ....cache_utils import Cache
29
+ from ....modeling_layers import GradientCheckpointingLayer
30
+ from ....modeling_outputs import (
31
+ BaseModelOutputWithPastAndCrossAttentions,
32
+ BaseModelOutputWithPoolingAndCrossAttentions,
33
+ MaskedLMOutput,
34
+ MultipleChoiceModelOutput,
35
+ NextSentencePredictorOutput,
36
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutput,
38
+ TokenClassifierOutput,
39
+ )
40
+ from ....modeling_utils import PreTrainedModel
41
+ from ....pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
42
+ from ....utils import (
43
+ ModelOutput,
44
+ add_code_sample_docstrings,
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from ....utils.deprecation import deprecate_kwarg
51
+ from .configuration_nezha import NezhaConfig
52
+
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+ _CHECKPOINT_FOR_DOC = "sijunhe/nezha-cn-base"
57
+ _CONFIG_FOR_DOC = "NezhaConfig"
58
+
59
+
60
+ def load_tf_weights_in_nezha(model, config, tf_checkpoint_path):
61
+ """Load tf checkpoints in a pytorch model."""
62
+ try:
63
+ import re
64
+
65
+ import numpy as np
66
+ import tensorflow as tf
67
+ except ImportError:
68
+ logger.error(
69
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
70
+ "https://www.tensorflow.org/install/ for installation instructions."
71
+ )
72
+ raise
73
+ tf_path = os.path.abspath(tf_checkpoint_path)
74
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
75
+ # Load weights from TF model
76
+ init_vars = tf.train.list_variables(tf_path)
77
+ names = []
78
+ arrays = []
79
+ for name, shape in init_vars:
80
+ logger.info(f"Loading TF weight {name} with shape {shape}")
81
+ array = tf.train.load_variable(tf_path, name)
82
+ names.append(name)
83
+ arrays.append(array)
84
+
85
+ for name, array in zip(names, arrays):
86
+ name = name.split("/")
87
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
88
+ # which are not required for using pretrained model
89
+ if any(
90
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
91
+ for n in name
92
+ ):
93
+ logger.info(f"Skipping {'/'.join(name)}")
94
+ continue
95
+ pointer = model
96
+ for m_name in name:
97
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
98
+ scope_names = re.split(r"_(\d+)", m_name)
99
+ else:
100
+ scope_names = [m_name]
101
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
102
+ pointer = getattr(pointer, "weight")
103
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
104
+ pointer = getattr(pointer, "bias")
105
+ elif scope_names[0] == "output_weights":
106
+ pointer = getattr(pointer, "weight")
107
+ elif scope_names[0] == "squad":
108
+ pointer = getattr(pointer, "classifier")
109
+ else:
110
+ try:
111
+ pointer = getattr(pointer, scope_names[0])
112
+ except AttributeError:
113
+ logger.info(f"Skipping {'/'.join(name)}")
114
+ continue
115
+ if len(scope_names) >= 2:
116
+ num = int(scope_names[1])
117
+ pointer = pointer[num]
118
+ if m_name[-11:] == "_embeddings":
119
+ pointer = getattr(pointer, "weight")
120
+ elif m_name == "kernel":
121
+ array = np.transpose(array)
122
+ try:
123
+ if pointer.shape != array.shape:
124
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
125
+ except AssertionError as e:
126
+ e.args += (pointer.shape, array.shape)
127
+ raise
128
+ logger.info(f"Initialize PyTorch weight {name}")
129
+ pointer.data = torch.from_numpy(array)
130
+ return model
131
+
132
+
133
+ class NezhaRelativePositionsEncoding(nn.Module):
134
+ """Implement the Functional Relative Position Encoding"""
135
+
136
+ def __init__(self, length, depth, max_relative_position=127):
137
+ super().__init__()
138
+ vocab_size = max_relative_position * 2 + 1
139
+ range_vec = torch.arange(length)
140
+ range_mat = range_vec.repeat(length).view(length, length)
141
+ distance_mat = range_mat - torch.t(range_mat)
142
+ distance_mat_clipped = torch.clamp(distance_mat, -max_relative_position, max_relative_position)
143
+ final_mat = distance_mat_clipped + max_relative_position
144
+
145
+ embeddings_table = torch.zeros(vocab_size, depth)
146
+ position = torch.arange(0, vocab_size, dtype=torch.int64).float().unsqueeze(1)
147
+ div_term = torch.exp(torch.arange(0, depth, 2).float() * (-math.log(10000.0) / depth))
148
+ embeddings_table[:, 0::2] = torch.sin(position * div_term)
149
+ embeddings_table[:, 1::2] = torch.cos(position * div_term)
150
+
151
+ flat_relative_positions_matrix = final_mat.view(-1)
152
+ one_hot_relative_positions_matrix = torch.nn.functional.one_hot(
153
+ flat_relative_positions_matrix, num_classes=vocab_size
154
+ ).float()
155
+ positions_encoding = torch.matmul(one_hot_relative_positions_matrix, embeddings_table)
156
+ my_shape = list(final_mat.size())
157
+ my_shape.append(depth)
158
+ positions_encoding = positions_encoding.view(my_shape)
159
+ self.register_buffer("positions_encoding", positions_encoding, persistent=False)
160
+
161
+ def forward(self, length):
162
+ return self.positions_encoding[:length, :length, :]
163
+
164
+
165
+ class NezhaEmbeddings(nn.Module):
166
+ """Construct the embeddings from word and token_type embeddings."""
167
+
168
+ def __init__(self, config):
169
+ super().__init__()
170
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
171
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
172
+
173
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
174
+ # any TensorFlow checkpoint file
175
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
176
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
177
+ self.register_buffer(
178
+ "token_type_ids", torch.zeros((1, config.max_position_embeddings), dtype=torch.long), persistent=False
179
+ )
180
+
181
+ def forward(
182
+ self,
183
+ input_ids: Optional[torch.LongTensor] = None,
184
+ token_type_ids: Optional[torch.LongTensor] = None,
185
+ inputs_embeds: Optional[torch.FloatTensor] = None,
186
+ ) -> torch.Tensor:
187
+ if input_ids is not None:
188
+ input_shape = input_ids.size()
189
+ else:
190
+ input_shape = inputs_embeds.size()[:-1]
191
+
192
+ seq_length = input_shape[1]
193
+
194
+ if inputs_embeds is None:
195
+ inputs_embeds = self.word_embeddings(input_ids)
196
+
197
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
198
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
199
+ # issue #5664
200
+ if token_type_ids is None:
201
+ if hasattr(self, "token_type_ids"):
202
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
203
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
204
+ token_type_ids = buffered_token_type_ids_expanded
205
+ else:
206
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=inputs_embeds.device)
207
+
208
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
209
+
210
+ embeddings = inputs_embeds + token_type_embeddings
211
+ embeddings = self.LayerNorm(embeddings)
212
+ embeddings = self.dropout(embeddings)
213
+ return embeddings
214
+
215
+
216
+ class NezhaSelfAttention(nn.Module):
217
+ def __init__(self, config):
218
+ super().__init__()
219
+ if config.hidden_size % config.num_attention_heads != 0:
220
+ raise ValueError(
221
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
222
+ f"heads ({config.num_attention_heads})"
223
+ )
224
+
225
+ self.num_attention_heads = config.num_attention_heads
226
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
227
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
228
+
229
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
230
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
231
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
232
+
233
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
234
+ self.relative_positions_encoding = NezhaRelativePositionsEncoding(
235
+ length=config.max_position_embeddings,
236
+ depth=self.attention_head_size,
237
+ max_relative_position=config.max_relative_position,
238
+ )
239
+ self.is_decoder = config.is_decoder
240
+
241
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
242
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
243
+ x = x.view(new_x_shape)
244
+ return x.permute(0, 2, 1, 3)
245
+
246
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
247
+ def forward(
248
+ self,
249
+ hidden_states: torch.Tensor,
250
+ attention_mask: Optional[torch.FloatTensor] = None,
251
+ head_mask: Optional[torch.FloatTensor] = None,
252
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
253
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
254
+ past_key_values: Optional[Cache] = None,
255
+ output_attentions: Optional[bool] = False,
256
+ ) -> tuple[torch.Tensor]:
257
+ mixed_query_layer = self.query(hidden_states)
258
+
259
+ # If this is instantiated as a cross-attention module, the keys
260
+ # and values come from an encoder; the attention mask needs to be
261
+ # such that the encoder's padding tokens are not attended to.
262
+ is_cross_attention = encoder_hidden_states is not None
263
+
264
+ if is_cross_attention and past_key_values is not None:
265
+ # reuse k,v, cross_attentions
266
+ key_layer = past_key_values[0]
267
+ value_layer = past_key_values[1]
268
+ attention_mask = encoder_attention_mask
269
+ elif is_cross_attention:
270
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
271
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
272
+ attention_mask = encoder_attention_mask
273
+ elif past_key_values is not None:
274
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
275
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
276
+ key_layer = torch.cat([past_key_values[0], key_layer], dim=2)
277
+ value_layer = torch.cat([past_key_values[1], value_layer], dim=2)
278
+ else:
279
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
280
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
281
+
282
+ query_layer = self.transpose_for_scores(mixed_query_layer)
283
+
284
+ if self.is_decoder:
285
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
286
+ # Further calls to cross_attention layer can then reuse all cross-attention
287
+ # key/value_states (first "if" case)
288
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
289
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
290
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
291
+ # if encoder bi-directional self-attention `past_key_values` is always `None`
292
+ past_key_values = (key_layer, value_layer)
293
+
294
+ # Take the dot product between "query" and "key" to get the raw attention scores.
295
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
296
+
297
+ batch_size, num_attention_heads, from_seq_length, to_seq_length = attention_scores.size()
298
+ relations_keys = self.relative_positions_encoding(to_seq_length)
299
+ query_layer_t = query_layer.permute(2, 0, 1, 3)
300
+
301
+ query_layer_r = query_layer_t.contiguous().view(
302
+ from_seq_length, batch_size * num_attention_heads, self.attention_head_size
303
+ )
304
+ key_position_scores = torch.matmul(query_layer_r, relations_keys.permute(0, 2, 1))
305
+ key_position_scores_r = key_position_scores.view(
306
+ from_seq_length, batch_size, num_attention_heads, from_seq_length
307
+ )
308
+ key_position_scores_r_t = key_position_scores_r.permute(1, 2, 0, 3)
309
+ attention_scores = attention_scores + key_position_scores_r_t
310
+
311
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
312
+
313
+ if attention_mask is not None:
314
+ # Apply the attention mask is (precomputed for all layers in NezhaModel forward() function)
315
+ attention_scores = attention_scores + attention_mask
316
+
317
+ # Normalize the attention scores to probabilities.
318
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
319
+
320
+ # This is actually dropping out entire tokens to attend to, which might
321
+ # seem a bit unusual, but is taken from the original Transformer paper.
322
+ attention_probs = self.dropout(attention_probs)
323
+
324
+ # Mask heads if we want to
325
+ if head_mask is not None:
326
+ attention_probs = attention_probs * head_mask
327
+
328
+ context_layer = torch.matmul(attention_probs, value_layer)
329
+ relations_values = self.relative_positions_encoding(to_seq_length)
330
+ attention_probs_t = attention_probs.permute(2, 0, 1, 3)
331
+ attentions_probs_r = attention_probs_t.contiguous().view(
332
+ from_seq_length, batch_size * num_attention_heads, to_seq_length
333
+ )
334
+ value_position_scores = torch.matmul(attentions_probs_r, relations_values)
335
+ value_position_scores_r = value_position_scores.view(
336
+ from_seq_length, batch_size, num_attention_heads, self.attention_head_size
337
+ )
338
+ value_position_scores_r_t = value_position_scores_r.permute(1, 2, 0, 3)
339
+ context_layer = context_layer + value_position_scores_r_t
340
+
341
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
342
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
343
+ context_layer = context_layer.view(new_context_layer_shape)
344
+
345
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
346
+
347
+ if self.is_decoder:
348
+ outputs = outputs + (past_key_values,)
349
+ return outputs
350
+
351
+
352
+ class NezhaSelfOutput(nn.Module):
353
+ def __init__(self, config):
354
+ super().__init__()
355
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
356
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
357
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
358
+
359
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
360
+ hidden_states = self.dense(hidden_states)
361
+ hidden_states = self.dropout(hidden_states)
362
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
363
+ return hidden_states
364
+
365
+
366
+ class NezhaAttention(nn.Module):
367
+ def __init__(self, config):
368
+ super().__init__()
369
+ self.self = NezhaSelfAttention(config)
370
+ self.output = NezhaSelfOutput(config)
371
+ self.pruned_heads = set()
372
+
373
+ def prune_heads(self, heads):
374
+ if len(heads) == 0:
375
+ return
376
+ heads, index = find_pruneable_heads_and_indices(
377
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
378
+ )
379
+
380
+ # Prune linear layers
381
+ self.self.query = prune_linear_layer(self.self.query, index)
382
+ self.self.key = prune_linear_layer(self.self.key, index)
383
+ self.self.value = prune_linear_layer(self.self.value, index)
384
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
385
+
386
+ # Update hyper params and store pruned heads
387
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
388
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
389
+ self.pruned_heads = self.pruned_heads.union(heads)
390
+
391
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
392
+ def forward(
393
+ self,
394
+ hidden_states: torch.Tensor,
395
+ attention_mask: Optional[torch.FloatTensor] = None,
396
+ head_mask: Optional[torch.FloatTensor] = None,
397
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
398
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
399
+ past_key_values: Optional[Cache] = None,
400
+ output_attentions: Optional[bool] = False,
401
+ ) -> tuple[torch.Tensor]:
402
+ self_outputs = self.self(
403
+ hidden_states,
404
+ attention_mask,
405
+ head_mask,
406
+ encoder_hidden_states,
407
+ encoder_attention_mask,
408
+ past_key_values,
409
+ output_attentions,
410
+ )
411
+ attention_output = self.output(self_outputs[0], hidden_states)
412
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
413
+ return outputs
414
+
415
+
416
+ class NezhaIntermediate(nn.Module):
417
+ def __init__(self, config):
418
+ super().__init__()
419
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
420
+ if isinstance(config.hidden_act, str):
421
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
422
+ else:
423
+ self.intermediate_act_fn = config.hidden_act
424
+
425
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
426
+ hidden_states = self.dense(hidden_states)
427
+ hidden_states = self.intermediate_act_fn(hidden_states)
428
+ return hidden_states
429
+
430
+
431
+ class NezhaOutput(nn.Module):
432
+ def __init__(self, config):
433
+ super().__init__()
434
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
435
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
436
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
437
+
438
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
439
+ hidden_states = self.dense(hidden_states)
440
+ hidden_states = self.dropout(hidden_states)
441
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
442
+ return hidden_states
443
+
444
+
445
+ class NezhaLayer(GradientCheckpointingLayer):
446
+ def __init__(self, config):
447
+ super().__init__()
448
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
449
+ self.seq_len_dim = 1
450
+ self.attention = NezhaAttention(config)
451
+ self.is_decoder = config.is_decoder
452
+ self.add_cross_attention = config.add_cross_attention
453
+ if self.add_cross_attention:
454
+ if not self.is_decoder:
455
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
456
+ self.crossattention = NezhaAttention(config)
457
+ self.intermediate = NezhaIntermediate(config)
458
+ self.output = NezhaOutput(config)
459
+
460
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
461
+ def forward(
462
+ self,
463
+ hidden_states: torch.Tensor,
464
+ attention_mask: Optional[torch.FloatTensor] = None,
465
+ head_mask: Optional[torch.FloatTensor] = None,
466
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
467
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
468
+ past_key_values: Optional[Cache] = None,
469
+ output_attentions: Optional[bool] = False,
470
+ ) -> tuple[torch.Tensor]:
471
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
472
+ self_attn_past_key_value = past_key_values[:2] if past_key_values is not None else None
473
+ self_attention_outputs = self.attention(
474
+ hidden_states,
475
+ attention_mask,
476
+ head_mask,
477
+ output_attentions=output_attentions,
478
+ past_key_values=self_attn_past_key_value,
479
+ )
480
+ attention_output = self_attention_outputs[0]
481
+
482
+ # if decoder, the last output is tuple of self-attn cache
483
+ if self.is_decoder:
484
+ outputs = self_attention_outputs[1:-1]
485
+ present_key_value = self_attention_outputs[-1]
486
+ else:
487
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
488
+
489
+ cross_attn_present_key_value = None
490
+ if self.is_decoder and encoder_hidden_states is not None:
491
+ if not hasattr(self, "crossattention"):
492
+ raise ValueError(
493
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
494
+ " by setting `config.add_cross_attention=True`"
495
+ )
496
+
497
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_values tuple
498
+ cross_attn_past_key_value = past_key_values[-2:] if past_key_values is not None else None
499
+ cross_attention_outputs = self.crossattention(
500
+ attention_output,
501
+ attention_mask,
502
+ head_mask,
503
+ encoder_hidden_states,
504
+ encoder_attention_mask,
505
+ cross_attn_past_key_value,
506
+ output_attentions,
507
+ )
508
+ attention_output = cross_attention_outputs[0]
509
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
510
+
511
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
512
+ cross_attn_present_key_value = cross_attention_outputs[-1]
513
+ present_key_value = present_key_value + cross_attn_present_key_value
514
+
515
+ layer_output = apply_chunking_to_forward(
516
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
517
+ )
518
+ outputs = (layer_output,) + outputs
519
+
520
+ # if decoder, return the attn key/values as the last output
521
+ if self.is_decoder:
522
+ outputs = outputs + (present_key_value,)
523
+
524
+ return outputs
525
+
526
+ def feed_forward_chunk(self, attention_output):
527
+ intermediate_output = self.intermediate(attention_output)
528
+ layer_output = self.output(intermediate_output, attention_output)
529
+ return layer_output
530
+
531
+
532
+ class NezhaEncoder(nn.Module):
533
+ def __init__(self, config):
534
+ super().__init__()
535
+ self.config = config
536
+ self.layer = nn.ModuleList([NezhaLayer(config) for _ in range(config.num_hidden_layers)])
537
+ self.gradient_checkpointing = False
538
+
539
+ def forward(
540
+ self,
541
+ hidden_states: torch.Tensor,
542
+ attention_mask: Optional[torch.FloatTensor] = None,
543
+ head_mask: Optional[torch.FloatTensor] = None,
544
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
545
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
546
+ past_key_values: Optional[Cache] = None,
547
+ use_cache: Optional[bool] = None,
548
+ output_attentions: Optional[bool] = False,
549
+ output_hidden_states: Optional[bool] = False,
550
+ return_dict: Optional[bool] = True,
551
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
552
+ all_hidden_states = () if output_hidden_states else None
553
+ all_self_attentions = () if output_attentions else None
554
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
555
+
556
+ if self.gradient_checkpointing and self.training:
557
+ if use_cache:
558
+ logger.warning_once(
559
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
560
+ )
561
+ use_cache = False
562
+
563
+ next_decoder_cache = () if use_cache else None
564
+ for i, layer_module in enumerate(self.layer):
565
+ if output_hidden_states:
566
+ all_hidden_states = all_hidden_states + (hidden_states,)
567
+
568
+ layer_head_mask = head_mask[i] if head_mask is not None else None
569
+
570
+ layer_outputs = layer_module(
571
+ hidden_states,
572
+ attention_mask,
573
+ layer_head_mask,
574
+ encoder_hidden_states,
575
+ encoder_attention_mask,
576
+ past_key_values[i] if past_key_values is not None else None,
577
+ output_attentions,
578
+ )
579
+
580
+ hidden_states = layer_outputs[0]
581
+ if use_cache:
582
+ next_decoder_cache += (layer_outputs[-1],)
583
+ if output_attentions:
584
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
585
+ if self.config.add_cross_attention:
586
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
587
+
588
+ if output_hidden_states:
589
+ all_hidden_states = all_hidden_states + (hidden_states,)
590
+
591
+ if not return_dict:
592
+ return tuple(
593
+ v
594
+ for v in [
595
+ hidden_states,
596
+ next_decoder_cache,
597
+ all_hidden_states,
598
+ all_self_attentions,
599
+ all_cross_attentions,
600
+ ]
601
+ if v is not None
602
+ )
603
+ return BaseModelOutputWithPastAndCrossAttentions(
604
+ last_hidden_state=hidden_states,
605
+ past_key_values=next_decoder_cache,
606
+ hidden_states=all_hidden_states,
607
+ attentions=all_self_attentions,
608
+ cross_attentions=all_cross_attentions,
609
+ )
610
+
611
+
612
+ class NezhaPooler(nn.Module):
613
+ def __init__(self, config):
614
+ super().__init__()
615
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
616
+ self.activation = nn.Tanh()
617
+
618
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
619
+ # We "pool" the model by simply taking the hidden state corresponding
620
+ # to the first token.
621
+ first_token_tensor = hidden_states[:, 0]
622
+ pooled_output = self.dense(first_token_tensor)
623
+ pooled_output = self.activation(pooled_output)
624
+ return pooled_output
625
+
626
+
627
+ class NezhaPredictionHeadTransform(nn.Module):
628
+ def __init__(self, config):
629
+ super().__init__()
630
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
631
+ if isinstance(config.hidden_act, str):
632
+ self.transform_act_fn = ACT2FN[config.hidden_act]
633
+ else:
634
+ self.transform_act_fn = config.hidden_act
635
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
636
+
637
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
638
+ hidden_states = self.dense(hidden_states)
639
+ hidden_states = self.transform_act_fn(hidden_states)
640
+ hidden_states = self.LayerNorm(hidden_states)
641
+ return hidden_states
642
+
643
+
644
+ class NezhaLMPredictionHead(nn.Module):
645
+ def __init__(self, config):
646
+ super().__init__()
647
+ self.transform = NezhaPredictionHeadTransform(config)
648
+
649
+ # The output weights are the same as the input embeddings, but there is
650
+ # an output-only bias for each token.
651
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
652
+
653
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
654
+
655
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
656
+ self.decoder.bias = self.bias
657
+
658
+ def _tie_weights(self):
659
+ self.decoder.bias = self.bias
660
+
661
+ def forward(self, hidden_states):
662
+ hidden_states = self.transform(hidden_states)
663
+ hidden_states = self.decoder(hidden_states)
664
+ return hidden_states
665
+
666
+
667
+ class NezhaOnlyMLMHead(nn.Module):
668
+ def __init__(self, config):
669
+ super().__init__()
670
+ self.predictions = NezhaLMPredictionHead(config)
671
+
672
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
673
+ prediction_scores = self.predictions(sequence_output)
674
+ return prediction_scores
675
+
676
+
677
+ class NezhaOnlyNSPHead(nn.Module):
678
+ def __init__(self, config):
679
+ super().__init__()
680
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
681
+
682
+ def forward(self, pooled_output):
683
+ seq_relationship_score = self.seq_relationship(pooled_output)
684
+ return seq_relationship_score
685
+
686
+
687
+ class NezhaPreTrainingHeads(nn.Module):
688
+ def __init__(self, config):
689
+ super().__init__()
690
+ self.predictions = NezhaLMPredictionHead(config)
691
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
692
+
693
+ def forward(self, sequence_output, pooled_output):
694
+ prediction_scores = self.predictions(sequence_output)
695
+ seq_relationship_score = self.seq_relationship(pooled_output)
696
+ return prediction_scores, seq_relationship_score
697
+
698
+
699
+ class NezhaPreTrainedModel(PreTrainedModel):
700
+ """
701
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
702
+ models.
703
+ """
704
+
705
+ config: NezhaConfig
706
+ load_tf_weights = load_tf_weights_in_nezha
707
+ base_model_prefix = "nezha"
708
+ supports_gradient_checkpointing = True
709
+
710
+ def _init_weights(self, module):
711
+ """Initialize the weights"""
712
+ if isinstance(module, nn.Linear):
713
+ # Slightly different from the TF version which uses truncated_normal for initialization
714
+ # cf https://github.com/pytorch/pytorch/pull/5617
715
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
716
+ if module.bias is not None:
717
+ module.bias.data.zero_()
718
+ elif isinstance(module, nn.Embedding):
719
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
720
+ if module.padding_idx is not None:
721
+ module.weight.data[module.padding_idx].zero_()
722
+ elif isinstance(module, nn.LayerNorm):
723
+ module.bias.data.zero_()
724
+ module.weight.data.fill_(1.0)
725
+
726
+
727
+ @dataclass
728
+ class NezhaForPreTrainingOutput(ModelOutput):
729
+ """
730
+ Output type of [`NezhaForPreTraining`].
731
+
732
+ Args:
733
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
734
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
735
+ (classification) loss.
736
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
737
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
738
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
739
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
740
+ before SoftMax).
741
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
742
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
743
+ shape `(batch_size, sequence_length, hidden_size)`.
744
+
745
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
746
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
747
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
748
+ sequence_length)`.
749
+
750
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
751
+ heads.
752
+ """
753
+
754
+ loss: Optional[torch.FloatTensor] = None
755
+ prediction_logits: Optional[torch.FloatTensor] = None
756
+ seq_relationship_logits: Optional[torch.FloatTensor] = None
757
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
758
+ attentions: Optional[tuple[torch.FloatTensor]] = None
759
+
760
+
761
+ NEZHA_START_DOCSTRING = r"""
762
+
763
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
764
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
765
+ etc.)
766
+
767
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
768
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
769
+ and behavior.
770
+
771
+ Parameters:
772
+ config ([`NezhaConfig`]): Model configuration class with all the parameters of the model.
773
+ Initializing with a config file does not load the weights associated with the model, only the
774
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
775
+ """
776
+
777
+ NEZHA_INPUTS_DOCSTRING = r"""
778
+ Args:
779
+ input_ids (`torch.LongTensor` of shape `({0})`):
780
+ Indices of input sequence tokens in the vocabulary.
781
+
782
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
783
+ [`PreTrainedTokenizer.__call__`] for details.
784
+
785
+ [What are input IDs?](../glossary#input-ids)
786
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
787
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
788
+
789
+ - 1 for tokens that are **not masked**,
790
+ - 0 for tokens that are **masked**.
791
+
792
+ [What are attention masks?](../glossary#attention-mask)
793
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
794
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
795
+ 1]`:
796
+
797
+ - 0 corresponds to a *sentence A* token,
798
+ - 1 corresponds to a *sentence B* token.
799
+
800
+ [What are token type IDs?](../glossary#token-type-ids)
801
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
802
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
803
+
804
+ - 1 indicates the head is **not masked**,
805
+ - 0 indicates the head is **masked**.
806
+
807
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
808
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
809
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
810
+ model's internal embedding lookup matrix.
811
+ output_attentions (`bool`, *optional*):
812
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
813
+ tensors for more detail.
814
+ output_hidden_states (`bool`, *optional*):
815
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
816
+ more detail.
817
+ return_dict (`bool`, *optional*):
818
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
819
+ """
820
+
821
+
822
+ @add_start_docstrings(
823
+ "The bare Nezha Model transformer outputting raw hidden-states without any specific head on top.",
824
+ NEZHA_START_DOCSTRING,
825
+ )
826
+ class NezhaModel(NezhaPreTrainedModel):
827
+ """
828
+
829
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
830
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
831
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
832
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
833
+
834
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
835
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
836
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
837
+ """
838
+
839
+ def __init__(self, config, add_pooling_layer=True):
840
+ super().__init__(config)
841
+ self.config = config
842
+
843
+ self.embeddings = NezhaEmbeddings(config)
844
+ self.encoder = NezhaEncoder(config)
845
+
846
+ self.pooler = NezhaPooler(config) if add_pooling_layer else None
847
+
848
+ # Initialize weights and apply final processing
849
+ self.post_init()
850
+
851
+ def get_input_embeddings(self):
852
+ return self.embeddings.word_embeddings
853
+
854
+ def set_input_embeddings(self, value):
855
+ self.embeddings.word_embeddings = value
856
+
857
+ def _prune_heads(self, heads_to_prune):
858
+ """
859
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
860
+ class PreTrainedModel
861
+ """
862
+ for layer, heads in heads_to_prune.items():
863
+ self.encoder.layer[layer].attention.prune_heads(heads)
864
+
865
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
866
+ @add_code_sample_docstrings(
867
+ checkpoint=_CHECKPOINT_FOR_DOC,
868
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
869
+ config_class=_CONFIG_FOR_DOC,
870
+ )
871
+ def forward(
872
+ self,
873
+ input_ids: Optional[torch.Tensor] = None,
874
+ attention_mask: Optional[torch.Tensor] = None,
875
+ token_type_ids: Optional[torch.Tensor] = None,
876
+ head_mask: Optional[torch.Tensor] = None,
877
+ inputs_embeds: Optional[torch.Tensor] = None,
878
+ encoder_hidden_states: Optional[torch.Tensor] = None,
879
+ encoder_attention_mask: Optional[torch.Tensor] = None,
880
+ past_key_values: Optional[Cache] = None,
881
+ use_cache: Optional[bool] = None,
882
+ output_attentions: Optional[bool] = None,
883
+ output_hidden_states: Optional[bool] = None,
884
+ return_dict: Optional[bool] = None,
885
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
886
+ r"""
887
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
888
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
889
+ the model is configured as a decoder.
890
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
891
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
892
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
893
+
894
+ - 1 for tokens that are **not masked**,
895
+ - 0 for tokens that are **masked**.
896
+ 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)`):
897
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
898
+
899
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
900
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
901
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
902
+ use_cache (`bool`, *optional*):
903
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
904
+ `past_key_values`).
905
+ """
906
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
907
+ output_hidden_states = (
908
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
909
+ )
910
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
911
+
912
+ if self.config.is_decoder:
913
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
914
+ else:
915
+ use_cache = False
916
+
917
+ if input_ids is not None and inputs_embeds is not None:
918
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
919
+ elif input_ids is not None:
920
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
921
+ input_shape = input_ids.size()
922
+ elif inputs_embeds is not None:
923
+ input_shape = inputs_embeds.size()[:-1]
924
+ else:
925
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
926
+
927
+ batch_size, seq_length = input_shape
928
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
929
+
930
+ # past_key_values_length
931
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
932
+
933
+ if attention_mask is None:
934
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
935
+
936
+ if token_type_ids is None:
937
+ if hasattr(self.embeddings, "token_type_ids"):
938
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
939
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
940
+ token_type_ids = buffered_token_type_ids_expanded
941
+ else:
942
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
943
+
944
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
945
+ # ourselves in which case we just need to make it broadcastable to all heads.
946
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
947
+
948
+ # If a 2D or 3D attention mask is provided for the cross-attention
949
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
950
+ if self.config.is_decoder and encoder_hidden_states is not None:
951
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
952
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
953
+ if encoder_attention_mask is None:
954
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
955
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
956
+ else:
957
+ encoder_extended_attention_mask = None
958
+
959
+ # Prepare head mask if needed
960
+ # 1.0 in head_mask indicate we keep the head
961
+ # attention_probs has shape bsz x n_heads x N x N
962
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
963
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
964
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
965
+
966
+ embedding_output = self.embeddings(
967
+ input_ids=input_ids,
968
+ token_type_ids=token_type_ids,
969
+ inputs_embeds=inputs_embeds,
970
+ )
971
+ encoder_outputs = self.encoder(
972
+ embedding_output,
973
+ attention_mask=extended_attention_mask,
974
+ head_mask=head_mask,
975
+ encoder_hidden_states=encoder_hidden_states,
976
+ encoder_attention_mask=encoder_extended_attention_mask,
977
+ past_key_values=past_key_values,
978
+ use_cache=use_cache,
979
+ output_attentions=output_attentions,
980
+ output_hidden_states=output_hidden_states,
981
+ return_dict=return_dict,
982
+ )
983
+ sequence_output = encoder_outputs[0]
984
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
985
+
986
+ if not return_dict:
987
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
988
+
989
+ return BaseModelOutputWithPoolingAndCrossAttentions(
990
+ last_hidden_state=sequence_output,
991
+ pooler_output=pooled_output,
992
+ past_key_values=encoder_outputs.past_key_values,
993
+ hidden_states=encoder_outputs.hidden_states,
994
+ attentions=encoder_outputs.attentions,
995
+ cross_attentions=encoder_outputs.cross_attentions,
996
+ )
997
+
998
+
999
+ @add_start_docstrings(
1000
+ """
1001
+ Nezha Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
1002
+ sentence prediction (classification)` head.
1003
+ """,
1004
+ NEZHA_START_DOCSTRING,
1005
+ )
1006
+ class NezhaForPreTraining(NezhaPreTrainedModel):
1007
+ _tied_weights_keys = ["cls.predictions.decoder"]
1008
+
1009
+ def __init__(self, config):
1010
+ super().__init__(config)
1011
+
1012
+ self.nezha = NezhaModel(config)
1013
+ self.cls = NezhaPreTrainingHeads(config)
1014
+
1015
+ # Initialize weights and apply final processing
1016
+ self.post_init()
1017
+
1018
+ def get_output_embeddings(self):
1019
+ return self.cls.predictions.decoder
1020
+
1021
+ def set_output_embeddings(self, new_embeddings):
1022
+ self.cls.predictions.decoder = new_embeddings
1023
+ self.cls.predictions.bias = new_embeddings.bias
1024
+
1025
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1026
+ @replace_return_docstrings(output_type=NezhaForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1027
+ def forward(
1028
+ self,
1029
+ input_ids: Optional[torch.Tensor] = None,
1030
+ attention_mask: Optional[torch.Tensor] = None,
1031
+ token_type_ids: Optional[torch.Tensor] = None,
1032
+ head_mask: Optional[torch.Tensor] = None,
1033
+ inputs_embeds: Optional[torch.Tensor] = None,
1034
+ labels: Optional[torch.Tensor] = None,
1035
+ next_sentence_label: Optional[torch.Tensor] = None,
1036
+ output_attentions: Optional[bool] = None,
1037
+ output_hidden_states: Optional[bool] = None,
1038
+ return_dict: Optional[bool] = None,
1039
+ ) -> Union[tuple[torch.Tensor], NezhaForPreTrainingOutput]:
1040
+ r"""
1041
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1042
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1043
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
1044
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1045
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1046
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
1047
+ pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
1048
+
1049
+ - 0 indicates sequence B is a continuation of sequence A,
1050
+ - 1 indicates sequence B is a random sequence.
1051
+ kwargs (`dict[str, any]`, optional, defaults to *{}*):
1052
+ Used to hide legacy arguments that have been deprecated.
1053
+
1054
+ Returns:
1055
+
1056
+ Example:
1057
+
1058
+ ```python
1059
+ >>> from transformers import AutoTokenizer, NezhaForPreTraining
1060
+ >>> import torch
1061
+
1062
+ >>> tokenizer = AutoTokenizer.from_pretrained("sijunhe/nezha-cn-base")
1063
+ >>> model = NezhaForPreTraining.from_pretrained("sijunhe/nezha-cn-base")
1064
+
1065
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1066
+ >>> outputs = model(**inputs)
1067
+
1068
+ >>> prediction_logits = outputs.prediction_logits
1069
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
1070
+ ```
1071
+ """
1072
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1073
+
1074
+ outputs = self.nezha(
1075
+ input_ids,
1076
+ attention_mask=attention_mask,
1077
+ token_type_ids=token_type_ids,
1078
+ head_mask=head_mask,
1079
+ inputs_embeds=inputs_embeds,
1080
+ output_attentions=output_attentions,
1081
+ output_hidden_states=output_hidden_states,
1082
+ return_dict=return_dict,
1083
+ )
1084
+
1085
+ sequence_output, pooled_output = outputs[:2]
1086
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
1087
+
1088
+ total_loss = None
1089
+ if labels is not None and next_sentence_label is not None:
1090
+ loss_fct = CrossEntropyLoss()
1091
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1092
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
1093
+ total_loss = masked_lm_loss + next_sentence_loss
1094
+
1095
+ if not return_dict:
1096
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1097
+ return ((total_loss,) + output) if total_loss is not None else output
1098
+
1099
+ return NezhaForPreTrainingOutput(
1100
+ loss=total_loss,
1101
+ prediction_logits=prediction_scores,
1102
+ seq_relationship_logits=seq_relationship_score,
1103
+ hidden_states=outputs.hidden_states,
1104
+ attentions=outputs.attentions,
1105
+ )
1106
+
1107
+
1108
+ @add_start_docstrings("""Nezha Model with a `language modeling` head on top.""", NEZHA_START_DOCSTRING)
1109
+ class NezhaForMaskedLM(NezhaPreTrainedModel):
1110
+ _tied_weights_keys = ["cls.predictions.decoder"]
1111
+
1112
+ def __init__(self, config):
1113
+ super().__init__(config)
1114
+
1115
+ if config.is_decoder:
1116
+ logger.warning(
1117
+ "If you want to use `NezhaForMaskedLM` make sure `config.is_decoder=False` for "
1118
+ "bi-directional self-attention."
1119
+ )
1120
+
1121
+ self.nezha = NezhaModel(config, add_pooling_layer=False)
1122
+ self.cls = NezhaOnlyMLMHead(config)
1123
+
1124
+ # Initialize weights and apply final processing
1125
+ self.post_init()
1126
+
1127
+ def get_output_embeddings(self):
1128
+ return self.cls.predictions.decoder
1129
+
1130
+ def set_output_embeddings(self, new_embeddings):
1131
+ self.cls.predictions.decoder = new_embeddings
1132
+ self.cls.predictions.bias = new_embeddings.bias
1133
+
1134
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1135
+ @add_code_sample_docstrings(
1136
+ checkpoint=_CHECKPOINT_FOR_DOC,
1137
+ output_type=MaskedLMOutput,
1138
+ config_class=_CONFIG_FOR_DOC,
1139
+ )
1140
+ def forward(
1141
+ self,
1142
+ input_ids: Optional[torch.Tensor] = None,
1143
+ attention_mask: Optional[torch.Tensor] = None,
1144
+ token_type_ids: Optional[torch.Tensor] = None,
1145
+ head_mask: Optional[torch.Tensor] = None,
1146
+ inputs_embeds: Optional[torch.Tensor] = None,
1147
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1148
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1149
+ labels: Optional[torch.Tensor] = None,
1150
+ output_attentions: Optional[bool] = None,
1151
+ output_hidden_states: Optional[bool] = None,
1152
+ return_dict: Optional[bool] = None,
1153
+ ) -> Union[tuple[torch.Tensor], MaskedLMOutput]:
1154
+ r"""
1155
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1156
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1157
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1158
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1159
+ """
1160
+
1161
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1162
+
1163
+ outputs = self.nezha(
1164
+ input_ids,
1165
+ attention_mask=attention_mask,
1166
+ token_type_ids=token_type_ids,
1167
+ head_mask=head_mask,
1168
+ inputs_embeds=inputs_embeds,
1169
+ encoder_hidden_states=encoder_hidden_states,
1170
+ encoder_attention_mask=encoder_attention_mask,
1171
+ output_attentions=output_attentions,
1172
+ output_hidden_states=output_hidden_states,
1173
+ return_dict=return_dict,
1174
+ )
1175
+
1176
+ sequence_output = outputs[0]
1177
+ prediction_scores = self.cls(sequence_output)
1178
+
1179
+ masked_lm_loss = None
1180
+ if labels is not None:
1181
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1182
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1183
+
1184
+ if not return_dict:
1185
+ output = (prediction_scores,) + outputs[2:]
1186
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1187
+
1188
+ return MaskedLMOutput(
1189
+ loss=masked_lm_loss,
1190
+ logits=prediction_scores,
1191
+ hidden_states=outputs.hidden_states,
1192
+ attentions=outputs.attentions,
1193
+ )
1194
+
1195
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
1196
+ input_shape = input_ids.shape
1197
+ effective_batch_size = input_shape[0]
1198
+
1199
+ # add a dummy token
1200
+ if self.config.pad_token_id is None:
1201
+ raise ValueError("The PAD token should be defined for generation")
1202
+
1203
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
1204
+ dummy_token = torch.full(
1205
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
1206
+ )
1207
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
1208
+
1209
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
1210
+
1211
+
1212
+ @add_start_docstrings(
1213
+ """Nezha Model with a `next sentence prediction (classification)` head on top.""",
1214
+ NEZHA_START_DOCSTRING,
1215
+ )
1216
+ class NezhaForNextSentencePrediction(NezhaPreTrainedModel):
1217
+ def __init__(self, config):
1218
+ super().__init__(config)
1219
+
1220
+ self.nezha = NezhaModel(config)
1221
+ self.cls = NezhaOnlyNSPHead(config)
1222
+
1223
+ # Initialize weights and apply final processing
1224
+ self.post_init()
1225
+
1226
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1227
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
1228
+ def forward(
1229
+ self,
1230
+ input_ids: Optional[torch.Tensor] = None,
1231
+ attention_mask: Optional[torch.Tensor] = None,
1232
+ token_type_ids: Optional[torch.Tensor] = None,
1233
+ head_mask: Optional[torch.Tensor] = None,
1234
+ inputs_embeds: Optional[torch.Tensor] = None,
1235
+ labels: Optional[torch.Tensor] = None,
1236
+ output_attentions: Optional[bool] = None,
1237
+ output_hidden_states: Optional[bool] = None,
1238
+ return_dict: Optional[bool] = None,
1239
+ **kwargs,
1240
+ ) -> Union[tuple[torch.Tensor], NextSentencePredictorOutput]:
1241
+ r"""
1242
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1243
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1244
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
1245
+
1246
+ - 0 indicates sequence B is a continuation of sequence A,
1247
+ - 1 indicates sequence B is a random sequence.
1248
+
1249
+ Returns:
1250
+
1251
+ Example:
1252
+
1253
+ ```python
1254
+ >>> from transformers import AutoTokenizer, NezhaForNextSentencePrediction
1255
+ >>> import torch
1256
+
1257
+ >>> tokenizer = AutoTokenizer.from_pretrained("sijunhe/nezha-cn-base")
1258
+ >>> model = NezhaForNextSentencePrediction.from_pretrained("sijunhe/nezha-cn-base")
1259
+
1260
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1261
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1262
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
1263
+
1264
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
1265
+ >>> logits = outputs.logits
1266
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
1267
+ ```
1268
+ """
1269
+
1270
+ if "next_sentence_label" in kwargs:
1271
+ warnings.warn(
1272
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
1273
+ " `labels` instead.",
1274
+ FutureWarning,
1275
+ )
1276
+ labels = kwargs.pop("next_sentence_label")
1277
+
1278
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1279
+
1280
+ outputs = self.nezha(
1281
+ input_ids,
1282
+ attention_mask=attention_mask,
1283
+ token_type_ids=token_type_ids,
1284
+ head_mask=head_mask,
1285
+ inputs_embeds=inputs_embeds,
1286
+ output_attentions=output_attentions,
1287
+ output_hidden_states=output_hidden_states,
1288
+ return_dict=return_dict,
1289
+ )
1290
+
1291
+ pooled_output = outputs[1]
1292
+
1293
+ seq_relationship_scores = self.cls(pooled_output)
1294
+
1295
+ next_sentence_loss = None
1296
+ if labels is not None:
1297
+ loss_fct = CrossEntropyLoss()
1298
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
1299
+
1300
+ if not return_dict:
1301
+ output = (seq_relationship_scores,) + outputs[2:]
1302
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1303
+
1304
+ return NextSentencePredictorOutput(
1305
+ loss=next_sentence_loss,
1306
+ logits=seq_relationship_scores,
1307
+ hidden_states=outputs.hidden_states,
1308
+ attentions=outputs.attentions,
1309
+ )
1310
+
1311
+
1312
+ @add_start_docstrings(
1313
+ """
1314
+ Nezha Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1315
+ output) e.g. for GLUE tasks.
1316
+ """,
1317
+ NEZHA_START_DOCSTRING,
1318
+ )
1319
+ class NezhaForSequenceClassification(NezhaPreTrainedModel):
1320
+ def __init__(self, config):
1321
+ super().__init__(config)
1322
+ self.num_labels = config.num_labels
1323
+ self.config = config
1324
+
1325
+ self.nezha = NezhaModel(config)
1326
+ classifier_dropout = (
1327
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1328
+ )
1329
+ self.dropout = nn.Dropout(classifier_dropout)
1330
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1331
+
1332
+ # Initialize weights and apply final processing
1333
+ self.post_init()
1334
+
1335
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1336
+ @add_code_sample_docstrings(
1337
+ checkpoint=_CHECKPOINT_FOR_DOC,
1338
+ output_type=SequenceClassifierOutput,
1339
+ config_class=_CONFIG_FOR_DOC,
1340
+ )
1341
+ def forward(
1342
+ self,
1343
+ input_ids: Optional[torch.Tensor] = None,
1344
+ attention_mask: Optional[torch.Tensor] = None,
1345
+ token_type_ids: Optional[torch.Tensor] = None,
1346
+ head_mask: Optional[torch.Tensor] = None,
1347
+ inputs_embeds: Optional[torch.Tensor] = None,
1348
+ labels: Optional[torch.Tensor] = None,
1349
+ output_attentions: Optional[bool] = None,
1350
+ output_hidden_states: Optional[bool] = None,
1351
+ return_dict: Optional[bool] = None,
1352
+ ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
1353
+ r"""
1354
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1355
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1356
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1357
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1358
+ """
1359
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1360
+
1361
+ outputs = self.nezha(
1362
+ input_ids,
1363
+ attention_mask=attention_mask,
1364
+ token_type_ids=token_type_ids,
1365
+ head_mask=head_mask,
1366
+ inputs_embeds=inputs_embeds,
1367
+ output_attentions=output_attentions,
1368
+ output_hidden_states=output_hidden_states,
1369
+ return_dict=return_dict,
1370
+ )
1371
+
1372
+ pooled_output = outputs[1]
1373
+
1374
+ pooled_output = self.dropout(pooled_output)
1375
+ logits = self.classifier(pooled_output)
1376
+
1377
+ loss = None
1378
+ if labels is not None:
1379
+ if self.config.problem_type is None:
1380
+ if self.num_labels == 1:
1381
+ self.config.problem_type = "regression"
1382
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1383
+ self.config.problem_type = "single_label_classification"
1384
+ else:
1385
+ self.config.problem_type = "multi_label_classification"
1386
+
1387
+ if self.config.problem_type == "regression":
1388
+ loss_fct = MSELoss()
1389
+ if self.num_labels == 1:
1390
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1391
+ else:
1392
+ loss = loss_fct(logits, labels)
1393
+ elif self.config.problem_type == "single_label_classification":
1394
+ loss_fct = CrossEntropyLoss()
1395
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1396
+ elif self.config.problem_type == "multi_label_classification":
1397
+ loss_fct = BCEWithLogitsLoss()
1398
+ loss = loss_fct(logits, labels)
1399
+ if not return_dict:
1400
+ output = (logits,) + outputs[2:]
1401
+ return ((loss,) + output) if loss is not None else output
1402
+
1403
+ return SequenceClassifierOutput(
1404
+ loss=loss,
1405
+ logits=logits,
1406
+ hidden_states=outputs.hidden_states,
1407
+ attentions=outputs.attentions,
1408
+ )
1409
+
1410
+
1411
+ @add_start_docstrings(
1412
+ """
1413
+ Nezha Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1414
+ softmax) e.g. for RocStories/SWAG tasks.
1415
+ """,
1416
+ NEZHA_START_DOCSTRING,
1417
+ )
1418
+ class NezhaForMultipleChoice(NezhaPreTrainedModel):
1419
+ def __init__(self, config):
1420
+ super().__init__(config)
1421
+
1422
+ self.nezha = NezhaModel(config)
1423
+ classifier_dropout = (
1424
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1425
+ )
1426
+ self.dropout = nn.Dropout(classifier_dropout)
1427
+ self.classifier = nn.Linear(config.hidden_size, 1)
1428
+
1429
+ # Initialize weights and apply final processing
1430
+ self.post_init()
1431
+
1432
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1433
+ @add_code_sample_docstrings(
1434
+ checkpoint=_CHECKPOINT_FOR_DOC,
1435
+ output_type=MultipleChoiceModelOutput,
1436
+ config_class=_CONFIG_FOR_DOC,
1437
+ )
1438
+ def forward(
1439
+ self,
1440
+ input_ids: Optional[torch.Tensor] = None,
1441
+ attention_mask: Optional[torch.Tensor] = None,
1442
+ token_type_ids: Optional[torch.Tensor] = None,
1443
+ head_mask: Optional[torch.Tensor] = None,
1444
+ inputs_embeds: Optional[torch.Tensor] = None,
1445
+ labels: Optional[torch.Tensor] = None,
1446
+ output_attentions: Optional[bool] = None,
1447
+ output_hidden_states: Optional[bool] = None,
1448
+ return_dict: Optional[bool] = None,
1449
+ ) -> Union[tuple[torch.Tensor], MultipleChoiceModelOutput]:
1450
+ r"""
1451
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1452
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1453
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1454
+ `input_ids` above)
1455
+ """
1456
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1457
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1458
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1459
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1460
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1461
+ inputs_embeds = (
1462
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1463
+ if inputs_embeds is not None
1464
+ else None
1465
+ )
1466
+
1467
+ outputs = self.nezha(
1468
+ input_ids,
1469
+ attention_mask=attention_mask,
1470
+ token_type_ids=token_type_ids,
1471
+ head_mask=head_mask,
1472
+ inputs_embeds=inputs_embeds,
1473
+ output_attentions=output_attentions,
1474
+ output_hidden_states=output_hidden_states,
1475
+ return_dict=return_dict,
1476
+ )
1477
+
1478
+ pooled_output = outputs[1]
1479
+ print(pooled_output.shape)
1480
+ pooled_output = self.dropout(pooled_output)
1481
+ logits = self.classifier(pooled_output)
1482
+ print(logits.shape)
1483
+ print(num_choices)
1484
+ reshaped_logits = logits.view(-1, num_choices)
1485
+
1486
+ loss = None
1487
+ if labels is not None:
1488
+ loss_fct = CrossEntropyLoss()
1489
+ loss = loss_fct(reshaped_logits, labels)
1490
+
1491
+ if not return_dict:
1492
+ output = (reshaped_logits,) + outputs[2:]
1493
+ return ((loss,) + output) if loss is not None else output
1494
+
1495
+ return MultipleChoiceModelOutput(
1496
+ loss=loss,
1497
+ logits=reshaped_logits,
1498
+ hidden_states=outputs.hidden_states,
1499
+ attentions=outputs.attentions,
1500
+ )
1501
+
1502
+
1503
+ @add_start_docstrings(
1504
+ """
1505
+ Nezha Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1506
+ Named-Entity-Recognition (NER) tasks.
1507
+ """,
1508
+ NEZHA_START_DOCSTRING,
1509
+ )
1510
+ class NezhaForTokenClassification(NezhaPreTrainedModel):
1511
+ def __init__(self, config):
1512
+ super().__init__(config)
1513
+ self.num_labels = config.num_labels
1514
+
1515
+ self.nezha = NezhaModel(config, add_pooling_layer=False)
1516
+ classifier_dropout = (
1517
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1518
+ )
1519
+ self.dropout = nn.Dropout(classifier_dropout)
1520
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1521
+
1522
+ # Initialize weights and apply final processing
1523
+ self.post_init()
1524
+
1525
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1526
+ @add_code_sample_docstrings(
1527
+ checkpoint=_CHECKPOINT_FOR_DOC,
1528
+ output_type=TokenClassifierOutput,
1529
+ config_class=_CONFIG_FOR_DOC,
1530
+ )
1531
+ def forward(
1532
+ self,
1533
+ input_ids: Optional[torch.Tensor] = None,
1534
+ attention_mask: Optional[torch.Tensor] = None,
1535
+ token_type_ids: Optional[torch.Tensor] = None,
1536
+ head_mask: Optional[torch.Tensor] = None,
1537
+ inputs_embeds: Optional[torch.Tensor] = None,
1538
+ labels: Optional[torch.Tensor] = None,
1539
+ output_attentions: Optional[bool] = None,
1540
+ output_hidden_states: Optional[bool] = None,
1541
+ return_dict: Optional[bool] = None,
1542
+ ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]:
1543
+ r"""
1544
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1545
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1546
+ """
1547
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1548
+
1549
+ outputs = self.nezha(
1550
+ input_ids,
1551
+ attention_mask=attention_mask,
1552
+ token_type_ids=token_type_ids,
1553
+ head_mask=head_mask,
1554
+ inputs_embeds=inputs_embeds,
1555
+ output_attentions=output_attentions,
1556
+ output_hidden_states=output_hidden_states,
1557
+ return_dict=return_dict,
1558
+ )
1559
+
1560
+ sequence_output = outputs[0]
1561
+
1562
+ sequence_output = self.dropout(sequence_output)
1563
+ logits = self.classifier(sequence_output)
1564
+
1565
+ loss = None
1566
+ if labels is not None:
1567
+ loss_fct = CrossEntropyLoss()
1568
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1569
+
1570
+ if not return_dict:
1571
+ output = (logits,) + outputs[2:]
1572
+ return ((loss,) + output) if loss is not None else output
1573
+
1574
+ return TokenClassifierOutput(
1575
+ loss=loss,
1576
+ logits=logits,
1577
+ hidden_states=outputs.hidden_states,
1578
+ attentions=outputs.attentions,
1579
+ )
1580
+
1581
+
1582
+ @add_start_docstrings(
1583
+ """
1584
+ Nezha Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1585
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1586
+ """,
1587
+ NEZHA_START_DOCSTRING,
1588
+ )
1589
+ class NezhaForQuestionAnswering(NezhaPreTrainedModel):
1590
+ def __init__(self, config):
1591
+ super().__init__(config)
1592
+ self.num_labels = config.num_labels
1593
+
1594
+ self.nezha = NezhaModel(config, add_pooling_layer=False)
1595
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1596
+
1597
+ # Initialize weights and apply final processing
1598
+ self.post_init()
1599
+
1600
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1601
+ @add_code_sample_docstrings(
1602
+ checkpoint=_CHECKPOINT_FOR_DOC,
1603
+ output_type=QuestionAnsweringModelOutput,
1604
+ config_class=_CONFIG_FOR_DOC,
1605
+ )
1606
+ def forward(
1607
+ self,
1608
+ input_ids: Optional[torch.Tensor] = None,
1609
+ attention_mask: Optional[torch.Tensor] = None,
1610
+ token_type_ids: Optional[torch.Tensor] = None,
1611
+ head_mask: Optional[torch.Tensor] = None,
1612
+ inputs_embeds: Optional[torch.Tensor] = None,
1613
+ start_positions: Optional[torch.Tensor] = None,
1614
+ end_positions: Optional[torch.Tensor] = None,
1615
+ output_attentions: Optional[bool] = None,
1616
+ output_hidden_states: Optional[bool] = None,
1617
+ return_dict: Optional[bool] = None,
1618
+ ) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1619
+ r"""
1620
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1621
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1622
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1623
+ are not taken into account for computing the loss.
1624
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1625
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1626
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1627
+ are not taken into account for computing the loss.
1628
+ """
1629
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1630
+
1631
+ outputs = self.nezha(
1632
+ input_ids,
1633
+ attention_mask=attention_mask,
1634
+ token_type_ids=token_type_ids,
1635
+ head_mask=head_mask,
1636
+ inputs_embeds=inputs_embeds,
1637
+ output_attentions=output_attentions,
1638
+ output_hidden_states=output_hidden_states,
1639
+ return_dict=return_dict,
1640
+ )
1641
+
1642
+ sequence_output = outputs[0]
1643
+
1644
+ logits = self.qa_outputs(sequence_output)
1645
+ start_logits, end_logits = logits.split(1, dim=-1)
1646
+ start_logits = start_logits.squeeze(-1).contiguous()
1647
+ end_logits = end_logits.squeeze(-1).contiguous()
1648
+
1649
+ total_loss = None
1650
+ if start_positions is not None and end_positions is not None:
1651
+ # If we are on multi-GPU, split add a dimension
1652
+ if len(start_positions.size()) > 1:
1653
+ start_positions = start_positions.squeeze(-1)
1654
+ if len(end_positions.size()) > 1:
1655
+ end_positions = end_positions.squeeze(-1)
1656
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1657
+ ignored_index = start_logits.size(1)
1658
+ start_positions = start_positions.clamp(0, ignored_index)
1659
+ end_positions = end_positions.clamp(0, ignored_index)
1660
+
1661
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1662
+ start_loss = loss_fct(start_logits, start_positions)
1663
+ end_loss = loss_fct(end_logits, end_positions)
1664
+ total_loss = (start_loss + end_loss) / 2
1665
+
1666
+ if not return_dict:
1667
+ output = (start_logits, end_logits) + outputs[2:]
1668
+ return ((total_loss,) + output) if total_loss is not None else output
1669
+
1670
+ return QuestionAnsweringModelOutput(
1671
+ loss=total_loss,
1672
+ start_logits=start_logits,
1673
+ end_logits=end_logits,
1674
+ hidden_states=outputs.hidden_states,
1675
+ attentions=outputs.attentions,
1676
+ )
1677
+
1678
+
1679
+ __all__ = [
1680
+ "NezhaForNextSentencePrediction",
1681
+ "NezhaForMaskedLM",
1682
+ "NezhaForPreTraining",
1683
+ "NezhaForMultipleChoice",
1684
+ "NezhaForQuestionAnswering",
1685
+ "NezhaForSequenceClassification",
1686
+ "NezhaForTokenClassification",
1687
+ "NezhaModel",
1688
+ "NezhaPreTrainedModel",
1689
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/open_llama/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 EleutherAI and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ....utils import _LazyModule
17
+ from ....utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_open_llama import *
22
+ from .modeling_open_llama import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/open_llama/configuration_open_llama.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """Open-Llama model configuration"""
21
+
22
+ from ....configuration_utils import PretrainedConfig
23
+ from ....utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class OpenLlamaConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`OpenLlamaModel`]. It is used to instantiate an
32
+ Open-Llama model according to the specified arguments, defining the model architecture. Instantiating a
33
+ configuration with the defaults will yield a similar configuration to that of the
34
+ [s-JoL/Open-Llama-V1](https://huggingface.co/s-JoL/Open-Llama-V1).
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 32000):
42
+ Vocabulary size of the Open-Llama model. Defines the number of different tokens that can be represented by
43
+ the `inputs_ids` passed when calling [`OpenLlamaModel`]
44
+ hidden_size (`int`, *optional*, defaults to 4096):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 11008):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 32):
49
+ Number of hidden layers in the Transformer encoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 32):
51
+ Number of attention heads for each attention layer in the Transformer encoder.
52
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
53
+ The non-linear activation function (function or string) in the decoder.
54
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
55
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
56
+ just in case (e.g., 512 or 1024 or 2048).
57
+ initializer_range (`float`, *optional*, defaults to 0.02):
58
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
59
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
60
+ The epsilon used by the rms normalization layers.
61
+ use_cache (`bool`, *optional*, defaults to `True`):
62
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
63
+ relevant if `config.is_decoder=True`.
64
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
65
+ Whether to tie weight embeddings
66
+ rope_theta (`float`, *optional*, defaults to 10000.0):
67
+ The base period of the RoPE embeddings.
68
+ rope_scaling (`Dict`, *optional*):
69
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
70
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
71
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
72
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
73
+ these scaling strategies behave:
74
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
75
+ experimental feature, subject to breaking API changes in future versions.
76
+
77
+ Example:
78
+
79
+ ```python
80
+ >>> from transformers import OpenLlamaModel, OpenLlamaConfig
81
+
82
+ >>> # Initializing a Open-Llama open_llama-7b style configuration
83
+ >>> configuration = OpenLlamaConfig()
84
+
85
+ >>> # Initializing a model from the open_llama-7b style configuration
86
+ >>> model = OpenLlamaModel(configuration)
87
+
88
+ >>> # Accessing the model configuration
89
+ >>> configuration = model.config
90
+ ```"""
91
+
92
+ model_type = "open-llama"
93
+
94
+ def __init__(
95
+ self,
96
+ vocab_size=100000,
97
+ hidden_size=4096,
98
+ intermediate_size=11008,
99
+ num_hidden_layers=32,
100
+ num_attention_heads=32,
101
+ hidden_act="silu",
102
+ max_position_embeddings=2048,
103
+ initializer_range=0.02,
104
+ rms_norm_eps=1e-6,
105
+ use_cache=True,
106
+ pad_token_id=0,
107
+ bos_token_id=1,
108
+ eos_token_id=2,
109
+ tie_word_embeddings=False,
110
+ use_memory_efficient_attention=True,
111
+ hidden_dropout_prob=0.1,
112
+ attention_dropout_prob=0.1,
113
+ use_stable_embedding=True,
114
+ shared_input_output_embedding=True,
115
+ rope_theta=10000.0,
116
+ rope_scaling=None,
117
+ **kwargs,
118
+ ):
119
+ self.vocab_size = vocab_size
120
+ self.max_position_embeddings = max_position_embeddings
121
+ self.hidden_size = hidden_size
122
+ self.intermediate_size = intermediate_size
123
+ self.num_hidden_layers = num_hidden_layers
124
+ self.num_attention_heads = num_attention_heads
125
+ self.hidden_act = hidden_act
126
+ self.initializer_range = initializer_range
127
+ self.rms_norm_eps = rms_norm_eps
128
+ self.use_cache = use_cache
129
+ self.use_memory_efficient_attention = kwargs.pop(
130
+ "use_memorry_efficient_attention", use_memory_efficient_attention
131
+ )
132
+ self.hidden_dropout_prob = hidden_dropout_prob
133
+ self.attention_dropout_prob = attention_dropout_prob
134
+ self.use_stable_embedding = use_stable_embedding
135
+ self.shared_input_output_embedding = shared_input_output_embedding
136
+ self.rope_theta = rope_theta
137
+ self.rope_scaling = rope_scaling
138
+ self._rope_scaling_validation()
139
+
140
+ super().__init__(
141
+ pad_token_id=pad_token_id,
142
+ bos_token_id=bos_token_id,
143
+ eos_token_id=eos_token_id,
144
+ tie_word_embeddings=tie_word_embeddings,
145
+ **kwargs,
146
+ )
147
+
148
+ def _rope_scaling_validation(self):
149
+ """
150
+ Validate the `rope_scaling` configuration.
151
+ """
152
+ if self.rope_scaling is None:
153
+ return
154
+
155
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
156
+ raise ValueError(
157
+ f"`rope_scaling` must be a dictionary with two fields, `type` and `factor`, got {self.rope_scaling}"
158
+ )
159
+ rope_scaling_type = self.rope_scaling.get("type", None)
160
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
161
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
162
+ raise ValueError(
163
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
164
+ )
165
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
166
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
167
+
168
+
169
+ __all__ = ["OpenLlamaConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/open_llama/modeling_open_llama.py ADDED
@@ -0,0 +1,940 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """PyTorch Open-Llama model."""
21
+
22
+ import math
23
+ from typing import Optional, Union
24
+
25
+ import torch
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from ....activations import ACT2FN
30
+ from ....cache_utils import Cache
31
+ from ....modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
32
+ from ....modeling_layers import GradientCheckpointingLayer
33
+ from ....modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
34
+ from ....modeling_utils import PreTrainedModel
35
+ from ....utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
36
+ from ....utils.deprecation import deprecate_kwarg
37
+ from .configuration_open_llama import OpenLlamaConfig
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ try:
43
+ from xformers import ops as xops
44
+ except ImportError:
45
+ xops = None
46
+
47
+
48
+ _CONFIG_FOR_DOC = "OpenLlamaConfig"
49
+
50
+
51
+ class OpenLlamaRMSNorm(nn.Module):
52
+ def __init__(self, hidden_size, eps=1e-6):
53
+ """
54
+ OpenLlamaRMSNorm is equivalent to T5LayerNorm
55
+ """
56
+ super().__init__()
57
+ self.weight = nn.Parameter(torch.ones(hidden_size))
58
+ self.variance_epsilon = eps
59
+
60
+ def forward(self, hidden_states):
61
+ input_dtype = hidden_states.dtype
62
+ hidden_states = hidden_states.to(torch.float32)
63
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
64
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
65
+ return self.weight * hidden_states.to(input_dtype)
66
+
67
+ def extra_repr(self):
68
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
69
+
70
+
71
+ class OpenLlamaRotaryEmbedding(nn.Module):
72
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
73
+ cos_cached: torch.Tensor
74
+ sin_cached: torch.Tensor
75
+
76
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
77
+ super().__init__()
78
+
79
+ self.dim = dim
80
+ self.max_position_embeddings = max_position_embeddings
81
+ self.base = base
82
+ inv_freq = 1.0 / (
83
+ self.base
84
+ ** (torch.arange(0, self.dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / self.dim)
85
+ )
86
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
87
+
88
+ # Build here to make `torch.jit.trace` work.
89
+ self._set_cos_sin_cache(
90
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
91
+ )
92
+
93
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
94
+ self.max_seq_len_cached = seq_len
95
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
96
+
97
+ freqs = torch.outer(t, self.inv_freq)
98
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
99
+ emb = torch.cat((freqs, freqs), dim=-1)
100
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
101
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
102
+
103
+ def forward(self, x, seq_len=None):
104
+ # x: [bs, num_attention_heads, seq_len, head_size]
105
+ if seq_len > self.max_seq_len_cached:
106
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
107
+
108
+ return (
109
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
110
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
111
+ )
112
+
113
+
114
+ class OpenLlamaLinearScalingRotaryEmbedding(OpenLlamaRotaryEmbedding):
115
+ """OpenLlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
116
+
117
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
118
+ self.scaling_factor = scaling_factor
119
+ super().__init__(dim, max_position_embeddings, base, device)
120
+
121
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
122
+ self.max_seq_len_cached = seq_len
123
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
124
+ t = t / self.scaling_factor
125
+
126
+ freqs = torch.outer(t, self.inv_freq)
127
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
128
+ emb = torch.cat((freqs, freqs), dim=-1)
129
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
130
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
131
+
132
+
133
+ class OpenLlamaDynamicNTKScalingRotaryEmbedding(OpenLlamaRotaryEmbedding):
134
+ """OpenLlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
135
+
136
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
137
+ self.scaling_factor = scaling_factor
138
+ super().__init__(dim, max_position_embeddings, base, device)
139
+
140
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
141
+ self.max_seq_len_cached = seq_len
142
+
143
+ if seq_len > self.max_position_embeddings:
144
+ base = self.base * (
145
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
146
+ ) ** (self.dim / (self.dim - 2))
147
+ inv_freq = 1.0 / (
148
+ base
149
+ ** (torch.arange(0, self.dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / self.dim)
150
+ )
151
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
152
+
153
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
154
+
155
+ freqs = torch.outer(t, self.inv_freq)
156
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
157
+ emb = torch.cat((freqs, freqs), dim=-1)
158
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
159
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
160
+
161
+
162
+ def rotate_half(x):
163
+ """Rotates half the hidden dims of the input."""
164
+ x1 = x[..., : x.shape[-1] // 2]
165
+ x2 = x[..., x.shape[-1] // 2 :]
166
+ return torch.cat((-x2, x1), dim=-1)
167
+
168
+
169
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
170
+ """Applies Rotary Position Embedding to the query and key tensors.
171
+
172
+ Args:
173
+ q (`torch.Tensor`): The query tensor.
174
+ k (`torch.Tensor`): The key tensor.
175
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
176
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
177
+ position_ids (`torch.Tensor`):
178
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
179
+ used to pass offsetted position ids when working with a KV-cache.
180
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
181
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
182
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
183
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
184
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
185
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
186
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
187
+ Returns:
188
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
189
+ """
190
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
191
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
192
+ q_embed = (q * cos) + (rotate_half(q) * sin)
193
+ k_embed = (k * cos) + (rotate_half(k) * sin)
194
+ return q_embed, k_embed
195
+
196
+
197
+ class OpenLlamaMLP(nn.Module):
198
+ def __init__(
199
+ self,
200
+ hidden_size: int,
201
+ intermediate_size: int,
202
+ hidden_act: str,
203
+ dropout_prob: float,
204
+ ):
205
+ super().__init__()
206
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
207
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
208
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
209
+ self.act_fn = ACT2FN[hidden_act]
210
+ self.dropout = nn.Dropout(dropout_prob)
211
+
212
+ def forward(self, x):
213
+ out = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
214
+ return self.dropout(out)
215
+
216
+
217
+ class OpenLlamaAttention(nn.Module):
218
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
219
+
220
+ def __init__(self, config: OpenLlamaConfig):
221
+ super().__init__()
222
+ self.config = config
223
+ self.hidden_size = config.hidden_size
224
+ self.num_heads = config.num_attention_heads
225
+ self.head_dim = self.hidden_size // self.num_heads
226
+ self.max_position_embeddings = config.max_position_embeddings
227
+ self.dropout_prob = config.attention_dropout_prob
228
+ self.rope_theta = config.rope_theta
229
+
230
+ if (self.head_dim * self.num_heads) != self.hidden_size:
231
+ raise ValueError(
232
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
233
+ f" and `num_heads`: {self.num_heads})."
234
+ )
235
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
236
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
237
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
238
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
239
+ self._init_rope()
240
+
241
+ def _init_rope(self):
242
+ if self.config.rope_scaling is None:
243
+ self.rotary_emb = OpenLlamaRotaryEmbedding(
244
+ self.head_dim,
245
+ max_position_embeddings=self.max_position_embeddings,
246
+ base=self.rope_theta,
247
+ )
248
+ else:
249
+ scaling_type = self.config.rope_scaling["type"]
250
+ scaling_factor = self.config.rope_scaling["factor"]
251
+ if scaling_type == "linear":
252
+ self.rotary_emb = OpenLlamaLinearScalingRotaryEmbedding(
253
+ self.head_dim,
254
+ max_position_embeddings=self.max_position_embeddings,
255
+ scaling_factor=scaling_factor,
256
+ base=self.rope_theta,
257
+ )
258
+ elif scaling_type == "dynamic":
259
+ self.rotary_emb = OpenLlamaDynamicNTKScalingRotaryEmbedding(
260
+ self.head_dim,
261
+ max_position_embeddings=self.max_position_embeddings,
262
+ scaling_factor=scaling_factor,
263
+ base=self.rope_theta,
264
+ )
265
+ else:
266
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
267
+
268
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
269
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
270
+
271
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
272
+ def forward(
273
+ self,
274
+ hidden_states: torch.Tensor,
275
+ attention_mask: Optional[torch.Tensor] = None,
276
+ position_ids: Optional[torch.LongTensor] = None,
277
+ past_key_values: Optional[Cache] = None,
278
+ output_attentions: bool = False,
279
+ use_cache: bool = False,
280
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
281
+ bsz, q_len, _ = hidden_states.size()
282
+
283
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
284
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
285
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
286
+
287
+ kv_seq_len = key_states.shape[-2]
288
+ if past_key_values is not None:
289
+ kv_seq_len += past_key_values[0].shape[-2]
290
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
291
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
292
+ # [bsz, nh, t, hd]
293
+
294
+ if past_key_values is not None:
295
+ # reuse k, v, self_attention
296
+ key_states = torch.cat([past_key_values[0], key_states], dim=2)
297
+ value_states = torch.cat([past_key_values[1], value_states], dim=2)
298
+
299
+ past_key_values = (key_states, value_states) if use_cache else None
300
+
301
+ if self.config.use_memory_efficient_attention and xops is not None and self.training:
302
+ attn_weights = None
303
+ query_states = query_states.transpose(1, 2)
304
+ key_states = key_states.transpose(1, 2)
305
+ value_states = value_states.transpose(1, 2)
306
+ attn_output = xops.memory_efficient_attention(
307
+ query_states, key_states, value_states, attn_bias=xops.LowerTriangularMask(), p=self.dropout_prob
308
+ )
309
+ else:
310
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
311
+
312
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
313
+ raise ValueError(
314
+ f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
315
+ f" {attn_weights.size()}"
316
+ )
317
+
318
+ if attention_mask is not None:
319
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
320
+ raise ValueError(
321
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
322
+ )
323
+ attn_weights = attn_weights + attention_mask
324
+ attn_weights = torch.max(
325
+ attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min, device=attn_weights.device)
326
+ )
327
+
328
+ # upcast attention to fp32
329
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
330
+ attn_output = torch.matmul(attn_weights, value_states)
331
+
332
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
333
+ raise ValueError(
334
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
335
+ f" {attn_output.size()}"
336
+ )
337
+
338
+ attn_output = attn_output.transpose(1, 2)
339
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
340
+
341
+ attn_output = self.o_proj(attn_output)
342
+
343
+ if not output_attentions:
344
+ attn_weights = None
345
+
346
+ return attn_output, attn_weights, past_key_values
347
+
348
+
349
+ class OpenLlamaDecoderLayer(GradientCheckpointingLayer):
350
+ def __init__(self, config: OpenLlamaConfig):
351
+ super().__init__()
352
+ self.hidden_size = config.hidden_size
353
+ self.self_attn = OpenLlamaAttention(config=config)
354
+ self.mlp = OpenLlamaMLP(
355
+ hidden_size=self.hidden_size,
356
+ intermediate_size=config.intermediate_size,
357
+ hidden_act=config.hidden_act,
358
+ dropout_prob=config.hidden_dropout_prob,
359
+ )
360
+ self.input_layernorm = OpenLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
361
+ self.post_attention_layernorm = OpenLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
362
+
363
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
364
+ def forward(
365
+ self,
366
+ hidden_states: torch.Tensor,
367
+ attention_mask: Optional[torch.Tensor] = None,
368
+ position_ids: Optional[torch.LongTensor] = None,
369
+ past_key_values: Optional[Cache] = None,
370
+ output_attentions: Optional[bool] = False,
371
+ use_cache: Optional[bool] = False,
372
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
373
+ """
374
+ Args:
375
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
376
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
377
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
378
+ output_attentions (`bool`, *optional*):
379
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
380
+ returned tensors for more detail.
381
+ use_cache (`bool`, *optional*):
382
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
383
+ (see `past_key_values`).
384
+ past_key_values (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
385
+ """
386
+
387
+ residual = hidden_states
388
+
389
+ hidden_states = self.input_layernorm(hidden_states)
390
+
391
+ # Self Attention
392
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
393
+ hidden_states=hidden_states,
394
+ attention_mask=attention_mask,
395
+ position_ids=position_ids,
396
+ past_key_values=past_key_values,
397
+ output_attentions=output_attentions,
398
+ use_cache=use_cache,
399
+ )
400
+ hidden_states = residual + hidden_states
401
+
402
+ # Fully Connected
403
+ residual = hidden_states
404
+ hidden_states = self.post_attention_layernorm(hidden_states)
405
+ hidden_states = self.mlp(hidden_states)
406
+ hidden_states = residual + hidden_states
407
+
408
+ outputs = (hidden_states,)
409
+
410
+ if output_attentions:
411
+ outputs += (self_attn_weights,)
412
+
413
+ if use_cache:
414
+ outputs += (present_key_value,)
415
+
416
+ return outputs
417
+
418
+
419
+ OPEN_LLAMA_START_DOCSTRING = r"""
420
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
421
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
422
+ etc.)
423
+
424
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
425
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
426
+ and behavior.
427
+
428
+ Parameters:
429
+ config ([`OpenLlamaConfig`]):
430
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
431
+ load the weights associated with the model, only the configuration. Check out the
432
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
433
+ """
434
+
435
+
436
+ @add_start_docstrings(
437
+ "The bare Open-Llama Model outputting raw hidden-states without any specific head on top.",
438
+ OPEN_LLAMA_START_DOCSTRING,
439
+ )
440
+ class OpenLlamaPreTrainedModel(PreTrainedModel):
441
+ config: OpenLlamaConfig
442
+ base_model_prefix = "model"
443
+ supports_gradient_checkpointing = True
444
+ _no_split_modules = ["OpenLlamaDecoderLayer"]
445
+
446
+ def _init_weights(self, module):
447
+ std = self.config.initializer_range
448
+ if isinstance(module, nn.Linear):
449
+ module.weight.data.normal_(mean=0.0, std=std)
450
+ if module.bias is not None:
451
+ module.bias.data.zero_()
452
+ elif isinstance(module, nn.Embedding):
453
+ if self.config.use_stable_embedding:
454
+ torch.nn.init.xavier_normal_(module.weight.data)
455
+ else:
456
+ module.weight.data.normal_(mean=0.0, std=std)
457
+ if module.padding_idx is not None:
458
+ module.weight.data[module.padding_idx].zero_()
459
+
460
+
461
+ OPEN_LLAMA_INPUTS_DOCSTRING = r"""
462
+ Args:
463
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
464
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
465
+ it.
466
+
467
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
468
+ [`PreTrainedTokenizer.__call__`] for details.
469
+
470
+ [What are input IDs?](../glossary#input-ids)
471
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
472
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
473
+
474
+ - 1 for tokens that are **not masked**,
475
+ - 0 for tokens that are **masked**.
476
+
477
+ [What are attention masks?](../glossary#attention-mask)
478
+
479
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
480
+ [`PreTrainedTokenizer.__call__`] for details.
481
+
482
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
483
+ `past_key_values`).
484
+
485
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
486
+ and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
487
+ information on the default strategy.
488
+
489
+ - 1 indicates the head is **not masked**,
490
+ - 0 indicates the head is **masked**.
491
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
492
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
493
+ config.n_positions - 1]`.
494
+
495
+ [What are position IDs?](../glossary#position-ids)
496
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
497
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
498
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
499
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
500
+
501
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
502
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
503
+
504
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
505
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
506
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
507
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
508
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
509
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
510
+ model's internal embedding lookup matrix.
511
+ use_cache (`bool`, *optional*):
512
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
513
+ `past_key_values`).
514
+ output_attentions (`bool`, *optional*):
515
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
516
+ tensors for more detail.
517
+ output_hidden_states (`bool`, *optional*):
518
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
519
+ more detail.
520
+ return_dict (`bool`, *optional*):
521
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
522
+ """
523
+
524
+
525
+ @add_start_docstrings(
526
+ "The bare Open-Llama Model outputting raw hidden-states without any specific head on top.",
527
+ OPEN_LLAMA_START_DOCSTRING,
528
+ )
529
+ class OpenLlamaModel(OpenLlamaPreTrainedModel):
530
+ """
531
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OpenLlamaDecoderLayer`]
532
+
533
+ Args:
534
+ config: OpenLlamaConfig
535
+ """
536
+
537
+ def __init__(self, config: OpenLlamaConfig):
538
+ super().__init__(config)
539
+ self.padding_idx = config.pad_token_id
540
+ self.vocab_size = config.vocab_size
541
+
542
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
543
+ if config.use_stable_embedding:
544
+ self.embed_layer_norm = nn.LayerNorm(config.hidden_size)
545
+ else:
546
+ self.embed_layer_norm = None
547
+ self.layers = nn.ModuleList([OpenLlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
548
+ self.norm = OpenLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
549
+
550
+ self.gradient_checkpointing = False
551
+ # Initialize weights and apply final processing
552
+ self.post_init()
553
+
554
+ @add_start_docstrings_to_model_forward(OPEN_LLAMA_INPUTS_DOCSTRING)
555
+ def forward(
556
+ self,
557
+ input_ids: Optional[torch.LongTensor] = None,
558
+ attention_mask: Optional[torch.Tensor] = None,
559
+ position_ids: Optional[torch.LongTensor] = None,
560
+ past_key_values: Optional[Cache] = None,
561
+ inputs_embeds: Optional[torch.FloatTensor] = None,
562
+ use_cache: Optional[bool] = None,
563
+ output_attentions: Optional[bool] = None,
564
+ output_hidden_states: Optional[bool] = None,
565
+ return_dict: Optional[bool] = None,
566
+ ) -> Union[tuple, BaseModelOutputWithPast]:
567
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
568
+ output_hidden_states = (
569
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
570
+ )
571
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
572
+
573
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
574
+
575
+ # retrieve input_ids and inputs_embeds
576
+ if input_ids is not None and inputs_embeds is not None:
577
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
578
+ elif input_ids is not None:
579
+ batch_size, seq_length = input_ids.shape
580
+ elif inputs_embeds is not None:
581
+ batch_size, seq_length, _ = inputs_embeds.shape
582
+ else:
583
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
584
+
585
+ seq_length_with_past = seq_length
586
+ past_key_values_length = 0
587
+
588
+ if self.gradient_checkpointing and self.training:
589
+ if use_cache:
590
+ logger.warning_once(
591
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
592
+ )
593
+ use_cache = False
594
+
595
+ if past_key_values is not None:
596
+ past_key_values_length = past_key_values.get_seq_length()
597
+ seq_length_with_past = seq_length_with_past + past_key_values_length
598
+
599
+ if position_ids is None:
600
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
601
+ position_ids = torch.arange(
602
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
603
+ )
604
+ position_ids = position_ids.unsqueeze(0)
605
+
606
+ if inputs_embeds is None:
607
+ inputs_embeds = self.embed_tokens(input_ids)
608
+ if self.embed_layer_norm:
609
+ inputs_embeds = self.embed_layer_norm(inputs_embeds)
610
+ # embed positions
611
+ if self.config.use_memory_efficient_attention and self.training:
612
+ attention_mask = None
613
+ elif attention_mask is None:
614
+ attention_mask = torch.ones(
615
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
616
+ )
617
+
618
+ input_shape = (batch_size, seq_length)
619
+ attention_mask = _prepare_4d_causal_attention_mask(
620
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
621
+ )
622
+
623
+ hidden_states = inputs_embeds
624
+
625
+ # decoder layers
626
+ all_hidden_states = () if output_hidden_states else None
627
+ all_self_attns = () if output_attentions else None
628
+ next_decoder_cache = () if use_cache else None
629
+
630
+ for idx, decoder_layer in enumerate(self.layers):
631
+ if output_hidden_states:
632
+ all_hidden_states += (hidden_states,)
633
+
634
+ layer_outputs = decoder_layer(
635
+ hidden_states,
636
+ attention_mask=attention_mask,
637
+ position_ids=position_ids,
638
+ past_key_values=past_key_values[idx] if past_key_values is not None else None,
639
+ output_attentions=output_attentions,
640
+ use_cache=use_cache,
641
+ )
642
+
643
+ hidden_states = layer_outputs[0]
644
+
645
+ if use_cache:
646
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
647
+
648
+ if output_attentions:
649
+ all_self_attns += (layer_outputs[1],)
650
+
651
+ hidden_states = self.norm(hidden_states)
652
+
653
+ # add hidden states from the last decoder layer
654
+ if output_hidden_states:
655
+ all_hidden_states += (hidden_states,)
656
+
657
+ next_cache = next_decoder_cache if use_cache else None
658
+ if not return_dict:
659
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
660
+ return BaseModelOutputWithPast(
661
+ last_hidden_state=hidden_states,
662
+ past_key_values=next_cache,
663
+ hidden_states=all_hidden_states,
664
+ attentions=all_self_attns,
665
+ )
666
+
667
+
668
+ class OpenLlamaForCausalLM(OpenLlamaPreTrainedModel):
669
+ def __init__(self, config):
670
+ super().__init__(config)
671
+ self.model = OpenLlamaModel(config)
672
+ if config.shared_input_output_embedding:
673
+ self.lm_head = None
674
+ else:
675
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
676
+
677
+ # Initialize weights and apply final processing
678
+ self.post_init()
679
+
680
+ @add_start_docstrings_to_model_forward(OPEN_LLAMA_INPUTS_DOCSTRING)
681
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
682
+ def forward(
683
+ self,
684
+ input_ids: Optional[torch.LongTensor] = None,
685
+ attention_mask: Optional[torch.Tensor] = None,
686
+ position_ids: Optional[torch.LongTensor] = None,
687
+ past_key_values: Optional[Cache] = None,
688
+ inputs_embeds: Optional[torch.FloatTensor] = None,
689
+ labels: Optional[torch.LongTensor] = None,
690
+ use_cache: Optional[bool] = None,
691
+ output_attentions: Optional[bool] = None,
692
+ output_hidden_states: Optional[bool] = None,
693
+ return_dict: Optional[bool] = None,
694
+ ) -> Union[tuple, CausalLMOutputWithPast]:
695
+ r"""
696
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
697
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
698
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
699
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
700
+
701
+ Returns:
702
+
703
+ Example:
704
+
705
+ ```python
706
+ >>> from transformers import AutoTokenizer, OpenLlamaForCausalLM
707
+
708
+ >>> model = OpenLlamaForCausalLM.from_pretrained("openlm-research/open_llama_7b")
709
+ >>> tokenizer = AutoTokenizer.from_pretrained("openlm-research/open_llama_7b")
710
+
711
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
712
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
713
+
714
+ >>> # Generate
715
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
716
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
717
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
718
+ ```"""
719
+
720
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
721
+ output_hidden_states = (
722
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
723
+ )
724
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
725
+
726
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
727
+ outputs = self.model(
728
+ input_ids=input_ids,
729
+ attention_mask=attention_mask,
730
+ position_ids=position_ids,
731
+ past_key_values=past_key_values,
732
+ inputs_embeds=inputs_embeds,
733
+ use_cache=use_cache,
734
+ output_attentions=output_attentions,
735
+ output_hidden_states=output_hidden_states,
736
+ return_dict=return_dict,
737
+ )
738
+
739
+ hidden_states = outputs[0]
740
+ if self.config.shared_input_output_embedding:
741
+ logits = torch.einsum(
742
+ "blh,vh->blv", hidden_states.to(self.model.embed_tokens.weight.device), self.model.embed_tokens.weight
743
+ )
744
+ else:
745
+ logits = self.lm_head(hidden_states)
746
+
747
+ loss = None
748
+ if labels is not None:
749
+ # move labels to correct device to enable model parallelism
750
+ labels = labels.to(logits.device)
751
+ # Shift so that tokens < n predict n
752
+ shift_logits = logits[..., :-1, :].contiguous()
753
+ shift_labels = labels[..., 1:].contiguous()
754
+ # Flatten the tokens
755
+ loss_fct = CrossEntropyLoss()
756
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
757
+ shift_labels = shift_labels.view(-1)
758
+ # Enable model parallelism
759
+ shift_labels = shift_labels.to(shift_logits.device)
760
+ loss = loss_fct(shift_logits, shift_labels)
761
+
762
+ if not return_dict:
763
+ output = (logits,) + outputs[1:]
764
+ return (loss,) + output if loss is not None else output
765
+
766
+ return CausalLMOutputWithPast(
767
+ loss=loss,
768
+ logits=logits,
769
+ past_key_values=outputs.past_key_values,
770
+ hidden_states=outputs.hidden_states,
771
+ attentions=outputs.attentions,
772
+ )
773
+
774
+ def prepare_inputs_for_generation(
775
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
776
+ ):
777
+ if past_key_values is not None:
778
+ past_length = past_key_values.get_seq_length()
779
+
780
+ # Some generation methods already pass only the last input ID
781
+ if input_ids.shape[1] > past_length:
782
+ remove_prefix_length = past_length
783
+ else:
784
+ # Default to old behavior: keep only final ID
785
+ remove_prefix_length = input_ids.shape[1] - 1
786
+
787
+ input_ids = input_ids[:, remove_prefix_length:]
788
+
789
+ position_ids = kwargs.get("position_ids")
790
+ if attention_mask is not None and position_ids is None:
791
+ # create position_ids on the fly for batch generation
792
+ position_ids = attention_mask.long().cumsum(-1) - 1
793
+ position_ids.masked_fill_(attention_mask == 0, 1)
794
+ if past_key_values:
795
+ position_ids = position_ids[:, -input_ids.shape[1] :]
796
+
797
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
798
+ if inputs_embeds is not None and past_key_values is None:
799
+ model_inputs = {"inputs_embeds": inputs_embeds}
800
+ else:
801
+ model_inputs = {"input_ids": input_ids}
802
+
803
+ model_inputs.update(
804
+ {
805
+ "position_ids": position_ids,
806
+ "past_key_values": past_key_values,
807
+ "use_cache": kwargs.get("use_cache"),
808
+ "attention_mask": attention_mask,
809
+ }
810
+ )
811
+ return model_inputs
812
+
813
+ @staticmethod
814
+ def _reorder_cache(past_key_values, beam_idx):
815
+ reordered_past = ()
816
+ for layer_past in past_key_values:
817
+ reordered_past += (
818
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
819
+ )
820
+ return reordered_past
821
+
822
+
823
+ @add_start_docstrings(
824
+ """
825
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
826
+
827
+ [`OpenLlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal
828
+ models (e.g. GPT-2) do.
829
+
830
+ Since it does classification on the last token, it requires to know the position of the last token. If a
831
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
832
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
833
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
834
+ each row of the batch).
835
+ """,
836
+ OPEN_LLAMA_START_DOCSTRING,
837
+ )
838
+ class OpenLlamaForSequenceClassification(OpenLlamaPreTrainedModel):
839
+ def __init__(self, config):
840
+ super().__init__(config)
841
+ self.num_labels = config.num_labels
842
+ self.model = OpenLlamaModel(config)
843
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
844
+
845
+ # Initialize weights and apply final processing
846
+ self.post_init()
847
+
848
+ @add_start_docstrings_to_model_forward(OPEN_LLAMA_INPUTS_DOCSTRING)
849
+ def forward(
850
+ self,
851
+ input_ids: Optional[torch.LongTensor] = None,
852
+ attention_mask: Optional[torch.Tensor] = None,
853
+ position_ids: Optional[torch.LongTensor] = None,
854
+ past_key_values: Optional[Cache] = None,
855
+ inputs_embeds: Optional[torch.FloatTensor] = None,
856
+ labels: Optional[torch.LongTensor] = None,
857
+ use_cache: Optional[bool] = None,
858
+ output_attentions: Optional[bool] = None,
859
+ output_hidden_states: Optional[bool] = None,
860
+ return_dict: Optional[bool] = None,
861
+ ) -> Union[tuple, SequenceClassifierOutputWithPast]:
862
+ r"""
863
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
864
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
865
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
866
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
867
+ """
868
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
869
+
870
+ transformer_outputs = self.model(
871
+ input_ids,
872
+ attention_mask=attention_mask,
873
+ position_ids=position_ids,
874
+ past_key_values=past_key_values,
875
+ inputs_embeds=inputs_embeds,
876
+ use_cache=use_cache,
877
+ output_attentions=output_attentions,
878
+ output_hidden_states=output_hidden_states,
879
+ return_dict=return_dict,
880
+ )
881
+ hidden_states = transformer_outputs[0]
882
+ logits = self.score(hidden_states)
883
+
884
+ if input_ids is not None:
885
+ batch_size = input_ids.shape[0]
886
+ else:
887
+ batch_size = inputs_embeds.shape[0]
888
+
889
+ if self.config.pad_token_id is None and batch_size != 1:
890
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
891
+ if self.config.pad_token_id is None:
892
+ sequence_lengths = -1
893
+ else:
894
+ if input_ids is not None:
895
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
896
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
897
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
898
+ sequence_lengths = sequence_lengths.to(logits.device)
899
+ else:
900
+ sequence_lengths = -1
901
+
902
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
903
+
904
+ loss = None
905
+ if labels is not None:
906
+ labels = labels.to(logits.device)
907
+ if self.config.problem_type is None:
908
+ if self.num_labels == 1:
909
+ self.config.problem_type = "regression"
910
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
911
+ self.config.problem_type = "single_label_classification"
912
+ else:
913
+ self.config.problem_type = "multi_label_classification"
914
+
915
+ if self.config.problem_type == "regression":
916
+ loss_fct = MSELoss()
917
+ if self.num_labels == 1:
918
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
919
+ else:
920
+ loss = loss_fct(pooled_logits, labels)
921
+ elif self.config.problem_type == "single_label_classification":
922
+ loss_fct = CrossEntropyLoss()
923
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
924
+ elif self.config.problem_type == "multi_label_classification":
925
+ loss_fct = BCEWithLogitsLoss()
926
+ loss = loss_fct(pooled_logits, labels)
927
+ if not return_dict:
928
+ output = (pooled_logits,) + transformer_outputs[1:]
929
+ return ((loss,) + output) if loss is not None else output
930
+
931
+ return SequenceClassifierOutputWithPast(
932
+ loss=loss,
933
+ logits=pooled_logits,
934
+ past_key_values=transformer_outputs.past_key_values,
935
+ hidden_states=transformer_outputs.hidden_states,
936
+ attentions=transformer_outputs.attentions,
937
+ )
938
+
939
+
940
+ __all__ = ["OpenLlamaPreTrainedModel", "OpenLlamaModel", "OpenLlamaForCausalLM", "OpenLlamaForSequenceClassification"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/qdqbert/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 _LazyModule
17
+ from ....utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_qdqbert import *
22
+ from .modeling_qdqbert import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/qdqbert/configuration_qdqbert.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
24
+ class QDQBertConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`QDQBertModel`]. It is used to instantiate an
27
+ QDQBERT model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the BERT
29
+ [google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 30522):
37
+ Vocabulary size of the QDQBERT model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`QDQBertModel`].
39
+ hidden_size (`int`, *optional*, defaults to 768):
40
+ Dimension of the encoder layers and the pooler layer.
41
+ num_hidden_layers (`int`, *optional*, defaults to 12):
42
+ Number of hidden layers in the Transformer encoder.
43
+ num_attention_heads (`int`, *optional*, defaults to 12):
44
+ Number of attention heads for each attention layer in the Transformer encoder.
45
+ intermediate_size (`int`, *optional*, defaults to 3072):
46
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
47
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
48
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
49
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
50
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
51
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
52
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
53
+ The dropout ratio for the attention probabilities.
54
+ max_position_embeddings (`int`, *optional*, defaults to 512):
55
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
56
+ just in case (e.g., 512 or 1024 or 2048).
57
+ type_vocab_size (`int`, *optional*, defaults to 2):
58
+ The vocabulary size of the `token_type_ids` passed when calling [`QDQBertModel`].
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
62
+ The epsilon used by the layer normalization layers.
63
+ is_decoder (`bool`, *optional*, defaults to `False`):
64
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+
69
+ Examples:
70
+
71
+ ```python
72
+ >>> from transformers import QDQBertModel, QDQBertConfig
73
+
74
+ >>> # Initializing a QDQBERT google-bert/bert-base-uncased style configuration
75
+ >>> configuration = QDQBertConfig()
76
+
77
+ >>> # Initializing a model from the google-bert/bert-base-uncased style configuration
78
+ >>> model = QDQBertModel(configuration)
79
+
80
+ >>> # Accessing the model configuration
81
+ >>> configuration = model.config
82
+ ```"""
83
+
84
+ model_type = "qdqbert"
85
+
86
+ def __init__(
87
+ self,
88
+ vocab_size=30522,
89
+ hidden_size=768,
90
+ num_hidden_layers=12,
91
+ num_attention_heads=12,
92
+ intermediate_size=3072,
93
+ hidden_act="gelu",
94
+ hidden_dropout_prob=0.1,
95
+ attention_probs_dropout_prob=0.1,
96
+ max_position_embeddings=512,
97
+ type_vocab_size=2,
98
+ initializer_range=0.02,
99
+ layer_norm_eps=1e-12,
100
+ use_cache=True,
101
+ pad_token_id=1,
102
+ bos_token_id=0,
103
+ eos_token_id=2,
104
+ **kwargs,
105
+ ):
106
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
107
+
108
+ self.vocab_size = vocab_size
109
+ self.max_position_embeddings = max_position_embeddings
110
+ self.hidden_size = hidden_size
111
+ self.num_hidden_layers = num_hidden_layers
112
+ self.num_attention_heads = num_attention_heads
113
+ self.intermediate_size = intermediate_size
114
+ self.hidden_act = hidden_act
115
+ self.hidden_dropout_prob = hidden_dropout_prob
116
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
117
+ self.initializer_range = initializer_range
118
+ self.type_vocab_size = type_vocab_size
119
+ self.layer_norm_eps = layer_norm_eps
120
+ self.use_cache = use_cache
121
+
122
+
123
+ __all__ = ["QDQBertConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/qdqbert/modeling_qdqbert.py ADDED
@@ -0,0 +1,1736 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 NVIDIA Corporation and The HuggingFace Team.
3
+ # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch QDQBERT model."""
17
+
18
+ import math
19
+ import os
20
+ import warnings
21
+ from typing import Optional, Union
22
+
23
+ import torch
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ....activations import ACT2FN
28
+ from ....cache_utils import Cache
29
+ from ....modeling_layers import GradientCheckpointingLayer
30
+ from ....modeling_outputs import (
31
+ BaseModelOutputWithPastAndCrossAttentions,
32
+ BaseModelOutputWithPoolingAndCrossAttentions,
33
+ CausalLMOutputWithCrossAttentions,
34
+ MaskedLMOutput,
35
+ MultipleChoiceModelOutput,
36
+ NextSentencePredictorOutput,
37
+ QuestionAnsweringModelOutput,
38
+ SequenceClassifierOutput,
39
+ TokenClassifierOutput,
40
+ )
41
+ from ....modeling_utils import PreTrainedModel
42
+ from ....pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
43
+ from ....utils import (
44
+ add_code_sample_docstrings,
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ is_pytorch_quantization_available,
48
+ logging,
49
+ replace_return_docstrings,
50
+ requires_backends,
51
+ )
52
+ from ....utils.deprecation import deprecate_kwarg
53
+ from .configuration_qdqbert import QDQBertConfig
54
+
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ # soft dependency
59
+ if is_pytorch_quantization_available():
60
+ try:
61
+ from pytorch_quantization import nn as quant_nn
62
+ from pytorch_quantization.nn.modules.tensor_quantizer import TensorQuantizer
63
+ except OSError:
64
+ logger.error(
65
+ "QDQBERT model are not usable since `pytorch_quantization` can't be loaded. Please try to reinstall it"
66
+ " following the instructions here:"
67
+ " https://github.com/NVIDIA/TensorRT/tree/master/tools/pytorch-quantization."
68
+ )
69
+
70
+ _CHECKPOINT_FOR_DOC = "google-bert/bert-base-uncased"
71
+ _CONFIG_FOR_DOC = "QDQBertConfig"
72
+
73
+
74
+ def load_tf_weights_in_qdqbert(model, tf_checkpoint_path):
75
+ """Load tf checkpoints in a pytorch model."""
76
+ try:
77
+ import re
78
+
79
+ import numpy as np
80
+ import tensorflow as tf
81
+ except ImportError:
82
+ logger.error(
83
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
84
+ "https://www.tensorflow.org/install/ for installation instructions."
85
+ )
86
+ raise
87
+ tf_path = os.path.abspath(tf_checkpoint_path)
88
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
89
+ # Load weights from TF model
90
+ init_vars = tf.train.list_variables(tf_path)
91
+ names = []
92
+ arrays = []
93
+ for name, shape in init_vars:
94
+ logger.info(f"Loading TF weight {name} with shape {shape}")
95
+ array = tf.train.load_variable(tf_path, name)
96
+ names.append(name)
97
+ arrays.append(array)
98
+
99
+ for name, array in zip(names, arrays):
100
+ name = name.split("/")
101
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
102
+ # which are not required for using pretrained model
103
+ if any(
104
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
105
+ for n in name
106
+ ):
107
+ logger.info(f"Skipping {'/'.join(name)}")
108
+ continue
109
+ pointer = model
110
+ for m_name in name:
111
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
112
+ scope_names = re.split(r"_(\d+)", m_name)
113
+ else:
114
+ scope_names = [m_name]
115
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
116
+ pointer = getattr(pointer, "weight")
117
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
118
+ pointer = getattr(pointer, "bias")
119
+ elif scope_names[0] == "output_weights":
120
+ pointer = getattr(pointer, "weight")
121
+ elif scope_names[0] == "squad":
122
+ pointer = getattr(pointer, "classifier")
123
+ else:
124
+ try:
125
+ pointer = getattr(pointer, scope_names[0])
126
+ except AttributeError:
127
+ logger.info(f"Skipping {'/'.join(name)}")
128
+ continue
129
+ if len(scope_names) >= 2:
130
+ num = int(scope_names[1])
131
+ pointer = pointer[num]
132
+ if m_name[-11:] == "_embeddings":
133
+ pointer = getattr(pointer, "weight")
134
+ elif m_name == "kernel":
135
+ array = np.transpose(array)
136
+ try:
137
+ if pointer.shape != array.shape:
138
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
139
+ except AssertionError as e:
140
+ e.args += (pointer.shape, array.shape)
141
+ raise
142
+ logger.info(f"Initialize PyTorch weight {name}")
143
+ pointer.data = torch.from_numpy(array)
144
+ return model
145
+
146
+
147
+ class QDQBertEmbeddings(nn.Module):
148
+ """Construct the embeddings from word, position and token_type embeddings."""
149
+
150
+ def __init__(self, config):
151
+ super().__init__()
152
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
153
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
154
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
155
+
156
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
157
+ # any TensorFlow checkpoint file
158
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
159
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
160
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
161
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
162
+ self.register_buffer(
163
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
164
+ )
165
+ self.register_buffer(
166
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
167
+ )
168
+
169
+ def forward(
170
+ self,
171
+ input_ids: Optional[torch.LongTensor] = None,
172
+ token_type_ids: Optional[torch.LongTensor] = None,
173
+ position_ids: Optional[torch.LongTensor] = None,
174
+ inputs_embeds: Optional[torch.FloatTensor] = None,
175
+ past_key_values_length: int = 0,
176
+ ) -> torch.Tensor:
177
+ if input_ids is not None:
178
+ input_shape = input_ids.size()
179
+ else:
180
+ input_shape = inputs_embeds.size()[:-1]
181
+
182
+ seq_length = input_shape[1]
183
+
184
+ if position_ids is None:
185
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
186
+
187
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
188
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
189
+ # issue #5664
190
+ if token_type_ids is None:
191
+ if hasattr(self, "token_type_ids"):
192
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
193
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
194
+ token_type_ids = buffered_token_type_ids_expanded
195
+ else:
196
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
197
+
198
+ if inputs_embeds is None:
199
+ inputs_embeds = self.word_embeddings(input_ids)
200
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
201
+
202
+ embeddings = inputs_embeds + token_type_embeddings
203
+ if self.position_embedding_type == "absolute":
204
+ position_embeddings = self.position_embeddings(position_ids)
205
+ embeddings += position_embeddings
206
+ embeddings = self.LayerNorm(embeddings)
207
+ embeddings = self.dropout(embeddings)
208
+ return embeddings
209
+
210
+
211
+ class QDQBertSelfAttention(nn.Module):
212
+ def __init__(self, config):
213
+ super().__init__()
214
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
215
+ raise ValueError(
216
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
217
+ f"heads ({config.num_attention_heads})"
218
+ )
219
+
220
+ self.num_attention_heads = config.num_attention_heads
221
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
222
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
223
+
224
+ self.query = quant_nn.QuantLinear(config.hidden_size, self.all_head_size)
225
+ self.key = quant_nn.QuantLinear(config.hidden_size, self.all_head_size)
226
+ self.value = quant_nn.QuantLinear(config.hidden_size, self.all_head_size)
227
+
228
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
229
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
230
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
231
+ self.max_position_embeddings = config.max_position_embeddings
232
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
233
+
234
+ self.is_decoder = config.is_decoder
235
+
236
+ self.matmul_q_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
237
+ self.matmul_k_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
238
+ self.matmul_v_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
239
+ self.matmul_a_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
240
+
241
+ def transpose_for_scores(self, x):
242
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
243
+ x = x.view(*new_x_shape)
244
+ return x.permute(0, 2, 1, 3)
245
+
246
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
247
+ def forward(
248
+ self,
249
+ hidden_states,
250
+ attention_mask=None,
251
+ head_mask=None,
252
+ encoder_hidden_states=None,
253
+ encoder_attention_mask=None,
254
+ past_key_values=None,
255
+ output_attentions=False,
256
+ ):
257
+ mixed_query_layer = self.query(hidden_states)
258
+
259
+ # If this is instantiated as a cross-attention module, the keys
260
+ # and values come from an encoder; the attention mask needs to be
261
+ # such that the encoder's padding tokens are not attended to.
262
+ is_cross_attention = encoder_hidden_states is not None
263
+
264
+ if is_cross_attention and past_key_values is not None:
265
+ # reuse k,v, cross_attentions
266
+ key_layer = past_key_values[0]
267
+ value_layer = past_key_values[1]
268
+ attention_mask = encoder_attention_mask
269
+ elif is_cross_attention:
270
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
271
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
272
+ attention_mask = encoder_attention_mask
273
+ elif past_key_values is not None:
274
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
275
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
276
+ key_layer = torch.cat([past_key_values[0], key_layer], dim=2)
277
+ value_layer = torch.cat([past_key_values[1], value_layer], dim=2)
278
+ else:
279
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
280
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
281
+
282
+ query_layer = self.transpose_for_scores(mixed_query_layer)
283
+
284
+ if self.is_decoder:
285
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
286
+ # Further calls to cross_attention layer can then reuse all cross-attention
287
+ # key/value_states (first "if" case)
288
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
289
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
290
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
291
+ # if encoder bi-directional self-attention `past_key_values` is always `None`
292
+ past_key_values = (key_layer, value_layer)
293
+
294
+ # Take the dot product between "query" and "key" to get the raw attention scores.
295
+ attention_scores = torch.matmul(
296
+ self.matmul_q_input_quantizer(query_layer), self.matmul_k_input_quantizer(key_layer.transpose(-1, -2))
297
+ )
298
+
299
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
300
+ seq_length = hidden_states.size()[1]
301
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
302
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
303
+ distance = position_ids_l - position_ids_r
304
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
305
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
306
+
307
+ if self.position_embedding_type == "relative_key":
308
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
309
+ attention_scores = attention_scores + relative_position_scores
310
+ elif self.position_embedding_type == "relative_key_query":
311
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
312
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
313
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
314
+
315
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
316
+ if attention_mask is not None:
317
+ # Apply the attention mask is (precomputed for all layers in QDQBertModel forward() function)
318
+ attention_scores = attention_scores + attention_mask
319
+
320
+ # Normalize the attention scores to probabilities.
321
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
322
+
323
+ # This is actually dropping out entire tokens to attend to, which might
324
+ # seem a bit unusual, but is taken from the original Transformer paper.
325
+ attention_probs = self.dropout(attention_probs)
326
+
327
+ # Mask heads if we want to
328
+ if head_mask is not None:
329
+ attention_probs = attention_probs * head_mask
330
+
331
+ context_layer = torch.matmul(
332
+ self.matmul_a_input_quantizer(attention_probs), self.matmul_v_input_quantizer(value_layer)
333
+ )
334
+
335
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
336
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
337
+ context_layer = context_layer.view(*new_context_layer_shape)
338
+
339
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
340
+
341
+ if self.is_decoder:
342
+ outputs = outputs + (past_key_values,)
343
+ return outputs
344
+
345
+
346
+ class QDQBertSelfOutput(nn.Module):
347
+ def __init__(self, config):
348
+ super().__init__()
349
+ # Quantize Linear layer
350
+ self.dense = quant_nn.QuantLinear(config.hidden_size, config.hidden_size)
351
+
352
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
353
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
354
+
355
+ # Quantize the inputs to the residual add
356
+ self.add_local_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
357
+ self.add_residual_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
358
+
359
+ def forward(self, hidden_states, input_tensor):
360
+ hidden_states = self.dense(hidden_states)
361
+ hidden_states = self.dropout(hidden_states)
362
+ # Quantize the inputs to the residual add
363
+ add_local = self.add_local_input_quantizer(hidden_states)
364
+ add_residual = self.add_residual_input_quantizer(input_tensor)
365
+ hidden_states = self.LayerNorm(add_local + add_residual)
366
+ return hidden_states
367
+
368
+
369
+ # Based on transformers.models.bert.modeling_bert.BertAttention with Bert -> QDQBert
370
+ class QDQBertAttention(nn.Module):
371
+ def __init__(self, config):
372
+ super().__init__()
373
+ self.self = QDQBertSelfAttention(config)
374
+ self.output = QDQBertSelfOutput(config)
375
+ self.pruned_heads = set()
376
+
377
+ def prune_heads(self, heads):
378
+ if len(heads) == 0:
379
+ return
380
+ heads, index = find_pruneable_heads_and_indices(
381
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
382
+ )
383
+
384
+ # Prune linear layers
385
+ self.self.query = prune_linear_layer(self.self.query, index)
386
+ self.self.key = prune_linear_layer(self.self.key, index)
387
+ self.self.value = prune_linear_layer(self.self.value, index)
388
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
389
+
390
+ # Update hyper params and store pruned heads
391
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
392
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
393
+ self.pruned_heads = self.pruned_heads.union(heads)
394
+
395
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
396
+ def forward(
397
+ self,
398
+ hidden_states,
399
+ attention_mask=None,
400
+ head_mask=None,
401
+ encoder_hidden_states=None,
402
+ encoder_attention_mask=None,
403
+ past_key_values=None,
404
+ output_attentions=False,
405
+ ):
406
+ self_outputs = self.self(
407
+ hidden_states,
408
+ attention_mask,
409
+ head_mask,
410
+ encoder_hidden_states,
411
+ encoder_attention_mask,
412
+ past_key_values,
413
+ output_attentions,
414
+ )
415
+ attention_output = self.output(self_outputs[0], hidden_states)
416
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
417
+ return outputs
418
+
419
+
420
+ class QDQBertIntermediate(nn.Module):
421
+ def __init__(self, config):
422
+ super().__init__()
423
+ # Quantize Linear layer
424
+ self.dense = quant_nn.QuantLinear(config.hidden_size, config.intermediate_size)
425
+ if isinstance(config.hidden_act, str):
426
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
427
+ else:
428
+ self.intermediate_act_fn = config.hidden_act
429
+
430
+ def forward(self, hidden_states):
431
+ hidden_states = self.dense(hidden_states)
432
+ hidden_states = self.intermediate_act_fn(hidden_states)
433
+ return hidden_states
434
+
435
+
436
+ class QDQBertOutput(nn.Module):
437
+ def __init__(self, config):
438
+ super().__init__()
439
+ # Quantize Linear layer
440
+ self.dense = quant_nn.QuantLinear(config.intermediate_size, config.hidden_size)
441
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
442
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
443
+
444
+ # Quantize the inputs to the residual add
445
+ self.add_local_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
446
+ self.add_residual_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
447
+
448
+ def forward(self, hidden_states, input_tensor):
449
+ hidden_states = self.dense(hidden_states)
450
+ hidden_states = self.dropout(hidden_states)
451
+ # Quantize the inputs to the residual add
452
+ add_local = self.add_local_input_quantizer(hidden_states)
453
+ add_residual = self.add_residual_input_quantizer(input_tensor)
454
+ hidden_states = self.LayerNorm(add_local + add_residual)
455
+ return hidden_states
456
+
457
+
458
+ # Based on transformers.models.bert.modeling_bert.BertLayer with Bert -> QDQBert
459
+ class QDQBertLayer(GradientCheckpointingLayer):
460
+ def __init__(self, config):
461
+ super().__init__()
462
+ self.seq_len_dim = 1
463
+ self.attention = QDQBertAttention(config)
464
+ self.is_decoder = config.is_decoder
465
+ self.add_cross_attention = config.add_cross_attention
466
+ if self.add_cross_attention:
467
+ if not self.is_decoder:
468
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
469
+ self.crossattention = QDQBertAttention(config)
470
+ self.intermediate = QDQBertIntermediate(config)
471
+ self.output = QDQBertOutput(config)
472
+
473
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
474
+ def forward(
475
+ self,
476
+ hidden_states,
477
+ attention_mask=None,
478
+ head_mask=None,
479
+ encoder_hidden_states=None,
480
+ encoder_attention_mask=None,
481
+ past_key_values=None,
482
+ output_attentions=False,
483
+ ):
484
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
485
+ self_attn_past_key_value = past_key_values[:2] if past_key_values is not None else None
486
+ self_attention_outputs = self.attention(
487
+ hidden_states,
488
+ attention_mask,
489
+ head_mask,
490
+ output_attentions=output_attentions,
491
+ past_key_values=self_attn_past_key_value,
492
+ )
493
+ attention_output = self_attention_outputs[0]
494
+
495
+ # if decoder, the last output is tuple of self-attn cache
496
+ if self.is_decoder:
497
+ outputs = self_attention_outputs[1:-1]
498
+ present_key_value = self_attention_outputs[-1]
499
+ else:
500
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
501
+
502
+ cross_attn_present_key_value = None
503
+ if self.is_decoder and encoder_hidden_states is not None:
504
+ if not hasattr(self, "crossattention"):
505
+ raise ValueError(
506
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
507
+ " by setting `config.add_cross_attention=True`"
508
+ )
509
+
510
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_values tuple
511
+ cross_attn_past_key_value = past_key_values[-2:] if past_key_values is not None else None
512
+ cross_attention_outputs = self.crossattention(
513
+ attention_output,
514
+ attention_mask,
515
+ head_mask,
516
+ encoder_hidden_states,
517
+ encoder_attention_mask,
518
+ cross_attn_past_key_value,
519
+ output_attentions,
520
+ )
521
+ attention_output = cross_attention_outputs[0]
522
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
523
+
524
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
525
+ cross_attn_present_key_value = cross_attention_outputs[-1]
526
+ present_key_value = present_key_value + cross_attn_present_key_value
527
+
528
+ layer_output = self.feed_forward_chunk(attention_output)
529
+ outputs = (layer_output,) + outputs
530
+
531
+ # if decoder, return the attn key/values as the last output
532
+ if self.is_decoder:
533
+ outputs = outputs + (present_key_value,)
534
+
535
+ return outputs
536
+
537
+ def feed_forward_chunk(self, attention_output):
538
+ intermediate_output = self.intermediate(attention_output)
539
+ layer_output = self.output(intermediate_output, attention_output)
540
+ return layer_output
541
+
542
+
543
+ # Based on transformers.models.bert.modeling_bert.BertEncoder with Bert -> QDQBert
544
+ class QDQBertEncoder(nn.Module):
545
+ def __init__(self, config):
546
+ super().__init__()
547
+ self.config = config
548
+ self.layer = nn.ModuleList([QDQBertLayer(config) for _ in range(config.num_hidden_layers)])
549
+ self.gradient_checkpointing = False
550
+
551
+ def forward(
552
+ self,
553
+ hidden_states,
554
+ attention_mask=None,
555
+ head_mask=None,
556
+ encoder_hidden_states=None,
557
+ encoder_attention_mask=None,
558
+ past_key_values=None,
559
+ use_cache=None,
560
+ output_attentions=False,
561
+ output_hidden_states=False,
562
+ return_dict=True,
563
+ ):
564
+ all_hidden_states = () if output_hidden_states else None
565
+ all_self_attentions = () if output_attentions else None
566
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
567
+
568
+ next_decoder_cache = () if use_cache else None
569
+ for i, layer_module in enumerate(self.layer):
570
+ if output_hidden_states:
571
+ all_hidden_states = all_hidden_states + (hidden_states,)
572
+
573
+ layer_head_mask = head_mask[i] if head_mask is not None else None
574
+
575
+ layer_outputs = layer_module(
576
+ hidden_states,
577
+ attention_mask,
578
+ layer_head_mask,
579
+ encoder_hidden_states,
580
+ encoder_attention_mask,
581
+ past_key_values[i] if past_key_values is not None else None,
582
+ output_attentions,
583
+ )
584
+
585
+ hidden_states = layer_outputs[0]
586
+ if use_cache:
587
+ next_decoder_cache += (layer_outputs[-1],)
588
+ if output_attentions:
589
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
590
+ if self.config.add_cross_attention:
591
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
592
+
593
+ if output_hidden_states:
594
+ all_hidden_states = all_hidden_states + (hidden_states,)
595
+
596
+ if not return_dict:
597
+ return tuple(
598
+ v
599
+ for v in [
600
+ hidden_states,
601
+ next_decoder_cache,
602
+ all_hidden_states,
603
+ all_self_attentions,
604
+ all_cross_attentions,
605
+ ]
606
+ if v is not None
607
+ )
608
+ return BaseModelOutputWithPastAndCrossAttentions(
609
+ last_hidden_state=hidden_states,
610
+ past_key_values=next_decoder_cache,
611
+ hidden_states=all_hidden_states,
612
+ attentions=all_self_attentions,
613
+ cross_attentions=all_cross_attentions,
614
+ )
615
+
616
+
617
+ class QDQBertPooler(nn.Module):
618
+ def __init__(self, config):
619
+ super().__init__()
620
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
621
+ self.activation = nn.Tanh()
622
+
623
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
624
+ # We "pool" the model by simply taking the hidden state corresponding
625
+ # to the first token.
626
+ first_token_tensor = hidden_states[:, 0]
627
+ pooled_output = self.dense(first_token_tensor)
628
+ pooled_output = self.activation(pooled_output)
629
+ return pooled_output
630
+
631
+
632
+ class QDQBertPredictionHeadTransform(nn.Module):
633
+ def __init__(self, config):
634
+ super().__init__()
635
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
636
+ if isinstance(config.hidden_act, str):
637
+ self.transform_act_fn = ACT2FN[config.hidden_act]
638
+ else:
639
+ self.transform_act_fn = config.hidden_act
640
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
641
+
642
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
643
+ hidden_states = self.dense(hidden_states)
644
+ hidden_states = self.transform_act_fn(hidden_states)
645
+ hidden_states = self.LayerNorm(hidden_states)
646
+ return hidden_states
647
+
648
+
649
+ # Based on transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert -> QDQBert
650
+ class QDQBertLMPredictionHead(nn.Module):
651
+ def __init__(self, config):
652
+ super().__init__()
653
+ self.transform = QDQBertPredictionHeadTransform(config)
654
+
655
+ # The output weights are the same as the input embeddings, but there is
656
+ # an output-only bias for each token.
657
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
658
+
659
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
660
+
661
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
662
+ self.decoder.bias = self.bias
663
+
664
+ def _tie_weights(self):
665
+ self.decoder.bias = self.bias
666
+
667
+ def forward(self, hidden_states):
668
+ hidden_states = self.transform(hidden_states)
669
+ hidden_states = self.decoder(hidden_states)
670
+ return hidden_states
671
+
672
+
673
+ # Based on transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert -> QDQBert
674
+ class QDQBertOnlyMLMHead(nn.Module):
675
+ def __init__(self, config):
676
+ super().__init__()
677
+ self.predictions = QDQBertLMPredictionHead(config)
678
+
679
+ def forward(self, sequence_output):
680
+ prediction_scores = self.predictions(sequence_output)
681
+ return prediction_scores
682
+
683
+
684
+ class QDQBertOnlyNSPHead(nn.Module):
685
+ def __init__(self, config):
686
+ super().__init__()
687
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
688
+
689
+ def forward(self, pooled_output):
690
+ seq_relationship_score = self.seq_relationship(pooled_output)
691
+ return seq_relationship_score
692
+
693
+
694
+ # Based on transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert -> QDQBert
695
+ class QDQBertPreTrainingHeads(nn.Module):
696
+ def __init__(self, config):
697
+ super().__init__()
698
+ self.predictions = QDQBertLMPredictionHead(config)
699
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
700
+
701
+ def forward(self, sequence_output, pooled_output):
702
+ prediction_scores = self.predictions(sequence_output)
703
+ seq_relationship_score = self.seq_relationship(pooled_output)
704
+ return prediction_scores, seq_relationship_score
705
+
706
+
707
+ # Based on transformers.models.bert.modeling_bert.BertPreTrainedModel with Bert -> QDQBert
708
+ class QDQBertPreTrainedModel(PreTrainedModel):
709
+ """
710
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
711
+ models.
712
+ """
713
+
714
+ config: QDQBertConfig
715
+ load_tf_weights = load_tf_weights_in_qdqbert
716
+ base_model_prefix = "bert"
717
+ supports_gradient_checkpointing = True
718
+
719
+ def _init_weights(self, module):
720
+ """Initialize the weights"""
721
+ if isinstance(module, nn.Linear):
722
+ # Slightly different from the TF version which uses truncated_normal for initialization
723
+ # cf https://github.com/pytorch/pytorch/pull/5617
724
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
725
+ if module.bias is not None:
726
+ module.bias.data.zero_()
727
+ elif isinstance(module, nn.Embedding):
728
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
729
+ if module.padding_idx is not None:
730
+ module.weight.data[module.padding_idx].zero_()
731
+ elif isinstance(module, nn.LayerNorm):
732
+ module.bias.data.zero_()
733
+ module.weight.data.fill_(1.0)
734
+
735
+
736
+ QDQBERT_START_DOCSTRING = r"""
737
+
738
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
739
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
740
+ etc.)
741
+
742
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
743
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
744
+ and behavior.
745
+
746
+ Parameters:
747
+ config ([`QDQBertConfig`]): Model configuration class with all the parameters of the model.
748
+ Initializing with a config file does not load the weights associated with the model, only the
749
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
750
+ """
751
+
752
+ QDQBERT_INPUTS_DOCSTRING = r"""
753
+ Args:
754
+ input_ids (`torch.LongTensor` of shape `({0})`):
755
+ Indices of input sequence tokens in the vocabulary.
756
+
757
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
758
+ [`PreTrainedTokenizer.__call__`] for details.
759
+
760
+ [What are input IDs?](../glossary#input-ids)
761
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
762
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
763
+
764
+ - 1 for tokens that are **not masked**,
765
+ - 0 for tokens that are **masked**.
766
+
767
+ [What are attention masks?](../glossary#attention-mask)
768
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
769
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
770
+ 1]`:
771
+
772
+ - 0 corresponds to a *sentence A* token,
773
+ - 1 corresponds to a *sentence B* token.
774
+
775
+ [What are token type IDs?](../glossary#token-type-ids)
776
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
777
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
778
+ config.max_position_embeddings - 1]`.
779
+
780
+ [What are position IDs?](../glossary#position-ids)
781
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
782
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
783
+
784
+ - 1 indicates the head is **not masked**,
785
+ - 0 indicates the head is **masked**.
786
+
787
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
788
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
789
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
790
+ model's internal embedding lookup matrix.
791
+ output_attentions (`bool`, *optional*):
792
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
793
+ tensors for more detail.
794
+ output_hidden_states (`bool`, *optional*):
795
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
796
+ more detail.
797
+ return_dict (`bool`, *optional*):
798
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
799
+ """
800
+
801
+
802
+ @add_start_docstrings(
803
+ "The bare QDQBERT Model transformer outputting raw hidden-states without any specific head on top.",
804
+ QDQBERT_START_DOCSTRING,
805
+ )
806
+ class QDQBertModel(QDQBertPreTrainedModel):
807
+ """
808
+
809
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
810
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
811
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
812
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
813
+
814
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
815
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
816
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
817
+ """
818
+
819
+ def __init__(self, config, add_pooling_layer: bool = True):
820
+ requires_backends(self, "pytorch_quantization")
821
+ super().__init__(config)
822
+ self.config = config
823
+
824
+ self.embeddings = QDQBertEmbeddings(config)
825
+ self.encoder = QDQBertEncoder(config)
826
+
827
+ self.pooler = QDQBertPooler(config) if add_pooling_layer else None
828
+
829
+ # Initialize weights and apply final processing
830
+ self.post_init()
831
+
832
+ def get_input_embeddings(self):
833
+ return self.embeddings.word_embeddings
834
+
835
+ def set_input_embeddings(self, value):
836
+ self.embeddings.word_embeddings = value
837
+
838
+ def _prune_heads(self, heads_to_prune: dict[int, list[int]]):
839
+ """
840
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
841
+ class PreTrainedModel
842
+ """
843
+ for layer, heads in heads_to_prune.items():
844
+ self.encoder.layer[layer].attention.prune_heads(heads)
845
+
846
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
847
+ @add_code_sample_docstrings(
848
+ checkpoint=_CHECKPOINT_FOR_DOC,
849
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
850
+ config_class=_CONFIG_FOR_DOC,
851
+ )
852
+ def forward(
853
+ self,
854
+ input_ids: Optional[torch.LongTensor] = None,
855
+ attention_mask: Optional[torch.FloatTensor] = None,
856
+ token_type_ids: Optional[torch.LongTensor] = None,
857
+ position_ids: Optional[torch.LongTensor] = None,
858
+ head_mask: Optional[torch.FloatTensor] = None,
859
+ inputs_embeds: Optional[torch.FloatTensor] = None,
860
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
861
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
862
+ past_key_values: Optional[Cache] = None,
863
+ use_cache: Optional[bool] = None,
864
+ output_attentions: Optional[bool] = None,
865
+ output_hidden_states: Optional[bool] = None,
866
+ return_dict: Optional[bool] = None,
867
+ ) -> Union[tuple, BaseModelOutputWithPoolingAndCrossAttentions]:
868
+ r"""
869
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
870
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
871
+ the model is configured as a decoder.
872
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
873
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
874
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
875
+
876
+ - 1 for tokens that are **not masked**,
877
+ - 0 for tokens that are **masked**.
878
+ 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)`):
879
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
880
+
881
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
882
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
883
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
884
+ use_cache (`bool`, *optional*):
885
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
886
+ `past_key_values`).
887
+ """
888
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
889
+ output_hidden_states = (
890
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
891
+ )
892
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
893
+
894
+ if self.config.is_decoder:
895
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
896
+ else:
897
+ use_cache = False
898
+
899
+ if input_ids is not None and inputs_embeds is not None:
900
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
901
+ elif input_ids is not None:
902
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
903
+ input_shape = input_ids.size()
904
+ batch_size, seq_length = input_shape
905
+ elif inputs_embeds is not None:
906
+ input_shape = inputs_embeds.size()[:-1]
907
+ batch_size, seq_length = input_shape
908
+ else:
909
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
910
+
911
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
912
+
913
+ # past_key_values_length
914
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
915
+
916
+ if attention_mask is None:
917
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
918
+
919
+ if token_type_ids is None:
920
+ if hasattr(self.embeddings, "token_type_ids"):
921
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
922
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
923
+ token_type_ids = buffered_token_type_ids_expanded
924
+ else:
925
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
926
+
927
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
928
+ # ourselves in which case we just need to make it broadcastable to all heads.
929
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
930
+
931
+ # If a 2D or 3D attention mask is provided for the cross-attention
932
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
933
+ if self.config.is_decoder and encoder_hidden_states is not None:
934
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
935
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
936
+ if encoder_attention_mask is None:
937
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
938
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
939
+ else:
940
+ encoder_extended_attention_mask = None
941
+
942
+ # Prepare head mask if needed
943
+ # 1.0 in head_mask indicate we keep the head
944
+ # attention_probs has shape bsz x n_heads x N x N
945
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
946
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
947
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
948
+
949
+ embedding_output = self.embeddings(
950
+ input_ids=input_ids,
951
+ position_ids=position_ids,
952
+ token_type_ids=token_type_ids,
953
+ inputs_embeds=inputs_embeds,
954
+ past_key_values_length=past_key_values_length,
955
+ )
956
+ encoder_outputs = self.encoder(
957
+ embedding_output,
958
+ attention_mask=extended_attention_mask,
959
+ head_mask=head_mask,
960
+ encoder_hidden_states=encoder_hidden_states,
961
+ encoder_attention_mask=encoder_extended_attention_mask,
962
+ past_key_values=past_key_values,
963
+ use_cache=use_cache,
964
+ output_attentions=output_attentions,
965
+ output_hidden_states=output_hidden_states,
966
+ return_dict=return_dict,
967
+ )
968
+ sequence_output = encoder_outputs[0]
969
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
970
+
971
+ if not return_dict:
972
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
973
+
974
+ return BaseModelOutputWithPoolingAndCrossAttentions(
975
+ last_hidden_state=sequence_output,
976
+ pooler_output=pooled_output,
977
+ past_key_values=encoder_outputs.past_key_values,
978
+ hidden_states=encoder_outputs.hidden_states,
979
+ attentions=encoder_outputs.attentions,
980
+ cross_attentions=encoder_outputs.cross_attentions,
981
+ )
982
+
983
+
984
+ @add_start_docstrings(
985
+ """QDQBERT Model with a `language modeling` head on top for CLM fine-tuning.""", QDQBERT_START_DOCSTRING
986
+ )
987
+ class QDQBertLMHeadModel(QDQBertPreTrainedModel):
988
+ _tied_weights_keys = ["predictions.decoder.weight", "predictions.decoder.bias"]
989
+
990
+ def __init__(self, config):
991
+ super().__init__(config)
992
+
993
+ if not config.is_decoder:
994
+ logger.warning("If you want to use `QDQBertLMHeadModel` as a standalone, add `is_decoder=True.`")
995
+
996
+ self.bert = QDQBertModel(config, add_pooling_layer=False)
997
+ self.cls = QDQBertOnlyMLMHead(config)
998
+
999
+ # Initialize weights and apply final processing
1000
+ self.post_init()
1001
+
1002
+ def get_output_embeddings(self):
1003
+ return self.cls.predictions.decoder
1004
+
1005
+ def set_output_embeddings(self, new_embeddings):
1006
+ self.cls.predictions.decoder = new_embeddings
1007
+ self.cls.predictions.bias = new_embeddings.bias
1008
+
1009
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1010
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
1011
+ def forward(
1012
+ self,
1013
+ input_ids: Optional[torch.LongTensor] = None,
1014
+ attention_mask: Optional[torch.Tensor] = None,
1015
+ token_type_ids: Optional[torch.LongTensor] = None,
1016
+ position_ids: Optional[torch.LongTensor] = None,
1017
+ head_mask: Optional[torch.Tensor] = None,
1018
+ inputs_embeds: Optional[torch.Tensor] = None,
1019
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1020
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1021
+ labels: Optional[torch.LongTensor] = None,
1022
+ past_key_values: Optional[tuple[tuple[torch.LongTensor]]] = None,
1023
+ use_cache: Optional[bool] = None,
1024
+ output_attentions: Optional[bool] = None,
1025
+ output_hidden_states: Optional[bool] = None,
1026
+ return_dict: Optional[bool] = None,
1027
+ ) -> Union[tuple, CausalLMOutputWithCrossAttentions]:
1028
+ r"""
1029
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1030
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1031
+ the model is configured as a decoder.
1032
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1033
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1034
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1035
+
1036
+ - 1 for tokens that are **not masked**,
1037
+ - 0 for tokens that are **masked**.
1038
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1039
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1040
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1041
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
1042
+ 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)`):
1043
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1044
+
1045
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1046
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1047
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1048
+ use_cache (`bool`, *optional*):
1049
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1050
+ `past_key_values`).
1051
+
1052
+ Returns:
1053
+
1054
+ Example:
1055
+
1056
+ ```python
1057
+ >>> from transformers import AutoTokenizer, QDQBertLMHeadModel, QDQBertConfig
1058
+ >>> import torch
1059
+
1060
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
1061
+ >>> config = QDQBertConfig.from_pretrained("google-bert/bert-base-cased")
1062
+ >>> config.is_decoder = True
1063
+ >>> model = QDQBertLMHeadModel.from_pretrained("google-bert/bert-base-cased", config=config)
1064
+
1065
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1066
+ >>> outputs = model(**inputs)
1067
+
1068
+ >>> prediction_logits = outputs.logits
1069
+ ```"""
1070
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1071
+ if labels is not None:
1072
+ use_cache = False
1073
+
1074
+ outputs = self.bert(
1075
+ input_ids,
1076
+ attention_mask=attention_mask,
1077
+ token_type_ids=token_type_ids,
1078
+ position_ids=position_ids,
1079
+ head_mask=head_mask,
1080
+ inputs_embeds=inputs_embeds,
1081
+ encoder_hidden_states=encoder_hidden_states,
1082
+ encoder_attention_mask=encoder_attention_mask,
1083
+ past_key_values=past_key_values,
1084
+ use_cache=use_cache,
1085
+ output_attentions=output_attentions,
1086
+ output_hidden_states=output_hidden_states,
1087
+ return_dict=return_dict,
1088
+ )
1089
+
1090
+ sequence_output = outputs[0]
1091
+ prediction_scores = self.cls(sequence_output)
1092
+
1093
+ lm_loss = None
1094
+ if labels is not None:
1095
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1096
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
1097
+ labels = labels[:, 1:].contiguous()
1098
+ loss_fct = CrossEntropyLoss()
1099
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1100
+
1101
+ if not return_dict:
1102
+ output = (prediction_scores,) + outputs[2:]
1103
+ return ((lm_loss,) + output) if lm_loss is not None else output
1104
+
1105
+ return CausalLMOutputWithCrossAttentions(
1106
+ loss=lm_loss,
1107
+ logits=prediction_scores,
1108
+ past_key_values=outputs.past_key_values,
1109
+ hidden_states=outputs.hidden_states,
1110
+ attentions=outputs.attentions,
1111
+ cross_attentions=outputs.cross_attentions,
1112
+ )
1113
+
1114
+ def prepare_inputs_for_generation(
1115
+ self,
1116
+ input_ids: Optional[torch.LongTensor],
1117
+ past_key_values=None,
1118
+ attention_mask: Optional[torch.Tensor] = None,
1119
+ **model_kwargs,
1120
+ ):
1121
+ input_shape = input_ids.shape
1122
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1123
+ if attention_mask is None:
1124
+ attention_mask = input_ids.new_ones(input_shape)
1125
+
1126
+ # cut decoder_input_ids if past_key_values is used
1127
+ if past_key_values is not None:
1128
+ past_length = past_key_values.get_seq_length()
1129
+
1130
+ # Some generation methods already pass only the last input ID
1131
+ if input_ids.shape[1] > past_length:
1132
+ remove_prefix_length = past_length
1133
+ else:
1134
+ # Default to old behavior: keep only final ID
1135
+ remove_prefix_length = input_ids.shape[1] - 1
1136
+
1137
+ input_ids = input_ids[:, remove_prefix_length:]
1138
+
1139
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
1140
+
1141
+ def _reorder_cache(self, past_key_values, beam_idx):
1142
+ reordered_past = ()
1143
+ for layer_past in past_key_values:
1144
+ reordered_past += (
1145
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1146
+ )
1147
+ return reordered_past
1148
+
1149
+
1150
+ @add_start_docstrings("""QDQBERT Model with a `language modeling` head on top.""", QDQBERT_START_DOCSTRING)
1151
+ class QDQBertForMaskedLM(QDQBertPreTrainedModel):
1152
+ _tied_weights_keys = ["predictions.decoder.weight", "predictions.decoder.bias"]
1153
+
1154
+ def __init__(self, config):
1155
+ super().__init__(config)
1156
+
1157
+ if config.is_decoder:
1158
+ logger.warning(
1159
+ "If you want to use `QDQBertForMaskedLM` make sure `config.is_decoder=False` for "
1160
+ "bi-directional self-attention."
1161
+ )
1162
+
1163
+ self.bert = QDQBertModel(config, add_pooling_layer=False)
1164
+ self.cls = QDQBertOnlyMLMHead(config)
1165
+
1166
+ # Initialize weights and apply final processing
1167
+ self.post_init()
1168
+
1169
+ def get_output_embeddings(self):
1170
+ return self.cls.predictions.decoder
1171
+
1172
+ def set_output_embeddings(self, new_embeddings):
1173
+ self.cls.predictions.decoder = new_embeddings
1174
+ self.cls.predictions.bias = new_embeddings.bias
1175
+
1176
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1177
+ @add_code_sample_docstrings(
1178
+ checkpoint=_CHECKPOINT_FOR_DOC,
1179
+ output_type=MaskedLMOutput,
1180
+ config_class=_CONFIG_FOR_DOC,
1181
+ )
1182
+ def forward(
1183
+ self,
1184
+ input_ids: Optional[torch.LongTensor] = None,
1185
+ attention_mask: Optional[torch.FloatTensor] = None,
1186
+ token_type_ids: Optional[torch.LongTensor] = None,
1187
+ position_ids: Optional[torch.LongTensor] = None,
1188
+ head_mask: Optional[torch.FloatTensor] = None,
1189
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1190
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1191
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1192
+ labels: Optional[torch.LongTensor] = None,
1193
+ output_attentions: Optional[bool] = None,
1194
+ output_hidden_states: Optional[bool] = None,
1195
+ return_dict: Optional[bool] = None,
1196
+ ) -> Union[tuple, MaskedLMOutput]:
1197
+ r"""
1198
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1199
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1200
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1201
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1202
+ """
1203
+
1204
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1205
+
1206
+ outputs = self.bert(
1207
+ 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
+ encoder_hidden_states=encoder_hidden_states,
1214
+ encoder_attention_mask=encoder_attention_mask,
1215
+ output_attentions=output_attentions,
1216
+ output_hidden_states=output_hidden_states,
1217
+ return_dict=return_dict,
1218
+ )
1219
+
1220
+ sequence_output = outputs[0]
1221
+ prediction_scores = self.cls(sequence_output)
1222
+
1223
+ masked_lm_loss = None
1224
+ if labels is not None:
1225
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1226
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1227
+
1228
+ if not return_dict:
1229
+ output = (prediction_scores,) + outputs[2:]
1230
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1231
+
1232
+ return MaskedLMOutput(
1233
+ loss=masked_lm_loss,
1234
+ logits=prediction_scores,
1235
+ hidden_states=outputs.hidden_states,
1236
+ attentions=outputs.attentions,
1237
+ )
1238
+
1239
+ def prepare_inputs_for_generation(
1240
+ self, input_ids: torch.LongTensor, attention_mask: Optional[torch.FloatTensor] = None, **model_kwargs
1241
+ ):
1242
+ input_shape = input_ids.shape
1243
+ effective_batch_size = input_shape[0]
1244
+
1245
+ # add a dummy token
1246
+ if self.config.pad_token_id is None:
1247
+ raise ValueError("The PAD token should be defined for generation")
1248
+
1249
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
1250
+ dummy_token = torch.full(
1251
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
1252
+ )
1253
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
1254
+
1255
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
1256
+
1257
+
1258
+ @add_start_docstrings(
1259
+ """Bert Model with a `next sentence prediction (classification)` head on top.""",
1260
+ QDQBERT_START_DOCSTRING,
1261
+ )
1262
+ class QDQBertForNextSentencePrediction(QDQBertPreTrainedModel):
1263
+ def __init__(self, config):
1264
+ super().__init__(config)
1265
+
1266
+ self.bert = QDQBertModel(config)
1267
+ self.cls = QDQBertOnlyNSPHead(config)
1268
+
1269
+ # Initialize weights and apply final processing
1270
+ self.post_init()
1271
+
1272
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1273
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
1274
+ def forward(
1275
+ self,
1276
+ input_ids: Optional[torch.LongTensor] = None,
1277
+ attention_mask: Optional[torch.FloatTensor] = None,
1278
+ token_type_ids: Optional[torch.LongTensor] = None,
1279
+ position_ids: Optional[torch.LongTensor] = None,
1280
+ head_mask: Optional[torch.FloatTensor] = None,
1281
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1282
+ labels: Optional[torch.LongTensor] = None,
1283
+ output_attentions: Optional[bool] = None,
1284
+ output_hidden_states: Optional[bool] = None,
1285
+ return_dict: Optional[bool] = None,
1286
+ **kwargs,
1287
+ ) -> Union[tuple, NextSentencePredictorOutput]:
1288
+ r"""
1289
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1290
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1291
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
1292
+
1293
+ - 0 indicates sequence B is a continuation of sequence A,
1294
+ - 1 indicates sequence B is a random sequence.
1295
+
1296
+ Returns:
1297
+
1298
+ Example:
1299
+
1300
+ ```python
1301
+ >>> from transformers import AutoTokenizer, QDQBertForNextSentencePrediction
1302
+ >>> import torch
1303
+
1304
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1305
+ >>> model = QDQBertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
1306
+
1307
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1308
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1309
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
1310
+
1311
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
1312
+ >>> logits = outputs.logits
1313
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
1314
+ ```"""
1315
+
1316
+ if "next_sentence_label" in kwargs:
1317
+ warnings.warn(
1318
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
1319
+ " `labels` instead.",
1320
+ FutureWarning,
1321
+ )
1322
+ labels = kwargs.pop("next_sentence_label")
1323
+
1324
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1325
+
1326
+ outputs = self.bert(
1327
+ input_ids,
1328
+ attention_mask=attention_mask,
1329
+ token_type_ids=token_type_ids,
1330
+ position_ids=position_ids,
1331
+ head_mask=head_mask,
1332
+ inputs_embeds=inputs_embeds,
1333
+ output_attentions=output_attentions,
1334
+ output_hidden_states=output_hidden_states,
1335
+ return_dict=return_dict,
1336
+ )
1337
+
1338
+ pooled_output = outputs[1]
1339
+
1340
+ seq_relationship_scores = self.cls(pooled_output)
1341
+
1342
+ next_sentence_loss = None
1343
+ if labels is not None:
1344
+ loss_fct = CrossEntropyLoss()
1345
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
1346
+
1347
+ if not return_dict:
1348
+ output = (seq_relationship_scores,) + outputs[2:]
1349
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1350
+
1351
+ return NextSentencePredictorOutput(
1352
+ loss=next_sentence_loss,
1353
+ logits=seq_relationship_scores,
1354
+ hidden_states=outputs.hidden_states,
1355
+ attentions=outputs.attentions,
1356
+ )
1357
+
1358
+
1359
+ @add_start_docstrings(
1360
+ """
1361
+ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1362
+ output) e.g. for GLUE tasks.
1363
+ """,
1364
+ QDQBERT_START_DOCSTRING,
1365
+ )
1366
+ class QDQBertForSequenceClassification(QDQBertPreTrainedModel):
1367
+ def __init__(self, config):
1368
+ super().__init__(config)
1369
+ self.num_labels = config.num_labels
1370
+ self.config = config
1371
+
1372
+ self.bert = QDQBertModel(config)
1373
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1374
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1375
+ # Initialize weights and apply final processing
1376
+ self.post_init()
1377
+
1378
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1379
+ @add_code_sample_docstrings(
1380
+ checkpoint=_CHECKPOINT_FOR_DOC,
1381
+ output_type=SequenceClassifierOutput,
1382
+ config_class=_CONFIG_FOR_DOC,
1383
+ )
1384
+ def forward(
1385
+ self,
1386
+ input_ids: Optional[torch.LongTensor] = None,
1387
+ attention_mask: Optional[torch.FloatTensor] = None,
1388
+ token_type_ids: Optional[torch.LongTensor] = None,
1389
+ position_ids: Optional[torch.LongTensor] = None,
1390
+ head_mask: Optional[torch.FloatTensor] = None,
1391
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1392
+ labels: Optional[torch.LongTensor] = None,
1393
+ output_attentions: Optional[bool] = None,
1394
+ output_hidden_states: Optional[bool] = None,
1395
+ return_dict: Optional[bool] = None,
1396
+ ) -> Union[tuple, SequenceClassifierOutput]:
1397
+ r"""
1398
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1399
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1400
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1401
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1402
+ """
1403
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1404
+
1405
+ outputs = self.bert(
1406
+ input_ids,
1407
+ attention_mask=attention_mask,
1408
+ token_type_ids=token_type_ids,
1409
+ position_ids=position_ids,
1410
+ head_mask=head_mask,
1411
+ inputs_embeds=inputs_embeds,
1412
+ output_attentions=output_attentions,
1413
+ output_hidden_states=output_hidden_states,
1414
+ return_dict=return_dict,
1415
+ )
1416
+
1417
+ pooled_output = outputs[1]
1418
+
1419
+ pooled_output = self.dropout(pooled_output)
1420
+ logits = self.classifier(pooled_output)
1421
+
1422
+ loss = None
1423
+ if labels is not None:
1424
+ if self.config.problem_type is None:
1425
+ if self.num_labels == 1:
1426
+ self.config.problem_type = "regression"
1427
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1428
+ self.config.problem_type = "single_label_classification"
1429
+ else:
1430
+ self.config.problem_type = "multi_label_classification"
1431
+
1432
+ if self.config.problem_type == "regression":
1433
+ loss_fct = MSELoss()
1434
+ if self.num_labels == 1:
1435
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1436
+ else:
1437
+ loss = loss_fct(logits, labels)
1438
+ elif self.config.problem_type == "single_label_classification":
1439
+ loss_fct = CrossEntropyLoss()
1440
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1441
+ elif self.config.problem_type == "multi_label_classification":
1442
+ loss_fct = BCEWithLogitsLoss()
1443
+ loss = loss_fct(logits, labels)
1444
+ if not return_dict:
1445
+ output = (logits,) + outputs[2:]
1446
+ return ((loss,) + output) if loss is not None else output
1447
+
1448
+ return SequenceClassifierOutput(
1449
+ loss=loss,
1450
+ logits=logits,
1451
+ hidden_states=outputs.hidden_states,
1452
+ attentions=outputs.attentions,
1453
+ )
1454
+
1455
+
1456
+ @add_start_docstrings(
1457
+ """
1458
+ Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1459
+ softmax) e.g. for RocStories/SWAG tasks.
1460
+ """,
1461
+ QDQBERT_START_DOCSTRING,
1462
+ )
1463
+ class QDQBertForMultipleChoice(QDQBertPreTrainedModel):
1464
+ def __init__(self, config):
1465
+ super().__init__(config)
1466
+
1467
+ self.bert = QDQBertModel(config)
1468
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1469
+ self.classifier = nn.Linear(config.hidden_size, 1)
1470
+
1471
+ # Initialize weights and apply final processing
1472
+ self.post_init()
1473
+
1474
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1475
+ @add_code_sample_docstrings(
1476
+ checkpoint=_CHECKPOINT_FOR_DOC,
1477
+ output_type=MultipleChoiceModelOutput,
1478
+ config_class=_CONFIG_FOR_DOC,
1479
+ )
1480
+ def forward(
1481
+ self,
1482
+ input_ids: Optional[torch.LongTensor] = None,
1483
+ attention_mask: Optional[torch.FloatTensor] = None,
1484
+ token_type_ids: Optional[torch.LongTensor] = None,
1485
+ position_ids: Optional[torch.LongTensor] = None,
1486
+ head_mask: Optional[torch.FloatTensor] = None,
1487
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1488
+ labels: Optional[torch.LongTensor] = None,
1489
+ output_attentions: Optional[bool] = None,
1490
+ output_hidden_states: Optional[bool] = None,
1491
+ return_dict: Optional[bool] = None,
1492
+ ) -> Union[tuple, MultipleChoiceModelOutput]:
1493
+ r"""
1494
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1495
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1496
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1497
+ `input_ids` above)
1498
+ """
1499
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1500
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1501
+
1502
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1503
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1504
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1505
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1506
+ inputs_embeds = (
1507
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1508
+ if inputs_embeds is not None
1509
+ else None
1510
+ )
1511
+
1512
+ outputs = self.bert(
1513
+ input_ids,
1514
+ attention_mask=attention_mask,
1515
+ token_type_ids=token_type_ids,
1516
+ position_ids=position_ids,
1517
+ head_mask=head_mask,
1518
+ inputs_embeds=inputs_embeds,
1519
+ output_attentions=output_attentions,
1520
+ output_hidden_states=output_hidden_states,
1521
+ return_dict=return_dict,
1522
+ )
1523
+
1524
+ pooled_output = outputs[1]
1525
+
1526
+ pooled_output = self.dropout(pooled_output)
1527
+ logits = self.classifier(pooled_output)
1528
+ reshaped_logits = logits.view(-1, num_choices)
1529
+
1530
+ loss = None
1531
+ if labels is not None:
1532
+ loss_fct = CrossEntropyLoss()
1533
+ loss = loss_fct(reshaped_logits, labels)
1534
+
1535
+ if not return_dict:
1536
+ output = (reshaped_logits,) + outputs[2:]
1537
+ return ((loss,) + output) if loss is not None else output
1538
+
1539
+ return MultipleChoiceModelOutput(
1540
+ loss=loss,
1541
+ logits=reshaped_logits,
1542
+ hidden_states=outputs.hidden_states,
1543
+ attentions=outputs.attentions,
1544
+ )
1545
+
1546
+
1547
+ @add_start_docstrings(
1548
+ """
1549
+ QDQBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1550
+ Named-Entity-Recognition (NER) tasks.
1551
+ """,
1552
+ QDQBERT_START_DOCSTRING,
1553
+ )
1554
+ class QDQBertForTokenClassification(QDQBertPreTrainedModel):
1555
+ def __init__(self, config):
1556
+ super().__init__(config)
1557
+ self.num_labels = config.num_labels
1558
+
1559
+ self.bert = QDQBertModel(config, add_pooling_layer=False)
1560
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1561
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1562
+
1563
+ # Initialize weights and apply final processing
1564
+ self.post_init()
1565
+
1566
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1567
+ @add_code_sample_docstrings(
1568
+ checkpoint=_CHECKPOINT_FOR_DOC,
1569
+ output_type=TokenClassifierOutput,
1570
+ config_class=_CONFIG_FOR_DOC,
1571
+ )
1572
+ def forward(
1573
+ self,
1574
+ input_ids: Optional[torch.LongTensor] = None,
1575
+ attention_mask: Optional[torch.FloatTensor] = None,
1576
+ token_type_ids: Optional[torch.LongTensor] = None,
1577
+ position_ids: Optional[torch.LongTensor] = None,
1578
+ head_mask: Optional[torch.FloatTensor] = None,
1579
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1580
+ labels: Optional[torch.LongTensor] = None,
1581
+ output_attentions: Optional[bool] = None,
1582
+ output_hidden_states: Optional[bool] = None,
1583
+ return_dict: Optional[bool] = None,
1584
+ ) -> Union[tuple, TokenClassifierOutput]:
1585
+ r"""
1586
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1587
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1588
+ """
1589
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1590
+
1591
+ outputs = self.bert(
1592
+ input_ids,
1593
+ attention_mask=attention_mask,
1594
+ token_type_ids=token_type_ids,
1595
+ position_ids=position_ids,
1596
+ head_mask=head_mask,
1597
+ inputs_embeds=inputs_embeds,
1598
+ output_attentions=output_attentions,
1599
+ output_hidden_states=output_hidden_states,
1600
+ return_dict=return_dict,
1601
+ )
1602
+
1603
+ sequence_output = outputs[0]
1604
+
1605
+ sequence_output = self.dropout(sequence_output)
1606
+ logits = self.classifier(sequence_output)
1607
+
1608
+ loss = None
1609
+ if labels is not None:
1610
+ loss_fct = CrossEntropyLoss()
1611
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1612
+
1613
+ if not return_dict:
1614
+ output = (logits,) + outputs[2:]
1615
+ return ((loss,) + output) if loss is not None else output
1616
+
1617
+ return TokenClassifierOutput(
1618
+ loss=loss,
1619
+ logits=logits,
1620
+ hidden_states=outputs.hidden_states,
1621
+ attentions=outputs.attentions,
1622
+ )
1623
+
1624
+
1625
+ @add_start_docstrings(
1626
+ """
1627
+ QDQBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1628
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1629
+ """,
1630
+ QDQBERT_START_DOCSTRING,
1631
+ )
1632
+ class QDQBertForQuestionAnswering(QDQBertPreTrainedModel):
1633
+ def __init__(self, config):
1634
+ super().__init__(config)
1635
+ self.num_labels = config.num_labels
1636
+
1637
+ self.bert = QDQBertModel(config, add_pooling_layer=False)
1638
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1639
+
1640
+ # Initialize weights and apply final processing
1641
+ self.post_init()
1642
+
1643
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1644
+ @add_code_sample_docstrings(
1645
+ checkpoint=_CHECKPOINT_FOR_DOC,
1646
+ output_type=QuestionAnsweringModelOutput,
1647
+ config_class=_CONFIG_FOR_DOC,
1648
+ )
1649
+ def forward(
1650
+ self,
1651
+ input_ids: Optional[torch.LongTensor] = None,
1652
+ attention_mask: Optional[torch.FloatTensor] = None,
1653
+ token_type_ids: Optional[torch.LongTensor] = None,
1654
+ position_ids: Optional[torch.LongTensor] = None,
1655
+ head_mask: Optional[torch.FloatTensor] = None,
1656
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1657
+ start_positions: Optional[torch.LongTensor] = None,
1658
+ end_positions: Optional[torch.LongTensor] = None,
1659
+ output_attentions: Optional[bool] = None,
1660
+ output_hidden_states: Optional[bool] = None,
1661
+ return_dict: Optional[bool] = None,
1662
+ ) -> Union[tuple, QuestionAnsweringModelOutput]:
1663
+ r"""
1664
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1665
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1666
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1667
+ are not taken into account for computing the loss.
1668
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1669
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1670
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1671
+ are not taken into account for computing the loss.
1672
+ """
1673
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1674
+
1675
+ outputs = self.bert(
1676
+ input_ids,
1677
+ attention_mask=attention_mask,
1678
+ token_type_ids=token_type_ids,
1679
+ position_ids=position_ids,
1680
+ head_mask=head_mask,
1681
+ inputs_embeds=inputs_embeds,
1682
+ output_attentions=output_attentions,
1683
+ output_hidden_states=output_hidden_states,
1684
+ return_dict=return_dict,
1685
+ )
1686
+
1687
+ sequence_output = outputs[0]
1688
+
1689
+ logits = self.qa_outputs(sequence_output)
1690
+ start_logits, end_logits = logits.split(1, dim=-1)
1691
+ start_logits = start_logits.squeeze(-1).contiguous()
1692
+ end_logits = end_logits.squeeze(-1).contiguous()
1693
+
1694
+ total_loss = None
1695
+ if start_positions is not None and end_positions is not None:
1696
+ # If we are on multi-GPU, split add a dimension
1697
+ if len(start_positions.size()) > 1:
1698
+ start_positions = start_positions.squeeze(-1)
1699
+ if len(end_positions.size()) > 1:
1700
+ end_positions = end_positions.squeeze(-1)
1701
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1702
+ ignored_index = start_logits.size(1)
1703
+ start_positions = start_positions.clamp(0, ignored_index)
1704
+ end_positions = end_positions.clamp(0, ignored_index)
1705
+
1706
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1707
+ start_loss = loss_fct(start_logits, start_positions)
1708
+ end_loss = loss_fct(end_logits, end_positions)
1709
+ total_loss = (start_loss + end_loss) / 2
1710
+
1711
+ if not return_dict:
1712
+ output = (start_logits, end_logits) + outputs[2:]
1713
+ return ((total_loss,) + output) if total_loss is not None else output
1714
+
1715
+ return QuestionAnsweringModelOutput(
1716
+ loss=total_loss,
1717
+ start_logits=start_logits,
1718
+ end_logits=end_logits,
1719
+ hidden_states=outputs.hidden_states,
1720
+ attentions=outputs.attentions,
1721
+ )
1722
+
1723
+
1724
+ __all__ = [
1725
+ "QDQBertForMaskedLM",
1726
+ "QDQBertForMultipleChoice",
1727
+ "QDQBertForNextSentencePrediction",
1728
+ "QDQBertForQuestionAnswering",
1729
+ "QDQBertForSequenceClassification",
1730
+ "QDQBertForTokenClassification",
1731
+ "QDQBertLayer",
1732
+ "QDQBertLMHeadModel",
1733
+ "QDQBertModel",
1734
+ "QDQBertPreTrainedModel",
1735
+ "load_tf_weights_in_qdqbert",
1736
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/retribert/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ....utils import _LazyModule
17
+ from ....utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_retribert import *
22
+ from .modeling_retribert import *
23
+ from .tokenization_retribert import *
24
+ from .tokenization_retribert_fast import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/retribert/configuration_retribert.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, 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
+ """RetriBERT model configuration"""
16
+
17
+ from ....configuration_utils import PretrainedConfig
18
+ from ....utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class RetriBertConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`RetriBertModel`]. It is used to instantiate a
27
+ RetriBertModel model according to the specified arguments, defining the model architecture. Instantiating a
28
+ configuration with the defaults will yield a similar configuration to that of the RetriBERT
29
+ [yjernite/retribert-base-uncased](https://huggingface.co/yjernite/retribert-base-uncased) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 30522):
37
+ Vocabulary size of the RetriBERT model. Defines the number of different tokens that can be represented by
38
+ the `inputs_ids` passed when calling [`RetriBertModel`]
39
+ hidden_size (`int`, *optional*, defaults to 768):
40
+ Dimensionality of the encoder layers and the pooler layer.
41
+ num_hidden_layers (`int`, *optional*, defaults to 12):
42
+ Number of hidden layers in the Transformer encoder.
43
+ num_attention_heads (`int`, *optional*, defaults to 12):
44
+ Number of attention heads for each attention layer in the Transformer encoder.
45
+ intermediate_size (`int`, *optional*, defaults to 3072):
46
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
47
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
48
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
49
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
50
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
51
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
52
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
53
+ The dropout ratio for the attention probabilities.
54
+ max_position_embeddings (`int`, *optional*, defaults to 512):
55
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
56
+ just in case (e.g., 512 or 1024 or 2048).
57
+ type_vocab_size (`int`, *optional*, defaults to 2):
58
+ The vocabulary size of the *token_type_ids* passed into [`BertModel`].
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
62
+ The epsilon used by the layer normalization layers.
63
+ share_encoders (`bool`, *optional*, defaults to `True`):
64
+ Whether or not to use the same Bert-type encoder for the queries and document
65
+ projection_dim (`int`, *optional*, defaults to 128):
66
+ Final dimension of the query and document representation after projection
67
+ """
68
+
69
+ model_type = "retribert"
70
+
71
+ def __init__(
72
+ self,
73
+ vocab_size=30522,
74
+ hidden_size=768,
75
+ num_hidden_layers=8,
76
+ num_attention_heads=12,
77
+ intermediate_size=3072,
78
+ hidden_act="gelu",
79
+ hidden_dropout_prob=0.1,
80
+ attention_probs_dropout_prob=0.1,
81
+ max_position_embeddings=512,
82
+ type_vocab_size=2,
83
+ initializer_range=0.02,
84
+ layer_norm_eps=1e-12,
85
+ share_encoders=True,
86
+ projection_dim=128,
87
+ pad_token_id=0,
88
+ **kwargs,
89
+ ):
90
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
91
+
92
+ self.vocab_size = vocab_size
93
+ self.hidden_size = hidden_size
94
+ self.num_hidden_layers = num_hidden_layers
95
+ self.num_attention_heads = num_attention_heads
96
+ self.hidden_act = hidden_act
97
+ self.intermediate_size = intermediate_size
98
+ self.hidden_dropout_prob = hidden_dropout_prob
99
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
100
+ self.max_position_embeddings = max_position_embeddings
101
+ self.type_vocab_size = type_vocab_size
102
+ self.initializer_range = initializer_range
103
+ self.layer_norm_eps = layer_norm_eps
104
+ self.share_encoders = share_encoders
105
+ self.projection_dim = projection_dim
106
+
107
+
108
+ __all__ = ["RetriBertConfig"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/retribert/modeling_retribert.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, 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
+ """
16
+ RetriBERT model
17
+ """
18
+
19
+ import math
20
+ from typing import Optional
21
+
22
+ import torch
23
+ import torch.utils.checkpoint as checkpoint
24
+ from torch import nn
25
+
26
+ from ....modeling_utils import PreTrainedModel
27
+ from ....utils import add_start_docstrings, logging
28
+ from ...bert.modeling_bert import BertModel
29
+ from .configuration_retribert import RetriBertConfig
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ # INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #
36
+ class RetriBertPreTrainedModel(PreTrainedModel):
37
+ """
38
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
39
+ models.
40
+ """
41
+
42
+ config: RetriBertConfig
43
+ load_tf_weights = None
44
+ base_model_prefix = "retribert"
45
+
46
+ def _init_weights(self, module):
47
+ """Initialize the weights"""
48
+ if isinstance(module, nn.Linear):
49
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
50
+ if module.bias is not None:
51
+ module.bias.data.zero_()
52
+ elif isinstance(module, nn.Embedding):
53
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
54
+ if module.padding_idx is not None:
55
+ module.weight.data[module.padding_idx].zero_()
56
+ elif isinstance(module, nn.LayerNorm):
57
+ module.bias.data.zero_()
58
+ module.weight.data.fill_(1.0)
59
+
60
+
61
+ RETRIBERT_START_DOCSTRING = r"""
62
+
63
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
64
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
65
+ etc.)
66
+
67
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
68
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
69
+ and behavior.
70
+
71
+ Parameters:
72
+ config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.
73
+ Initializing with a config file does not load the weights associated with the model, only the
74
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
75
+ """
76
+
77
+
78
+ @add_start_docstrings(
79
+ """Bert Based model to embed queries or document for document retrieval.""",
80
+ RETRIBERT_START_DOCSTRING,
81
+ )
82
+ class RetriBertModel(RetriBertPreTrainedModel):
83
+ def __init__(self, config: RetriBertConfig) -> None:
84
+ super().__init__(config)
85
+ self.projection_dim = config.projection_dim
86
+
87
+ self.bert_query = BertModel(config)
88
+ self.bert_doc = None if config.share_encoders else BertModel(config)
89
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
90
+ self.project_query = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
91
+ self.project_doc = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
92
+
93
+ self.ce_loss = nn.CrossEntropyLoss(reduction="mean")
94
+
95
+ # Initialize weights and apply final processing
96
+ self.post_init()
97
+
98
+ def embed_sentences_checkpointed(
99
+ self,
100
+ input_ids,
101
+ attention_mask,
102
+ sent_encoder,
103
+ checkpoint_batch_size=-1,
104
+ ):
105
+ # reproduces BERT forward pass with checkpointing
106
+ if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
107
+ return sent_encoder(input_ids, attention_mask=attention_mask)[1]
108
+ else:
109
+ # prepare implicit variables
110
+ device = input_ids.device
111
+ input_shape = input_ids.size()
112
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
113
+ head_mask = [None] * sent_encoder.config.num_hidden_layers
114
+ extended_attention_mask: torch.Tensor = sent_encoder.get_extended_attention_mask(
115
+ attention_mask, input_shape
116
+ )
117
+
118
+ # define function for checkpointing
119
+ def partial_encode(*inputs):
120
+ encoder_outputs = sent_encoder.encoder(
121
+ inputs[0],
122
+ attention_mask=inputs[1],
123
+ head_mask=head_mask,
124
+ )
125
+ sequence_output = encoder_outputs[0]
126
+ pooled_output = sent_encoder.pooler(sequence_output)
127
+ return pooled_output
128
+
129
+ # run embedding layer on everything at once
130
+ embedding_output = sent_encoder.embeddings(
131
+ input_ids=input_ids, position_ids=None, token_type_ids=token_type_ids, inputs_embeds=None
132
+ )
133
+ # run encoding and pooling on one mini-batch at a time
134
+ pooled_output_list = []
135
+ for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size)):
136
+ b_embedding_output = embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
137
+ b_attention_mask = extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
138
+ pooled_output = checkpoint.checkpoint(partial_encode, b_embedding_output, b_attention_mask)
139
+ pooled_output_list.append(pooled_output)
140
+ return torch.cat(pooled_output_list, dim=0)
141
+
142
+ def embed_questions(
143
+ self,
144
+ input_ids,
145
+ attention_mask=None,
146
+ checkpoint_batch_size=-1,
147
+ ):
148
+ q_reps = self.embed_sentences_checkpointed(
149
+ input_ids,
150
+ attention_mask,
151
+ self.bert_query,
152
+ checkpoint_batch_size,
153
+ )
154
+ return self.project_query(q_reps)
155
+
156
+ def embed_answers(
157
+ self,
158
+ input_ids,
159
+ attention_mask=None,
160
+ checkpoint_batch_size=-1,
161
+ ):
162
+ a_reps = self.embed_sentences_checkpointed(
163
+ input_ids,
164
+ attention_mask,
165
+ self.bert_query if self.bert_doc is None else self.bert_doc,
166
+ checkpoint_batch_size,
167
+ )
168
+ return self.project_doc(a_reps)
169
+
170
+ def forward(
171
+ self,
172
+ input_ids_query: torch.LongTensor,
173
+ attention_mask_query: Optional[torch.FloatTensor],
174
+ input_ids_doc: torch.LongTensor,
175
+ attention_mask_doc: Optional[torch.FloatTensor],
176
+ checkpoint_batch_size: int = -1,
177
+ ) -> torch.FloatTensor:
178
+ r"""
179
+ Args:
180
+ input_ids_query (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
181
+ Indices of input sequence tokens in the vocabulary for the queries in a batch.
182
+
183
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
184
+ [`PreTrainedTokenizer.__call__`] for details.
185
+
186
+ [What are input IDs?](../glossary#input-ids)
187
+ attention_mask_query (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
188
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
189
+
190
+ - 1 for tokens that are **not masked**,
191
+ - 0 for tokens that are **masked**.
192
+
193
+ [What are attention masks?](../glossary#attention-mask)
194
+ input_ids_doc (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
195
+ Indices of input sequence tokens in the vocabulary for the documents in a batch.
196
+ attention_mask_doc (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
197
+ Mask to avoid performing attention on documents padding token indices.
198
+ checkpoint_batch_size (`int`, *optional*, defaults to `-1`):
199
+ If greater than 0, uses gradient checkpointing to only compute sequence representation on
200
+ `checkpoint_batch_size` examples at a time on the GPU. All query representations are still compared to
201
+ all document representations in the batch.
202
+
203
+ Return:
204
+ `torch.FloatTensor``: The bidirectional cross-entropy loss obtained while trying to match each query to its
205
+ corresponding document and each document to its corresponding query in the batch
206
+ """
207
+ device = input_ids_query.device
208
+ q_reps = self.embed_questions(input_ids_query, attention_mask_query, checkpoint_batch_size)
209
+ a_reps = self.embed_answers(input_ids_doc, attention_mask_doc, checkpoint_batch_size)
210
+ compare_scores = torch.mm(q_reps, a_reps.t())
211
+ loss_qa = self.ce_loss(compare_scores, torch.arange(compare_scores.shape[1]).to(device))
212
+ loss_aq = self.ce_loss(compare_scores.t(), torch.arange(compare_scores.shape[0]).to(device))
213
+ loss = (loss_qa + loss_aq) / 2
214
+ return loss
215
+
216
+
217
+ __all__ = ["RetriBertModel", "RetriBertPreTrainedModel"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/retribert/tokenization_retribert.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for RetriBERT."""
16
+
17
+ import collections
18
+ import os
19
+ import unicodedata
20
+ from typing import Optional
21
+
22
+ from ....tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
23
+ from ....utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
29
+
30
+
31
+ def load_vocab(vocab_file):
32
+ """Loads a vocabulary file into a dictionary."""
33
+ vocab = collections.OrderedDict()
34
+ with open(vocab_file, "r", encoding="utf-8") as reader:
35
+ tokens = reader.readlines()
36
+ for index, token in enumerate(tokens):
37
+ token = token.rstrip("\n")
38
+ vocab[token] = index
39
+ return vocab
40
+
41
+
42
+ def whitespace_tokenize(text):
43
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
44
+ text = text.strip()
45
+ if not text:
46
+ return []
47
+ tokens = text.split()
48
+ return tokens
49
+
50
+
51
+ class RetriBertTokenizer(PreTrainedTokenizer):
52
+ r"""
53
+ Constructs a RetriBERT tokenizer.
54
+
55
+ [`RetriBertTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation splitting
56
+ and wordpiece.
57
+
58
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer
59
+ to: this superclass for more information regarding those methods.
60
+
61
+ Args:
62
+ vocab_file (`str`):
63
+ File containing the vocabulary.
64
+ do_lower_case (`bool`, *optional*, defaults to `True`):
65
+ Whether or not to lowercase the input when tokenizing.
66
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
67
+ Whether or not to do basic tokenization before WordPiece.
68
+ never_split (`Iterable`, *optional*):
69
+ Collection of tokens which will never be split during tokenization. Only has an effect when
70
+ `do_basic_tokenize=True`
71
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
72
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
73
+ token instead.
74
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
75
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
76
+ sequence classification or for a text and a question for question answering. It is also used as the last
77
+ token of a sequence built with special tokens.
78
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
79
+ The token used for padding, for example when batching sequences of different lengths.
80
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
81
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
82
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
83
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
84
+ The token used for masking values. This is the token used when training this model with masked language
85
+ modeling. This is the token which the model will try to predict.
86
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
87
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see this
88
+ [issue](https://github.com/huggingface/transformers/issues/328)).
89
+ strip_accents (`bool`, *optional*):
90
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
91
+ value for `lowercase` (as in the original BERT).
92
+ """
93
+
94
+ vocab_files_names = VOCAB_FILES_NAMES
95
+ model_input_names = ["input_ids", "attention_mask"]
96
+
97
+ def __init__(
98
+ self,
99
+ vocab_file,
100
+ do_lower_case=True,
101
+ do_basic_tokenize=True,
102
+ never_split=None,
103
+ unk_token="[UNK]",
104
+ sep_token="[SEP]",
105
+ pad_token="[PAD]",
106
+ cls_token="[CLS]",
107
+ mask_token="[MASK]",
108
+ tokenize_chinese_chars=True,
109
+ strip_accents=None,
110
+ **kwargs,
111
+ ):
112
+ if not os.path.isfile(vocab_file):
113
+ raise ValueError(
114
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
115
+ " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
116
+ )
117
+ self.vocab = load_vocab(vocab_file)
118
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
119
+ self.do_basic_tokenize = do_basic_tokenize
120
+ if do_basic_tokenize:
121
+ self.basic_tokenizer = BasicTokenizer(
122
+ do_lower_case=do_lower_case,
123
+ never_split=never_split,
124
+ tokenize_chinese_chars=tokenize_chinese_chars,
125
+ strip_accents=strip_accents,
126
+ )
127
+
128
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
129
+
130
+ super().__init__(
131
+ do_lower_case=do_lower_case,
132
+ do_basic_tokenize=do_basic_tokenize,
133
+ never_split=never_split,
134
+ unk_token=unk_token,
135
+ sep_token=sep_token,
136
+ pad_token=pad_token,
137
+ cls_token=cls_token,
138
+ mask_token=mask_token,
139
+ tokenize_chinese_chars=tokenize_chinese_chars,
140
+ strip_accents=strip_accents,
141
+ **kwargs,
142
+ )
143
+
144
+ @property
145
+ def do_lower_case(self):
146
+ return self.basic_tokenizer.do_lower_case
147
+
148
+ @property
149
+ def vocab_size(self):
150
+ return len(self.vocab)
151
+
152
+ def get_vocab(self):
153
+ return dict(self.vocab, **self.added_tokens_encoder)
154
+
155
+ def _tokenize(self, text, split_special_tokens=False):
156
+ split_tokens = []
157
+ if self.do_basic_tokenize:
158
+ for token in self.basic_tokenizer.tokenize(
159
+ text, never_split=self.all_special_tokens if not split_special_tokens else None
160
+ ):
161
+ # If the token is part of the never_split set
162
+ if token in self.basic_tokenizer.never_split:
163
+ split_tokens.append(token)
164
+ else:
165
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
166
+ else:
167
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
168
+ return split_tokens
169
+
170
+ def _convert_token_to_id(self, token):
171
+ """Converts a token (str) in an id using the vocab."""
172
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
173
+
174
+ def _convert_id_to_token(self, index):
175
+ """Converts an index (integer) in a token (str) using the vocab."""
176
+ return self.ids_to_tokens.get(index, self.unk_token)
177
+
178
+ def convert_tokens_to_string(self, tokens):
179
+ """Converts a sequence of tokens (string) in a single string."""
180
+ out_string = " ".join(tokens).replace(" ##", "").strip()
181
+ return out_string
182
+
183
+ def build_inputs_with_special_tokens(
184
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
185
+ ) -> list[int]:
186
+ """
187
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
188
+ adding special tokens. A BERT sequence has the following format:
189
+
190
+ - single sequence: `[CLS] X [SEP]`
191
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
192
+
193
+ Args:
194
+ token_ids_0 (`List[int]`):
195
+ List of IDs to which the special tokens will be added.
196
+ token_ids_1 (`List[int]`, *optional*):
197
+ Optional second list of IDs for sequence pairs.
198
+
199
+ Returns:
200
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
201
+ """
202
+ if token_ids_1 is None:
203
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
204
+ cls = [self.cls_token_id]
205
+ sep = [self.sep_token_id]
206
+ return cls + token_ids_0 + sep + token_ids_1 + sep
207
+
208
+ def get_special_tokens_mask(
209
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
210
+ ) -> list[int]:
211
+ """
212
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
213
+ special tokens using the tokenizer `prepare_for_model` method.
214
+
215
+ Args:
216
+ token_ids_0 (`List[int]`):
217
+ List of IDs.
218
+ token_ids_1 (`List[int]`, *optional*):
219
+ Optional second list of IDs for sequence pairs.
220
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
221
+ Whether or not the token list is already formatted with special tokens for the model.
222
+
223
+ Returns:
224
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
225
+ """
226
+
227
+ if already_has_special_tokens:
228
+ return super().get_special_tokens_mask(
229
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
230
+ )
231
+
232
+ if token_ids_1 is not None:
233
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
234
+ return [1] + ([0] * len(token_ids_0)) + [1]
235
+
236
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
237
+ index = 0
238
+ if os.path.isdir(save_directory):
239
+ vocab_file = os.path.join(
240
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
241
+ )
242
+ else:
243
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
244
+ with open(vocab_file, "w", encoding="utf-8") as writer:
245
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
246
+ if index != token_index:
247
+ logger.warning(
248
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
249
+ " Please check that the vocabulary is not corrupted!"
250
+ )
251
+ index = token_index
252
+ writer.write(token + "\n")
253
+ index += 1
254
+ return (vocab_file,)
255
+
256
+
257
+ class BasicTokenizer:
258
+ """
259
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
260
+
261
+ Args:
262
+ do_lower_case (`bool`, *optional*, defaults to `True`):
263
+ Whether or not to lowercase the input when tokenizing.
264
+ never_split (`Iterable`, *optional*):
265
+ Collection of tokens which will never be split during tokenization. Only has an effect when
266
+ `do_basic_tokenize=True`
267
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
268
+ Whether or not to tokenize Chinese characters.
269
+
270
+ This should likely be deactivated for Japanese (see this
271
+ [issue](https://github.com/huggingface/transformers/issues/328)).
272
+ strip_accents (`bool`, *optional*):
273
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
274
+ value for `lowercase` (as in the original BERT).
275
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
276
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
277
+ the full context of the words, such as contractions.
278
+ """
279
+
280
+ def __init__(
281
+ self,
282
+ do_lower_case=True,
283
+ never_split=None,
284
+ tokenize_chinese_chars=True,
285
+ strip_accents=None,
286
+ do_split_on_punc=True,
287
+ ):
288
+ if never_split is None:
289
+ never_split = []
290
+ self.do_lower_case = do_lower_case
291
+ self.never_split = set(never_split)
292
+ self.tokenize_chinese_chars = tokenize_chinese_chars
293
+ self.strip_accents = strip_accents
294
+ self.do_split_on_punc = do_split_on_punc
295
+
296
+ def tokenize(self, text, never_split=None):
297
+ """
298
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
299
+
300
+ Args:
301
+ never_split (`List[str]`, *optional*)
302
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
303
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
304
+ """
305
+ # union() returns a new set by concatenating the two sets.
306
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
307
+ text = self._clean_text(text)
308
+
309
+ # This was added on November 1st, 2018 for the multilingual and Chinese
310
+ # models. This is also applied to the English models now, but it doesn't
311
+ # matter since the English models were not trained on any Chinese data
312
+ # and generally don't have any Chinese data in them (there are Chinese
313
+ # characters in the vocabulary because Wikipedia does have some Chinese
314
+ # words in the English Wikipedia.).
315
+ if self.tokenize_chinese_chars:
316
+ text = self._tokenize_chinese_chars(text)
317
+ # prevents treating the same character with different unicode codepoints as different characters
318
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
319
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
320
+ split_tokens = []
321
+ for token in orig_tokens:
322
+ if token not in never_split:
323
+ if self.do_lower_case:
324
+ token = token.lower()
325
+ if self.strip_accents is not False:
326
+ token = self._run_strip_accents(token)
327
+ elif self.strip_accents:
328
+ token = self._run_strip_accents(token)
329
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
330
+
331
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
332
+ return output_tokens
333
+
334
+ def _run_strip_accents(self, text):
335
+ """Strips accents from a piece of text."""
336
+ text = unicodedata.normalize("NFD", text)
337
+ output = []
338
+ for char in text:
339
+ cat = unicodedata.category(char)
340
+ if cat == "Mn":
341
+ continue
342
+ output.append(char)
343
+ return "".join(output)
344
+
345
+ def _run_split_on_punc(self, text, never_split=None):
346
+ """Splits punctuation on a piece of text."""
347
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
348
+ return [text]
349
+ chars = list(text)
350
+ i = 0
351
+ start_new_word = True
352
+ output = []
353
+ while i < len(chars):
354
+ char = chars[i]
355
+ if _is_punctuation(char):
356
+ output.append([char])
357
+ start_new_word = True
358
+ else:
359
+ if start_new_word:
360
+ output.append([])
361
+ start_new_word = False
362
+ output[-1].append(char)
363
+ i += 1
364
+
365
+ return ["".join(x) for x in output]
366
+
367
+ def _tokenize_chinese_chars(self, text):
368
+ """Adds whitespace around any CJK character."""
369
+ output = []
370
+ for char in text:
371
+ cp = ord(char)
372
+ if self._is_chinese_char(cp):
373
+ output.append(" ")
374
+ output.append(char)
375
+ output.append(" ")
376
+ else:
377
+ output.append(char)
378
+ return "".join(output)
379
+
380
+ def _is_chinese_char(self, cp):
381
+ """Checks whether CP is the codepoint of a CJK character."""
382
+ # This defines a "chinese character" as anything in the CJK Unicode block:
383
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
384
+ #
385
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
386
+ # despite its name. The modern Korean Hangul alphabet is a different block,
387
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
388
+ # space-separated words, so they are not treated specially and handled
389
+ # like the all of the other languages.
390
+ if (
391
+ (cp >= 0x4E00 and cp <= 0x9FFF)
392
+ or (cp >= 0x3400 and cp <= 0x4DBF)
393
+ or (cp >= 0x20000 and cp <= 0x2A6DF)
394
+ or (cp >= 0x2A700 and cp <= 0x2B73F)
395
+ or (cp >= 0x2B740 and cp <= 0x2B81F)
396
+ or (cp >= 0x2B820 and cp <= 0x2CEAF)
397
+ or (cp >= 0xF900 and cp <= 0xFAFF)
398
+ or (cp >= 0x2F800 and cp <= 0x2FA1F)
399
+ ):
400
+ return True
401
+
402
+ return False
403
+
404
+ def _clean_text(self, text):
405
+ """Performs invalid character removal and whitespace cleanup on text."""
406
+ output = []
407
+ for char in text:
408
+ cp = ord(char)
409
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
410
+ continue
411
+ if _is_whitespace(char):
412
+ output.append(" ")
413
+ else:
414
+ output.append(char)
415
+ return "".join(output)
416
+
417
+
418
+ class WordpieceTokenizer:
419
+ """Runs WordPiece tokenization."""
420
+
421
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
422
+ self.vocab = vocab
423
+ self.unk_token = unk_token
424
+ self.max_input_chars_per_word = max_input_chars_per_word
425
+
426
+ def tokenize(self, text):
427
+ """
428
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
429
+ tokenization using the given vocabulary.
430
+
431
+ For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
432
+
433
+ Args:
434
+ text: A single token or whitespace separated tokens. This should have
435
+ already been passed through *BasicTokenizer*.
436
+
437
+ Returns:
438
+ A list of wordpiece tokens.
439
+ """
440
+
441
+ output_tokens = []
442
+ for token in whitespace_tokenize(text):
443
+ chars = list(token)
444
+ if len(chars) > self.max_input_chars_per_word:
445
+ output_tokens.append(self.unk_token)
446
+ continue
447
+
448
+ is_bad = False
449
+ start = 0
450
+ sub_tokens = []
451
+ while start < len(chars):
452
+ end = len(chars)
453
+ cur_substr = None
454
+ while start < end:
455
+ substr = "".join(chars[start:end])
456
+ if start > 0:
457
+ substr = "##" + substr
458
+ if substr in self.vocab:
459
+ cur_substr = substr
460
+ break
461
+ end -= 1
462
+ if cur_substr is None:
463
+ is_bad = True
464
+ break
465
+ sub_tokens.append(cur_substr)
466
+ start = end
467
+
468
+ if is_bad:
469
+ output_tokens.append(self.unk_token)
470
+ else:
471
+ output_tokens.extend(sub_tokens)
472
+ return output_tokens
473
+
474
+
475
+ __all__ = ["RetriBertTokenizer"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/retribert/tokenization_retribert_fast.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for RetriBERT."""
16
+
17
+ import json
18
+ from typing import Optional
19
+
20
+ from tokenizers import normalizers
21
+
22
+ from ....tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ....utils import logging
24
+ from .tokenization_retribert import RetriBertTokenizer
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
30
+
31
+
32
+ class RetriBertTokenizerFast(PreTrainedTokenizerFast):
33
+ r"""
34
+ Construct a "fast" RetriBERT tokenizer (backed by HuggingFace's *tokenizers* library).
35
+
36
+ [`RetriBertTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization: punctuation
37
+ splitting and wordpiece.
38
+
39
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
40
+ refer to this superclass for more information regarding those methods.
41
+
42
+ Args:
43
+ vocab_file (`str`):
44
+ File containing the vocabulary.
45
+ do_lower_case (`bool`, *optional*, defaults to `True`):
46
+ Whether or not to lowercase the input when tokenizing.
47
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
48
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
49
+ token instead.
50
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
51
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
52
+ sequence classification or for a text and a question for question answering. It is also used as the last
53
+ token of a sequence built with special tokens.
54
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
55
+ The token used for padding, for example when batching sequences of different lengths.
56
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
57
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
58
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
59
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
60
+ The token used for masking values. This is the token used when training this model with masked language
61
+ modeling. This is the token which the model will try to predict.
62
+ clean_text (`bool`, *optional*, defaults to `True`):
63
+ Whether or not to clean the text before tokenization by removing any control characters and replacing all
64
+ whitespaces by the classic one.
65
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
66
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
67
+ issue](https://github.com/huggingface/transformers/issues/328)).
68
+ strip_accents (`bool`, *optional*):
69
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
70
+ value for `lowercase` (as in the original BERT).
71
+ wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
72
+ The prefix for subwords.
73
+ """
74
+
75
+ vocab_files_names = VOCAB_FILES_NAMES
76
+ slow_tokenizer_class = RetriBertTokenizer
77
+ model_input_names = ["input_ids", "attention_mask"]
78
+
79
+ def __init__(
80
+ self,
81
+ vocab_file=None,
82
+ tokenizer_file=None,
83
+ do_lower_case=True,
84
+ unk_token="[UNK]",
85
+ sep_token="[SEP]",
86
+ pad_token="[PAD]",
87
+ cls_token="[CLS]",
88
+ mask_token="[MASK]",
89
+ tokenize_chinese_chars=True,
90
+ strip_accents=None,
91
+ **kwargs,
92
+ ):
93
+ super().__init__(
94
+ vocab_file,
95
+ tokenizer_file=tokenizer_file,
96
+ do_lower_case=do_lower_case,
97
+ unk_token=unk_token,
98
+ sep_token=sep_token,
99
+ pad_token=pad_token,
100
+ cls_token=cls_token,
101
+ mask_token=mask_token,
102
+ tokenize_chinese_chars=tokenize_chinese_chars,
103
+ strip_accents=strip_accents,
104
+ **kwargs,
105
+ )
106
+
107
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
108
+ if (
109
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
110
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
111
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
112
+ ):
113
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
114
+ normalizer_state["lowercase"] = do_lower_case
115
+ normalizer_state["strip_accents"] = strip_accents
116
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
117
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
118
+
119
+ self.do_lower_case = do_lower_case
120
+
121
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
122
+ """
123
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
124
+ adding special tokens. A BERT sequence has the following format:
125
+
126
+ - single sequence: `[CLS] X [SEP]`
127
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
128
+
129
+ Args:
130
+ token_ids_0 (`List[int]`):
131
+ List of IDs to which the special tokens will be added.
132
+ token_ids_1 (`List[int]`, *optional*):
133
+ Optional second list of IDs for sequence pairs.
134
+
135
+ Returns:
136
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
137
+ """
138
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
139
+
140
+ if token_ids_1 is not None:
141
+ output += token_ids_1 + [self.sep_token_id]
142
+
143
+ return output
144
+
145
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
146
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
147
+ return tuple(files)
148
+
149
+
150
+ __all__ = ["RetriBertTokenizerFast"]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 _LazyModule
17
+ from ....utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_speech_to_text_2 import *
22
+ from .modeling_speech_to_text_2 import *
23
+ from .processing_speech_to_text_2 import *
24
+ from .tokenization_speech_to_text_2 import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/transformers/models/deprecated/speech_to_text_2/configuration_speech_to_text_2.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 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
+ """Speech2Text model configuration"""
16
+
17
+ from ....configuration_utils import PretrainedConfig
18
+ from ....utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class Speech2Text2Config(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`Speech2Text2ForCausalLM`]. It is used to
27
+ instantiate an Speech2Text2 model according to the specified arguments, defining the model architecture.
28
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the Speech2Text2
29
+ [facebook/s2t-wav2vec2-large-en-de](https://huggingface.co/facebook/s2t-wav2vec2-large-en-de) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 50265):
37
+ Vocabulary size of the Speech2Text model. Defines the number of different tokens that can be represented by
38
+ the `inputs_ids` passed when calling [`Speech2TextModel`]
39
+ d_model (`int`, *optional*, defaults to 1024):
40
+ Dimensionality of the layers and the pooler layer.
41
+ decoder_layers (`int`, *optional*, defaults to 12):
42
+ Number of decoder layers.
43
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
44
+ Number of attention heads for each attention layer in the Transformer decoder.
45
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
46
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
47
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
48
+ The non-linear activation function (function or string) in the pooler. If string, `"gelu"`, `"relu"`,
49
+ `"silu"` and `"gelu_new"` are supported.
50
+ dropout (`float`, *optional*, defaults to 0.1):
51
+ The dropout probability for all fully connected layers in the embeddings, and pooler.
52
+ attention_dropout (`float`, *optional*, defaults to 0.0):
53
+ The dropout ratio for the attention probabilities.
54
+ activation_dropout (`float`, *optional*, defaults to 0.0):
55
+ The dropout ratio for activations inside the fully connected layer.
56
+ init_std (`float`, *optional*, defaults to 0.02):
57
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
58
+ https://huggingface.co/papers/1909.11556>`__ for more details.
59
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
60
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
61
+ for more details.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models).
64
+ max_target_positions (`int`, *optional*, defaults to 1024):
65
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
66
+ just in case (e.g., 512 or 1024 or 2048).
67
+
68
+ Example:
69
+
70
+ ```python
71
+ >>> from transformers import Speech2Text2Config, Speech2Text2ForCausalLM
72
+
73
+ >>> # Initializing a Speech2Text2 s2t_transformer_s style configuration
74
+ >>> configuration = Speech2Text2Config()
75
+
76
+ >>> # Initializing a model (with random weights) from the s2t_transformer_s style configuration
77
+ >>> model = Speech2Text2ForCausalLM(configuration)
78
+
79
+ >>> # Accessing the model configuration
80
+ >>> configuration = model.config
81
+ ```"""
82
+
83
+ model_type = "speech_to_text_2"
84
+ keys_to_ignore_at_inference = ["past_key_values"]
85
+ attribute_map = {"num_attention_heads": "decoder_attention_heads", "hidden_size": "d_model"}
86
+
87
+ def __init__(
88
+ self,
89
+ vocab_size=10000,
90
+ decoder_layers=6,
91
+ decoder_ffn_dim=2048,
92
+ decoder_attention_heads=4,
93
+ decoder_layerdrop=0.0,
94
+ use_cache=True,
95
+ activation_function="relu",
96
+ d_model=256,
97
+ dropout=0.1,
98
+ attention_dropout=0.0,
99
+ activation_dropout=0.0,
100
+ init_std=0.02,
101
+ decoder_start_token_id=2,
102
+ scale_embedding=True,
103
+ pad_token_id=1,
104
+ bos_token_id=0,
105
+ eos_token_id=2,
106
+ max_target_positions=1024,
107
+ **kwargs,
108
+ ):
109
+ self.vocab_size = vocab_size
110
+ self.d_model = d_model
111
+ self.decoder_ffn_dim = decoder_ffn_dim
112
+ self.decoder_layers = decoder_layers
113
+ self.decoder_attention_heads = decoder_attention_heads
114
+ self.dropout = dropout
115
+ self.attention_dropout = attention_dropout
116
+ self.activation_dropout = activation_dropout
117
+ self.activation_function = activation_function
118
+ self.init_std = init_std
119
+ self.decoder_layerdrop = decoder_layerdrop
120
+ self.use_cache = use_cache
121
+ self.num_hidden_layers = decoder_layers
122
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
123
+ self.max_target_positions = max_target_positions
124
+
125
+ super().__init__(
126
+ pad_token_id=pad_token_id,
127
+ bos_token_id=bos_token_id,
128
+ eos_token_id=eos_token_id,
129
+ decoder_start_token_id=decoder_start_token_id,
130
+ **kwargs,
131
+ )
132
+
133
+
134
+ __all__ = ["Speech2Text2Config"]