ZTWHHH commited on
Commit
ccdd81f
·
verified ·
1 Parent(s): 1349da7

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. videochat2/lib/python3.10/site-packages/transformers/models/dpt/__init__.py +76 -0
  2. videochat2/lib/python3.10/site-packages/transformers/models/dpt/__pycache__/__init__.cpython-310.pyc +0 -0
  3. videochat2/lib/python3.10/site-packages/transformers/models/dpt/image_processing_dpt.py +484 -0
  4. videochat2/lib/python3.10/site-packages/transformers/models/flaubert/__pycache__/tokenization_flaubert.cpython-310.pyc +0 -0
  5. videochat2/lib/python3.10/site-packages/transformers/models/fnet/__init__.py +107 -0
  6. videochat2/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/__init__.cpython-310.pyc +0 -0
  7. videochat2/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/configuration_fnet.cpython-310.pyc +0 -0
  8. videochat2/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/convert_fnet_original_flax_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  9. videochat2/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/modeling_fnet.cpython-310.pyc +0 -0
  10. videochat2/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet_fast.cpython-310.pyc +0 -0
  11. videochat2/lib/python3.10/site-packages/transformers/models/fnet/configuration_fnet.py +119 -0
  12. videochat2/lib/python3.10/site-packages/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py +157 -0
  13. videochat2/lib/python3.10/site-packages/transformers/models/fnet/modeling_fnet.py +1182 -0
  14. videochat2/lib/python3.10/site-packages/transformers/models/fnet/tokenization_fnet.py +338 -0
  15. videochat2/lib/python3.10/site-packages/transformers/models/fnet/tokenization_fnet_fast.py +187 -0
  16. videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/__init__.py +64 -0
  17. videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/__init__.cpython-310.pyc +0 -0
  18. videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/configuration_kosmos2.cpython-310.pyc +0 -0
  19. videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  20. videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/modeling_kosmos2.cpython-310.pyc +0 -0
  21. videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/processing_kosmos2.cpython-310.pyc +0 -0
  22. videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/configuration_kosmos2.py +295 -0
  23. videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.py +77 -0
  24. videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/modeling_kosmos2.py +2054 -0
  25. videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/processing_kosmos2.py +666 -0
  26. videochat2/lib/python3.10/site-packages/transformers/models/mgp_str/__pycache__/__init__.cpython-310.pyc +0 -0
  27. videochat2/lib/python3.10/site-packages/transformers/models/mgp_str/__pycache__/processing_mgp_str.cpython-310.pyc +0 -0
  28. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__init__.py +145 -0
  29. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/__init__.cpython-310.pyc +0 -0
  30. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/configuration_mobilebert.cpython-310.pyc +0 -0
  31. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/convert_mobilebert_original_tf_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  32. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/modeling_mobilebert.cpython-310.pyc +0 -0
  33. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/modeling_tf_mobilebert.cpython-310.pyc +0 -0
  34. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/tokenization_mobilebert.cpython-310.pyc +0 -0
  35. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/tokenization_mobilebert_fast.cpython-310.pyc +0 -0
  36. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/configuration_mobilebert.py +183 -0
  37. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/convert_mobilebert_original_tf_checkpoint_to_pytorch.py +58 -0
  38. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/modeling_mobilebert.py +1617 -0
  39. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/modeling_tf_mobilebert.py +1970 -0
  40. videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/tokenization_mobilebert_fast.py +174 -0
  41. videochat2/lib/python3.10/site-packages/transformers/models/nllb_moe/__init__.py +68 -0
  42. videochat2/lib/python3.10/site-packages/transformers/models/nllb_moe/__pycache__/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  43. videochat2/lib/python3.10/site-packages/transformers/models/nllb_moe/__pycache__/modeling_nllb_moe.cpython-310.pyc +0 -0
  44. videochat2/lib/python3.10/site-packages/transformers/models/nllb_moe/configuration_nllb_moe.py +218 -0
  45. videochat2/lib/python3.10/site-packages/transformers/models/nllb_moe/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.py +160 -0
  46. videochat2/lib/python3.10/site-packages/transformers/models/nllb_moe/modeling_nllb_moe.py +1792 -0
  47. videochat2/lib/python3.10/site-packages/transformers/models/qdqbert/__init__.py +71 -0
  48. videochat2/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/__init__.py +65 -0
  49. videochat2/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/__pycache__/configuration_seamless_m4t_v2.cpython-310.pyc +0 -0
  50. videochat2/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/configuration_seamless_m4t_v2.py +425 -0
videochat2/lib/python3.10/site-packages/transformers/models/dpt/__init__.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available
17
+ from ...utils import OptionalDependencyNotAvailable
18
+
19
+
20
+ _import_structure = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]}
21
+
22
+ try:
23
+ if not is_vision_available():
24
+ raise OptionalDependencyNotAvailable()
25
+ except OptionalDependencyNotAvailable:
26
+ pass
27
+ else:
28
+ _import_structure["feature_extraction_dpt"] = ["DPTFeatureExtractor"]
29
+ _import_structure["image_processing_dpt"] = ["DPTImageProcessor"]
30
+
31
+ try:
32
+ if not is_torch_available():
33
+ raise OptionalDependencyNotAvailable()
34
+ except OptionalDependencyNotAvailable:
35
+ pass
36
+ else:
37
+ _import_structure["modeling_dpt"] = [
38
+ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST",
39
+ "DPTForDepthEstimation",
40
+ "DPTForSemanticSegmentation",
41
+ "DPTModel",
42
+ "DPTPreTrainedModel",
43
+ ]
44
+
45
+
46
+ if TYPE_CHECKING:
47
+ from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig
48
+
49
+ try:
50
+ if not is_vision_available():
51
+ raise OptionalDependencyNotAvailable()
52
+ except OptionalDependencyNotAvailable:
53
+ pass
54
+ else:
55
+ from .feature_extraction_dpt import DPTFeatureExtractor
56
+ from .image_processing_dpt import DPTImageProcessor
57
+
58
+ try:
59
+ if not is_torch_available():
60
+ raise OptionalDependencyNotAvailable()
61
+ except OptionalDependencyNotAvailable:
62
+ pass
63
+ else:
64
+ from .modeling_dpt import (
65
+ DPT_PRETRAINED_MODEL_ARCHIVE_LIST,
66
+ DPTForDepthEstimation,
67
+ DPTForSemanticSegmentation,
68
+ DPTModel,
69
+ DPTPreTrainedModel,
70
+ )
71
+
72
+
73
+ else:
74
+ import sys
75
+
76
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
videochat2/lib/python3.10/site-packages/transformers/models/dpt/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.27 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/dpt/image_processing_dpt.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 DPT."""
16
+
17
+ import math
18
+ from typing import Dict, Iterable, List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+
22
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
23
+ from ...image_transforms import pad, resize, to_channel_dimension_format
24
+ from ...image_utils import (
25
+ IMAGENET_STANDARD_MEAN,
26
+ IMAGENET_STANDARD_STD,
27
+ ChannelDimension,
28
+ ImageInput,
29
+ PILImageResampling,
30
+ get_image_size,
31
+ infer_channel_dimension_format,
32
+ is_scaled_image,
33
+ is_torch_available,
34
+ is_torch_tensor,
35
+ make_list_of_images,
36
+ to_numpy_array,
37
+ valid_images,
38
+ validate_kwargs,
39
+ validate_preprocess_arguments,
40
+ )
41
+ from ...utils import TensorType, is_vision_available, logging
42
+
43
+
44
+ if is_torch_available():
45
+ import torch
46
+
47
+ if is_vision_available():
48
+ import PIL
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+
54
+ def get_resize_output_image_size(
55
+ input_image: np.ndarray,
56
+ output_size: Union[int, Iterable[int]],
57
+ keep_aspect_ratio: bool,
58
+ multiple: int,
59
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
60
+ ) -> Tuple[int, int]:
61
+ def constraint_to_multiple_of(val, multiple, min_val=0, max_val=None):
62
+ x = round(val / multiple) * multiple
63
+
64
+ if max_val is not None and x > max_val:
65
+ x = math.floor(val / multiple) * multiple
66
+
67
+ if x < min_val:
68
+ x = math.ceil(val / multiple) * multiple
69
+
70
+ return x
71
+
72
+ output_size = (output_size, output_size) if isinstance(output_size, int) else output_size
73
+
74
+ input_height, input_width = get_image_size(input_image, input_data_format)
75
+ output_height, output_width = output_size
76
+
77
+ # determine new height and width
78
+ scale_height = output_height / input_height
79
+ scale_width = output_width / input_width
80
+
81
+ if keep_aspect_ratio:
82
+ # scale as little as possible
83
+ if abs(1 - scale_width) < abs(1 - scale_height):
84
+ # fit width
85
+ scale_height = scale_width
86
+ else:
87
+ # fit height
88
+ scale_width = scale_height
89
+
90
+ new_height = constraint_to_multiple_of(scale_height * input_height, multiple=multiple)
91
+ new_width = constraint_to_multiple_of(scale_width * input_width, multiple=multiple)
92
+
93
+ return (new_height, new_width)
94
+
95
+
96
+ class DPTImageProcessor(BaseImageProcessor):
97
+ r"""
98
+ Constructs a DPT image processor.
99
+
100
+ Args:
101
+ do_resize (`bool`, *optional*, defaults to `True`):
102
+ Whether to resize the image's (height, width) dimensions. Can be overidden by `do_resize` in `preprocess`.
103
+ size (`Dict[str, int]` *optional*, defaults to `{"height": 384, "width": 384}`):
104
+ Size of the image after resizing. Can be overidden by `size` in `preprocess`.
105
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
106
+ Defines the resampling filter to use if resizing the image. Can be overidden by `resample` in `preprocess`.
107
+ keep_aspect_ratio (`bool`, *optional*, defaults to `False`):
108
+ If `True`, the image is resized to the largest possible size such that the aspect ratio is preserved. Can
109
+ be overidden by `keep_aspect_ratio` in `preprocess`.
110
+ ensure_multiple_of (`int`, *optional*, defaults to 1):
111
+ If `do_resize` is `True`, the image is resized to a size that is a multiple of this value. Can be overidden
112
+ by `ensure_multiple_of` in `preprocess`.
113
+ do_rescale (`bool`, *optional*, defaults to `True`):
114
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overidden by `do_rescale` in
115
+ `preprocess`.
116
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
117
+ Scale factor to use if rescaling the image. Can be overidden by `rescale_factor` in `preprocess`.
118
+ do_normalize (`bool`, *optional*, defaults to `True`):
119
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
120
+ method.
121
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
122
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
123
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
124
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
125
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
126
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
127
+ do_pad (`bool`, *optional*, defaults to `False`):
128
+ Whether to apply center padding. This was introduced in the DINOv2 paper, which uses the model in
129
+ combination with DPT.
130
+ size_divisor (`int`, *optional*):
131
+ If `do_pad` is `True`, pads the image dimensions to be divisible by this value. This was introduced in the
132
+ DINOv2 paper, which uses the model in combination with DPT.
133
+ """
134
+
135
+ model_input_names = ["pixel_values"]
136
+
137
+ def __init__(
138
+ self,
139
+ do_resize: bool = True,
140
+ size: Dict[str, int] = None,
141
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
142
+ keep_aspect_ratio: bool = False,
143
+ ensure_multiple_of: int = 1,
144
+ do_rescale: bool = True,
145
+ rescale_factor: Union[int, float] = 1 / 255,
146
+ do_normalize: bool = True,
147
+ image_mean: Optional[Union[float, List[float]]] = None,
148
+ image_std: Optional[Union[float, List[float]]] = None,
149
+ do_pad: bool = False,
150
+ size_divisor: int = None,
151
+ **kwargs,
152
+ ) -> None:
153
+ super().__init__(**kwargs)
154
+ size = size if size is not None else {"height": 384, "width": 384}
155
+ size = get_size_dict(size)
156
+ self.do_resize = do_resize
157
+ self.size = size
158
+ self.keep_aspect_ratio = keep_aspect_ratio
159
+ self.ensure_multiple_of = ensure_multiple_of
160
+ self.resample = resample
161
+ self.do_rescale = do_rescale
162
+ self.rescale_factor = rescale_factor
163
+ self.do_normalize = do_normalize
164
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
165
+ self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
166
+ self.do_pad = do_pad
167
+ self.size_divisor = size_divisor
168
+ self._valid_processor_keys = [
169
+ "images",
170
+ "do_resize",
171
+ "size",
172
+ "keep_aspect_ratio",
173
+ "ensure_multiple_of",
174
+ "resample",
175
+ "do_rescale",
176
+ "rescale_factor",
177
+ "do_normalize",
178
+ "image_mean",
179
+ "image_std",
180
+ "do_pad",
181
+ "size_divisor",
182
+ "return_tensors",
183
+ "data_format",
184
+ "input_data_format",
185
+ ]
186
+
187
+ def resize(
188
+ self,
189
+ image: np.ndarray,
190
+ size: Dict[str, int],
191
+ keep_aspect_ratio: bool = False,
192
+ ensure_multiple_of: int = 1,
193
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
194
+ data_format: Optional[Union[str, ChannelDimension]] = None,
195
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
196
+ **kwargs,
197
+ ) -> np.ndarray:
198
+ """
199
+ Resize an image to target size `(size["height"], size["width"])`. If `keep_aspect_ratio` is `True`, the image
200
+ is resized to the largest possible size such that the aspect ratio is preserved. If `ensure_multiple_of` is
201
+ set, the image is resized to a size that is a multiple of this value.
202
+
203
+ Args:
204
+ image (`np.ndarray`):
205
+ Image to resize.
206
+ size (`Dict[str, int]`):
207
+ Target size of the output image.
208
+ keep_aspect_ratio (`bool`, *optional*, defaults to `False`):
209
+ If `True`, the image is resized to the largest possible size such that the aspect ratio is preserved.
210
+ ensure_multiple_of (`int`, *optional*, defaults to 1):
211
+ The image is resized to a size that is a multiple of this value.
212
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
213
+ Defines the resampling filter to use if resizing the image. Otherwise, the image is resized to size
214
+ specified in `size`.
215
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
216
+ Resampling filter to use when resiizing the image.
217
+ data_format (`str` or `ChannelDimension`, *optional*):
218
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
219
+ input_data_format (`str` or `ChannelDimension`, *optional*):
220
+ The channel dimension format of the input image. If not provided, it will be inferred.
221
+ """
222
+ size = get_size_dict(size)
223
+ if "height" not in size or "width" not in size:
224
+ raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}")
225
+
226
+ output_size = get_resize_output_image_size(
227
+ image,
228
+ output_size=(size["height"], size["width"]),
229
+ keep_aspect_ratio=keep_aspect_ratio,
230
+ multiple=ensure_multiple_of,
231
+ input_data_format=input_data_format,
232
+ )
233
+ return resize(
234
+ image,
235
+ size=output_size,
236
+ resample=resample,
237
+ data_format=data_format,
238
+ input_data_format=input_data_format,
239
+ **kwargs,
240
+ )
241
+
242
+ def pad_image(
243
+ self,
244
+ image: np.array,
245
+ size_divisor: int,
246
+ data_format: Optional[Union[str, ChannelDimension]] = None,
247
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
248
+ ):
249
+ """
250
+ Center pad an image to be a multiple of `multiple`.
251
+
252
+ Args:
253
+ image (`np.ndarray`):
254
+ Image to pad.
255
+ size_divisor (`int`):
256
+ The width and height of the image will be padded to a multiple of this number.
257
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
258
+ The channel dimension format for the output image. Can be one of:
259
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
260
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
261
+ - Unset: Use the channel dimension format of the input image.
262
+ input_data_format (`ChannelDimension` or `str`, *optional*):
263
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
264
+ from the input image. Can be one of:
265
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
266
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
267
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
268
+ """
269
+
270
+ def _get_pad(size, size_divisor):
271
+ new_size = math.ceil(size / size_divisor) * size_divisor
272
+ pad_size = new_size - size
273
+ pad_size_left = pad_size // 2
274
+ pad_size_right = pad_size - pad_size_left
275
+ return pad_size_left, pad_size_right
276
+
277
+ if input_data_format is None:
278
+ input_data_format = infer_channel_dimension_format(image)
279
+
280
+ height, width = get_image_size(image, input_data_format)
281
+
282
+ pad_size_left, pad_size_right = _get_pad(height, size_divisor)
283
+ pad_size_top, pad_size_bottom = _get_pad(width, size_divisor)
284
+
285
+ return pad(image, ((pad_size_left, pad_size_right), (pad_size_top, pad_size_bottom)), data_format=data_format)
286
+
287
+ def preprocess(
288
+ self,
289
+ images: ImageInput,
290
+ do_resize: bool = None,
291
+ size: int = None,
292
+ keep_aspect_ratio: bool = None,
293
+ ensure_multiple_of: int = None,
294
+ resample: PILImageResampling = None,
295
+ do_rescale: bool = None,
296
+ rescale_factor: float = None,
297
+ do_normalize: bool = None,
298
+ image_mean: Optional[Union[float, List[float]]] = None,
299
+ image_std: Optional[Union[float, List[float]]] = None,
300
+ do_pad: bool = None,
301
+ size_divisor: int = None,
302
+ return_tensors: Optional[Union[str, TensorType]] = None,
303
+ data_format: ChannelDimension = ChannelDimension.FIRST,
304
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
305
+ **kwargs,
306
+ ) -> PIL.Image.Image:
307
+ """
308
+ Preprocess an image or batch of images.
309
+
310
+ Args:
311
+ images (`ImageInput`):
312
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
313
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
314
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
315
+ Whether to resize the image.
316
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
317
+ Size of the image after reszing. If `keep_aspect_ratio` is `True`, the image is resized to the largest
318
+ possible size such that the aspect ratio is preserved. If `ensure_multiple_of` is set, the image is
319
+ resized to a size that is a multiple of this value.
320
+ keep_aspect_ratio (`bool`, *optional*, defaults to `self.keep_aspect_ratio`):
321
+ Whether to keep the aspect ratio of the image. If False, the image will be resized to (size, size). If
322
+ True, the image will be resized to keep the aspect ratio and the size will be the maximum possible.
323
+ ensure_multiple_of (`int`, *optional*, defaults to `self.ensure_multiple_of`):
324
+ Ensure that the image size is a multiple of this value.
325
+ resample (`int`, *optional*, defaults to `self.resample`):
326
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
327
+ has an effect if `do_resize` is set to `True`.
328
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
329
+ Whether to rescale the image values between [0 - 1].
330
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
331
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
332
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
333
+ Whether to normalize the image.
334
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
335
+ Image mean.
336
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
337
+ Image standard deviation.
338
+ return_tensors (`str` or `TensorType`, *optional*):
339
+ The type of tensors to return. Can be one of:
340
+ - Unset: Return a list of `np.ndarray`.
341
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
342
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
343
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
344
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
345
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
346
+ The channel dimension format for the output image. Can be one of:
347
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
348
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
349
+ input_data_format (`ChannelDimension` or `str`, *optional*):
350
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
351
+ from the input image. Can be one of:
352
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
353
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
354
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
355
+ """
356
+ do_resize = do_resize if do_resize is not None else self.do_resize
357
+ size = size if size is not None else self.size
358
+ size = get_size_dict(size)
359
+ keep_aspect_ratio = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
360
+ ensure_multiple_of = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
361
+ resample = resample if resample is not None else self.resample
362
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
363
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
364
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
365
+ image_mean = image_mean if image_mean is not None else self.image_mean
366
+ image_std = image_std if image_std is not None else self.image_std
367
+ do_pad = do_pad if do_pad is not None else self.do_pad
368
+ size_divisor = size_divisor if size_divisor is not None else self.size_divisor
369
+
370
+ images = make_list_of_images(images)
371
+
372
+ validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
373
+
374
+ if not valid_images(images):
375
+ raise ValueError(
376
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
377
+ "torch.Tensor, tf.Tensor or jax.ndarray."
378
+ )
379
+ validate_preprocess_arguments(
380
+ do_rescale=do_rescale,
381
+ rescale_factor=rescale_factor,
382
+ do_normalize=do_normalize,
383
+ image_mean=image_mean,
384
+ image_std=image_std,
385
+ do_pad=do_pad,
386
+ size_divisibility=size_divisor,
387
+ do_resize=do_resize,
388
+ size=size,
389
+ resample=resample,
390
+ )
391
+ # All transformations expect numpy arrays.
392
+ images = [to_numpy_array(image) for image in images]
393
+
394
+ if is_scaled_image(images[0]) and do_rescale:
395
+ logger.warning_once(
396
+ "It looks like you are trying to rescale already rescaled images. If the input"
397
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
398
+ )
399
+
400
+ if input_data_format is None:
401
+ # We assume that all images have the same channel dimension format.
402
+ input_data_format = infer_channel_dimension_format(images[0])
403
+
404
+ if do_resize:
405
+ images = [
406
+ self.resize(
407
+ image=image,
408
+ size=size,
409
+ resample=resample,
410
+ keep_aspect_ratio=keep_aspect_ratio,
411
+ ensure_multiple_of=ensure_multiple_of,
412
+ input_data_format=input_data_format,
413
+ )
414
+ for image in images
415
+ ]
416
+
417
+ if do_rescale:
418
+ images = [
419
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
420
+ for image in images
421
+ ]
422
+
423
+ if do_normalize:
424
+ images = [
425
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
426
+ for image in images
427
+ ]
428
+
429
+ if do_pad:
430
+ images = [
431
+ self.pad_image(image=image, size_divisor=size_divisor, input_data_format=input_data_format)
432
+ for image in images
433
+ ]
434
+
435
+ images = [
436
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
437
+ ]
438
+
439
+ data = {"pixel_values": images}
440
+ return BatchFeature(data=data, tensor_type=return_tensors)
441
+
442
+ # Copied from transformers.models.beit.image_processing_beit.BeitImageProcessor.post_process_semantic_segmentation with Beit->DPT
443
+ def post_process_semantic_segmentation(self, outputs, target_sizes: List[Tuple] = None):
444
+ """
445
+ Converts the output of [`DPTForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch.
446
+
447
+ Args:
448
+ outputs ([`DPTForSemanticSegmentation`]):
449
+ Raw outputs of the model.
450
+ target_sizes (`List[Tuple]` of length `batch_size`, *optional*):
451
+ List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
452
+ predictions will not be resized.
453
+
454
+ Returns:
455
+ semantic_segmentation: `List[torch.Tensor]` of length `batch_size`, where each item is a semantic
456
+ segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is
457
+ specified). Each entry of each `torch.Tensor` correspond to a semantic class id.
458
+ """
459
+ # TODO: add support for other frameworks
460
+ logits = outputs.logits
461
+
462
+ # Resize logits and compute semantic segmentation maps
463
+ if target_sizes is not None:
464
+ if len(logits) != len(target_sizes):
465
+ raise ValueError(
466
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
467
+ )
468
+
469
+ if is_torch_tensor(target_sizes):
470
+ target_sizes = target_sizes.numpy()
471
+
472
+ semantic_segmentation = []
473
+
474
+ for idx in range(len(logits)):
475
+ resized_logits = torch.nn.functional.interpolate(
476
+ logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
477
+ )
478
+ semantic_map = resized_logits[0].argmax(dim=0)
479
+ semantic_segmentation.append(semantic_map)
480
+ else:
481
+ semantic_segmentation = logits.argmax(dim=1)
482
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
483
+
484
+ return semantic_segmentation
videochat2/lib/python3.10/site-packages/transformers/models/flaubert/__pycache__/tokenization_flaubert.cpython-310.pyc ADDED
Binary file (18.2 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/fnet/__init__.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_sentencepiece_available,
20
+ is_tokenizers_available,
21
+ is_torch_available,
22
+ )
23
+
24
+
25
+ _import_structure = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]}
26
+
27
+ try:
28
+ if not is_sentencepiece_available():
29
+ raise OptionalDependencyNotAvailable()
30
+ except OptionalDependencyNotAvailable:
31
+ pass
32
+ else:
33
+ _import_structure["tokenization_fnet"] = ["FNetTokenizer"]
34
+
35
+ try:
36
+ if not is_tokenizers_available():
37
+ raise OptionalDependencyNotAvailable()
38
+ except OptionalDependencyNotAvailable:
39
+ pass
40
+ else:
41
+ _import_structure["tokenization_fnet_fast"] = ["FNetTokenizerFast"]
42
+
43
+ try:
44
+ if not is_torch_available():
45
+ raise OptionalDependencyNotAvailable()
46
+ except OptionalDependencyNotAvailable:
47
+ pass
48
+ else:
49
+ _import_structure["modeling_fnet"] = [
50
+ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST",
51
+ "FNetForMaskedLM",
52
+ "FNetForMultipleChoice",
53
+ "FNetForNextSentencePrediction",
54
+ "FNetForPreTraining",
55
+ "FNetForQuestionAnswering",
56
+ "FNetForSequenceClassification",
57
+ "FNetForTokenClassification",
58
+ "FNetLayer",
59
+ "FNetModel",
60
+ "FNetPreTrainedModel",
61
+ ]
62
+
63
+
64
+ if TYPE_CHECKING:
65
+ from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig
66
+
67
+ try:
68
+ if not is_sentencepiece_available():
69
+ raise OptionalDependencyNotAvailable()
70
+ except OptionalDependencyNotAvailable:
71
+ pass
72
+ else:
73
+ from .tokenization_fnet import FNetTokenizer
74
+
75
+ try:
76
+ if not is_tokenizers_available():
77
+ raise OptionalDependencyNotAvailable()
78
+ except OptionalDependencyNotAvailable:
79
+ pass
80
+ else:
81
+ from .tokenization_fnet_fast import FNetTokenizerFast
82
+
83
+ try:
84
+ if not is_torch_available():
85
+ raise OptionalDependencyNotAvailable()
86
+ except OptionalDependencyNotAvailable:
87
+ pass
88
+ else:
89
+ from .modeling_fnet import (
90
+ FNET_PRETRAINED_MODEL_ARCHIVE_LIST,
91
+ FNetForMaskedLM,
92
+ FNetForMultipleChoice,
93
+ FNetForNextSentencePrediction,
94
+ FNetForPreTraining,
95
+ FNetForQuestionAnswering,
96
+ FNetForSequenceClassification,
97
+ FNetForTokenClassification,
98
+ FNetLayer,
99
+ FNetModel,
100
+ FNetPreTrainedModel,
101
+ )
102
+
103
+
104
+ else:
105
+ import sys
106
+
107
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
videochat2/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/configuration_fnet.cpython-310.pyc ADDED
Binary file (4.95 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/convert_fnet_original_flax_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (3.85 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/modeling_fnet.cpython-310.pyc ADDED
Binary file (35.9 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet_fast.cpython-310.pyc ADDED
Binary file (6.99 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/fnet/configuration_fnet.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google AI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ FNet model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ from ..deprecated._archive_maps import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP # noqa: F401, E402
25
+
26
+
27
+ class FNetConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`FNetModel`]. It is used to instantiate an FNet
30
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
31
+ defaults will yield a similar configuration to that of the FNet
32
+ [google/fnet-base](https://huggingface.co/google/fnet-base) architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 32000):
40
+ Vocabulary size of the FNet model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`FNetModel`] or [`TFFNetModel`].
42
+ hidden_size (`int`, *optional*, defaults to 768):
43
+ Dimension of the encoder layers and the pooler layer.
44
+ num_hidden_layers (`int`, *optional*, defaults to 12):
45
+ Number of hidden layers in the Transformer encoder.
46
+ intermediate_size (`int`, *optional*, defaults to 3072):
47
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
48
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
49
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
50
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
51
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
52
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
53
+ max_position_embeddings (`int`, *optional*, defaults to 512):
54
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
55
+ just in case (e.g., 512 or 1024 or 2048).
56
+ type_vocab_size (`int`, *optional*, defaults to 4):
57
+ The vocabulary size of the `token_type_ids` passed when calling [`FNetModel`] or [`TFFNetModel`].
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
61
+ The epsilon used by the layer normalization layers.
62
+ use_tpu_fourier_optimizations (`bool`, *optional*, defaults to `False`):
63
+ Determines whether to use TPU optimized FFTs. If `True`, the model will favor axis-wise FFTs transforms.
64
+ Set to `False` for GPU/CPU hardware, in which case n-dimensional FFTs are used.
65
+ tpu_short_seq_length (`int`, *optional*, defaults to 512):
66
+ The sequence length that is expected by the model when using TPUs. This will be used to initialize the DFT
67
+ matrix only when *use_tpu_fourier_optimizations* is set to `True` and the input sequence is shorter than or
68
+ equal to 4096 tokens.
69
+
70
+ Example:
71
+
72
+ ```python
73
+ >>> from transformers import FNetConfig, FNetModel
74
+
75
+ >>> # Initializing a FNet fnet-base style configuration
76
+ >>> configuration = FNetConfig()
77
+
78
+ >>> # Initializing a model (with random weights) from the fnet-base style configuration
79
+ >>> model = FNetModel(configuration)
80
+
81
+ >>> # Accessing the model configuration
82
+ >>> configuration = model.config
83
+ ```"""
84
+
85
+ model_type = "fnet"
86
+
87
+ def __init__(
88
+ self,
89
+ vocab_size=32000,
90
+ hidden_size=768,
91
+ num_hidden_layers=12,
92
+ intermediate_size=3072,
93
+ hidden_act="gelu_new",
94
+ hidden_dropout_prob=0.1,
95
+ max_position_embeddings=512,
96
+ type_vocab_size=4,
97
+ initializer_range=0.02,
98
+ layer_norm_eps=1e-12,
99
+ use_tpu_fourier_optimizations=False,
100
+ tpu_short_seq_length=512,
101
+ pad_token_id=3,
102
+ bos_token_id=1,
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.intermediate_size = intermediate_size
113
+ self.hidden_act = hidden_act
114
+ self.hidden_dropout_prob = hidden_dropout_prob
115
+ self.initializer_range = initializer_range
116
+ self.type_vocab_size = type_vocab_size
117
+ self.layer_norm_eps = layer_norm_eps
118
+ self.use_tpu_fourier_optimizations = use_tpu_fourier_optimizations
119
+ self.tpu_short_seq_length = tpu_short_seq_length
videochat2/lib/python3.10/site-packages/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert FNet checkpoint."""
16
+
17
+
18
+ import argparse
19
+
20
+ import torch
21
+ from flax.training.checkpoints import restore_checkpoint
22
+
23
+ from transformers import FNetConfig, FNetForPreTraining
24
+ from transformers.utils import logging
25
+
26
+
27
+ logging.set_verbosity_info()
28
+
29
+
30
+ def convert_flax_checkpoint_to_pytorch(flax_checkpoint_path, fnet_config_file, save_path):
31
+ # Initialise PyTorch model
32
+ config = FNetConfig.from_json_file(fnet_config_file)
33
+ print(f"Building PyTorch model from configuration: {config}")
34
+ fnet_pretraining_model = FNetForPreTraining(config)
35
+
36
+ checkpoint_dict = restore_checkpoint(flax_checkpoint_path, None)
37
+ pretrained_model_params = checkpoint_dict["target"]
38
+
39
+ # Embeddings
40
+ # Position IDs
41
+ state_dict = fnet_pretraining_model.state_dict()
42
+
43
+ position_ids = state_dict["fnet.embeddings.position_ids"]
44
+ new_state_dict = {"fnet.embeddings.position_ids": position_ids}
45
+ # Embedding Layers
46
+ new_state_dict["fnet.embeddings.word_embeddings.weight"] = torch.tensor(
47
+ pretrained_model_params["encoder"]["embedder"]["word"]["embedding"]
48
+ )
49
+ new_state_dict["fnet.embeddings.position_embeddings.weight"] = torch.tensor(
50
+ pretrained_model_params["encoder"]["embedder"]["position"]["embedding"][0]
51
+ )
52
+ new_state_dict["fnet.embeddings.token_type_embeddings.weight"] = torch.tensor(
53
+ pretrained_model_params["encoder"]["embedder"]["type"]["embedding"]
54
+ )
55
+ new_state_dict["fnet.embeddings.projection.weight"] = torch.tensor(
56
+ pretrained_model_params["encoder"]["embedder"]["hidden_mapping_in"]["kernel"]
57
+ ).T
58
+ new_state_dict["fnet.embeddings.projection.bias"] = torch.tensor(
59
+ pretrained_model_params["encoder"]["embedder"]["hidden_mapping_in"]["bias"]
60
+ )
61
+ new_state_dict["fnet.embeddings.LayerNorm.weight"] = torch.tensor(
62
+ pretrained_model_params["encoder"]["embedder"]["layer_norm"]["scale"]
63
+ )
64
+ new_state_dict["fnet.embeddings.LayerNorm.bias"] = torch.tensor(
65
+ pretrained_model_params["encoder"]["embedder"]["layer_norm"]["bias"]
66
+ )
67
+
68
+ # Encoder Layers
69
+ for layer in range(config.num_hidden_layers):
70
+ new_state_dict[f"fnet.encoder.layer.{layer}.fourier.output.LayerNorm.weight"] = torch.tensor(
71
+ pretrained_model_params["encoder"][f"encoder_{layer}"]["mixing_layer_norm"]["scale"]
72
+ )
73
+ new_state_dict[f"fnet.encoder.layer.{layer}.fourier.output.LayerNorm.bias"] = torch.tensor(
74
+ pretrained_model_params["encoder"][f"encoder_{layer}"]["mixing_layer_norm"]["bias"]
75
+ )
76
+
77
+ new_state_dict[f"fnet.encoder.layer.{layer}.intermediate.dense.weight"] = torch.tensor(
78
+ pretrained_model_params["encoder"][f"feed_forward_{layer}"]["intermediate"]["kernel"]
79
+ ).T
80
+ new_state_dict[f"fnet.encoder.layer.{layer}.intermediate.dense.bias"] = torch.tensor(
81
+ pretrained_model_params["encoder"][f"feed_forward_{layer}"]["intermediate"]["bias"]
82
+ )
83
+
84
+ new_state_dict[f"fnet.encoder.layer.{layer}.output.dense.weight"] = torch.tensor(
85
+ pretrained_model_params["encoder"][f"feed_forward_{layer}"]["output"]["kernel"]
86
+ ).T
87
+ new_state_dict[f"fnet.encoder.layer.{layer}.output.dense.bias"] = torch.tensor(
88
+ pretrained_model_params["encoder"][f"feed_forward_{layer}"]["output"]["bias"]
89
+ )
90
+
91
+ new_state_dict[f"fnet.encoder.layer.{layer}.output.LayerNorm.weight"] = torch.tensor(
92
+ pretrained_model_params["encoder"][f"encoder_{layer}"]["output_layer_norm"]["scale"]
93
+ )
94
+ new_state_dict[f"fnet.encoder.layer.{layer}.output.LayerNorm.bias"] = torch.tensor(
95
+ pretrained_model_params["encoder"][f"encoder_{layer}"]["output_layer_norm"]["bias"]
96
+ )
97
+
98
+ # Pooler Layers
99
+ new_state_dict["fnet.pooler.dense.weight"] = torch.tensor(pretrained_model_params["encoder"]["pooler"]["kernel"]).T
100
+ new_state_dict["fnet.pooler.dense.bias"] = torch.tensor(pretrained_model_params["encoder"]["pooler"]["bias"])
101
+
102
+ # Masked LM Layers
103
+ new_state_dict["cls.predictions.transform.dense.weight"] = torch.tensor(
104
+ pretrained_model_params["predictions_dense"]["kernel"]
105
+ ).T
106
+ new_state_dict["cls.predictions.transform.dense.bias"] = torch.tensor(
107
+ pretrained_model_params["predictions_dense"]["bias"]
108
+ )
109
+ new_state_dict["cls.predictions.transform.LayerNorm.weight"] = torch.tensor(
110
+ pretrained_model_params["predictions_layer_norm"]["scale"]
111
+ )
112
+ new_state_dict["cls.predictions.transform.LayerNorm.bias"] = torch.tensor(
113
+ pretrained_model_params["predictions_layer_norm"]["bias"]
114
+ )
115
+ new_state_dict["cls.predictions.decoder.weight"] = torch.tensor(
116
+ pretrained_model_params["encoder"]["embedder"]["word"]["embedding"]
117
+ )
118
+ new_state_dict["cls.predictions.decoder.bias"] = torch.tensor(
119
+ pretrained_model_params["predictions_output"]["output_bias"]
120
+ )
121
+ new_state_dict["cls.predictions.bias"] = torch.tensor(pretrained_model_params["predictions_output"]["output_bias"])
122
+
123
+ # Seq Relationship Layers
124
+ new_state_dict["cls.seq_relationship.weight"] = torch.tensor(
125
+ pretrained_model_params["classification"]["output_kernel"]
126
+ )
127
+ new_state_dict["cls.seq_relationship.bias"] = torch.tensor(
128
+ pretrained_model_params["classification"]["output_bias"]
129
+ )
130
+
131
+ # Load State Dict
132
+ fnet_pretraining_model.load_state_dict(new_state_dict)
133
+
134
+ # Save PreTrained
135
+ print(f"Saving pretrained model to {save_path}")
136
+ fnet_pretraining_model.save_pretrained(save_path)
137
+
138
+
139
+ if __name__ == "__main__":
140
+ parser = argparse.ArgumentParser()
141
+ # Required parameters
142
+ parser.add_argument(
143
+ "--flax_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
144
+ )
145
+ parser.add_argument(
146
+ "--fnet_config_file",
147
+ default=None,
148
+ type=str,
149
+ required=True,
150
+ help=(
151
+ "The config json file corresponding to the pre-trained FNet model. \n"
152
+ "This specifies the model architecture."
153
+ ),
154
+ )
155
+ parser.add_argument("--save_path", default=None, type=str, required=True, help="Path to the output model.")
156
+ args = parser.parse_args()
157
+ convert_flax_checkpoint_to_pytorch(args.flax_checkpoint_path, args.fnet_config_file, args.save_path)
videochat2/lib/python3.10/site-packages/transformers/models/fnet/modeling_fnet.py ADDED
@@ -0,0 +1,1182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google Research and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch FNet model."""
16
+
17
+ import warnings
18
+ from dataclasses import dataclass
19
+ from functools import partial
20
+ from typing import Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ...utils import is_scipy_available
28
+
29
+
30
+ if is_scipy_available():
31
+ from scipy import linalg
32
+
33
+ from ...activations import ACT2FN
34
+ from ...modeling_outputs import (
35
+ BaseModelOutput,
36
+ BaseModelOutputWithPooling,
37
+ MaskedLMOutput,
38
+ ModelOutput,
39
+ MultipleChoiceModelOutput,
40
+ NextSentencePredictorOutput,
41
+ QuestionAnsweringModelOutput,
42
+ SequenceClassifierOutput,
43
+ TokenClassifierOutput,
44
+ )
45
+ from ...modeling_utils import PreTrainedModel
46
+ from ...pytorch_utils import apply_chunking_to_forward
47
+ from ...utils import (
48
+ add_code_sample_docstrings,
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ logging,
52
+ replace_return_docstrings,
53
+ )
54
+ from .configuration_fnet import FNetConfig
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+ _CHECKPOINT_FOR_DOC = "google/fnet-base"
60
+ _CONFIG_FOR_DOC = "FNetConfig"
61
+
62
+
63
+ from ..deprecated._archive_maps import FNET_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
64
+
65
+
66
+ # Adapted from https://github.com/google-research/google-research/blob/master/f_net/fourier.py
67
+ def _two_dim_matmul(x, matrix_dim_one, matrix_dim_two):
68
+ """Applies 2D matrix multiplication to 3D input arrays."""
69
+ seq_length = x.shape[1]
70
+ matrix_dim_one = matrix_dim_one[:seq_length, :seq_length]
71
+ x = x.type(torch.complex64)
72
+ return torch.einsum("bij,jk,ni->bnk", x, matrix_dim_two, matrix_dim_one)
73
+
74
+
75
+ # # Adapted from https://github.com/google-research/google-research/blob/master/f_net/fourier.py
76
+ def two_dim_matmul(x, matrix_dim_one, matrix_dim_two):
77
+ return _two_dim_matmul(x, matrix_dim_one, matrix_dim_two)
78
+
79
+
80
+ # Adapted from https://github.com/google-research/google-research/blob/master/f_net/fourier.py
81
+ def fftn(x):
82
+ """
83
+ Applies n-dimensional Fast Fourier Transform (FFT) to input array.
84
+
85
+ Args:
86
+ x: Input n-dimensional array.
87
+
88
+ Returns:
89
+ n-dimensional Fourier transform of input n-dimensional array.
90
+ """
91
+ out = x
92
+ for axis in reversed(range(x.ndim)[1:]): # We don't need to apply FFT to last axis
93
+ out = torch.fft.fft(out, axis=axis)
94
+ return out
95
+
96
+
97
+ class FNetEmbeddings(nn.Module):
98
+ """Construct the embeddings from word, position and token_type embeddings."""
99
+
100
+ def __init__(self, config):
101
+ super().__init__()
102
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
103
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
104
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
105
+
106
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
107
+ # any TensorFlow checkpoint file
108
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
109
+ # NOTE: This is the project layer and will be needed. The original code allows for different embedding and different model dimensions.
110
+ self.projection = nn.Linear(config.hidden_size, config.hidden_size)
111
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
112
+
113
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
114
+ self.register_buffer(
115
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
116
+ )
117
+
118
+ self.register_buffer(
119
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
120
+ )
121
+
122
+ def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
123
+ if input_ids is not None:
124
+ input_shape = input_ids.size()
125
+ else:
126
+ input_shape = inputs_embeds.size()[:-1]
127
+
128
+ seq_length = input_shape[1]
129
+
130
+ if position_ids is None:
131
+ position_ids = self.position_ids[:, :seq_length]
132
+
133
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
134
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
135
+ # issue #5664
136
+ if token_type_ids is None:
137
+ if hasattr(self, "token_type_ids"):
138
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
139
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
140
+ token_type_ids = buffered_token_type_ids_expanded
141
+ else:
142
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
143
+
144
+ if inputs_embeds is None:
145
+ inputs_embeds = self.word_embeddings(input_ids)
146
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
147
+
148
+ embeddings = inputs_embeds + token_type_embeddings
149
+
150
+ position_embeddings = self.position_embeddings(position_ids)
151
+ embeddings += position_embeddings
152
+ embeddings = self.LayerNorm(embeddings)
153
+ embeddings = self.projection(embeddings)
154
+ embeddings = self.dropout(embeddings)
155
+ return embeddings
156
+
157
+
158
+ class FNetBasicFourierTransform(nn.Module):
159
+ def __init__(self, config):
160
+ super().__init__()
161
+ self._init_fourier_transform(config)
162
+
163
+ def _init_fourier_transform(self, config):
164
+ if not config.use_tpu_fourier_optimizations:
165
+ self.fourier_transform = partial(torch.fft.fftn, dim=(1, 2))
166
+ elif config.max_position_embeddings <= 4096:
167
+ if is_scipy_available():
168
+ self.register_buffer(
169
+ "dft_mat_hidden", torch.tensor(linalg.dft(config.hidden_size), dtype=torch.complex64)
170
+ )
171
+ self.register_buffer(
172
+ "dft_mat_seq", torch.tensor(linalg.dft(config.tpu_short_seq_length), dtype=torch.complex64)
173
+ )
174
+ self.fourier_transform = partial(
175
+ two_dim_matmul, matrix_dim_one=self.dft_mat_seq, matrix_dim_two=self.dft_mat_hidden
176
+ )
177
+ else:
178
+ logging.warning(
179
+ "SciPy is needed for DFT matrix calculation and is not found. Using TPU optimized fast fourier"
180
+ " transform instead."
181
+ )
182
+ self.fourier_transform = fftn
183
+ else:
184
+ self.fourier_transform = fftn
185
+
186
+ def forward(self, hidden_states):
187
+ # NOTE: We do not use torch.vmap as it is not integrated into PyTorch stable versions.
188
+ # Interested users can modify the code to use vmap from the nightly versions, getting the vmap from here:
189
+ # https://pytorch.org/docs/master/generated/torch.vmap.html. Note that fourier transform methods will need
190
+ # change accordingly.
191
+
192
+ outputs = self.fourier_transform(hidden_states).real
193
+ return (outputs,)
194
+
195
+
196
+ class FNetBasicOutput(nn.Module):
197
+ def __init__(self, config):
198
+ super().__init__()
199
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
200
+
201
+ def forward(self, hidden_states, input_tensor):
202
+ hidden_states = self.LayerNorm(input_tensor + hidden_states)
203
+ return hidden_states
204
+
205
+
206
+ class FNetFourierTransform(nn.Module):
207
+ def __init__(self, config):
208
+ super().__init__()
209
+ self.self = FNetBasicFourierTransform(config)
210
+ self.output = FNetBasicOutput(config)
211
+
212
+ def forward(self, hidden_states):
213
+ self_outputs = self.self(hidden_states)
214
+ fourier_output = self.output(self_outputs[0], hidden_states)
215
+ outputs = (fourier_output,)
216
+ return outputs
217
+
218
+
219
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->FNet
220
+ class FNetIntermediate(nn.Module):
221
+ def __init__(self, config):
222
+ super().__init__()
223
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
224
+ if isinstance(config.hidden_act, str):
225
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
226
+ else:
227
+ self.intermediate_act_fn = config.hidden_act
228
+
229
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
230
+ hidden_states = self.dense(hidden_states)
231
+ hidden_states = self.intermediate_act_fn(hidden_states)
232
+ return hidden_states
233
+
234
+
235
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->FNet
236
+ class FNetOutput(nn.Module):
237
+ def __init__(self, config):
238
+ super().__init__()
239
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
240
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
241
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
242
+
243
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
244
+ hidden_states = self.dense(hidden_states)
245
+ hidden_states = self.dropout(hidden_states)
246
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
247
+ return hidden_states
248
+
249
+
250
+ class FNetLayer(nn.Module):
251
+ def __init__(self, config):
252
+ super().__init__()
253
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
254
+ self.seq_len_dim = 1 # The dimension which has the sequence length
255
+ self.fourier = FNetFourierTransform(config)
256
+ self.intermediate = FNetIntermediate(config)
257
+ self.output = FNetOutput(config)
258
+
259
+ def forward(self, hidden_states):
260
+ self_fourier_outputs = self.fourier(hidden_states)
261
+ fourier_output = self_fourier_outputs[0]
262
+
263
+ layer_output = apply_chunking_to_forward(
264
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, fourier_output
265
+ )
266
+
267
+ outputs = (layer_output,)
268
+
269
+ return outputs
270
+
271
+ def feed_forward_chunk(self, fourier_output):
272
+ intermediate_output = self.intermediate(fourier_output)
273
+ layer_output = self.output(intermediate_output, fourier_output)
274
+ return layer_output
275
+
276
+
277
+ class FNetEncoder(nn.Module):
278
+ def __init__(self, config):
279
+ super().__init__()
280
+ self.config = config
281
+ self.layer = nn.ModuleList([FNetLayer(config) for _ in range(config.num_hidden_layers)])
282
+ self.gradient_checkpointing = False
283
+
284
+ def forward(self, hidden_states, output_hidden_states=False, return_dict=True):
285
+ all_hidden_states = () if output_hidden_states else None
286
+
287
+ for i, layer_module in enumerate(self.layer):
288
+ if output_hidden_states:
289
+ all_hidden_states = all_hidden_states + (hidden_states,)
290
+
291
+ if self.gradient_checkpointing and self.training:
292
+ layer_outputs = self._gradient_checkpointing_func(layer_module.__call__, hidden_states)
293
+ else:
294
+ layer_outputs = layer_module(hidden_states)
295
+
296
+ hidden_states = layer_outputs[0]
297
+
298
+ if output_hidden_states:
299
+ all_hidden_states = all_hidden_states + (hidden_states,)
300
+
301
+ if not return_dict:
302
+ return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
303
+
304
+ return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
305
+
306
+
307
+ # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->FNet
308
+ class FNetPooler(nn.Module):
309
+ def __init__(self, config):
310
+ super().__init__()
311
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
312
+ self.activation = nn.Tanh()
313
+
314
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
315
+ # We "pool" the model by simply taking the hidden state corresponding
316
+ # to the first token.
317
+ first_token_tensor = hidden_states[:, 0]
318
+ pooled_output = self.dense(first_token_tensor)
319
+ pooled_output = self.activation(pooled_output)
320
+ return pooled_output
321
+
322
+
323
+ # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->FNet
324
+ class FNetPredictionHeadTransform(nn.Module):
325
+ def __init__(self, config):
326
+ super().__init__()
327
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
328
+ if isinstance(config.hidden_act, str):
329
+ self.transform_act_fn = ACT2FN[config.hidden_act]
330
+ else:
331
+ self.transform_act_fn = config.hidden_act
332
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
333
+
334
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
335
+ hidden_states = self.dense(hidden_states)
336
+ hidden_states = self.transform_act_fn(hidden_states)
337
+ hidden_states = self.LayerNorm(hidden_states)
338
+ return hidden_states
339
+
340
+
341
+ class FNetLMPredictionHead(nn.Module):
342
+ def __init__(self, config):
343
+ super().__init__()
344
+ self.transform = FNetPredictionHeadTransform(config)
345
+
346
+ # The output weights are the same as the input embeddings, but there is
347
+ # an output-only bias for each token.
348
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
349
+
350
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
351
+ self.decoder.bias = self.bias
352
+
353
+ def forward(self, hidden_states):
354
+ hidden_states = self.transform(hidden_states)
355
+ hidden_states = self.decoder(hidden_states)
356
+ return hidden_states
357
+
358
+ def _tie_weights(self):
359
+ # To tie those two weights if they get disconnected (on TPU or when the bias is resized)
360
+ self.bias = self.decoder.bias
361
+
362
+
363
+ class FNetOnlyMLMHead(nn.Module):
364
+ def __init__(self, config):
365
+ super().__init__()
366
+ self.predictions = FNetLMPredictionHead(config)
367
+
368
+ def forward(self, sequence_output):
369
+ prediction_scores = self.predictions(sequence_output)
370
+ return prediction_scores
371
+
372
+
373
+ # Copied from transformers.models.bert.modeling_bert.BertOnlyNSPHead with Bert->FNet
374
+ class FNetOnlyNSPHead(nn.Module):
375
+ def __init__(self, config):
376
+ super().__init__()
377
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
378
+
379
+ def forward(self, pooled_output):
380
+ seq_relationship_score = self.seq_relationship(pooled_output)
381
+ return seq_relationship_score
382
+
383
+
384
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert->FNet
385
+ class FNetPreTrainingHeads(nn.Module):
386
+ def __init__(self, config):
387
+ super().__init__()
388
+ self.predictions = FNetLMPredictionHead(config)
389
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
390
+
391
+ def forward(self, sequence_output, pooled_output):
392
+ prediction_scores = self.predictions(sequence_output)
393
+ seq_relationship_score = self.seq_relationship(pooled_output)
394
+ return prediction_scores, seq_relationship_score
395
+
396
+
397
+ class FNetPreTrainedModel(PreTrainedModel):
398
+ """
399
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
400
+ models.
401
+ """
402
+
403
+ config_class = FNetConfig
404
+ base_model_prefix = "fnet"
405
+ supports_gradient_checkpointing = True
406
+
407
+ def _init_weights(self, module):
408
+ """Initialize the weights"""
409
+ if isinstance(module, nn.Linear):
410
+ # Slightly different from the TF version which uses truncated_normal for initialization
411
+ # cf https://github.com/pytorch/pytorch/pull/5617
412
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
413
+ # NOTE: Original code uses same initialization as weights for biases as well.
414
+ if module.bias is not None:
415
+ module.bias.data.zero_()
416
+ elif isinstance(module, nn.Embedding):
417
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
418
+ if module.padding_idx is not None:
419
+ module.weight.data[module.padding_idx].zero_()
420
+ elif isinstance(module, nn.LayerNorm):
421
+ module.bias.data.zero_()
422
+ module.weight.data.fill_(1.0)
423
+
424
+
425
+ @dataclass
426
+ class FNetForPreTrainingOutput(ModelOutput):
427
+ """
428
+ Output type of [`FNetForPreTraining`].
429
+
430
+ Args:
431
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
432
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
433
+ (classification) loss.
434
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
435
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
436
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
437
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
438
+ before SoftMax).
439
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
440
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
441
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
442
+ plus the initial embedding outputs.
443
+ """
444
+
445
+ loss: Optional[torch.FloatTensor] = None
446
+ prediction_logits: torch.FloatTensor = None
447
+ seq_relationship_logits: torch.FloatTensor = None
448
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
449
+
450
+
451
+ FNET_START_DOCSTRING = r"""
452
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
453
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
454
+ behavior.
455
+
456
+ Parameters:
457
+ config ([`FNetConfig`]): Model configuration class with all the parameters of the model.
458
+ Initializing with a config file does not load the weights associated with the model, only the
459
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
460
+ """
461
+
462
+ FNET_INPUTS_DOCSTRING = r"""
463
+ Args:
464
+ input_ids (`torch.LongTensor` of shape `({0})`):
465
+ Indices of input sequence tokens in the vocabulary.
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
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
472
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
473
+ 1]`:
474
+
475
+ - 0 corresponds to a *sentence A* token,
476
+ - 1 corresponds to a *sentence B* token.
477
+
478
+ [What are token type IDs?](../glossary#token-type-ids)
479
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
480
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
481
+ config.max_position_embeddings - 1]`.
482
+
483
+ [What are position IDs?](../glossary#position-ids)
484
+
485
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
486
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
487
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
488
+ model's internal embedding lookup matrix.
489
+ output_hidden_states (`bool`, *optional*):
490
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
491
+ more detail.
492
+ return_dict (`bool`, *optional*):
493
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
494
+ """
495
+
496
+
497
+ @add_start_docstrings(
498
+ "The bare FNet Model transformer outputting raw hidden-states without any specific head on top.",
499
+ FNET_START_DOCSTRING,
500
+ )
501
+ class FNetModel(FNetPreTrainedModel):
502
+ """
503
+
504
+ The model can behave as an encoder, following the architecture described in [FNet: Mixing Tokens with Fourier
505
+ Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
506
+
507
+ """
508
+
509
+ def __init__(self, config, add_pooling_layer=True):
510
+ super().__init__(config)
511
+ self.config = config
512
+
513
+ self.embeddings = FNetEmbeddings(config)
514
+ self.encoder = FNetEncoder(config)
515
+
516
+ self.pooler = FNetPooler(config) if add_pooling_layer else None
517
+
518
+ # Initialize weights and apply final processing
519
+ self.post_init()
520
+
521
+ def get_input_embeddings(self):
522
+ return self.embeddings.word_embeddings
523
+
524
+ def set_input_embeddings(self, value):
525
+ self.embeddings.word_embeddings = value
526
+
527
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
528
+ @add_code_sample_docstrings(
529
+ checkpoint=_CHECKPOINT_FOR_DOC,
530
+ output_type=BaseModelOutput,
531
+ config_class=_CONFIG_FOR_DOC,
532
+ )
533
+ def forward(
534
+ self,
535
+ input_ids: Optional[torch.LongTensor] = None,
536
+ token_type_ids: Optional[torch.LongTensor] = None,
537
+ position_ids: Optional[torch.LongTensor] = None,
538
+ inputs_embeds: Optional[torch.FloatTensor] = None,
539
+ output_hidden_states: Optional[bool] = None,
540
+ return_dict: Optional[bool] = None,
541
+ ) -> Union[tuple, BaseModelOutput]:
542
+ output_hidden_states = (
543
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
544
+ )
545
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
546
+
547
+ if input_ids is not None and inputs_embeds is not None:
548
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
549
+ elif input_ids is not None:
550
+ input_shape = input_ids.size()
551
+ batch_size, seq_length = input_shape
552
+ elif inputs_embeds is not None:
553
+ input_shape = inputs_embeds.size()[:-1]
554
+ batch_size, seq_length = input_shape
555
+ else:
556
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
557
+
558
+ if (
559
+ self.config.use_tpu_fourier_optimizations
560
+ and seq_length <= 4096
561
+ and self.config.tpu_short_seq_length != seq_length
562
+ ):
563
+ raise ValueError(
564
+ "The `tpu_short_seq_length` in FNetConfig should be set equal to the sequence length being passed to"
565
+ " the model when using TPU optimizations."
566
+ )
567
+
568
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
569
+
570
+ if token_type_ids is None:
571
+ if hasattr(self.embeddings, "token_type_ids"):
572
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
573
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
574
+ token_type_ids = buffered_token_type_ids_expanded
575
+ else:
576
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
577
+
578
+ embedding_output = self.embeddings(
579
+ input_ids=input_ids,
580
+ position_ids=position_ids,
581
+ token_type_ids=token_type_ids,
582
+ inputs_embeds=inputs_embeds,
583
+ )
584
+ encoder_outputs = self.encoder(
585
+ embedding_output,
586
+ output_hidden_states=output_hidden_states,
587
+ return_dict=return_dict,
588
+ )
589
+ sequence_output = encoder_outputs[0]
590
+
591
+ pooler_output = self.pooler(sequence_output) if self.pooler is not None else None
592
+
593
+ if not return_dict:
594
+ return (sequence_output, pooler_output) + encoder_outputs[1:]
595
+
596
+ return BaseModelOutputWithPooling(
597
+ last_hidden_state=sequence_output,
598
+ pooler_output=pooler_output,
599
+ hidden_states=encoder_outputs.hidden_states,
600
+ )
601
+
602
+
603
+ @add_start_docstrings(
604
+ """
605
+ FNet Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
606
+ sentence prediction (classification)` head.
607
+ """,
608
+ FNET_START_DOCSTRING,
609
+ )
610
+ class FNetForPreTraining(FNetPreTrainedModel):
611
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
612
+
613
+ def __init__(self, config):
614
+ super().__init__(config)
615
+
616
+ self.fnet = FNetModel(config)
617
+ self.cls = FNetPreTrainingHeads(config)
618
+
619
+ # Initialize weights and apply final processing
620
+ self.post_init()
621
+
622
+ def get_output_embeddings(self):
623
+ return self.cls.predictions.decoder
624
+
625
+ def set_output_embeddings(self, new_embeddings):
626
+ self.cls.predictions.decoder = new_embeddings
627
+
628
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
629
+ @replace_return_docstrings(output_type=FNetForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
630
+ def forward(
631
+ self,
632
+ input_ids: Optional[torch.Tensor] = None,
633
+ token_type_ids: Optional[torch.Tensor] = None,
634
+ position_ids: Optional[torch.Tensor] = None,
635
+ inputs_embeds: Optional[torch.Tensor] = None,
636
+ labels: Optional[torch.Tensor] = None,
637
+ next_sentence_label: Optional[torch.Tensor] = None,
638
+ output_hidden_states: Optional[bool] = None,
639
+ return_dict: Optional[bool] = None,
640
+ ) -> Union[Tuple, FNetForPreTrainingOutput]:
641
+ r"""
642
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
643
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
644
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
645
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
646
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
647
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
648
+ (see `input_ids` docstring) Indices should be in `[0, 1]`:
649
+
650
+ - 0 indicates sequence B is a continuation of sequence A,
651
+ - 1 indicates sequence B is a random sequence.
652
+ kwargs (`Dict[str, any]`, optional, defaults to *{}*):
653
+ Used to hide legacy arguments that have been deprecated.
654
+
655
+ Returns:
656
+
657
+ Example:
658
+
659
+ ```python
660
+ >>> from transformers import AutoTokenizer, FNetForPreTraining
661
+ >>> import torch
662
+
663
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/fnet-base")
664
+ >>> model = FNetForPreTraining.from_pretrained("google/fnet-base")
665
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
666
+ >>> outputs = model(**inputs)
667
+ >>> prediction_logits = outputs.prediction_logits
668
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
669
+ ```"""
670
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
671
+
672
+ outputs = self.fnet(
673
+ input_ids,
674
+ token_type_ids=token_type_ids,
675
+ position_ids=position_ids,
676
+ inputs_embeds=inputs_embeds,
677
+ output_hidden_states=output_hidden_states,
678
+ return_dict=return_dict,
679
+ )
680
+
681
+ sequence_output, pooled_output = outputs[:2]
682
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
683
+
684
+ total_loss = None
685
+ if labels is not None and next_sentence_label is not None:
686
+ loss_fct = CrossEntropyLoss()
687
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
688
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
689
+ total_loss = masked_lm_loss + next_sentence_loss
690
+
691
+ if not return_dict:
692
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
693
+ return ((total_loss,) + output) if total_loss is not None else output
694
+
695
+ return FNetForPreTrainingOutput(
696
+ loss=total_loss,
697
+ prediction_logits=prediction_scores,
698
+ seq_relationship_logits=seq_relationship_score,
699
+ hidden_states=outputs.hidden_states,
700
+ )
701
+
702
+
703
+ @add_start_docstrings("""FNet Model with a `language modeling` head on top.""", FNET_START_DOCSTRING)
704
+ class FNetForMaskedLM(FNetPreTrainedModel):
705
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
706
+
707
+ def __init__(self, config):
708
+ super().__init__(config)
709
+
710
+ self.fnet = FNetModel(config)
711
+ self.cls = FNetOnlyMLMHead(config)
712
+
713
+ # Initialize weights and apply final processing
714
+ self.post_init()
715
+
716
+ def get_output_embeddings(self):
717
+ return self.cls.predictions.decoder
718
+
719
+ def set_output_embeddings(self, new_embeddings):
720
+ self.cls.predictions.decoder = new_embeddings
721
+
722
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
723
+ @add_code_sample_docstrings(
724
+ checkpoint=_CHECKPOINT_FOR_DOC,
725
+ output_type=MaskedLMOutput,
726
+ config_class=_CONFIG_FOR_DOC,
727
+ )
728
+ def forward(
729
+ self,
730
+ input_ids: Optional[torch.Tensor] = None,
731
+ token_type_ids: Optional[torch.Tensor] = None,
732
+ position_ids: Optional[torch.Tensor] = None,
733
+ inputs_embeds: Optional[torch.Tensor] = None,
734
+ labels: Optional[torch.Tensor] = None,
735
+ output_hidden_states: Optional[bool] = None,
736
+ return_dict: Optional[bool] = None,
737
+ ) -> Union[Tuple, MaskedLMOutput]:
738
+ r"""
739
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
740
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
741
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
742
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
743
+ """
744
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
745
+
746
+ outputs = self.fnet(
747
+ input_ids,
748
+ token_type_ids=token_type_ids,
749
+ position_ids=position_ids,
750
+ inputs_embeds=inputs_embeds,
751
+ output_hidden_states=output_hidden_states,
752
+ return_dict=return_dict,
753
+ )
754
+
755
+ sequence_output = outputs[0]
756
+ prediction_scores = self.cls(sequence_output)
757
+
758
+ masked_lm_loss = None
759
+ if labels is not None:
760
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
761
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
762
+
763
+ if not return_dict:
764
+ output = (prediction_scores,) + outputs[2:]
765
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
766
+
767
+ return MaskedLMOutput(loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states)
768
+
769
+
770
+ @add_start_docstrings(
771
+ """FNet Model with a `next sentence prediction (classification)` head on top.""",
772
+ FNET_START_DOCSTRING,
773
+ )
774
+ class FNetForNextSentencePrediction(FNetPreTrainedModel):
775
+ def __init__(self, config):
776
+ super().__init__(config)
777
+
778
+ self.fnet = FNetModel(config)
779
+ self.cls = FNetOnlyNSPHead(config)
780
+
781
+ # Initialize weights and apply final processing
782
+ self.post_init()
783
+
784
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
785
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
786
+ def forward(
787
+ self,
788
+ input_ids: Optional[torch.Tensor] = None,
789
+ token_type_ids: Optional[torch.Tensor] = None,
790
+ position_ids: Optional[torch.Tensor] = None,
791
+ inputs_embeds: Optional[torch.Tensor] = None,
792
+ labels: Optional[torch.Tensor] = None,
793
+ output_hidden_states: Optional[bool] = None,
794
+ return_dict: Optional[bool] = None,
795
+ **kwargs,
796
+ ) -> Union[Tuple, NextSentencePredictorOutput]:
797
+ r"""
798
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
799
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
800
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
801
+
802
+ - 0 indicates sequence B is a continuation of sequence A,
803
+ - 1 indicates sequence B is a random sequence.
804
+
805
+ Returns:
806
+
807
+ Example:
808
+
809
+ ```python
810
+ >>> from transformers import AutoTokenizer, FNetForNextSentencePrediction
811
+ >>> import torch
812
+
813
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/fnet-base")
814
+ >>> model = FNetForNextSentencePrediction.from_pretrained("google/fnet-base")
815
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
816
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
817
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
818
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
819
+ >>> logits = outputs.logits
820
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
821
+ ```"""
822
+
823
+ if "next_sentence_label" in kwargs:
824
+ warnings.warn(
825
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
826
+ " `labels` instead.",
827
+ FutureWarning,
828
+ )
829
+ labels = kwargs.pop("next_sentence_label")
830
+
831
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
832
+
833
+ outputs = self.fnet(
834
+ input_ids,
835
+ token_type_ids=token_type_ids,
836
+ position_ids=position_ids,
837
+ inputs_embeds=inputs_embeds,
838
+ output_hidden_states=output_hidden_states,
839
+ return_dict=return_dict,
840
+ )
841
+
842
+ pooled_output = outputs[1]
843
+
844
+ seq_relationship_scores = self.cls(pooled_output)
845
+
846
+ next_sentence_loss = None
847
+ if labels is not None:
848
+ loss_fct = CrossEntropyLoss()
849
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
850
+
851
+ if not return_dict:
852
+ output = (seq_relationship_scores,) + outputs[2:]
853
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
854
+
855
+ return NextSentencePredictorOutput(
856
+ loss=next_sentence_loss,
857
+ logits=seq_relationship_scores,
858
+ hidden_states=outputs.hidden_states,
859
+ )
860
+
861
+
862
+ @add_start_docstrings(
863
+ """
864
+ FNet Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
865
+ output) e.g. for GLUE tasks.
866
+ """,
867
+ FNET_START_DOCSTRING,
868
+ )
869
+ class FNetForSequenceClassification(FNetPreTrainedModel):
870
+ def __init__(self, config):
871
+ super().__init__(config)
872
+ self.num_labels = config.num_labels
873
+ self.fnet = FNetModel(config)
874
+
875
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
876
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
877
+
878
+ # Initialize weights and apply final processing
879
+ self.post_init()
880
+
881
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
882
+ @add_code_sample_docstrings(
883
+ checkpoint=_CHECKPOINT_FOR_DOC,
884
+ output_type=SequenceClassifierOutput,
885
+ config_class=_CONFIG_FOR_DOC,
886
+ )
887
+ def forward(
888
+ self,
889
+ input_ids: Optional[torch.Tensor] = None,
890
+ token_type_ids: Optional[torch.Tensor] = None,
891
+ position_ids: Optional[torch.Tensor] = None,
892
+ inputs_embeds: Optional[torch.Tensor] = None,
893
+ labels: Optional[torch.Tensor] = None,
894
+ output_hidden_states: Optional[bool] = None,
895
+ return_dict: Optional[bool] = None,
896
+ ) -> Union[Tuple, SequenceClassifierOutput]:
897
+ r"""
898
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
899
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
900
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
901
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
902
+ """
903
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
904
+
905
+ outputs = self.fnet(
906
+ input_ids,
907
+ token_type_ids=token_type_ids,
908
+ position_ids=position_ids,
909
+ inputs_embeds=inputs_embeds,
910
+ output_hidden_states=output_hidden_states,
911
+ return_dict=return_dict,
912
+ )
913
+
914
+ pooled_output = outputs[1]
915
+ pooled_output = self.dropout(pooled_output)
916
+ logits = self.classifier(pooled_output)
917
+
918
+ loss = None
919
+ if labels is not None:
920
+ if self.config.problem_type is None:
921
+ if self.num_labels == 1:
922
+ self.config.problem_type = "regression"
923
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
924
+ self.config.problem_type = "single_label_classification"
925
+ else:
926
+ self.config.problem_type = "multi_label_classification"
927
+
928
+ if self.config.problem_type == "regression":
929
+ loss_fct = MSELoss()
930
+ if self.num_labels == 1:
931
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
932
+ else:
933
+ loss = loss_fct(logits, labels)
934
+ elif self.config.problem_type == "single_label_classification":
935
+ loss_fct = CrossEntropyLoss()
936
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
937
+ elif self.config.problem_type == "multi_label_classification":
938
+ loss_fct = BCEWithLogitsLoss()
939
+ loss = loss_fct(logits, labels)
940
+ if not return_dict:
941
+ output = (logits,) + outputs[2:]
942
+ return ((loss,) + output) if loss is not None else output
943
+
944
+ return SequenceClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
945
+
946
+
947
+ @add_start_docstrings(
948
+ """
949
+ FNet Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
950
+ softmax) e.g. for RocStories/SWAG tasks.
951
+ """,
952
+ FNET_START_DOCSTRING,
953
+ )
954
+ class FNetForMultipleChoice(FNetPreTrainedModel):
955
+ def __init__(self, config):
956
+ super().__init__(config)
957
+
958
+ self.fnet = FNetModel(config)
959
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
960
+ self.classifier = nn.Linear(config.hidden_size, 1)
961
+
962
+ # Initialize weights and apply final processing
963
+ self.post_init()
964
+
965
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
966
+ @add_code_sample_docstrings(
967
+ checkpoint=_CHECKPOINT_FOR_DOC,
968
+ output_type=MultipleChoiceModelOutput,
969
+ config_class=_CONFIG_FOR_DOC,
970
+ )
971
+ def forward(
972
+ self,
973
+ input_ids: Optional[torch.Tensor] = None,
974
+ token_type_ids: Optional[torch.Tensor] = None,
975
+ position_ids: Optional[torch.Tensor] = None,
976
+ inputs_embeds: Optional[torch.Tensor] = None,
977
+ labels: Optional[torch.Tensor] = None,
978
+ output_hidden_states: Optional[bool] = None,
979
+ return_dict: Optional[bool] = None,
980
+ ) -> Union[Tuple, MultipleChoiceModelOutput]:
981
+ r"""
982
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
983
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
984
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
985
+ `input_ids` above)
986
+ """
987
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
988
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
989
+
990
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
991
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
992
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
993
+ inputs_embeds = (
994
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
995
+ if inputs_embeds is not None
996
+ else None
997
+ )
998
+
999
+ outputs = self.fnet(
1000
+ input_ids,
1001
+ token_type_ids=token_type_ids,
1002
+ position_ids=position_ids,
1003
+ inputs_embeds=inputs_embeds,
1004
+ output_hidden_states=output_hidden_states,
1005
+ return_dict=return_dict,
1006
+ )
1007
+
1008
+ pooled_output = outputs[1]
1009
+
1010
+ pooled_output = self.dropout(pooled_output)
1011
+ logits = self.classifier(pooled_output)
1012
+ reshaped_logits = logits.view(-1, num_choices)
1013
+
1014
+ loss = None
1015
+ if labels is not None:
1016
+ loss_fct = CrossEntropyLoss()
1017
+ loss = loss_fct(reshaped_logits, labels)
1018
+
1019
+ if not return_dict:
1020
+ output = (reshaped_logits,) + outputs[2:]
1021
+ return ((loss,) + output) if loss is not None else output
1022
+
1023
+ return MultipleChoiceModelOutput(loss=loss, logits=reshaped_logits, hidden_states=outputs.hidden_states)
1024
+
1025
+
1026
+ @add_start_docstrings(
1027
+ """
1028
+ FNet Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1029
+ Named-Entity-Recognition (NER) tasks.
1030
+ """,
1031
+ FNET_START_DOCSTRING,
1032
+ )
1033
+ class FNetForTokenClassification(FNetPreTrainedModel):
1034
+ def __init__(self, config):
1035
+ super().__init__(config)
1036
+ self.num_labels = config.num_labels
1037
+
1038
+ self.fnet = FNetModel(config)
1039
+
1040
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1041
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1042
+
1043
+ # Initialize weights and apply final processing
1044
+ self.post_init()
1045
+
1046
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1047
+ @add_code_sample_docstrings(
1048
+ checkpoint=_CHECKPOINT_FOR_DOC,
1049
+ output_type=TokenClassifierOutput,
1050
+ config_class=_CONFIG_FOR_DOC,
1051
+ )
1052
+ def forward(
1053
+ self,
1054
+ input_ids: Optional[torch.Tensor] = None,
1055
+ token_type_ids: Optional[torch.Tensor] = None,
1056
+ position_ids: Optional[torch.Tensor] = None,
1057
+ inputs_embeds: Optional[torch.Tensor] = None,
1058
+ labels: Optional[torch.Tensor] = None,
1059
+ output_hidden_states: Optional[bool] = None,
1060
+ return_dict: Optional[bool] = None,
1061
+ ) -> Union[Tuple, TokenClassifierOutput]:
1062
+ r"""
1063
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1064
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1065
+ """
1066
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1067
+
1068
+ outputs = self.fnet(
1069
+ input_ids,
1070
+ token_type_ids=token_type_ids,
1071
+ position_ids=position_ids,
1072
+ inputs_embeds=inputs_embeds,
1073
+ output_hidden_states=output_hidden_states,
1074
+ return_dict=return_dict,
1075
+ )
1076
+
1077
+ sequence_output = outputs[0]
1078
+
1079
+ sequence_output = self.dropout(sequence_output)
1080
+ logits = self.classifier(sequence_output)
1081
+
1082
+ loss = None
1083
+ if labels is not None:
1084
+ loss_fct = CrossEntropyLoss()
1085
+ # Only keep active parts of the loss
1086
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1087
+
1088
+ if not return_dict:
1089
+ output = (logits,) + outputs[2:]
1090
+ return ((loss,) + output) if loss is not None else output
1091
+
1092
+ return TokenClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
1093
+
1094
+
1095
+ @add_start_docstrings(
1096
+ """
1097
+ FNet Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1098
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1099
+ """,
1100
+ FNET_START_DOCSTRING,
1101
+ )
1102
+ class FNetForQuestionAnswering(FNetPreTrainedModel):
1103
+ def __init__(self, config):
1104
+ super().__init__(config)
1105
+
1106
+ self.num_labels = config.num_labels
1107
+
1108
+ self.fnet = FNetModel(config)
1109
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1110
+
1111
+ # Initialize weights and apply final processing
1112
+ self.post_init()
1113
+
1114
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1115
+ @add_code_sample_docstrings(
1116
+ checkpoint=_CHECKPOINT_FOR_DOC,
1117
+ output_type=QuestionAnsweringModelOutput,
1118
+ config_class=_CONFIG_FOR_DOC,
1119
+ )
1120
+ def forward(
1121
+ self,
1122
+ input_ids: Optional[torch.Tensor] = None,
1123
+ token_type_ids: Optional[torch.Tensor] = None,
1124
+ position_ids: Optional[torch.Tensor] = None,
1125
+ inputs_embeds: Optional[torch.Tensor] = None,
1126
+ start_positions: Optional[torch.Tensor] = None,
1127
+ end_positions: Optional[torch.Tensor] = None,
1128
+ output_hidden_states: Optional[bool] = None,
1129
+ return_dict: Optional[bool] = None,
1130
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1131
+ r"""
1132
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1133
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1134
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1135
+ are not taken into account for computing the loss.
1136
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1137
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1138
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1139
+ are not taken into account for computing the loss.
1140
+ """
1141
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1142
+
1143
+ outputs = self.fnet(
1144
+ input_ids,
1145
+ token_type_ids=token_type_ids,
1146
+ position_ids=position_ids,
1147
+ inputs_embeds=inputs_embeds,
1148
+ output_hidden_states=output_hidden_states,
1149
+ return_dict=return_dict,
1150
+ )
1151
+
1152
+ sequence_output = outputs[0]
1153
+
1154
+ logits = self.qa_outputs(sequence_output)
1155
+ start_logits, end_logits = logits.split(1, dim=-1)
1156
+ start_logits = start_logits.squeeze(-1).contiguous()
1157
+ end_logits = end_logits.squeeze(-1).contiguous()
1158
+
1159
+ total_loss = None
1160
+ if start_positions is not None and end_positions is not None:
1161
+ # If we are on multi-GPU, split add a dimension
1162
+ if len(start_positions.size()) > 1:
1163
+ start_positions = start_positions.squeeze(-1)
1164
+ if len(end_positions.size()) > 1:
1165
+ end_positions = end_positions.squeeze(-1)
1166
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1167
+ ignored_index = start_logits.size(1)
1168
+ start_positions = start_positions.clamp(0, ignored_index)
1169
+ end_positions = end_positions.clamp(0, ignored_index)
1170
+
1171
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1172
+ start_loss = loss_fct(start_logits, start_positions)
1173
+ end_loss = loss_fct(end_logits, end_positions)
1174
+ total_loss = (start_loss + end_loss) / 2
1175
+
1176
+ if not return_dict:
1177
+ output = (start_logits, end_logits) + outputs[2:]
1178
+ return ((total_loss,) + output) if total_loss is not None else output
1179
+
1180
+ return QuestionAnsweringModelOutput(
1181
+ loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states
1182
+ )
videochat2/lib/python3.10/site-packages/transformers/models/fnet/tokenization_fnet.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google Research, Google AI, Google Brain and the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Tokenization classes for FNet model."""
16
+
17
+ import os
18
+ import unicodedata
19
+ from shutil import copyfile
20
+ from typing import Any, Dict, List, Optional, Tuple
21
+
22
+ import sentencepiece as spm
23
+
24
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
25
+ from ...utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
30
+
31
+
32
+ SPIECE_UNDERLINE = "▁"
33
+
34
+
35
+ class FNetTokenizer(PreTrainedTokenizer):
36
+ """
37
+ Construct an FNet tokenizer. Adapted from [`AlbertTokenizer`]. Based on
38
+ [SentencePiece](https://github.com/google/sentencepiece). This tokenizer inherits from [`PreTrainedTokenizer`]
39
+ which contains most of the main methods. Users should refer to this superclass for more information regarding those
40
+ methods.
41
+
42
+ Args:
43
+ vocab_file (`str`):
44
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
45
+ contains the vocabulary necessary to instantiate a tokenizer.
46
+ do_lower_case (`bool`, *optional*, defaults to `False`):
47
+ Whether or not to lowercase the input when tokenizing.
48
+ remove_space (`bool`, *optional*, defaults to `True`):
49
+ Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
50
+ keep_accents (`bool`, *optional*, defaults to `True`):
51
+ Whether or not to keep accents when tokenizing.
52
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
53
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
54
+ token instead.
55
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
56
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
57
+ sequence classification or for a text and a question for question answering. It is also used as the last
58
+ token of a sequence built with special tokens.
59
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
60
+ The token used for padding, for example when batching sequences of different lengths.
61
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
62
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
63
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
64
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
65
+ The token used for masking values. This is the token used when training this model with masked language
66
+ modeling. This is the token which the model will try to predict.
67
+ sp_model_kwargs (`dict`, *optional*):
68
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
69
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
70
+ to set:
71
+
72
+ - `enable_sampling`: Enable subword regularization.
73
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
74
+
75
+ - `nbest_size = {0,1}`: No sampling is performed.
76
+ - `nbest_size > 1`: samples from the nbest_size results.
77
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
78
+ using forward-filtering-and-backward-sampling algorithm.
79
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
80
+ BPE-dropout.
81
+
82
+ Attributes:
83
+ sp_model (`SentencePieceProcessor`):
84
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
85
+ """
86
+
87
+ vocab_files_names = VOCAB_FILES_NAMES
88
+ model_input_names = ["input_ids", "token_type_ids"]
89
+
90
+ def __init__(
91
+ self,
92
+ vocab_file,
93
+ do_lower_case=False,
94
+ remove_space=True,
95
+ keep_accents=True,
96
+ unk_token="<unk>",
97
+ sep_token="[SEP]",
98
+ pad_token="<pad>",
99
+ cls_token="[CLS]",
100
+ mask_token="[MASK]",
101
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
102
+ **kwargs,
103
+ ) -> None:
104
+ # Mask token behave like a normal word, i.e. include the space before it and
105
+ # is included in the raw text, there should be a match in a non-normalized sentence.
106
+ mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
107
+ cls_token = AddedToken(cls_token, special=True) if isinstance(cls_token, str) else cls_token
108
+ sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
109
+ mask_token = AddedToken(mask_token, special=True) if isinstance(mask_token, str) else mask_token
110
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
111
+
112
+ self.do_lower_case = do_lower_case
113
+ self.remove_space = remove_space
114
+ self.keep_accents = keep_accents
115
+ self.vocab_file = vocab_file
116
+
117
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
118
+ self.sp_model.Load(vocab_file)
119
+
120
+ super().__init__(
121
+ do_lower_case=do_lower_case,
122
+ remove_space=remove_space,
123
+ keep_accents=keep_accents,
124
+ unk_token=unk_token,
125
+ sep_token=sep_token,
126
+ pad_token=pad_token,
127
+ cls_token=cls_token,
128
+ mask_token=mask_token,
129
+ sp_model_kwargs=self.sp_model_kwargs,
130
+ **kwargs,
131
+ )
132
+
133
+ @property
134
+ def vocab_size(self):
135
+ return len(self.sp_model)
136
+
137
+ def get_vocab(self):
138
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
139
+ vocab.update(self.added_tokens_encoder)
140
+ return vocab
141
+
142
+ def __getstate__(self):
143
+ state = self.__dict__.copy()
144
+ state["sp_model"] = None
145
+ return state
146
+
147
+ def __setstate__(self, d):
148
+ self.__dict__ = d
149
+
150
+ # for backward compatibility
151
+ if not hasattr(self, "sp_model_kwargs"):
152
+ self.sp_model_kwargs = {}
153
+
154
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
155
+ self.sp_model.Load(self.vocab_file)
156
+
157
+ def preprocess_text(self, inputs):
158
+ if self.remove_space:
159
+ outputs = " ".join(inputs.strip().split())
160
+ else:
161
+ outputs = inputs
162
+ outputs = outputs.replace("``", '"').replace("''", '"')
163
+
164
+ if not self.keep_accents:
165
+ outputs = unicodedata.normalize("NFKD", outputs)
166
+ outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
167
+ if self.do_lower_case:
168
+ outputs = outputs.lower()
169
+
170
+ return outputs
171
+
172
+ def _tokenize(self, text: str) -> List[str]:
173
+ """Tokenize a string."""
174
+ text = self.preprocess_text(text)
175
+ pieces = self.sp_model.encode(text, out_type=str)
176
+ new_pieces = []
177
+ for piece in pieces:
178
+ if len(piece) > 1 and piece[-1] == str(",") and piece[-2].isdigit():
179
+ cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
180
+ if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
181
+ if len(cur_pieces[0]) == 1:
182
+ cur_pieces = cur_pieces[1:]
183
+ else:
184
+ cur_pieces[0] = cur_pieces[0][1:]
185
+ cur_pieces.append(piece[-1])
186
+ new_pieces.extend(cur_pieces)
187
+ else:
188
+ new_pieces.append(piece)
189
+
190
+ return new_pieces
191
+
192
+ def _convert_token_to_id(self, token):
193
+ """Converts a token (str) in an id using the vocab."""
194
+ return self.sp_model.PieceToId(token)
195
+
196
+ def _convert_id_to_token(self, index):
197
+ """Converts an index (integer) in a token (str) using the vocab."""
198
+ return self.sp_model.IdToPiece(index)
199
+
200
+ # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.convert_tokens_to_string
201
+ def convert_tokens_to_string(self, tokens):
202
+ """Converts a sequence of tokens (string) in a single string."""
203
+ current_sub_tokens = []
204
+ out_string = ""
205
+ prev_is_special = False
206
+ for token in tokens:
207
+ # make sure that special tokens are not decoded using sentencepiece model
208
+ if token in self.all_special_tokens:
209
+ if not prev_is_special:
210
+ out_string += " "
211
+ out_string += self.sp_model.decode(current_sub_tokens) + token
212
+ prev_is_special = True
213
+ current_sub_tokens = []
214
+ else:
215
+ current_sub_tokens.append(token)
216
+ prev_is_special = False
217
+ out_string += self.sp_model.decode(current_sub_tokens)
218
+ return out_string.strip()
219
+
220
+ def _decode(
221
+ self,
222
+ token_ids: List[int],
223
+ skip_special_tokens: bool = False,
224
+ clean_up_tokenization_spaces: bool = None,
225
+ spaces_between_special_tokens: bool = False,
226
+ **kwargs,
227
+ ) -> str:
228
+ text = super()._decode(
229
+ token_ids=token_ids,
230
+ skip_special_tokens=skip_special_tokens,
231
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
232
+ spaces_between_special_tokens=spaces_between_special_tokens,
233
+ **kwargs,
234
+ )
235
+ # Mimic the behavior of the Rust tokenizer:
236
+ # No space after <unk>
237
+ if not spaces_between_special_tokens:
238
+ text = text.replace("<unk> ", "<unk>")
239
+ return text
240
+
241
+ def build_inputs_with_special_tokens(
242
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
243
+ ) -> List[int]:
244
+ """
245
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
246
+ adding special tokens. An FNet sequence has the following format:
247
+
248
+ - single sequence: `[CLS] X [SEP]`
249
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
250
+
251
+ Args:
252
+ token_ids_0 (`List[int]`):
253
+ List of IDs to which the special tokens will be added.
254
+ token_ids_1 (`List[int]`, *optional*):
255
+ Optional second list of IDs for sequence pairs.
256
+
257
+ Returns:
258
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
259
+ """
260
+ sep = [self.sep_token_id]
261
+ cls = [self.cls_token_id]
262
+ if token_ids_1 is None:
263
+ return cls + token_ids_0 + sep
264
+ return cls + token_ids_0 + sep + token_ids_1 + sep
265
+
266
+ def get_special_tokens_mask(
267
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
268
+ ) -> List[int]:
269
+ """
270
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
271
+ special tokens using the tokenizer `prepare_for_model` method.
272
+
273
+ Args:
274
+ token_ids_0 (`List[int]`):
275
+ List of IDs.
276
+ token_ids_1 (`List[int]`, *optional*):
277
+ Optional second list of IDs for sequence pairs.
278
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
279
+ Whether or not the token list is already formatted with special tokens for the model.
280
+
281
+ Returns:
282
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
283
+ """
284
+
285
+ if already_has_special_tokens:
286
+ return super().get_special_tokens_mask(
287
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
288
+ )
289
+
290
+ if token_ids_1 is not None:
291
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
292
+ return [1] + ([0] * len(token_ids_0)) + [1]
293
+
294
+ def create_token_type_ids_from_sequences(
295
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
296
+ ) -> List[int]:
297
+ """
298
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An FNet sequence
299
+ pair mask has the following format: :
300
+
301
+ ```
302
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence |
303
+ ```
304
+
305
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
306
+
307
+ Args:
308
+ token_ids_0 (`List[int]`):
309
+ List of IDs.
310
+ token_ids_1 (`List[int]`, *optional*):
311
+ Optional second list of IDs for sequence pairs.
312
+
313
+ Returns:
314
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
315
+ """
316
+ sep = [self.sep_token_id]
317
+ cls = [self.cls_token_id]
318
+
319
+ if token_ids_1 is None:
320
+ return len(cls + token_ids_0 + sep) * [0]
321
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
322
+
323
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
324
+ if not os.path.isdir(save_directory):
325
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
326
+ return
327
+ out_vocab_file = os.path.join(
328
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
329
+ )
330
+
331
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
332
+ copyfile(self.vocab_file, out_vocab_file)
333
+ elif not os.path.isfile(self.vocab_file):
334
+ with open(out_vocab_file, "wb") as fi:
335
+ content_spiece_model = self.sp_model.serialized_model_proto()
336
+ fi.write(content_spiece_model)
337
+
338
+ return (out_vocab_file,)
videochat2/lib/python3.10/site-packages/transformers/models/fnet/tokenization_fnet_fast.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google AI, Google Brain and the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Tokenization classes for FNet model."""
16
+
17
+
18
+ import os
19
+ from shutil import copyfile
20
+ from typing import List, Optional, Tuple
21
+
22
+ from ...tokenization_utils import AddedToken
23
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
24
+ from ...utils import is_sentencepiece_available, logging
25
+
26
+
27
+ if is_sentencepiece_available():
28
+ from .tokenization_fnet import FNetTokenizer
29
+ else:
30
+ FNetTokenizer = None
31
+
32
+ logger = logging.get_logger(__name__)
33
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
34
+
35
+
36
+ SPIECE_UNDERLINE = "▁"
37
+
38
+
39
+ class FNetTokenizerFast(PreTrainedTokenizerFast):
40
+ """
41
+ Construct a "fast" FNetTokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
42
+ [`AlbertTokenizerFast`]. Based on
43
+ [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This
44
+ tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to
45
+ this superclass for more information regarding those methods
46
+
47
+ Args:
48
+ vocab_file (`str`):
49
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
50
+ contains the vocabulary necessary to instantiate a tokenizer.
51
+ do_lower_case (`bool`, *optional*, defaults to `False`):
52
+ Whether or not to lowercase the input when tokenizing.
53
+ remove_space (`bool`, *optional*, defaults to `True`):
54
+ Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
55
+ keep_accents (`bool`, *optional*, defaults to `True`):
56
+ Whether or not to keep accents when tokenizing.
57
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
58
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
59
+ token instead.
60
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
61
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
62
+ sequence classification or for a text and a question for question answering. It is also used as the last
63
+ token of a sequence built with special tokens.
64
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
65
+ The token used for padding, for example when batching sequences of different lengths.
66
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
67
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
68
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
69
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
70
+ The token used for masking values. This is the token used when training this model with masked language
71
+ modeling. This is the token which the model will try to predict.
72
+ """
73
+
74
+ vocab_files_names = VOCAB_FILES_NAMES
75
+ model_input_names = ["input_ids", "token_type_ids"]
76
+ slow_tokenizer_class = FNetTokenizer
77
+
78
+ def __init__(
79
+ self,
80
+ vocab_file=None,
81
+ tokenizer_file=None,
82
+ do_lower_case=False,
83
+ remove_space=True,
84
+ keep_accents=True,
85
+ unk_token="<unk>",
86
+ sep_token="[SEP]",
87
+ pad_token="<pad>",
88
+ cls_token="[CLS]",
89
+ mask_token="[MASK]",
90
+ **kwargs,
91
+ ):
92
+ # Mask token behave like a normal word, i.e. include the space before it and
93
+ # is included in the raw text, there should be a match in a non-normalized sentence.
94
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
95
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
96
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
97
+
98
+ super().__init__(
99
+ vocab_file,
100
+ tokenizer_file=tokenizer_file,
101
+ do_lower_case=do_lower_case,
102
+ remove_space=remove_space,
103
+ keep_accents=keep_accents,
104
+ unk_token=unk_token,
105
+ sep_token=sep_token,
106
+ pad_token=pad_token,
107
+ cls_token=cls_token,
108
+ mask_token=mask_token,
109
+ **kwargs,
110
+ )
111
+
112
+ self.do_lower_case = do_lower_case
113
+ self.remove_space = remove_space
114
+ self.keep_accents = keep_accents
115
+ self.vocab_file = vocab_file
116
+
117
+ @property
118
+ def can_save_slow_tokenizer(self) -> bool:
119
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
120
+
121
+ def build_inputs_with_special_tokens(
122
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
123
+ ) -> List[int]:
124
+ """
125
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
126
+ adding special tokens. An FNet sequence has the following format:
127
+
128
+ - single sequence: `[CLS] X [SEP]`
129
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
130
+
131
+ Args:
132
+ token_ids_0 (`List[int]`):
133
+ List of IDs to which the special tokens will be added
134
+ token_ids_1 (`List[int]`, *optional*):
135
+ Optional second list of IDs for sequence pairs.
136
+
137
+ Returns:
138
+ `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
139
+ """
140
+ sep = [self.sep_token_id]
141
+ cls = [self.cls_token_id]
142
+ if token_ids_1 is None:
143
+ return cls + token_ids_0 + sep
144
+ return cls + token_ids_0 + sep + token_ids_1 + sep
145
+
146
+ def create_token_type_ids_from_sequences(
147
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
148
+ ) -> List[int]:
149
+ """
150
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An FNet
151
+ sequence pair mask has the following format:
152
+
153
+ ```
154
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
155
+ | first sequence | second sequence |
156
+ ```
157
+
158
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
159
+
160
+ Args:
161
+ token_ids_0 (`List[int]`):
162
+ List of ids.
163
+ token_ids_1 (`List[int]`, *optional*):
164
+ Optional second list of IDs for sequence pairs.
165
+
166
+ Returns:
167
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
168
+ """
169
+ sep = [self.sep_token_id]
170
+ cls = [self.cls_token_id]
171
+
172
+ if token_ids_1 is None:
173
+ return len(cls + token_ids_0 + sep) * [0]
174
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
175
+
176
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
177
+ if not os.path.isdir(save_directory):
178
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
179
+ return
180
+ out_vocab_file = os.path.join(
181
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
182
+ )
183
+
184
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
185
+ copyfile(self.vocab_file, out_vocab_file)
186
+
187
+ return (out_vocab_file,)
videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/__init__.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_torch_available,
21
+ is_vision_available,
22
+ )
23
+
24
+
25
+ _import_structure = {
26
+ "configuration_kosmos2": ["KOSMOS2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Kosmos2Config"],
27
+ "processing_kosmos2": ["Kosmos2Processor"],
28
+ }
29
+
30
+ try:
31
+ if not is_torch_available():
32
+ raise OptionalDependencyNotAvailable()
33
+ except OptionalDependencyNotAvailable:
34
+ pass
35
+ else:
36
+ _import_structure["modeling_kosmos2"] = [
37
+ "KOSMOS2_PRETRAINED_MODEL_ARCHIVE_LIST",
38
+ "Kosmos2ForConditionalGeneration",
39
+ "Kosmos2Model",
40
+ "Kosmos2PreTrainedModel",
41
+ ]
42
+
43
+
44
+ if TYPE_CHECKING:
45
+ from .configuration_kosmos2 import KOSMOS2_PRETRAINED_CONFIG_ARCHIVE_MAP, Kosmos2Config
46
+ from .processing_kosmos2 import Kosmos2Processor
47
+
48
+ try:
49
+ if not is_torch_available():
50
+ raise OptionalDependencyNotAvailable()
51
+ except OptionalDependencyNotAvailable:
52
+ pass
53
+ else:
54
+ from .modeling_kosmos2 import (
55
+ KOSMOS2_PRETRAINED_MODEL_ARCHIVE_LIST,
56
+ Kosmos2ForConditionalGeneration,
57
+ Kosmos2Model,
58
+ Kosmos2PreTrainedModel,
59
+ )
60
+
61
+ else:
62
+ import sys
63
+
64
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)
videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (998 Bytes). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/configuration_kosmos2.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (2.31 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/modeling_kosmos2.cpython-310.pyc ADDED
Binary file (64.4 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/__pycache__/processing_kosmos2.cpython-310.pyc ADDED
Binary file (21 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/configuration_kosmos2.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ KOSMOS-2 model configuration"""
16
+
17
+ import os
18
+ from typing import Union
19
+
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ from ..deprecated._archive_maps import KOSMOS2_PRETRAINED_CONFIG_ARCHIVE_MAP # noqa: F401, E402
28
+
29
+
30
+ class Kosmos2TextConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`Kosmos2TextModel`]. It is used to instantiate a
33
+ KOSMOS-2 text decoder according to the specified arguments, defining the model architecture. Instantiating a
34
+ configuration with the defaults will yield a similar configuration to that of the text decoder of the KOSMOS-2
35
+ [microsoft/kosmos-2-patch14-224](https://huggingface.co/microsoft/kosmos-2-patch14-224) architecture.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 65037):
42
+ Vocabulary size of the Kosmos2 model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`Kosmos2Model`].
44
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
45
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
46
+ just in case (e.g., 512 or 1024 or 2048).
47
+ embed_dim (`int`, *optional*, defaults to 2048):
48
+ Dimensionality of the layers and the pooler layer.
49
+ layers (`int`, *optional*, defaults to 24):
50
+ Number of hidden layers in the Transformer encoder.
51
+ ffn_dim (`int`, *optional*, defaults to 8192):
52
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
53
+ attention_heads (`int`, *optional*, defaults to 32):
54
+ Number of attention heads for each attention layer in the Transformer encoder.
55
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
56
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
57
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
58
+ dropout (`float`, *optional*, defaults to 0.1):
59
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
60
+ attention_dropout (`float`, *optional*, defaults to 0.1):
61
+ The dropout ratio for the attention probabilities.
62
+ activation_dropout (`float`, *optional*, defaults to 0.0):
63
+ The dropout ratio for activations inside the fully connected layer.
64
+ layerdrop (`float`, *optional*, defaults to 0.0):
65
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
66
+ for more details.
67
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
68
+ The epsilon used by the layer normalization layers.
69
+ init_std (`float`, *optional*, defaults to 0.02):
70
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
71
+ scale_embedding (`bool`, *optional*, defaults to `True`):
72
+ Scale embeddings by diving by sqrt(embed_dim).
73
+ use_cache (`bool`, *optional*, defaults to `True`):
74
+ Whether or not the model should return the last key/values attentions (not used by all models).
75
+ ```"""
76
+
77
+ model_type = "kosmos_2_text_model"
78
+ keys_to_ignore_at_inference = ["past_key_values"]
79
+ attribute_map = {
80
+ "num_attention_heads": "attention_heads",
81
+ "hidden_size": "embed_dim",
82
+ "num_hidden_layers": "layers",
83
+ }
84
+
85
+ def __init__(
86
+ self,
87
+ vocab_size=65037,
88
+ max_position_embeddings=2048,
89
+ embed_dim=2048,
90
+ layers=24,
91
+ ffn_dim=8192,
92
+ attention_heads=32,
93
+ activation_function="gelu",
94
+ dropout=0.1,
95
+ attention_dropout=0.1,
96
+ activation_dropout=0.0,
97
+ layerdrop=0.0,
98
+ layer_norm_eps=1e-5,
99
+ init_std=0.02,
100
+ scale_embedding=True,
101
+ use_cache=True,
102
+ pad_token_id=1,
103
+ bos_token_id=0,
104
+ eos_token_id=2,
105
+ **kwargs,
106
+ ):
107
+ super().__init__(
108
+ pad_token_id=pad_token_id,
109
+ bos_token_id=bos_token_id,
110
+ eos_token_id=eos_token_id,
111
+ **kwargs,
112
+ )
113
+
114
+ self.vocab_size = vocab_size
115
+ self.max_position_embeddings = max_position_embeddings
116
+ self.embed_dim = embed_dim
117
+ self.layers = layers
118
+ self.ffn_dim = ffn_dim
119
+ self.attention_heads = attention_heads
120
+ self.activation_function = activation_function
121
+ self.dropout = dropout
122
+ self.attention_dropout = attention_dropout
123
+ self.activation_dropout = activation_dropout
124
+ self.layerdrop = layerdrop
125
+ self.layer_norm_eps = layer_norm_eps
126
+ self.init_std = init_std
127
+ self.scale_embedding = scale_embedding
128
+ self.use_cache = use_cache
129
+
130
+ @classmethod
131
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
132
+ cls._set_token_in_kwargs(kwargs)
133
+
134
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
135
+
136
+ # get the text config dict if we are loading from Kosmos2Config
137
+ if config_dict.get("model_type") == "kosmos-2":
138
+ config_dict = config_dict["text_config"]
139
+
140
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
141
+ logger.warning(
142
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
143
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
144
+ )
145
+
146
+ return cls.from_dict(config_dict, **kwargs)
147
+
148
+
149
+ class Kosmos2VisionConfig(PretrainedConfig):
150
+ r"""
151
+ This is the configuration class to store the configuration of a [`Kosmos2VisionModel`]. It is used to instantiate a
152
+ KOSMOS-2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a
153
+ configuration with the defaults will yield a similar configuration to that of the vision encoder of the KOSMOS-2
154
+ [microsoft/kosmos-2-patch14-224](https://huggingface.co/microsoft/kosmos-2-patch14-224) architecture.
155
+
156
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
157
+ documentation from [`PretrainedConfig`] for more information.
158
+
159
+ Args:
160
+ hidden_size (`int`, *optional*, defaults to 1024):
161
+ Dimensionality of the encoder layers and the pooler layer.
162
+ intermediate_size (`int`, *optional*, defaults to 4096):
163
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
164
+ num_hidden_layers (`int`, *optional*, defaults to 24):
165
+ Number of hidden layers in the Transformer encoder.
166
+ num_attention_heads (`int`, *optional*, defaults to 16):
167
+ Number of attention heads for each attention layer in the Transformer encoder.
168
+ num_channels (`int`, *optional*, defaults to 3):
169
+ The number of input channels.
170
+ image_size (`int`, *optional*, defaults to 224):
171
+ The size (resolution) of each image.
172
+ patch_size (`int`, *optional*, defaults to 14):
173
+ The size (resolution) of each patch.
174
+ hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
175
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
176
+ `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
177
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
178
+ The epsilon used by the layer normalization layers.
179
+ attention_dropout (`float`, *optional*, defaults to 0.0):
180
+ The dropout ratio for the attention probabilities.
181
+ initializer_range (`float`, *optional*, defaults to 0.02):
182
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
183
+ initializer_factor (`float`, *optional*, defaults to 1):
184
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
185
+ testing).
186
+ ```"""
187
+
188
+ model_type = "kosmos_2_vision_model"
189
+
190
+ def __init__(
191
+ self,
192
+ hidden_size=1024,
193
+ intermediate_size=4096,
194
+ num_hidden_layers=24,
195
+ num_attention_heads=16,
196
+ num_channels=3,
197
+ image_size=224,
198
+ patch_size=14,
199
+ hidden_act="quick_gelu",
200
+ layer_norm_eps=1e-5,
201
+ attention_dropout=0.0,
202
+ initializer_range=0.02,
203
+ initializer_factor=1.0,
204
+ **kwargs,
205
+ ):
206
+ super().__init__(**kwargs)
207
+
208
+ self.hidden_size = hidden_size
209
+ self.intermediate_size = intermediate_size
210
+ self.num_hidden_layers = num_hidden_layers
211
+ self.num_attention_heads = num_attention_heads
212
+ self.num_channels = num_channels
213
+ self.patch_size = patch_size
214
+ self.image_size = image_size
215
+ self.initializer_range = initializer_range
216
+ self.initializer_factor = initializer_factor
217
+ self.attention_dropout = attention_dropout
218
+ self.layer_norm_eps = layer_norm_eps
219
+ self.hidden_act = hidden_act
220
+
221
+ @classmethod
222
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
223
+ cls._set_token_in_kwargs(kwargs)
224
+
225
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
226
+
227
+ # get the vision config dict if we are loading from Kosmos2Config
228
+ if config_dict.get("model_type") == "kosmos-2":
229
+ config_dict = config_dict["vision_config"]
230
+
231
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
232
+ logger.warning(
233
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
234
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
235
+ )
236
+
237
+ return cls.from_dict(config_dict, **kwargs)
238
+
239
+
240
+ class Kosmos2Config(PretrainedConfig):
241
+ r"""
242
+ This is the configuration class to store the configuration of a [`Kosmos2Model`]. It is used to instantiate a
243
+ KOSMOS-2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
244
+ with the defaults will yield a similar configuration to that of the KOSMOS-2
245
+ [microsoft/kosmos-2-patch14-224](https://huggingface.co/microsoft/kosmos-2-patch14-224) architecture.
246
+
247
+ Args:
248
+ text_config (`dict`, *optional*):
249
+ Dictionary of configuration options used to initialize [`Kosmos2TextConfig`].
250
+ vision_config (`dict`, *optional*):
251
+ Dictionary of configuration options used to initialize [`Kosmos2VisionConfig`].
252
+ latent_query_num (`int`, *optional*, defaults to 64):
253
+ The number of latent query tokens that represent the image features used in the text decoder component.
254
+ kwargs (*optional*):
255
+ Dictionary of keyword arguments.
256
+
257
+ Example:
258
+
259
+ ```python
260
+ >>> from transformers import Kosmos2Config, Kosmos2Model
261
+
262
+ >>> # Initializing a Kosmos-2 kosmos-2-patch14-224 style configuration
263
+ >>> configuration = Kosmos2Config()
264
+
265
+ >>> # Initializing a model (with random weights) from the kosmos-2-patch14-224 style configuration
266
+ >>> model = Kosmos2Model(configuration)
267
+
268
+ >>> # Accessing the model configuration
269
+ >>> configuration = model.config
270
+ ```"""
271
+
272
+ model_type = "kosmos-2"
273
+ is_composition = True
274
+
275
+ def __init__(
276
+ self,
277
+ text_config=None,
278
+ vision_config=None,
279
+ latent_query_num=64,
280
+ **kwargs,
281
+ ):
282
+ super().__init__(**kwargs)
283
+
284
+ if text_config is None:
285
+ text_config = {}
286
+ logger.info("`text_config` is `None`. Initializing the `Kosmos2TextConfig` with default values.")
287
+
288
+ if vision_config is None:
289
+ vision_config = {}
290
+ logger.info("`vision_config` is `None`. Initializing the `Kosmos2VisionConfig` with default values.")
291
+
292
+ self.text_config = Kosmos2TextConfig(**text_config)
293
+ self.vision_config = Kosmos2VisionConfig(**vision_config)
294
+
295
+ self.latent_query_num = latent_query_num
videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ from fairseq.checkpoint_utils import load_checkpoint_to_cpu
4
+
5
+ from transformers import Kosmos2Config, Kosmos2ForConditionalGeneration
6
+
7
+
8
+ KEYS_TO_MODIFY_MAPPING = {
9
+ "gpt_model.decoder.output_projection": "text_model.lm_head",
10
+ "gpt_model.decoder": "text_model.model",
11
+ "img_connector": "image_to_text_projection",
12
+ "img_model.visual.class_embedding": "vision_model.model.embeddings.class_embedding",
13
+ "img_model.visual.positional_embedding": "vision_model.model.embeddings.position_embedding.weight",
14
+ "img_model.visual.conv1": "vision_model.model.embeddings.patch_embedding",
15
+ "img_model.visual": "vision_model.model",
16
+ "ln_pre": "pre_layrnorm",
17
+ "ln_post": "post_layernorm",
18
+ "transformer.resblocks": "encoder.layers",
19
+ "ts_attn": "self_attn",
20
+ "ln_1": "layer_norm1",
21
+ "ln_2": "layer_norm2",
22
+ "c_fc": "fc1",
23
+ "c_proj": "fc2",
24
+ }
25
+
26
+
27
+ KEYS_TO_IGNORE = [
28
+ # this buffer in the original code is only used to send weights to the desired device
29
+ "gpt_model.decoder.embed_positions._float_tensor",
30
+ # this weight is never used in the forward in the original KOSMOS-2)
31
+ "gpt_model.decoder.self_attn_sope.scale",
32
+ ]
33
+
34
+
35
+ def rename_key(key):
36
+ for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
37
+ if key_to_modify in key:
38
+ key = key.replace(key_to_modify, new_key)
39
+
40
+ return key
41
+
42
+
43
+ def convert_kosmos2_checkpoint_to_pytorch(checkpoint_path, pytorch_dump_folder_path):
44
+ state = load_checkpoint_to_cpu(checkpoint_path)
45
+ state_dict = state["model"]
46
+ state_dict_keys = list(state_dict.keys())
47
+
48
+ config = Kosmos2Config()
49
+ # This is necessary to match the results given by the original demo
50
+ config.text_config.no_repeat_ngram_size = 3
51
+ model = Kosmos2ForConditionalGeneration(config)
52
+
53
+ # convert (by renaming keys)
54
+ converted_state_dict = {}
55
+ for key in state_dict_keys:
56
+ if key in KEYS_TO_IGNORE:
57
+ continue
58
+ renamed_key = rename_key(key)
59
+ converted_state_dict[renamed_key] = state_dict[key]
60
+
61
+ # check weight loading
62
+ model.load_state_dict(converted_state_dict, strict=True)
63
+ # save the result
64
+ model.save_pretrained(pytorch_dump_folder_path)
65
+
66
+
67
+ if __name__ == "__main__":
68
+ parser = argparse.ArgumentParser()
69
+ # Required parameters
70
+ parser.add_argument(
71
+ "--kosmos2_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump."
72
+ )
73
+ parser.add_argument(
74
+ "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
75
+ )
76
+ args = parser.parse_args()
77
+ convert_kosmos2_checkpoint_to_pytorch(args.kosmos2_checkpoint_path, args.pytorch_dump_folder_path)
videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/modeling_kosmos2.py ADDED
@@ -0,0 +1,2054 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch KOSMOS-2 model."""
16
+
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Any, List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...modeling_outputs import (
29
+ BaseModelOutput,
30
+ BaseModelOutputWithPastAndCrossAttentions,
31
+ BaseModelOutputWithPooling,
32
+ CausalLMOutputWithCrossAttentions,
33
+ )
34
+ from ...modeling_utils import PreTrainedModel
35
+ from ...utils import (
36
+ ModelOutput,
37
+ add_start_docstrings,
38
+ add_start_docstrings_to_model_forward,
39
+ logging,
40
+ replace_return_docstrings,
41
+ )
42
+ from .configuration_kosmos2 import Kosmos2Config, Kosmos2TextConfig, Kosmos2VisionConfig
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _CONFIG_FOR_DOC = Kosmos2Config
48
+
49
+
50
+ from ..deprecated._archive_maps import KOSMOS2_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
51
+
52
+
53
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
54
+ """
55
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
56
+ """
57
+ bsz, src_len = mask.size()
58
+ tgt_len = tgt_len if tgt_len is not None else src_len
59
+
60
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
61
+
62
+ inverted_mask = 1.0 - expanded_mask
63
+
64
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
65
+
66
+
67
+ def _make_causal_mask(
68
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
69
+ ):
70
+ """
71
+ Make causal mask used for bi-directional self-attention.
72
+ """
73
+ bsz, tgt_len = input_ids_shape
74
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
75
+ mask_cond = torch.arange(mask.size(-1), device=device)
76
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
77
+ mask = mask.to(dtype)
78
+
79
+ if past_key_values_length > 0:
80
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
81
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
82
+
83
+
84
+ # Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
85
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
86
+ """
87
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
88
+ are ignored. This is modified from fairseq's `utils.make_positions`.
89
+
90
+ Args:
91
+ x: torch.Tensor x:
92
+
93
+ Returns: torch.Tensor
94
+ """
95
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
96
+ mask = input_ids.ne(padding_idx).int()
97
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
98
+ return incremental_indices.long() + padding_idx
99
+
100
+
101
+ KOSMOS2_START_DOCSTRING = r"""
102
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
103
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
104
+ etc.)
105
+
106
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
107
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
108
+ and behavior.
109
+
110
+ Parameters:
111
+ config ([`Kosmos2Config`]): Model configuration class with all the parameters of the model.
112
+ Initializing with a config file does not load the weights associated with the model, only the
113
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
114
+ """
115
+
116
+ KOSMOS2_VISION_INPUTS_DOCSTRING = r"""
117
+ Args:
118
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
119
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
120
+ [`CLIPImageProcessor.__call__`] for details.
121
+ output_attentions (`bool`, *optional*):
122
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
123
+ tensors for more detail.
124
+ output_hidden_states (`bool`, *optional*):
125
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
126
+ more detail.
127
+ return_dict (`bool`, *optional*):
128
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
129
+ """
130
+
131
+ KOSMOS2_TEXT_INPUTS_DOCSTRING = r"""
132
+ Args:
133
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
134
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
135
+ it.
136
+
137
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
138
+ [`PreTrainedTokenizer.__call__`] for details.
139
+
140
+ [What are input IDs?](../glossary#input-ids)
141
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
142
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
143
+
144
+ - 1 for tokens that are **not masked**,
145
+ - 0 for tokens that are **masked**.
146
+
147
+ [What are attention masks?](../glossary#attention-mask)
148
+ image_embeds: (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
149
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
150
+ image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
151
+ Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
152
+ 1]`:
153
+
154
+ - 1 for places where to put the image features,
155
+ - 0 for places that are not for image features (i.e. for text tokens).
156
+
157
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
158
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
159
+ the model is configured as a decoder.
160
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
161
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
162
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
163
+
164
+ - 1 for tokens that are **not masked**,
165
+ - 0 for tokens that are **masked**.
166
+
167
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
168
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
169
+
170
+ - 1 indicates the head is **not masked**,
171
+ - 0 indicates the head is **masked**.
172
+
173
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
174
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
175
+
176
+ - 1 indicates the head is **not masked**,
177
+ - 0 indicates the head is **masked**.
178
+
179
+ 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)`):
180
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
181
+
182
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
183
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
184
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
185
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
186
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
187
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
188
+ model's internal embedding lookup matrix.
189
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
190
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
191
+ config.max_position_embeddings - 1]`.
192
+
193
+ [What are position IDs?](../glossary#position-ids)
194
+ use_cache (`bool`, *optional*):
195
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
196
+ `past_key_values`).
197
+ output_attentions (`bool`, *optional*):
198
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
199
+ tensors for more detail.
200
+ output_hidden_states (`bool`, *optional*):
201
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
202
+ more detail.
203
+ return_dict (`bool`, *optional*):
204
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
205
+ """
206
+
207
+ KOSMOS2_INPUTS_DOCSTRING = r"""
208
+ Args:
209
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
210
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
211
+ [`CLIPImageProcessor.__call__`] for details.
212
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
213
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
214
+ it.
215
+
216
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
217
+ [`PreTrainedTokenizer.__call__`] for details.
218
+
219
+ [What are input IDs?](../glossary#input-ids)
220
+ image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
221
+ Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0,
222
+ 1]`:
223
+
224
+ - 1 for places where to put the image features,
225
+ - 0 for places that are not for image features (i.e. for text tokens).
226
+
227
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
228
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
229
+
230
+ - 1 for tokens that are **not masked**,
231
+ - 0 for tokens that are **masked**.
232
+
233
+ [What are attention masks?](../glossary#attention-mask)
234
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
235
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
236
+
237
+ - 1 indicates the head is **not masked**,
238
+ - 0 indicates the head is **masked**.
239
+ 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)`):
240
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
241
+
242
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
243
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
244
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
245
+ image_embeds: (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
246
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
247
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
248
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
249
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
250
+ model's internal embedding lookup matrix.
251
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
252
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
253
+ config.max_position_embeddings - 1]`.
254
+
255
+ [What are position IDs?](../glossary#position-ids)
256
+ use_cache (`bool`, *optional*):
257
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
258
+ `past_key_values`).
259
+ output_attentions (`bool`, *optional*):
260
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
261
+ tensors for more detail.
262
+ output_hidden_states (`bool`, *optional*):
263
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
264
+ more detail.
265
+ return_dict (`bool`, *optional*):
266
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
267
+ """
268
+
269
+
270
+ @dataclass
271
+ class Kosmos2ModelOutput(ModelOutput):
272
+ """
273
+ Base class for text model's outputs that also contains a pooling of the last hidden states.
274
+
275
+ Args:
276
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
277
+ Sequence of hidden-states at the output of the last layer of the model.
278
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
279
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
280
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
281
+
282
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
283
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
284
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
285
+ sequence_length)`.
286
+
287
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
288
+ heads.
289
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
290
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
291
+ projection_attentions (`tuple(torch.FloatTensor)`, *optional*):
292
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
293
+ sequence_length)`.
294
+
295
+ Attentions weights given by `Kosmos2ImageToTextProjection`, after the attention softmax, used to compute
296
+ the weighted average in the self-attention heads.
297
+ vision_model_output(`BaseModelOutputWithPooling`, *optional*):
298
+ The output of the [`Kosmos2VisionModel`].
299
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
300
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
301
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
302
+ `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
303
+ encoder_sequence_length, embed_size_per_head)`.
304
+
305
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
306
+ `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
307
+ input) to speed up sequential decoding.
308
+ """
309
+
310
+ last_hidden_state: torch.FloatTensor = None
311
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
312
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
313
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
314
+ image_embeds: Optional[torch.FloatTensor] = None
315
+ projection_attentions: Optional[Tuple[torch.FloatTensor]] = None
316
+ vision_model_output: BaseModelOutputWithPooling = None
317
+
318
+ def to_tuple(self) -> Tuple[Any]:
319
+ return tuple(
320
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
321
+ for k in self.keys()
322
+ )
323
+
324
+
325
+ @dataclass
326
+ class Kosmos2ForConditionalGenerationModelOutput(ModelOutput):
327
+ """
328
+ Model output class for `Kosmos2ForConditionalGeneration`.
329
+
330
+ Args:
331
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
332
+ Language modeling loss (for next-token prediction).
333
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
334
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
335
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
336
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
337
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
338
+
339
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
340
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
341
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
342
+ sequence_length)`.
343
+
344
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
345
+ heads.
346
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, latent_query_num, hidden_size)`, *optional*):
347
+ Sequence of hidden-states at the output of `Kosmos2ImageToTextProjection`.
348
+ projection_attentions (`tuple(torch.FloatTensor)`, *optional*):
349
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
350
+ sequence_length)`.
351
+
352
+ Attentions weights given by `Kosmos2ImageToTextProjection`, after the attention softmax, used to compute
353
+ the weighted average in the self-attention heads.
354
+ vision_model_output(`BaseModelOutputWithPooling`, *optional*):
355
+ The output of the [`Kosmos2VisionModel`].
356
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
357
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
358
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
359
+ `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
360
+ encoder_sequence_length, embed_size_per_head)`.
361
+
362
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
363
+ `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
364
+ input) to speed up sequential decoding.
365
+ """
366
+
367
+ loss: Optional[torch.FloatTensor] = None
368
+ logits: torch.FloatTensor = None
369
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
370
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
371
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
372
+ image_embeds: Optional[torch.FloatTensor] = None
373
+ projection_attentions: Optional[Tuple[torch.FloatTensor]] = None
374
+ vision_model_output: BaseModelOutputWithPooling = None
375
+
376
+ def to_tuple(self) -> Tuple[Any]:
377
+ return tuple(
378
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
379
+ for k in self.keys()
380
+ )
381
+
382
+
383
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->Kosmos2
384
+ class Kosmos2VisionEmbeddings(nn.Module):
385
+ def __init__(self, config: Kosmos2VisionConfig):
386
+ super().__init__()
387
+ self.config = config
388
+ self.embed_dim = config.hidden_size
389
+ self.image_size = config.image_size
390
+ self.patch_size = config.patch_size
391
+
392
+ self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
393
+
394
+ self.patch_embedding = nn.Conv2d(
395
+ in_channels=config.num_channels,
396
+ out_channels=self.embed_dim,
397
+ kernel_size=self.patch_size,
398
+ stride=self.patch_size,
399
+ bias=False,
400
+ )
401
+
402
+ self.num_patches = (self.image_size // self.patch_size) ** 2
403
+ self.num_positions = self.num_patches + 1
404
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
405
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
406
+
407
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
408
+ batch_size = pixel_values.shape[0]
409
+ target_dtype = self.patch_embedding.weight.dtype
410
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
411
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
412
+
413
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1)
414
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
415
+ embeddings = embeddings + self.position_embedding(self.position_ids)
416
+ return embeddings
417
+
418
+
419
+ # Copied from transformers.models.clip.modeling_clip.CLIPAttention with CLIP->Kosmos2Vision
420
+ class Kosmos2VisionAttention(nn.Module):
421
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
422
+
423
+ def __init__(self, config):
424
+ super().__init__()
425
+ self.config = config
426
+ self.embed_dim = config.hidden_size
427
+ self.num_heads = config.num_attention_heads
428
+ self.head_dim = self.embed_dim // self.num_heads
429
+ if self.head_dim * self.num_heads != self.embed_dim:
430
+ raise ValueError(
431
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
432
+ f" {self.num_heads})."
433
+ )
434
+ self.scale = self.head_dim**-0.5
435
+ self.dropout = config.attention_dropout
436
+
437
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
438
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
439
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
440
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
441
+
442
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
443
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
444
+
445
+ def forward(
446
+ self,
447
+ hidden_states: torch.Tensor,
448
+ attention_mask: Optional[torch.Tensor] = None,
449
+ causal_attention_mask: Optional[torch.Tensor] = None,
450
+ output_attentions: Optional[bool] = False,
451
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
452
+ """Input shape: Batch x Time x Channel"""
453
+
454
+ bsz, tgt_len, embed_dim = hidden_states.size()
455
+
456
+ # get query proj
457
+ query_states = self.q_proj(hidden_states) * self.scale
458
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
459
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
460
+
461
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
462
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
463
+ key_states = key_states.view(*proj_shape)
464
+ value_states = value_states.view(*proj_shape)
465
+
466
+ src_len = key_states.size(1)
467
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
468
+
469
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
470
+ raise ValueError(
471
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
472
+ f" {attn_weights.size()}"
473
+ )
474
+
475
+ # apply the causal_attention_mask first
476
+ if causal_attention_mask is not None:
477
+ if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
478
+ raise ValueError(
479
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
480
+ f" {causal_attention_mask.size()}"
481
+ )
482
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
483
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
484
+
485
+ if attention_mask is not None:
486
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
487
+ raise ValueError(
488
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
489
+ )
490
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
491
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
492
+
493
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
494
+
495
+ if output_attentions:
496
+ # this operation is a bit akward, but it's required to
497
+ # make sure that attn_weights keeps its gradient.
498
+ # In order to do so, attn_weights have to reshaped
499
+ # twice and have to be reused in the following
500
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
501
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
502
+ else:
503
+ attn_weights_reshaped = None
504
+
505
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
506
+
507
+ attn_output = torch.bmm(attn_probs, value_states)
508
+
509
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
510
+ raise ValueError(
511
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
512
+ f" {attn_output.size()}"
513
+ )
514
+
515
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
516
+ attn_output = attn_output.transpose(1, 2)
517
+ attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
518
+
519
+ attn_output = self.out_proj(attn_output)
520
+
521
+ return attn_output, attn_weights_reshaped
522
+
523
+
524
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Kosmos2Vision
525
+ class Kosmos2VisionMLP(nn.Module):
526
+ def __init__(self, config):
527
+ super().__init__()
528
+ self.config = config
529
+ self.activation_fn = ACT2FN[config.hidden_act]
530
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
531
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
532
+
533
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
534
+ hidden_states = self.fc1(hidden_states)
535
+ hidden_states = self.activation_fn(hidden_states)
536
+ hidden_states = self.fc2(hidden_states)
537
+ return hidden_states
538
+
539
+
540
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Kosmos2Vision
541
+ class Kosmos2VisionEncoderLayer(nn.Module):
542
+ def __init__(self, config: Kosmos2VisionConfig):
543
+ super().__init__()
544
+ self.embed_dim = config.hidden_size
545
+ self.self_attn = Kosmos2VisionAttention(config)
546
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
547
+ self.mlp = Kosmos2VisionMLP(config)
548
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
549
+
550
+ def forward(
551
+ self,
552
+ hidden_states: torch.Tensor,
553
+ attention_mask: torch.Tensor,
554
+ causal_attention_mask: torch.Tensor,
555
+ output_attentions: Optional[bool] = False,
556
+ ) -> Tuple[torch.FloatTensor]:
557
+ """
558
+ Args:
559
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
560
+ attention_mask (`torch.FloatTensor`): attention mask of size
561
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
562
+ `(config.encoder_attention_heads,)`.
563
+ output_attentions (`bool`, *optional*):
564
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
565
+ returned tensors for more detail.
566
+ """
567
+ residual = hidden_states
568
+
569
+ hidden_states = self.layer_norm1(hidden_states)
570
+ hidden_states, attn_weights = self.self_attn(
571
+ hidden_states=hidden_states,
572
+ attention_mask=attention_mask,
573
+ causal_attention_mask=causal_attention_mask,
574
+ output_attentions=output_attentions,
575
+ )
576
+ hidden_states = residual + hidden_states
577
+
578
+ residual = hidden_states
579
+ hidden_states = self.layer_norm2(hidden_states)
580
+ hidden_states = self.mlp(hidden_states)
581
+ hidden_states = residual + hidden_states
582
+
583
+ outputs = (hidden_states,)
584
+
585
+ if output_attentions:
586
+ outputs += (attn_weights,)
587
+
588
+ return outputs
589
+
590
+
591
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Kosmos2Vision
592
+ class Kosmos2VisionEncoder(nn.Module):
593
+ """
594
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
595
+ [`Kosmos2VisionEncoderLayer`].
596
+
597
+ Args:
598
+ config: Kosmos2VisionConfig
599
+ """
600
+
601
+ def __init__(self, config: Kosmos2VisionConfig):
602
+ super().__init__()
603
+ self.config = config
604
+ self.layers = nn.ModuleList([Kosmos2VisionEncoderLayer(config) for _ in range(config.num_hidden_layers)])
605
+ self.gradient_checkpointing = False
606
+
607
+ def forward(
608
+ self,
609
+ inputs_embeds,
610
+ attention_mask: Optional[torch.Tensor] = None,
611
+ causal_attention_mask: Optional[torch.Tensor] = None,
612
+ output_attentions: Optional[bool] = None,
613
+ output_hidden_states: Optional[bool] = None,
614
+ return_dict: Optional[bool] = None,
615
+ ) -> Union[Tuple, BaseModelOutput]:
616
+ r"""
617
+ Args:
618
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
619
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
620
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
621
+ than the model's internal embedding lookup matrix.
622
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
623
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
624
+
625
+ - 1 for tokens that are **not masked**,
626
+ - 0 for tokens that are **masked**.
627
+
628
+ [What are attention masks?](../glossary#attention-mask)
629
+ causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
630
+ Causal mask for the text model. Mask values selected in `[0, 1]`:
631
+
632
+ - 1 for tokens that are **not masked**,
633
+ - 0 for tokens that are **masked**.
634
+
635
+ [What are attention masks?](../glossary#attention-mask)
636
+ output_attentions (`bool`, *optional*):
637
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
638
+ returned tensors for more detail.
639
+ output_hidden_states (`bool`, *optional*):
640
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
641
+ for more detail.
642
+ return_dict (`bool`, *optional*):
643
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
644
+ """
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
+ encoder_states = () if output_hidden_states else None
652
+ all_attentions = () if output_attentions else None
653
+
654
+ hidden_states = inputs_embeds
655
+ for idx, encoder_layer in enumerate(self.layers):
656
+ if output_hidden_states:
657
+ encoder_states = encoder_states + (hidden_states,)
658
+ if self.gradient_checkpointing and self.training:
659
+ layer_outputs = self._gradient_checkpointing_func(
660
+ encoder_layer.__call__,
661
+ hidden_states,
662
+ attention_mask,
663
+ causal_attention_mask,
664
+ output_attentions,
665
+ )
666
+ else:
667
+ layer_outputs = encoder_layer(
668
+ hidden_states,
669
+ attention_mask,
670
+ causal_attention_mask,
671
+ output_attentions=output_attentions,
672
+ )
673
+
674
+ hidden_states = layer_outputs[0]
675
+
676
+ if output_attentions:
677
+ all_attentions = all_attentions + (layer_outputs[1],)
678
+
679
+ if output_hidden_states:
680
+ encoder_states = encoder_states + (hidden_states,)
681
+
682
+ if not return_dict:
683
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
684
+ return BaseModelOutput(
685
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
686
+ )
687
+
688
+
689
+ # Similar to `transformers.models.clip.modeling_clip.CLIPVisionTransformer` but without docstring for `forward`
690
+ class Kosmos2VisionTransformer(nn.Module):
691
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionTransformer.__init__ with CLIPVision->Kosmos2Vision,CLIP_VISION->KOSMOS2_VISION,CLIP->Kosmos2Vision
692
+ def __init__(self, config: Kosmos2VisionConfig):
693
+ super().__init__()
694
+ self.config = config
695
+ embed_dim = config.hidden_size
696
+
697
+ self.embeddings = Kosmos2VisionEmbeddings(config)
698
+ self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
699
+ self.encoder = Kosmos2VisionEncoder(config)
700
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
701
+
702
+ def forward(
703
+ self,
704
+ pixel_values: Optional[torch.FloatTensor] = None,
705
+ output_attentions: Optional[bool] = None,
706
+ output_hidden_states: Optional[bool] = None,
707
+ return_dict: Optional[bool] = None,
708
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
709
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
710
+ output_hidden_states = (
711
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
712
+ )
713
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
714
+
715
+ if pixel_values is None:
716
+ raise ValueError("You have to specify pixel_values")
717
+
718
+ hidden_states = self.embeddings(pixel_values)
719
+ hidden_states = self.pre_layrnorm(hidden_states)
720
+
721
+ encoder_outputs = self.encoder(
722
+ inputs_embeds=hidden_states,
723
+ output_attentions=output_attentions,
724
+ output_hidden_states=output_hidden_states,
725
+ return_dict=return_dict,
726
+ )
727
+
728
+ last_hidden_state = encoder_outputs[0]
729
+ pooled_output = last_hidden_state[:, 0, :]
730
+ pooled_output = self.post_layernorm(pooled_output)
731
+
732
+ if not return_dict:
733
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
734
+
735
+ return BaseModelOutputWithPooling(
736
+ last_hidden_state=last_hidden_state,
737
+ pooler_output=pooled_output,
738
+ hidden_states=encoder_outputs.hidden_states,
739
+ attentions=encoder_outputs.attentions,
740
+ )
741
+
742
+
743
+ # Similar to `transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding` but allowing to pass `position_ids`
744
+ class Kosmos2TextSinusoidalPositionalEmbedding(nn.Module):
745
+ """This module produces sinusoidal positional embeddings of any length."""
746
+
747
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.__init__
748
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
749
+ super().__init__()
750
+ self.offset = 2
751
+ self.embedding_dim = embedding_dim
752
+ self.padding_idx = padding_idx
753
+ self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
754
+
755
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.make_weights
756
+ def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
757
+ emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
758
+ if hasattr(self, "weights"):
759
+ # in forward put the weights on the correct dtype and device of the param
760
+ emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
761
+
762
+ self.register_buffer("weights", emb_weights, persistent=False)
763
+
764
+ @staticmethod
765
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.get_embedding
766
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
767
+ """
768
+ Build sinusoidal embeddings.
769
+
770
+ This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
771
+ "Attention Is All You Need".
772
+ """
773
+ half_dim = embedding_dim // 2
774
+ emb = math.log(10000) / (half_dim - 1)
775
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
776
+ emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
777
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
778
+ if embedding_dim % 2 == 1:
779
+ # zero pad
780
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
781
+ if padding_idx is not None:
782
+ emb[padding_idx, :] = 0
783
+
784
+ return emb.to(torch.get_default_dtype())
785
+
786
+ @torch.no_grad()
787
+ def forward(
788
+ self,
789
+ input_ids: torch.Tensor = None,
790
+ inputs_embeds: torch.Tensor = None,
791
+ past_key_values_length: int = 0,
792
+ position_ids: torch.Tensor = None,
793
+ ):
794
+ if input_ids is not None:
795
+ bsz, seq_len = input_ids.size()
796
+ if position_ids is None:
797
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
798
+ position_ids = create_position_ids_from_input_ids(
799
+ input_ids, self.padding_idx, past_key_values_length
800
+ ).to(input_ids.device)
801
+ else:
802
+ bsz, seq_len = inputs_embeds.size()[:-1]
803
+ if position_ids is None:
804
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, past_key_values_length)
805
+
806
+ # expand embeddings if needed
807
+ max_pos = self.padding_idx + 1 + seq_len + past_key_values_length
808
+ if max_pos > self.weights.size(0):
809
+ self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
810
+
811
+ return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach()
812
+
813
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.create_position_ids_from_inputs_embeds
814
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds, past_key_values_length):
815
+ """
816
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
817
+
818
+ Args:
819
+ inputs_embeds: torch.Tensor
820
+
821
+ Returns: torch.Tensor
822
+ """
823
+ input_shape = inputs_embeds.size()[:-1]
824
+ sequence_length = input_shape[1]
825
+
826
+ position_ids = torch.arange(
827
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
828
+ )
829
+ return position_ids.unsqueeze(0).expand(input_shape).contiguous() + past_key_values_length
830
+
831
+
832
+ class KosmosTextAttention(nn.Module):
833
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
834
+
835
+ # Similar to transformers.models.bart.modeling_bart.BartAttention.__init__ except an additional `inner_attn_ln`.
836
+ def __init__(
837
+ self,
838
+ config,
839
+ embed_dim: int,
840
+ num_heads: int,
841
+ dropout: float = 0.0,
842
+ is_decoder: bool = False,
843
+ add_inner_attn_layernorm: bool = False,
844
+ bias: bool = True,
845
+ ):
846
+ super().__init__()
847
+ self.embed_dim = embed_dim
848
+ self.num_heads = num_heads
849
+ self.dropout = dropout
850
+ self.head_dim = embed_dim // num_heads
851
+
852
+ if (self.head_dim * num_heads) != self.embed_dim:
853
+ raise ValueError(
854
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
855
+ f" and `num_heads`: {num_heads})."
856
+ )
857
+ self.scaling = self.head_dim**-0.5
858
+ self.is_decoder = is_decoder
859
+
860
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
861
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
862
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
863
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
864
+
865
+ # End opy
866
+ self.inner_attn_ln = None
867
+ if add_inner_attn_layernorm:
868
+ self.inner_attn_ln = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
869
+
870
+ def _shape(self, projection: torch.Tensor) -> torch.Tensor:
871
+ new_projection_shape = projection.size()[:-1] + (self.num_heads, self.head_dim)
872
+ # move heads to 2nd position (B, T, H * D) -> (B, T, H, D) -> (B, H, T, D)
873
+ new_projection = projection.view(new_projection_shape).permute(0, 2, 1, 3)
874
+ return new_projection
875
+
876
+ def forward(
877
+ self,
878
+ hidden_states: torch.Tensor,
879
+ encoder_hidden_states: Optional[torch.Tensor] = None,
880
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
881
+ attention_mask: Optional[torch.Tensor] = None,
882
+ layer_head_mask: Optional[torch.Tensor] = None,
883
+ output_attentions: bool = False,
884
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
885
+ """Input shape: Batch x Time x Channel"""
886
+
887
+ # if key_value_states are provided this layer is used as a cross-attention layer
888
+ # for the decoder
889
+ is_cross_attention = encoder_hidden_states is not None
890
+ batch_size, seq_length = hidden_states.shape[:2]
891
+
892
+ # use encoder_hidden_states if cross attention
893
+ current_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
894
+ # checking that the `sequence_length` of the `past_key_value` is the same as the he provided
895
+ # `encoder_hidden_states` to support prefix tuning
896
+ if is_cross_attention and past_key_value and past_key_value[0].shape[2] == current_states.shape[1]:
897
+ # reuse k,v, cross_attentions
898
+ key_states = past_key_value[0]
899
+ value_states = past_key_value[1]
900
+ else:
901
+ key_states = self._shape(self.k_proj(current_states))
902
+ value_states = self._shape(self.v_proj(current_states))
903
+ if past_key_value is not None and not is_cross_attention:
904
+ # reuse k, v, self_attention
905
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
906
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
907
+
908
+ query_states = self._shape(self.q_proj(hidden_states) * self.scaling)
909
+ attn_weights = torch.matmul(query_states, key_states.transpose(-1, -2))
910
+
911
+ if self.is_decoder:
912
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
913
+ # Further calls to cross_attention layer can then reuse all cross-attention
914
+ # key/value_states (first "if" case)
915
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
916
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
917
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
918
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
919
+ past_key_value = (key_states, value_states)
920
+
921
+ src_len = key_states.size(2)
922
+
923
+ if attention_mask is not None:
924
+ if attention_mask.size() != (batch_size, 1, seq_length, src_len):
925
+ raise ValueError(
926
+ f"Attention mask should be of size {(batch_size, 1, seq_length, src_len)}, but is {attention_mask.size()}"
927
+ )
928
+ attn_weights = attn_weights + attention_mask
929
+
930
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
931
+
932
+ # Mask heads if we want to
933
+ if layer_head_mask is not None:
934
+ attn_weights = attn_weights * layer_head_mask
935
+
936
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
937
+
938
+ # attn_output = torch.bmm(attn_probs, value_states) ?
939
+ context_states = torch.matmul(attn_weights, value_states)
940
+ # attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) ?
941
+ context_states = context_states.permute(0, 2, 1, 3).contiguous().view(batch_size, seq_length, -1)
942
+
943
+ if self.inner_attn_ln is not None:
944
+ context_states = self.inner_attn_ln(context_states)
945
+
946
+ attn_output = self.out_proj(context_states)
947
+
948
+ return attn_output, attn_weights, past_key_value
949
+
950
+
951
+ class Kosmos2TextFFN(nn.Module):
952
+ def __init__(self, config: Kosmos2TextConfig):
953
+ super().__init__()
954
+
955
+ self.dropout = config.dropout
956
+ self.activation_fn = ACT2FN[config.activation_function]
957
+ self.activation_dropout = config.activation_dropout
958
+
959
+ self.fc1 = nn.Linear(config.embed_dim, config.ffn_dim)
960
+ self.fc2 = nn.Linear(config.ffn_dim, config.embed_dim)
961
+
962
+ self.ffn_layernorm = nn.LayerNorm(config.ffn_dim, eps=config.layer_norm_eps)
963
+
964
+ def forward(self, hidden_states):
965
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
966
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
967
+ hidden_states = self.ffn_layernorm(hidden_states)
968
+ hidden_states = self.fc2(hidden_states)
969
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
970
+
971
+ return hidden_states
972
+
973
+
974
+ class Kosmos2TextBlock(nn.Module):
975
+ def __init__(self, config: Kosmos2TextConfig):
976
+ super().__init__()
977
+ self.embed_dim = config.embed_dim
978
+
979
+ self.self_attn = KosmosTextAttention(
980
+ config,
981
+ embed_dim=self.embed_dim,
982
+ num_heads=config.attention_heads,
983
+ dropout=config.attention_dropout,
984
+ is_decoder=True,
985
+ add_inner_attn_layernorm=True,
986
+ )
987
+ self.dropout = config.dropout
988
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
989
+
990
+ if config.add_cross_attention:
991
+ self.encoder_attn = KosmosTextAttention(
992
+ config,
993
+ embed_dim=self.embed_dim,
994
+ num_heads=config.attention_heads,
995
+ dropout=config.attention_dropout,
996
+ is_decoder=True,
997
+ add_inner_attn_layernorm=False,
998
+ )
999
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
1000
+
1001
+ self.ffn = Kosmos2TextFFN(config)
1002
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
1003
+
1004
+ def forward(
1005
+ self,
1006
+ hidden_states: torch.Tensor,
1007
+ attention_mask: Optional[torch.Tensor] = None,
1008
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1009
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1010
+ layer_head_mask: Optional[torch.Tensor] = None,
1011
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
1012
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1013
+ output_attentions: Optional[bool] = False,
1014
+ use_cache: Optional[bool] = True,
1015
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1016
+ residual = hidden_states
1017
+
1018
+ # Self Attention
1019
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
1020
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
1021
+
1022
+ hidden_states = self.self_attn_layer_norm(hidden_states)
1023
+
1024
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
1025
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1026
+ hidden_states=hidden_states,
1027
+ past_key_value=self_attn_past_key_value,
1028
+ attention_mask=attention_mask,
1029
+ layer_head_mask=layer_head_mask,
1030
+ output_attentions=output_attentions,
1031
+ )
1032
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1033
+ hidden_states = residual + hidden_states
1034
+
1035
+ # Cross-Attention Block
1036
+ cross_attn_present_key_value = None
1037
+ cross_attn_weights = None
1038
+ if encoder_hidden_states is not None:
1039
+ if not hasattr(self, "encoder_attn"):
1040
+ raise ValueError(
1041
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
1042
+ " by setting `config.add_cross_attention=True`"
1043
+ )
1044
+
1045
+ residual = hidden_states
1046
+
1047
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
1048
+
1049
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
1050
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
1051
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
1052
+ hidden_states=hidden_states,
1053
+ encoder_hidden_states=encoder_hidden_states,
1054
+ attention_mask=encoder_attention_mask,
1055
+ layer_head_mask=cross_attn_layer_head_mask,
1056
+ past_key_value=cross_attn_past_key_value,
1057
+ output_attentions=output_attentions,
1058
+ )
1059
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1060
+ hidden_states = residual + hidden_states
1061
+
1062
+ # add cross-attn to positions 3,4 of present_key_value tuple
1063
+ present_key_value = present_key_value + cross_attn_present_key_value
1064
+
1065
+ # Fully Connected
1066
+ residual = hidden_states
1067
+
1068
+ hidden_states = self.final_layer_norm(hidden_states)
1069
+
1070
+ # FFN
1071
+ hidden_states = self.ffn(hidden_states)
1072
+ hidden_states = residual + hidden_states
1073
+
1074
+ outputs = (hidden_states,)
1075
+
1076
+ if output_attentions:
1077
+ outputs += (self_attn_weights, cross_attn_weights)
1078
+
1079
+ if use_cache:
1080
+ outputs += (present_key_value,)
1081
+
1082
+ return outputs
1083
+
1084
+
1085
+ class Kosmos2TextTransformer(nn.Module):
1086
+ """
1087
+ Transformer decoder consisting of `config.layers` layers. Each layer is a [`Kosmos2TextBlock`].
1088
+
1089
+ Args:
1090
+ config: Kosmos2TextConfig
1091
+ """
1092
+
1093
+ def __init__(self, config: Kosmos2TextConfig):
1094
+ super().__init__()
1095
+ self.config = config
1096
+ self.dropout = config.dropout
1097
+ self.layerdrop = config.layerdrop
1098
+
1099
+ self.embed_scale = math.sqrt(config.embed_dim) if config.scale_embedding else 1.0
1100
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.embed_dim, padding_idx=config.pad_token_id)
1101
+
1102
+ self.embed_positions = Kosmos2TextSinusoidalPositionalEmbedding(
1103
+ num_positions=config.max_position_embeddings,
1104
+ embedding_dim=config.embed_dim,
1105
+ padding_idx=config.pad_token_id,
1106
+ )
1107
+
1108
+ self.layers = nn.ModuleList([Kosmos2TextBlock(config) for _ in range(config.layers)])
1109
+ self.layer_norm = nn.LayerNorm(config.embed_dim, config.layer_norm_eps)
1110
+
1111
+ self.gradient_checkpointing = False
1112
+
1113
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
1114
+ # create causal mask
1115
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1116
+ combined_attention_mask = None
1117
+ if input_shape[-1] > 1:
1118
+ combined_attention_mask = _make_causal_mask(
1119
+ input_shape,
1120
+ inputs_embeds.dtype,
1121
+ device=inputs_embeds.device,
1122
+ past_key_values_length=past_key_values_length,
1123
+ )
1124
+
1125
+ if attention_mask is not None:
1126
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1127
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
1128
+ inputs_embeds.device
1129
+ )
1130
+ combined_attention_mask = (
1131
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
1132
+ )
1133
+
1134
+ return combined_attention_mask
1135
+
1136
+ def forward_embedding(
1137
+ self,
1138
+ input_ids,
1139
+ inputs_embeds: torch.Tensor = None,
1140
+ image_embeds: torch.Tensor = None,
1141
+ img_input_mask: torch.Tensor = None,
1142
+ past_key_values_length: int = 0,
1143
+ position_ids: torch.Tensor = None,
1144
+ ):
1145
+ # The argument `inputs_embeds` should be the one without being multiplied by `self.embed_scale`.
1146
+ if inputs_embeds is None:
1147
+ inputs_embeds = self.embed_tokens(input_ids)
1148
+
1149
+ if image_embeds is not None:
1150
+ inputs_embeds[img_input_mask.to(dtype=torch.bool)] = image_embeds.to(inputs_embeds.device).view(
1151
+ -1, image_embeds.size(-1)
1152
+ )
1153
+
1154
+ inputs_embeds = inputs_embeds * self.embed_scale
1155
+
1156
+ # embed positions
1157
+ positions = self.embed_positions(
1158
+ input_ids=input_ids,
1159
+ inputs_embeds=inputs_embeds,
1160
+ past_key_values_length=past_key_values_length,
1161
+ position_ids=position_ids,
1162
+ )
1163
+ positions = positions.to(inputs_embeds.device)
1164
+
1165
+ hidden_states = inputs_embeds + positions
1166
+
1167
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1168
+
1169
+ return hidden_states
1170
+
1171
+ def forward(
1172
+ self,
1173
+ input_ids: Optional[torch.Tensor] = None,
1174
+ attention_mask: Optional[torch.Tensor] = None,
1175
+ image_embeds: Optional[torch.Tensor] = None,
1176
+ image_embeds_position_mask: Optional[torch.Tensor] = None,
1177
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1178
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1179
+ head_mask: Optional[torch.Tensor] = None,
1180
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1181
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1182
+ inputs_embeds: Optional[torch.Tensor] = None,
1183
+ position_ids: Optional[torch.Tensor] = None,
1184
+ use_cache: Optional[bool] = None,
1185
+ output_attentions: Optional[bool] = None,
1186
+ output_hidden_states: Optional[bool] = None,
1187
+ return_dict: Optional[bool] = None,
1188
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
1189
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1190
+ output_hidden_states = (
1191
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1192
+ )
1193
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1194
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1195
+
1196
+ if input_ids is not None and inputs_embeds is not None:
1197
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1198
+ elif input_ids is not None:
1199
+ input_shape = input_ids.shape
1200
+ input_ids = input_ids.view(-1, input_shape[-1])
1201
+ elif inputs_embeds is not None:
1202
+ input_shape = inputs_embeds.size()[:-1]
1203
+ else:
1204
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1205
+
1206
+ # past_key_values_length
1207
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1208
+
1209
+ # We don't need img info. when `past_key_values_length` > 0
1210
+ if past_key_values_length > 0:
1211
+ image_embeds = None
1212
+ image_embeds_position_mask = None
1213
+
1214
+ hidden_states = self.forward_embedding(
1215
+ input_ids=input_ids,
1216
+ inputs_embeds=inputs_embeds,
1217
+ image_embeds=image_embeds,
1218
+ img_input_mask=image_embeds_position_mask,
1219
+ past_key_values_length=past_key_values_length,
1220
+ position_ids=position_ids,
1221
+ )
1222
+
1223
+ attention_mask = self._prepare_decoder_attention_mask(
1224
+ attention_mask, input_shape, hidden_states, past_key_values_length
1225
+ )
1226
+
1227
+ # expand encoder attention mask
1228
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1229
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1230
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
1231
+
1232
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1233
+
1234
+ if self.gradient_checkpointing and self.training:
1235
+ if use_cache:
1236
+ logger.warning_once(
1237
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1238
+ )
1239
+ use_cache = False
1240
+
1241
+ # decoder layers
1242
+ all_hidden_states = () if output_hidden_states else None
1243
+ all_self_attns = () if output_attentions else None
1244
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
1245
+ present_key_value_states = () if use_cache else None
1246
+
1247
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
1248
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
1249
+ if attn_mask is not None:
1250
+ if attn_mask.size()[0] != (len(self.layers)):
1251
+ raise ValueError(
1252
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
1253
+ f" {head_mask.size()[0]}."
1254
+ )
1255
+
1256
+ for idx, decoder_layer in enumerate(self.layers):
1257
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1258
+ if output_hidden_states:
1259
+ all_hidden_states += (hidden_states,)
1260
+ if self.training:
1261
+ dropout_probability = torch.rand([])
1262
+ if dropout_probability < self.layerdrop:
1263
+ continue
1264
+
1265
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1266
+
1267
+ if self.gradient_checkpointing and self.training:
1268
+ layer_outputs = self._gradient_checkpointing_func(
1269
+ decoder_layer.__call__,
1270
+ hidden_states,
1271
+ attention_mask,
1272
+ encoder_hidden_states,
1273
+ encoder_attention_mask,
1274
+ head_mask[idx] if head_mask is not None else None,
1275
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
1276
+ None,
1277
+ output_attentions,
1278
+ use_cache,
1279
+ )
1280
+ else:
1281
+ layer_outputs = decoder_layer(
1282
+ hidden_states,
1283
+ attention_mask=attention_mask,
1284
+ encoder_hidden_states=encoder_hidden_states,
1285
+ encoder_attention_mask=encoder_attention_mask,
1286
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1287
+ cross_attn_layer_head_mask=(
1288
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
1289
+ ),
1290
+ past_key_value=past_key_value,
1291
+ output_attentions=output_attentions,
1292
+ use_cache=use_cache,
1293
+ )
1294
+ hidden_states = layer_outputs[0]
1295
+
1296
+ if use_cache:
1297
+ present_key_value_states += (layer_outputs[3 if output_attentions else 1],)
1298
+
1299
+ if output_attentions:
1300
+ all_self_attns += (layer_outputs[1],)
1301
+
1302
+ if encoder_hidden_states is not None:
1303
+ all_cross_attentions += (layer_outputs[2],)
1304
+
1305
+ # add final layer norm
1306
+ hidden_states = self.layer_norm(hidden_states)
1307
+
1308
+ # add hidden states from the last decoder layer
1309
+ if output_hidden_states:
1310
+ all_hidden_states += (hidden_states,)
1311
+
1312
+ if not return_dict:
1313
+ return tuple(
1314
+ v
1315
+ for v in [
1316
+ hidden_states,
1317
+ present_key_value_states,
1318
+ all_hidden_states,
1319
+ all_self_attns,
1320
+ all_cross_attentions,
1321
+ ]
1322
+ if v is not None
1323
+ )
1324
+ return BaseModelOutputWithPastAndCrossAttentions(
1325
+ last_hidden_state=hidden_states,
1326
+ past_key_values=present_key_value_states,
1327
+ hidden_states=all_hidden_states,
1328
+ attentions=all_self_attns,
1329
+ cross_attentions=all_cross_attentions,
1330
+ )
1331
+
1332
+
1333
+ class Kosmos2PreTrainedModel(PreTrainedModel):
1334
+ """
1335
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1336
+ models.
1337
+ """
1338
+
1339
+ config_class = Kosmos2Config
1340
+ supports_gradient_checkpointing = True
1341
+ _no_split_modules = ["Kosmos2VisionEncoderLayer", "Kosmos2TextBlock"]
1342
+
1343
+ def _init_weights(self, module):
1344
+ """Initialize the weights"""
1345
+ if isinstance(self, Kosmos2VisionModel):
1346
+ factor = self.config.initializer_factor
1347
+ elif isinstance(self, (Kosmos2Model, Kosmos2ForConditionalGeneration)):
1348
+ factor = self.config.vision_config.initializer_factor
1349
+
1350
+ if isinstance(self, (Kosmos2TextModel, Kosmos2TextForCausalLM)):
1351
+ std = self.config.init_std
1352
+ elif isinstance(self, (Kosmos2Model, Kosmos2ForConditionalGeneration)):
1353
+ std = self.config.text_config.init_std
1354
+
1355
+ if isinstance(module, Kosmos2VisionEmbeddings):
1356
+ nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
1357
+ nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
1358
+ nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
1359
+ elif isinstance(module, Kosmos2VisionAttention):
1360
+ in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
1361
+ out_proj_std = (module.embed_dim**-0.5) * factor
1362
+ nn.init.normal_(module.q_proj.weight, std=in_proj_std)
1363
+ nn.init.normal_(module.k_proj.weight, std=in_proj_std)
1364
+ nn.init.normal_(module.v_proj.weight, std=in_proj_std)
1365
+ nn.init.normal_(module.out_proj.weight, std=out_proj_std)
1366
+ if module.q_proj.bias is not None:
1367
+ module.q_proj.bias.data.zero_()
1368
+ if module.k_proj.bias is not None:
1369
+ module.k_proj.bias.data.zero_()
1370
+ if module.v_proj.bias is not None:
1371
+ module.v_proj.bias.data.zero_()
1372
+ if module.out_proj.bias is not None:
1373
+ module.out_proj.bias.data.zero_()
1374
+ elif isinstance(module, Kosmos2VisionMLP):
1375
+ in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
1376
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
1377
+ nn.init.normal_(module.fc1.weight, std=fc_std)
1378
+ nn.init.normal_(module.fc2.weight, std=in_proj_std)
1379
+ if module.fc1.bias is not None:
1380
+ module.fc1.bias.data.zero_()
1381
+ if module.fc2.bias is not None:
1382
+ module.fc2.bias.data.zero_()
1383
+ elif isinstance(module, Kosmos2VisionEncoderLayer):
1384
+ module.layer_norm1.bias.data.zero_()
1385
+ module.layer_norm1.weight.data.fill_(1.0)
1386
+ module.layer_norm2.bias.data.zero_()
1387
+ module.layer_norm2.weight.data.fill_(1.0)
1388
+ elif isinstance(module, Kosmos2VisionTransformer):
1389
+ module.pre_layrnorm.bias.data.zero_()
1390
+ module.pre_layrnorm.weight.data.fill_(1.0)
1391
+ module.post_layernorm.bias.data.zero_()
1392
+ module.post_layernorm.weight.data.fill_(1.0)
1393
+ elif isinstance(module, KosmosTextAttention):
1394
+ nn.init.normal_(module.q_proj.weight, std=std)
1395
+ nn.init.normal_(module.k_proj.weight, std=std)
1396
+ nn.init.normal_(module.v_proj.weight, std=std)
1397
+ nn.init.normal_(module.out_proj.weight, std=std)
1398
+ if module.q_proj.bias is not None:
1399
+ module.q_proj.bias.data.zero_()
1400
+ if module.k_proj.bias is not None:
1401
+ module.k_proj.bias.data.zero_()
1402
+ if module.v_proj.bias is not None:
1403
+ module.v_proj.bias.data.zero_()
1404
+ if module.out_proj.bias is not None:
1405
+ module.out_proj.bias.data.zero_()
1406
+ elif isinstance(module, Kosmos2TextFFN):
1407
+ nn.init.normal_(module.fc1.weight, std=std)
1408
+ nn.init.normal_(module.fc2.weight, std=std)
1409
+ if module.fc1.bias is not None:
1410
+ module.fc1.bias.data.zero_()
1411
+ if module.fc2.bias is not None:
1412
+ module.fc2.bias.data.zero_()
1413
+ elif isinstance(module, Kosmos2TextForCausalLM):
1414
+ nn.init.normal_(module.lm_head.weight, std=std)
1415
+ if module.lm_head.bias is not None:
1416
+ module.lm_head.bias.data.zero_()
1417
+ elif isinstance(module, Kosmos2ImageToTextProjection):
1418
+ nn.init.normal_(module.dense.weight, std=std)
1419
+ if module.dense.bias is not None:
1420
+ module.dense.bias.data.zero_()
1421
+ elif isinstance(module, Kosmos2TextTransformer):
1422
+ module.embed_tokens.weight.data.normal_(mean=0.0, std=std)
1423
+ if module.embed_tokens.padding_idx is not None:
1424
+ module.embed_tokens.weight.data[module.embed_tokens.padding_idx].zero_()
1425
+
1426
+
1427
+ class Kosmos2VisionModel(Kosmos2PreTrainedModel):
1428
+ config_class = Kosmos2VisionConfig
1429
+ main_input_name = "pixel_values"
1430
+
1431
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModel.__init__ with CLIP_VISION->KOSMOS2_VISION,CLIP->Kosmos2,self.vision_model->self.model
1432
+ def __init__(self, config: Kosmos2VisionConfig):
1433
+ super().__init__(config)
1434
+ self.model = Kosmos2VisionTransformer(config)
1435
+ # Initialize weights and apply final processing
1436
+ self.post_init()
1437
+
1438
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModel.get_input_embeddings with CLIP_VISION->KOSMOS2_VISION,CLIP->Kosmos2,self.vision_model->self.model
1439
+ def get_input_embeddings(self) -> nn.Module:
1440
+ return self.model.embeddings.patch_embedding
1441
+
1442
+ @add_start_docstrings_to_model_forward(KOSMOS2_VISION_INPUTS_DOCSTRING)
1443
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=Kosmos2VisionConfig)
1444
+ def forward(
1445
+ self,
1446
+ pixel_values: Optional[torch.FloatTensor] = None,
1447
+ output_attentions: Optional[bool] = None,
1448
+ output_hidden_states: Optional[bool] = None,
1449
+ return_dict: Optional[bool] = None,
1450
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1451
+ r"""
1452
+ Returns:
1453
+
1454
+ """
1455
+ return self.model(
1456
+ pixel_values=pixel_values,
1457
+ output_attentions=output_attentions,
1458
+ output_hidden_states=output_hidden_states,
1459
+ return_dict=return_dict,
1460
+ )
1461
+
1462
+
1463
+ class Kosmos2TextModel(Kosmos2PreTrainedModel):
1464
+ config_class = Kosmos2TextConfig
1465
+
1466
+ def __init__(self, config: Kosmos2TextConfig):
1467
+ super().__init__(config)
1468
+ self.model = Kosmos2TextTransformer(config)
1469
+ # Initialize weights and apply final processing
1470
+ self.post_init()
1471
+
1472
+ def get_input_embeddings(self) -> nn.Module:
1473
+ return self.model.embed_tokens
1474
+
1475
+ def set_input_embeddings(self, value):
1476
+ self.model.embed_tokens = value
1477
+
1478
+ @add_start_docstrings_to_model_forward(KOSMOS2_TEXT_INPUTS_DOCSTRING)
1479
+ @replace_return_docstrings(output_type=BaseModelOutputWithPastAndCrossAttentions, config_class=Kosmos2TextConfig)
1480
+ def forward(
1481
+ self,
1482
+ input_ids: Optional[torch.Tensor] = None,
1483
+ attention_mask: Optional[torch.Tensor] = None,
1484
+ image_embeds: Optional[torch.Tensor] = None,
1485
+ image_embeds_position_mask: Optional[torch.Tensor] = None,
1486
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1487
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1488
+ head_mask: Optional[torch.Tensor] = None,
1489
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1490
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1491
+ inputs_embeds: Optional[torch.Tensor] = None,
1492
+ position_ids: Optional[torch.Tensor] = None,
1493
+ use_cache: Optional[bool] = None,
1494
+ output_attentions: Optional[bool] = None,
1495
+ output_hidden_states: Optional[bool] = None,
1496
+ return_dict: Optional[bool] = None,
1497
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
1498
+ r"""
1499
+ Returns:
1500
+
1501
+ """
1502
+ return self.model(
1503
+ input_ids=input_ids,
1504
+ attention_mask=attention_mask,
1505
+ image_embeds=image_embeds,
1506
+ image_embeds_position_mask=image_embeds_position_mask,
1507
+ encoder_hidden_states=encoder_hidden_states,
1508
+ encoder_attention_mask=encoder_attention_mask,
1509
+ head_mask=head_mask,
1510
+ cross_attn_head_mask=cross_attn_head_mask,
1511
+ past_key_values=past_key_values,
1512
+ inputs_embeds=inputs_embeds,
1513
+ position_ids=position_ids,
1514
+ use_cache=use_cache,
1515
+ output_attentions=output_attentions,
1516
+ output_hidden_states=output_hidden_states,
1517
+ return_dict=return_dict,
1518
+ )
1519
+
1520
+
1521
+ @add_start_docstrings(
1522
+ """
1523
+ The text model from KOSMOS-2 with a language modeling head on top (linear layer with weights tied to the input
1524
+ embeddings).
1525
+ """,
1526
+ KOSMOS2_START_DOCSTRING,
1527
+ )
1528
+ class Kosmos2TextForCausalLM(Kosmos2PreTrainedModel):
1529
+ config_class = Kosmos2TextConfig
1530
+ _tied_weights_keys = ["lm_head.weight"]
1531
+
1532
+ def __init__(self, config: Kosmos2TextConfig):
1533
+ super().__init__(config)
1534
+
1535
+ self.model = Kosmos2TextTransformer(config)
1536
+ self.lm_head = nn.Linear(in_features=config.embed_dim, out_features=config.vocab_size, bias=False)
1537
+
1538
+ # Initialize weights and apply final processing
1539
+ self.post_init()
1540
+
1541
+ def get_input_embeddings(self) -> nn.Module:
1542
+ return self.model.embed_tokens
1543
+
1544
+ def set_input_embeddings(self, value):
1545
+ self.model.embed_tokens = value
1546
+
1547
+ def get_output_embeddings(self) -> nn.Module:
1548
+ return self.lm_head
1549
+
1550
+ def set_output_embeddings(self, new_embeddings):
1551
+ self.lm_head = new_embeddings
1552
+
1553
+ @add_start_docstrings_to_model_forward(KOSMOS2_TEXT_INPUTS_DOCSTRING)
1554
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=Kosmos2TextConfig)
1555
+ def forward(
1556
+ self,
1557
+ input_ids: Optional[torch.Tensor] = None,
1558
+ attention_mask: Optional[torch.Tensor] = None,
1559
+ image_embeds: Optional[torch.Tensor] = None,
1560
+ image_embeds_position_mask: Optional[torch.Tensor] = None,
1561
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1562
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1563
+ head_mask: Optional[torch.Tensor] = None,
1564
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1565
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1566
+ inputs_embeds: Optional[torch.Tensor] = None,
1567
+ position_ids: Optional[torch.Tensor] = None,
1568
+ labels: Optional[torch.LongTensor] = None,
1569
+ use_cache: Optional[bool] = None,
1570
+ output_attentions: Optional[bool] = None,
1571
+ output_hidden_states: Optional[bool] = None,
1572
+ return_dict: Optional[bool] = None,
1573
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1574
+ r"""
1575
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1576
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1577
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1578
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1579
+
1580
+ Returns:
1581
+
1582
+ """
1583
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1584
+
1585
+ if labels is not None:
1586
+ if use_cache:
1587
+ logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
1588
+ use_cache = False
1589
+
1590
+ outputs = self.model(
1591
+ input_ids=input_ids,
1592
+ attention_mask=attention_mask,
1593
+ image_embeds=image_embeds,
1594
+ image_embeds_position_mask=image_embeds_position_mask,
1595
+ encoder_hidden_states=encoder_hidden_states,
1596
+ encoder_attention_mask=encoder_attention_mask,
1597
+ head_mask=head_mask,
1598
+ cross_attn_head_mask=cross_attn_head_mask,
1599
+ past_key_values=past_key_values,
1600
+ inputs_embeds=inputs_embeds,
1601
+ position_ids=position_ids,
1602
+ use_cache=use_cache,
1603
+ output_attentions=output_attentions,
1604
+ output_hidden_states=output_hidden_states,
1605
+ return_dict=return_dict,
1606
+ )
1607
+ lm_logits = self.lm_head(outputs[0])
1608
+
1609
+ loss = None
1610
+ if labels is not None:
1611
+ # move labels to correct device to enable model parallelism
1612
+ labels = labels.to(lm_logits.device)
1613
+ # Shift so that tokens < n predict n
1614
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1615
+ shift_labels = labels[..., 1:].contiguous()
1616
+ batch_size, seq_length, vocab_size = shift_logits.shape
1617
+ # Flatten the tokens
1618
+ loss_fct = CrossEntropyLoss()
1619
+ loss = loss_fct(
1620
+ shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)
1621
+ )
1622
+
1623
+ if not return_dict:
1624
+ output = (lm_logits,) + outputs[1:]
1625
+ return (loss,) + output if loss is not None else output
1626
+
1627
+ return CausalLMOutputWithCrossAttentions(
1628
+ loss=loss,
1629
+ logits=lm_logits,
1630
+ past_key_values=outputs.past_key_values,
1631
+ hidden_states=outputs.hidden_states,
1632
+ attentions=outputs.attentions,
1633
+ cross_attentions=outputs.cross_attentions,
1634
+ )
1635
+
1636
+ def prepare_inputs_for_generation(
1637
+ self,
1638
+ input_ids,
1639
+ image_embeds=None,
1640
+ image_embeds_position_mask=None,
1641
+ past_key_values=None,
1642
+ attention_mask=None,
1643
+ use_cache=None,
1644
+ **model_kwargs,
1645
+ ):
1646
+ input_shape = input_ids.shape
1647
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1648
+ if attention_mask is None:
1649
+ attention_mask = input_ids.new_ones(input_shape)
1650
+
1651
+ position_ids = None
1652
+
1653
+ # cut input_ids if past_key_values is used
1654
+ if past_key_values is not None:
1655
+ position_ids = create_position_ids_from_input_ids(
1656
+ input_ids,
1657
+ padding_idx=self.config.pad_token_id,
1658
+ past_key_values_length=0,
1659
+ )[:, -1:]
1660
+
1661
+ input_ids = input_ids[:, -1:]
1662
+ # the image info. is already encoded into the past keys/values
1663
+ image_embeds = None
1664
+ image_embeds_position_mask = None
1665
+ elif image_embeds_position_mask is not None:
1666
+ # appending `False` to `image_embeds_position_mask` (because `input_ids` grows during generation)
1667
+ batch_size, seq_len = input_ids.size()
1668
+ mask_len = image_embeds_position_mask.size()[-1]
1669
+ image_embeds_position_mask = torch.cat(
1670
+ (
1671
+ image_embeds_position_mask,
1672
+ torch.zeros(size=(batch_size, seq_len - mask_len), dtype=torch.bool, device=input_ids.device),
1673
+ ),
1674
+ dim=1,
1675
+ )
1676
+
1677
+ return {
1678
+ "input_ids": input_ids,
1679
+ "image_embeds": image_embeds,
1680
+ "image_embeds_position_mask": image_embeds_position_mask,
1681
+ "past_key_values": past_key_values,
1682
+ "attention_mask": attention_mask,
1683
+ "position_ids": position_ids,
1684
+ "use_cache": use_cache,
1685
+ }
1686
+
1687
+ @staticmethod
1688
+ # Copied from transformers.models.umt5.modeling_umt5.UMT5ForConditionalGeneration._reorder_cache
1689
+ def _reorder_cache(past_key_values, beam_idx):
1690
+ reordered_past = ()
1691
+ for layer_past in past_key_values:
1692
+ reordered_past += (
1693
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1694
+ )
1695
+ return reordered_past
1696
+
1697
+
1698
+ class Kosmos2ImageToTextProjection(nn.Module):
1699
+ """The layer that transforms the image model's output to part of the text model's input (namely, image features)"""
1700
+
1701
+ def __init__(self, config: Kosmos2Config):
1702
+ super().__init__()
1703
+ self.dense = nn.Linear(config.vision_config.hidden_size, config.text_config.embed_dim)
1704
+ self.latent_query = nn.Parameter(torch.randn(config.latent_query_num, config.text_config.embed_dim))
1705
+
1706
+ self.x_attn = KosmosTextAttention(
1707
+ config.text_config,
1708
+ config.text_config.embed_dim,
1709
+ config.text_config.attention_heads,
1710
+ dropout=config.text_config.attention_dropout,
1711
+ is_decoder=False,
1712
+ add_inner_attn_layernorm=False,
1713
+ )
1714
+
1715
+ def forward(self, features):
1716
+ hidden_states = self.dense(features)
1717
+
1718
+ # shape = [batch, latent_query_num, h_dim]
1719
+ latent_query = self.latent_query.unsqueeze(0).expand(hidden_states.size(0), -1, -1)
1720
+ key_value_states = torch.cat([hidden_states, latent_query], dim=1)
1721
+
1722
+ hidden_states, attn_weights, _ = self.x_attn(
1723
+ hidden_states=latent_query,
1724
+ encoder_hidden_states=key_value_states,
1725
+ past_key_value=None,
1726
+ attention_mask=None,
1727
+ output_attentions=None,
1728
+ )
1729
+
1730
+ return hidden_states, attn_weights
1731
+
1732
+
1733
+ @add_start_docstrings(
1734
+ """
1735
+ KOSMOS-2 Model for generating text and image features. The model consists of a vision encoder and a language model.
1736
+ """,
1737
+ KOSMOS2_START_DOCSTRING,
1738
+ )
1739
+ class Kosmos2Model(Kosmos2PreTrainedModel):
1740
+ config_class = Kosmos2Config
1741
+ main_input_name = "pixel_values"
1742
+
1743
+ def __init__(self, config: Kosmos2Config):
1744
+ super().__init__(config)
1745
+
1746
+ self.text_model = Kosmos2TextModel(config.text_config)
1747
+ self.vision_model = Kosmos2VisionModel(config.vision_config)
1748
+ self.image_to_text_projection = Kosmos2ImageToTextProjection(config)
1749
+
1750
+ # Initialize weights and apply final processing
1751
+ self.post_init()
1752
+
1753
+ def get_input_embeddings(self) -> nn.Module:
1754
+ return self.text_model.model.embed_tokens
1755
+
1756
+ def set_input_embeddings(self, value):
1757
+ self.text_model.model.embed_tokens = value
1758
+
1759
+ @add_start_docstrings_to_model_forward(KOSMOS2_INPUTS_DOCSTRING)
1760
+ @replace_return_docstrings(output_type=Kosmos2ModelOutput, config_class=_CONFIG_FOR_DOC)
1761
+ def forward(
1762
+ self,
1763
+ pixel_values: Optional[torch.Tensor] = None,
1764
+ input_ids: Optional[torch.Tensor] = None,
1765
+ image_embeds_position_mask: Optional[torch.Tensor] = None,
1766
+ attention_mask: Optional[torch.Tensor] = None,
1767
+ head_mask: Optional[torch.Tensor] = None,
1768
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1769
+ image_embeds: Optional[torch.Tensor] = None,
1770
+ inputs_embeds: Optional[torch.Tensor] = None,
1771
+ position_ids: Optional[torch.Tensor] = None,
1772
+ use_cache: Optional[bool] = None,
1773
+ output_attentions: Optional[bool] = None,
1774
+ output_hidden_states: Optional[bool] = None,
1775
+ return_dict: Optional[bool] = None,
1776
+ ) -> Union[Tuple, Kosmos2ModelOutput]:
1777
+ r"""
1778
+ Returns:
1779
+
1780
+ Examples:
1781
+
1782
+ ```python
1783
+ >>> from PIL import Image
1784
+ >>> import requests
1785
+ >>> from transformers import AutoProcessor, Kosmos2Model
1786
+
1787
+ >>> model = Kosmos2Model.from_pretrained("microsoft/kosmos-2-patch14-224")
1788
+ >>> processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224")
1789
+
1790
+ >>> url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
1791
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1792
+
1793
+ >>> text = (
1794
+ ... "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863>"
1795
+ ... "</object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911>"
1796
+ ... "</object>"
1797
+ ... )
1798
+
1799
+ >>> inputs = processor(text=text, images=image, return_tensors="pt", add_eos_token=True)
1800
+
1801
+ >>> last_hidden_state = model(
1802
+ ... pixel_values=inputs["pixel_values"],
1803
+ ... input_ids=inputs["input_ids"],
1804
+ ... attention_mask=inputs["attention_mask"],
1805
+ ... image_embeds_position_mask=inputs["image_embeds_position_mask"],
1806
+ ... ).last_hidden_state
1807
+ >>> list(last_hidden_state.shape)
1808
+ [1, 91, 2048]
1809
+ ```"""
1810
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1811
+ output_hidden_states = (
1812
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1813
+ )
1814
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1815
+
1816
+ vision_model_output = None
1817
+ projection_attentions = None
1818
+ if image_embeds is None:
1819
+ if pixel_values is None:
1820
+ raise ValueError("You have to specify either `pixel_values` or `image_embeds`.")
1821
+
1822
+ vision_model_output = self.vision_model(
1823
+ pixel_values=pixel_values,
1824
+ output_attentions=output_attentions,
1825
+ output_hidden_states=output_hidden_states,
1826
+ return_dict=return_dict,
1827
+ )
1828
+ # The whole `last_hidden_state` through `post_layernorm` instead of just `pooled_output`.
1829
+ image_embeds = self.vision_model.model.post_layernorm(vision_model_output[0])
1830
+ # normalized features
1831
+ image_embeds = nn.functional.normalize(image_embeds, dim=-1)
1832
+ image_embeds, projection_attentions = self.image_to_text_projection(image_embeds)
1833
+
1834
+ outputs = self.text_model(
1835
+ input_ids=input_ids,
1836
+ attention_mask=attention_mask,
1837
+ image_embeds=image_embeds,
1838
+ image_embeds_position_mask=image_embeds_position_mask,
1839
+ head_mask=head_mask,
1840
+ past_key_values=past_key_values,
1841
+ inputs_embeds=inputs_embeds,
1842
+ position_ids=position_ids,
1843
+ use_cache=use_cache,
1844
+ output_attentions=output_attentions,
1845
+ output_hidden_states=output_hidden_states,
1846
+ return_dict=return_dict,
1847
+ )
1848
+
1849
+ if not return_dict:
1850
+ outputs = outputs + (image_embeds, projection_attentions, vision_model_output)
1851
+ return tuple(output for output in outputs if output is not None)
1852
+
1853
+ return Kosmos2ModelOutput(
1854
+ last_hidden_state=outputs.last_hidden_state,
1855
+ past_key_values=outputs.past_key_values,
1856
+ hidden_states=outputs.hidden_states,
1857
+ attentions=outputs.attentions,
1858
+ image_embeds=image_embeds,
1859
+ projection_attentions=projection_attentions,
1860
+ vision_model_output=vision_model_output,
1861
+ )
1862
+
1863
+
1864
+ @add_start_docstrings(
1865
+ """
1866
+ KOSMOS-2 Model for generating text and bounding boxes given an image. The model consists of a vision encoder and a
1867
+ language model.
1868
+ """,
1869
+ KOSMOS2_START_DOCSTRING,
1870
+ )
1871
+ class Kosmos2ForConditionalGeneration(Kosmos2PreTrainedModel):
1872
+ config_class = Kosmos2Config
1873
+ main_input_name = "pixel_values"
1874
+ _tied_weights_keys = ["text_model.lm_head.weight"]
1875
+
1876
+ def __init__(self, config: Kosmos2Config):
1877
+ super().__init__(config)
1878
+
1879
+ self.text_model = Kosmos2TextForCausalLM(config.text_config)
1880
+ self.vision_model = Kosmos2VisionModel(config.vision_config)
1881
+
1882
+ self.image_to_text_projection = Kosmos2ImageToTextProjection(config)
1883
+
1884
+ # Initialize weights and apply final processing
1885
+ self.post_init()
1886
+
1887
+ def get_input_embeddings(self) -> nn.Module:
1888
+ return self.text_model.model.embed_tokens
1889
+
1890
+ def set_input_embeddings(self, value):
1891
+ self.text_model.model.embed_tokens = value
1892
+
1893
+ def get_output_embeddings(self) -> nn.Module:
1894
+ return self.text_model.get_output_embeddings()
1895
+
1896
+ def set_output_embeddings(self, new_embeddings):
1897
+ self.text_model.set_output_embeddings(new_embeddings)
1898
+
1899
+ @add_start_docstrings_to_model_forward(KOSMOS2_INPUTS_DOCSTRING)
1900
+ @replace_return_docstrings(output_type=Kosmos2ForConditionalGenerationModelOutput, config_class=_CONFIG_FOR_DOC)
1901
+ def forward(
1902
+ self,
1903
+ pixel_values: Optional[torch.Tensor] = None,
1904
+ input_ids: Optional[torch.Tensor] = None,
1905
+ image_embeds_position_mask: Optional[torch.Tensor] = None,
1906
+ attention_mask: Optional[torch.Tensor] = None,
1907
+ head_mask: Optional[torch.Tensor] = None,
1908
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1909
+ image_embeds: Optional[torch.Tensor] = None,
1910
+ inputs_embeds: Optional[torch.Tensor] = None,
1911
+ position_ids: Optional[torch.Tensor] = None,
1912
+ labels: Optional[torch.LongTensor] = None,
1913
+ use_cache: Optional[bool] = None,
1914
+ output_attentions: Optional[bool] = None,
1915
+ output_hidden_states: Optional[bool] = None,
1916
+ return_dict: Optional[bool] = None,
1917
+ ) -> Union[Tuple, Kosmos2ForConditionalGenerationModelOutput]:
1918
+ r"""
1919
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1920
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1921
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1922
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1923
+
1924
+ Returns:
1925
+
1926
+ Examples:
1927
+
1928
+ ```python
1929
+ >>> from PIL import Image
1930
+ >>> import requests
1931
+ >>> from transformers import AutoProcessor, Kosmos2ForConditionalGeneration
1932
+
1933
+ >>> model = Kosmos2ForConditionalGeneration.from_pretrained("microsoft/kosmos-2-patch14-224")
1934
+ >>> processor = AutoProcessor.from_pretrained("microsoft/kosmos-2-patch14-224")
1935
+
1936
+ >>> url = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
1937
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1938
+
1939
+ >>> prompt = "<grounding> An image of"
1940
+
1941
+ >>> inputs = processor(text=prompt, images=image, return_tensors="pt")
1942
+
1943
+ >>> generated_ids = model.generate(
1944
+ ... pixel_values=inputs["pixel_values"],
1945
+ ... input_ids=inputs["input_ids"],
1946
+ ... attention_mask=inputs["attention_mask"],
1947
+ ... image_embeds=None,
1948
+ ... image_embeds_position_mask=inputs["image_embeds_position_mask"],
1949
+ ... use_cache=True,
1950
+ ... max_new_tokens=64,
1951
+ ... )
1952
+ >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
1953
+ >>> processed_text = processor.post_process_generation(generated_text, cleanup_and_extract=False)
1954
+ >>> processed_text
1955
+ '<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>.'
1956
+
1957
+ >>> caption, entities = processor.post_process_generation(generated_text)
1958
+ >>> caption
1959
+ 'An image of a snowman warming himself by a fire.'
1960
+
1961
+ >>> entities
1962
+ [('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]
1963
+ ```"""
1964
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1965
+ output_hidden_states = (
1966
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1967
+ )
1968
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1969
+
1970
+ vision_model_output = None
1971
+ projection_attentions = None
1972
+ if image_embeds is None:
1973
+ if pixel_values is None:
1974
+ raise ValueError("You have to specify either `pixel_values` or `image_embeds`.")
1975
+
1976
+ vision_model_output = self.vision_model(
1977
+ pixel_values=pixel_values,
1978
+ output_attentions=output_attentions,
1979
+ output_hidden_states=output_hidden_states,
1980
+ return_dict=return_dict,
1981
+ )
1982
+ # The whole `last_hidden_state` through `post_layernorm` instead of just `pooled_output`.
1983
+ image_embeds = self.vision_model.model.post_layernorm(vision_model_output[0])
1984
+ # normalized features
1985
+ image_embeds = nn.functional.normalize(image_embeds, dim=-1)
1986
+ image_embeds, projection_attentions = self.image_to_text_projection(image_embeds)
1987
+
1988
+ lm_outputs = self.text_model(
1989
+ input_ids=input_ids,
1990
+ attention_mask=attention_mask,
1991
+ image_embeds=image_embeds,
1992
+ image_embeds_position_mask=image_embeds_position_mask,
1993
+ head_mask=head_mask,
1994
+ past_key_values=past_key_values,
1995
+ inputs_embeds=inputs_embeds,
1996
+ position_ids=position_ids,
1997
+ labels=labels,
1998
+ use_cache=use_cache,
1999
+ output_attentions=output_attentions,
2000
+ output_hidden_states=output_hidden_states,
2001
+ return_dict=return_dict,
2002
+ )
2003
+
2004
+ if not return_dict:
2005
+ outputs = lm_outputs + (image_embeds, projection_attentions, vision_model_output)
2006
+ return tuple(output for output in outputs if output is not None)
2007
+
2008
+ return Kosmos2ForConditionalGenerationModelOutput(
2009
+ loss=lm_outputs.loss,
2010
+ logits=lm_outputs.logits,
2011
+ past_key_values=lm_outputs.past_key_values,
2012
+ hidden_states=lm_outputs.hidden_states,
2013
+ attentions=lm_outputs.attentions,
2014
+ image_embeds=image_embeds,
2015
+ projection_attentions=projection_attentions,
2016
+ vision_model_output=vision_model_output,
2017
+ )
2018
+
2019
+ def generate(
2020
+ self,
2021
+ pixel_values: Optional[torch.Tensor] = None,
2022
+ image_embeds_position_mask: Optional[torch.Tensor] = None,
2023
+ input_ids: Optional[torch.Tensor] = None,
2024
+ attention_mask: Optional[torch.Tensor] = None,
2025
+ image_embeds: Optional[torch.Tensor] = None,
2026
+ **kwargs,
2027
+ ):
2028
+ # in order to allow `inputs` argument (as in `GenerationMixin`)
2029
+ inputs = kwargs.pop("inputs", None)
2030
+ if pixel_values is not None and inputs is not None:
2031
+ raise ValueError(
2032
+ f"`inputs`: {inputs} were passed alongside `pixel_values` which is not allowed."
2033
+ f"Make sure to either pass `inputs` or pixel_values=..."
2034
+ )
2035
+ if pixel_values is None and inputs is not None:
2036
+ pixel_values = inputs
2037
+
2038
+ if image_embeds is None:
2039
+ vision_model_output = self.vision_model(pixel_values)
2040
+ # The whole `last_hidden_state` through `post_layernorm` instead of just `pooled_output`.
2041
+ image_embeds = self.vision_model.model.post_layernorm(vision_model_output[0])
2042
+ # normalized features
2043
+ image_embeds = nn.functional.normalize(image_embeds, dim=-1)
2044
+ image_embeds, projection_attentions = self.image_to_text_projection(image_embeds)
2045
+
2046
+ output = self.text_model.generate(
2047
+ input_ids=input_ids,
2048
+ attention_mask=attention_mask,
2049
+ image_embeds=image_embeds,
2050
+ image_embeds_position_mask=image_embeds_position_mask,
2051
+ **kwargs,
2052
+ )
2053
+
2054
+ return output
videochat2/lib/python3.10/site-packages/transformers/models/kosmos2/processing_kosmos2.py ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Processor class for KOSMOS-2."""
16
+
17
+ import copy
18
+ import math
19
+ import re
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ from ...image_processing_utils import BatchFeature
23
+ from ...image_utils import ImageInput, is_batched
24
+ from ...processing_utils import ProcessorMixin
25
+ from ...tokenization_utils import AddedToken
26
+ from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, TextInput, TruncationStrategy
27
+ from ...utils import TensorType
28
+
29
+
30
+ BboxInput = Union[
31
+ List[Tuple[int, int]],
32
+ List[Tuple[float, float, float, float]],
33
+ List[List[Tuple[int, int]]],
34
+ List[List[Tuple[float, float, float]]],
35
+ ]
36
+
37
+
38
+ class Kosmos2Processor(ProcessorMixin):
39
+ r"""
40
+ Constructs an KOSMOS-2 processor which wraps a KOSMOS-2 image processor and a KOSMOS-2 tokenizer into a single
41
+ processor.
42
+
43
+ [`Kosmos2Processor`] offers all the functionalities of [`CLIPImageProcessor`] and some functionalities of
44
+ [`XLMRobertaTokenizerFast`]. See the docstring of [`~Kosmos2Processor.__call__`] and [`~Kosmos2Processor.decode`]
45
+ for more information.
46
+
47
+ Args:
48
+ image_processor (`CLIPImageProcessor`):
49
+ An instance of [`CLIPImageProcessor`]. The image processor is a required input.
50
+ tokenizer (`XLMRobertaTokenizerFast`):
51
+ An instance of ['XLMRobertaTokenizerFast`]. The tokenizer is a required input.
52
+ num_patch_index_tokens (`int`, *optional*, defaults to 1024):
53
+ The number of tokens that represent patch indices.
54
+ """
55
+
56
+ attributes = ["image_processor", "tokenizer"]
57
+ image_processor_class = "CLIPImageProcessor"
58
+ tokenizer_class = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")
59
+
60
+ def __init__(self, image_processor, tokenizer, num_patch_index_tokens=1024):
61
+ tokenizer.return_token_type_ids = False
62
+
63
+ self.eod_token = "</doc>"
64
+
65
+ self.boi_token = "<image>"
66
+ self.eoi_token = "</image>"
67
+
68
+ self.eoc_token = "</chunk>"
69
+ self.eol_token = "</line>"
70
+
71
+ self.bop_token = "<phrase>"
72
+ self.eop_token = "</phrase>"
73
+
74
+ self.boo_token = "<object>"
75
+ self.eoo_token = "</object>"
76
+
77
+ self.dom_token = "</delimiter_of_multi_objects/>"
78
+
79
+ self.grd_token = "<grounding>"
80
+
81
+ self.tag_tokens = [
82
+ self.eod_token,
83
+ self.boi_token,
84
+ self.eoi_token,
85
+ self.eoc_token,
86
+ self.eol_token,
87
+ self.bop_token,
88
+ self.eop_token,
89
+ self.boo_token,
90
+ self.eoo_token,
91
+ self.dom_token,
92
+ self.grd_token,
93
+ ]
94
+
95
+ self.num_patch_index_tokens = num_patch_index_tokens
96
+ patch_index_tokens = [f"<patch_index_{str(x).zfill(4)}>" for x in range(self.num_patch_index_tokens)]
97
+
98
+ tokens_to_add = []
99
+ for token in self.tag_tokens + patch_index_tokens:
100
+ tokens_to_add.append(AddedToken(token, lstrip=True, rstrip=False, normalized=False))
101
+ tokenizer.add_tokens(tokens_to_add)
102
+
103
+ super().__init__(image_processor, tokenizer)
104
+
105
+ def __call__(
106
+ self,
107
+ images: ImageInput = None,
108
+ text: Union[TextInput, List[TextInput]] = None,
109
+ bboxes: BboxInput = None,
110
+ num_image_tokens: Optional[int] = 64,
111
+ first_image_token_id: Optional[int] = None,
112
+ add_special_tokens: bool = True,
113
+ add_eos_token: bool = False,
114
+ padding: Union[bool, str, PaddingStrategy] = False,
115
+ truncation: Union[bool, str, TruncationStrategy] = None,
116
+ max_length: Optional[int] = None,
117
+ pad_to_multiple_of: Optional[int] = None,
118
+ return_attention_mask: Optional[bool] = None,
119
+ return_length: bool = False,
120
+ verbose: bool = True,
121
+ return_tensors: Optional[Union[str, TensorType]] = None,
122
+ **kwargs,
123
+ ) -> BatchFeature:
124
+ """
125
+ This method uses [`CLIPImageProcessor.__call__`] method to prepare image(s) for the model, and
126
+ [`XLMRobertaTokenizerFast.__call__`] to prepare text for the model.
127
+
128
+ Please refer to the docstring of the above two methods for more information.
129
+
130
+ The rest of this documentation shows the arguments specific to `Kosmos2Processor`.
131
+
132
+ Args:
133
+ bboxes (`Union[List[Tuple[int]], List[Tuple[float]], List[List[Tuple[int]]], List[List[Tuple[float]]]]`, *optional*):
134
+ The bounding bboxes associated to `texts`.
135
+ num_image_tokens (`int`, defaults to 64):
136
+ The number of (consecutive) places that are used to mark the placeholders to store image information.
137
+ This should be the same as `latent_query_num` in the instance of `Kosmos2Config` you are using.
138
+ first_image_token_id (`int`, *optional*):
139
+ The token id that will be used for the first place of the subsequence that is reserved to store image
140
+ information. If unset, will default to `self.tokenizer.unk_token_id + 1`.
141
+ add_eos_token (`bool`, defaults to `False`):
142
+ Whether or not to include `EOS` token id in the encoding when `add_special_tokens=True`.
143
+ """
144
+ if images is None and text is None:
145
+ raise ValueError("You have to specify either images or text.")
146
+
147
+ encoding = BatchFeature()
148
+
149
+ if images is not None:
150
+ image_encoding = self.image_processor(images, return_tensors=return_tensors)
151
+ encoding.update(image_encoding)
152
+
153
+ if text is not None:
154
+ text = self.preprocess_examples(text, images, bboxes, num_image_tokens=num_image_tokens)
155
+
156
+ if add_special_tokens and not add_eos_token:
157
+ if isinstance(text, str):
158
+ text = f"{self.tokenizer.bos_token}{text}"
159
+ elif isinstance(text, list):
160
+ text = [f"{self.tokenizer.bos_token}{s}" for s in text]
161
+
162
+ text_encoding = self.tokenizer(
163
+ text=text,
164
+ add_special_tokens=(add_special_tokens and add_eos_token),
165
+ padding=padding and images is None,
166
+ truncation=truncation,
167
+ max_length=max_length,
168
+ pad_to_multiple_of=pad_to_multiple_of if images is None else pad_to_multiple_of,
169
+ return_attention_mask=return_attention_mask,
170
+ verbose=verbose,
171
+ return_tensors=return_tensors if images is None else None,
172
+ **kwargs,
173
+ )
174
+ encoding.update(text_encoding)
175
+
176
+ if text is not None and images is not None:
177
+ # Use the id of the first token after <unk>
178
+ if first_image_token_id is None:
179
+ first_image_token_id = self.tokenizer.unk_token_id + 1
180
+
181
+ # To see if we need one more `0` (for `<s>`) at the beginning of `image_embeds_position_mask`.
182
+ with_bos = add_special_tokens
183
+
184
+ # The first (actual) `<image>` token is always at the 1st or 2nd place (after `<s>` if any). Here we look
185
+ # for the second `<image>` token (which indicate the first image token).
186
+ start_index = int(with_bos) + 1
187
+
188
+ # Add `image_embeds_position_mask`: the leading and trailing `0` are for `boi` and `eoi` tokens. The `1` indicates
189
+ # the places of image tokens.
190
+ image_token_ids = list(range(first_image_token_id, first_image_token_id + num_image_tokens))
191
+ base_image_embeds_position_mask = [0] + [1] * num_image_tokens + [0]
192
+
193
+ # loop over `encoding["input_ids"]`
194
+ input_ids = []
195
+ image_embeds_position_mask = []
196
+ all_input_ids = encoding["input_ids"]
197
+ # not batched -> (changed to) batch of size 1
198
+ if isinstance(text, str):
199
+ all_input_ids = [all_input_ids]
200
+ encoding["attention_mask"] = [encoding["attention_mask"]]
201
+ for text_ids in all_input_ids:
202
+ # change the ids for the fake `<image>` tokens in `input_ids`
203
+ text_ids = text_ids[:start_index] + image_token_ids + text_ids[start_index + num_image_tokens :]
204
+ input_ids.append(text_ids)
205
+
206
+ mask = copy.copy(base_image_embeds_position_mask)
207
+ if with_bos:
208
+ # for `<s>`
209
+ mask = [0] + mask
210
+ # trailing part (which are not related to the image)
211
+ mask += [0] * (len(text_ids) - len(mask))
212
+ image_embeds_position_mask.append(mask)
213
+
214
+ if isinstance(text, list):
215
+ sorted_length = sorted(
216
+ [(idx, len(x)) for idx, x in enumerate(text_encoding.input_ids)], key=lambda x: x[-1]
217
+ )
218
+ _, min_len_not_padded = sorted_length[0]
219
+ idx, _ = sorted_length[-1]
220
+
221
+ text_encoding = self.tokenizer(
222
+ text=[text[idx]],
223
+ add_special_tokens=(add_special_tokens and add_eos_token),
224
+ padding=padding,
225
+ truncation=truncation,
226
+ max_length=max_length,
227
+ pad_to_multiple_of=pad_to_multiple_of,
228
+ verbose=verbose,
229
+ return_tensors=None,
230
+ **kwargs,
231
+ )
232
+ max_len_padded = len(text_encoding.input_ids[0])
233
+
234
+ if min_len_not_padded != max_len_padded:
235
+ if self.tokenizer.padding_side == "right":
236
+ input_ids = [x + [self.tokenizer.pad_token_id] * (max_len_padded - len(x)) for x in input_ids]
237
+ image_embeds_position_mask = [
238
+ x + [0] * (max_len_padded - len(x)) for x in image_embeds_position_mask
239
+ ]
240
+ encoding["attention_mask"] = [
241
+ x + [0] * (max_len_padded - len(x)) for x in encoding["attention_mask"]
242
+ ]
243
+ elif self.tokenizer.padding_side == "left":
244
+ input_ids = [[self.tokenizer.pad_token_id] * (max_len_padded - len(x)) + x for x in input_ids]
245
+ image_embeds_position_mask = [
246
+ [0] * (max_len_padded - len(x)) + x for x in image_embeds_position_mask
247
+ ]
248
+ encoding["attention_mask"] = [
249
+ [0] * (max_len_padded - len(x)) + x for x in encoding["attention_mask"]
250
+ ]
251
+
252
+ # un-batch if necessary
253
+ if isinstance(text, str) and return_tensors is None:
254
+ input_ids = input_ids[0]
255
+ encoding["attention_mask"] = encoding["attention_mask"][0]
256
+ image_embeds_position_mask = image_embeds_position_mask[0]
257
+
258
+ # update (with the target tensor type if specified)
259
+ encoding.update(
260
+ BatchEncoding(
261
+ data={
262
+ "input_ids": input_ids,
263
+ "attention_mask": encoding["attention_mask"],
264
+ "image_embeds_position_mask": image_embeds_position_mask,
265
+ },
266
+ tensor_type=return_tensors,
267
+ )
268
+ )
269
+
270
+ return encoding
271
+
272
+ def _check_bboxes_for_single_text(self, bboxes):
273
+ """
274
+ Check `bboxes` for a single text example. It could be
275
+ - `None`: no bounding box associated to a text.
276
+ - A list with each element being the bounding boxes associated to one `<phrase> ... </phrase>` pair found
277
+ in a text. This could be:
278
+ - `None`: no bounding box associated to a `<phrase> ... </phrase>` pair.
279
+ - A tuple of 2 integers: A single bounding box specified by patch indices.
280
+ - A tuple of 4 float point number: A single bounding box specified by (normalized) coordinates.
281
+ - A list containing the above 2 tuple types: Multiple bounding boxes for a
282
+ `<phrase> ... </phrase>` pair.
283
+ """
284
+ if bboxes is None:
285
+ return
286
+ elif not isinstance(bboxes, list):
287
+ raise ValueError("`bboxes` (for a single text example) should be `None` or a list.")
288
+
289
+ # `bbox` is the bounding boxes for a single <phrase> </phrase> pair
290
+ for bbox in bboxes:
291
+ if bbox is None:
292
+ continue
293
+ elif not isinstance(bbox, list):
294
+ bbox = [bbox]
295
+ for element in bbox:
296
+ if not isinstance(element, tuple) or not (
297
+ (len(element) == 2 and all(isinstance(x, int) for x in element))
298
+ or (len(element) == 4 and all(isinstance(x, float) for x in element))
299
+ ):
300
+ raise ValueError(
301
+ "Each element in `bboxes` (for a single text example) should be either `None`, a tuple containing "
302
+ "2 integers or 4 float point numbers, or a list containing such tuples. Also "
303
+ "make sure the arguments `texts` and `bboxes` passed to `preprocess_text` are both in "
304
+ "batches or both for a single example."
305
+ )
306
+
307
+ def _preprocess_single_example(self, text, image, bboxes, img_info_tokens):
308
+ text = text.strip()
309
+ if image is not None:
310
+ # Add `<image> ... (fake) image tokens ... </image>`
311
+ text = f"{img_info_tokens} {text}"
312
+
313
+ # Add `<object> <patch_idx_xxxx> <patch_idx_yyy> </object>` after `<phrase> phrase text </phrase>`
314
+ text = self._insert_patch_index_tokens(text, bboxes)
315
+ return text
316
+
317
+ def preprocess_examples(
318
+ self,
319
+ texts: Union[TextInput, List[TextInput]],
320
+ images: ImageInput = None,
321
+ bboxes: BboxInput = None,
322
+ num_image_tokens: Optional[int] = 64,
323
+ ) -> Union[str, List[str]]:
324
+ """Add image and bounding box information to `texts` as image and patch index tokens.
325
+
326
+ Args:
327
+ texts (`Union[TextInput, List[TextInput]]`): The texts to be processed.
328
+ images (`ImageInput`, *optional*): The images associated to `texts`.
329
+ bboxes (`Union[List[Tuple[int]], List[Tuple[float]], List[List[Tuple[int]]], List[List[Tuple[float]]]]`, *optional*):
330
+ The bounding bboxes associated to `texts`.
331
+ num_image_tokens (`int`, *optional*, defaults to 64):
332
+ The number of image tokens (used as latent queries). This should corresponds to the `latent_query_num`
333
+ attribute in `Kosmos2Config`.
334
+
335
+ Returns:
336
+ `Union[TextInput, List[TextInput]]`: The processed texts with image and patch index tokens.
337
+ """
338
+ # These are fake `<image>` tokens enclosed between (the actual) `<image>` token and `</image>`.
339
+ img_tokens = [self.boi_token] * num_image_tokens
340
+ img_info_tokens = " ".join([self.boi_token] + img_tokens + [self.eoi_token])
341
+
342
+ # make batch to simplify processing logic
343
+ batched = True
344
+ if isinstance(texts, str):
345
+ batched = False
346
+ texts = [texts]
347
+
348
+ if images is None:
349
+ images = [None] * len(texts)
350
+ elif not is_batched(images):
351
+ images = [images]
352
+ if len(texts) != len(images):
353
+ raise ValueError(
354
+ f"The number of examples in `texts` and `images` should be the same. Got {len(texts)} v.s. {len(images)} instead."
355
+ )
356
+
357
+ if not batched:
358
+ self._check_bboxes_for_single_text(bboxes)
359
+ bboxes = [bboxes]
360
+ elif bboxes is not None:
361
+ if not isinstance(bboxes, list):
362
+ raise ValueError("`bboxes` should be `None` or a list (as a batch) when `texts` is passed as a batch.")
363
+ for x in bboxes:
364
+ self._check_bboxes_for_single_text(x)
365
+ else:
366
+ bboxes = [None] * len(texts)
367
+
368
+ if len(bboxes) != len(texts):
369
+ raise ValueError(
370
+ f"The number of examples in `texts` and `bboxes` should be the same. Got {len(texts)} v.s. {len(bboxes)} instead."
371
+ )
372
+
373
+ result = [
374
+ self._preprocess_single_example(text, image, bbox, img_info_tokens)
375
+ for text, image, bbox in zip(texts, images, bboxes)
376
+ ]
377
+ # un-batch if necessary
378
+ if not batched:
379
+ result = result[0]
380
+
381
+ return result
382
+
383
+ # Copied from transformers.models.blip.processing_blip.BlipProcessor.batch_decode with BertTokenizerFast->PreTrainedTokenizer
384
+ def batch_decode(self, *args, **kwargs):
385
+ """
386
+ This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
387
+ refer to the docstring of this method for more information.
388
+ """
389
+ return self.tokenizer.batch_decode(*args, **kwargs)
390
+
391
+ # Copied from transformers.models.blip.processing_blip.BlipProcessor.decode with BertTokenizerFast->PreTrainedTokenizer
392
+ def decode(self, *args, **kwargs):
393
+ """
394
+ This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
395
+ the docstring of this method for more information.
396
+ """
397
+ return self.tokenizer.decode(*args, **kwargs)
398
+
399
+ def post_process_generation(self, text, cleanup_and_extract=True):
400
+ caption = text.split(self.eoi_token)[-1]
401
+ if cleanup_and_extract:
402
+ return clean_text_and_extract_entities_with_bboxes(caption)
403
+ return caption
404
+
405
+ @property
406
+ # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
407
+ def model_input_names(self):
408
+ tokenizer_input_names = self.tokenizer.model_input_names
409
+ image_processor_input_names = self.image_processor.model_input_names
410
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
411
+
412
+ def _insert_patch_index_tokens(self, text: str, bboxes: Union[List[Tuple[int]], List[Tuple[float]]]) -> str:
413
+ if bboxes is None or len(bboxes) == 0:
414
+ return text
415
+
416
+ matched_phrases = list(re.finditer(r"<phrase>.+?</phrase>", string=text))
417
+ if len(matched_phrases) != len(bboxes):
418
+ raise ValueError(
419
+ f"The number of elements in `bboxes` should be the same as the number of `<phrase> ... </phrase>` pairs in `text`. Got {len(matched_phrases)} v.s. {len(bboxes)} instead."
420
+ )
421
+
422
+ # insert object's patch index tokens
423
+ # the found `<phrase> ... </phrase>` pairs.
424
+ curr_pos = 0
425
+ buffer = []
426
+ for matched, bbox in zip(matched_phrases, bboxes):
427
+ _, end = matched.span()
428
+ buffer.append(text[curr_pos:end])
429
+ curr_pos = end
430
+ # A phrase without bbox
431
+ if bbox is None:
432
+ continue
433
+ # A phrase with a single bbox
434
+ if isinstance(bbox, tuple):
435
+ bbox = [bbox]
436
+ patch_index_strings = []
437
+ # A phrase could have multiple bboxes
438
+ if not all(box is not None for box in bbox):
439
+ raise ValueError(
440
+ "The multiple bounding boxes for a single phrase should not contain any `None` value."
441
+ )
442
+ for box in bbox:
443
+ patch_index_1, patch_index_2 = self._convert_bbox_to_patch_index_tokens(box)
444
+ patch_index_strings.append(f"{patch_index_1} {patch_index_2}")
445
+ # `bbox` being an empty list
446
+ if len(patch_index_strings) == 0:
447
+ continue
448
+ position_str = " </delimiter_of_multi_objects/> ".join(patch_index_strings)
449
+ buffer.append(f"<object> {position_str} </object>")
450
+ # remaining
451
+ if curr_pos < len(text):
452
+ buffer.append(text[curr_pos:])
453
+
454
+ text = "".join(buffer)
455
+ return text
456
+
457
+ def _convert_bbox_to_patch_index_tokens(
458
+ self, bbox: Union[Tuple[int, int], Tuple[float, float, float, float]]
459
+ ) -> Tuple[str, str]:
460
+ # already computed patch indices
461
+ if len(bbox) == 2:
462
+ idx_1, idx_2 = bbox
463
+ # bbox specified with (normalized) coordinates
464
+ else:
465
+ # use `self.tokenizer` to get `num_patches_per_side`
466
+ num_patches_per_side = int(math.sqrt(self.num_patch_index_tokens))
467
+ idx_1, idx_2 = coordinate_to_patch_index(bbox, num_patches_per_side)
468
+
469
+ token_1 = f"<patch_index_{str(idx_1).zfill(4)}>"
470
+ token_2 = f"<patch_index_{str(idx_2).zfill(4)}>"
471
+
472
+ return token_1, token_2
473
+
474
+
475
+ def coordinate_to_patch_index(bbox: Tuple[float, float, float, float], num_patches_per_side: int) -> Tuple[int, int]:
476
+ """Convert a bounding box to a pair of patch indices.
477
+
478
+ Args:
479
+ bbox (`Tuple[float, float, float, float]`):
480
+ The 4 coordinates of the bounding box, with the format being (x1, y1, x2, y2) specifying the upper-left and
481
+ lower-right corners of the box. It should have x2 > x1 and y2 > y1.
482
+ num_patches_per_side (`int`): the number of patches along each side.
483
+
484
+ Returns:
485
+ `Tuple[int, int]`: A pair of patch indices representing the upper-left patch and lower-right patch.
486
+ """
487
+ (x1, y1, x2, y2) = bbox
488
+
489
+ if not (x2 > x1 and y2 > y1):
490
+ raise ValueError("The coordinates in `bbox` should be `(x1, y1, x2, y2)` with `x2 > x1` and `y2 > y1`.")
491
+
492
+ ul_x = math.floor(x1 * num_patches_per_side)
493
+ ul_y = math.floor(y1 * num_patches_per_side)
494
+
495
+ lr_x = math.ceil(x2 * num_patches_per_side - 1)
496
+ lr_y = math.ceil(y2 * num_patches_per_side - 1)
497
+
498
+ ul_idx = ul_y * num_patches_per_side + ul_x
499
+ lr_idx = lr_y * num_patches_per_side + lr_x
500
+
501
+ return ul_idx, lr_idx
502
+
503
+
504
+ # copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L35C1-L75C38
505
+ # (with format modifications)
506
+ def patch_index_to_coordinate(ul_idx: int, lr_idx: int, num_patches_per_side: int):
507
+ """
508
+ Given a grid of length `num_patches_per_side` and the indices of the upper-left and lower-right corners of a
509
+ bounding box, returns the normalized coordinates of the bounding box, in the form (x1, y1, x2, y2).
510
+
511
+ Args:
512
+ ul_idx (`int`): the index of the grid cell that corresponds to the upper-left corner of the bounding box.
513
+ lr_idx (`int`): the index of the grid cell that corresponds to the lower-right corner of the bounding box.
514
+ num_patches_per_side (`int`): the number of patches along each side.
515
+
516
+ Returns:
517
+ `Tuple[float]`: the normalized coordinates of the bounding box, in the form (x1, y1, x2, y2).
518
+ """
519
+ # Compute the size of each cell in the grid
520
+ cell_size = 1.0 / num_patches_per_side
521
+
522
+ # Compute the x and y indices of the upper-left and lower-right corners of the bounding box
523
+ ul_x = ul_idx % num_patches_per_side
524
+ ul_y = ul_idx // num_patches_per_side
525
+
526
+ lr_x = lr_idx % num_patches_per_side
527
+ lr_y = lr_idx // num_patches_per_side
528
+
529
+ # Compute the normalized coordinates of the bounding box
530
+ if ul_idx == lr_idx:
531
+ x1 = ul_x * cell_size
532
+ y1 = ul_y * cell_size
533
+ x2 = lr_x * cell_size + cell_size
534
+ y2 = lr_y * cell_size + cell_size
535
+ elif ul_x == lr_x or ul_y == lr_y:
536
+ x1 = ul_x * cell_size
537
+ y1 = ul_y * cell_size
538
+ x2 = lr_x * cell_size + cell_size
539
+ y2 = lr_y * cell_size + cell_size
540
+ else:
541
+ x1 = ul_x * cell_size + cell_size / 2
542
+ y1 = ul_y * cell_size + cell_size / 2
543
+ x2 = lr_x * cell_size + cell_size / 2
544
+ y2 = lr_y * cell_size + cell_size / 2
545
+
546
+ return x1, y1, x2, y2
547
+
548
+
549
+ # copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L4-L33
550
+ # (with format modifications)
551
+ def extract_entities_with_patch_indices(text):
552
+ """Extract entities contained in `text`. The bounding bboxes is given in the form of patch indices.
553
+
554
+ This functioin is only intended to be used within `clean_text_and_extract_entities_with_bboxes` where further
555
+ processing happens, including converting to normalized coordinates and whitespace character cleaning up.
556
+
557
+ Examples:
558
+
559
+ ```python
560
+ >>> text = "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>."
561
+ >>> entities = extract_entities_with_patch_indices(text)
562
+ >>> entities
563
+ [(' a snowman', (31, 41), [(44, 863)]), (' a fire', (130, 137), [(5, 911)])]
564
+ ```"""
565
+ # The regular expression pattern for matching the required formats
566
+ pattern = r"(?:(<phrase>([^<]+)</phrase>))?<object>((?:<patch_index_\d+><patch_index_\d+></delimiter_of_multi_objects/>)*<patch_index_\d+><patch_index_\d+>)</object>"
567
+
568
+ # Find all matches in the given string
569
+ matches = re.finditer(pattern, text)
570
+
571
+ # Initialize an empty list to store the valid patch_index combinations
572
+ entities_with_patch_indices = []
573
+
574
+ for match in matches:
575
+ # span of a `phrase` that is between <phrase> and </phrase>
576
+ span = match.span(2)
577
+ phrase_tag, phrase, match_content = match.groups()
578
+ if not phrase_tag:
579
+ phrase = None
580
+ # We take the starting position of `<object>`
581
+ span = (match.span(0)[0], match.span(0)[0])
582
+
583
+ # Split the match_content by the delimiter to get individual patch_index pairs
584
+ patch_index_pairs = match_content.split("</delimiter_of_multi_objects/>")
585
+
586
+ entity_bboxes = []
587
+ for pair in patch_index_pairs:
588
+ # Extract the xxxx and yyyy values from the patch_index pair
589
+ x = re.search(r"<patch_index_(\d+)>", pair)
590
+ y = re.search(r"<patch_index_(\d+)>", pair[1:])
591
+
592
+ if x and y:
593
+ if phrase:
594
+ entity_bboxes.append((int(x.group(1)), int(y.group(1))))
595
+ else:
596
+ entity_bboxes.append((int(x.group(1)), int(y.group(1))))
597
+
598
+ if phrase:
599
+ entities_with_patch_indices.append((phrase, span, entity_bboxes))
600
+ else:
601
+ for bbox in entity_bboxes:
602
+ # fake entity name
603
+ entity = f"<patch_index_{bbox[0]}><patch_index_{bbox[1]}>"
604
+ entities_with_patch_indices.append((entity, span, [bbox]))
605
+
606
+ return entities_with_patch_indices
607
+
608
+
609
+ def adjust_entity_positions(entity, text):
610
+ """Adjust the positions of the entities in `text` to be relative to the text with special fields removed."""
611
+ entity_name, (start, end) = entity
612
+ # computed the length of strings with special fields (tag tokens, patch index tokens, etc.) removed
613
+ adjusted_start = len(re.sub("<.*?>", "", text[:start]))
614
+ adjusted_end = len(re.sub("<.*?>", "", text[:end]))
615
+ adjusted_entity = (entity_name, (adjusted_start, adjusted_end))
616
+ return adjusted_entity
617
+
618
+
619
+ def _cleanup_spaces(text, entities):
620
+ """Remove the spaces around the text and the entities in it."""
621
+ new_text = text.strip()
622
+ leading_spaces = len(text) - len(text.lstrip())
623
+
624
+ new_entities = []
625
+ for entity_name, (start, end), bboxes in entities:
626
+ entity_name_leading_spaces = len(entity_name) - len(entity_name.lstrip())
627
+ entity_name_trailing_spaces = len(entity_name) - len(entity_name.rstrip())
628
+
629
+ start = start - leading_spaces + entity_name_leading_spaces
630
+ end = end - leading_spaces - entity_name_trailing_spaces
631
+ entity_name = entity_name.strip()
632
+
633
+ new_entities.append((entity_name, (start, end), bboxes))
634
+
635
+ return new_text, new_entities
636
+
637
+
638
+ # copied from https://github.com/microsoft/unilm/blob/97e4923e97d3ee10b57e97013556e3fd0d207a9b/kosmos-2/demo/decode_string.py#L77-L87
639
+ # (with format modifications)
640
+ def clean_text_and_extract_entities_with_bboxes(text, num_patches_per_side=32):
641
+ """Remove the tag tokens from `text`, extract entities in it with some cleaning up of white characters.
642
+
643
+ Examples:
644
+
645
+ ```python
646
+ >>> text = "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863></object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911></object>."
647
+ >>> clean_text, entities = clean_text_and_extract_entities_with_bboxes(text)
648
+ >>> clean_text
649
+ 'An image of a snowman warming himself by a fire.'
650
+
651
+ >>> entities
652
+ [('a snowman', (12, 21), [(0.390625, 0.046875, 0.984375, 0.828125)]), ('a fire', (41, 47), [(0.171875, 0.015625, 0.484375, 0.890625)])]
653
+ ```"""
654
+ # remove special fields (tag tokens, patch index tokens, etc.)
655
+ processed_text = re.sub("<.*?>", "", text)
656
+
657
+ entities_with_patch_indices = extract_entities_with_patch_indices(text)
658
+ entities = []
659
+ for item in entities_with_patch_indices:
660
+ entity, bboxes = item[0:2], item[2]
661
+ adjusted_entity = adjust_entity_positions(entity, text)
662
+ bboxes_in_coords = [patch_index_to_coordinate(bbox[0], bbox[1], num_patches_per_side) for bbox in bboxes]
663
+
664
+ entities.append(adjusted_entity + (bboxes_in_coords,))
665
+
666
+ return _cleanup_spaces(processed_text, entities)
videochat2/lib/python3.10/site-packages/transformers/models/mgp_str/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.09 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/mgp_str/__pycache__/processing_mgp_str.cpython-310.pyc ADDED
Binary file (8.05 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__init__.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_tf_available,
21
+ is_tokenizers_available,
22
+ is_torch_available,
23
+ )
24
+
25
+
26
+ _import_structure = {
27
+ "configuration_mobilebert": [
28
+ "MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP",
29
+ "MobileBertConfig",
30
+ "MobileBertOnnxConfig",
31
+ ],
32
+ "tokenization_mobilebert": ["MobileBertTokenizer"],
33
+ }
34
+
35
+ try:
36
+ if not is_tokenizers_available():
37
+ raise OptionalDependencyNotAvailable()
38
+ except OptionalDependencyNotAvailable:
39
+ pass
40
+ else:
41
+ _import_structure["tokenization_mobilebert_fast"] = ["MobileBertTokenizerFast"]
42
+
43
+ try:
44
+ if not is_torch_available():
45
+ raise OptionalDependencyNotAvailable()
46
+ except OptionalDependencyNotAvailable:
47
+ pass
48
+ else:
49
+ _import_structure["modeling_mobilebert"] = [
50
+ "MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
51
+ "MobileBertForMaskedLM",
52
+ "MobileBertForMultipleChoice",
53
+ "MobileBertForNextSentencePrediction",
54
+ "MobileBertForPreTraining",
55
+ "MobileBertForQuestionAnswering",
56
+ "MobileBertForSequenceClassification",
57
+ "MobileBertForTokenClassification",
58
+ "MobileBertLayer",
59
+ "MobileBertModel",
60
+ "MobileBertPreTrainedModel",
61
+ "load_tf_weights_in_mobilebert",
62
+ ]
63
+
64
+ try:
65
+ if not is_tf_available():
66
+ raise OptionalDependencyNotAvailable()
67
+ except OptionalDependencyNotAvailable:
68
+ pass
69
+ else:
70
+ _import_structure["modeling_tf_mobilebert"] = [
71
+ "TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
72
+ "TFMobileBertForMaskedLM",
73
+ "TFMobileBertForMultipleChoice",
74
+ "TFMobileBertForNextSentencePrediction",
75
+ "TFMobileBertForPreTraining",
76
+ "TFMobileBertForQuestionAnswering",
77
+ "TFMobileBertForSequenceClassification",
78
+ "TFMobileBertForTokenClassification",
79
+ "TFMobileBertMainLayer",
80
+ "TFMobileBertModel",
81
+ "TFMobileBertPreTrainedModel",
82
+ ]
83
+
84
+
85
+ if TYPE_CHECKING:
86
+ from .configuration_mobilebert import (
87
+ MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
88
+ MobileBertConfig,
89
+ MobileBertOnnxConfig,
90
+ )
91
+ from .tokenization_mobilebert import MobileBertTokenizer
92
+
93
+ try:
94
+ if not is_tokenizers_available():
95
+ raise OptionalDependencyNotAvailable()
96
+ except OptionalDependencyNotAvailable:
97
+ pass
98
+ else:
99
+ from .tokenization_mobilebert_fast import MobileBertTokenizerFast
100
+
101
+ try:
102
+ if not is_torch_available():
103
+ raise OptionalDependencyNotAvailable()
104
+ except OptionalDependencyNotAvailable:
105
+ pass
106
+ else:
107
+ from .modeling_mobilebert import (
108
+ MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
109
+ MobileBertForMaskedLM,
110
+ MobileBertForMultipleChoice,
111
+ MobileBertForNextSentencePrediction,
112
+ MobileBertForPreTraining,
113
+ MobileBertForQuestionAnswering,
114
+ MobileBertForSequenceClassification,
115
+ MobileBertForTokenClassification,
116
+ MobileBertLayer,
117
+ MobileBertModel,
118
+ MobileBertPreTrainedModel,
119
+ load_tf_weights_in_mobilebert,
120
+ )
121
+
122
+ try:
123
+ if not is_tf_available():
124
+ raise OptionalDependencyNotAvailable()
125
+ except OptionalDependencyNotAvailable:
126
+ pass
127
+ else:
128
+ from .modeling_tf_mobilebert import (
129
+ TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
130
+ TFMobileBertForMaskedLM,
131
+ TFMobileBertForMultipleChoice,
132
+ TFMobileBertForNextSentencePrediction,
133
+ TFMobileBertForPreTraining,
134
+ TFMobileBertForQuestionAnswering,
135
+ TFMobileBertForSequenceClassification,
136
+ TFMobileBertForTokenClassification,
137
+ TFMobileBertMainLayer,
138
+ TFMobileBertModel,
139
+ TFMobileBertPreTrainedModel,
140
+ )
141
+
142
+ else:
143
+ import sys
144
+
145
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.22 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/configuration_mobilebert.cpython-310.pyc ADDED
Binary file (7.11 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/convert_mobilebert_original_tf_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (1.42 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/modeling_mobilebert.cpython-310.pyc ADDED
Binary file (48.4 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/modeling_tf_mobilebert.cpython-310.pyc ADDED
Binary file (56.4 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/tokenization_mobilebert.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/__pycache__/tokenization_mobilebert_fast.cpython-310.pyc ADDED
Binary file (6.83 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/configuration_mobilebert.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ MobileBERT model configuration"""
16
+ from collections import OrderedDict
17
+ from typing import Mapping
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...onnx import OnnxConfig
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ from ..deprecated._archive_maps import MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP # noqa: F401, E402
28
+
29
+
30
+ class MobileBertConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`MobileBertModel`] or a [`TFMobileBertModel`]. It
33
+ is used to instantiate a MobileBERT model according to the specified arguments, defining the model architecture.
34
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the MobileBERT
35
+ [google/mobilebert-uncased](https://huggingface.co/google/mobilebert-uncased) architecture.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 30522):
43
+ Vocabulary size of the MobileBERT model. Defines the number of different tokens that can be represented by
44
+ the `inputs_ids` passed when calling [`MobileBertModel`] or [`TFMobileBertModel`].
45
+ hidden_size (`int`, *optional*, defaults to 512):
46
+ Dimensionality of the encoder layers and the pooler layer.
47
+ num_hidden_layers (`int`, *optional*, defaults to 24):
48
+ Number of hidden layers in the Transformer encoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 4):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ intermediate_size (`int`, *optional*, defaults to 512):
52
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
53
+ hidden_act (`str` or `function`, *optional*, defaults to `"relu"`):
54
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
55
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
56
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
57
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
58
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
59
+ The dropout ratio for the attention probabilities.
60
+ max_position_embeddings (`int`, *optional*, defaults to 512):
61
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
62
+ just in case (e.g., 512 or 1024 or 2048).
63
+ type_vocab_size (`int`, *optional*, defaults to 2):
64
+ The vocabulary size of the `token_type_ids` passed when calling [`MobileBertModel`] or
65
+ [`TFMobileBertModel`].
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
69
+ The epsilon used by the layer normalization layers.
70
+
71
+ pad_token_id (`int`, *optional*, defaults to 0):
72
+ The ID of the token in the word embedding to use as padding.
73
+ embedding_size (`int`, *optional*, defaults to 128):
74
+ The dimension of the word embedding vectors.
75
+ trigram_input (`bool`, *optional*, defaults to `True`):
76
+ Use a convolution of trigram as input.
77
+ use_bottleneck (`bool`, *optional*, defaults to `True`):
78
+ Whether to use bottleneck in BERT.
79
+ intra_bottleneck_size (`int`, *optional*, defaults to 128):
80
+ Size of bottleneck layer output.
81
+ use_bottleneck_attention (`bool`, *optional*, defaults to `False`):
82
+ Whether to use attention inputs from the bottleneck transformation.
83
+ key_query_shared_bottleneck (`bool`, *optional*, defaults to `True`):
84
+ Whether to use the same linear transformation for query&key in the bottleneck.
85
+ num_feedforward_networks (`int`, *optional*, defaults to 4):
86
+ Number of FFNs in a block.
87
+ normalization_type (`str`, *optional*, defaults to `"no_norm"`):
88
+ The normalization type in MobileBERT.
89
+ classifier_dropout (`float`, *optional*):
90
+ The dropout ratio for the classification head.
91
+
92
+ Examples:
93
+
94
+ ```python
95
+ >>> from transformers import MobileBertConfig, MobileBertModel
96
+
97
+ >>> # Initializing a MobileBERT configuration
98
+ >>> configuration = MobileBertConfig()
99
+
100
+ >>> # Initializing a model (with random weights) from the configuration above
101
+ >>> model = MobileBertModel(configuration)
102
+
103
+ >>> # Accessing the model configuration
104
+ >>> configuration = model.config
105
+ ```
106
+ """
107
+
108
+ model_type = "mobilebert"
109
+
110
+ def __init__(
111
+ self,
112
+ vocab_size=30522,
113
+ hidden_size=512,
114
+ num_hidden_layers=24,
115
+ num_attention_heads=4,
116
+ intermediate_size=512,
117
+ hidden_act="relu",
118
+ hidden_dropout_prob=0.0,
119
+ attention_probs_dropout_prob=0.1,
120
+ max_position_embeddings=512,
121
+ type_vocab_size=2,
122
+ initializer_range=0.02,
123
+ layer_norm_eps=1e-12,
124
+ pad_token_id=0,
125
+ embedding_size=128,
126
+ trigram_input=True,
127
+ use_bottleneck=True,
128
+ intra_bottleneck_size=128,
129
+ use_bottleneck_attention=False,
130
+ key_query_shared_bottleneck=True,
131
+ num_feedforward_networks=4,
132
+ normalization_type="no_norm",
133
+ classifier_activation=True,
134
+ classifier_dropout=None,
135
+ **kwargs,
136
+ ):
137
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
138
+
139
+ self.vocab_size = vocab_size
140
+ self.hidden_size = hidden_size
141
+ self.num_hidden_layers = num_hidden_layers
142
+ self.num_attention_heads = num_attention_heads
143
+ self.hidden_act = hidden_act
144
+ self.intermediate_size = intermediate_size
145
+ self.hidden_dropout_prob = hidden_dropout_prob
146
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
147
+ self.max_position_embeddings = max_position_embeddings
148
+ self.type_vocab_size = type_vocab_size
149
+ self.initializer_range = initializer_range
150
+ self.layer_norm_eps = layer_norm_eps
151
+ self.embedding_size = embedding_size
152
+ self.trigram_input = trigram_input
153
+ self.use_bottleneck = use_bottleneck
154
+ self.intra_bottleneck_size = intra_bottleneck_size
155
+ self.use_bottleneck_attention = use_bottleneck_attention
156
+ self.key_query_shared_bottleneck = key_query_shared_bottleneck
157
+ self.num_feedforward_networks = num_feedforward_networks
158
+ self.normalization_type = normalization_type
159
+ self.classifier_activation = classifier_activation
160
+
161
+ if self.use_bottleneck:
162
+ self.true_hidden_size = intra_bottleneck_size
163
+ else:
164
+ self.true_hidden_size = hidden_size
165
+
166
+ self.classifier_dropout = classifier_dropout
167
+
168
+
169
+ # Copied from transformers.models.bert.configuration_bert.BertOnnxConfig with Bert->MobileBert
170
+ class MobileBertOnnxConfig(OnnxConfig):
171
+ @property
172
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
173
+ if self.task == "multiple-choice":
174
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
175
+ else:
176
+ dynamic_axis = {0: "batch", 1: "sequence"}
177
+ return OrderedDict(
178
+ [
179
+ ("input_ids", dynamic_axis),
180
+ ("attention_mask", dynamic_axis),
181
+ ("token_type_ids", dynamic_axis),
182
+ ]
183
+ )
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/convert_mobilebert_original_tf_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import argparse
16
+
17
+ import torch
18
+
19
+ from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert
20
+ from transformers.utils import logging
21
+
22
+
23
+ logging.set_verbosity_info()
24
+
25
+
26
+ def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, mobilebert_config_file, pytorch_dump_path):
27
+ # Initialise PyTorch model
28
+ config = MobileBertConfig.from_json_file(mobilebert_config_file)
29
+ print(f"Building PyTorch model from configuration: {config}")
30
+ model = MobileBertForPreTraining(config)
31
+ # Load weights from tf checkpoint
32
+ model = load_tf_weights_in_mobilebert(model, config, tf_checkpoint_path)
33
+ # Save pytorch-model
34
+ print(f"Save PyTorch model to {pytorch_dump_path}")
35
+ torch.save(model.state_dict(), pytorch_dump_path)
36
+
37
+
38
+ if __name__ == "__main__":
39
+ parser = argparse.ArgumentParser()
40
+ # Required parameters
41
+ parser.add_argument(
42
+ "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
43
+ )
44
+ parser.add_argument(
45
+ "--mobilebert_config_file",
46
+ default=None,
47
+ type=str,
48
+ required=True,
49
+ help=(
50
+ "The config json file corresponding to the pre-trained MobileBERT model. \n"
51
+ "This specifies the model architecture."
52
+ ),
53
+ )
54
+ parser.add_argument(
55
+ "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
56
+ )
57
+ args = parser.parse_args()
58
+ convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/modeling_mobilebert.py ADDED
@@ -0,0 +1,1617 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License
2
+ #
3
+ # Copyright (c) 2020 The Google AI Language Team Authors, The HuggingFace Inc. team and github/lonePatient
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in all
13
+ # copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ # SOFTWARE.
22
+
23
+ import math
24
+ import os
25
+ import warnings
26
+ from dataclasses import dataclass
27
+ from typing import Optional, Tuple, Union
28
+
29
+ import torch
30
+ from torch import nn
31
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
32
+
33
+ from ...activations import ACT2FN
34
+ from ...modeling_outputs import (
35
+ BaseModelOutput,
36
+ BaseModelOutputWithPooling,
37
+ MaskedLMOutput,
38
+ MultipleChoiceModelOutput,
39
+ NextSentencePredictorOutput,
40
+ QuestionAnsweringModelOutput,
41
+ SequenceClassifierOutput,
42
+ TokenClassifierOutput,
43
+ )
44
+ from ...modeling_utils import PreTrainedModel
45
+ from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
46
+ from ...utils import (
47
+ ModelOutput,
48
+ add_code_sample_docstrings,
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ logging,
52
+ replace_return_docstrings,
53
+ )
54
+ from .configuration_mobilebert import MobileBertConfig
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+ _CHECKPOINT_FOR_DOC = "google/mobilebert-uncased"
60
+ _CONFIG_FOR_DOC = "MobileBertConfig"
61
+
62
+ # TokenClassification docstring
63
+ _CHECKPOINT_FOR_TOKEN_CLASSIFICATION = "mrm8488/mobilebert-finetuned-ner"
64
+ _TOKEN_CLASS_EXPECTED_OUTPUT = "['I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC']"
65
+ _TOKEN_CLASS_EXPECTED_LOSS = 0.03
66
+
67
+ # QuestionAnswering docstring
68
+ _CHECKPOINT_FOR_QA = "csarron/mobilebert-uncased-squad-v2"
69
+ _QA_EXPECTED_OUTPUT = "'a nice puppet'"
70
+ _QA_EXPECTED_LOSS = 3.98
71
+ _QA_TARGET_START_INDEX = 12
72
+ _QA_TARGET_END_INDEX = 13
73
+
74
+ # SequenceClassification docstring
75
+ _CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "lordtt13/emo-mobilebert"
76
+ _SEQ_CLASS_EXPECTED_OUTPUT = "'others'"
77
+ _SEQ_CLASS_EXPECTED_LOSS = "4.72"
78
+
79
+
80
+ from ..deprecated._archive_maps import MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
81
+
82
+
83
+ def load_tf_weights_in_mobilebert(model, config, tf_checkpoint_path):
84
+ """Load tf checkpoints in a pytorch model."""
85
+ try:
86
+ import re
87
+
88
+ import numpy as np
89
+ import tensorflow as tf
90
+ except ImportError:
91
+ logger.error(
92
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
93
+ "https://www.tensorflow.org/install/ for installation instructions."
94
+ )
95
+ raise
96
+ tf_path = os.path.abspath(tf_checkpoint_path)
97
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
98
+ # Load weights from TF model
99
+ init_vars = tf.train.list_variables(tf_path)
100
+ names = []
101
+ arrays = []
102
+ for name, shape in init_vars:
103
+ logger.info(f"Loading TF weight {name} with shape {shape}")
104
+ array = tf.train.load_variable(tf_path, name)
105
+ names.append(name)
106
+ arrays.append(array)
107
+
108
+ for name, array in zip(names, arrays):
109
+ name = name.replace("ffn_layer", "ffn")
110
+ name = name.replace("FakeLayerNorm", "LayerNorm")
111
+ name = name.replace("extra_output_weights", "dense/kernel")
112
+ name = name.replace("bert", "mobilebert")
113
+ name = name.split("/")
114
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
115
+ # which are not required for using pretrained model
116
+ if any(
117
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
118
+ for n in name
119
+ ):
120
+ logger.info(f"Skipping {'/'.join(name)}")
121
+ continue
122
+ pointer = model
123
+ for m_name in name:
124
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
125
+ scope_names = re.split(r"_(\d+)", m_name)
126
+ else:
127
+ scope_names = [m_name]
128
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
129
+ pointer = getattr(pointer, "weight")
130
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
131
+ pointer = getattr(pointer, "bias")
132
+ elif scope_names[0] == "output_weights":
133
+ pointer = getattr(pointer, "weight")
134
+ elif scope_names[0] == "squad":
135
+ pointer = getattr(pointer, "classifier")
136
+ else:
137
+ try:
138
+ pointer = getattr(pointer, scope_names[0])
139
+ except AttributeError:
140
+ logger.info(f"Skipping {'/'.join(name)}")
141
+ continue
142
+ if len(scope_names) >= 2:
143
+ num = int(scope_names[1])
144
+ pointer = pointer[num]
145
+ if m_name[-11:] == "_embeddings":
146
+ pointer = getattr(pointer, "weight")
147
+ elif m_name == "kernel":
148
+ array = np.transpose(array)
149
+ try:
150
+ assert (
151
+ pointer.shape == array.shape
152
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
153
+ except AssertionError as e:
154
+ e.args += (pointer.shape, array.shape)
155
+ raise
156
+ logger.info(f"Initialize PyTorch weight {name}")
157
+ pointer.data = torch.from_numpy(array)
158
+ return model
159
+
160
+
161
+ class NoNorm(nn.Module):
162
+ def __init__(self, feat_size, eps=None):
163
+ super().__init__()
164
+ self.bias = nn.Parameter(torch.zeros(feat_size))
165
+ self.weight = nn.Parameter(torch.ones(feat_size))
166
+
167
+ def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
168
+ return input_tensor * self.weight + self.bias
169
+
170
+
171
+ NORM2FN = {"layer_norm": nn.LayerNorm, "no_norm": NoNorm}
172
+
173
+
174
+ class MobileBertEmbeddings(nn.Module):
175
+ """Construct the embeddings from word, position and token_type embeddings."""
176
+
177
+ def __init__(self, config):
178
+ super().__init__()
179
+ self.trigram_input = config.trigram_input
180
+ self.embedding_size = config.embedding_size
181
+ self.hidden_size = config.hidden_size
182
+
183
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
184
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
185
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
186
+
187
+ embed_dim_multiplier = 3 if self.trigram_input else 1
188
+ embedded_input_size = self.embedding_size * embed_dim_multiplier
189
+ self.embedding_transformation = nn.Linear(embedded_input_size, config.hidden_size)
190
+
191
+ self.LayerNorm = NORM2FN[config.normalization_type](config.hidden_size)
192
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
193
+
194
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
195
+ self.register_buffer(
196
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
197
+ )
198
+
199
+ def forward(
200
+ self,
201
+ input_ids: Optional[torch.LongTensor] = None,
202
+ token_type_ids: Optional[torch.LongTensor] = None,
203
+ position_ids: Optional[torch.LongTensor] = None,
204
+ inputs_embeds: Optional[torch.FloatTensor] = None,
205
+ ) -> torch.Tensor:
206
+ if input_ids is not None:
207
+ input_shape = input_ids.size()
208
+ else:
209
+ input_shape = inputs_embeds.size()[:-1]
210
+
211
+ seq_length = input_shape[1]
212
+
213
+ if position_ids is None:
214
+ position_ids = self.position_ids[:, :seq_length]
215
+
216
+ if token_type_ids is None:
217
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
218
+ if inputs_embeds is None:
219
+ inputs_embeds = self.word_embeddings(input_ids)
220
+
221
+ if self.trigram_input:
222
+ # From the paper MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited
223
+ # Devices (https://arxiv.org/abs/2004.02984)
224
+ #
225
+ # The embedding table in BERT models accounts for a substantial proportion of model size. To compress
226
+ # the embedding layer, we reduce the embedding dimension to 128 in MobileBERT.
227
+ # Then, we apply a 1D convolution with kernel size 3 on the raw token embedding to produce a 512
228
+ # dimensional output.
229
+ inputs_embeds = torch.cat(
230
+ [
231
+ nn.functional.pad(inputs_embeds[:, 1:], [0, 0, 0, 1, 0, 0], value=0.0),
232
+ inputs_embeds,
233
+ nn.functional.pad(inputs_embeds[:, :-1], [0, 0, 1, 0, 0, 0], value=0.0),
234
+ ],
235
+ dim=2,
236
+ )
237
+ if self.trigram_input or self.embedding_size != self.hidden_size:
238
+ inputs_embeds = self.embedding_transformation(inputs_embeds)
239
+
240
+ # Add positional embeddings and token type embeddings, then layer
241
+ # normalize and perform dropout.
242
+ position_embeddings = self.position_embeddings(position_ids)
243
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
244
+ embeddings = inputs_embeds + position_embeddings + token_type_embeddings
245
+ embeddings = self.LayerNorm(embeddings)
246
+ embeddings = self.dropout(embeddings)
247
+ return embeddings
248
+
249
+
250
+ class MobileBertSelfAttention(nn.Module):
251
+ def __init__(self, config):
252
+ super().__init__()
253
+ self.num_attention_heads = config.num_attention_heads
254
+ self.attention_head_size = int(config.true_hidden_size / config.num_attention_heads)
255
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
256
+
257
+ self.query = nn.Linear(config.true_hidden_size, self.all_head_size)
258
+ self.key = nn.Linear(config.true_hidden_size, self.all_head_size)
259
+ self.value = nn.Linear(
260
+ config.true_hidden_size if config.use_bottleneck_attention else config.hidden_size, self.all_head_size
261
+ )
262
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
263
+
264
+ def transpose_for_scores(self, x):
265
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
266
+ x = x.view(new_x_shape)
267
+ return x.permute(0, 2, 1, 3)
268
+
269
+ def forward(
270
+ self,
271
+ query_tensor: torch.Tensor,
272
+ key_tensor: torch.Tensor,
273
+ value_tensor: torch.Tensor,
274
+ attention_mask: Optional[torch.FloatTensor] = None,
275
+ head_mask: Optional[torch.FloatTensor] = None,
276
+ output_attentions: Optional[bool] = None,
277
+ ) -> Tuple[torch.Tensor]:
278
+ mixed_query_layer = self.query(query_tensor)
279
+ mixed_key_layer = self.key(key_tensor)
280
+ mixed_value_layer = self.value(value_tensor)
281
+
282
+ query_layer = self.transpose_for_scores(mixed_query_layer)
283
+ key_layer = self.transpose_for_scores(mixed_key_layer)
284
+ value_layer = self.transpose_for_scores(mixed_value_layer)
285
+
286
+ # Take the dot product between "query" and "key" to get the raw attention scores.
287
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
288
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
289
+ if attention_mask is not None:
290
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
291
+ attention_scores = attention_scores + attention_mask
292
+ # Normalize the attention scores to probabilities.
293
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
294
+ # This is actually dropping out entire tokens to attend to, which might
295
+ # seem a bit unusual, but is taken from the original Transformer paper.
296
+ attention_probs = self.dropout(attention_probs)
297
+ # Mask heads if we want to
298
+ if head_mask is not None:
299
+ attention_probs = attention_probs * head_mask
300
+ context_layer = torch.matmul(attention_probs, value_layer)
301
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
302
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
303
+ context_layer = context_layer.view(new_context_layer_shape)
304
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
305
+ return outputs
306
+
307
+
308
+ class MobileBertSelfOutput(nn.Module):
309
+ def __init__(self, config):
310
+ super().__init__()
311
+ self.use_bottleneck = config.use_bottleneck
312
+ self.dense = nn.Linear(config.true_hidden_size, config.true_hidden_size)
313
+ self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size, eps=config.layer_norm_eps)
314
+ if not self.use_bottleneck:
315
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
316
+
317
+ def forward(self, hidden_states: torch.Tensor, residual_tensor: torch.Tensor) -> torch.Tensor:
318
+ layer_outputs = self.dense(hidden_states)
319
+ if not self.use_bottleneck:
320
+ layer_outputs = self.dropout(layer_outputs)
321
+ layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
322
+ return layer_outputs
323
+
324
+
325
+ class MobileBertAttention(nn.Module):
326
+ def __init__(self, config):
327
+ super().__init__()
328
+ self.self = MobileBertSelfAttention(config)
329
+ self.output = MobileBertSelfOutput(config)
330
+ self.pruned_heads = set()
331
+
332
+ def prune_heads(self, heads):
333
+ if len(heads) == 0:
334
+ return
335
+ heads, index = find_pruneable_heads_and_indices(
336
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
337
+ )
338
+
339
+ # Prune linear layers
340
+ self.self.query = prune_linear_layer(self.self.query, index)
341
+ self.self.key = prune_linear_layer(self.self.key, index)
342
+ self.self.value = prune_linear_layer(self.self.value, index)
343
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
344
+
345
+ # Update hyper params and store pruned heads
346
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
347
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
348
+ self.pruned_heads = self.pruned_heads.union(heads)
349
+
350
+ def forward(
351
+ self,
352
+ query_tensor: torch.Tensor,
353
+ key_tensor: torch.Tensor,
354
+ value_tensor: torch.Tensor,
355
+ layer_input: torch.Tensor,
356
+ attention_mask: Optional[torch.FloatTensor] = None,
357
+ head_mask: Optional[torch.FloatTensor] = None,
358
+ output_attentions: Optional[bool] = None,
359
+ ) -> Tuple[torch.Tensor]:
360
+ self_outputs = self.self(
361
+ query_tensor,
362
+ key_tensor,
363
+ value_tensor,
364
+ attention_mask,
365
+ head_mask,
366
+ output_attentions,
367
+ )
368
+ # Run a linear projection of `hidden_size` then add a residual
369
+ # with `layer_input`.
370
+ attention_output = self.output(self_outputs[0], layer_input)
371
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
372
+ return outputs
373
+
374
+
375
+ class MobileBertIntermediate(nn.Module):
376
+ def __init__(self, config):
377
+ super().__init__()
378
+ self.dense = nn.Linear(config.true_hidden_size, config.intermediate_size)
379
+ if isinstance(config.hidden_act, str):
380
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
381
+ else:
382
+ self.intermediate_act_fn = config.hidden_act
383
+
384
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
385
+ hidden_states = self.dense(hidden_states)
386
+ hidden_states = self.intermediate_act_fn(hidden_states)
387
+ return hidden_states
388
+
389
+
390
+ class OutputBottleneck(nn.Module):
391
+ def __init__(self, config):
392
+ super().__init__()
393
+ self.dense = nn.Linear(config.true_hidden_size, config.hidden_size)
394
+ self.LayerNorm = NORM2FN[config.normalization_type](config.hidden_size, eps=config.layer_norm_eps)
395
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
396
+
397
+ def forward(self, hidden_states: torch.Tensor, residual_tensor: torch.Tensor) -> torch.Tensor:
398
+ layer_outputs = self.dense(hidden_states)
399
+ layer_outputs = self.dropout(layer_outputs)
400
+ layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
401
+ return layer_outputs
402
+
403
+
404
+ class MobileBertOutput(nn.Module):
405
+ def __init__(self, config):
406
+ super().__init__()
407
+ self.use_bottleneck = config.use_bottleneck
408
+ self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size)
409
+ self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size)
410
+ if not self.use_bottleneck:
411
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
412
+ else:
413
+ self.bottleneck = OutputBottleneck(config)
414
+
415
+ def forward(
416
+ self, intermediate_states: torch.Tensor, residual_tensor_1: torch.Tensor, residual_tensor_2: torch.Tensor
417
+ ) -> torch.Tensor:
418
+ layer_output = self.dense(intermediate_states)
419
+ if not self.use_bottleneck:
420
+ layer_output = self.dropout(layer_output)
421
+ layer_output = self.LayerNorm(layer_output + residual_tensor_1)
422
+ else:
423
+ layer_output = self.LayerNorm(layer_output + residual_tensor_1)
424
+ layer_output = self.bottleneck(layer_output, residual_tensor_2)
425
+ return layer_output
426
+
427
+
428
+ class BottleneckLayer(nn.Module):
429
+ def __init__(self, config):
430
+ super().__init__()
431
+ self.dense = nn.Linear(config.hidden_size, config.intra_bottleneck_size)
432
+ self.LayerNorm = NORM2FN[config.normalization_type](config.intra_bottleneck_size, eps=config.layer_norm_eps)
433
+
434
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
435
+ layer_input = self.dense(hidden_states)
436
+ layer_input = self.LayerNorm(layer_input)
437
+ return layer_input
438
+
439
+
440
+ class Bottleneck(nn.Module):
441
+ def __init__(self, config):
442
+ super().__init__()
443
+ self.key_query_shared_bottleneck = config.key_query_shared_bottleneck
444
+ self.use_bottleneck_attention = config.use_bottleneck_attention
445
+ self.input = BottleneckLayer(config)
446
+ if self.key_query_shared_bottleneck:
447
+ self.attention = BottleneckLayer(config)
448
+
449
+ def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor]:
450
+ # This method can return three different tuples of values. These different values make use of bottlenecks,
451
+ # which are linear layers used to project the hidden states to a lower-dimensional vector, reducing memory
452
+ # usage. These linear layer have weights that are learned during training.
453
+ #
454
+ # If `config.use_bottleneck_attention`, it will return the result of the bottleneck layer four times for the
455
+ # key, query, value, and "layer input" to be used by the attention layer.
456
+ # This bottleneck is used to project the hidden. This last layer input will be used as a residual tensor
457
+ # in the attention self output, after the attention scores have been computed.
458
+ #
459
+ # If not `config.use_bottleneck_attention` and `config.key_query_shared_bottleneck`, this will return
460
+ # four values, three of which have been passed through a bottleneck: the query and key, passed through the same
461
+ # bottleneck, and the residual layer to be applied in the attention self output, through another bottleneck.
462
+ #
463
+ # Finally, in the last case, the values for the query, key and values are the hidden states without bottleneck,
464
+ # and the residual layer will be this value passed through a bottleneck.
465
+
466
+ bottlenecked_hidden_states = self.input(hidden_states)
467
+ if self.use_bottleneck_attention:
468
+ return (bottlenecked_hidden_states,) * 4
469
+ elif self.key_query_shared_bottleneck:
470
+ shared_attention_input = self.attention(hidden_states)
471
+ return (shared_attention_input, shared_attention_input, hidden_states, bottlenecked_hidden_states)
472
+ else:
473
+ return (hidden_states, hidden_states, hidden_states, bottlenecked_hidden_states)
474
+
475
+
476
+ class FFNOutput(nn.Module):
477
+ def __init__(self, config):
478
+ super().__init__()
479
+ self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size)
480
+ self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size, eps=config.layer_norm_eps)
481
+
482
+ def forward(self, hidden_states: torch.Tensor, residual_tensor: torch.Tensor) -> torch.Tensor:
483
+ layer_outputs = self.dense(hidden_states)
484
+ layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
485
+ return layer_outputs
486
+
487
+
488
+ class FFNLayer(nn.Module):
489
+ def __init__(self, config):
490
+ super().__init__()
491
+ self.intermediate = MobileBertIntermediate(config)
492
+ self.output = FFNOutput(config)
493
+
494
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
495
+ intermediate_output = self.intermediate(hidden_states)
496
+ layer_outputs = self.output(intermediate_output, hidden_states)
497
+ return layer_outputs
498
+
499
+
500
+ class MobileBertLayer(nn.Module):
501
+ def __init__(self, config):
502
+ super().__init__()
503
+ self.use_bottleneck = config.use_bottleneck
504
+ self.num_feedforward_networks = config.num_feedforward_networks
505
+
506
+ self.attention = MobileBertAttention(config)
507
+ self.intermediate = MobileBertIntermediate(config)
508
+ self.output = MobileBertOutput(config)
509
+ if self.use_bottleneck:
510
+ self.bottleneck = Bottleneck(config)
511
+ if config.num_feedforward_networks > 1:
512
+ self.ffn = nn.ModuleList([FFNLayer(config) for _ in range(config.num_feedforward_networks - 1)])
513
+
514
+ def forward(
515
+ self,
516
+ hidden_states: torch.Tensor,
517
+ attention_mask: Optional[torch.FloatTensor] = None,
518
+ head_mask: Optional[torch.FloatTensor] = None,
519
+ output_attentions: Optional[bool] = None,
520
+ ) -> Tuple[torch.Tensor]:
521
+ if self.use_bottleneck:
522
+ query_tensor, key_tensor, value_tensor, layer_input = self.bottleneck(hidden_states)
523
+ else:
524
+ query_tensor, key_tensor, value_tensor, layer_input = [hidden_states] * 4
525
+
526
+ self_attention_outputs = self.attention(
527
+ query_tensor,
528
+ key_tensor,
529
+ value_tensor,
530
+ layer_input,
531
+ attention_mask,
532
+ head_mask,
533
+ output_attentions=output_attentions,
534
+ )
535
+ attention_output = self_attention_outputs[0]
536
+ s = (attention_output,)
537
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
538
+
539
+ if self.num_feedforward_networks != 1:
540
+ for i, ffn_module in enumerate(self.ffn):
541
+ attention_output = ffn_module(attention_output)
542
+ s += (attention_output,)
543
+
544
+ intermediate_output = self.intermediate(attention_output)
545
+ layer_output = self.output(intermediate_output, attention_output, hidden_states)
546
+ outputs = (
547
+ (layer_output,)
548
+ + outputs
549
+ + (
550
+ torch.tensor(1000),
551
+ query_tensor,
552
+ key_tensor,
553
+ value_tensor,
554
+ layer_input,
555
+ attention_output,
556
+ intermediate_output,
557
+ )
558
+ + s
559
+ )
560
+ return outputs
561
+
562
+
563
+ class MobileBertEncoder(nn.Module):
564
+ def __init__(self, config):
565
+ super().__init__()
566
+ self.layer = nn.ModuleList([MobileBertLayer(config) for _ in range(config.num_hidden_layers)])
567
+
568
+ def forward(
569
+ self,
570
+ hidden_states: torch.Tensor,
571
+ attention_mask: Optional[torch.FloatTensor] = None,
572
+ head_mask: Optional[torch.FloatTensor] = None,
573
+ output_attentions: Optional[bool] = False,
574
+ output_hidden_states: Optional[bool] = False,
575
+ return_dict: Optional[bool] = True,
576
+ ) -> Union[Tuple, BaseModelOutput]:
577
+ all_hidden_states = () if output_hidden_states else None
578
+ all_attentions = () if output_attentions else None
579
+ for i, layer_module in enumerate(self.layer):
580
+ if output_hidden_states:
581
+ all_hidden_states = all_hidden_states + (hidden_states,)
582
+
583
+ layer_outputs = layer_module(
584
+ hidden_states,
585
+ attention_mask,
586
+ head_mask[i],
587
+ output_attentions,
588
+ )
589
+ hidden_states = layer_outputs[0]
590
+
591
+ if output_attentions:
592
+ all_attentions = all_attentions + (layer_outputs[1],)
593
+
594
+ # Add last layer
595
+ if output_hidden_states:
596
+ all_hidden_states = all_hidden_states + (hidden_states,)
597
+
598
+ if not return_dict:
599
+ return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
600
+ return BaseModelOutput(
601
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
602
+ )
603
+
604
+
605
+ class MobileBertPooler(nn.Module):
606
+ def __init__(self, config):
607
+ super().__init__()
608
+ self.do_activate = config.classifier_activation
609
+ if self.do_activate:
610
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
611
+
612
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
613
+ # We "pool" the model by simply taking the hidden state corresponding
614
+ # to the first token.
615
+ first_token_tensor = hidden_states[:, 0]
616
+ if not self.do_activate:
617
+ return first_token_tensor
618
+ else:
619
+ pooled_output = self.dense(first_token_tensor)
620
+ pooled_output = torch.tanh(pooled_output)
621
+ return pooled_output
622
+
623
+
624
+ class MobileBertPredictionHeadTransform(nn.Module):
625
+ def __init__(self, config):
626
+ super().__init__()
627
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
628
+ if isinstance(config.hidden_act, str):
629
+ self.transform_act_fn = ACT2FN[config.hidden_act]
630
+ else:
631
+ self.transform_act_fn = config.hidden_act
632
+ self.LayerNorm = NORM2FN["layer_norm"](config.hidden_size, eps=config.layer_norm_eps)
633
+
634
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
635
+ hidden_states = self.dense(hidden_states)
636
+ hidden_states = self.transform_act_fn(hidden_states)
637
+ hidden_states = self.LayerNorm(hidden_states)
638
+ return hidden_states
639
+
640
+
641
+ class MobileBertLMPredictionHead(nn.Module):
642
+ def __init__(self, config):
643
+ super().__init__()
644
+ self.transform = MobileBertPredictionHeadTransform(config)
645
+ # The output weights are the same as the input embeddings, but there is
646
+ # an output-only bias for each token.
647
+ self.dense = nn.Linear(config.vocab_size, config.hidden_size - config.embedding_size, bias=False)
648
+ self.decoder = nn.Linear(config.embedding_size, config.vocab_size, bias=False)
649
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
650
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
651
+ self.decoder.bias = self.bias
652
+
653
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
654
+ hidden_states = self.transform(hidden_states)
655
+ hidden_states = hidden_states.matmul(torch.cat([self.decoder.weight.t(), self.dense.weight], dim=0))
656
+ hidden_states += self.decoder.bias
657
+ return hidden_states
658
+
659
+
660
+ class MobileBertOnlyMLMHead(nn.Module):
661
+ def __init__(self, config):
662
+ super().__init__()
663
+ self.predictions = MobileBertLMPredictionHead(config)
664
+
665
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
666
+ prediction_scores = self.predictions(sequence_output)
667
+ return prediction_scores
668
+
669
+
670
+ class MobileBertPreTrainingHeads(nn.Module):
671
+ def __init__(self, config):
672
+ super().__init__()
673
+ self.predictions = MobileBertLMPredictionHead(config)
674
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
675
+
676
+ def forward(self, sequence_output: torch.Tensor, pooled_output: torch.Tensor) -> Tuple[torch.Tensor]:
677
+ prediction_scores = self.predictions(sequence_output)
678
+ seq_relationship_score = self.seq_relationship(pooled_output)
679
+ return prediction_scores, seq_relationship_score
680
+
681
+
682
+ class MobileBertPreTrainedModel(PreTrainedModel):
683
+ """
684
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
685
+ models.
686
+ """
687
+
688
+ config_class = MobileBertConfig
689
+ load_tf_weights = load_tf_weights_in_mobilebert
690
+ base_model_prefix = "mobilebert"
691
+
692
+ def _init_weights(self, module):
693
+ """Initialize the weights"""
694
+ if isinstance(module, nn.Linear):
695
+ # Slightly different from the TF version which uses truncated_normal for initialization
696
+ # cf https://github.com/pytorch/pytorch/pull/5617
697
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
698
+ if module.bias is not None:
699
+ module.bias.data.zero_()
700
+ elif isinstance(module, nn.Embedding):
701
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
702
+ if module.padding_idx is not None:
703
+ module.weight.data[module.padding_idx].zero_()
704
+ elif isinstance(module, (nn.LayerNorm, NoNorm)):
705
+ module.bias.data.zero_()
706
+ module.weight.data.fill_(1.0)
707
+
708
+
709
+ @dataclass
710
+ class MobileBertForPreTrainingOutput(ModelOutput):
711
+ """
712
+ Output type of [`MobileBertForPreTraining`].
713
+
714
+ Args:
715
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
716
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
717
+ (classification) loss.
718
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
719
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
720
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
721
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
722
+ before SoftMax).
723
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
724
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
725
+ shape `(batch_size, sequence_length, hidden_size)`.
726
+
727
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
728
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
729
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
730
+ sequence_length)`.
731
+
732
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
733
+ heads.
734
+ """
735
+
736
+ loss: Optional[torch.FloatTensor] = None
737
+ prediction_logits: torch.FloatTensor = None
738
+ seq_relationship_logits: torch.FloatTensor = None
739
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
740
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
741
+
742
+
743
+ MOBILEBERT_START_DOCSTRING = r"""
744
+
745
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
746
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
747
+ etc.)
748
+
749
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
750
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
751
+ and behavior.
752
+
753
+ Parameters:
754
+ config ([`MobileBertConfig`]): Model configuration class with all the parameters of the model.
755
+ Initializing with a config file does not load the weights associated with the model, only the
756
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
757
+ """
758
+
759
+ MOBILEBERT_INPUTS_DOCSTRING = r"""
760
+ Args:
761
+ input_ids (`torch.LongTensor` of shape `({0})`):
762
+ Indices of input sequence tokens in the vocabulary.
763
+
764
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
765
+ [`PreTrainedTokenizer.__call__`] for details.
766
+
767
+ [What are input IDs?](../glossary#input-ids)
768
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
769
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
770
+
771
+ - 1 for tokens that are **not masked**,
772
+ - 0 for tokens that are **masked**.
773
+
774
+ [What are attention masks?](../glossary#attention-mask)
775
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
776
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
777
+ 1]`:
778
+
779
+ - 0 corresponds to a *sentence A* token,
780
+ - 1 corresponds to a *sentence B* token.
781
+
782
+ [What are token type IDs?](../glossary#token-type-ids)
783
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
784
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
785
+ config.max_position_embeddings - 1]`.
786
+
787
+ [What are position IDs?](../glossary#position-ids)
788
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
789
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
790
+
791
+ - 1 indicates the head is **not masked**,
792
+ - 0 indicates the head is **masked**.
793
+
794
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
795
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
796
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
797
+ model's internal embedding lookup matrix.
798
+ output_attentions (`bool`, *optional*):
799
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
800
+ tensors for more detail.
801
+ output_hidden_states (`bool`, *optional*):
802
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
803
+ more detail.
804
+ return_dict (`bool`, *optional*):
805
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
806
+ """
807
+
808
+
809
+ @add_start_docstrings(
810
+ "The bare MobileBert Model transformer outputting raw hidden-states without any specific head on top.",
811
+ MOBILEBERT_START_DOCSTRING,
812
+ )
813
+ class MobileBertModel(MobileBertPreTrainedModel):
814
+ """
815
+ https://arxiv.org/pdf/2004.02984.pdf
816
+ """
817
+
818
+ def __init__(self, config, add_pooling_layer=True):
819
+ super().__init__(config)
820
+ self.config = config
821
+ self.embeddings = MobileBertEmbeddings(config)
822
+ self.encoder = MobileBertEncoder(config)
823
+
824
+ self.pooler = MobileBertPooler(config) if add_pooling_layer else None
825
+
826
+ # Initialize weights and apply final processing
827
+ self.post_init()
828
+
829
+ def get_input_embeddings(self):
830
+ return self.embeddings.word_embeddings
831
+
832
+ def set_input_embeddings(self, value):
833
+ self.embeddings.word_embeddings = value
834
+
835
+ def _prune_heads(self, heads_to_prune):
836
+ """
837
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
838
+ class PreTrainedModel
839
+ """
840
+ for layer, heads in heads_to_prune.items():
841
+ self.encoder.layer[layer].attention.prune_heads(heads)
842
+
843
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
844
+ @add_code_sample_docstrings(
845
+ checkpoint=_CHECKPOINT_FOR_DOC,
846
+ output_type=BaseModelOutputWithPooling,
847
+ config_class=_CONFIG_FOR_DOC,
848
+ )
849
+ def forward(
850
+ self,
851
+ input_ids: Optional[torch.LongTensor] = None,
852
+ attention_mask: Optional[torch.FloatTensor] = None,
853
+ token_type_ids: Optional[torch.LongTensor] = None,
854
+ position_ids: Optional[torch.LongTensor] = None,
855
+ head_mask: Optional[torch.FloatTensor] = None,
856
+ inputs_embeds: Optional[torch.FloatTensor] = None,
857
+ output_hidden_states: Optional[bool] = None,
858
+ output_attentions: Optional[bool] = None,
859
+ return_dict: Optional[bool] = None,
860
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
861
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
862
+ output_hidden_states = (
863
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
864
+ )
865
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
866
+
867
+ if input_ids is not None and inputs_embeds is not None:
868
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
869
+ elif input_ids is not None:
870
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
871
+ input_shape = input_ids.size()
872
+ elif inputs_embeds is not None:
873
+ input_shape = inputs_embeds.size()[:-1]
874
+ else:
875
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
876
+
877
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
878
+
879
+ if attention_mask is None:
880
+ attention_mask = torch.ones(input_shape, device=device)
881
+ if token_type_ids is None:
882
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
883
+
884
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
885
+ # ourselves in which case we just need to make it broadcastable to all heads.
886
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
887
+
888
+ # Prepare head mask if needed
889
+ # 1.0 in head_mask indicate we keep the head
890
+ # attention_probs has shape bsz x n_heads x N x N
891
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
892
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
893
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
894
+
895
+ embedding_output = self.embeddings(
896
+ input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
897
+ )
898
+ encoder_outputs = self.encoder(
899
+ embedding_output,
900
+ attention_mask=extended_attention_mask,
901
+ head_mask=head_mask,
902
+ output_attentions=output_attentions,
903
+ output_hidden_states=output_hidden_states,
904
+ return_dict=return_dict,
905
+ )
906
+ sequence_output = encoder_outputs[0]
907
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
908
+
909
+ if not return_dict:
910
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
911
+
912
+ return BaseModelOutputWithPooling(
913
+ last_hidden_state=sequence_output,
914
+ pooler_output=pooled_output,
915
+ hidden_states=encoder_outputs.hidden_states,
916
+ attentions=encoder_outputs.attentions,
917
+ )
918
+
919
+
920
+ @add_start_docstrings(
921
+ """
922
+ MobileBert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
923
+ `next sentence prediction (classification)` head.
924
+ """,
925
+ MOBILEBERT_START_DOCSTRING,
926
+ )
927
+ class MobileBertForPreTraining(MobileBertPreTrainedModel):
928
+ _tied_weights_keys = ["cls.predictions.decoder.weight", "cls.predictions.decoder.bias"]
929
+
930
+ def __init__(self, config):
931
+ super().__init__(config)
932
+ self.mobilebert = MobileBertModel(config)
933
+ self.cls = MobileBertPreTrainingHeads(config)
934
+
935
+ # Initialize weights and apply final processing
936
+ self.post_init()
937
+
938
+ def get_output_embeddings(self):
939
+ return self.cls.predictions.decoder
940
+
941
+ def set_output_embeddings(self, new_embeddigs):
942
+ self.cls.predictions.decoder = new_embeddigs
943
+
944
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding:
945
+ # resize dense output embedings at first
946
+ self.cls.predictions.dense = self._get_resized_lm_head(
947
+ self.cls.predictions.dense, new_num_tokens=new_num_tokens, transposed=True
948
+ )
949
+
950
+ return super().resize_token_embeddings(new_num_tokens=new_num_tokens)
951
+
952
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
953
+ @replace_return_docstrings(output_type=MobileBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
954
+ def forward(
955
+ self,
956
+ input_ids: Optional[torch.LongTensor] = None,
957
+ attention_mask: Optional[torch.FloatTensor] = None,
958
+ token_type_ids: Optional[torch.LongTensor] = None,
959
+ position_ids: Optional[torch.LongTensor] = None,
960
+ head_mask: Optional[torch.FloatTensor] = None,
961
+ inputs_embeds: Optional[torch.FloatTensor] = None,
962
+ labels: Optional[torch.LongTensor] = None,
963
+ next_sentence_label: Optional[torch.LongTensor] = None,
964
+ output_attentions: Optional[torch.FloatTensor] = None,
965
+ output_hidden_states: Optional[torch.FloatTensor] = None,
966
+ return_dict: Optional[torch.FloatTensor] = None,
967
+ ) -> Union[Tuple, MobileBertForPreTrainingOutput]:
968
+ r"""
969
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
970
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
971
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
972
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
973
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
974
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
975
+ (see `input_ids` docstring) Indices should be in `[0, 1]`:
976
+
977
+ - 0 indicates sequence B is a continuation of sequence A,
978
+ - 1 indicates sequence B is a random sequence.
979
+
980
+ Returns:
981
+
982
+ Examples:
983
+
984
+ ```python
985
+ >>> from transformers import AutoTokenizer, MobileBertForPreTraining
986
+ >>> import torch
987
+
988
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mobilebert-uncased")
989
+ >>> model = MobileBertForPreTraining.from_pretrained("google/mobilebert-uncased")
990
+
991
+ >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)
992
+ >>> # Batch size 1
993
+ >>> outputs = model(input_ids)
994
+
995
+ >>> prediction_logits = outputs.prediction_logits
996
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
997
+ ```"""
998
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
999
+
1000
+ outputs = self.mobilebert(
1001
+ input_ids,
1002
+ attention_mask=attention_mask,
1003
+ token_type_ids=token_type_ids,
1004
+ position_ids=position_ids,
1005
+ head_mask=head_mask,
1006
+ inputs_embeds=inputs_embeds,
1007
+ output_attentions=output_attentions,
1008
+ output_hidden_states=output_hidden_states,
1009
+ return_dict=return_dict,
1010
+ )
1011
+ sequence_output, pooled_output = outputs[:2]
1012
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
1013
+
1014
+ total_loss = None
1015
+ if labels is not None and next_sentence_label is not None:
1016
+ loss_fct = CrossEntropyLoss()
1017
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1018
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
1019
+ total_loss = masked_lm_loss + next_sentence_loss
1020
+
1021
+ if not return_dict:
1022
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1023
+ return ((total_loss,) + output) if total_loss is not None else output
1024
+
1025
+ return MobileBertForPreTrainingOutput(
1026
+ loss=total_loss,
1027
+ prediction_logits=prediction_scores,
1028
+ seq_relationship_logits=seq_relationship_score,
1029
+ hidden_states=outputs.hidden_states,
1030
+ attentions=outputs.attentions,
1031
+ )
1032
+
1033
+
1034
+ @add_start_docstrings("""MobileBert Model with a `language modeling` head on top.""", MOBILEBERT_START_DOCSTRING)
1035
+ class MobileBertForMaskedLM(MobileBertPreTrainedModel):
1036
+ _tied_weights_keys = ["cls.predictions.decoder.weight", "cls.predictions.decoder.bias"]
1037
+
1038
+ def __init__(self, config):
1039
+ super().__init__(config)
1040
+ self.mobilebert = MobileBertModel(config, add_pooling_layer=False)
1041
+ self.cls = MobileBertOnlyMLMHead(config)
1042
+ self.config = config
1043
+
1044
+ # Initialize weights and apply final processing
1045
+ self.post_init()
1046
+
1047
+ def get_output_embeddings(self):
1048
+ return self.cls.predictions.decoder
1049
+
1050
+ def set_output_embeddings(self, new_embeddigs):
1051
+ self.cls.predictions.decoder = new_embeddigs
1052
+
1053
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding:
1054
+ # resize dense output embedings at first
1055
+ self.cls.predictions.dense = self._get_resized_lm_head(
1056
+ self.cls.predictions.dense, new_num_tokens=new_num_tokens, transposed=True
1057
+ )
1058
+ return super().resize_token_embeddings(new_num_tokens=new_num_tokens)
1059
+
1060
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1061
+ @add_code_sample_docstrings(
1062
+ checkpoint=_CHECKPOINT_FOR_DOC,
1063
+ output_type=MaskedLMOutput,
1064
+ config_class=_CONFIG_FOR_DOC,
1065
+ expected_output="'paris'",
1066
+ expected_loss=0.57,
1067
+ )
1068
+ def forward(
1069
+ self,
1070
+ input_ids: Optional[torch.LongTensor] = None,
1071
+ attention_mask: Optional[torch.FloatTensor] = None,
1072
+ token_type_ids: Optional[torch.LongTensor] = None,
1073
+ position_ids: Optional[torch.LongTensor] = None,
1074
+ head_mask: Optional[torch.FloatTensor] = None,
1075
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1076
+ labels: Optional[torch.LongTensor] = None,
1077
+ output_attentions: Optional[bool] = None,
1078
+ output_hidden_states: Optional[bool] = None,
1079
+ return_dict: Optional[bool] = None,
1080
+ ) -> Union[Tuple, MaskedLMOutput]:
1081
+ r"""
1082
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1083
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1084
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1085
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1086
+ """
1087
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1088
+
1089
+ outputs = self.mobilebert(
1090
+ input_ids,
1091
+ attention_mask=attention_mask,
1092
+ token_type_ids=token_type_ids,
1093
+ position_ids=position_ids,
1094
+ head_mask=head_mask,
1095
+ inputs_embeds=inputs_embeds,
1096
+ output_attentions=output_attentions,
1097
+ output_hidden_states=output_hidden_states,
1098
+ return_dict=return_dict,
1099
+ )
1100
+
1101
+ sequence_output = outputs[0]
1102
+ prediction_scores = self.cls(sequence_output)
1103
+
1104
+ masked_lm_loss = None
1105
+ if labels is not None:
1106
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1107
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1108
+
1109
+ if not return_dict:
1110
+ output = (prediction_scores,) + outputs[2:]
1111
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1112
+
1113
+ return MaskedLMOutput(
1114
+ loss=masked_lm_loss,
1115
+ logits=prediction_scores,
1116
+ hidden_states=outputs.hidden_states,
1117
+ attentions=outputs.attentions,
1118
+ )
1119
+
1120
+
1121
+ class MobileBertOnlyNSPHead(nn.Module):
1122
+ def __init__(self, config):
1123
+ super().__init__()
1124
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
1125
+
1126
+ def forward(self, pooled_output: torch.Tensor) -> torch.Tensor:
1127
+ seq_relationship_score = self.seq_relationship(pooled_output)
1128
+ return seq_relationship_score
1129
+
1130
+
1131
+ @add_start_docstrings(
1132
+ """MobileBert Model with a `next sentence prediction (classification)` head on top.""",
1133
+ MOBILEBERT_START_DOCSTRING,
1134
+ )
1135
+ class MobileBertForNextSentencePrediction(MobileBertPreTrainedModel):
1136
+ def __init__(self, config):
1137
+ super().__init__(config)
1138
+
1139
+ self.mobilebert = MobileBertModel(config)
1140
+ self.cls = MobileBertOnlyNSPHead(config)
1141
+
1142
+ # Initialize weights and apply final processing
1143
+ self.post_init()
1144
+
1145
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1146
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
1147
+ def forward(
1148
+ self,
1149
+ input_ids: Optional[torch.LongTensor] = None,
1150
+ attention_mask: Optional[torch.FloatTensor] = None,
1151
+ token_type_ids: Optional[torch.LongTensor] = None,
1152
+ position_ids: Optional[torch.LongTensor] = None,
1153
+ head_mask: Optional[torch.FloatTensor] = None,
1154
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1155
+ labels: Optional[torch.LongTensor] = None,
1156
+ output_attentions: Optional[bool] = None,
1157
+ output_hidden_states: Optional[bool] = None,
1158
+ return_dict: Optional[bool] = None,
1159
+ **kwargs,
1160
+ ) -> Union[Tuple, NextSentencePredictorOutput]:
1161
+ r"""
1162
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1163
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1164
+ (see `input_ids` docstring) Indices should be in `[0, 1]`.
1165
+
1166
+ - 0 indicates sequence B is a continuation of sequence A,
1167
+ - 1 indicates sequence B is a random sequence.
1168
+
1169
+ Returns:
1170
+
1171
+ Examples:
1172
+
1173
+ ```python
1174
+ >>> from transformers import AutoTokenizer, MobileBertForNextSentencePrediction
1175
+ >>> import torch
1176
+
1177
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mobilebert-uncased")
1178
+ >>> model = MobileBertForNextSentencePrediction.from_pretrained("google/mobilebert-uncased")
1179
+
1180
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1181
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1182
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
1183
+
1184
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
1185
+ >>> loss = outputs.loss
1186
+ >>> logits = outputs.logits
1187
+ ```"""
1188
+
1189
+ if "next_sentence_label" in kwargs:
1190
+ warnings.warn(
1191
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
1192
+ " `labels` instead.",
1193
+ FutureWarning,
1194
+ )
1195
+ labels = kwargs.pop("next_sentence_label")
1196
+
1197
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1198
+
1199
+ outputs = self.mobilebert(
1200
+ input_ids,
1201
+ attention_mask=attention_mask,
1202
+ token_type_ids=token_type_ids,
1203
+ position_ids=position_ids,
1204
+ head_mask=head_mask,
1205
+ inputs_embeds=inputs_embeds,
1206
+ output_attentions=output_attentions,
1207
+ output_hidden_states=output_hidden_states,
1208
+ return_dict=return_dict,
1209
+ )
1210
+
1211
+ pooled_output = outputs[1]
1212
+ seq_relationship_score = self.cls(pooled_output)
1213
+
1214
+ next_sentence_loss = None
1215
+ if labels is not None:
1216
+ loss_fct = CrossEntropyLoss()
1217
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), labels.view(-1))
1218
+
1219
+ if not return_dict:
1220
+ output = (seq_relationship_score,) + outputs[2:]
1221
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1222
+
1223
+ return NextSentencePredictorOutput(
1224
+ loss=next_sentence_loss,
1225
+ logits=seq_relationship_score,
1226
+ hidden_states=outputs.hidden_states,
1227
+ attentions=outputs.attentions,
1228
+ )
1229
+
1230
+
1231
+ @add_start_docstrings(
1232
+ """
1233
+ MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
1234
+ pooled output) e.g. for GLUE tasks.
1235
+ """,
1236
+ MOBILEBERT_START_DOCSTRING,
1237
+ )
1238
+ # Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification with Bert->MobileBert all-casing
1239
+ class MobileBertForSequenceClassification(MobileBertPreTrainedModel):
1240
+ def __init__(self, config):
1241
+ super().__init__(config)
1242
+ self.num_labels = config.num_labels
1243
+ self.config = config
1244
+
1245
+ self.mobilebert = MobileBertModel(config)
1246
+ classifier_dropout = (
1247
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1248
+ )
1249
+ self.dropout = nn.Dropout(classifier_dropout)
1250
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1251
+
1252
+ # Initialize weights and apply final processing
1253
+ self.post_init()
1254
+
1255
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1256
+ @add_code_sample_docstrings(
1257
+ checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
1258
+ output_type=SequenceClassifierOutput,
1259
+ config_class=_CONFIG_FOR_DOC,
1260
+ expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
1261
+ expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
1262
+ )
1263
+ def forward(
1264
+ self,
1265
+ input_ids: Optional[torch.Tensor] = None,
1266
+ attention_mask: Optional[torch.Tensor] = None,
1267
+ token_type_ids: Optional[torch.Tensor] = None,
1268
+ position_ids: Optional[torch.Tensor] = None,
1269
+ head_mask: Optional[torch.Tensor] = None,
1270
+ inputs_embeds: Optional[torch.Tensor] = None,
1271
+ labels: Optional[torch.Tensor] = None,
1272
+ output_attentions: Optional[bool] = None,
1273
+ output_hidden_states: Optional[bool] = None,
1274
+ return_dict: Optional[bool] = None,
1275
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1276
+ r"""
1277
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1278
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1279
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1280
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1281
+ """
1282
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1283
+
1284
+ outputs = self.mobilebert(
1285
+ input_ids,
1286
+ attention_mask=attention_mask,
1287
+ token_type_ids=token_type_ids,
1288
+ position_ids=position_ids,
1289
+ head_mask=head_mask,
1290
+ inputs_embeds=inputs_embeds,
1291
+ output_attentions=output_attentions,
1292
+ output_hidden_states=output_hidden_states,
1293
+ return_dict=return_dict,
1294
+ )
1295
+
1296
+ pooled_output = outputs[1]
1297
+
1298
+ pooled_output = self.dropout(pooled_output)
1299
+ logits = self.classifier(pooled_output)
1300
+
1301
+ loss = None
1302
+ if labels is not None:
1303
+ if self.config.problem_type is None:
1304
+ if self.num_labels == 1:
1305
+ self.config.problem_type = "regression"
1306
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1307
+ self.config.problem_type = "single_label_classification"
1308
+ else:
1309
+ self.config.problem_type = "multi_label_classification"
1310
+
1311
+ if self.config.problem_type == "regression":
1312
+ loss_fct = MSELoss()
1313
+ if self.num_labels == 1:
1314
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1315
+ else:
1316
+ loss = loss_fct(logits, labels)
1317
+ elif self.config.problem_type == "single_label_classification":
1318
+ loss_fct = CrossEntropyLoss()
1319
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1320
+ elif self.config.problem_type == "multi_label_classification":
1321
+ loss_fct = BCEWithLogitsLoss()
1322
+ loss = loss_fct(logits, labels)
1323
+ if not return_dict:
1324
+ output = (logits,) + outputs[2:]
1325
+ return ((loss,) + output) if loss is not None else output
1326
+
1327
+ return SequenceClassifierOutput(
1328
+ loss=loss,
1329
+ logits=logits,
1330
+ hidden_states=outputs.hidden_states,
1331
+ attentions=outputs.attentions,
1332
+ )
1333
+
1334
+
1335
+ @add_start_docstrings(
1336
+ """
1337
+ MobileBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
1338
+ linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1339
+ """,
1340
+ MOBILEBERT_START_DOCSTRING,
1341
+ )
1342
+ # Copied from transformers.models.bert.modeling_bert.BertForQuestionAnswering with Bert->MobileBert all-casing
1343
+ class MobileBertForQuestionAnswering(MobileBertPreTrainedModel):
1344
+ def __init__(self, config):
1345
+ super().__init__(config)
1346
+ self.num_labels = config.num_labels
1347
+
1348
+ self.mobilebert = MobileBertModel(config, add_pooling_layer=False)
1349
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1350
+
1351
+ # Initialize weights and apply final processing
1352
+ self.post_init()
1353
+
1354
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1355
+ @add_code_sample_docstrings(
1356
+ checkpoint=_CHECKPOINT_FOR_QA,
1357
+ output_type=QuestionAnsweringModelOutput,
1358
+ config_class=_CONFIG_FOR_DOC,
1359
+ qa_target_start_index=_QA_TARGET_START_INDEX,
1360
+ qa_target_end_index=_QA_TARGET_END_INDEX,
1361
+ expected_output=_QA_EXPECTED_OUTPUT,
1362
+ expected_loss=_QA_EXPECTED_LOSS,
1363
+ )
1364
+ def forward(
1365
+ self,
1366
+ input_ids: Optional[torch.Tensor] = None,
1367
+ attention_mask: Optional[torch.Tensor] = None,
1368
+ token_type_ids: Optional[torch.Tensor] = None,
1369
+ position_ids: Optional[torch.Tensor] = None,
1370
+ head_mask: Optional[torch.Tensor] = None,
1371
+ inputs_embeds: Optional[torch.Tensor] = None,
1372
+ start_positions: Optional[torch.Tensor] = None,
1373
+ end_positions: Optional[torch.Tensor] = None,
1374
+ output_attentions: Optional[bool] = None,
1375
+ output_hidden_states: Optional[bool] = None,
1376
+ return_dict: Optional[bool] = None,
1377
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1378
+ r"""
1379
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1380
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1381
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1382
+ are not taken into account for computing the loss.
1383
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1384
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1385
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1386
+ are not taken into account for computing the loss.
1387
+ """
1388
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1389
+
1390
+ outputs = self.mobilebert(
1391
+ input_ids,
1392
+ attention_mask=attention_mask,
1393
+ token_type_ids=token_type_ids,
1394
+ position_ids=position_ids,
1395
+ head_mask=head_mask,
1396
+ inputs_embeds=inputs_embeds,
1397
+ output_attentions=output_attentions,
1398
+ output_hidden_states=output_hidden_states,
1399
+ return_dict=return_dict,
1400
+ )
1401
+
1402
+ sequence_output = outputs[0]
1403
+
1404
+ logits = self.qa_outputs(sequence_output)
1405
+ start_logits, end_logits = logits.split(1, dim=-1)
1406
+ start_logits = start_logits.squeeze(-1).contiguous()
1407
+ end_logits = end_logits.squeeze(-1).contiguous()
1408
+
1409
+ total_loss = None
1410
+ if start_positions is not None and end_positions is not None:
1411
+ # If we are on multi-GPU, split add a dimension
1412
+ if len(start_positions.size()) > 1:
1413
+ start_positions = start_positions.squeeze(-1)
1414
+ if len(end_positions.size()) > 1:
1415
+ end_positions = end_positions.squeeze(-1)
1416
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1417
+ ignored_index = start_logits.size(1)
1418
+ start_positions = start_positions.clamp(0, ignored_index)
1419
+ end_positions = end_positions.clamp(0, ignored_index)
1420
+
1421
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1422
+ start_loss = loss_fct(start_logits, start_positions)
1423
+ end_loss = loss_fct(end_logits, end_positions)
1424
+ total_loss = (start_loss + end_loss) / 2
1425
+
1426
+ if not return_dict:
1427
+ output = (start_logits, end_logits) + outputs[2:]
1428
+ return ((total_loss,) + output) if total_loss is not None else output
1429
+
1430
+ return QuestionAnsweringModelOutput(
1431
+ loss=total_loss,
1432
+ start_logits=start_logits,
1433
+ end_logits=end_logits,
1434
+ hidden_states=outputs.hidden_states,
1435
+ attentions=outputs.attentions,
1436
+ )
1437
+
1438
+
1439
+ @add_start_docstrings(
1440
+ """
1441
+ MobileBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
1442
+ a softmax) e.g. for RocStories/SWAG tasks.
1443
+ """,
1444
+ MOBILEBERT_START_DOCSTRING,
1445
+ )
1446
+ # Copied from transformers.models.bert.modeling_bert.BertForMultipleChoice with Bert->MobileBert all-casing
1447
+ class MobileBertForMultipleChoice(MobileBertPreTrainedModel):
1448
+ def __init__(self, config):
1449
+ super().__init__(config)
1450
+
1451
+ self.mobilebert = MobileBertModel(config)
1452
+ classifier_dropout = (
1453
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1454
+ )
1455
+ self.dropout = nn.Dropout(classifier_dropout)
1456
+ self.classifier = nn.Linear(config.hidden_size, 1)
1457
+
1458
+ # Initialize weights and apply final processing
1459
+ self.post_init()
1460
+
1461
+ @add_start_docstrings_to_model_forward(
1462
+ MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1463
+ )
1464
+ @add_code_sample_docstrings(
1465
+ checkpoint=_CHECKPOINT_FOR_DOC,
1466
+ output_type=MultipleChoiceModelOutput,
1467
+ config_class=_CONFIG_FOR_DOC,
1468
+ )
1469
+ def forward(
1470
+ self,
1471
+ input_ids: Optional[torch.Tensor] = None,
1472
+ attention_mask: Optional[torch.Tensor] = None,
1473
+ token_type_ids: Optional[torch.Tensor] = None,
1474
+ position_ids: Optional[torch.Tensor] = None,
1475
+ head_mask: Optional[torch.Tensor] = None,
1476
+ inputs_embeds: Optional[torch.Tensor] = None,
1477
+ labels: Optional[torch.Tensor] = None,
1478
+ output_attentions: Optional[bool] = None,
1479
+ output_hidden_states: Optional[bool] = None,
1480
+ return_dict: Optional[bool] = None,
1481
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
1482
+ r"""
1483
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1484
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1485
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1486
+ `input_ids` above)
1487
+ """
1488
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1489
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1490
+
1491
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1492
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1493
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1494
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1495
+ inputs_embeds = (
1496
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1497
+ if inputs_embeds is not None
1498
+ else None
1499
+ )
1500
+
1501
+ outputs = self.mobilebert(
1502
+ input_ids,
1503
+ attention_mask=attention_mask,
1504
+ token_type_ids=token_type_ids,
1505
+ position_ids=position_ids,
1506
+ head_mask=head_mask,
1507
+ inputs_embeds=inputs_embeds,
1508
+ output_attentions=output_attentions,
1509
+ output_hidden_states=output_hidden_states,
1510
+ return_dict=return_dict,
1511
+ )
1512
+
1513
+ pooled_output = outputs[1]
1514
+
1515
+ pooled_output = self.dropout(pooled_output)
1516
+ logits = self.classifier(pooled_output)
1517
+ reshaped_logits = logits.view(-1, num_choices)
1518
+
1519
+ loss = None
1520
+ if labels is not None:
1521
+ loss_fct = CrossEntropyLoss()
1522
+ loss = loss_fct(reshaped_logits, labels)
1523
+
1524
+ if not return_dict:
1525
+ output = (reshaped_logits,) + outputs[2:]
1526
+ return ((loss,) + output) if loss is not None else output
1527
+
1528
+ return MultipleChoiceModelOutput(
1529
+ loss=loss,
1530
+ logits=reshaped_logits,
1531
+ hidden_states=outputs.hidden_states,
1532
+ attentions=outputs.attentions,
1533
+ )
1534
+
1535
+
1536
+ @add_start_docstrings(
1537
+ """
1538
+ MobileBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
1539
+ for Named-Entity-Recognition (NER) tasks.
1540
+ """,
1541
+ MOBILEBERT_START_DOCSTRING,
1542
+ )
1543
+ # Copied from transformers.models.bert.modeling_bert.BertForTokenClassification with Bert->MobileBert all-casing
1544
+ class MobileBertForTokenClassification(MobileBertPreTrainedModel):
1545
+ def __init__(self, config):
1546
+ super().__init__(config)
1547
+ self.num_labels = config.num_labels
1548
+
1549
+ self.mobilebert = MobileBertModel(config, add_pooling_layer=False)
1550
+ classifier_dropout = (
1551
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1552
+ )
1553
+ self.dropout = nn.Dropout(classifier_dropout)
1554
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1555
+
1556
+ # Initialize weights and apply final processing
1557
+ self.post_init()
1558
+
1559
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1560
+ @add_code_sample_docstrings(
1561
+ checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
1562
+ output_type=TokenClassifierOutput,
1563
+ config_class=_CONFIG_FOR_DOC,
1564
+ expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
1565
+ expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
1566
+ )
1567
+ def forward(
1568
+ self,
1569
+ input_ids: Optional[torch.Tensor] = None,
1570
+ attention_mask: Optional[torch.Tensor] = None,
1571
+ token_type_ids: Optional[torch.Tensor] = None,
1572
+ position_ids: Optional[torch.Tensor] = None,
1573
+ head_mask: Optional[torch.Tensor] = None,
1574
+ inputs_embeds: Optional[torch.Tensor] = None,
1575
+ labels: Optional[torch.Tensor] = None,
1576
+ output_attentions: Optional[bool] = None,
1577
+ output_hidden_states: Optional[bool] = None,
1578
+ return_dict: Optional[bool] = None,
1579
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1580
+ r"""
1581
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1582
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1583
+ """
1584
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1585
+
1586
+ outputs = self.mobilebert(
1587
+ input_ids,
1588
+ attention_mask=attention_mask,
1589
+ token_type_ids=token_type_ids,
1590
+ position_ids=position_ids,
1591
+ head_mask=head_mask,
1592
+ inputs_embeds=inputs_embeds,
1593
+ output_attentions=output_attentions,
1594
+ output_hidden_states=output_hidden_states,
1595
+ return_dict=return_dict,
1596
+ )
1597
+
1598
+ sequence_output = outputs[0]
1599
+
1600
+ sequence_output = self.dropout(sequence_output)
1601
+ logits = self.classifier(sequence_output)
1602
+
1603
+ loss = None
1604
+ if labels is not None:
1605
+ loss_fct = CrossEntropyLoss()
1606
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1607
+
1608
+ if not return_dict:
1609
+ output = (logits,) + outputs[2:]
1610
+ return ((loss,) + output) if loss is not None else output
1611
+
1612
+ return TokenClassifierOutput(
1613
+ loss=loss,
1614
+ logits=logits,
1615
+ hidden_states=outputs.hidden_states,
1616
+ attentions=outputs.attentions,
1617
+ )
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/modeling_tf_mobilebert.py ADDED
@@ -0,0 +1,1970 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ TF 2.0 MobileBERT model."""
17
+
18
+
19
+ from __future__ import annotations
20
+
21
+ import warnings
22
+ from dataclasses import dataclass
23
+ from typing import Optional, Tuple, Union
24
+
25
+ import numpy as np
26
+ import tensorflow as tf
27
+
28
+ from ...activations_tf import get_tf_activation
29
+ from ...modeling_tf_outputs import (
30
+ TFBaseModelOutput,
31
+ TFBaseModelOutputWithPooling,
32
+ TFMaskedLMOutput,
33
+ TFMultipleChoiceModelOutput,
34
+ TFNextSentencePredictorOutput,
35
+ TFQuestionAnsweringModelOutput,
36
+ TFSequenceClassifierOutput,
37
+ TFTokenClassifierOutput,
38
+ )
39
+ from ...modeling_tf_utils import (
40
+ TFMaskedLanguageModelingLoss,
41
+ TFModelInputType,
42
+ TFMultipleChoiceLoss,
43
+ TFNextSentencePredictionLoss,
44
+ TFPreTrainedModel,
45
+ TFQuestionAnsweringLoss,
46
+ TFSequenceClassificationLoss,
47
+ TFTokenClassificationLoss,
48
+ get_initializer,
49
+ keras,
50
+ keras_serializable,
51
+ unpack_inputs,
52
+ )
53
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
54
+ from ...utils import (
55
+ ModelOutput,
56
+ add_code_sample_docstrings,
57
+ add_start_docstrings,
58
+ add_start_docstrings_to_model_forward,
59
+ logging,
60
+ replace_return_docstrings,
61
+ )
62
+ from .configuration_mobilebert import MobileBertConfig
63
+
64
+
65
+ logger = logging.get_logger(__name__)
66
+
67
+ _CHECKPOINT_FOR_DOC = "google/mobilebert-uncased"
68
+ _CONFIG_FOR_DOC = "MobileBertConfig"
69
+
70
+ # TokenClassification docstring
71
+ _CHECKPOINT_FOR_TOKEN_CLASSIFICATION = "vumichien/mobilebert-finetuned-ner"
72
+ _TOKEN_CLASS_EXPECTED_OUTPUT = "['I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC']"
73
+ _TOKEN_CLASS_EXPECTED_LOSS = 0.03
74
+
75
+ # QuestionAnswering docstring
76
+ _CHECKPOINT_FOR_QA = "vumichien/mobilebert-uncased-squad-v2"
77
+ _QA_EXPECTED_OUTPUT = "'a nice puppet'"
78
+ _QA_EXPECTED_LOSS = 3.98
79
+ _QA_TARGET_START_INDEX = 12
80
+ _QA_TARGET_END_INDEX = 13
81
+
82
+ # SequenceClassification docstring
83
+ _CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "vumichien/emo-mobilebert"
84
+ _SEQ_CLASS_EXPECTED_OUTPUT = "'others'"
85
+ _SEQ_CLASS_EXPECTED_LOSS = "4.72"
86
+
87
+
88
+ from ..deprecated._archive_maps import TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
89
+
90
+
91
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertPreTrainingLoss
92
+ class TFMobileBertPreTrainingLoss:
93
+ """
94
+ Loss function suitable for BERT-like pretraining, that is, the task of pretraining a language model by combining
95
+ NSP + MLM. .. note:: Any label of -100 will be ignored (along with the corresponding logits) in the loss
96
+ computation.
97
+ """
98
+
99
+ def hf_compute_loss(self, labels: tf.Tensor, logits: tf.Tensor) -> tf.Tensor:
100
+ loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction=keras.losses.Reduction.NONE)
101
+
102
+ # Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
103
+ unmasked_lm_losses = loss_fn(y_true=tf.nn.relu(labels["labels"]), y_pred=logits[0])
104
+ # make sure only labels that are not equal to -100
105
+ # are taken into account for the loss computation
106
+ lm_loss_mask = tf.cast(labels["labels"] != -100, dtype=unmasked_lm_losses.dtype)
107
+ masked_lm_losses = unmasked_lm_losses * lm_loss_mask
108
+ reduced_masked_lm_loss = tf.reduce_sum(masked_lm_losses) / tf.reduce_sum(lm_loss_mask)
109
+
110
+ # Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
111
+ unmasked_ns_loss = loss_fn(y_true=tf.nn.relu(labels["next_sentence_label"]), y_pred=logits[1])
112
+ ns_loss_mask = tf.cast(labels["next_sentence_label"] != -100, dtype=unmasked_ns_loss.dtype)
113
+ masked_ns_loss = unmasked_ns_loss * ns_loss_mask
114
+
115
+ reduced_masked_ns_loss = tf.reduce_sum(masked_ns_loss) / tf.reduce_sum(ns_loss_mask)
116
+
117
+ return tf.reshape(reduced_masked_lm_loss + reduced_masked_ns_loss, (1,))
118
+
119
+
120
+ class TFMobileBertIntermediate(keras.layers.Layer):
121
+ def __init__(self, config, **kwargs):
122
+ super().__init__(**kwargs)
123
+
124
+ self.dense = keras.layers.Dense(config.intermediate_size, name="dense")
125
+
126
+ if isinstance(config.hidden_act, str):
127
+ self.intermediate_act_fn = get_tf_activation(config.hidden_act)
128
+ else:
129
+ self.intermediate_act_fn = config.hidden_act
130
+ self.config = config
131
+
132
+ def call(self, hidden_states):
133
+ hidden_states = self.dense(hidden_states)
134
+ hidden_states = self.intermediate_act_fn(hidden_states)
135
+
136
+ return hidden_states
137
+
138
+ def build(self, input_shape=None):
139
+ if self.built:
140
+ return
141
+ self.built = True
142
+ if getattr(self, "dense", None) is not None:
143
+ with tf.name_scope(self.dense.name):
144
+ self.dense.build([None, None, self.config.true_hidden_size])
145
+
146
+
147
+ class TFLayerNorm(keras.layers.LayerNormalization):
148
+ def __init__(self, feat_size, *args, **kwargs):
149
+ self.feat_size = feat_size
150
+ super().__init__(*args, **kwargs)
151
+
152
+ def build(self, input_shape=None):
153
+ super().build([None, None, self.feat_size])
154
+
155
+
156
+ class TFNoNorm(keras.layers.Layer):
157
+ def __init__(self, feat_size, epsilon=None, **kwargs):
158
+ super().__init__(**kwargs)
159
+ self.feat_size = feat_size
160
+
161
+ def build(self, input_shape):
162
+ self.bias = self.add_weight("bias", shape=[self.feat_size], initializer="zeros")
163
+ self.weight = self.add_weight("weight", shape=[self.feat_size], initializer="ones")
164
+ super().build(input_shape)
165
+
166
+ def call(self, inputs: tf.Tensor):
167
+ return inputs * self.weight + self.bias
168
+
169
+
170
+ NORM2FN = {"layer_norm": TFLayerNorm, "no_norm": TFNoNorm}
171
+
172
+
173
+ class TFMobileBertEmbeddings(keras.layers.Layer):
174
+ """Construct the embeddings from word, position and token_type embeddings."""
175
+
176
+ def __init__(self, config, **kwargs):
177
+ super().__init__(**kwargs)
178
+
179
+ self.trigram_input = config.trigram_input
180
+ self.embedding_size = config.embedding_size
181
+ self.config = config
182
+ self.hidden_size = config.hidden_size
183
+ self.max_position_embeddings = config.max_position_embeddings
184
+ self.initializer_range = config.initializer_range
185
+ self.embedding_transformation = keras.layers.Dense(config.hidden_size, name="embedding_transformation")
186
+
187
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
188
+ # any TensorFlow checkpoint file
189
+ self.LayerNorm = NORM2FN[config.normalization_type](
190
+ config.hidden_size, epsilon=config.layer_norm_eps, name="LayerNorm"
191
+ )
192
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
193
+ self.embedded_input_size = self.embedding_size * (3 if self.trigram_input else 1)
194
+
195
+ def build(self, input_shape=None):
196
+ with tf.name_scope("word_embeddings"):
197
+ self.weight = self.add_weight(
198
+ name="weight",
199
+ shape=[self.config.vocab_size, self.embedding_size],
200
+ initializer=get_initializer(initializer_range=self.initializer_range),
201
+ )
202
+
203
+ with tf.name_scope("token_type_embeddings"):
204
+ self.token_type_embeddings = self.add_weight(
205
+ name="embeddings",
206
+ shape=[self.config.type_vocab_size, self.hidden_size],
207
+ initializer=get_initializer(initializer_range=self.initializer_range),
208
+ )
209
+
210
+ with tf.name_scope("position_embeddings"):
211
+ self.position_embeddings = self.add_weight(
212
+ name="embeddings",
213
+ shape=[self.max_position_embeddings, self.hidden_size],
214
+ initializer=get_initializer(initializer_range=self.initializer_range),
215
+ )
216
+
217
+ if self.built:
218
+ return
219
+ self.built = True
220
+ if getattr(self, "embedding_transformation", None) is not None:
221
+ with tf.name_scope(self.embedding_transformation.name):
222
+ self.embedding_transformation.build([None, None, self.embedded_input_size])
223
+ if getattr(self, "LayerNorm", None) is not None:
224
+ with tf.name_scope(self.LayerNorm.name):
225
+ self.LayerNorm.build(None)
226
+
227
+ def call(self, input_ids=None, position_ids=None, token_type_ids=None, inputs_embeds=None, training=False):
228
+ """
229
+ Applies embedding based on inputs tensor.
230
+
231
+ Returns:
232
+ final_embeddings (`tf.Tensor`): output embedding tensor.
233
+ """
234
+ assert not (input_ids is None and inputs_embeds is None)
235
+
236
+ if input_ids is not None:
237
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
238
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
239
+
240
+ input_shape = shape_list(inputs_embeds)[:-1]
241
+
242
+ if token_type_ids is None:
243
+ token_type_ids = tf.fill(dims=input_shape, value=0)
244
+
245
+ if self.trigram_input:
246
+ # From the paper MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited
247
+ # Devices (https://arxiv.org/abs/2004.02984)
248
+ #
249
+ # The embedding table in BERT models accounts for a substantial proportion of model size. To compress
250
+ # the embedding layer, we reduce the embedding dimension to 128 in MobileBERT.
251
+ # Then, we apply a 1D convolution with kernel size 3 on the raw token embedding to produce a 512
252
+ # dimensional output.
253
+ inputs_embeds = tf.concat(
254
+ [
255
+ tf.pad(inputs_embeds[:, 1:], ((0, 0), (0, 1), (0, 0))),
256
+ inputs_embeds,
257
+ tf.pad(inputs_embeds[:, :-1], ((0, 0), (1, 0), (0, 0))),
258
+ ],
259
+ axis=2,
260
+ )
261
+
262
+ if self.trigram_input or self.embedding_size != self.hidden_size:
263
+ inputs_embeds = self.embedding_transformation(inputs_embeds)
264
+
265
+ if position_ids is None:
266
+ position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
267
+
268
+ position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
269
+ token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
270
+ final_embeddings = inputs_embeds + position_embeds + token_type_embeds
271
+ final_embeddings = self.LayerNorm(inputs=final_embeddings)
272
+ final_embeddings = self.dropout(inputs=final_embeddings, training=training)
273
+
274
+ return final_embeddings
275
+
276
+
277
+ class TFMobileBertSelfAttention(keras.layers.Layer):
278
+ def __init__(self, config, **kwargs):
279
+ super().__init__(**kwargs)
280
+ if config.hidden_size % config.num_attention_heads != 0:
281
+ raise ValueError(
282
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
283
+ f"heads ({config.num_attention_heads}"
284
+ )
285
+
286
+ self.num_attention_heads = config.num_attention_heads
287
+ self.output_attentions = config.output_attentions
288
+ assert config.hidden_size % config.num_attention_heads == 0
289
+ self.attention_head_size = int(config.true_hidden_size / config.num_attention_heads)
290
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
291
+
292
+ self.query = keras.layers.Dense(
293
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
294
+ )
295
+ self.key = keras.layers.Dense(
296
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
297
+ )
298
+ self.value = keras.layers.Dense(
299
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
300
+ )
301
+
302
+ self.dropout = keras.layers.Dropout(config.attention_probs_dropout_prob)
303
+ self.config = config
304
+
305
+ def transpose_for_scores(self, x, batch_size):
306
+ # Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
307
+ x = tf.reshape(x, (batch_size, -1, self.num_attention_heads, self.attention_head_size))
308
+ return tf.transpose(x, perm=[0, 2, 1, 3])
309
+
310
+ def call(
311
+ self, query_tensor, key_tensor, value_tensor, attention_mask, head_mask, output_attentions, training=False
312
+ ):
313
+ batch_size = shape_list(attention_mask)[0]
314
+ mixed_query_layer = self.query(query_tensor)
315
+ mixed_key_layer = self.key(key_tensor)
316
+ mixed_value_layer = self.value(value_tensor)
317
+ query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
318
+ key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)
319
+ value_layer = self.transpose_for_scores(mixed_value_layer, batch_size)
320
+
321
+ # Take the dot product between "query" and "key" to get the raw attention scores.
322
+ attention_scores = tf.matmul(
323
+ query_layer, key_layer, transpose_b=True
324
+ ) # (batch size, num_heads, seq_len_q, seq_len_k)
325
+ dk = tf.cast(shape_list(key_layer)[-1], dtype=attention_scores.dtype) # scale attention_scores
326
+ attention_scores = attention_scores / tf.math.sqrt(dk)
327
+
328
+ if attention_mask is not None:
329
+ # Apply the attention mask is (precomputed for all layers in TFMobileBertModel call() function)
330
+ attention_mask = tf.cast(attention_mask, dtype=attention_scores.dtype)
331
+ attention_scores = attention_scores + attention_mask
332
+
333
+ # Normalize the attention scores to probabilities.
334
+ attention_probs = stable_softmax(attention_scores, axis=-1)
335
+
336
+ # This is actually dropping out entire tokens to attend to, which might
337
+ # seem a bit unusual, but is taken from the original Transformer paper.
338
+ attention_probs = self.dropout(attention_probs, training=training)
339
+
340
+ # Mask heads if we want to
341
+ if head_mask is not None:
342
+ attention_probs = attention_probs * head_mask
343
+
344
+ context_layer = tf.matmul(attention_probs, value_layer)
345
+
346
+ context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])
347
+ context_layer = tf.reshape(
348
+ context_layer, (batch_size, -1, self.all_head_size)
349
+ ) # (batch_size, seq_len_q, all_head_size)
350
+
351
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
352
+
353
+ return outputs
354
+
355
+ def build(self, input_shape=None):
356
+ if self.built:
357
+ return
358
+ self.built = True
359
+ if getattr(self, "query", None) is not None:
360
+ with tf.name_scope(self.query.name):
361
+ self.query.build([None, None, self.config.true_hidden_size])
362
+ if getattr(self, "key", None) is not None:
363
+ with tf.name_scope(self.key.name):
364
+ self.key.build([None, None, self.config.true_hidden_size])
365
+ if getattr(self, "value", None) is not None:
366
+ with tf.name_scope(self.value.name):
367
+ self.value.build(
368
+ [
369
+ None,
370
+ None,
371
+ self.config.true_hidden_size
372
+ if self.config.use_bottleneck_attention
373
+ else self.config.hidden_size,
374
+ ]
375
+ )
376
+
377
+
378
+ class TFMobileBertSelfOutput(keras.layers.Layer):
379
+ def __init__(self, config, **kwargs):
380
+ super().__init__(**kwargs)
381
+ self.use_bottleneck = config.use_bottleneck
382
+ self.dense = keras.layers.Dense(
383
+ config.true_hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
384
+ )
385
+ self.LayerNorm = NORM2FN[config.normalization_type](
386
+ config.true_hidden_size, epsilon=config.layer_norm_eps, name="LayerNorm"
387
+ )
388
+ if not self.use_bottleneck:
389
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
390
+ self.config = config
391
+
392
+ def call(self, hidden_states, residual_tensor, training=False):
393
+ hidden_states = self.dense(hidden_states)
394
+ if not self.use_bottleneck:
395
+ hidden_states = self.dropout(hidden_states, training=training)
396
+ hidden_states = self.LayerNorm(hidden_states + residual_tensor)
397
+ return hidden_states
398
+
399
+ def build(self, input_shape=None):
400
+ if self.built:
401
+ return
402
+ self.built = True
403
+ if getattr(self, "dense", None) is not None:
404
+ with tf.name_scope(self.dense.name):
405
+ self.dense.build([None, None, self.config.true_hidden_size])
406
+ if getattr(self, "LayerNorm", None) is not None:
407
+ with tf.name_scope(self.LayerNorm.name):
408
+ self.LayerNorm.build(None)
409
+
410
+
411
+ class TFMobileBertAttention(keras.layers.Layer):
412
+ def __init__(self, config, **kwargs):
413
+ super().__init__(**kwargs)
414
+ self.self = TFMobileBertSelfAttention(config, name="self")
415
+ self.mobilebert_output = TFMobileBertSelfOutput(config, name="output")
416
+
417
+ def prune_heads(self, heads):
418
+ raise NotImplementedError
419
+
420
+ def call(
421
+ self,
422
+ query_tensor,
423
+ key_tensor,
424
+ value_tensor,
425
+ layer_input,
426
+ attention_mask,
427
+ head_mask,
428
+ output_attentions,
429
+ training=False,
430
+ ):
431
+ self_outputs = self.self(
432
+ query_tensor, key_tensor, value_tensor, attention_mask, head_mask, output_attentions, training=training
433
+ )
434
+
435
+ attention_output = self.mobilebert_output(self_outputs[0], layer_input, training=training)
436
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
437
+ return outputs
438
+
439
+ def build(self, input_shape=None):
440
+ if self.built:
441
+ return
442
+ self.built = True
443
+ if getattr(self, "self", None) is not None:
444
+ with tf.name_scope(self.self.name):
445
+ self.self.build(None)
446
+ if getattr(self, "mobilebert_output", None) is not None:
447
+ with tf.name_scope(self.mobilebert_output.name):
448
+ self.mobilebert_output.build(None)
449
+
450
+
451
+ class TFOutputBottleneck(keras.layers.Layer):
452
+ def __init__(self, config, **kwargs):
453
+ super().__init__(**kwargs)
454
+ self.dense = keras.layers.Dense(config.hidden_size, name="dense")
455
+ self.LayerNorm = NORM2FN[config.normalization_type](
456
+ config.hidden_size, epsilon=config.layer_norm_eps, name="LayerNorm"
457
+ )
458
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
459
+ self.config = config
460
+
461
+ def call(self, hidden_states, residual_tensor, training=False):
462
+ layer_outputs = self.dense(hidden_states)
463
+ layer_outputs = self.dropout(layer_outputs, training=training)
464
+ layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
465
+ return layer_outputs
466
+
467
+ def build(self, input_shape=None):
468
+ if self.built:
469
+ return
470
+ self.built = True
471
+ if getattr(self, "dense", None) is not None:
472
+ with tf.name_scope(self.dense.name):
473
+ self.dense.build([None, None, self.config.true_hidden_size])
474
+ if getattr(self, "LayerNorm", None) is not None:
475
+ with tf.name_scope(self.LayerNorm.name):
476
+ self.LayerNorm.build(None)
477
+
478
+
479
+ class TFMobileBertOutput(keras.layers.Layer):
480
+ def __init__(self, config, **kwargs):
481
+ super().__init__(**kwargs)
482
+ self.use_bottleneck = config.use_bottleneck
483
+ self.dense = keras.layers.Dense(
484
+ config.true_hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
485
+ )
486
+ self.LayerNorm = NORM2FN[config.normalization_type](
487
+ config.true_hidden_size, epsilon=config.layer_norm_eps, name="LayerNorm"
488
+ )
489
+ if not self.use_bottleneck:
490
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
491
+ else:
492
+ self.bottleneck = TFOutputBottleneck(config, name="bottleneck")
493
+ self.config = config
494
+
495
+ def call(self, hidden_states, residual_tensor_1, residual_tensor_2, training=False):
496
+ hidden_states = self.dense(hidden_states)
497
+ if not self.use_bottleneck:
498
+ hidden_states = self.dropout(hidden_states, training=training)
499
+ hidden_states = self.LayerNorm(hidden_states + residual_tensor_1)
500
+ else:
501
+ hidden_states = self.LayerNorm(hidden_states + residual_tensor_1)
502
+ hidden_states = self.bottleneck(hidden_states, residual_tensor_2)
503
+ return hidden_states
504
+
505
+ def build(self, input_shape=None):
506
+ if self.built:
507
+ return
508
+ self.built = True
509
+ if getattr(self, "dense", None) is not None:
510
+ with tf.name_scope(self.dense.name):
511
+ self.dense.build([None, None, self.config.intermediate_size])
512
+ if getattr(self, "LayerNorm", None) is not None:
513
+ with tf.name_scope(self.LayerNorm.name):
514
+ self.LayerNorm.build(None)
515
+ if getattr(self, "bottleneck", None) is not None:
516
+ with tf.name_scope(self.bottleneck.name):
517
+ self.bottleneck.build(None)
518
+
519
+
520
+ class TFBottleneckLayer(keras.layers.Layer):
521
+ def __init__(self, config, **kwargs):
522
+ super().__init__(**kwargs)
523
+ self.dense = keras.layers.Dense(config.intra_bottleneck_size, name="dense")
524
+ self.LayerNorm = NORM2FN[config.normalization_type](
525
+ config.intra_bottleneck_size, epsilon=config.layer_norm_eps, name="LayerNorm"
526
+ )
527
+ self.config = config
528
+
529
+ def call(self, inputs):
530
+ hidden_states = self.dense(inputs)
531
+ hidden_states = self.LayerNorm(hidden_states)
532
+ return hidden_states
533
+
534
+ def build(self, input_shape=None):
535
+ if self.built:
536
+ return
537
+ self.built = True
538
+ if getattr(self, "dense", None) is not None:
539
+ with tf.name_scope(self.dense.name):
540
+ self.dense.build([None, None, self.config.hidden_size])
541
+ if getattr(self, "LayerNorm", None) is not None:
542
+ with tf.name_scope(self.LayerNorm.name):
543
+ self.LayerNorm.build(None)
544
+
545
+
546
+ class TFBottleneck(keras.layers.Layer):
547
+ def __init__(self, config, **kwargs):
548
+ super().__init__(**kwargs)
549
+ self.key_query_shared_bottleneck = config.key_query_shared_bottleneck
550
+ self.use_bottleneck_attention = config.use_bottleneck_attention
551
+ self.bottleneck_input = TFBottleneckLayer(config, name="input")
552
+ if self.key_query_shared_bottleneck:
553
+ self.attention = TFBottleneckLayer(config, name="attention")
554
+
555
+ def call(self, hidden_states):
556
+ # This method can return three different tuples of values. These different values make use of bottlenecks,
557
+ # which are linear layers used to project the hidden states to a lower-dimensional vector, reducing memory
558
+ # usage. These linear layer have weights that are learned during training.
559
+ #
560
+ # If `config.use_bottleneck_attention`, it will return the result of the bottleneck layer four times for the
561
+ # key, query, value, and "layer input" to be used by the attention layer.
562
+ # This bottleneck is used to project the hidden. This last layer input will be used as a residual tensor
563
+ # in the attention self output, after the attention scores have been computed.
564
+ #
565
+ # If not `config.use_bottleneck_attention` and `config.key_query_shared_bottleneck`, this will return
566
+ # four values, three of which have been passed through a bottleneck: the query and key, passed through the same
567
+ # bottleneck, and the residual layer to be applied in the attention self output, through another bottleneck.
568
+ #
569
+ # Finally, in the last case, the values for the query, key and values are the hidden states without bottleneck,
570
+ # and the residual layer will be this value passed through a bottleneck.
571
+
572
+ bottlenecked_hidden_states = self.bottleneck_input(hidden_states)
573
+ if self.use_bottleneck_attention:
574
+ return (bottlenecked_hidden_states,) * 4
575
+ elif self.key_query_shared_bottleneck:
576
+ shared_attention_input = self.attention(hidden_states)
577
+ return (shared_attention_input, shared_attention_input, hidden_states, bottlenecked_hidden_states)
578
+ else:
579
+ return (hidden_states, hidden_states, hidden_states, bottlenecked_hidden_states)
580
+
581
+ def build(self, input_shape=None):
582
+ if self.built:
583
+ return
584
+ self.built = True
585
+ if getattr(self, "bottleneck_input", None) is not None:
586
+ with tf.name_scope(self.bottleneck_input.name):
587
+ self.bottleneck_input.build(None)
588
+ if getattr(self, "attention", None) is not None:
589
+ with tf.name_scope(self.attention.name):
590
+ self.attention.build(None)
591
+
592
+
593
+ class TFFFNOutput(keras.layers.Layer):
594
+ def __init__(self, config, **kwargs):
595
+ super().__init__(**kwargs)
596
+ self.dense = keras.layers.Dense(config.true_hidden_size, name="dense")
597
+ self.LayerNorm = NORM2FN[config.normalization_type](
598
+ config.true_hidden_size, epsilon=config.layer_norm_eps, name="LayerNorm"
599
+ )
600
+ self.config = config
601
+
602
+ def call(self, hidden_states, residual_tensor):
603
+ hidden_states = self.dense(hidden_states)
604
+ hidden_states = self.LayerNorm(hidden_states + residual_tensor)
605
+ return hidden_states
606
+
607
+ def build(self, input_shape=None):
608
+ if self.built:
609
+ return
610
+ self.built = True
611
+ if getattr(self, "dense", None) is not None:
612
+ with tf.name_scope(self.dense.name):
613
+ self.dense.build([None, None, self.config.intermediate_size])
614
+ if getattr(self, "LayerNorm", None) is not None:
615
+ with tf.name_scope(self.LayerNorm.name):
616
+ self.LayerNorm.build(None)
617
+
618
+
619
+ class TFFFNLayer(keras.layers.Layer):
620
+ def __init__(self, config, **kwargs):
621
+ super().__init__(**kwargs)
622
+ self.intermediate = TFMobileBertIntermediate(config, name="intermediate")
623
+ self.mobilebert_output = TFFFNOutput(config, name="output")
624
+
625
+ def call(self, hidden_states):
626
+ intermediate_output = self.intermediate(hidden_states)
627
+ layer_outputs = self.mobilebert_output(intermediate_output, hidden_states)
628
+ return layer_outputs
629
+
630
+ def build(self, input_shape=None):
631
+ if self.built:
632
+ return
633
+ self.built = True
634
+ if getattr(self, "intermediate", None) is not None:
635
+ with tf.name_scope(self.intermediate.name):
636
+ self.intermediate.build(None)
637
+ if getattr(self, "mobilebert_output", None) is not None:
638
+ with tf.name_scope(self.mobilebert_output.name):
639
+ self.mobilebert_output.build(None)
640
+
641
+
642
+ class TFMobileBertLayer(keras.layers.Layer):
643
+ def __init__(self, config, **kwargs):
644
+ super().__init__(**kwargs)
645
+ self.use_bottleneck = config.use_bottleneck
646
+ self.num_feedforward_networks = config.num_feedforward_networks
647
+ self.attention = TFMobileBertAttention(config, name="attention")
648
+ self.intermediate = TFMobileBertIntermediate(config, name="intermediate")
649
+ self.mobilebert_output = TFMobileBertOutput(config, name="output")
650
+
651
+ if self.use_bottleneck:
652
+ self.bottleneck = TFBottleneck(config, name="bottleneck")
653
+ if config.num_feedforward_networks > 1:
654
+ self.ffn = [TFFFNLayer(config, name=f"ffn.{i}") for i in range(config.num_feedforward_networks - 1)]
655
+
656
+ def call(self, hidden_states, attention_mask, head_mask, output_attentions, training=False):
657
+ if self.use_bottleneck:
658
+ query_tensor, key_tensor, value_tensor, layer_input = self.bottleneck(hidden_states)
659
+ else:
660
+ query_tensor, key_tensor, value_tensor, layer_input = [hidden_states] * 4
661
+
662
+ attention_outputs = self.attention(
663
+ query_tensor,
664
+ key_tensor,
665
+ value_tensor,
666
+ layer_input,
667
+ attention_mask,
668
+ head_mask,
669
+ output_attentions,
670
+ training=training,
671
+ )
672
+
673
+ attention_output = attention_outputs[0]
674
+ s = (attention_output,)
675
+
676
+ if self.num_feedforward_networks != 1:
677
+ for i, ffn_module in enumerate(self.ffn):
678
+ attention_output = ffn_module(attention_output)
679
+ s += (attention_output,)
680
+
681
+ intermediate_output = self.intermediate(attention_output)
682
+ layer_output = self.mobilebert_output(intermediate_output, attention_output, hidden_states, training=training)
683
+
684
+ outputs = (
685
+ (layer_output,)
686
+ + attention_outputs[1:]
687
+ + (
688
+ tf.constant(0),
689
+ query_tensor,
690
+ key_tensor,
691
+ value_tensor,
692
+ layer_input,
693
+ attention_output,
694
+ intermediate_output,
695
+ )
696
+ + s
697
+ ) # add attentions if we output them
698
+
699
+ return outputs
700
+
701
+ def build(self, input_shape=None):
702
+ if self.built:
703
+ return
704
+ self.built = True
705
+ if getattr(self, "attention", None) is not None:
706
+ with tf.name_scope(self.attention.name):
707
+ self.attention.build(None)
708
+ if getattr(self, "intermediate", None) is not None:
709
+ with tf.name_scope(self.intermediate.name):
710
+ self.intermediate.build(None)
711
+ if getattr(self, "mobilebert_output", None) is not None:
712
+ with tf.name_scope(self.mobilebert_output.name):
713
+ self.mobilebert_output.build(None)
714
+ if getattr(self, "bottleneck", None) is not None:
715
+ with tf.name_scope(self.bottleneck.name):
716
+ self.bottleneck.build(None)
717
+ if getattr(self, "ffn", None) is not None:
718
+ for layer in self.ffn:
719
+ with tf.name_scope(layer.name):
720
+ layer.build(None)
721
+
722
+
723
+ class TFMobileBertEncoder(keras.layers.Layer):
724
+ def __init__(self, config, **kwargs):
725
+ super().__init__(**kwargs)
726
+ self.output_attentions = config.output_attentions
727
+ self.output_hidden_states = config.output_hidden_states
728
+ self.layer = [TFMobileBertLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
729
+
730
+ def call(
731
+ self,
732
+ hidden_states,
733
+ attention_mask,
734
+ head_mask,
735
+ output_attentions,
736
+ output_hidden_states,
737
+ return_dict,
738
+ training=False,
739
+ ):
740
+ all_hidden_states = () if output_hidden_states else None
741
+ all_attentions = () if output_attentions else None
742
+ for i, layer_module in enumerate(self.layer):
743
+ if output_hidden_states:
744
+ all_hidden_states = all_hidden_states + (hidden_states,)
745
+
746
+ layer_outputs = layer_module(
747
+ hidden_states, attention_mask, head_mask[i], output_attentions, training=training
748
+ )
749
+
750
+ hidden_states = layer_outputs[0]
751
+
752
+ if output_attentions:
753
+ all_attentions = all_attentions + (layer_outputs[1],)
754
+
755
+ # Add last layer
756
+ if output_hidden_states:
757
+ all_hidden_states = all_hidden_states + (hidden_states,)
758
+
759
+ if not return_dict:
760
+ return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
761
+ return TFBaseModelOutput(
762
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
763
+ )
764
+
765
+ def build(self, input_shape=None):
766
+ if self.built:
767
+ return
768
+ self.built = True
769
+ if getattr(self, "layer", None) is not None:
770
+ for layer in self.layer:
771
+ with tf.name_scope(layer.name):
772
+ layer.build(None)
773
+
774
+
775
+ class TFMobileBertPooler(keras.layers.Layer):
776
+ def __init__(self, config, **kwargs):
777
+ super().__init__(**kwargs)
778
+ self.do_activate = config.classifier_activation
779
+ if self.do_activate:
780
+ self.dense = keras.layers.Dense(
781
+ config.hidden_size,
782
+ kernel_initializer=get_initializer(config.initializer_range),
783
+ activation="tanh",
784
+ name="dense",
785
+ )
786
+ self.config = config
787
+
788
+ def call(self, hidden_states):
789
+ # We "pool" the model by simply taking the hidden state corresponding
790
+ # to the first token.
791
+ first_token_tensor = hidden_states[:, 0]
792
+ if not self.do_activate:
793
+ return first_token_tensor
794
+ else:
795
+ pooled_output = self.dense(first_token_tensor)
796
+ return pooled_output
797
+
798
+ def build(self, input_shape=None):
799
+ if self.built:
800
+ return
801
+ self.built = True
802
+ if getattr(self, "dense", None) is not None:
803
+ with tf.name_scope(self.dense.name):
804
+ self.dense.build([None, None, self.config.hidden_size])
805
+
806
+
807
+ class TFMobileBertPredictionHeadTransform(keras.layers.Layer):
808
+ def __init__(self, config, **kwargs):
809
+ super().__init__(**kwargs)
810
+ self.dense = keras.layers.Dense(
811
+ config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
812
+ )
813
+ if isinstance(config.hidden_act, str):
814
+ self.transform_act_fn = get_tf_activation(config.hidden_act)
815
+ else:
816
+ self.transform_act_fn = config.hidden_act
817
+ self.LayerNorm = NORM2FN["layer_norm"](config.hidden_size, epsilon=config.layer_norm_eps, name="LayerNorm")
818
+ self.config = config
819
+
820
+ def call(self, hidden_states):
821
+ hidden_states = self.dense(hidden_states)
822
+ hidden_states = self.transform_act_fn(hidden_states)
823
+ hidden_states = self.LayerNorm(hidden_states)
824
+ return hidden_states
825
+
826
+ def build(self, input_shape=None):
827
+ if self.built:
828
+ return
829
+ self.built = True
830
+ if getattr(self, "dense", None) is not None:
831
+ with tf.name_scope(self.dense.name):
832
+ self.dense.build([None, None, self.config.hidden_size])
833
+ if getattr(self, "LayerNorm", None) is not None:
834
+ with tf.name_scope(self.LayerNorm.name):
835
+ self.LayerNorm.build(None)
836
+
837
+
838
+ class TFMobileBertLMPredictionHead(keras.layers.Layer):
839
+ def __init__(self, config, **kwargs):
840
+ super().__init__(**kwargs)
841
+ self.transform = TFMobileBertPredictionHeadTransform(config, name="transform")
842
+ self.config = config
843
+
844
+ def build(self, input_shape=None):
845
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
846
+ self.dense = self.add_weight(
847
+ shape=(self.config.hidden_size - self.config.embedding_size, self.config.vocab_size),
848
+ initializer="zeros",
849
+ trainable=True,
850
+ name="dense/weight",
851
+ )
852
+ self.decoder = self.add_weight(
853
+ shape=(self.config.vocab_size, self.config.embedding_size),
854
+ initializer="zeros",
855
+ trainable=True,
856
+ name="decoder/weight",
857
+ )
858
+
859
+ if self.built:
860
+ return
861
+ self.built = True
862
+ if getattr(self, "transform", None) is not None:
863
+ with tf.name_scope(self.transform.name):
864
+ self.transform.build(None)
865
+
866
+ def get_output_embeddings(self):
867
+ return self
868
+
869
+ def set_output_embeddings(self, value):
870
+ self.decoder = value
871
+ self.config.vocab_size = shape_list(value)[0]
872
+
873
+ def get_bias(self):
874
+ return {"bias": self.bias}
875
+
876
+ def set_bias(self, value):
877
+ self.bias = value["bias"]
878
+ self.config.vocab_size = shape_list(value["bias"])[0]
879
+
880
+ def call(self, hidden_states):
881
+ hidden_states = self.transform(hidden_states)
882
+ hidden_states = tf.matmul(hidden_states, tf.concat([tf.transpose(self.decoder), self.dense], axis=0))
883
+ hidden_states = hidden_states + self.bias
884
+ return hidden_states
885
+
886
+
887
+ class TFMobileBertMLMHead(keras.layers.Layer):
888
+ def __init__(self, config, **kwargs):
889
+ super().__init__(**kwargs)
890
+ self.predictions = TFMobileBertLMPredictionHead(config, name="predictions")
891
+
892
+ def call(self, sequence_output):
893
+ prediction_scores = self.predictions(sequence_output)
894
+ return prediction_scores
895
+
896
+ def build(self, input_shape=None):
897
+ if self.built:
898
+ return
899
+ self.built = True
900
+ if getattr(self, "predictions", None) is not None:
901
+ with tf.name_scope(self.predictions.name):
902
+ self.predictions.build(None)
903
+
904
+
905
+ @keras_serializable
906
+ class TFMobileBertMainLayer(keras.layers.Layer):
907
+ config_class = MobileBertConfig
908
+
909
+ def __init__(self, config, add_pooling_layer=True, **kwargs):
910
+ super().__init__(**kwargs)
911
+
912
+ self.config = config
913
+ self.num_hidden_layers = config.num_hidden_layers
914
+ self.output_attentions = config.output_attentions
915
+ self.output_hidden_states = config.output_hidden_states
916
+ self.return_dict = config.use_return_dict
917
+
918
+ self.embeddings = TFMobileBertEmbeddings(config, name="embeddings")
919
+ self.encoder = TFMobileBertEncoder(config, name="encoder")
920
+ self.pooler = TFMobileBertPooler(config, name="pooler") if add_pooling_layer else None
921
+
922
+ def get_input_embeddings(self):
923
+ return self.embeddings
924
+
925
+ def set_input_embeddings(self, value):
926
+ self.embeddings.weight = value
927
+ self.embeddings.vocab_size = shape_list(value)[0]
928
+
929
+ def _prune_heads(self, heads_to_prune):
930
+ """
931
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
932
+ class PreTrainedModel
933
+ """
934
+ raise NotImplementedError
935
+
936
+ @unpack_inputs
937
+ def call(
938
+ self,
939
+ input_ids=None,
940
+ attention_mask=None,
941
+ token_type_ids=None,
942
+ position_ids=None,
943
+ head_mask=None,
944
+ inputs_embeds=None,
945
+ output_attentions=None,
946
+ output_hidden_states=None,
947
+ return_dict=None,
948
+ training=False,
949
+ ):
950
+ if input_ids is not None and inputs_embeds is not None:
951
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
952
+ elif input_ids is not None:
953
+ input_shape = shape_list(input_ids)
954
+ elif inputs_embeds is not None:
955
+ input_shape = shape_list(inputs_embeds)[:-1]
956
+ else:
957
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
958
+
959
+ if attention_mask is None:
960
+ attention_mask = tf.fill(input_shape, 1)
961
+
962
+ if token_type_ids is None:
963
+ token_type_ids = tf.fill(input_shape, 0)
964
+
965
+ embedding_output = self.embeddings(input_ids, position_ids, token_type_ids, inputs_embeds, training=training)
966
+
967
+ # We create a 3D attention mask from a 2D tensor mask.
968
+ # Sizes are [batch_size, 1, 1, to_seq_length]
969
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
970
+ # this attention mask is more simple than the triangular masking of causal attention
971
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
972
+ extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))
973
+
974
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
975
+ # masked positions, this operation will create a tensor which is 0.0 for
976
+ # positions we want to attend and -10000.0 for masked positions.
977
+ # Since we are adding it to the raw scores before the softmax, this is
978
+ # effectively the same as removing these entirely.
979
+ extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)
980
+ one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
981
+ ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
982
+ extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
983
+
984
+ # Prepare head mask if needed
985
+ # 1.0 in head_mask indicate we keep the head
986
+ # attention_probs has shape bsz x n_heads x N x N
987
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
988
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
989
+ if head_mask is not None:
990
+ raise NotImplementedError
991
+ else:
992
+ head_mask = [None] * self.num_hidden_layers
993
+
994
+ encoder_outputs = self.encoder(
995
+ embedding_output,
996
+ extended_attention_mask,
997
+ head_mask,
998
+ output_attentions,
999
+ output_hidden_states,
1000
+ return_dict,
1001
+ training=training,
1002
+ )
1003
+
1004
+ sequence_output = encoder_outputs[0]
1005
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1006
+
1007
+ if not return_dict:
1008
+ return (
1009
+ sequence_output,
1010
+ pooled_output,
1011
+ ) + encoder_outputs[1:]
1012
+
1013
+ return TFBaseModelOutputWithPooling(
1014
+ last_hidden_state=sequence_output,
1015
+ pooler_output=pooled_output,
1016
+ hidden_states=encoder_outputs.hidden_states,
1017
+ attentions=encoder_outputs.attentions,
1018
+ )
1019
+
1020
+ def build(self, input_shape=None):
1021
+ if self.built:
1022
+ return
1023
+ self.built = True
1024
+ if getattr(self, "embeddings", None) is not None:
1025
+ with tf.name_scope(self.embeddings.name):
1026
+ self.embeddings.build(None)
1027
+ if getattr(self, "encoder", None) is not None:
1028
+ with tf.name_scope(self.encoder.name):
1029
+ self.encoder.build(None)
1030
+ if getattr(self, "pooler", None) is not None:
1031
+ with tf.name_scope(self.pooler.name):
1032
+ self.pooler.build(None)
1033
+
1034
+
1035
+ class TFMobileBertPreTrainedModel(TFPreTrainedModel):
1036
+ """
1037
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1038
+ models.
1039
+ """
1040
+
1041
+ config_class = MobileBertConfig
1042
+ base_model_prefix = "mobilebert"
1043
+
1044
+
1045
+ @dataclass
1046
+ class TFMobileBertForPreTrainingOutput(ModelOutput):
1047
+ """
1048
+ Output type of [`TFMobileBertForPreTraining`].
1049
+
1050
+ Args:
1051
+ prediction_logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
1052
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
1053
+ seq_relationship_logits (`tf.Tensor` of shape `(batch_size, 2)`):
1054
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
1055
+ before SoftMax).
1056
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1057
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
1058
+ `(batch_size, sequence_length, hidden_size)`.
1059
+
1060
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
1061
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
1062
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
1063
+ sequence_length)`.
1064
+
1065
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
1066
+ heads.
1067
+ """
1068
+
1069
+ loss: tf.Tensor | None = None
1070
+ prediction_logits: tf.Tensor = None
1071
+ seq_relationship_logits: tf.Tensor = None
1072
+ hidden_states: Tuple[tf.Tensor] | None = None
1073
+ attentions: Tuple[tf.Tensor] | None = None
1074
+
1075
+
1076
+ MOBILEBERT_START_DOCSTRING = r"""
1077
+
1078
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
1079
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1080
+ etc.)
1081
+
1082
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
1083
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
1084
+ behavior.
1085
+
1086
+ <Tip>
1087
+
1088
+ TensorFlow models and layers in `transformers` accept two formats as input:
1089
+
1090
+ - having all inputs as keyword arguments (like PyTorch models), or
1091
+ - having all inputs as a list, tuple or dict in the first positional argument.
1092
+
1093
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
1094
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
1095
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
1096
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
1097
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
1098
+ positional argument:
1099
+
1100
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
1101
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
1102
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
1103
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
1104
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
1105
+
1106
+ Note that when creating models and layers with
1107
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
1108
+ about any of this, as you can just pass inputs like you would to any other Python function!
1109
+
1110
+ </Tip>
1111
+
1112
+ Parameters:
1113
+ config ([`MobileBertConfig`]): Model configuration class with all the parameters of the model.
1114
+ Initializing with a config file does not load the weights associated with the model, only the
1115
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1116
+ """
1117
+
1118
+ MOBILEBERT_INPUTS_DOCSTRING = r"""
1119
+ Args:
1120
+ input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
1121
+ Indices of input sequence tokens in the vocabulary.
1122
+
1123
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
1124
+ [`PreTrainedTokenizer.encode`] for details.
1125
+
1126
+ [What are input IDs?](../glossary#input-ids)
1127
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
1128
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1129
+
1130
+ - 1 for tokens that are **not masked**,
1131
+ - 0 for tokens that are **masked**.
1132
+
1133
+ [What are attention masks?](../glossary#attention-mask)
1134
+ token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
1135
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1136
+ 1]`:
1137
+
1138
+ - 0 corresponds to a *sentence A* token,
1139
+ - 1 corresponds to a *sentence B* token.
1140
+
1141
+ [What are token type IDs?](../glossary#token-type-ids)
1142
+ position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
1143
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1144
+ config.max_position_embeddings - 1]`.
1145
+
1146
+ [What are position IDs?](../glossary#position-ids)
1147
+ head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1148
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
1149
+
1150
+ - 1 indicates the head is **not masked**,
1151
+ - 0 indicates the head is **masked**.
1152
+
1153
+ inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
1154
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1155
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1156
+ model's internal embedding lookup matrix.
1157
+ output_attentions (`bool`, *optional*):
1158
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1159
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
1160
+ config will be used instead.
1161
+ output_hidden_states (`bool`, *optional*):
1162
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1163
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
1164
+ used instead.
1165
+ return_dict (`bool`, *optional*):
1166
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
1167
+ eager mode, in graph mode the value will always be set to True.
1168
+ training (`bool`, *optional*, defaults to `False`):
1169
+ Whether or not to use the model in training mode (some modules like dropout modules have different
1170
+ behaviors between training and evaluation).
1171
+ """
1172
+
1173
+
1174
+ @add_start_docstrings(
1175
+ "The bare MobileBert Model transformer outputting raw hidden-states without any specific head on top.",
1176
+ MOBILEBERT_START_DOCSTRING,
1177
+ )
1178
+ class TFMobileBertModel(TFMobileBertPreTrainedModel):
1179
+ def __init__(self, config, *inputs, **kwargs):
1180
+ super().__init__(config, *inputs, **kwargs)
1181
+ self.mobilebert = TFMobileBertMainLayer(config, name="mobilebert")
1182
+
1183
+ @unpack_inputs
1184
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1185
+ @add_code_sample_docstrings(
1186
+ checkpoint=_CHECKPOINT_FOR_DOC,
1187
+ output_type=TFBaseModelOutputWithPooling,
1188
+ config_class=_CONFIG_FOR_DOC,
1189
+ )
1190
+ def call(
1191
+ self,
1192
+ input_ids: TFModelInputType | None = None,
1193
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1194
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1195
+ position_ids: np.ndarray | tf.Tensor | None = None,
1196
+ head_mask: np.ndarray | tf.Tensor | None = None,
1197
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1198
+ output_attentions: Optional[bool] = None,
1199
+ output_hidden_states: Optional[bool] = None,
1200
+ return_dict: Optional[bool] = None,
1201
+ training: Optional[bool] = False,
1202
+ ) -> Union[Tuple, TFBaseModelOutputWithPooling]:
1203
+ outputs = self.mobilebert(
1204
+ input_ids=input_ids,
1205
+ attention_mask=attention_mask,
1206
+ token_type_ids=token_type_ids,
1207
+ position_ids=position_ids,
1208
+ head_mask=head_mask,
1209
+ inputs_embeds=inputs_embeds,
1210
+ output_attentions=output_attentions,
1211
+ output_hidden_states=output_hidden_states,
1212
+ return_dict=return_dict,
1213
+ training=training,
1214
+ )
1215
+
1216
+ return outputs
1217
+
1218
+ def build(self, input_shape=None):
1219
+ if self.built:
1220
+ return
1221
+ self.built = True
1222
+ if getattr(self, "mobilebert", None) is not None:
1223
+ with tf.name_scope(self.mobilebert.name):
1224
+ self.mobilebert.build(None)
1225
+
1226
+
1227
+ @add_start_docstrings(
1228
+ """
1229
+ MobileBert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
1230
+ `next sentence prediction (classification)` head.
1231
+ """,
1232
+ MOBILEBERT_START_DOCSTRING,
1233
+ )
1234
+ class TFMobileBertForPreTraining(TFMobileBertPreTrainedModel, TFMobileBertPreTrainingLoss):
1235
+ def __init__(self, config, *inputs, **kwargs):
1236
+ super().__init__(config, *inputs, **kwargs)
1237
+ self.mobilebert = TFMobileBertMainLayer(config, name="mobilebert")
1238
+ self.predictions = TFMobileBertMLMHead(config, name="predictions___cls")
1239
+ self.seq_relationship = TFMobileBertOnlyNSPHead(config, name="seq_relationship___cls")
1240
+
1241
+ def get_lm_head(self):
1242
+ return self.predictions.predictions
1243
+
1244
+ def get_prefix_bias_name(self):
1245
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
1246
+ return self.name + "/" + self.predictions.name + "/" + self.predictions.predictions.name
1247
+
1248
+ @unpack_inputs
1249
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1250
+ @replace_return_docstrings(output_type=TFMobileBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1251
+ def call(
1252
+ self,
1253
+ input_ids: TFModelInputType | None = None,
1254
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1255
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1256
+ position_ids: np.ndarray | tf.Tensor | None = None,
1257
+ head_mask: np.ndarray | tf.Tensor | None = None,
1258
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1259
+ output_attentions: Optional[bool] = None,
1260
+ output_hidden_states: Optional[bool] = None,
1261
+ return_dict: Optional[bool] = None,
1262
+ labels: np.ndarray | tf.Tensor | None = None,
1263
+ next_sentence_label: np.ndarray | tf.Tensor | None = None,
1264
+ training: Optional[bool] = False,
1265
+ ) -> Union[Tuple, TFMobileBertForPreTrainingOutput]:
1266
+ r"""
1267
+ Return:
1268
+
1269
+ Examples:
1270
+
1271
+ ```python
1272
+ >>> import tensorflow as tf
1273
+ >>> from transformers import AutoTokenizer, TFMobileBertForPreTraining
1274
+
1275
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mobilebert-uncased")
1276
+ >>> model = TFMobileBertForPreTraining.from_pretrained("google/mobilebert-uncased")
1277
+ >>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute"))[None, :] # Batch size 1
1278
+ >>> outputs = model(input_ids)
1279
+ >>> prediction_scores, seq_relationship_scores = outputs[:2]
1280
+ ```"""
1281
+ outputs = self.mobilebert(
1282
+ input_ids,
1283
+ attention_mask=attention_mask,
1284
+ token_type_ids=token_type_ids,
1285
+ position_ids=position_ids,
1286
+ head_mask=head_mask,
1287
+ inputs_embeds=inputs_embeds,
1288
+ output_attentions=output_attentions,
1289
+ output_hidden_states=output_hidden_states,
1290
+ return_dict=return_dict,
1291
+ training=training,
1292
+ )
1293
+
1294
+ sequence_output, pooled_output = outputs[:2]
1295
+ prediction_scores = self.predictions(sequence_output)
1296
+ seq_relationship_score = self.seq_relationship(pooled_output)
1297
+
1298
+ total_loss = None
1299
+ if labels is not None and next_sentence_label is not None:
1300
+ d_labels = {"labels": labels}
1301
+ d_labels["next_sentence_label"] = next_sentence_label
1302
+ total_loss = self.hf_compute_loss(labels=d_labels, logits=(prediction_scores, seq_relationship_score))
1303
+
1304
+ if not return_dict:
1305
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1306
+ return ((total_loss,) + output) if total_loss is not None else output
1307
+
1308
+ return TFMobileBertForPreTrainingOutput(
1309
+ loss=total_loss,
1310
+ prediction_logits=prediction_scores,
1311
+ seq_relationship_logits=seq_relationship_score,
1312
+ hidden_states=outputs.hidden_states,
1313
+ attentions=outputs.attentions,
1314
+ )
1315
+
1316
+ def build(self, input_shape=None):
1317
+ if self.built:
1318
+ return
1319
+ self.built = True
1320
+ if getattr(self, "mobilebert", None) is not None:
1321
+ with tf.name_scope(self.mobilebert.name):
1322
+ self.mobilebert.build(None)
1323
+ if getattr(self, "predictions", None) is not None:
1324
+ with tf.name_scope(self.predictions.name):
1325
+ self.predictions.build(None)
1326
+ if getattr(self, "seq_relationship", None) is not None:
1327
+ with tf.name_scope(self.seq_relationship.name):
1328
+ self.seq_relationship.build(None)
1329
+
1330
+ def tf_to_pt_weight_rename(self, tf_weight):
1331
+ if tf_weight == "cls.predictions.decoder.weight":
1332
+ return tf_weight, "mobilebert.embeddings.word_embeddings.weight"
1333
+ else:
1334
+ return (tf_weight,)
1335
+
1336
+
1337
+ @add_start_docstrings("""MobileBert Model with a `language modeling` head on top.""", MOBILEBERT_START_DOCSTRING)
1338
+ class TFMobileBertForMaskedLM(TFMobileBertPreTrainedModel, TFMaskedLanguageModelingLoss):
1339
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1340
+ _keys_to_ignore_on_load_unexpected = [
1341
+ r"pooler",
1342
+ r"seq_relationship___cls",
1343
+ r"cls.seq_relationship",
1344
+ ]
1345
+
1346
+ def __init__(self, config, *inputs, **kwargs):
1347
+ super().__init__(config, *inputs, **kwargs)
1348
+
1349
+ self.mobilebert = TFMobileBertMainLayer(config, add_pooling_layer=False, name="mobilebert")
1350
+ self.predictions = TFMobileBertMLMHead(config, name="predictions___cls")
1351
+
1352
+ def get_lm_head(self):
1353
+ return self.predictions.predictions
1354
+
1355
+ def get_prefix_bias_name(self):
1356
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
1357
+ return self.name + "/" + self.mlm.name + "/" + self.mlm.predictions.name
1358
+
1359
+ @unpack_inputs
1360
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1361
+ @add_code_sample_docstrings(
1362
+ checkpoint=_CHECKPOINT_FOR_DOC,
1363
+ output_type=TFMaskedLMOutput,
1364
+ config_class=_CONFIG_FOR_DOC,
1365
+ expected_output="'paris'",
1366
+ expected_loss=0.57,
1367
+ )
1368
+ def call(
1369
+ self,
1370
+ input_ids: TFModelInputType | None = None,
1371
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1372
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1373
+ position_ids: np.ndarray | tf.Tensor | None = None,
1374
+ head_mask: np.ndarray | tf.Tensor | None = None,
1375
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1376
+ output_attentions: Optional[bool] = None,
1377
+ output_hidden_states: Optional[bool] = None,
1378
+ return_dict: Optional[bool] = None,
1379
+ labels: np.ndarray | tf.Tensor | None = None,
1380
+ training: Optional[bool] = False,
1381
+ ) -> Union[Tuple, TFMaskedLMOutput]:
1382
+ r"""
1383
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1384
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1385
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1386
+ loss is only computed for the tokens with labels
1387
+ """
1388
+ outputs = self.mobilebert(
1389
+ input_ids,
1390
+ attention_mask=attention_mask,
1391
+ token_type_ids=token_type_ids,
1392
+ position_ids=position_ids,
1393
+ head_mask=head_mask,
1394
+ inputs_embeds=inputs_embeds,
1395
+ output_attentions=output_attentions,
1396
+ output_hidden_states=output_hidden_states,
1397
+ return_dict=return_dict,
1398
+ training=training,
1399
+ )
1400
+ sequence_output = outputs[0]
1401
+ prediction_scores = self.predictions(sequence_output, training=training)
1402
+
1403
+ loss = None if labels is None else self.hf_compute_loss(labels, prediction_scores)
1404
+
1405
+ if not return_dict:
1406
+ output = (prediction_scores,) + outputs[2:]
1407
+ return ((loss,) + output) if loss is not None else output
1408
+
1409
+ return TFMaskedLMOutput(
1410
+ loss=loss,
1411
+ logits=prediction_scores,
1412
+ hidden_states=outputs.hidden_states,
1413
+ attentions=outputs.attentions,
1414
+ )
1415
+
1416
+ def build(self, input_shape=None):
1417
+ if self.built:
1418
+ return
1419
+ self.built = True
1420
+ if getattr(self, "mobilebert", None) is not None:
1421
+ with tf.name_scope(self.mobilebert.name):
1422
+ self.mobilebert.build(None)
1423
+ if getattr(self, "predictions", None) is not None:
1424
+ with tf.name_scope(self.predictions.name):
1425
+ self.predictions.build(None)
1426
+
1427
+ def tf_to_pt_weight_rename(self, tf_weight):
1428
+ if tf_weight == "cls.predictions.decoder.weight":
1429
+ return tf_weight, "mobilebert.embeddings.word_embeddings.weight"
1430
+ else:
1431
+ return (tf_weight,)
1432
+
1433
+
1434
+ class TFMobileBertOnlyNSPHead(keras.layers.Layer):
1435
+ def __init__(self, config, **kwargs):
1436
+ super().__init__(**kwargs)
1437
+ self.seq_relationship = keras.layers.Dense(2, name="seq_relationship")
1438
+ self.config = config
1439
+
1440
+ def call(self, pooled_output):
1441
+ seq_relationship_score = self.seq_relationship(pooled_output)
1442
+ return seq_relationship_score
1443
+
1444
+ def build(self, input_shape=None):
1445
+ if self.built:
1446
+ return
1447
+ self.built = True
1448
+ if getattr(self, "seq_relationship", None) is not None:
1449
+ with tf.name_scope(self.seq_relationship.name):
1450
+ self.seq_relationship.build([None, None, self.config.hidden_size])
1451
+
1452
+
1453
+ @add_start_docstrings(
1454
+ """MobileBert Model with a `next sentence prediction (classification)` head on top.""",
1455
+ MOBILEBERT_START_DOCSTRING,
1456
+ )
1457
+ class TFMobileBertForNextSentencePrediction(TFMobileBertPreTrainedModel, TFNextSentencePredictionLoss):
1458
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1459
+ _keys_to_ignore_on_load_unexpected = [r"predictions___cls", r"cls.predictions"]
1460
+
1461
+ def __init__(self, config, *inputs, **kwargs):
1462
+ super().__init__(config, *inputs, **kwargs)
1463
+
1464
+ self.mobilebert = TFMobileBertMainLayer(config, name="mobilebert")
1465
+ self.cls = TFMobileBertOnlyNSPHead(config, name="seq_relationship___cls")
1466
+
1467
+ @unpack_inputs
1468
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1469
+ @replace_return_docstrings(output_type=TFNextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
1470
+ def call(
1471
+ self,
1472
+ input_ids: TFModelInputType | None = None,
1473
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1474
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1475
+ position_ids: np.ndarray | tf.Tensor | None = None,
1476
+ head_mask: np.ndarray | tf.Tensor | None = None,
1477
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1478
+ output_attentions: Optional[bool] = None,
1479
+ output_hidden_states: Optional[bool] = None,
1480
+ return_dict: Optional[bool] = None,
1481
+ next_sentence_label: np.ndarray | tf.Tensor | None = None,
1482
+ training: Optional[bool] = False,
1483
+ ) -> Union[Tuple, TFNextSentencePredictorOutput]:
1484
+ r"""
1485
+ Return:
1486
+
1487
+ Examples:
1488
+
1489
+ ```python
1490
+ >>> import tensorflow as tf
1491
+ >>> from transformers import AutoTokenizer, TFMobileBertForNextSentencePrediction
1492
+
1493
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mobilebert-uncased")
1494
+ >>> model = TFMobileBertForNextSentencePrediction.from_pretrained("google/mobilebert-uncased")
1495
+
1496
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1497
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1498
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="tf")
1499
+
1500
+ >>> logits = model(encoding["input_ids"], token_type_ids=encoding["token_type_ids"])[0]
1501
+ ```"""
1502
+ outputs = self.mobilebert(
1503
+ input_ids,
1504
+ attention_mask=attention_mask,
1505
+ token_type_ids=token_type_ids,
1506
+ position_ids=position_ids,
1507
+ head_mask=head_mask,
1508
+ inputs_embeds=inputs_embeds,
1509
+ output_attentions=output_attentions,
1510
+ output_hidden_states=output_hidden_states,
1511
+ return_dict=return_dict,
1512
+ training=training,
1513
+ )
1514
+ pooled_output = outputs[1]
1515
+ seq_relationship_scores = self.cls(pooled_output)
1516
+
1517
+ next_sentence_loss = (
1518
+ None
1519
+ if next_sentence_label is None
1520
+ else self.hf_compute_loss(labels=next_sentence_label, logits=seq_relationship_scores)
1521
+ )
1522
+
1523
+ if not return_dict:
1524
+ output = (seq_relationship_scores,) + outputs[2:]
1525
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1526
+
1527
+ return TFNextSentencePredictorOutput(
1528
+ loss=next_sentence_loss,
1529
+ logits=seq_relationship_scores,
1530
+ hidden_states=outputs.hidden_states,
1531
+ attentions=outputs.attentions,
1532
+ )
1533
+
1534
+ def build(self, input_shape=None):
1535
+ if self.built:
1536
+ return
1537
+ self.built = True
1538
+ if getattr(self, "mobilebert", None) is not None:
1539
+ with tf.name_scope(self.mobilebert.name):
1540
+ self.mobilebert.build(None)
1541
+ if getattr(self, "cls", None) is not None:
1542
+ with tf.name_scope(self.cls.name):
1543
+ self.cls.build(None)
1544
+
1545
+
1546
+ @add_start_docstrings(
1547
+ """
1548
+ MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
1549
+ pooled output) e.g. for GLUE tasks.
1550
+ """,
1551
+ MOBILEBERT_START_DOCSTRING,
1552
+ )
1553
+ class TFMobileBertForSequenceClassification(TFMobileBertPreTrainedModel, TFSequenceClassificationLoss):
1554
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1555
+ _keys_to_ignore_on_load_unexpected = [
1556
+ r"predictions___cls",
1557
+ r"seq_relationship___cls",
1558
+ r"cls.predictions",
1559
+ r"cls.seq_relationship",
1560
+ ]
1561
+ _keys_to_ignore_on_load_missing = [r"dropout"]
1562
+
1563
+ def __init__(self, config, *inputs, **kwargs):
1564
+ super().__init__(config, *inputs, **kwargs)
1565
+ self.num_labels = config.num_labels
1566
+
1567
+ self.mobilebert = TFMobileBertMainLayer(config, name="mobilebert")
1568
+ classifier_dropout = (
1569
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1570
+ )
1571
+ self.dropout = keras.layers.Dropout(classifier_dropout)
1572
+ self.classifier = keras.layers.Dense(
1573
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1574
+ )
1575
+ self.config = config
1576
+
1577
+ @unpack_inputs
1578
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1579
+ @add_code_sample_docstrings(
1580
+ checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
1581
+ output_type=TFSequenceClassifierOutput,
1582
+ config_class=_CONFIG_FOR_DOC,
1583
+ expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
1584
+ expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
1585
+ )
1586
+ def call(
1587
+ self,
1588
+ input_ids: TFModelInputType | None = None,
1589
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1590
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1591
+ position_ids: np.ndarray | tf.Tensor | None = None,
1592
+ head_mask: np.ndarray | tf.Tensor | None = None,
1593
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1594
+ output_attentions: Optional[bool] = None,
1595
+ output_hidden_states: Optional[bool] = None,
1596
+ return_dict: Optional[bool] = None,
1597
+ labels: np.ndarray | tf.Tensor | None = None,
1598
+ training: Optional[bool] = False,
1599
+ ) -> Union[Tuple, TFSequenceClassifierOutput]:
1600
+ r"""
1601
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1602
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1603
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1604
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1605
+ """
1606
+ outputs = self.mobilebert(
1607
+ input_ids,
1608
+ attention_mask=attention_mask,
1609
+ token_type_ids=token_type_ids,
1610
+ position_ids=position_ids,
1611
+ head_mask=head_mask,
1612
+ inputs_embeds=inputs_embeds,
1613
+ output_attentions=output_attentions,
1614
+ output_hidden_states=output_hidden_states,
1615
+ return_dict=return_dict,
1616
+ training=training,
1617
+ )
1618
+ pooled_output = outputs[1]
1619
+
1620
+ pooled_output = self.dropout(pooled_output, training=training)
1621
+ logits = self.classifier(pooled_output)
1622
+
1623
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1624
+
1625
+ if not return_dict:
1626
+ output = (logits,) + outputs[2:]
1627
+ return ((loss,) + output) if loss is not None else output
1628
+
1629
+ return TFSequenceClassifierOutput(
1630
+ loss=loss,
1631
+ logits=logits,
1632
+ hidden_states=outputs.hidden_states,
1633
+ attentions=outputs.attentions,
1634
+ )
1635
+
1636
+ def build(self, input_shape=None):
1637
+ if self.built:
1638
+ return
1639
+ self.built = True
1640
+ if getattr(self, "mobilebert", None) is not None:
1641
+ with tf.name_scope(self.mobilebert.name):
1642
+ self.mobilebert.build(None)
1643
+ if getattr(self, "classifier", None) is not None:
1644
+ with tf.name_scope(self.classifier.name):
1645
+ self.classifier.build([None, None, self.config.hidden_size])
1646
+
1647
+
1648
+ @add_start_docstrings(
1649
+ """
1650
+ MobileBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
1651
+ linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1652
+ """,
1653
+ MOBILEBERT_START_DOCSTRING,
1654
+ )
1655
+ class TFMobileBertForQuestionAnswering(TFMobileBertPreTrainedModel, TFQuestionAnsweringLoss):
1656
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1657
+ _keys_to_ignore_on_load_unexpected = [
1658
+ r"pooler",
1659
+ r"predictions___cls",
1660
+ r"seq_relationship___cls",
1661
+ r"cls.predictions",
1662
+ r"cls.seq_relationship",
1663
+ ]
1664
+
1665
+ def __init__(self, config, *inputs, **kwargs):
1666
+ super().__init__(config, *inputs, **kwargs)
1667
+ self.num_labels = config.num_labels
1668
+
1669
+ self.mobilebert = TFMobileBertMainLayer(config, add_pooling_layer=False, name="mobilebert")
1670
+ self.qa_outputs = keras.layers.Dense(
1671
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
1672
+ )
1673
+ self.config = config
1674
+
1675
+ @unpack_inputs
1676
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1677
+ @add_code_sample_docstrings(
1678
+ checkpoint=_CHECKPOINT_FOR_QA,
1679
+ output_type=TFQuestionAnsweringModelOutput,
1680
+ config_class=_CONFIG_FOR_DOC,
1681
+ qa_target_start_index=_QA_TARGET_START_INDEX,
1682
+ qa_target_end_index=_QA_TARGET_END_INDEX,
1683
+ expected_output=_QA_EXPECTED_OUTPUT,
1684
+ expected_loss=_QA_EXPECTED_LOSS,
1685
+ )
1686
+ def call(
1687
+ self,
1688
+ input_ids: TFModelInputType | None = None,
1689
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1690
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1691
+ position_ids: np.ndarray | tf.Tensor | None = None,
1692
+ head_mask: np.ndarray | tf.Tensor | None = None,
1693
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1694
+ output_attentions: Optional[bool] = None,
1695
+ output_hidden_states: Optional[bool] = None,
1696
+ return_dict: Optional[bool] = None,
1697
+ start_positions: np.ndarray | tf.Tensor | None = None,
1698
+ end_positions: np.ndarray | tf.Tensor | None = None,
1699
+ training: Optional[bool] = False,
1700
+ ) -> Union[Tuple, TFQuestionAnsweringModelOutput]:
1701
+ r"""
1702
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1703
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1704
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1705
+ are not taken into account for computing the loss.
1706
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1707
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1708
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1709
+ are not taken into account for computing the loss.
1710
+ """
1711
+ outputs = self.mobilebert(
1712
+ input_ids,
1713
+ attention_mask=attention_mask,
1714
+ token_type_ids=token_type_ids,
1715
+ position_ids=position_ids,
1716
+ head_mask=head_mask,
1717
+ inputs_embeds=inputs_embeds,
1718
+ output_attentions=output_attentions,
1719
+ output_hidden_states=output_hidden_states,
1720
+ return_dict=return_dict,
1721
+ training=training,
1722
+ )
1723
+ sequence_output = outputs[0]
1724
+
1725
+ logits = self.qa_outputs(sequence_output)
1726
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
1727
+ start_logits = tf.squeeze(start_logits, axis=-1)
1728
+ end_logits = tf.squeeze(end_logits, axis=-1)
1729
+
1730
+ loss = None
1731
+ if start_positions is not None and end_positions is not None:
1732
+ labels = {"start_position": start_positions, "end_position": end_positions}
1733
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
1734
+
1735
+ if not return_dict:
1736
+ output = (start_logits, end_logits) + outputs[2:]
1737
+ return ((loss,) + output) if loss is not None else output
1738
+
1739
+ return TFQuestionAnsweringModelOutput(
1740
+ loss=loss,
1741
+ start_logits=start_logits,
1742
+ end_logits=end_logits,
1743
+ hidden_states=outputs.hidden_states,
1744
+ attentions=outputs.attentions,
1745
+ )
1746
+
1747
+ def build(self, input_shape=None):
1748
+ if self.built:
1749
+ return
1750
+ self.built = True
1751
+ if getattr(self, "mobilebert", None) is not None:
1752
+ with tf.name_scope(self.mobilebert.name):
1753
+ self.mobilebert.build(None)
1754
+ if getattr(self, "qa_outputs", None) is not None:
1755
+ with tf.name_scope(self.qa_outputs.name):
1756
+ self.qa_outputs.build([None, None, self.config.hidden_size])
1757
+
1758
+
1759
+ @add_start_docstrings(
1760
+ """
1761
+ MobileBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
1762
+ a softmax) e.g. for RocStories/SWAG tasks.
1763
+ """,
1764
+ MOBILEBERT_START_DOCSTRING,
1765
+ )
1766
+ class TFMobileBertForMultipleChoice(TFMobileBertPreTrainedModel, TFMultipleChoiceLoss):
1767
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1768
+ _keys_to_ignore_on_load_unexpected = [
1769
+ r"predictions___cls",
1770
+ r"seq_relationship___cls",
1771
+ r"cls.predictions",
1772
+ r"cls.seq_relationship",
1773
+ ]
1774
+ _keys_to_ignore_on_load_missing = [r"dropout"]
1775
+
1776
+ def __init__(self, config, *inputs, **kwargs):
1777
+ super().__init__(config, *inputs, **kwargs)
1778
+
1779
+ self.mobilebert = TFMobileBertMainLayer(config, name="mobilebert")
1780
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
1781
+ self.classifier = keras.layers.Dense(
1782
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1783
+ )
1784
+ self.config = config
1785
+
1786
+ @unpack_inputs
1787
+ @add_start_docstrings_to_model_forward(
1788
+ MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1789
+ )
1790
+ @add_code_sample_docstrings(
1791
+ checkpoint=_CHECKPOINT_FOR_DOC,
1792
+ output_type=TFMultipleChoiceModelOutput,
1793
+ config_class=_CONFIG_FOR_DOC,
1794
+ )
1795
+ def call(
1796
+ self,
1797
+ input_ids: TFModelInputType | None = None,
1798
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1799
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1800
+ position_ids: np.ndarray | tf.Tensor | None = None,
1801
+ head_mask: np.ndarray | tf.Tensor | None = None,
1802
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1803
+ output_attentions: Optional[bool] = None,
1804
+ output_hidden_states: Optional[bool] = None,
1805
+ return_dict: Optional[bool] = None,
1806
+ labels: np.ndarray | tf.Tensor | None = None,
1807
+ training: Optional[bool] = False,
1808
+ ) -> Union[Tuple, TFMultipleChoiceModelOutput]:
1809
+ r"""
1810
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1811
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1812
+ where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
1813
+ """
1814
+ if input_ids is not None:
1815
+ num_choices = shape_list(input_ids)[1]
1816
+ seq_length = shape_list(input_ids)[2]
1817
+ else:
1818
+ num_choices = shape_list(inputs_embeds)[1]
1819
+ seq_length = shape_list(inputs_embeds)[2]
1820
+
1821
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
1822
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
1823
+ flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None
1824
+ flat_position_ids = tf.reshape(position_ids, (-1, seq_length)) if position_ids is not None else None
1825
+ flat_inputs_embeds = (
1826
+ tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
1827
+ if inputs_embeds is not None
1828
+ else None
1829
+ )
1830
+ outputs = self.mobilebert(
1831
+ flat_input_ids,
1832
+ flat_attention_mask,
1833
+ flat_token_type_ids,
1834
+ flat_position_ids,
1835
+ head_mask,
1836
+ flat_inputs_embeds,
1837
+ output_attentions,
1838
+ output_hidden_states,
1839
+ return_dict=return_dict,
1840
+ training=training,
1841
+ )
1842
+ pooled_output = outputs[1]
1843
+ pooled_output = self.dropout(pooled_output, training=training)
1844
+ logits = self.classifier(pooled_output)
1845
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
1846
+
1847
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
1848
+
1849
+ if not return_dict:
1850
+ output = (reshaped_logits,) + outputs[2:]
1851
+ return ((loss,) + output) if loss is not None else output
1852
+
1853
+ return TFMultipleChoiceModelOutput(
1854
+ loss=loss,
1855
+ logits=reshaped_logits,
1856
+ hidden_states=outputs.hidden_states,
1857
+ attentions=outputs.attentions,
1858
+ )
1859
+
1860
+ def build(self, input_shape=None):
1861
+ if self.built:
1862
+ return
1863
+ self.built = True
1864
+ if getattr(self, "mobilebert", None) is not None:
1865
+ with tf.name_scope(self.mobilebert.name):
1866
+ self.mobilebert.build(None)
1867
+ if getattr(self, "classifier", None) is not None:
1868
+ with tf.name_scope(self.classifier.name):
1869
+ self.classifier.build([None, None, self.config.hidden_size])
1870
+
1871
+
1872
+ @add_start_docstrings(
1873
+ """
1874
+ MobileBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
1875
+ for Named-Entity-Recognition (NER) tasks.
1876
+ """,
1877
+ MOBILEBERT_START_DOCSTRING,
1878
+ )
1879
+ class TFMobileBertForTokenClassification(TFMobileBertPreTrainedModel, TFTokenClassificationLoss):
1880
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1881
+ _keys_to_ignore_on_load_unexpected = [
1882
+ r"pooler",
1883
+ r"predictions___cls",
1884
+ r"seq_relationship___cls",
1885
+ r"cls.predictions",
1886
+ r"cls.seq_relationship",
1887
+ ]
1888
+ _keys_to_ignore_on_load_missing = [r"dropout"]
1889
+
1890
+ def __init__(self, config, *inputs, **kwargs):
1891
+ super().__init__(config, *inputs, **kwargs)
1892
+ self.num_labels = config.num_labels
1893
+
1894
+ self.mobilebert = TFMobileBertMainLayer(config, add_pooling_layer=False, name="mobilebert")
1895
+ classifier_dropout = (
1896
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1897
+ )
1898
+ self.dropout = keras.layers.Dropout(classifier_dropout)
1899
+ self.classifier = keras.layers.Dense(
1900
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1901
+ )
1902
+ self.config = config
1903
+
1904
+ @unpack_inputs
1905
+ @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1906
+ @add_code_sample_docstrings(
1907
+ checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
1908
+ output_type=TFTokenClassifierOutput,
1909
+ config_class=_CONFIG_FOR_DOC,
1910
+ expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
1911
+ expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
1912
+ )
1913
+ def call(
1914
+ self,
1915
+ input_ids: TFModelInputType | None = None,
1916
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1917
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1918
+ position_ids: np.ndarray | tf.Tensor | None = None,
1919
+ head_mask: np.ndarray | tf.Tensor | None = None,
1920
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1921
+ output_attentions: Optional[bool] = None,
1922
+ output_hidden_states: Optional[bool] = None,
1923
+ return_dict: Optional[bool] = None,
1924
+ labels: np.ndarray | tf.Tensor | None = None,
1925
+ training: Optional[bool] = False,
1926
+ ) -> Union[Tuple, TFTokenClassifierOutput]:
1927
+ r"""
1928
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1929
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1930
+ """
1931
+ outputs = self.mobilebert(
1932
+ input_ids,
1933
+ attention_mask=attention_mask,
1934
+ token_type_ids=token_type_ids,
1935
+ position_ids=position_ids,
1936
+ head_mask=head_mask,
1937
+ inputs_embeds=inputs_embeds,
1938
+ output_attentions=output_attentions,
1939
+ output_hidden_states=output_hidden_states,
1940
+ return_dict=return_dict,
1941
+ training=training,
1942
+ )
1943
+ sequence_output = outputs[0]
1944
+
1945
+ sequence_output = self.dropout(sequence_output, training=training)
1946
+ logits = self.classifier(sequence_output)
1947
+
1948
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1949
+
1950
+ if not return_dict:
1951
+ output = (logits,) + outputs[2:]
1952
+ return ((loss,) + output) if loss is not None else output
1953
+
1954
+ return TFTokenClassifierOutput(
1955
+ loss=loss,
1956
+ logits=logits,
1957
+ hidden_states=outputs.hidden_states,
1958
+ attentions=outputs.attentions,
1959
+ )
1960
+
1961
+ def build(self, input_shape=None):
1962
+ if self.built:
1963
+ return
1964
+ self.built = True
1965
+ if getattr(self, "mobilebert", None) is not None:
1966
+ with tf.name_scope(self.mobilebert.name):
1967
+ self.mobilebert.build(None)
1968
+ if getattr(self, "classifier", None) is not None:
1969
+ with tf.name_scope(self.classifier.name):
1970
+ self.classifier.build([None, None, self.config.hidden_size])
videochat2/lib/python3.10/site-packages/transformers/models/mobilebert/tokenization_mobilebert_fast.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ #
3
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """Tokenization classes for MobileBERT."""
17
+
18
+ import json
19
+ from typing import List, Optional, Tuple
20
+
21
+ from tokenizers import normalizers
22
+
23
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
24
+ from ...utils import logging
25
+ from .tokenization_mobilebert import MobileBertTokenizer
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
31
+
32
+
33
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast with BERT->MobileBERT,Bert->MobileBert
34
+ class MobileBertTokenizerFast(PreTrainedTokenizerFast):
35
+ r"""
36
+ Construct a "fast" MobileBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
37
+
38
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
39
+ refer to this superclass for more information regarding those methods.
40
+
41
+ Args:
42
+ vocab_file (`str`):
43
+ File containing the vocabulary.
44
+ do_lower_case (`bool`, *optional*, defaults to `True`):
45
+ Whether or not to lowercase the input when tokenizing.
46
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
47
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
48
+ token instead.
49
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
50
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
51
+ sequence classification or for a text and a question for question answering. It is also used as the last
52
+ token of a sequence built with special tokens.
53
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
54
+ The token used for padding, for example when batching sequences of different lengths.
55
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
56
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
57
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
58
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
59
+ The token used for masking values. This is the token used when training this model with masked language
60
+ modeling. This is the token which the model will try to predict.
61
+ clean_text (`bool`, *optional*, defaults to `True`):
62
+ Whether or not to clean the text before tokenization by removing any control characters and replacing all
63
+ whitespaces by the classic one.
64
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
65
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
66
+ issue](https://github.com/huggingface/transformers/issues/328)).
67
+ strip_accents (`bool`, *optional*):
68
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
69
+ value for `lowercase` (as in the original MobileBERT).
70
+ wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
71
+ The prefix for subwords.
72
+ """
73
+
74
+ vocab_files_names = VOCAB_FILES_NAMES
75
+ slow_tokenizer_class = MobileBertTokenizer
76
+
77
+ def __init__(
78
+ self,
79
+ vocab_file=None,
80
+ tokenizer_file=None,
81
+ do_lower_case=True,
82
+ unk_token="[UNK]",
83
+ sep_token="[SEP]",
84
+ pad_token="[PAD]",
85
+ cls_token="[CLS]",
86
+ mask_token="[MASK]",
87
+ tokenize_chinese_chars=True,
88
+ strip_accents=None,
89
+ **kwargs,
90
+ ):
91
+ super().__init__(
92
+ vocab_file,
93
+ tokenizer_file=tokenizer_file,
94
+ do_lower_case=do_lower_case,
95
+ unk_token=unk_token,
96
+ sep_token=sep_token,
97
+ pad_token=pad_token,
98
+ cls_token=cls_token,
99
+ mask_token=mask_token,
100
+ tokenize_chinese_chars=tokenize_chinese_chars,
101
+ strip_accents=strip_accents,
102
+ **kwargs,
103
+ )
104
+
105
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
106
+ if (
107
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
108
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
109
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
110
+ ):
111
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
112
+ normalizer_state["lowercase"] = do_lower_case
113
+ normalizer_state["strip_accents"] = strip_accents
114
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
115
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
116
+
117
+ self.do_lower_case = do_lower_case
118
+
119
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
120
+ """
121
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
122
+ adding special tokens. A MobileBERT sequence has the following format:
123
+
124
+ - single sequence: `[CLS] X [SEP]`
125
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
126
+
127
+ Args:
128
+ token_ids_0 (`List[int]`):
129
+ List of IDs to which the special tokens will be added.
130
+ token_ids_1 (`List[int]`, *optional*):
131
+ Optional second list of IDs for sequence pairs.
132
+
133
+ Returns:
134
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
135
+ """
136
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
137
+
138
+ if token_ids_1 is not None:
139
+ output += token_ids_1 + [self.sep_token_id]
140
+
141
+ return output
142
+
143
+ def create_token_type_ids_from_sequences(
144
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
145
+ ) -> List[int]:
146
+ """
147
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A MobileBERT sequence
148
+ pair mask has the following format:
149
+
150
+ ```
151
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
152
+ | first sequence | second sequence |
153
+ ```
154
+
155
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
156
+
157
+ Args:
158
+ token_ids_0 (`List[int]`):
159
+ List of IDs.
160
+ token_ids_1 (`List[int]`, *optional*):
161
+ Optional second list of IDs for sequence pairs.
162
+
163
+ Returns:
164
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
165
+ """
166
+ sep = [self.sep_token_id]
167
+ cls = [self.cls_token_id]
168
+ if token_ids_1 is None:
169
+ return len(cls + token_ids_0 + sep) * [0]
170
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
171
+
172
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
173
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
174
+ return tuple(files)
videochat2/lib/python3.10/site-packages/transformers/models/nllb_moe/__init__.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
18
+
19
+
20
+ _import_structure = {
21
+ "configuration_nllb_moe": [
22
+ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP",
23
+ "NllbMoeConfig",
24
+ ]
25
+ }
26
+
27
+ try:
28
+ if not is_torch_available():
29
+ raise OptionalDependencyNotAvailable()
30
+ except OptionalDependencyNotAvailable:
31
+ pass
32
+ else:
33
+ _import_structure["modeling_nllb_moe"] = [
34
+ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST",
35
+ "NllbMoeForConditionalGeneration",
36
+ "NllbMoeModel",
37
+ "NllbMoePreTrainedModel",
38
+ "NllbMoeTop2Router",
39
+ "NllbMoeSparseMLP",
40
+ ]
41
+
42
+
43
+ if TYPE_CHECKING:
44
+ from .configuration_nllb_moe import (
45
+ NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP,
46
+ NllbMoeConfig,
47
+ )
48
+
49
+ try:
50
+ if not is_torch_available():
51
+ raise OptionalDependencyNotAvailable()
52
+ except OptionalDependencyNotAvailable:
53
+ pass
54
+ else:
55
+ from .modeling_nllb_moe import (
56
+ NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST,
57
+ NllbMoeForConditionalGeneration,
58
+ NllbMoeModel,
59
+ NllbMoePreTrainedModel,
60
+ NllbMoeSparseMLP,
61
+ NllbMoeTop2Router,
62
+ )
63
+
64
+
65
+ else:
66
+ import sys
67
+
68
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
videochat2/lib/python3.10/site-packages/transformers/models/nllb_moe/__pycache__/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (4.44 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/nllb_moe/__pycache__/modeling_nllb_moe.cpython-310.pyc ADDED
Binary file (56.6 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/nllb_moe/configuration_nllb_moe.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023, HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ NLLB-MoE model configuration"""
16
+ from ...configuration_utils import PretrainedConfig
17
+ from ...utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ from ..deprecated._archive_maps import NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP # noqa: F401, E402
24
+
25
+
26
+ class NllbMoeConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`NllbMoeModel`]. It is used to instantiate an
29
+ NLLB-MoE model according to the specified arguments, defining the model architecture. Instantiating a configuration
30
+ with the defaults will yield a similar configuration to that of the NLLB-MoE
31
+ [facebook/nllb-moe-54b](https://huggingface.co/facebook/nllb-moe-54b) 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
+ vocab_size (`int`, *optional*, defaults to 50265):
39
+ Vocabulary size of the NllbMoe model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`NllbMoeModel`] or
41
+ d_model (`int`, *optional*, defaults to 1024):
42
+ Dimensionality of the layers and the pooler layer.
43
+ encoder_layers (`int`, *optional*, defaults to 12):
44
+ Number of encoder layers.
45
+ decoder_layers (`int`, *optional*, defaults to 12):
46
+ Number of decoder layers.
47
+ encoder_attention_heads (`int`, *optional*, defaults to 16):
48
+ Number of attention heads for each attention layer in the Transformer encoder.
49
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
50
+ Number of attention heads for each attention layer in the Transformer decoder.
51
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
52
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
53
+ encoder_ffn_dim (`int`, *optional*, defaults to 4096):
54
+ Dimensionality of the "intermediate" (often named feed-forward) layer in encoder.
55
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
56
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
57
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
58
+ dropout (`float`, *optional*, defaults to 0.1):
59
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
60
+ attention_dropout (`float`, *optional*, defaults to 0.0):
61
+ The dropout ratio for the attention probabilities.
62
+ activation_dropout (`float`, *optional*, defaults to 0.0):
63
+ The dropout ratio for activations inside the fully connected layer.
64
+ classifier_dropout (`float`, *optional*, defaults to 0.0):
65
+ The dropout ratio for classifier.
66
+ max_position_embeddings (`int`, *optional*, defaults to 1024):
67
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
68
+ just in case (e.g., 512 or 1024 or 2048).
69
+ init_std (`float`, *optional*, defaults to 0.02):
70
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
71
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
72
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
73
+ for more details.
74
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
75
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
76
+ for more details.
77
+ second_expert_policy ( `str`, *optional*, default to `"all"`):
78
+ The policy used for the sampling the probability of being sampled to a second expert for each token.
79
+ normalize_router_prob_before_dropping (`bool`, *optional*, defaults to `True`):
80
+ Whether or not to normalize the router probabilities before applying a mask based on the experts capacity
81
+ (capacity dropping).
82
+ batch_prioritized_routing (`bool`, *optional*, defaults to `True`):
83
+ Whether or not to orders the tokens by their router probabilities before capacity dropping. This means that
84
+ the tokens that have the highest probabilities will be routed before other tokens that might be further in
85
+ the sequence.
86
+ moe_eval_capacity_token_fraction (`float`, *optional*, defaults to 1.0):
87
+ Fraction of tokens as capacity during validation, if set to negative, uses the same as training. Should be
88
+ in range: (0.0, 1.0].
89
+ num_experts (`int`, *optional*, defaults to 128):
90
+ Number of experts for each NllbMoeSparseMlp layer.
91
+ expert_capacity (`int`, *optional*, defaults to 64):
92
+ Number of tokens that can be stored in each expert.
93
+ encoder_sparse_step (`int`, *optional*, defaults to 4):
94
+ Frequency of the sparse layers in the encoder. 4 means that one out of 4 layers will be sparse.
95
+ decoder_sparse_step (`int`, *optional*, defaults to 4):
96
+ Frequency of the sparse layers in the decoder. 4 means that one out of 4 layers will be sparse.
97
+ router_dtype (`str`, *optional*, default to `"float32"`):
98
+ The `dtype` used for the routers. It is preferable to keep the `dtype` to `"float32"` as specified in the
99
+ *selective precision* discussion in [the paper](https://arxiv.org/abs/2101.03961).
100
+ router_ignore_padding_tokens (`bool`, *optional*, defaults to `False`):
101
+ Whether to ignore padding tokens when routing. if `False`, the padding tokens are not routed to any
102
+ experts.
103
+ router_bias (`bool`, *optional*, defaults to `False`):
104
+ Whether or not the classifier of the router should have a bias.
105
+ moe_token_dropout (`float`, *optional*, defualt ot 0.2):
106
+ Masking rate for MoE expert output masking (EOM), which is implemented via a Dropout2d on the expert
107
+ outputs.
108
+ output_router_logits (`bool`, *optional*, defaults to `False`):
109
+ Whether or not to return the router logits. Only set to `True` to get the auxiliary loss when training.
110
+ use_cache (`bool`, *optional*, defaults to `True`):
111
+ Whether or not the model should return the last key/values attentions (not used by all models).
112
+
113
+ Example:
114
+
115
+ ```python
116
+ >>> from transformers import NllbMoeModel, NllbMoeConfig
117
+
118
+ >>> # Initializing a NllbMoe facebook/nllb-moe-54b style configuration
119
+ >>> configuration = NllbMoeConfig()
120
+
121
+ >>> # Initializing a model from the facebook/nllb-moe-54b style configuration
122
+ >>> model = NllbMoeModel(configuration)
123
+
124
+ >>> # Accessing the model configuration
125
+ >>> configuration = model.config
126
+ ```"""
127
+
128
+ model_type = "nllb-moe"
129
+ keys_to_ignore_at_inference = ["past_key_values"]
130
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
131
+
132
+ def __init__(
133
+ self,
134
+ vocab_size=128112,
135
+ max_position_embeddings=1024,
136
+ encoder_layers=12,
137
+ encoder_ffn_dim=4096,
138
+ encoder_attention_heads=16,
139
+ decoder_layers=12,
140
+ decoder_ffn_dim=4096,
141
+ decoder_attention_heads=16,
142
+ encoder_layerdrop=0.05,
143
+ decoder_layerdrop=0.05,
144
+ use_cache=True,
145
+ is_encoder_decoder=True,
146
+ activation_function="relu",
147
+ d_model=1024,
148
+ dropout=0.1,
149
+ attention_dropout=0.1,
150
+ activation_dropout=0.0,
151
+ init_std=0.02,
152
+ decoder_start_token_id=2,
153
+ scale_embedding=True,
154
+ router_bias=False,
155
+ router_dtype="float32",
156
+ router_ignore_padding_tokens=False,
157
+ num_experts=128,
158
+ expert_capacity=64,
159
+ encoder_sparse_step=4,
160
+ decoder_sparse_step=4,
161
+ router_z_loss_coef=0.001,
162
+ router_aux_loss_coef=0.001,
163
+ second_expert_policy="all",
164
+ normalize_router_prob_before_dropping=False,
165
+ batch_prioritized_routing=False,
166
+ moe_eval_capacity_token_fraction=1.0,
167
+ moe_token_dropout=0.2,
168
+ pad_token_id=1,
169
+ bos_token_id=0,
170
+ eos_token_id=2,
171
+ output_router_logits=False,
172
+ **kwargs,
173
+ ):
174
+ self.vocab_size = vocab_size
175
+ self.max_position_embeddings = max_position_embeddings
176
+ self.d_model = d_model
177
+ self.encoder_ffn_dim = encoder_ffn_dim
178
+ self.encoder_layers = encoder_layers
179
+ self.encoder_attention_heads = encoder_attention_heads
180
+ self.decoder_ffn_dim = decoder_ffn_dim
181
+ self.decoder_layers = decoder_layers
182
+ self.decoder_attention_heads = decoder_attention_heads
183
+ self.dropout = dropout
184
+ self.attention_dropout = attention_dropout
185
+ self.activation_dropout = activation_dropout
186
+ self.activation_function = activation_function
187
+ self.init_std = init_std
188
+ self.encoder_layerdrop = encoder_layerdrop
189
+ self.decoder_layerdrop = decoder_layerdrop
190
+ self.use_cache = use_cache
191
+ self.num_hidden_layers = encoder_layers
192
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
193
+ self.router_z_loss_coef = router_z_loss_coef
194
+ self.router_aux_loss_coef = router_aux_loss_coef
195
+ self.decoder_sparse_step = decoder_sparse_step
196
+ self.encoder_sparse_step = encoder_sparse_step
197
+ self.num_experts = num_experts
198
+ self.expert_capacity = expert_capacity
199
+ self.router_bias = router_bias
200
+ if router_dtype not in ["float32", "float16", "bfloat16"]:
201
+ raise ValueError(f"`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}")
202
+ self.router_dtype = router_dtype
203
+
204
+ self.router_ignore_padding_tokens = router_ignore_padding_tokens
205
+ self.batch_prioritized_routing = batch_prioritized_routing
206
+ self.second_expert_policy = second_expert_policy
207
+ self.normalize_router_prob_before_dropping = normalize_router_prob_before_dropping
208
+ self.moe_eval_capacity_token_fraction = moe_eval_capacity_token_fraction
209
+ self.moe_token_dropout = moe_token_dropout
210
+ self.output_router_logits = output_router_logits
211
+ super().__init__(
212
+ pad_token_id=pad_token_id,
213
+ bos_token_id=bos_token_id,
214
+ eos_token_id=eos_token_id,
215
+ is_encoder_decoder=is_encoder_decoder,
216
+ decoder_start_token_id=decoder_start_token_id,
217
+ **kwargs,
218
+ )
videochat2/lib/python3.10/site-packages/transformers/models/nllb_moe/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import argparse
15
+ import json
16
+ import os
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from transformers import NllbMoeConfig, NllbMoeModel
22
+ from transformers.modeling_utils import dtype_byte_size
23
+ from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME
24
+
25
+
26
+ def remove_ignore_keys_(state_dict):
27
+ ignore_keys = [
28
+ "encoder.version",
29
+ "decoder.version",
30
+ "model.encoder.version",
31
+ "model.decoder.version",
32
+ "decoder.output_projection.weight",
33
+ "_float_tensor",
34
+ "encoder.embed_positions._float_tensor",
35
+ "decoder.embed_positions._float_tensor",
36
+ ]
37
+ for k in ignore_keys:
38
+ state_dict.pop(k, None)
39
+
40
+
41
+ def make_linear_from_emb(emb):
42
+ vocab_size, emb_size = emb.weight.shape
43
+ lin_layer = nn.Linear(vocab_size, emb_size, bias=False)
44
+ lin_layer.weight.data = emb.weight.data
45
+ return lin_layer
46
+
47
+
48
+ def rename_fairseq_keys(state_dict, expert_idx=None):
49
+ new_dict = {}
50
+ for old_key in state_dict.keys():
51
+ key = old_key
52
+ if "moe_layer.experts." in key:
53
+ if expert_idx is not None:
54
+ key = key.replace("moe_layer.experts.0", f"ffn.experts.expert_{expert_idx}")
55
+ else:
56
+ key = key.replace("moe_layer.experts.", "ffn.experts.expert_")
57
+ if "gate" in key:
58
+ key = key.replace(".moe_layer.gate.wg", ".ffn.router.classifier")
59
+ if "fc2" and "experts" not in key:
60
+ key = key.replace(".fc2.", ".ffn.fc2.")
61
+ if "fc1" and "experts" not in key:
62
+ key = key.replace(".fc1.", ".ffn.fc1.")
63
+ if ".encoder_attn." in key:
64
+ key = key.replace(".encoder_attn.", ".cross_attention.")
65
+ if "encoder_attn_layer_norm" in key:
66
+ key = key.replace("encoder_attn_layer_norm", "cross_attention_layer_norm")
67
+ if "final_layer_norm" in key:
68
+ key = key.replace("final_layer_norm", "ff_layer_norm")
69
+ new_dict[key] = state_dict[old_key]
70
+ return new_dict
71
+
72
+
73
+ def shard_on_the_fly(switch_checkpoint_path, dump_path, num_experts, dtype, weights_name: str = WEIGHTS_NAME):
74
+ sharded_state_dicts = []
75
+ total_size = 0
76
+ os.makedirs(dump_path, exist_ok=True)
77
+
78
+ for expert in range(num_experts):
79
+ expert_path = switch_checkpoint_path + f"-rank-{expert}.pt"
80
+ if os.path.isfile(expert_path):
81
+ expert_state = torch.load(expert_path)["model"]
82
+ remove_ignore_keys_(expert_state)
83
+ expert_state = rename_fairseq_keys(expert_state, expert)
84
+ save_path = os.path.join(
85
+ dump_path, weights_name.replace(".bin", f"-{len(sharded_state_dicts)+1:05d}-of-???.bin")
86
+ )
87
+ torch.save(expert_state, save_path)
88
+ sharded_state_dicts.append(expert_state.keys())
89
+ total_size += sum([value.numel() for key, value in expert_state.items()]) * dtype_byte_size(
90
+ expert_state[list(expert_state)[0]].dtype
91
+ )
92
+
93
+ # Add the last block
94
+ save_path = os.path.join(dump_path, weights_name.replace(".bin", f"-{len(sharded_state_dicts)+1:05d}-of-???.bin"))
95
+ shared_weights = torch.load(switch_checkpoint_path + "-shared.pt")["model"]
96
+ remove_ignore_keys_(shared_weights)
97
+ shared_weights = rename_fairseq_keys(shared_weights, None)
98
+ shared_weights["shared.weight"] = shared_weights["decoder.embed_tokens.weight"]
99
+ sharded_state_dicts.append(shared_weights.keys())
100
+
101
+ # If we only have the shared weights (dummy model/experts saved on the same file)
102
+ if len(sharded_state_dicts) == 1:
103
+ save_path = os.path.join(dump_path, weights_name)
104
+ torch.save(shared_weights, save_path)
105
+ return {weights_name: sharded_state_dicts[0]}, None
106
+ else:
107
+ torch.save(shared_weights, save_path)
108
+ # Otherwise, let's build the index
109
+ weight_map = {}
110
+ for idx, shard in enumerate(sharded_state_dicts):
111
+ shard_file = weights_name.replace(".bin", f"-{idx+1:05d}-of-{len(sharded_state_dicts):05d}.bin")
112
+ temp_filename = os.path.join(dump_path, weights_name.replace(".bin", f"-{idx+1:05d}-of-???.bin"))
113
+ os.rename(temp_filename, os.path.join(dump_path, shard_file))
114
+ for key in shard:
115
+ weight_map[key] = shard_file
116
+
117
+ # Add the metadata
118
+ metadata = {"total_size": total_size}
119
+ index = {"metadata": metadata, "weight_map": weight_map}
120
+
121
+ with open(os.path.join(dump_path, WEIGHTS_INDEX_NAME), "w", encoding="utf-8") as f:
122
+ content = json.dumps(index, indent=2, sort_keys=True) + "\n"
123
+ f.write(content)
124
+
125
+ return metadata, index
126
+
127
+
128
+ if __name__ == "__main__":
129
+ parser = argparse.ArgumentParser()
130
+ # Required parameters
131
+ parser.add_argument(
132
+ "--nllb_moe_checkpoint_path",
133
+ default="/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000",
134
+ type=str,
135
+ required=False,
136
+ help="Path to a directory containing a folder per layer. Follows the original Google format.",
137
+ )
138
+ parser.add_argument("--dtype", default="float32", type=str, required=False, help="dtype of the saved model")
139
+ parser.add_argument(
140
+ "--pytorch_dump_folder_path",
141
+ default="/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b",
142
+ type=str,
143
+ required=False,
144
+ help="Path to the output pytorch model.",
145
+ )
146
+ args = parser.parse_args()
147
+ metadata, index = shard_on_the_fly(
148
+ args.nllb_moe_checkpoint_path,
149
+ args.pytorch_dump_folder_path,
150
+ 128,
151
+ args.dtype,
152
+ )
153
+
154
+ config = NllbMoeConfig.from_pretrained(
155
+ "facebook/nllb-200-3.3B", encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128
156
+ )
157
+ config.save_pretrained(args.pytorch_dump_folder_path)
158
+ model = NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path)
159
+ print("Done")
160
+ model.save_pretrained(args.pytorch_dump_folder_path)
videochat2/lib/python3.10/site-packages/transformers/models/nllb_moe/modeling_nllb_moe.py ADDED
@@ -0,0 +1,1792 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 NllbMoe Authors and HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch NLLB-MoE model."""
16
+
17
+
18
+ import math
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ from torch.nn import CrossEntropyLoss
24
+
25
+ from ...activations import ACT2FN
26
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
27
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
28
+ from ...modeling_outputs import (
29
+ MoEModelOutput,
30
+ MoEModelOutputWithPastAndCrossAttentions,
31
+ Seq2SeqMoEModelOutput,
32
+ Seq2SeqMoEOutput,
33
+ )
34
+ from ...modeling_utils import PreTrainedModel
35
+ from ...utils import (
36
+ add_end_docstrings,
37
+ add_start_docstrings,
38
+ add_start_docstrings_to_model_forward,
39
+ logging,
40
+ replace_return_docstrings,
41
+ )
42
+ from .configuration_nllb_moe import NllbMoeConfig
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _CONFIG_FOR_DOC = "NllbMoeConfig"
48
+ _CHECKPOINT_FOR_DOC = "hf-internal-testing/dummy-nllb-moe-2-experts"
49
+ _REAL_CHECKPOINT_FOR_DOC = "facebook/nllb-moe-54b"
50
+
51
+
52
+ ####################################################
53
+ # This dict contains ids and associated url
54
+ # for the pretrained weights provided with the models
55
+ ####################################################
56
+
57
+ from ..deprecated._archive_maps import NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
58
+
59
+
60
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
61
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
62
+ """
63
+ Shift input ids one token to the right.
64
+ """
65
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
66
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
67
+ shifted_input_ids[:, 0] = decoder_start_token_id
68
+
69
+ if pad_token_id is None:
70
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
71
+ # replace possible -100 values in labels by `pad_token_id`
72
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
73
+
74
+ return shifted_input_ids
75
+
76
+
77
+ # Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
78
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
79
+ """
80
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
81
+ are ignored. This is modified from fairseq's `utils.make_positions`.
82
+
83
+ Args:
84
+ x: torch.Tensor x:
85
+
86
+ Returns: torch.Tensor
87
+ """
88
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
89
+ mask = input_ids.ne(padding_idx).int()
90
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
91
+ return incremental_indices.long() + padding_idx
92
+
93
+
94
+ def load_balancing_loss_func(router_probs: torch.Tensor, expert_indices: torch.Tensor) -> float:
95
+ r"""
96
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
97
+
98
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
99
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
100
+ experts is too unbalanced.
101
+
102
+ Args:
103
+ router_probs (`torch.Tensor`):
104
+ Probability assigned to each expert per token. Shape: [batch_size, seqeunce_length, num_experts].
105
+ expert_indices (`torch.Tensor`):
106
+ Indices tensor of shape [batch_size, seqeunce_length] identifying the selected expert for a given token.
107
+
108
+ Returns:
109
+ The auxiliary loss.
110
+ """
111
+ if router_probs is None:
112
+ return 0
113
+
114
+ num_experts = router_probs.shape[-1]
115
+
116
+ # cast the expert indices to int64, otherwise one-hot encoding will fail
117
+ if expert_indices.dtype != torch.int64:
118
+ expert_indices = expert_indices.to(torch.int64)
119
+
120
+ if len(expert_indices.shape) == 2:
121
+ expert_indices = expert_indices.unsqueeze(2)
122
+
123
+ expert_mask = torch.nn.functional.one_hot(expert_indices, num_experts)
124
+
125
+ # For a given token, determine if it was routed to a given expert.
126
+ expert_mask = torch.max(expert_mask, axis=-2).values
127
+
128
+ # cast to float32 otherwise mean will fail
129
+ expert_mask = expert_mask.to(torch.float32)
130
+ tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
131
+
132
+ router_prob_per_group_and_expert = torch.mean(router_probs, axis=-2)
133
+ return torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert) * (num_experts**2)
134
+
135
+
136
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding
137
+ class NllbMoeSinusoidalPositionalEmbedding(nn.Module):
138
+ """This module produces sinusoidal positional embeddings of any length."""
139
+
140
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
141
+ super().__init__()
142
+ self.offset = 2
143
+ self.embedding_dim = embedding_dim
144
+ self.padding_idx = padding_idx
145
+ self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
146
+
147
+ def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
148
+ emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
149
+ if hasattr(self, "weights"):
150
+ # in forward put the weights on the correct dtype and device of the param
151
+ emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
152
+
153
+ self.register_buffer("weights", emb_weights, persistent=False)
154
+
155
+ @staticmethod
156
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
157
+ """
158
+ Build sinusoidal embeddings.
159
+
160
+ This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
161
+ "Attention Is All You Need".
162
+ """
163
+ half_dim = embedding_dim // 2
164
+ emb = math.log(10000) / (half_dim - 1)
165
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
166
+ emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
167
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
168
+ if embedding_dim % 2 == 1:
169
+ # zero pad
170
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
171
+ if padding_idx is not None:
172
+ emb[padding_idx, :] = 0
173
+
174
+ return emb.to(torch.get_default_dtype())
175
+
176
+ @torch.no_grad()
177
+ def forward(
178
+ self, input_ids: torch.Tensor = None, inputs_embeds: torch.Tensor = None, past_key_values_length: int = 0
179
+ ):
180
+ if input_ids is not None:
181
+ bsz, seq_len = input_ids.size()
182
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
183
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length).to(
184
+ input_ids.device
185
+ )
186
+ else:
187
+ bsz, seq_len = inputs_embeds.size()[:-1]
188
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, past_key_values_length)
189
+
190
+ # expand embeddings if needed
191
+ max_pos = self.padding_idx + 1 + seq_len + past_key_values_length
192
+ if max_pos > self.weights.size(0):
193
+ self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
194
+
195
+ return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach()
196
+
197
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds, past_key_values_length):
198
+ """
199
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
200
+
201
+ Args:
202
+ inputs_embeds: torch.Tensor
203
+
204
+ Returns: torch.Tensor
205
+ """
206
+ input_shape = inputs_embeds.size()[:-1]
207
+ sequence_length = input_shape[1]
208
+
209
+ position_ids = torch.arange(
210
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
211
+ )
212
+ return position_ids.unsqueeze(0).expand(input_shape).contiguous() + past_key_values_length
213
+
214
+
215
+ class NllbMoeTop2Router(nn.Module):
216
+ """
217
+ Router using tokens choose top-2 experts assignment.
218
+
219
+ This router uses the same mechanism as in NLLB-MoE from the fairseq repository. Items are sorted by router_probs
220
+ and then routed to their choice of expert until the expert's expert_capacity is reached. **There is no guarantee
221
+ that each token is processed by an expert**, or that each expert receives at least one token.
222
+
223
+ The router combining weights are also returned to make sure that the states that are not updated will be masked.
224
+
225
+ """
226
+
227
+ def __init__(self, config: NllbMoeConfig):
228
+ super().__init__()
229
+ self.num_experts = config.num_experts
230
+ self.expert_capacity = config.expert_capacity
231
+ self.classifier = nn.Linear(config.hidden_size, self.num_experts, bias=config.router_bias)
232
+ self.router_ignore_padding_tokens = config.router_ignore_padding_tokens
233
+ self.dtype = getattr(torch, config.router_dtype)
234
+
235
+ self.second_expert_policy = config.second_expert_policy
236
+ self.normalize_router_prob_before_dropping = config.normalize_router_prob_before_dropping
237
+ self.batch_prioritized_routing = config.batch_prioritized_routing
238
+ self.moe_eval_capacity_token_fraction = config.moe_eval_capacity_token_fraction
239
+
240
+ def _cast_classifier(self):
241
+ r"""
242
+ `bitsandbytes` `Linear8bitLt` layers does not support manual casting Therefore we need to check if they are an
243
+ instance of the `Linear8bitLt` class by checking special attributes.
244
+ """
245
+ if not (hasattr(self.classifier, "SCB") or hasattr(self.classifier, "CB")):
246
+ self.classifier = self.classifier.to(self.dtype)
247
+
248
+ def normalize_router_probabilities(self, router_probs, top_1_mask, top_2_mask):
249
+ top_1_max_probs = (router_probs * top_1_mask).sum(dim=1)
250
+ top_2_max_probs = (router_probs * top_2_mask).sum(dim=1)
251
+ denom_s = torch.clamp(top_1_max_probs + top_2_max_probs, min=torch.finfo(router_probs.dtype).eps)
252
+ top_1_max_probs = top_1_max_probs / denom_s
253
+ top_2_max_probs = top_2_max_probs / denom_s
254
+ return top_1_max_probs, top_2_max_probs
255
+
256
+ def route_tokens(
257
+ self,
258
+ router_logits: torch.Tensor,
259
+ input_dtype: torch.dtype = torch.float32,
260
+ padding_mask: Optional[torch.LongTensor] = None,
261
+ ) -> Tuple:
262
+ """
263
+ Computes the `dispatch_mask` and the `dispatch_weights` for each experts. The masks are adapted to the expert
264
+ capacity.
265
+ """
266
+ nb_tokens = router_logits.shape[0]
267
+ # Apply Softmax and cast back to the original `dtype`
268
+ router_probs = nn.functional.softmax(router_logits, dim=-1, dtype=self.dtype).to(input_dtype)
269
+ top_1_expert_index = torch.argmax(router_probs, dim=-1)
270
+ top_1_mask = torch.nn.functional.one_hot(top_1_expert_index, num_classes=self.num_experts)
271
+
272
+ if self.second_expert_policy == "sampling":
273
+ gumbel = torch.distributions.gumbel.Gumbel(0, 1).rsample
274
+ router_logits += gumbel(router_logits.shape).to(router_logits.device)
275
+
276
+ # replace top_1_expert_index with min values
277
+ logits_except_top_1 = router_logits.masked_fill(top_1_mask.bool(), float("-inf"))
278
+ top_2_expert_index = torch.argmax(logits_except_top_1, dim=-1)
279
+ top_2_mask = torch.nn.functional.one_hot(top_2_expert_index, num_classes=self.num_experts)
280
+
281
+ if self.normalize_router_prob_before_dropping:
282
+ top_1_max_probs, top_2_max_probs = self.normalize_router_probabilities(
283
+ router_probs, top_1_mask, top_2_mask
284
+ )
285
+
286
+ if self.second_expert_policy == "random":
287
+ top_2_max_probs = (router_probs * top_2_mask).sum(dim=1)
288
+ sampled = (2 * top_2_max_probs) > torch.rand_like(top_2_max_probs.float())
289
+ top_2_mask = top_2_mask * sampled.repeat(self.num_experts, 1).transpose(1, 0)
290
+
291
+ if padding_mask is not None and not self.router_ignore_padding_tokens:
292
+ if len(padding_mask.shape) == 4:
293
+ # only get the last causal mask
294
+ padding_mask = padding_mask[:, :, -1, :].reshape(-1)[-nb_tokens:]
295
+ non_padding = ~padding_mask.bool()
296
+ top_1_mask = top_1_mask * non_padding.unsqueeze(-1).to(top_1_mask.dtype)
297
+ top_2_mask = top_2_mask * non_padding.unsqueeze(-1).to(top_1_mask.dtype)
298
+
299
+ if self.batch_prioritized_routing:
300
+ # sort tokens based on their routing probability
301
+ # to make sure important tokens are routed, first
302
+ importance_scores = -1 * router_probs.max(dim=1)[0]
303
+ sorted_top_1_mask = top_1_mask[importance_scores.argsort(dim=0)]
304
+ sorted_cumsum1 = (torch.cumsum(sorted_top_1_mask, dim=0) - 1) * sorted_top_1_mask
305
+ locations1 = sorted_cumsum1[importance_scores.argsort(dim=0).argsort(dim=0)]
306
+
307
+ sorted_top_2_mask = top_2_mask[importance_scores.argsort(dim=0)]
308
+ sorted_cumsum2 = (torch.cumsum(sorted_top_2_mask, dim=0) - 1) * sorted_top_2_mask
309
+ locations2 = sorted_cumsum2[importance_scores.argsort(dim=0).argsort(dim=0)]
310
+ # Update 2nd's location by accounting for locations of 1st
311
+ locations2 += torch.sum(top_1_mask, dim=0, keepdim=True)
312
+
313
+ else:
314
+ locations1 = torch.cumsum(top_1_mask, dim=0) - 1
315
+ locations2 = torch.cumsum(top_2_mask, dim=0) - 1
316
+ # Update 2nd's location by accounting for locations of 1st
317
+ locations2 += torch.sum(top_1_mask, dim=0, keepdim=True)
318
+
319
+ if not self.training and self.moe_eval_capacity_token_fraction > 0:
320
+ self.expert_capacity = math.ceil(self.moe_eval_capacity_token_fraction * nb_tokens)
321
+ else:
322
+ capacity = 2 * math.ceil(nb_tokens / self.num_experts)
323
+ self.expert_capacity = capacity if self.expert_capacity is None else self.expert_capacity
324
+
325
+ # Remove locations outside capacity from ( cumsum < capacity = False will not be routed)
326
+ top_1_mask = top_1_mask * torch.lt(locations1, self.expert_capacity)
327
+ top_2_mask = top_2_mask * torch.lt(locations2, self.expert_capacity)
328
+
329
+ if not self.normalize_router_prob_before_dropping:
330
+ top_1_max_probs, top_2_max_probs = self.normalize_router_probabilities(
331
+ router_probs, top_1_mask, top_2_mask
332
+ )
333
+
334
+ # Calculate combine_weights and dispatch_mask
335
+ gates1 = top_1_max_probs[:, None] * top_1_mask
336
+ gates2 = top_2_max_probs[:, None] * top_2_mask
337
+ router_probs = gates1 + gates2
338
+
339
+ return top_1_mask, router_probs
340
+
341
+ def forward(self, hidden_states: torch.Tensor, padding_mask: Optional[torch.LongTensor] = None) -> Tuple:
342
+ r"""
343
+ The hidden states are reshaped to simplify the computation of the router probabilities (combining weights for
344
+ each experts.)
345
+
346
+ Args:
347
+ hidden_states (`torch.Tensor`):
348
+ (batch_size, sequence_length, hidden_dim) from which router probabilities are computed.
349
+ Returns:
350
+ top_1_mask (`torch.Tensor` of shape (batch_size, sequence_length)):
351
+ Index tensor of shape [batch_size, sequence_length] corresponding to the expert selected for each token
352
+ using the top1 probabilities of the router.
353
+ router_probabilities (`torch.Tensor` of shape (batch_size, sequence_length, nump_experts)):
354
+ Tensor of shape (batch_size, sequence_length, num_experts) corresponding to the probabilities for each
355
+ token and expert. Used for routing tokens to experts.
356
+ router_logits (`torch.Tensor` of shape (batch_size, sequence_length))):
357
+ Logits tensor of shape (batch_size, sequence_length, num_experts) corresponding to raw router logits.
358
+ This is used later for computing router z-loss.
359
+ """
360
+ self.input_dtype = hidden_states.dtype
361
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
362
+ hidden_states = hidden_states.reshape((batch_size * sequence_length), hidden_dim)
363
+ hidden_states = hidden_states.to(self.dtype)
364
+ self._cast_classifier()
365
+ router_logits = self.classifier(hidden_states)
366
+ top_1_mask, router_probs = self.route_tokens(router_logits, self.input_dtype, padding_mask)
367
+ return top_1_mask, router_probs
368
+
369
+
370
+ class NllbMoeDenseActDense(nn.Module):
371
+ def __init__(self, config: NllbMoeConfig, ffn_dim: int):
372
+ super().__init__()
373
+ self.fc1 = nn.Linear(config.d_model, ffn_dim)
374
+ self.fc2 = nn.Linear(ffn_dim, config.d_model)
375
+ self.dropout = nn.Dropout(config.activation_dropout)
376
+ self.act = ACT2FN[config.activation_function]
377
+
378
+ def forward(self, hidden_states):
379
+ hidden_states = self.fc1(hidden_states)
380
+ hidden_states = self.act(hidden_states)
381
+ hidden_states = self.dropout(hidden_states)
382
+ if (
383
+ isinstance(self.fc2.weight, torch.Tensor)
384
+ and hidden_states.dtype != self.fc2.weight.dtype
385
+ and (self.fc2.weight.dtype != torch.int8 and self.fc2.weight.dtype != torch.uint8)
386
+ ):
387
+ hidden_states = hidden_states.to(self.fc2.weight.dtype)
388
+ hidden_states = self.fc2(hidden_states)
389
+ return hidden_states
390
+
391
+
392
+ class NllbMoeSparseMLP(nn.Module):
393
+ r"""
394
+ Implementation of the NLLB-MoE sparse MLP module.
395
+ """
396
+
397
+ def __init__(self, config: NllbMoeConfig, ffn_dim: int, expert_class: nn.Module = NllbMoeDenseActDense):
398
+ super().__init__()
399
+ self.router = NllbMoeTop2Router(config)
400
+ self.moe_token_dropout = config.moe_token_dropout
401
+ self.token_dropout = nn.Dropout(self.moe_token_dropout)
402
+ self.num_experts = config.num_experts
403
+
404
+ self.experts = nn.ModuleDict()
405
+ for idx in range(self.num_experts):
406
+ self.experts[f"expert_{idx}"] = expert_class(config, ffn_dim)
407
+
408
+ def forward(self, hidden_states: torch.Tensor, padding_mask: Optional[torch.Tensor] = False):
409
+ r"""
410
+ The goal of this forward pass is to have the same number of operation as the equivalent `NllbMoeDenseActDense`
411
+ (mlp) layer. This means that all of the hidden states should be processed at most twice ( since we are using a
412
+ top_2 gating mecanism). This means that we keep the complexity to O(batch_size x sequence_length x hidden_dim)
413
+ instead of O(num_experts x batch_size x sequence_length x hidden_dim).
414
+
415
+ 1- Get the `router_probs` from the `router`. The shape of the `router_mask` is `(batch_size X sequence_length,
416
+ num_expert)` and corresponds to the boolean version of the `router_probs`. The inputs are masked using the
417
+ `router_mask`.
418
+
419
+ 2- Dispatch the hidden_states to its associated experts. The router probabilities are used to weight the
420
+ contribution of each experts when updating the masked hidden states.
421
+
422
+ Args:
423
+ hidden_states (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_dim)`):
424
+ The hidden states
425
+ padding_mask (`torch.Tensor`, *optional*, defaults to `False`):
426
+ Attention mask. Can be in the causal form or not.
427
+
428
+ Returns:
429
+ hidden_states (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_dim)`):
430
+ Updated hidden states
431
+ router_logits (`torch.Tensor` of shape `(batch_size, sequence_length, num_experts)`):
432
+ Needed for computing the loss
433
+
434
+ """
435
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
436
+
437
+ top_1_mask, router_probs = self.router(hidden_states, padding_mask)
438
+ router_mask = router_probs.bool()
439
+ hidden_states = hidden_states.reshape((batch_size * sequence_length), hidden_dim)
440
+ masked_hidden_states = torch.einsum("bm,be->ebm", hidden_states, router_mask)
441
+ for idx, expert in enumerate(self.experts.values()):
442
+ token_indices = router_mask[:, idx]
443
+ combining_weights = router_probs[token_indices, idx]
444
+ expert_output = expert(masked_hidden_states[idx, token_indices])
445
+ if self.moe_token_dropout > 0:
446
+ if self.training:
447
+ expert_output = self.token_dropout(expert_output)
448
+ else:
449
+ expert_output *= 1 - self.moe_token_dropout
450
+ masked_hidden_states[idx, token_indices] = torch.einsum("b,be->be", combining_weights, expert_output)
451
+ hidden_states = masked_hidden_states.sum(dim=0).reshape(batch_size, sequence_length, hidden_dim)
452
+
453
+ top_1_expert_index = torch.argmax(top_1_mask, dim=-1)
454
+ return hidden_states, (router_probs, top_1_expert_index)
455
+
456
+
457
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->NllbMoe,key_value_states->encoder_hidden_states
458
+ class NllbMoeAttention(nn.Module):
459
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
460
+
461
+ def __init__(
462
+ self,
463
+ embed_dim: int,
464
+ num_heads: int,
465
+ dropout: float = 0.0,
466
+ is_decoder: bool = False,
467
+ bias: bool = True,
468
+ is_causal: bool = False,
469
+ config: Optional[NllbMoeConfig] = None,
470
+ ):
471
+ super().__init__()
472
+ self.embed_dim = embed_dim
473
+ self.num_heads = num_heads
474
+ self.dropout = dropout
475
+ self.head_dim = embed_dim // num_heads
476
+ self.config = config
477
+
478
+ if (self.head_dim * num_heads) != self.embed_dim:
479
+ raise ValueError(
480
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
481
+ f" and `num_heads`: {num_heads})."
482
+ )
483
+ self.scaling = self.head_dim**-0.5
484
+ self.is_decoder = is_decoder
485
+ self.is_causal = is_causal
486
+
487
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
488
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
489
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
490
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
491
+
492
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
493
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
494
+
495
+ def forward(
496
+ self,
497
+ hidden_states: torch.Tensor,
498
+ encoder_hidden_states: Optional[torch.Tensor] = None,
499
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
500
+ attention_mask: Optional[torch.Tensor] = None,
501
+ layer_head_mask: Optional[torch.Tensor] = None,
502
+ output_attentions: bool = False,
503
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
504
+ """Input shape: Batch x Time x Channel"""
505
+
506
+ # if encoder_hidden_states are provided this layer is used as a cross-attention layer
507
+ # for the decoder
508
+ is_cross_attention = encoder_hidden_states is not None
509
+
510
+ bsz, tgt_len, _ = hidden_states.size()
511
+
512
+ # get query proj
513
+ query_states = self.q_proj(hidden_states) * self.scaling
514
+ # get key, value proj
515
+ # `past_key_value[0].shape[2] == encoder_hidden_states.shape[1]`
516
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
517
+ # the provided `encoder_hidden_states` to support prefix tuning
518
+ if (
519
+ is_cross_attention
520
+ and past_key_value is not None
521
+ and past_key_value[0].shape[2] == encoder_hidden_states.shape[1]
522
+ ):
523
+ # reuse k,v, cross_attentions
524
+ key_states = past_key_value[0]
525
+ value_states = past_key_value[1]
526
+ elif is_cross_attention:
527
+ # cross_attentions
528
+ key_states = self._shape(self.k_proj(encoder_hidden_states), -1, bsz)
529
+ value_states = self._shape(self.v_proj(encoder_hidden_states), -1, bsz)
530
+ elif past_key_value is not None:
531
+ # reuse k, v, self_attention
532
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
533
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
534
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
535
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
536
+ else:
537
+ # self_attention
538
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
539
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
540
+
541
+ if self.is_decoder:
542
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
543
+ # Further calls to cross_attention layer can then reuse all cross-attention
544
+ # key/value_states (first "if" case)
545
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
546
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
547
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
548
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
549
+ past_key_value = (key_states, value_states)
550
+
551
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
552
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
553
+ key_states = key_states.reshape(*proj_shape)
554
+ value_states = value_states.reshape(*proj_shape)
555
+
556
+ src_len = key_states.size(1)
557
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
558
+
559
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
560
+ raise ValueError(
561
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
562
+ f" {attn_weights.size()}"
563
+ )
564
+
565
+ if attention_mask is not None:
566
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
567
+ raise ValueError(
568
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
569
+ )
570
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
571
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
572
+
573
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
574
+
575
+ if layer_head_mask is not None:
576
+ if layer_head_mask.size() != (self.num_heads,):
577
+ raise ValueError(
578
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
579
+ f" {layer_head_mask.size()}"
580
+ )
581
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
582
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
583
+
584
+ if output_attentions:
585
+ # this operation is a bit awkward, but it's required to
586
+ # make sure that attn_weights keeps its gradient.
587
+ # In order to do so, attn_weights have to be reshaped
588
+ # twice and have to be reused in the following
589
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
590
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
591
+ else:
592
+ attn_weights_reshaped = None
593
+
594
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
595
+
596
+ attn_output = torch.bmm(attn_probs, value_states)
597
+
598
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
599
+ raise ValueError(
600
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
601
+ f" {attn_output.size()}"
602
+ )
603
+
604
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
605
+ attn_output = attn_output.transpose(1, 2)
606
+
607
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
608
+ # partitioned across GPUs when using tensor-parallelism.
609
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
610
+
611
+ attn_output = self.out_proj(attn_output)
612
+
613
+ return attn_output, attn_weights_reshaped, past_key_value
614
+
615
+
616
+ class NllbMoeEncoderLayer(nn.Module):
617
+ def __init__(self, config: NllbMoeConfig, is_sparse: bool = False):
618
+ super().__init__()
619
+ self.embed_dim = config.d_model
620
+ self.is_sparse = is_sparse
621
+ self.self_attn = NllbMoeAttention(
622
+ embed_dim=self.embed_dim,
623
+ num_heads=config.encoder_attention_heads,
624
+ dropout=config.attention_dropout,
625
+ )
626
+ self.attn_dropout = nn.Dropout(config.dropout)
627
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
628
+ if not self.is_sparse:
629
+ self.ffn = NllbMoeDenseActDense(config, ffn_dim=config.encoder_ffn_dim)
630
+ else:
631
+ self.ffn = NllbMoeSparseMLP(config, ffn_dim=config.encoder_ffn_dim)
632
+ self.ff_layer_norm = nn.LayerNorm(config.d_model)
633
+ self.ff_dropout = nn.Dropout(config.activation_dropout)
634
+
635
+ def forward(
636
+ self,
637
+ hidden_states: torch.Tensor,
638
+ attention_mask: torch.Tensor,
639
+ layer_head_mask: torch.Tensor,
640
+ output_attentions: bool = False,
641
+ output_router_logits: bool = False,
642
+ ) -> torch.Tensor:
643
+ """
644
+ Args:
645
+ hidden_states (`torch.FloatTensor`):
646
+ input to the layer of shape `(batch, seq_len, embed_dim)`
647
+ attention_mask (`torch.FloatTensor`):
648
+ attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very
649
+ large negative values.
650
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
651
+ `(encoder_attention_heads,)`.
652
+ output_attentions (`bool`, *optional*):
653
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
654
+ returned tensors for more detail.
655
+ """
656
+ residual = hidden_states
657
+ hidden_states = self.self_attn_layer_norm(hidden_states)
658
+ hidden_states, attn_weights, _ = self.self_attn(
659
+ hidden_states=hidden_states,
660
+ attention_mask=attention_mask,
661
+ layer_head_mask=layer_head_mask,
662
+ output_attentions=output_attentions,
663
+ )
664
+ hidden_states = self.attn_dropout(hidden_states)
665
+ hidden_states = residual + hidden_states
666
+
667
+ residual = hidden_states
668
+
669
+ hidden_states = self.ff_layer_norm(hidden_states)
670
+ if self.is_sparse:
671
+ hidden_states, router_states = self.ffn(hidden_states, attention_mask)
672
+ else:
673
+ # router_states set to None to track which layers have None gradients.
674
+ hidden_states, router_states = self.ffn(hidden_states), None
675
+
676
+ hidden_states = self.ff_dropout(hidden_states)
677
+
678
+ hidden_states = residual + hidden_states
679
+
680
+ if hidden_states.dtype == torch.float16 and (
681
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
682
+ ):
683
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
684
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
685
+
686
+ outputs = (hidden_states,)
687
+
688
+ if output_attentions:
689
+ outputs += (attn_weights,)
690
+
691
+ if output_router_logits:
692
+ outputs += (router_states,)
693
+
694
+ return outputs
695
+
696
+
697
+ class NllbMoeDecoderLayer(nn.Module):
698
+ def __init__(self, config: NllbMoeConfig, is_sparse: bool = False):
699
+ super().__init__()
700
+ self.embed_dim = config.d_model
701
+ self.is_sparse = is_sparse
702
+ self.self_attn = NllbMoeAttention(
703
+ embed_dim=self.embed_dim,
704
+ num_heads=config.decoder_attention_heads,
705
+ dropout=config.attention_dropout,
706
+ is_decoder=True,
707
+ )
708
+ self.dropout = config.dropout
709
+ self.activation_fn = ACT2FN[config.activation_function]
710
+ self.attn_dropout = nn.Dropout(config.dropout)
711
+
712
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
713
+ self.cross_attention = NllbMoeAttention(
714
+ self.embed_dim, config.decoder_attention_heads, config.attention_dropout, is_decoder=True
715
+ )
716
+ self.cross_attention_layer_norm = nn.LayerNorm(self.embed_dim)
717
+ if not self.is_sparse:
718
+ self.ffn = NllbMoeDenseActDense(config, ffn_dim=config.decoder_ffn_dim)
719
+ else:
720
+ self.ffn = NllbMoeSparseMLP(config, ffn_dim=config.decoder_ffn_dim)
721
+ self.ff_layer_norm = nn.LayerNorm(config.d_model)
722
+ self.ff_dropout = nn.Dropout(config.activation_dropout)
723
+
724
+ def forward(
725
+ self,
726
+ hidden_states: torch.Tensor,
727
+ attention_mask: Optional[torch.Tensor] = None,
728
+ encoder_hidden_states: Optional[torch.Tensor] = None,
729
+ encoder_attention_mask: Optional[torch.Tensor] = None,
730
+ layer_head_mask: Optional[torch.Tensor] = None,
731
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
732
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
733
+ output_attentions: Optional[bool] = False,
734
+ output_router_logits: Optional[bool] = False,
735
+ use_cache: Optional[bool] = True,
736
+ ) -> torch.Tensor:
737
+ """
738
+ Args:
739
+ hidden_states (`torch.FloatTensor`):
740
+ input to the layer of shape `(batch, seq_len, embed_dim)`
741
+ attention_mask (`torch.FloatTensor`):
742
+ attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very
743
+ large negative values.
744
+ encoder_hidden_states (`torch.FloatTensor`):
745
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
746
+ encoder_attention_mask (`torch.FloatTensor`):
747
+ encoder attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by
748
+ very large negative values.
749
+ layer_head_mask (`torch.FloatTensor`):
750
+ mask for attention heads in a given layer of size `(encoder_attention_heads,)`.
751
+ cross_attn_layer_head_mask (`torch.FloatTensor`):
752
+ mask for cross-attention heads in a given layer of size `(decoder_attention_heads,)`.
753
+ past_key_value (`Tuple(torch.FloatTensor)`):
754
+ cached past key and value projection states
755
+ output_attentions (`bool`, *optional*):
756
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
757
+ returned tensors for more detail.
758
+ """
759
+ residual = hidden_states
760
+ hidden_states = self.self_attn_layer_norm(hidden_states)
761
+
762
+ # Self Attention
763
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
764
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
765
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
766
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
767
+ hidden_states=hidden_states,
768
+ past_key_value=self_attn_past_key_value,
769
+ attention_mask=attention_mask,
770
+ layer_head_mask=layer_head_mask,
771
+ output_attentions=output_attentions,
772
+ )
773
+ hidden_states = self.attn_dropout(hidden_states)
774
+ hidden_states = residual + hidden_states
775
+
776
+ # Cross-Attention Block
777
+ cross_attn_present_key_value = None
778
+ cross_attn_weights = None
779
+ if encoder_hidden_states is not None:
780
+ residual = hidden_states
781
+ hidden_states = self.cross_attention_layer_norm(hidden_states)
782
+
783
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
784
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
785
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.cross_attention(
786
+ hidden_states=hidden_states,
787
+ encoder_hidden_states=encoder_hidden_states,
788
+ past_key_value=cross_attn_past_key_value,
789
+ attention_mask=encoder_attention_mask,
790
+ layer_head_mask=cross_attn_layer_head_mask,
791
+ output_attentions=output_attentions,
792
+ )
793
+ hidden_states = self.attn_dropout(hidden_states)
794
+ hidden_states = residual + hidden_states
795
+
796
+ # add cross-attn to positions 3,4 of present_key_value tuple
797
+ present_key_value += cross_attn_present_key_value
798
+
799
+ # Fully Connected
800
+ residual = hidden_states
801
+
802
+ hidden_states = self.ff_layer_norm(hidden_states)
803
+ if self.is_sparse:
804
+ hidden_states, router_states = self.ffn(hidden_states, attention_mask)
805
+ else:
806
+ hidden_states, router_states = self.ffn(hidden_states), None
807
+
808
+ hidden_states = self.ff_dropout(hidden_states)
809
+
810
+ hidden_states = residual + hidden_states
811
+
812
+ # clamp inf values to enable fp16 training
813
+ if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
814
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
815
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
816
+
817
+ outputs = (hidden_states, present_key_value)
818
+
819
+ if output_attentions:
820
+ outputs += (self_attn_weights, cross_attn_weights)
821
+
822
+ if output_router_logits:
823
+ outputs += (router_states,)
824
+
825
+ return outputs
826
+
827
+
828
+ class NllbMoePreTrainedModel(PreTrainedModel):
829
+ config_class = NllbMoeConfig
830
+ base_model_prefix = "model"
831
+ supports_gradient_checkpointing = True
832
+ _no_split_modules = ["NllbMoeEncoderLayer", "NllbMoeDecoderLayer"]
833
+
834
+ def _init_weights(self, module):
835
+ """Initialize the weights"""
836
+ std = self.config.init_std
837
+ if isinstance(module, nn.Linear):
838
+ module.weight.data.normal_(mean=0.0, std=std)
839
+ if module.bias is not None:
840
+ module.bias.data.zero_()
841
+ elif isinstance(module, nn.Embedding):
842
+ module.weight.data.normal_(mean=0.0, std=std)
843
+ if module.padding_idx is not None:
844
+ module.weight.data[module.padding_idx].zero_()
845
+
846
+
847
+ NLLB_MOE_START_DOCSTRING = r"""
848
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
849
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
850
+ etc.)
851
+
852
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
853
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
854
+ and behavior.
855
+
856
+ Parameters:
857
+ config ([`NllbMoeConfig`]):
858
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
859
+ load the weights associated with the model, only the configuration. Check out the
860
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
861
+ """
862
+
863
+ NLLB_MOE_GENERATION_EXAMPLE = r"""
864
+ Translation example:
865
+
866
+ ```python
867
+ >>> from transformers import AutoTokenizer, NllbMoeForConditionalGeneration
868
+
869
+ >>> model = NllbMoeForConditionalGeneration.from_pretrained("facebook/nllb-moe-54b")
870
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/nllb-moe-54b")
871
+
872
+ >>> text_to_translate = "Life is like a box of chocolates"
873
+ >>> model_inputs = tokenizer(text_to_translate, return_tensors="pt")
874
+
875
+ >>> # translate to French
876
+ >>> gen_tokens = model.generate(**model_inputs, forced_bos_token_id=tokenizer.get_lang_id("eng_Latn"))
877
+ >>> print(tokenizer.batch_decode(gen_tokens, skip_special_tokens=True))
878
+ ```
879
+ """
880
+
881
+ NLLB_MOE_INPUTS_DOCSTRING = r"""
882
+ Args:
883
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
884
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
885
+ it.
886
+
887
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
888
+ [`PreTrainedTokenizer.__call__`] for details.
889
+
890
+ [What are input IDs?](../glossary#input-ids)
891
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
892
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
893
+
894
+ - 1 for tokens that are **not masked**,
895
+ - 0 for tokens that are **masked**.
896
+
897
+ [What are attention masks?](../glossary#attention-mask)
898
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
899
+ Indices of decoder input sequence tokens in the vocabulary.
900
+
901
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
902
+ [`PreTrainedTokenizer.__call__`] for details.
903
+
904
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
905
+
906
+ NllbMoe uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If
907
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
908
+ `past_key_values`).
909
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
910
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
911
+ be used by default.
912
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
913
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
914
+
915
+ - 1 indicates the head is **not masked**,
916
+ - 0 indicates the head is **masked**.
917
+
918
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
919
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
920
+
921
+ - 1 indicates the head is **not masked**,
922
+ - 0 indicates the head is **masked**.
923
+
924
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
925
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
926
+ 1]`:
927
+
928
+ - 1 indicates the head is **not masked**,
929
+ - 0 indicates the head is **masked**.
930
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
931
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
932
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
933
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
934
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
935
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
936
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
937
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
938
+
939
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
940
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
941
+
942
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
943
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
944
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
945
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
946
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
947
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
948
+ than the model's internal embedding lookup matrix.
949
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
950
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
951
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
952
+ input (see `past_key_values`). This is useful if you want more control over how to convert
953
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
954
+
955
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
956
+ of `inputs_embeds`.
957
+ use_cache (`bool`, *optional*):
958
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
959
+ `past_key_values`).
960
+ output_attentions (`bool`, *optional*):
961
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
962
+ tensors for more detail.
963
+ output_hidden_states (`bool`, *optional*):
964
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
965
+ more detail.
966
+ output_router_logits (`bool`, *optional*):
967
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
968
+ should not be returned during inference.
969
+ return_dict (`bool`, *optional*):
970
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
971
+ """
972
+
973
+
974
+ class NllbMoeEncoder(NllbMoePreTrainedModel):
975
+ """
976
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
977
+ [`NllbMoeEncoderLayer`].
978
+
979
+ Args:
980
+ config:
981
+ NllbMoeConfig
982
+ embed_tokens (nn.Embedding):
983
+ output embedding
984
+ """
985
+
986
+ def __init__(self, config: NllbMoeConfig, embed_tokens: Optional[nn.Embedding] = None):
987
+ super().__init__(config)
988
+
989
+ self.dropout = config.dropout
990
+ self.layerdrop = config.encoder_layerdrop
991
+
992
+ embed_dim = config.d_model
993
+ self.padding_idx = config.pad_token_id
994
+ self.max_source_positions = config.max_position_embeddings
995
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
996
+
997
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
998
+
999
+ if embed_tokens is not None:
1000
+ self.embed_tokens.weight = embed_tokens.weight
1001
+
1002
+ self.embed_positions = NllbMoeSinusoidalPositionalEmbedding(
1003
+ config.max_position_embeddings,
1004
+ embed_dim,
1005
+ self.padding_idx,
1006
+ )
1007
+ sparse_step = config.encoder_sparse_step
1008
+ self.layers = nn.ModuleList()
1009
+ for i in range(config.encoder_layers):
1010
+ is_sparse = (i + 1) % sparse_step == 0 if sparse_step > 0 else False
1011
+ self.layers.append(NllbMoeEncoderLayer(config, is_sparse))
1012
+
1013
+ self.layer_norm = nn.LayerNorm(config.d_model)
1014
+
1015
+ self.gradient_checkpointing = False
1016
+ # Initialize weights and apply final processing
1017
+ self.post_init()
1018
+
1019
+ def forward(
1020
+ self,
1021
+ input_ids: Optional[torch.Tensor] = None,
1022
+ attention_mask: Optional[torch.Tensor] = None,
1023
+ head_mask: Optional[torch.Tensor] = None,
1024
+ inputs_embeds: Optional[torch.Tensor] = None,
1025
+ output_attentions: Optional[bool] = None,
1026
+ output_hidden_states: Optional[bool] = None,
1027
+ output_router_logits: Optional[bool] = None,
1028
+ return_dict: Optional[bool] = None,
1029
+ ):
1030
+ r"""
1031
+ Args:
1032
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1033
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1034
+ provide it.
1035
+
1036
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1037
+ [`PreTrainedTokenizer.__call__`] for details.
1038
+
1039
+ [What are input IDs?](../glossary#input-ids)
1040
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1041
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1042
+
1043
+ - 1 for tokens that are **not masked**,
1044
+ - 0 for tokens that are **masked**.
1045
+
1046
+ [What are attention masks?](../glossary#attention-mask)
1047
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
1048
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1049
+
1050
+ - 1 indicates the head is **not masked**,
1051
+ - 0 indicates the head is **masked**.
1052
+
1053
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1054
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1055
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1056
+ than the model's internal embedding lookup matrix.
1057
+ output_attentions (`bool`, *optional*):
1058
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1059
+ returned tensors for more detail.
1060
+ output_hidden_states (`bool`, *optional*):
1061
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1062
+ for more detail.
1063
+ output_router_logits (`bool`, *optional*):
1064
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
1065
+ and should not be returned during inference.
1066
+ return_dict (`bool`, *optional*):
1067
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1068
+ """
1069
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1070
+ output_hidden_states = (
1071
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1072
+ )
1073
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1074
+
1075
+ # retrieve input_ids and inputs_embeds
1076
+ if input_ids is not None and inputs_embeds is not None:
1077
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1078
+ elif input_ids is not None:
1079
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1080
+ input_shape = input_ids.size()
1081
+ input_ids = input_ids.view(-1, input_shape[-1])
1082
+ elif inputs_embeds is not None:
1083
+ input_shape = inputs_embeds.size()[:-1]
1084
+ else:
1085
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1086
+
1087
+ if inputs_embeds is None:
1088
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
1089
+
1090
+ embed_pos = self.embed_positions(input_ids, inputs_embeds)
1091
+ embed_pos = embed_pos.to(inputs_embeds.device)
1092
+
1093
+ hidden_states = inputs_embeds + embed_pos
1094
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1095
+
1096
+ # expand attention_mask
1097
+ if attention_mask is not None:
1098
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1099
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
1100
+
1101
+ encoder_states = () if output_hidden_states else None
1102
+ all_router_probs = () if output_router_logits else None
1103
+ all_attentions = () if output_attentions else None
1104
+
1105
+ # check if head_mask has a correct number of layers specified if desired
1106
+ if head_mask is not None:
1107
+ if head_mask.size()[0] != len(self.layers):
1108
+ raise ValueError(
1109
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
1110
+ f" {head_mask.size()[0]}."
1111
+ )
1112
+
1113
+ for idx, encoder_layer in enumerate(self.layers):
1114
+ if output_hidden_states:
1115
+ encoder_states = encoder_states + (hidden_states,)
1116
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1117
+ dropout_probability = torch.rand([])
1118
+ if self.training and (dropout_probability < self.layerdrop): # skip the layer
1119
+ layer_outputs = (None, None, None)
1120
+ else:
1121
+ if self.gradient_checkpointing and self.training:
1122
+ layer_outputs = self._gradient_checkpointing_func(
1123
+ encoder_layer.__call__,
1124
+ hidden_states,
1125
+ attention_mask,
1126
+ (head_mask[idx] if head_mask is not None else None),
1127
+ output_attentions,
1128
+ )
1129
+ else:
1130
+ layer_outputs = encoder_layer(
1131
+ hidden_states,
1132
+ attention_mask,
1133
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1134
+ output_attentions=output_attentions,
1135
+ output_router_logits=output_router_logits,
1136
+ )
1137
+
1138
+ hidden_states = layer_outputs[0]
1139
+
1140
+ if output_attentions:
1141
+ all_attentions += (layer_outputs[1],)
1142
+
1143
+ if output_router_logits:
1144
+ all_router_probs += (layer_outputs[-1],)
1145
+
1146
+ last_hidden_state = self.layer_norm(hidden_states)
1147
+
1148
+ if output_hidden_states:
1149
+ encoder_states += (last_hidden_state,)
1150
+
1151
+ if not return_dict:
1152
+ return tuple(
1153
+ v for v in [last_hidden_state, encoder_states, all_attentions, all_router_probs] if v is not None
1154
+ )
1155
+
1156
+ return MoEModelOutput(
1157
+ last_hidden_state=last_hidden_state,
1158
+ hidden_states=encoder_states,
1159
+ attentions=all_attentions,
1160
+ router_probs=all_router_probs,
1161
+ )
1162
+
1163
+
1164
+ class NllbMoeDecoder(NllbMoePreTrainedModel):
1165
+ """
1166
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`NllbMoeDecoderLayer`]
1167
+
1168
+ Args:
1169
+ config:
1170
+ NllbMoeConfig
1171
+ embed_tokens (nn.Embedding):
1172
+ output embedding
1173
+ """
1174
+
1175
+ def __init__(self, config: NllbMoeConfig, embed_tokens: Optional[nn.Embedding] = None):
1176
+ super().__init__(config)
1177
+ self.dropout = config.dropout
1178
+ self.layerdrop = config.decoder_layerdrop
1179
+ self.padding_idx = config.pad_token_id
1180
+ self.max_target_positions = config.max_position_embeddings
1181
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
1182
+
1183
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
1184
+
1185
+ if embed_tokens is not None:
1186
+ self.embed_tokens.weight = embed_tokens.weight
1187
+
1188
+ self.embed_positions = NllbMoeSinusoidalPositionalEmbedding(
1189
+ config.max_position_embeddings,
1190
+ config.d_model,
1191
+ self.padding_idx,
1192
+ )
1193
+
1194
+ sparse_step = config.decoder_sparse_step
1195
+ self.layers = nn.ModuleList()
1196
+ for i in range(config.decoder_layers):
1197
+ is_sparse = (i + 1) % sparse_step == 0 if sparse_step > 0 else False
1198
+ self.layers.append(NllbMoeDecoderLayer(config, is_sparse))
1199
+
1200
+ self.layer_norm = nn.LayerNorm(config.d_model)
1201
+
1202
+ self.gradient_checkpointing = False
1203
+ # Initialize weights and apply final processing
1204
+ self.post_init()
1205
+
1206
+ def forward(
1207
+ self,
1208
+ input_ids: Optional[torch.Tensor] = None,
1209
+ attention_mask: Optional[torch.Tensor] = None,
1210
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1211
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1212
+ head_mask: Optional[torch.Tensor] = None,
1213
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1214
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1215
+ inputs_embeds: Optional[torch.Tensor] = None,
1216
+ use_cache: Optional[bool] = None,
1217
+ output_attentions: Optional[bool] = None,
1218
+ output_hidden_states: Optional[bool] = None,
1219
+ output_router_logits: Optional[bool] = None,
1220
+ return_dict: Optional[bool] = None,
1221
+ ):
1222
+ r"""
1223
+ Args:
1224
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1225
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1226
+ provide it.
1227
+
1228
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1229
+ [`PreTrainedTokenizer.__call__`] for details.
1230
+
1231
+ [What are input IDs?](../glossary#input-ids)
1232
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1233
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1234
+
1235
+ - 1 for tokens that are **not masked**,
1236
+ - 0 for tokens that are **masked**.
1237
+
1238
+ [What are attention masks?](../glossary#attention-mask)
1239
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
1240
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1241
+ of the decoder.
1242
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
1243
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
1244
+ selected in `[0, 1]`:
1245
+
1246
+ - 1 for tokens that are **not masked**,
1247
+ - 0 for tokens that are **masked**.
1248
+
1249
+ [What are attention masks?](../glossary#attention-mask)
1250
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1251
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1252
+
1253
+ - 1 indicates the head is **not masked**,
1254
+ - 0 indicates the head is **masked**.
1255
+
1256
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1257
+ Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
1258
+ cross-attention on hidden heads. Mask values selected in `[0, 1]`:
1259
+
1260
+ - 1 indicates the head is **not masked**,
1261
+ - 0 indicates the head is **masked**.
1262
+
1263
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1264
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1265
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1266
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
1267
+
1268
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1269
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1270
+
1271
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1272
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1273
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1274
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1275
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1276
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1277
+ than the model's internal embedding lookup matrix.
1278
+ output_attentions (`bool`, *optional*):
1279
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1280
+ returned tensors for more detail.
1281
+ output_hidden_states (`bool`, *optional*):
1282
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1283
+ for more detail.
1284
+ output_router_logits (`bool`, *optional*):
1285
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
1286
+ and should not be returned during inference.
1287
+ return_dict (`bool`, *optional*):
1288
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1289
+ """
1290
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1291
+ output_hidden_states = (
1292
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1293
+ )
1294
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1295
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1296
+
1297
+ # retrieve input_ids and inputs_embeds
1298
+ if input_ids is not None and inputs_embeds is not None:
1299
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1300
+ elif input_ids is not None:
1301
+ input_shape = input_ids.size()
1302
+ input_ids = input_ids.view(-1, input_shape[-1])
1303
+ elif inputs_embeds is not None:
1304
+ input_shape = inputs_embeds.size()[:-1]
1305
+ else:
1306
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1307
+
1308
+ # past_key_values_length
1309
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1310
+
1311
+ if inputs_embeds is None:
1312
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
1313
+
1314
+ # create causal mask
1315
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1316
+ combined_attention_mask = _prepare_4d_causal_attention_mask(
1317
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
1318
+ )
1319
+
1320
+ # expand encoder attention mask
1321
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1322
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1323
+ encoder_attention_mask = _prepare_4d_attention_mask(
1324
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
1325
+ )
1326
+
1327
+ # embed positions
1328
+ positions = self.embed_positions(input_ids, inputs_embeds, past_key_values_length)
1329
+ positions = positions.to(inputs_embeds.device)
1330
+
1331
+ hidden_states = inputs_embeds + positions
1332
+
1333
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1334
+
1335
+ if self.gradient_checkpointing and self.training:
1336
+ if use_cache:
1337
+ logger.warning_once(
1338
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting" " `use_cache=False`..."
1339
+ )
1340
+ use_cache = False
1341
+
1342
+ # decoder layers
1343
+ all_hidden_states = () if output_hidden_states else None
1344
+ all_self_attns = () if output_attentions else None
1345
+ all_router_probs = () if output_router_logits else None
1346
+ all_cross_attentions = () if output_attentions else None
1347
+ present_key_value_states = () if use_cache else None
1348
+
1349
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
1350
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
1351
+ if attn_mask is not None:
1352
+ if attn_mask.size()[0] != len(self.layers):
1353
+ raise ValueError(
1354
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
1355
+ f" {head_mask.size()[0]}."
1356
+ )
1357
+ deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()
1358
+
1359
+ for idx, decoder_layer in enumerate(self.layers):
1360
+ if output_hidden_states:
1361
+ all_hidden_states += (hidden_states,)
1362
+
1363
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1364
+ dropout_probability = torch.rand([])
1365
+
1366
+ skip_the_layer = True if self.training and (dropout_probability < self.layerdrop) else False
1367
+ if not skip_the_layer or deepspeed_zero3_is_enabled:
1368
+ layer_head_mask = head_mask[idx] if head_mask is not None else None
1369
+ cross_attn_layer_head_mask = cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
1370
+
1371
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1372
+
1373
+ # under deepspeed zero3 all gpus must run in sync
1374
+ if self.gradient_checkpointing and self.training:
1375
+ if use_cache:
1376
+ logger.warning_once(
1377
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1378
+ )
1379
+ use_cache = False
1380
+ layer_outputs = self._gradient_checkpointing_func(
1381
+ decoder_layer.forward,
1382
+ hidden_states,
1383
+ combined_attention_mask,
1384
+ encoder_hidden_states,
1385
+ encoder_attention_mask,
1386
+ layer_head_mask,
1387
+ cross_attn_layer_head_mask,
1388
+ None, # past_key_value is always None with gradient checkpointing
1389
+ use_cache,
1390
+ output_attentions,
1391
+ )
1392
+ else:
1393
+ layer_outputs = decoder_layer(
1394
+ hidden_states,
1395
+ attention_mask=combined_attention_mask,
1396
+ encoder_hidden_states=encoder_hidden_states,
1397
+ encoder_attention_mask=encoder_attention_mask,
1398
+ layer_head_mask=layer_head_mask,
1399
+ cross_attn_layer_head_mask=cross_attn_layer_head_mask,
1400
+ past_key_value=past_key_value,
1401
+ use_cache=use_cache,
1402
+ output_attentions=output_attentions,
1403
+ output_router_logits=output_router_logits,
1404
+ )
1405
+
1406
+ hidden_states = layer_outputs[0]
1407
+
1408
+ if skip_the_layer:
1409
+ continue
1410
+
1411
+ if use_cache:
1412
+ present_key_value_states += (layer_outputs[1],)
1413
+
1414
+ if output_attentions:
1415
+ all_self_attns += (layer_outputs[2],)
1416
+ all_cross_attentions += (layer_outputs[3],)
1417
+
1418
+ if output_router_logits:
1419
+ all_router_probs += (layer_outputs[-1],)
1420
+
1421
+ hidden_states = self.layer_norm(hidden_states)
1422
+
1423
+ # Add last layer
1424
+ if output_hidden_states:
1425
+ all_hidden_states += (hidden_states,)
1426
+
1427
+ if not return_dict:
1428
+ return tuple(
1429
+ v
1430
+ for v in [
1431
+ hidden_states,
1432
+ present_key_value_states,
1433
+ all_hidden_states,
1434
+ all_self_attns,
1435
+ all_cross_attentions,
1436
+ all_router_probs,
1437
+ ]
1438
+ if v is not None
1439
+ )
1440
+ return MoEModelOutputWithPastAndCrossAttentions(
1441
+ last_hidden_state=hidden_states,
1442
+ past_key_values=present_key_value_states,
1443
+ hidden_states=all_hidden_states,
1444
+ attentions=all_self_attns,
1445
+ cross_attentions=all_cross_attentions,
1446
+ router_probs=all_router_probs,
1447
+ )
1448
+
1449
+
1450
+ @add_start_docstrings(
1451
+ "The bare NllbMoe Model outputting raw hidden-states without any specific head on top.",
1452
+ NLLB_MOE_START_DOCSTRING,
1453
+ )
1454
+ class NllbMoeModel(NllbMoePreTrainedModel):
1455
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1456
+
1457
+ def __init__(self, config: NllbMoeConfig):
1458
+ super().__init__(config)
1459
+
1460
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
1461
+ self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
1462
+
1463
+ self.encoder = NllbMoeEncoder(config, self.shared)
1464
+ self.decoder = NllbMoeDecoder(config, self.shared)
1465
+
1466
+ # Initialize weights and apply final processing
1467
+ self.post_init()
1468
+
1469
+ def get_input_embeddings(self):
1470
+ return self.shared
1471
+
1472
+ def set_input_embeddings(self, value):
1473
+ self.shared = value
1474
+ self.encoder.embed_tokens = self.shared
1475
+ self.decoder.embed_tokens = self.shared
1476
+
1477
+ def _tie_weights(self):
1478
+ if self.config.tie_word_embeddings:
1479
+ self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared)
1480
+ self._tie_or_clone_weights(self.decoder.embed_tokens, self.shared)
1481
+
1482
+ def get_encoder(self):
1483
+ return self.encoder
1484
+
1485
+ def get_decoder(self):
1486
+ return self.decoder
1487
+
1488
+ @add_start_docstrings_to_model_forward(NLLB_MOE_INPUTS_DOCSTRING)
1489
+ @add_start_docstrings_to_model_forward(NLLB_MOE_INPUTS_DOCSTRING)
1490
+ @replace_return_docstrings(output_type=Seq2SeqMoEModelOutput, config_class=_CONFIG_FOR_DOC)
1491
+ def forward(
1492
+ self,
1493
+ input_ids: Optional[torch.LongTensor] = None,
1494
+ attention_mask: Optional[torch.Tensor] = None,
1495
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1496
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1497
+ head_mask: Optional[torch.Tensor] = None,
1498
+ decoder_head_mask: Optional[torch.Tensor] = None,
1499
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1500
+ encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1501
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1502
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1503
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1504
+ use_cache: Optional[bool] = None,
1505
+ output_attentions: Optional[bool] = None,
1506
+ output_hidden_states: Optional[bool] = None,
1507
+ output_router_logits: Optional[bool] = None,
1508
+ return_dict: Optional[bool] = None,
1509
+ ) -> Union[Tuple[torch.Tensor], Seq2SeqMoEModelOutput]:
1510
+ r"""
1511
+ Returns:
1512
+
1513
+ Example:
1514
+
1515
+ ```python
1516
+ >>> from transformers import AutoTokenizer, NllbMoeModel
1517
+
1518
+ >>> tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/random-nllb-moe-2-experts")
1519
+ >>> model = SwitchTransformersModel.from_pretrained("hf-internal-testing/random-nllb-moe-2-experts")
1520
+
1521
+ >>> input_ids = tokenizer(
1522
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
1523
+ ... ).input_ids # Batch size 1
1524
+ >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1
1525
+
1526
+ >>> # preprocess: Prepend decoder_input_ids with start token which is pad token for NllbMoeModel
1527
+ >>> decoder_input_ids = model._shift_right(decoder_input_ids)
1528
+
1529
+ >>> # forward pass
1530
+ >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
1531
+ >>> last_hidden_states = outputs.last_hidden_state
1532
+ ```"""
1533
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1534
+ if encoder_outputs is None:
1535
+ encoder_outputs = self.encoder(
1536
+ input_ids=input_ids,
1537
+ attention_mask=attention_mask,
1538
+ head_mask=head_mask,
1539
+ inputs_embeds=inputs_embeds,
1540
+ output_attentions=output_attentions,
1541
+ output_hidden_states=output_hidden_states,
1542
+ output_router_logits=output_router_logits,
1543
+ return_dict=return_dict,
1544
+ )
1545
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1546
+ elif return_dict and not isinstance(encoder_outputs, MoEModelOutput):
1547
+ encoder_outputs = MoEModelOutput(
1548
+ last_hidden_state=encoder_outputs[0],
1549
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1550
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1551
+ router_probs=encoder_outputs[3] if len(encoder_outputs) > 3 else None,
1552
+ )
1553
+
1554
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
1555
+ decoder_outputs = self.decoder(
1556
+ input_ids=decoder_input_ids,
1557
+ attention_mask=decoder_attention_mask,
1558
+ encoder_hidden_states=encoder_outputs[0],
1559
+ encoder_attention_mask=attention_mask,
1560
+ head_mask=decoder_head_mask,
1561
+ cross_attn_head_mask=cross_attn_head_mask,
1562
+ past_key_values=past_key_values,
1563
+ inputs_embeds=decoder_inputs_embeds,
1564
+ use_cache=use_cache,
1565
+ output_attentions=output_attentions,
1566
+ output_hidden_states=output_hidden_states,
1567
+ output_router_logits=output_router_logits,
1568
+ return_dict=return_dict,
1569
+ )
1570
+
1571
+ if not return_dict:
1572
+ return decoder_outputs + encoder_outputs
1573
+
1574
+ return Seq2SeqMoEModelOutput(
1575
+ past_key_values=decoder_outputs.past_key_values,
1576
+ cross_attentions=decoder_outputs.cross_attentions,
1577
+ last_hidden_state=decoder_outputs.last_hidden_state,
1578
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1579
+ encoder_hidden_states=encoder_outputs.hidden_states,
1580
+ decoder_hidden_states=decoder_outputs.hidden_states,
1581
+ encoder_attentions=encoder_outputs.attentions,
1582
+ decoder_attentions=decoder_outputs.attentions,
1583
+ encoder_router_logits=encoder_outputs.router_probs,
1584
+ decoder_router_logits=decoder_outputs.router_probs,
1585
+ )
1586
+
1587
+
1588
+ @add_start_docstrings(
1589
+ "The NllbMoe Model with a language modeling head. Can be used for summarization.", NLLB_MOE_START_DOCSTRING
1590
+ )
1591
+ class NllbMoeForConditionalGeneration(NllbMoePreTrainedModel):
1592
+ base_model_prefix = "model"
1593
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight", "lm_head.weight"]
1594
+
1595
+ def __init__(self, config: NllbMoeConfig):
1596
+ super().__init__(config)
1597
+ self.model = NllbMoeModel(config)
1598
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
1599
+
1600
+ self.router_z_loss_coef = config.router_z_loss_coef
1601
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1602
+ # Initialize weights and apply final processing
1603
+ self.post_init()
1604
+
1605
+ def get_encoder(self):
1606
+ return self.model.get_encoder()
1607
+
1608
+ def get_decoder(self):
1609
+ return self.model.get_decoder()
1610
+
1611
+ def get_output_embeddings(self):
1612
+ return self.lm_head
1613
+
1614
+ def set_output_embeddings(self, new_embeddings):
1615
+ self.lm_head = new_embeddings
1616
+
1617
+ @add_start_docstrings_to_model_forward(NLLB_MOE_INPUTS_DOCSTRING)
1618
+ @replace_return_docstrings(output_type=Seq2SeqMoEOutput, config_class=_CONFIG_FOR_DOC)
1619
+ @add_end_docstrings(NLLB_MOE_GENERATION_EXAMPLE)
1620
+ def forward(
1621
+ self,
1622
+ input_ids: Optional[torch.LongTensor] = None,
1623
+ attention_mask: Optional[torch.Tensor] = None,
1624
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1625
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1626
+ head_mask: Optional[torch.Tensor] = None,
1627
+ decoder_head_mask: Optional[torch.Tensor] = None,
1628
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1629
+ encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1630
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1631
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1632
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1633
+ labels: Optional[torch.LongTensor] = None,
1634
+ use_cache: Optional[bool] = None,
1635
+ output_attentions: Optional[bool] = None,
1636
+ output_hidden_states: Optional[bool] = None,
1637
+ output_router_logits: Optional[bool] = None,
1638
+ return_dict: Optional[bool] = None,
1639
+ ) -> Union[Tuple[torch.Tensor], Seq2SeqMoEOutput]:
1640
+ r"""
1641
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1642
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1643
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1644
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1645
+
1646
+ Returns:
1647
+ """
1648
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1649
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1650
+ output_router_logits = (
1651
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1652
+ )
1653
+ if labels is not None:
1654
+ if decoder_input_ids is None:
1655
+ decoder_input_ids = shift_tokens_right(
1656
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1657
+ )
1658
+
1659
+ outputs = self.model(
1660
+ input_ids,
1661
+ attention_mask=attention_mask,
1662
+ decoder_input_ids=decoder_input_ids,
1663
+ encoder_outputs=encoder_outputs,
1664
+ decoder_attention_mask=decoder_attention_mask,
1665
+ head_mask=head_mask,
1666
+ decoder_head_mask=decoder_head_mask,
1667
+ cross_attn_head_mask=cross_attn_head_mask,
1668
+ past_key_values=past_key_values,
1669
+ inputs_embeds=inputs_embeds,
1670
+ decoder_inputs_embeds=decoder_inputs_embeds,
1671
+ use_cache=use_cache,
1672
+ output_attentions=output_attentions,
1673
+ output_hidden_states=output_hidden_states,
1674
+ output_router_logits=output_router_logits,
1675
+ return_dict=return_dict,
1676
+ )
1677
+ lm_logits = self.lm_head(outputs[0])
1678
+
1679
+ loss = None
1680
+ encoder_aux_loss = None
1681
+ decoder_aux_loss = None
1682
+
1683
+ if labels is not None:
1684
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1685
+ # todo check in the config if router loss enables
1686
+
1687
+ if output_router_logits:
1688
+ encoder_router_logits = outputs[-1]
1689
+ decoder_router_logits = outputs[3 if output_attentions else 4]
1690
+
1691
+ # Compute the router loss (z_loss + auxiliary loss) for each router in the encoder and decoder
1692
+ encoder_router_logits, encoder_expert_indexes = self._unpack_router_logits(encoder_router_logits)
1693
+ encoder_aux_loss = load_balancing_loss_func(encoder_router_logits, encoder_expert_indexes)
1694
+
1695
+ decoder_router_logits, decoder_expert_indexes = self._unpack_router_logits(decoder_router_logits)
1696
+ decoder_aux_loss = load_balancing_loss_func(decoder_router_logits, decoder_expert_indexes)
1697
+
1698
+ loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
1699
+
1700
+ if output_router_logits and labels is not None:
1701
+ aux_loss = self.router_aux_loss_coef * (encoder_aux_loss + decoder_aux_loss)
1702
+ loss = loss + aux_loss
1703
+
1704
+ output = (loss,) if loss is not None else ()
1705
+ if not return_dict:
1706
+ output += (lm_logits,)
1707
+ if output_router_logits: # only return the loss if they are not None
1708
+ output += (
1709
+ encoder_aux_loss,
1710
+ decoder_aux_loss,
1711
+ *outputs[1:],
1712
+ )
1713
+ else:
1714
+ output += outputs[1:]
1715
+
1716
+ return output
1717
+
1718
+ return Seq2SeqMoEOutput(
1719
+ loss=loss,
1720
+ logits=lm_logits,
1721
+ past_key_values=outputs.past_key_values,
1722
+ cross_attentions=outputs.cross_attentions,
1723
+ encoder_aux_loss=encoder_aux_loss,
1724
+ decoder_aux_loss=decoder_aux_loss,
1725
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1726
+ encoder_hidden_states=outputs.encoder_hidden_states,
1727
+ decoder_hidden_states=outputs.decoder_hidden_states,
1728
+ encoder_attentions=outputs.encoder_attentions,
1729
+ decoder_attentions=outputs.decoder_attentions,
1730
+ encoder_router_logits=outputs.encoder_router_logits,
1731
+ decoder_router_logits=outputs.decoder_router_logits,
1732
+ )
1733
+
1734
+ def _unpack_router_logits(self, router_outputs):
1735
+ total_router_logits = []
1736
+ total_expert_indexes = []
1737
+ for router_output in router_outputs:
1738
+ if router_output is not None:
1739
+ router_logits, expert_indexes = router_output
1740
+ total_router_logits.append(router_logits)
1741
+ total_expert_indexes.append(expert_indexes)
1742
+
1743
+ total_router_logits = torch.cat(total_router_logits, dim=1) if len(total_router_logits) > 0 else None
1744
+ total_expert_indexes = torch.stack(total_expert_indexes, dim=1) if len(total_expert_indexes) > 0 else None
1745
+ return total_router_logits, total_expert_indexes
1746
+
1747
+ # Copied from transfomers.models.switch_transformers.SwitchTransformersForConditionalGeneration.prepare_inputs_for_generation
1748
+ def prepare_inputs_for_generation(
1749
+ self,
1750
+ decoder_input_ids,
1751
+ past_key_values=None,
1752
+ attention_mask=None,
1753
+ head_mask=None,
1754
+ decoder_head_mask=None,
1755
+ cross_attn_head_mask=None,
1756
+ use_cache=None,
1757
+ encoder_outputs=None,
1758
+ **kwargs,
1759
+ ):
1760
+ # cut decoder_input_ids if past is used
1761
+ if past_key_values is not None:
1762
+ past_length = past_key_values[0][0].shape[2]
1763
+
1764
+ # Some generation methods already pass only the last input ID
1765
+ if decoder_input_ids.shape[1] > past_length:
1766
+ remove_prefix_length = past_length
1767
+ else:
1768
+ # Default to old behavior: keep only final ID
1769
+ remove_prefix_length = decoder_input_ids.shape[1] - 1
1770
+
1771
+ decoder_input_ids = decoder_input_ids[:, remove_prefix_length:]
1772
+
1773
+ return {
1774
+ "input_ids": None, # encoder_outputs is defined. input_ids not needed
1775
+ "encoder_outputs": encoder_outputs,
1776
+ "past_key_values": past_key_values,
1777
+ "decoder_input_ids": decoder_input_ids,
1778
+ "attention_mask": attention_mask,
1779
+ "head_mask": head_mask,
1780
+ "decoder_head_mask": decoder_head_mask,
1781
+ "cross_attn_head_mask": cross_attn_head_mask,
1782
+ "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
1783
+ }
1784
+
1785
+ @staticmethod
1786
+ def _reorder_cache(past_key_values, beam_idx):
1787
+ reordered_past = ()
1788
+ for layer_past in past_key_values:
1789
+ reordered_past += (
1790
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1791
+ )
1792
+ return reordered_past
videochat2/lib/python3.10/site-packages/transformers/models/qdqbert/__init__.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 NVIDIA Corporation and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
17
+
18
+
19
+ _import_structure = {"configuration_qdqbert": ["QDQBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "QDQBertConfig"]}
20
+
21
+ try:
22
+ if not is_torch_available():
23
+ raise OptionalDependencyNotAvailable()
24
+ except OptionalDependencyNotAvailable:
25
+ pass
26
+ else:
27
+ _import_structure["modeling_qdqbert"] = [
28
+ "QDQBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
29
+ "QDQBertForMaskedLM",
30
+ "QDQBertForMultipleChoice",
31
+ "QDQBertForNextSentencePrediction",
32
+ "QDQBertForQuestionAnswering",
33
+ "QDQBertForSequenceClassification",
34
+ "QDQBertForTokenClassification",
35
+ "QDQBertLayer",
36
+ "QDQBertLMHeadModel",
37
+ "QDQBertModel",
38
+ "QDQBertPreTrainedModel",
39
+ "load_tf_weights_in_qdqbert",
40
+ ]
41
+
42
+
43
+ if TYPE_CHECKING:
44
+ from .configuration_qdqbert import QDQBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, QDQBertConfig
45
+
46
+ try:
47
+ if not is_torch_available():
48
+ raise OptionalDependencyNotAvailable()
49
+ except OptionalDependencyNotAvailable:
50
+ pass
51
+ else:
52
+ from .modeling_qdqbert import (
53
+ QDQBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
54
+ QDQBertForMaskedLM,
55
+ QDQBertForMultipleChoice,
56
+ QDQBertForNextSentencePrediction,
57
+ QDQBertForQuestionAnswering,
58
+ QDQBertForSequenceClassification,
59
+ QDQBertForTokenClassification,
60
+ QDQBertLayer,
61
+ QDQBertLMHeadModel,
62
+ QDQBertModel,
63
+ QDQBertPreTrainedModel,
64
+ load_tf_weights_in_qdqbert,
65
+ )
66
+
67
+
68
+ else:
69
+ import sys
70
+
71
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
videochat2/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/__init__.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_torch_available,
20
+ )
21
+
22
+
23
+ _import_structure = {
24
+ "configuration_seamless_m4t_v2": ["SEAMLESS_M4T_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "SeamlessM4Tv2Config"],
25
+ }
26
+
27
+ try:
28
+ if not is_torch_available():
29
+ raise OptionalDependencyNotAvailable()
30
+ except OptionalDependencyNotAvailable:
31
+ pass
32
+ else:
33
+ _import_structure["modeling_seamless_m4t_v2"] = [
34
+ "SEAMLESS_M4T_V2_PRETRAINED_MODEL_ARCHIVE_LIST",
35
+ "SeamlessM4Tv2ForTextToSpeech",
36
+ "SeamlessM4Tv2ForSpeechToSpeech",
37
+ "SeamlessM4Tv2ForTextToText",
38
+ "SeamlessM4Tv2ForSpeechToText",
39
+ "SeamlessM4Tv2Model",
40
+ "SeamlessM4Tv2PreTrainedModel",
41
+ ]
42
+
43
+ if TYPE_CHECKING:
44
+ from .configuration_seamless_m4t_v2 import SEAMLESS_M4T_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, SeamlessM4Tv2Config
45
+
46
+ try:
47
+ if not is_torch_available():
48
+ raise OptionalDependencyNotAvailable()
49
+ except OptionalDependencyNotAvailable:
50
+ pass
51
+ else:
52
+ from .modeling_seamless_m4t_v2 import (
53
+ SEAMLESS_M4T_V2_PRETRAINED_MODEL_ARCHIVE_LIST,
54
+ SeamlessM4Tv2ForSpeechToSpeech,
55
+ SeamlessM4Tv2ForSpeechToText,
56
+ SeamlessM4Tv2ForTextToSpeech,
57
+ SeamlessM4Tv2ForTextToText,
58
+ SeamlessM4Tv2Model,
59
+ SeamlessM4Tv2PreTrainedModel,
60
+ )
61
+
62
+ else:
63
+ import sys
64
+
65
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
videochat2/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/__pycache__/configuration_seamless_m4t_v2.cpython-310.pyc ADDED
Binary file (20 kB). View file
 
videochat2/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/configuration_seamless_m4t_v2.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ SeamlessM4Tv2 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
+ from ..deprecated._archive_maps import SEAMLESS_M4T_V2_PRETRAINED_CONFIG_ARCHIVE_MAP # noqa: F401, E402
25
+
26
+
27
+ class SeamlessM4Tv2Config(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`~SeamlessM4Tv2Model`]. It is used to instantiate
30
+ an SeamlessM4Tv2 model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the SeamlessM4Tv2
32
+ [""](https://huggingface.co/"") architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 256102):
40
+ Vocabulary size of the text modality of the SeamlessM4Tv2 model. Defines the number of different tokens
41
+ that can be represented by the `inputs_ids` passed when calling [`~SeamlessM4Tv2Model`],
42
+ [`~SeamlessM4Tv2ForTextToSpeech`] or [`~SeamlessM4Tv2ForTextToText`].
43
+ t2u_vocab_size (`int`, *optional*, defaults to 10082):
44
+ Unit vocabulary size of the SeamlessM4Tv2 model. Defines the number of different "unit tokens" that can be
45
+ represented by the `inputs_ids` passed when calling the Text-To-Units sub-model of [`~SeamlessM4Tv2Model`],
46
+ [`~SeamlessM4Tv2ForSpeechToSpeech`] or [`~SeamlessM4Tv2ForTextToSpeech`].
47
+ char_vocab_size (`int`, *optional*, defaults to 10943):
48
+ Character vocabulary size of the SeamlessM4Tv2 model. Defines the number of different character tokens that
49
+ can be represented by the `char_inputs_ids` passed when calling the Text-To-Units sub-model of
50
+ [`~SeamlessM4Tv2Model`], [`~SeamlessM4Tv2ForSpeechToSpeech`] or [`~SeamlessM4Tv2ForTextToSpeech`].
51
+
52
+ > Parameters shared across sub-models
53
+
54
+ hidden_size (`int`, *optional*, defaults to 1024):
55
+ Dimensionality of the "intermediate" layers in the architecture.
56
+ initializer_range (`float`, *optional*, defaults to 0.02):
57
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
58
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
59
+ The epsilon used by the layer normalization layers.
60
+ use_cache (`bool`, *optional*, defaults to `True`):
61
+ Whether or not the model should return the last key/values attentions (not used by all models).
62
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
63
+ The maximum sequence length that this model text encoder and decoder might ever be used with. Typically set
64
+ this to something large just in case (e.g., 512 or 1024 or 2048).
65
+ is_encoder_decoder (`bool`, *optional*, defaults to `True`):
66
+ Whether the model is used as an encoder/decoder or not.
67
+ encoder_layerdrop (`float`, *optional*, defaults to 0.05):
68
+ The LayerDrop probability for the encoders. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
69
+ for more details.
70
+ decoder_layerdrop (`float`, *optional*, defaults to 0.05):
71
+ The LayerDrop probability for the decoders. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
72
+ for more details.
73
+ activation_function (`str` or `function`, *optional*, defaults to `"relu"`):
74
+ The non-linear activation function (function or string) in the decoder and feed-forward layers. If string,
75
+ `"gelu"`, `"relu"`, `"selu"`, `"swish"` and `"gelu_new"` are supported.
76
+ dropout (`float`, *optional*, defaults to 0.1):
77
+ The dropout probability for all fully connected layers in the embeddings, encoder, decoder, and pooler.
78
+ attention_dropout (`float`, *optional*, defaults to 0.1):
79
+ The dropout probability for all attention layers.
80
+ activation_dropout (`float`, *optional*, defaults to 0.0):
81
+ The dropout probability for all activation layers in the model.
82
+ scale_embedding (`bool`, *optional*, defaults to `True`):
83
+ Scale embeddings by diving by sqrt(d_model).
84
+
85
+ > Text encoder and text decoder specific parameters
86
+
87
+ encoder_layers (`int`, *optional*, defaults to 24):
88
+ Number of hidden layers in the Transformer text encoder.
89
+ encoder_ffn_dim (`int`, *optional*, defaults to 8192):
90
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer text encoder.
91
+ encoder_attention_heads (`int`, *optional*, defaults to 16):
92
+ Number of attention heads for each attention layer in the Transformer text encoder.
93
+ decoder_layers (`int`, *optional*, defaults to 24):
94
+ Number of hidden layers in the Transformer text decoder.
95
+ decoder_ffn_dim (`int`, *optional*, defaults to 8192):
96
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer text decoder.
97
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
98
+ Number of attention heads for each attention layer in the Transformer text decoder.
99
+ decoder_start_token_id (`int`, *optional*, defaults to 3):
100
+ If an encoder-decoder model starts decoding with a different token than _bos_, the id of that token. Only
101
+ applied in the text decoder.
102
+ max_new_tokens (`int`, *optional*, defaults to 256):
103
+ The maximum numbers of text tokens to generate, ignoring the number of tokens in the prompt.
104
+ pad_token_id (`int`, *optional*, defaults to 0):
105
+ The id of the _padding_ text token. Only applied to the text-decoder model.
106
+ bos_token_id (`int`, *optional*, defaults to 2):
107
+ The id of the _beginning-of-stream_ text token. Only applied to the text-decoder model.
108
+ eos_token_id (`int`, *optional*, defaults to 3):
109
+ The id of the _end-of-stream_ text token. Only applied to the text-decoder model.
110
+
111
+ > Speech encoder specific parameters
112
+
113
+ speech_encoder_layers (`int`, *optional*, defaults to 24):
114
+ Number of hidden layers in the Transformer speech encoder.
115
+ speech_encoder_attention_heads (`int`, *optional*, defaults to 16):
116
+ Number of attention heads for each attention layer in the Transformer speech encoder.
117
+ speech_encoder_intermediate_size (`int`, *optional*, defaults to 4096):
118
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer speech encoder.
119
+ speech_encoder_hidden_act (`str` or `function`, *optional*, defaults to `"swish"`):
120
+ The non-linear activation function (function or string) in the speech encoder. If string, `"gelu"`,
121
+ `"relu"`, `"selu"`, `"swish"` and `"gelu_new"` are supported.
122
+ speech_encoder_dropout (`float`, *optional*, defaults to 0.0):
123
+ The dropout probability for all layers in the speech encoder.
124
+ add_adapter (`bool`, *optional*, defaults to `True`):
125
+ Add an adapter layer on top of the speech encoder.
126
+ speech_encoder_layerdrop (`float`, *optional*, defaults to 0.1):
127
+ The LayerDrop probability for the speech encoder. See the [LayerDrop paper](see
128
+ https://arxiv.org/abs/1909.11556) for more details.
129
+ feature_projection_input_dim (`int`, *optional*, defaults to 160):
130
+ Input dimension of the input feature projection of the speech encoder, i.e the dimension after processing
131
+ input audios with [`SeamlessM4TFeatureExtractor`].
132
+ adaptor_kernel_size (`int`, *optional*, defaults to 8):
133
+ Kernel size of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
134
+ adaptor_stride (`int`, *optional*, defaults to 8):
135
+ Stride of the convolutional layers in the adapter network. Only relevant if `add_adapter is True`.
136
+ adaptor_dropout (`float`, *optional*, defaults to 0.1):
137
+ The dropout probability for all layers in the speech adapter.
138
+ num_adapter_layers (`int`, *optional*, defaults to 1):
139
+ Number of convolutional layers that should be used in the adapter network. Only relevant if `add_adapter is
140
+ True`.
141
+ position_embeddings_type (`str`, *optional*, defaults to `"relative_key"`):
142
+ Can be specified to `relative_key`. If left to `None`, no relative position embedding is applied. Only
143
+ applied to the speech encoder. For more information on `"relative_key"`, please refer to [Self-Attention
144
+ with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
145
+ conv_depthwise_kernel_size (`int`, *optional*, defaults to 31):
146
+ Kernel size of convolutional depthwise 1D layer in Conformer blocks. Only applied to the speech encoder.
147
+ left_max_position_embeddings (`int`, *optional*, defaults to 64):
148
+ The left clipping value for relative positions.
149
+ right_max_position_embeddings (`int`, *optional*, defaults to 8):
150
+ The right clipping value for relative positions.
151
+ speech_encoder_chunk_size (`int`, *optional*, defaults to 20000): The size of each attention chunk.
152
+ speech_encoder_left_chunk_num (`int`, *optional*, defaults to 128):
153
+ Number of chunks on the left up to which lookahead is allowed.
154
+
155
+ > Text-To-Unit (t2u) model specific parameters
156
+
157
+ t2u_bos_token_id (`int`, *optional*, defaults to 0):
158
+ The id of the _beginning-of-stream_ unit token. Only applied to the text-to-unit seq2seq model.
159
+ t2u_pad_token_id (`int`, *optional*, defaults to 1):
160
+ The id of the _padding_ unit token. Only applied to the text-to-unit seq2seq model.
161
+ t2u_eos_token_id (`int`, *optional*, defaults to 2):
162
+ The id of the _end-of-stream_ unit token. Only applied to the text-to-unit seq2seq model.
163
+ t2u_encoder_layers (`int`, *optional*, defaults to 6):
164
+ Number of hidden layers in the Transformer text-to-unit encoder.
165
+ t2u_encoder_ffn_dim (`int`, *optional*, defaults to 8192):
166
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer text-to-unit encoder.
167
+ t2u_encoder_attention_heads (`int`, *optional*, defaults to 16):
168
+ Number of attention heads for each attention layer in the Transformer text-to-unit encoder.
169
+ t2u_decoder_layers (`int`, *optional*, defaults to 6):
170
+ Number of hidden layers in the Transformer text-to-unit decoder.
171
+ t2u_decoder_ffn_dim (`int`, *optional*, defaults to 8192):
172
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer text-to-unit decoder.
173
+ t2u_decoder_attention_heads (`int`, *optional*, defaults to 16):
174
+ Number of attention heads for each attention layer in the Transformer text-to-unit decoder.
175
+ t2u_max_position_embeddings (`int`, *optional*, defaults to 4096):
176
+ The maximum sequence length that this model text-to-unit component might ever be used with. Typically set
177
+ this to something large just in case (e.g., 512 or 1024 or 2048).
178
+ t2u_variance_predictor_embed_dim (`int`, *optional*, defaults to 1024):
179
+ The projection dimension of the text-to-unit's duration predictor.
180
+ t2u_variance_predictor_hidden_dim (`int`, *optional*, defaults to 256):
181
+ Internal dimension of the text-to-unit's duration predictor.
182
+ t2u_variance_predictor_kernel_size (`int`, *optional*, defaults to 3):
183
+ Kernel size of the convolutional layers of the text-to-unit's duration predictor.
184
+ t2u_variance_pred_dropout (`float`, *optional*, defaults to 0.5):
185
+ The dropout probability of the text-to-unit's duration predictor.
186
+
187
+ > Hifi-Gan Vocoder specific parameters
188
+
189
+ sampling_rate (`int`, *optional*, defaults to 16000):
190
+ The sampling rate at which the output audio will be generated, expressed in hertz (Hz).
191
+ upsample_initial_channel (`int`, *optional*, defaults to 512):
192
+ The number of input channels into the hifi-gan upsampling network. Applies to the vocoder only.
193
+ upsample_rates (`Tuple[int]` or `List[int]`, *optional*, defaults to `[5, 4, 4, 2, 2]`):
194
+ A tuple of integers defining the stride of each 1D convolutional layer in the vocoder upsampling network.
195
+ The length of *upsample_rates* defines the number of convolutional layers and has to match the length of
196
+ *upsample_kernel_sizes*. Applies to the vocoder only.
197
+ upsample_kernel_sizes (`Tuple[int]` or `List[int]`, *optional*, defaults to `[11, 8, 8, 4, 4]`):
198
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the vocoder upsampling
199
+ network. The length of *upsample_kernel_sizes* defines the number of convolutional layers and has to match
200
+ the length of *upsample_rates*. Applies to the vocoder only.
201
+ resblock_kernel_sizes (`Tuple[int]` or `List[int]`, *optional*, defaults to `[3, 7, 11]`):
202
+ A tuple of integers defining the kernel sizes of the vocoder 1D convolutional layers in the multi-receptive
203
+ field fusion (MRF) module. Applies to the vocoder only.
204
+ resblock_dilation_sizes (`Tuple[Tuple[int]]` or `List[List[int]]`, *optional*, defaults to `[[1, 3, 5], [1, 3, 5], [1, 3, 5]]`):
205
+ A nested tuple of integers defining the dilation rates of the vocoder dilated 1D convolutional layers in
206
+ the multi-receptive field fusion (MRF) module. Applies to the vocoder only.
207
+ leaky_relu_slope (`float`, *optional*, defaults to 0.1):
208
+ The angle of the negative slope used by the leaky ReLU activation in the vocoder. Applies to the vocoder
209
+ only.
210
+ unit_hifi_gan_vocab_size (`int`, *optional*, defaults to 10000):
211
+ Vocabulary size of the SeamlessM4Tv2 vocoder. Defines the number of different unit tokens that can be
212
+ represented by the `inputs_ids` passed when calling the vocoder of [`~SeamlessM4Tv2Model`],
213
+ [`~SeamlessM4Tv2ForSpeechToSpeech`] or [`~SeamlessM4Tv2ForTextToSpeech`].
214
+ unit_embed_dim (`int`, *optional*, defaults to 1280):
215
+ The projection dimension of the input ids given to the hifi-gan vocoder. Applies to the vocoder only.
216
+ lang_embed_dim (`int`, *optional*, defaults to 256):
217
+ The projection dimension of the target language given to the hifi-gan vocoder. Applies to the vocoder only.
218
+ spkr_embed_dim (`int`, *optional*, defaults to 256):
219
+ The projection dimension of the speaker id given to the hifi-gan vocoder. Applies to the vocoder only.
220
+ vocoder_num_langs (`int`, *optional*, defaults to 36):
221
+ Number of langs supported by the vocoder. Might be different from `t2u_num_langs`.
222
+ vocoder_num_spkrs (`int`, *optional*, defaults to 200):
223
+ Number of speakers supported by the vocoder.
224
+ variance_predictor_kernel_size (`int`, *optional*, defaults to 3):
225
+ Kernel size of the duration predictor. Applies to the vocoder only.
226
+ var_pred_dropout (`float`, *optional*, defaults to 0.5):
227
+ The dropout probability of the duration predictor. Applies to the vocoder only.
228
+ vocoder_offset (`int`, *optional*, defaults to 4):
229
+ Offset the unit token ids by this number to account for symbol tokens. Applies to the vocoder only.
230
+
231
+ ```python
232
+ >>> from transformers import SeamlessM4Tv2Model, SeamlessM4Tv2Config
233
+
234
+ >>> # Initializing a SeamlessM4Tv2 "" style configuration
235
+ >>> configuration = SeamlessM4Tv2Config()
236
+
237
+ >>> # Initializing a model from the "" style configuration
238
+ >>> model = SeamlessM4Tv2Model(configuration)
239
+
240
+ >>> # Accessing the model configuration
241
+ >>> configuration = model.config
242
+ ```"""
243
+
244
+ model_type = "seamless_m4t_v2"
245
+
246
+ def __init__(
247
+ self,
248
+ vocab_size=256102,
249
+ t2u_vocab_size=10082,
250
+ char_vocab_size=10943,
251
+ # shared config
252
+ hidden_size=1024,
253
+ initializer_range=0.02,
254
+ layer_norm_eps=1e-5,
255
+ use_cache=True,
256
+ max_position_embeddings=4096,
257
+ is_encoder_decoder=True,
258
+ encoder_layerdrop=0.05,
259
+ decoder_layerdrop=0.05,
260
+ activation_function="relu",
261
+ dropout=0.1,
262
+ attention_dropout=0.1,
263
+ activation_dropout=0.0,
264
+ scale_embedding=True,
265
+ # text encoder|decoder
266
+ encoder_layers=24,
267
+ encoder_ffn_dim=8192,
268
+ encoder_attention_heads=16,
269
+ decoder_layers=24,
270
+ decoder_ffn_dim=8192,
271
+ decoder_attention_heads=16,
272
+ decoder_start_token_id=3,
273
+ max_new_tokens=256,
274
+ pad_token_id=0,
275
+ bos_token_id=2,
276
+ eos_token_id=3,
277
+ # speech_encoder
278
+ speech_encoder_layers=24,
279
+ speech_encoder_attention_heads=16,
280
+ speech_encoder_intermediate_size=4096,
281
+ speech_encoder_hidden_act="swish",
282
+ speech_encoder_dropout=0.0,
283
+ add_adapter=True,
284
+ speech_encoder_layerdrop=0.1,
285
+ feature_projection_input_dim=160,
286
+ adaptor_kernel_size=8,
287
+ adaptor_stride=8,
288
+ adaptor_dropout=0.1,
289
+ num_adapter_layers=1,
290
+ position_embeddings_type="relative_key",
291
+ conv_depthwise_kernel_size=31,
292
+ left_max_position_embeddings=64,
293
+ right_max_position_embeddings=8,
294
+ speech_encoder_chunk_size=20000,
295
+ speech_encoder_left_chunk_num=128,
296
+ # t2u config
297
+ t2u_bos_token_id=0,
298
+ t2u_pad_token_id=1,
299
+ t2u_eos_token_id=2,
300
+ t2u_encoder_layers=6,
301
+ t2u_encoder_ffn_dim=8192,
302
+ t2u_encoder_attention_heads=16,
303
+ t2u_decoder_layers=6,
304
+ t2u_decoder_ffn_dim=8192,
305
+ t2u_decoder_attention_heads=16,
306
+ t2u_max_position_embeddings=4096,
307
+ t2u_variance_predictor_embed_dim=1024,
308
+ t2u_variance_predictor_hidden_dim=256,
309
+ t2u_variance_predictor_kernel_size=3,
310
+ t2u_variance_pred_dropout=0.5,
311
+ # hifi-gan vocoder config
312
+ sampling_rate=16000,
313
+ upsample_initial_channel=512,
314
+ upsample_rates=[5, 4, 4, 2, 2],
315
+ upsample_kernel_sizes=[11, 8, 8, 4, 4],
316
+ resblock_kernel_sizes=[3, 7, 11],
317
+ resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
318
+ leaky_relu_slope=0.1,
319
+ # specific to Code Hifi-Gan
320
+ unit_hifi_gan_vocab_size=10000,
321
+ unit_embed_dim=1280,
322
+ lang_embed_dim=256,
323
+ spkr_embed_dim=256,
324
+ vocoder_num_langs=36,
325
+ vocoder_num_spkrs=200,
326
+ variance_predictor_kernel_size=3,
327
+ var_pred_dropout=0.5,
328
+ vocoder_offset=4,
329
+ **kwargs,
330
+ ):
331
+ # overall_config
332
+ self.vocab_size = vocab_size
333
+ self.t2u_vocab_size = t2u_vocab_size
334
+ self.char_vocab_size = char_vocab_size
335
+ self.hidden_size = hidden_size
336
+ self.initializer_range = initializer_range
337
+ self.layer_norm_eps = layer_norm_eps
338
+ self.max_position_embeddings = max_position_embeddings
339
+ self.use_cache = use_cache
340
+ self.max_new_tokens = max_new_tokens
341
+ self.encoder_layerdrop = encoder_layerdrop
342
+ self.decoder_layerdrop = decoder_layerdrop
343
+ self.activation_function = activation_function
344
+ self.dropout = dropout
345
+ self.attention_dropout = attention_dropout
346
+ self.activation_dropout = activation_dropout
347
+ self.scale_embedding = scale_embedding
348
+ # for proper config init
349
+ self.num_attention_heads = decoder_attention_heads
350
+ self.num_hidden_layers = decoder_layers
351
+
352
+ # text|unit encoder|decoder
353
+ self.encoder_layers = encoder_layers
354
+ self.encoder_ffn_dim = encoder_ffn_dim
355
+ self.encoder_attention_heads = encoder_attention_heads
356
+ self.decoder_layers = decoder_layers
357
+ self.decoder_ffn_dim = decoder_ffn_dim
358
+ self.decoder_attention_heads = decoder_attention_heads
359
+
360
+ # speech_encoder
361
+ self.speech_encoder_layers = speech_encoder_layers
362
+ self.speech_encoder_hidden_act = speech_encoder_hidden_act
363
+ self.speech_encoder_dropout = speech_encoder_dropout
364
+ self.speech_encoder_attention_heads = speech_encoder_attention_heads
365
+ self.speech_encoder_layerdrop = speech_encoder_layerdrop
366
+ self.speech_encoder_intermediate_size = speech_encoder_intermediate_size
367
+ self.feature_projection_input_dim = feature_projection_input_dim
368
+ self.adaptor_kernel_size = adaptor_kernel_size
369
+ self.adaptor_stride = adaptor_stride
370
+ self.adaptor_dropout = adaptor_dropout
371
+ self.num_adapter_layers = num_adapter_layers
372
+ self.position_embeddings_type = position_embeddings_type
373
+ self.conv_depthwise_kernel_size = conv_depthwise_kernel_size
374
+ self.add_adapter = add_adapter
375
+ self.left_max_position_embeddings = left_max_position_embeddings
376
+ self.right_max_position_embeddings = right_max_position_embeddings
377
+ self.speech_encoder_chunk_size = speech_encoder_chunk_size
378
+ self.speech_encoder_left_chunk_num = speech_encoder_left_chunk_num
379
+
380
+ # t2u config
381
+ self.t2u_bos_token_id = t2u_bos_token_id
382
+ self.t2u_pad_token_id = t2u_pad_token_id
383
+ self.t2u_eos_token_id = t2u_eos_token_id
384
+ self.t2u_encoder_layers = t2u_encoder_layers
385
+ self.t2u_encoder_ffn_dim = t2u_encoder_ffn_dim
386
+ self.t2u_encoder_attention_heads = t2u_encoder_attention_heads
387
+ self.t2u_decoder_layers = t2u_decoder_layers
388
+ self.t2u_decoder_ffn_dim = t2u_decoder_ffn_dim
389
+ self.t2u_decoder_attention_heads = t2u_decoder_attention_heads
390
+ self.t2u_max_position_embeddings = t2u_max_position_embeddings
391
+ self.t2u_variance_predictor_embed_dim = t2u_variance_predictor_embed_dim # TODO: add to docstrings
392
+ self.t2u_variance_predictor_hidden_dim = t2u_variance_predictor_hidden_dim # TODO: add to docstrings
393
+ self.t2u_variance_predictor_kernel_size = t2u_variance_predictor_kernel_size # TODO: add to docstrings
394
+ self.t2u_variance_pred_dropout = t2u_variance_pred_dropout # TODO: add to docstrings
395
+
396
+ # hifi-gan vocoder config
397
+ # original parameters specific to Hifi-Gan
398
+ self.sampling_rate = sampling_rate
399
+ self.upsample_initial_channel = upsample_initial_channel
400
+ self.upsample_rates = upsample_rates
401
+ self.upsample_kernel_sizes = upsample_kernel_sizes
402
+ self.resblock_kernel_sizes = resblock_kernel_sizes
403
+ self.resblock_dilation_sizes = resblock_dilation_sizes
404
+ self.leaky_relu_slope = leaky_relu_slope
405
+
406
+ # specific to Code Hifi-Gan
407
+ self.unit_hifi_gan_vocab_size = unit_hifi_gan_vocab_size
408
+ self.unit_embed_dim = unit_embed_dim
409
+ self.lang_embed_dim = lang_embed_dim
410
+ self.spkr_embed_dim = spkr_embed_dim
411
+ self.vocoder_num_langs = vocoder_num_langs
412
+ self.vocoder_num_spkrs = vocoder_num_spkrs
413
+ self.variance_predictor_kernel_size = variance_predictor_kernel_size
414
+ self.var_pred_dropout = var_pred_dropout
415
+ self.vocoder_offset = vocoder_offset
416
+
417
+ super().__init__(
418
+ pad_token_id=pad_token_id,
419
+ bos_token_id=bos_token_id,
420
+ eos_token_id=eos_token_id,
421
+ decoder_start_token_id=decoder_start_token_id,
422
+ is_encoder_decoder=is_encoder_decoder,
423
+ max_position_embeddings=max_position_embeddings,
424
+ **kwargs,
425
+ )