Student0809 commited on
Commit
b9950ae
·
verified ·
1 Parent(s): ee3af03

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. docs/transformers/build/lib/transformers/models/deit/image_processing_deit.py +301 -0
  2. docs/transformers/build/lib/transformers/models/deprecated/bort/__init__.py +0 -0
  3. docs/transformers/build/lib/transformers/models/deprecated/deta/configuration_deta.py +270 -0
  4. docs/transformers/build/lib/transformers/models/deprecated/deta/convert_deta_resnet_to_pytorch.py +319 -0
  5. docs/transformers/build/lib/transformers/models/deprecated/deta/image_processing_deta.py +1227 -0
  6. docs/transformers/build/lib/transformers/models/deprecated/deta/modeling_deta.py +0 -0
  7. docs/transformers/build/lib/transformers/models/deprecated/efficientformer/__init__.py +29 -0
  8. docs/transformers/build/lib/transformers/models/deprecated/efficientformer/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.py +252 -0
  9. docs/transformers/build/lib/transformers/models/depth_anything/convert_depth_anything_to_hf.py +368 -0
  10. docs/transformers/build/lib/transformers/models/depth_pro/__init__.py +29 -0
  11. docs/transformers/build/lib/transformers/models/phi3/modeling_phi3.py +1126 -0
  12. docs/transformers/build/lib/transformers/models/phi4_multimodal/image_processing_phi4_multimodal_fast.py +263 -0
  13. docs/transformers/build/lib/transformers/models/phi4_multimodal/modeling_phi4_multimodal.py +0 -0
  14. docs/transformers/build/lib/transformers/models/phi4_multimodal/modular_phi4_multimodal.py +1850 -0
  15. docs/transformers/build/lib/transformers/models/phi4_multimodal/processing_phi4_multimodal.py +195 -0
  16. docs/transformers/build/lib/transformers/models/phimoe/configuration_phimoe.py +203 -0
  17. docs/transformers/build/lib/transformers/models/phimoe/modeling_phimoe.py +1627 -0
  18. docs/transformers/build/lib/transformers/models/phobert/__init__.py +26 -0
  19. docs/transformers/build/lib/transformers/models/phobert/tokenization_phobert.py +351 -0
  20. docs/transformers/build/lib/transformers/models/pix2struct/__init__.py +29 -0
docs/transformers/build/lib/transformers/models/deit/image_processing_deit.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 DeiT."""
16
+
17
+ from typing import Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ...image_transforms import resize, to_channel_dimension_format
23
+ from ...image_utils import (
24
+ IMAGENET_STANDARD_MEAN,
25
+ IMAGENET_STANDARD_STD,
26
+ ChannelDimension,
27
+ ImageInput,
28
+ PILImageResampling,
29
+ infer_channel_dimension_format,
30
+ is_scaled_image,
31
+ make_list_of_images,
32
+ to_numpy_array,
33
+ valid_images,
34
+ validate_preprocess_arguments,
35
+ )
36
+ from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
37
+ from ...utils.import_utils import requires
38
+
39
+
40
+ if is_vision_available():
41
+ import PIL
42
+
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+
47
+ @requires(backends=("vision",))
48
+ class DeiTImageProcessor(BaseImageProcessor):
49
+ r"""
50
+ Constructs a DeiT image processor.
51
+
52
+ Args:
53
+ do_resize (`bool`, *optional*, defaults to `True`):
54
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
55
+ `do_resize` in `preprocess`.
56
+ size (`Dict[str, int]` *optional*, defaults to `{"height": 256, "width": 256}`):
57
+ Size of the image after `resize`. Can be overridden by `size` in `preprocess`.
58
+ resample (`PILImageResampling` filter, *optional*, defaults to `Resampling.BICUBIC`):
59
+ Resampling filter to use if resizing the image. Can be overridden by `resample` in `preprocess`.
60
+ do_center_crop (`bool`, *optional*, defaults to `True`):
61
+ Whether to center crop the image. If the input size is smaller than `crop_size` along any edge, the image
62
+ is padded with 0's and then center cropped. Can be overridden by `do_center_crop` in `preprocess`.
63
+ crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
64
+ Desired output size when applying center-cropping. Can be overridden by `crop_size` in `preprocess`.
65
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
66
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
67
+ `preprocess` method.
68
+ do_rescale (`bool`, *optional*, defaults to `True`):
69
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
70
+ parameter in the `preprocess` method.
71
+ do_normalize (`bool`, *optional*, defaults to `True`):
72
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
73
+ method.
74
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
75
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
76
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
77
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
78
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
79
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
80
+ """
81
+
82
+ model_input_names = ["pixel_values"]
83
+
84
+ def __init__(
85
+ self,
86
+ do_resize: bool = True,
87
+ size: Dict[str, int] = None,
88
+ resample: PILImageResampling = PIL.Image.BICUBIC,
89
+ do_center_crop: bool = True,
90
+ crop_size: Dict[str, int] = None,
91
+ rescale_factor: Union[int, float] = 1 / 255,
92
+ do_rescale: bool = True,
93
+ do_normalize: bool = True,
94
+ image_mean: Optional[Union[float, List[float]]] = None,
95
+ image_std: Optional[Union[float, List[float]]] = None,
96
+ **kwargs,
97
+ ) -> None:
98
+ super().__init__(**kwargs)
99
+ size = size if size is not None else {"height": 256, "width": 256}
100
+ size = get_size_dict(size)
101
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
102
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
103
+
104
+ self.do_resize = do_resize
105
+ self.size = size
106
+ self.resample = resample
107
+ self.do_center_crop = do_center_crop
108
+ self.crop_size = crop_size
109
+ self.do_rescale = do_rescale
110
+ self.rescale_factor = rescale_factor
111
+ self.do_normalize = do_normalize
112
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
113
+ self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
114
+
115
+ # Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.resize with PILImageResampling.BILINEAR->PILImageResampling.BICUBIC
116
+ def resize(
117
+ self,
118
+ image: np.ndarray,
119
+ size: Dict[str, int],
120
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
121
+ data_format: Optional[Union[str, ChannelDimension]] = None,
122
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
123
+ **kwargs,
124
+ ) -> np.ndarray:
125
+ """
126
+ Resize an image to `(size["height"], size["width"])`.
127
+
128
+ Args:
129
+ image (`np.ndarray`):
130
+ Image to resize.
131
+ size (`Dict[str, int]`):
132
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
133
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
134
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`.
135
+ data_format (`ChannelDimension` or `str`, *optional*):
136
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
137
+ image is used. Can be one of:
138
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
139
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
140
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
141
+ input_data_format (`ChannelDimension` or `str`, *optional*):
142
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
143
+ from the input image. Can be one of:
144
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
145
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
146
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
147
+
148
+ Returns:
149
+ `np.ndarray`: The resized image.
150
+ """
151
+ size = get_size_dict(size)
152
+ if "height" not in size or "width" not in size:
153
+ raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
154
+ output_size = (size["height"], size["width"])
155
+ return resize(
156
+ image,
157
+ size=output_size,
158
+ resample=resample,
159
+ data_format=data_format,
160
+ input_data_format=input_data_format,
161
+ **kwargs,
162
+ )
163
+
164
+ @filter_out_non_signature_kwargs()
165
+ def preprocess(
166
+ self,
167
+ images: ImageInput,
168
+ do_resize: Optional[bool] = None,
169
+ size: Dict[str, int] = None,
170
+ resample=None,
171
+ do_center_crop: Optional[bool] = None,
172
+ crop_size: Dict[str, int] = None,
173
+ do_rescale: Optional[bool] = None,
174
+ rescale_factor: Optional[float] = None,
175
+ do_normalize: Optional[bool] = None,
176
+ image_mean: Optional[Union[float, List[float]]] = None,
177
+ image_std: Optional[Union[float, List[float]]] = None,
178
+ return_tensors: Optional[Union[str, TensorType]] = None,
179
+ data_format: ChannelDimension = ChannelDimension.FIRST,
180
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
181
+ ) -> PIL.Image.Image:
182
+ """
183
+ Preprocess an image or batch of images.
184
+
185
+ Args:
186
+ images (`ImageInput`):
187
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
188
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
189
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
190
+ Whether to resize the image.
191
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
192
+ Size of the image after `resize`.
193
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
194
+ PILImageResampling filter to use if resizing the image Only has an effect if `do_resize` is set to
195
+ `True`.
196
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
197
+ Whether to center crop the image.
198
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
199
+ Size of the image after center crop. If one edge the image is smaller than `crop_size`, it will be
200
+ padded with zeros and then cropped
201
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
202
+ Whether to rescale the image values between [0 - 1].
203
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
204
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
205
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
206
+ Whether to normalize the image.
207
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
208
+ Image mean.
209
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
210
+ Image standard deviation.
211
+ return_tensors (`str` or `TensorType`, *optional*):
212
+ The type of tensors to return. Can be one of:
213
+ - `None`: Return a list of `np.ndarray`.
214
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
215
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
216
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
217
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
218
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
219
+ The channel dimension format for the output image. Can be one of:
220
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
221
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
222
+ input_data_format (`ChannelDimension` or `str`, *optional*):
223
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
224
+ from the input image. Can be one of:
225
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
226
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
227
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
228
+ """
229
+ do_resize = do_resize if do_resize is not None else self.do_resize
230
+ resample = resample if resample is not None else self.resample
231
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
232
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
233
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
234
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
235
+ image_mean = image_mean if image_mean is not None else self.image_mean
236
+ image_std = image_std if image_std is not None else self.image_std
237
+
238
+ size = size if size is not None else self.size
239
+ size = get_size_dict(size)
240
+ crop_size = crop_size if crop_size is not None else self.crop_size
241
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
242
+
243
+ images = make_list_of_images(images)
244
+
245
+ if not valid_images(images):
246
+ raise ValueError(
247
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
248
+ "torch.Tensor, tf.Tensor or jax.ndarray."
249
+ )
250
+ validate_preprocess_arguments(
251
+ do_rescale=do_rescale,
252
+ rescale_factor=rescale_factor,
253
+ do_normalize=do_normalize,
254
+ image_mean=image_mean,
255
+ image_std=image_std,
256
+ do_center_crop=do_center_crop,
257
+ crop_size=crop_size,
258
+ do_resize=do_resize,
259
+ size=size,
260
+ resample=resample,
261
+ )
262
+ # All transformations expect numpy arrays.
263
+ images = [to_numpy_array(image) for image in images]
264
+
265
+ if do_rescale and is_scaled_image(images[0]):
266
+ logger.warning_once(
267
+ "It looks like you are trying to rescale already rescaled images. If the input"
268
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
269
+ )
270
+
271
+ if input_data_format is None:
272
+ # We assume that all images have the same channel dimension format.
273
+ input_data_format = infer_channel_dimension_format(images[0])
274
+
275
+ all_images = []
276
+ for image in images:
277
+ if do_resize:
278
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
279
+
280
+ if do_center_crop:
281
+ image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
282
+
283
+ if do_rescale:
284
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
285
+
286
+ if do_normalize:
287
+ image = self.normalize(
288
+ image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
289
+ )
290
+
291
+ all_images.append(image)
292
+ images = [
293
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
294
+ for image in all_images
295
+ ]
296
+
297
+ data = {"pixel_values": images}
298
+ return BatchFeature(data=data, tensor_type=return_tensors)
299
+
300
+
301
+ __all__ = ["DeiTImageProcessor"]
docs/transformers/build/lib/transformers/models/deprecated/bort/__init__.py ADDED
File without changes
docs/transformers/build/lib/transformers/models/deprecated/deta/configuration_deta.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 SenseTime and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """DETA model configuration"""
16
+
17
+ from ....configuration_utils import PretrainedConfig
18
+ from ....utils import logging
19
+ from ...auto import CONFIG_MAPPING
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class DetaConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`DetaModel`]. It is used to instantiate a DETA
28
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
29
+ defaults will yield a similar configuration to that of the DETA
30
+ [SenseTime/deformable-detr](https://huggingface.co/SenseTime/deformable-detr) architecture.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ backbone_config (`PretrainedConfig` or `dict`, *optional*, defaults to `ResNetConfig()`):
37
+ The configuration of the backbone model.
38
+ backbone (`str`, *optional*):
39
+ Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
40
+ will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
41
+ is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
42
+ use_pretrained_backbone (`bool`, *optional*, `False`):
43
+ Whether to use pretrained weights for the backbone.
44
+ use_timm_backbone (`bool`, *optional*, `False`):
45
+ Whether to load `backbone` from the timm library. If `False`, the backbone is loaded from the transformers
46
+ library.
47
+ backbone_kwargs (`dict`, *optional*):
48
+ Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
49
+ e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
50
+ num_queries (`int`, *optional*, defaults to 900):
51
+ Number of object queries, i.e. detection slots. This is the maximal number of objects [`DetaModel`] can
52
+ detect in a single image. In case `two_stage` is set to `True`, we use `two_stage_num_proposals` instead.
53
+ d_model (`int`, *optional*, defaults to 256):
54
+ Dimension of the layers.
55
+ encoder_layers (`int`, *optional*, defaults to 6):
56
+ Number of encoder layers.
57
+ decoder_layers (`int`, *optional*, defaults to 6):
58
+ Number of decoder layers.
59
+ encoder_attention_heads (`int`, *optional*, defaults to 8):
60
+ Number of attention heads for each attention layer in the Transformer encoder.
61
+ decoder_attention_heads (`int`, *optional*, defaults to 8):
62
+ Number of attention heads for each attention layer in the Transformer decoder.
63
+ decoder_ffn_dim (`int`, *optional*, defaults to 2048):
64
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
65
+ encoder_ffn_dim (`int`, *optional*, defaults to 2048):
66
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
67
+ activation_function (`str` or `function`, *optional*, defaults to `"relu"`):
68
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
69
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
70
+ dropout (`float`, *optional*, defaults to 0.1):
71
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
72
+ attention_dropout (`float`, *optional*, defaults to 0.0):
73
+ The dropout ratio for the attention probabilities.
74
+ activation_dropout (`float`, *optional*, defaults to 0.0):
75
+ The dropout ratio for activations inside the fully connected layer.
76
+ init_std (`float`, *optional*, defaults to 0.02):
77
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
78
+ init_xavier_std (`float`, *optional*, defaults to 1):
79
+ The scaling factor used for the Xavier initialization gain in the HM Attention map module.
80
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
81
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
82
+ for more details.
83
+ auxiliary_loss (`bool`, *optional*, defaults to `False`):
84
+ Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
85
+ position_embedding_type (`str`, *optional*, defaults to `"sine"`):
86
+ Type of position embeddings to be used on top of the image features. One of `"sine"` or `"learned"`.
87
+ class_cost (`float`, *optional*, defaults to 1):
88
+ Relative weight of the classification error in the Hungarian matching cost.
89
+ bbox_cost (`float`, *optional*, defaults to 5):
90
+ Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost.
91
+ giou_cost (`float`, *optional*, defaults to 2):
92
+ Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost.
93
+ mask_loss_coefficient (`float`, *optional*, defaults to 1):
94
+ Relative weight of the Focal loss in the panoptic segmentation loss.
95
+ dice_loss_coefficient (`float`, *optional*, defaults to 1):
96
+ Relative weight of the DICE/F-1 loss in the panoptic segmentation loss.
97
+ bbox_loss_coefficient (`float`, *optional*, defaults to 5):
98
+ Relative weight of the L1 bounding box loss in the object detection loss.
99
+ giou_loss_coefficient (`float`, *optional*, defaults to 2):
100
+ Relative weight of the generalized IoU loss in the object detection loss.
101
+ eos_coefficient (`float`, *optional*, defaults to 0.1):
102
+ Relative classification weight of the 'no-object' class in the object detection loss.
103
+ num_feature_levels (`int`, *optional*, defaults to 5):
104
+ The number of input feature levels.
105
+ encoder_n_points (`int`, *optional*, defaults to 4):
106
+ The number of sampled keys in each feature level for each attention head in the encoder.
107
+ decoder_n_points (`int`, *optional*, defaults to 4):
108
+ The number of sampled keys in each feature level for each attention head in the decoder.
109
+ two_stage (`bool`, *optional*, defaults to `True`):
110
+ Whether to apply a two-stage deformable DETR, where the region proposals are also generated by a variant of
111
+ DETA, which are further fed into the decoder for iterative bounding box refinement.
112
+ two_stage_num_proposals (`int`, *optional*, defaults to 300):
113
+ The number of region proposals to be generated, in case `two_stage` is set to `True`.
114
+ with_box_refine (`bool`, *optional*, defaults to `True`):
115
+ Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
116
+ based on the predictions from the previous layer.
117
+ focal_alpha (`float`, *optional*, defaults to 0.25):
118
+ Alpha parameter in the focal loss.
119
+ assign_first_stage (`bool`, *optional*, defaults to `True`):
120
+ Whether to assign each prediction i to the highest overlapping ground truth object if the overlap is larger than a threshold 0.7.
121
+ assign_second_stage (`bool`, *optional*, defaults to `True`):
122
+ Whether to assign second assignment procedure in the second stage closely follows the first stage assignment procedure.
123
+ disable_custom_kernels (`bool`, *optional*, defaults to `True`):
124
+ Disable the use of custom CUDA and CPU kernels. This option is necessary for the ONNX export, as custom
125
+ kernels are not supported by PyTorch ONNX export.
126
+
127
+ Examples:
128
+
129
+ ```python
130
+ >>> from transformers import DetaConfig, DetaModel
131
+
132
+ >>> # Initializing a DETA SenseTime/deformable-detr style configuration
133
+ >>> configuration = DetaConfig()
134
+
135
+ >>> # Initializing a model (with random weights) from the SenseTime/deformable-detr style configuration
136
+ >>> model = DetaModel(configuration)
137
+
138
+ >>> # Accessing the model configuration
139
+ >>> configuration = model.config
140
+ ```"""
141
+
142
+ model_type = "deta"
143
+ attribute_map = {
144
+ "hidden_size": "d_model",
145
+ "num_attention_heads": "encoder_attention_heads",
146
+ }
147
+
148
+ def __init__(
149
+ self,
150
+ backbone_config=None,
151
+ backbone=None,
152
+ use_pretrained_backbone=False,
153
+ use_timm_backbone=False,
154
+ backbone_kwargs=None,
155
+ num_queries=900,
156
+ max_position_embeddings=2048,
157
+ encoder_layers=6,
158
+ encoder_ffn_dim=2048,
159
+ encoder_attention_heads=8,
160
+ decoder_layers=6,
161
+ decoder_ffn_dim=1024,
162
+ decoder_attention_heads=8,
163
+ encoder_layerdrop=0.0,
164
+ is_encoder_decoder=True,
165
+ activation_function="relu",
166
+ d_model=256,
167
+ dropout=0.1,
168
+ attention_dropout=0.0,
169
+ activation_dropout=0.0,
170
+ init_std=0.02,
171
+ init_xavier_std=1.0,
172
+ return_intermediate=True,
173
+ auxiliary_loss=False,
174
+ position_embedding_type="sine",
175
+ num_feature_levels=5,
176
+ encoder_n_points=4,
177
+ decoder_n_points=4,
178
+ two_stage=True,
179
+ two_stage_num_proposals=300,
180
+ with_box_refine=True,
181
+ assign_first_stage=True,
182
+ assign_second_stage=True,
183
+ class_cost=1,
184
+ bbox_cost=5,
185
+ giou_cost=2,
186
+ mask_loss_coefficient=1,
187
+ dice_loss_coefficient=1,
188
+ bbox_loss_coefficient=5,
189
+ giou_loss_coefficient=2,
190
+ eos_coefficient=0.1,
191
+ focal_alpha=0.25,
192
+ disable_custom_kernels=True,
193
+ **kwargs,
194
+ ):
195
+ if use_pretrained_backbone:
196
+ raise ValueError("Pretrained backbones are not supported yet.")
197
+
198
+ if backbone_config is not None and backbone is not None:
199
+ raise ValueError("You can't specify both `backbone` and `backbone_config`.")
200
+
201
+ if backbone_config is None and backbone is None:
202
+ logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.")
203
+ backbone_config = CONFIG_MAPPING["resnet"](out_features=["stage2", "stage3", "stage4"])
204
+ else:
205
+ if isinstance(backbone_config, dict):
206
+ backbone_model_type = backbone_config.pop("model_type")
207
+ config_class = CONFIG_MAPPING[backbone_model_type]
208
+ backbone_config = config_class.from_dict(backbone_config)
209
+
210
+ if backbone_kwargs is not None and backbone_kwargs and backbone_config is not None:
211
+ raise ValueError("You can't specify both `backbone_kwargs` and `backbone_config`.")
212
+
213
+ self.backbone_config = backbone_config
214
+ self.backbone = backbone
215
+ self.use_pretrained_backbone = use_pretrained_backbone
216
+ self.use_timm_backbone = use_timm_backbone
217
+ self.backbone_kwargs = backbone_kwargs
218
+ self.num_queries = num_queries
219
+ self.max_position_embeddings = max_position_embeddings
220
+ self.d_model = d_model
221
+ self.encoder_ffn_dim = encoder_ffn_dim
222
+ self.encoder_layers = encoder_layers
223
+ self.encoder_attention_heads = encoder_attention_heads
224
+ self.decoder_ffn_dim = decoder_ffn_dim
225
+ self.decoder_layers = decoder_layers
226
+ self.decoder_attention_heads = decoder_attention_heads
227
+ self.dropout = dropout
228
+ self.attention_dropout = attention_dropout
229
+ self.activation_dropout = activation_dropout
230
+ self.activation_function = activation_function
231
+ self.init_std = init_std
232
+ self.init_xavier_std = init_xavier_std
233
+ self.encoder_layerdrop = encoder_layerdrop
234
+ self.auxiliary_loss = auxiliary_loss
235
+ self.position_embedding_type = position_embedding_type
236
+ # deformable attributes
237
+ self.num_feature_levels = num_feature_levels
238
+ self.encoder_n_points = encoder_n_points
239
+ self.decoder_n_points = decoder_n_points
240
+ self.two_stage = two_stage
241
+ self.two_stage_num_proposals = two_stage_num_proposals
242
+ self.with_box_refine = with_box_refine
243
+ self.assign_first_stage = assign_first_stage
244
+ self.assign_second_stage = assign_second_stage
245
+ if two_stage is True and with_box_refine is False:
246
+ raise ValueError("If two_stage is True, with_box_refine must be True.")
247
+ # Hungarian matcher
248
+ self.class_cost = class_cost
249
+ self.bbox_cost = bbox_cost
250
+ self.giou_cost = giou_cost
251
+ # Loss coefficients
252
+ self.mask_loss_coefficient = mask_loss_coefficient
253
+ self.dice_loss_coefficient = dice_loss_coefficient
254
+ self.bbox_loss_coefficient = bbox_loss_coefficient
255
+ self.giou_loss_coefficient = giou_loss_coefficient
256
+ self.eos_coefficient = eos_coefficient
257
+ self.focal_alpha = focal_alpha
258
+ self.disable_custom_kernels = disable_custom_kernels
259
+ super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
260
+
261
+ @property
262
+ def num_attention_heads(self) -> int:
263
+ return self.encoder_attention_heads
264
+
265
+ @property
266
+ def hidden_size(self) -> int:
267
+ return self.d_model
268
+
269
+
270
+ __all__ = ["DetaConfig"]
docs/transformers/build/lib/transformers/models/deprecated/deta/convert_deta_resnet_to_pytorch.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert DETA checkpoints from the original repository.
16
+
17
+ URL: https://github.com/jozhang97/DETA/tree/master"""
18
+
19
+ import argparse
20
+ import json
21
+ from pathlib import Path
22
+
23
+ import requests
24
+ import torch
25
+ from huggingface_hub import hf_hub_download
26
+ from PIL import Image
27
+
28
+ from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor
29
+ from transformers.utils import logging
30
+
31
+
32
+ logging.set_verbosity_info()
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ def get_deta_config():
37
+ config = DetaConfig(
38
+ num_queries=900,
39
+ encoder_ffn_dim=2048,
40
+ decoder_ffn_dim=2048,
41
+ num_feature_levels=5,
42
+ assign_first_stage=True,
43
+ with_box_refine=True,
44
+ two_stage=True,
45
+ )
46
+
47
+ # set labels
48
+ config.num_labels = 91
49
+ repo_id = "huggingface/label-files"
50
+ filename = "coco-detection-id2label.json"
51
+ id2label = json.loads(Path(hf_hub_download(repo_id, filename, repo_type="dataset")).read_text())
52
+ id2label = {int(k): v for k, v in id2label.items()}
53
+ config.id2label = id2label
54
+ config.label2id = {v: k for k, v in id2label.items()}
55
+
56
+ return config
57
+
58
+
59
+ # here we list all keys to be renamed (original name on the left, our name on the right)
60
+ def create_rename_keys(config):
61
+ rename_keys = []
62
+
63
+ # stem
64
+ # fmt: off
65
+ rename_keys.append(("backbone.0.body.conv1.weight", "model.backbone.model.embedder.embedder.convolution.weight"))
66
+ rename_keys.append(("backbone.0.body.bn1.weight", "model.backbone.model.embedder.embedder.normalization.weight"))
67
+ rename_keys.append(("backbone.0.body.bn1.bias", "model.backbone.model.embedder.embedder.normalization.bias"))
68
+ rename_keys.append(("backbone.0.body.bn1.running_mean", "model.backbone.model.embedder.embedder.normalization.running_mean"))
69
+ rename_keys.append(("backbone.0.body.bn1.running_var", "model.backbone.model.embedder.embedder.normalization.running_var"))
70
+ # stages
71
+ for stage_idx in range(len(config.backbone_config.depths)):
72
+ for layer_idx in range(config.backbone_config.depths[stage_idx]):
73
+ # shortcut
74
+ if layer_idx == 0:
75
+ rename_keys.append(
76
+ (
77
+ f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight",
78
+ f"model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight",
79
+ )
80
+ )
81
+ rename_keys.append(
82
+ (
83
+ f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight",
84
+ f"model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight",
85
+ )
86
+ )
87
+ rename_keys.append(
88
+ (
89
+ f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias",
90
+ f"model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias",
91
+ )
92
+ )
93
+ rename_keys.append(
94
+ (
95
+ f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean",
96
+ f"model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean",
97
+ )
98
+ )
99
+ rename_keys.append(
100
+ (
101
+ f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var",
102
+ f"model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var",
103
+ )
104
+ )
105
+ # 3 convs
106
+ for i in range(3):
107
+ rename_keys.append(
108
+ (
109
+ f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight",
110
+ f"model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight",
111
+ )
112
+ )
113
+ rename_keys.append(
114
+ (
115
+ f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight",
116
+ f"model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight",
117
+ )
118
+ )
119
+ rename_keys.append(
120
+ (
121
+ f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias",
122
+ f"model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias",
123
+ )
124
+ )
125
+ rename_keys.append(
126
+ (
127
+ f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean",
128
+ f"model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean",
129
+ )
130
+ )
131
+ rename_keys.append(
132
+ (
133
+ f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var",
134
+ f"model.backbone.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var",
135
+ )
136
+ )
137
+ # transformer encoder
138
+ for i in range(config.encoder_layers):
139
+ rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight", f"model.encoder.layers.{i}.self_attn.sampling_offsets.weight"))
140
+ rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias", f"model.encoder.layers.{i}.self_attn.sampling_offsets.bias"))
141
+ rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.attention_weights.weight", f"model.encoder.layers.{i}.self_attn.attention_weights.weight"))
142
+ rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.attention_weights.bias", f"model.encoder.layers.{i}.self_attn.attention_weights.bias"))
143
+ rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.value_proj.weight", f"model.encoder.layers.{i}.self_attn.value_proj.weight"))
144
+ rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.value_proj.bias", f"model.encoder.layers.{i}.self_attn.value_proj.bias"))
145
+ rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.output_proj.weight", f"model.encoder.layers.{i}.self_attn.output_proj.weight"))
146
+ rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.output_proj.bias", f"model.encoder.layers.{i}.self_attn.output_proj.bias"))
147
+ rename_keys.append((f"transformer.encoder.layers.{i}.norm1.weight", f"model.encoder.layers.{i}.self_attn_layer_norm.weight"))
148
+ rename_keys.append((f"transformer.encoder.layers.{i}.norm1.bias", f"model.encoder.layers.{i}.self_attn_layer_norm.bias"))
149
+ rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"model.encoder.layers.{i}.fc1.weight"))
150
+ rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"model.encoder.layers.{i}.fc1.bias"))
151
+ rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"model.encoder.layers.{i}.fc2.weight"))
152
+ rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"model.encoder.layers.{i}.fc2.bias"))
153
+ rename_keys.append((f"transformer.encoder.layers.{i}.norm2.weight", f"model.encoder.layers.{i}.final_layer_norm.weight"))
154
+ rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"model.encoder.layers.{i}.final_layer_norm.bias"))
155
+
156
+ # transformer decoder
157
+ for i in range(config.decoder_layers):
158
+ rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight", f"model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight"))
159
+ rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias", f"model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias"))
160
+ rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.attention_weights.weight", f"model.decoder.layers.{i}.encoder_attn.attention_weights.weight"))
161
+ rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.attention_weights.bias", f"model.decoder.layers.{i}.encoder_attn.attention_weights.bias"))
162
+ rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.value_proj.weight", f"model.decoder.layers.{i}.encoder_attn.value_proj.weight"))
163
+ rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.value_proj.bias", f"model.decoder.layers.{i}.encoder_attn.value_proj.bias"))
164
+ rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.output_proj.weight", f"model.decoder.layers.{i}.encoder_attn.output_proj.weight"))
165
+ rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.output_proj.bias", f"model.decoder.layers.{i}.encoder_attn.output_proj.bias"))
166
+ rename_keys.append((f"transformer.decoder.layers.{i}.norm1.weight", f"model.decoder.layers.{i}.encoder_attn_layer_norm.weight"))
167
+ rename_keys.append((f"transformer.decoder.layers.{i}.norm1.bias", f"model.decoder.layers.{i}.encoder_attn_layer_norm.bias"))
168
+ rename_keys.append((f"transformer.decoder.layers.{i}.self_attn.out_proj.weight", f"model.decoder.layers.{i}.self_attn.out_proj.weight"))
169
+ rename_keys.append((f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"model.decoder.layers.{i}.self_attn.out_proj.bias"))
170
+ rename_keys.append((f"transformer.decoder.layers.{i}.norm2.weight", f"model.decoder.layers.{i}.self_attn_layer_norm.weight"))
171
+ rename_keys.append((f"transformer.decoder.layers.{i}.norm2.bias", f"model.decoder.layers.{i}.self_attn_layer_norm.bias"))
172
+ rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"model.decoder.layers.{i}.fc1.weight"))
173
+ rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"model.decoder.layers.{i}.fc1.bias"))
174
+ rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"model.decoder.layers.{i}.fc2.weight"))
175
+ rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"model.decoder.layers.{i}.fc2.bias"))
176
+ rename_keys.append((f"transformer.decoder.layers.{i}.norm3.weight", f"model.decoder.layers.{i}.final_layer_norm.weight"))
177
+ rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"model.decoder.layers.{i}.final_layer_norm.bias"))
178
+
179
+ # fmt: on
180
+
181
+ return rename_keys
182
+
183
+
184
+ def rename_key(dct, old, new):
185
+ val = dct.pop(old)
186
+ dct[new] = val
187
+
188
+
189
+ def read_in_decoder_q_k_v(state_dict, config):
190
+ # transformer decoder self-attention layers
191
+ hidden_size = config.d_model
192
+ for i in range(config.decoder_layers):
193
+ # read in weights + bias of input projection layer of self-attention
194
+ in_proj_weight = state_dict.pop(f"transformer.decoder.layers.{i}.self_attn.in_proj_weight")
195
+ in_proj_bias = state_dict.pop(f"transformer.decoder.layers.{i}.self_attn.in_proj_bias")
196
+ # next, add query, keys and values (in that order) to the state dict
197
+ state_dict[f"model.decoder.layers.{i}.self_attn.q_proj.weight"] = in_proj_weight[:hidden_size, :]
198
+ state_dict[f"model.decoder.layers.{i}.self_attn.q_proj.bias"] = in_proj_bias[:hidden_size]
199
+ state_dict[f"model.decoder.layers.{i}.self_attn.k_proj.weight"] = in_proj_weight[
200
+ hidden_size : hidden_size * 2, :
201
+ ]
202
+ state_dict[f"model.decoder.layers.{i}.self_attn.k_proj.bias"] = in_proj_bias[hidden_size : hidden_size * 2]
203
+ state_dict[f"model.decoder.layers.{i}.self_attn.v_proj.weight"] = in_proj_weight[-hidden_size:, :]
204
+ state_dict[f"model.decoder.layers.{i}.self_attn.v_proj.bias"] = in_proj_bias[-hidden_size:]
205
+
206
+
207
+ # We will verify our results on an image of cute cats
208
+ def prepare_img():
209
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
210
+ im = Image.open(requests.get(url, stream=True).raw)
211
+
212
+ return im
213
+
214
+
215
+ @torch.no_grad()
216
+ def convert_deta_checkpoint(model_name, pytorch_dump_folder_path, push_to_hub):
217
+ """
218
+ Copy/paste/tweak model's weights to our DETA structure.
219
+ """
220
+
221
+ # load config
222
+ config = get_deta_config()
223
+
224
+ # load original state dict
225
+ if model_name == "deta-resnet-50":
226
+ filename = "adet_checkpoint0011.pth"
227
+ elif model_name == "deta-resnet-50-24-epochs":
228
+ filename = "adet_2x_checkpoint0023.pth"
229
+ else:
230
+ raise ValueError(f"Model name {model_name} not supported")
231
+ checkpoint_path = hf_hub_download(repo_id="nielsr/deta-checkpoints", filename=filename)
232
+ state_dict = torch.load(checkpoint_path, map_location="cpu", weights_only=True)["model"]
233
+
234
+ # rename keys
235
+ rename_keys = create_rename_keys(config)
236
+ for src, dest in rename_keys:
237
+ rename_key(state_dict, src, dest)
238
+ read_in_decoder_q_k_v(state_dict, config)
239
+
240
+ # fix some prefixes
241
+ for key in state_dict.copy().keys():
242
+ if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key:
243
+ val = state_dict.pop(key)
244
+ state_dict[key.replace("transformer.decoder", "model.decoder")] = val
245
+ if "input_proj" in key:
246
+ val = state_dict.pop(key)
247
+ state_dict["model." + key] = val
248
+ if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key:
249
+ val = state_dict.pop(key)
250
+ state_dict[key.replace("transformer", "model")] = val
251
+
252
+ # finally, create HuggingFace model and load state dict
253
+ model = DetaForObjectDetection(config)
254
+ model.load_state_dict(state_dict)
255
+ model.eval()
256
+
257
+ device = "cuda" if torch.cuda.is_available() else "cpu"
258
+ model.to(device)
259
+
260
+ # load image processor
261
+ processor = DetaImageProcessor(format="coco_detection")
262
+
263
+ # verify our conversion on image
264
+ img = prepare_img()
265
+ encoding = processor(images=img, return_tensors="pt")
266
+ pixel_values = encoding["pixel_values"]
267
+ outputs = model(pixel_values.to(device))
268
+
269
+ # verify logits
270
+ if model_name == "deta-resnet-50":
271
+ expected_logits = torch.tensor(
272
+ [[-7.3978, -2.5406, -4.1668], [-8.2684, -3.9933, -3.8096], [-7.0515, -3.7973, -5.8516]]
273
+ )
274
+ expected_boxes = torch.tensor([[0.5043, 0.4973, 0.9998], [0.2542, 0.5489, 0.4748], [0.5490, 0.2765, 0.0570]])
275
+ elif model_name == "deta-resnet-50-24-epochs":
276
+ expected_logits = torch.tensor(
277
+ [[-7.1688, -2.4857, -4.8669], [-7.8630, -3.8154, -4.2674], [-7.2730, -4.1865, -5.5323]]
278
+ )
279
+ expected_boxes = torch.tensor([[0.5021, 0.4971, 0.9994], [0.2546, 0.5486, 0.4731], [0.1686, 0.1986, 0.2142]])
280
+
281
+ assert torch.allclose(outputs.logits[0, :3, :3], expected_logits.to(device), atol=1e-4)
282
+ assert torch.allclose(outputs.pred_boxes[0, :3, :3], expected_boxes.to(device), atol=1e-4)
283
+ print("Everything ok!")
284
+
285
+ if pytorch_dump_folder_path:
286
+ # Save model and processor
287
+ logger.info(f"Saving PyTorch model and processor to {pytorch_dump_folder_path}...")
288
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
289
+ model.save_pretrained(pytorch_dump_folder_path)
290
+ processor.save_pretrained(pytorch_dump_folder_path)
291
+
292
+ # Push to hub
293
+ if push_to_hub:
294
+ print("Pushing model and processor to hub...")
295
+ model.push_to_hub(f"jozhang97/{model_name}")
296
+ processor.push_to_hub(f"jozhang97/{model_name}")
297
+
298
+
299
+ if __name__ == "__main__":
300
+ parser = argparse.ArgumentParser()
301
+
302
+ parser.add_argument(
303
+ "--model_name",
304
+ type=str,
305
+ default="deta-resnet-50",
306
+ choices=["deta-resnet-50", "deta-resnet-50-24-epochs"],
307
+ help="Name of the model you'd like to convert.",
308
+ )
309
+ parser.add_argument(
310
+ "--pytorch_dump_folder_path",
311
+ default=None,
312
+ type=str,
313
+ help="Path to the folder to output PyTorch model.",
314
+ )
315
+ parser.add_argument(
316
+ "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
317
+ )
318
+ args = parser.parse_args()
319
+ convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
docs/transformers/build/lib/transformers/models/deprecated/deta/image_processing_deta.py ADDED
@@ -0,0 +1,1227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Image processor class for Deformable DETR."""
16
+
17
+ import pathlib
18
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+
22
+ from ....feature_extraction_utils import BatchFeature
23
+ from ....image_processing_utils import BaseImageProcessor, get_size_dict
24
+ from ....image_transforms import (
25
+ PaddingMode,
26
+ center_to_corners_format,
27
+ corners_to_center_format,
28
+ pad,
29
+ rescale,
30
+ resize,
31
+ rgb_to_id,
32
+ to_channel_dimension_format,
33
+ )
34
+ from ....image_utils import (
35
+ IMAGENET_DEFAULT_MEAN,
36
+ IMAGENET_DEFAULT_STD,
37
+ AnnotationFormat,
38
+ AnnotationType,
39
+ ChannelDimension,
40
+ ImageInput,
41
+ PILImageResampling,
42
+ get_image_size,
43
+ infer_channel_dimension_format,
44
+ is_batched,
45
+ is_scaled_image,
46
+ to_numpy_array,
47
+ valid_images,
48
+ validate_annotations,
49
+ validate_preprocess_arguments,
50
+ )
51
+ from ....utils import (
52
+ is_flax_available,
53
+ is_jax_tensor,
54
+ is_tf_available,
55
+ is_tf_tensor,
56
+ is_torch_available,
57
+ is_torch_tensor,
58
+ is_torchvision_available,
59
+ is_vision_available,
60
+ logging,
61
+ )
62
+ from ....utils.generic import TensorType
63
+
64
+
65
+ if is_torch_available():
66
+ import torch
67
+
68
+
69
+ if is_torchvision_available():
70
+ from torchvision.ops.boxes import batched_nms
71
+
72
+ if is_vision_available():
73
+ import PIL
74
+
75
+
76
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
77
+
78
+ SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION, AnnotationFormat.COCO_PANOPTIC)
79
+
80
+
81
+ def get_size_with_aspect_ratio(image_size, size, max_size=None) -> Tuple[int, int]:
82
+ """
83
+ Computes the output image size given the input image size and the desired output size.
84
+
85
+ Args:
86
+ image_size (`Tuple[int, int]`):
87
+ The input image size.
88
+ size (`int`):
89
+ The desired output size.
90
+ max_size (`int`, *optional*):
91
+ The maximum allowed output size.
92
+ """
93
+ height, width = image_size
94
+ raw_size = None
95
+ if max_size is not None:
96
+ min_original_size = float(min((height, width)))
97
+ max_original_size = float(max((height, width)))
98
+ if max_original_size / min_original_size * size > max_size:
99
+ raw_size = max_size * min_original_size / max_original_size
100
+ size = int(round(raw_size))
101
+
102
+ if (height <= width and height == size) or (width <= height and width == size):
103
+ oh, ow = height, width
104
+ elif width < height:
105
+ ow = size
106
+ if max_size is not None and raw_size is not None:
107
+ oh = int(raw_size * height / width)
108
+ else:
109
+ oh = int(size * height / width)
110
+ else:
111
+ oh = size
112
+ if max_size is not None and raw_size is not None:
113
+ ow = int(raw_size * width / height)
114
+ else:
115
+ ow = int(size * width / height)
116
+
117
+ return (oh, ow)
118
+
119
+
120
+ def get_resize_output_image_size(
121
+ input_image: np.ndarray,
122
+ size: Union[int, Tuple[int, int], List[int]],
123
+ max_size: Optional[int] = None,
124
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
125
+ ) -> Tuple[int, int]:
126
+ """
127
+ Computes the output image size given the input image size and the desired output size. If the desired output size
128
+ is a tuple or list, the output image size is returned as is. If the desired output size is an integer, the output
129
+ image size is computed by keeping the aspect ratio of the input image size.
130
+
131
+ Args:
132
+ input_image (`np.ndarray`):
133
+ The image to resize.
134
+ size (`int` or `Tuple[int, int]` or `List[int]`):
135
+ The desired output size.
136
+ max_size (`int`, *optional*):
137
+ The maximum allowed output size.
138
+ input_data_format (`ChannelDimension` or `str`, *optional*):
139
+ The channel dimension format of the input image. If not provided, it will be inferred from the input image.
140
+ """
141
+ image_size = get_image_size(input_image, input_data_format)
142
+ if isinstance(size, (list, tuple)):
143
+ return size
144
+
145
+ return get_size_with_aspect_ratio(image_size, size, max_size)
146
+
147
+
148
+ def get_image_size_for_max_height_width(
149
+ input_image: np.ndarray,
150
+ max_height: int,
151
+ max_width: int,
152
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
153
+ ) -> Tuple[int, int]:
154
+ """
155
+ Computes the output image size given the input image and the maximum allowed height and width. Keep aspect ratio.
156
+ Important, even if image_height < max_height and image_width < max_width, the image will be resized
157
+ to at least one of the edges be equal to max_height or max_width.
158
+
159
+ For example:
160
+ - input_size: (100, 200), max_height: 50, max_width: 50 -> output_size: (25, 50)
161
+ - input_size: (100, 200), max_height: 200, max_width: 500 -> output_size: (200, 400)
162
+
163
+ Args:
164
+ input_image (`np.ndarray`):
165
+ The image to resize.
166
+ max_height (`int`):
167
+ The maximum allowed height.
168
+ max_width (`int`):
169
+ The maximum allowed width.
170
+ input_data_format (`ChannelDimension` or `str`, *optional*):
171
+ The channel dimension format of the input image. If not provided, it will be inferred from the input image.
172
+ """
173
+ image_size = get_image_size(input_image, input_data_format)
174
+ height, width = image_size
175
+ height_scale = max_height / height
176
+ width_scale = max_width / width
177
+ min_scale = min(height_scale, width_scale)
178
+ new_height = int(height * min_scale)
179
+ new_width = int(width * min_scale)
180
+ return new_height, new_width
181
+
182
+
183
+ def get_numpy_to_framework_fn(arr) -> Callable:
184
+ """
185
+ Returns a function that converts a numpy array to the framework of the input array.
186
+
187
+ Args:
188
+ arr (`np.ndarray`): The array to convert.
189
+ """
190
+ if isinstance(arr, np.ndarray):
191
+ return np.array
192
+ if is_tf_available() and is_tf_tensor(arr):
193
+ import tensorflow as tf
194
+
195
+ return tf.convert_to_tensor
196
+ if is_torch_available() and is_torch_tensor(arr):
197
+ import torch
198
+
199
+ return torch.tensor
200
+ if is_flax_available() and is_jax_tensor(arr):
201
+ import jax.numpy as jnp
202
+
203
+ return jnp.array
204
+ raise ValueError(f"Cannot convert arrays of type {type(arr)}")
205
+
206
+
207
+ def safe_squeeze(arr: np.ndarray, axis: Optional[int] = None) -> np.ndarray:
208
+ """
209
+ Squeezes an array, but only if the axis specified has dim 1.
210
+ """
211
+ if axis is None:
212
+ return arr.squeeze()
213
+
214
+ try:
215
+ return arr.squeeze(axis=axis)
216
+ except ValueError:
217
+ return arr
218
+
219
+
220
+ def normalize_annotation(annotation: Dict, image_size: Tuple[int, int]) -> Dict:
221
+ image_height, image_width = image_size
222
+ norm_annotation = {}
223
+ for key, value in annotation.items():
224
+ if key == "boxes":
225
+ boxes = value
226
+ boxes = corners_to_center_format(boxes)
227
+ boxes /= np.asarray([image_width, image_height, image_width, image_height], dtype=np.float32)
228
+ norm_annotation[key] = boxes
229
+ else:
230
+ norm_annotation[key] = value
231
+ return norm_annotation
232
+
233
+
234
+ def max_across_indices(values: Iterable[Any]) -> List[Any]:
235
+ """
236
+ Return the maximum value across all indices of an iterable of values.
237
+ """
238
+ return [max(values_i) for values_i in zip(*values)]
239
+
240
+
241
+ def get_max_height_width(
242
+ images: List[np.ndarray], input_data_format: Optional[Union[str, ChannelDimension]] = None
243
+ ) -> List[int]:
244
+ """
245
+ Get the maximum height and width across all images in a batch.
246
+ """
247
+ if input_data_format is None:
248
+ input_data_format = infer_channel_dimension_format(images[0])
249
+
250
+ if input_data_format == ChannelDimension.FIRST:
251
+ _, max_height, max_width = max_across_indices([img.shape for img in images])
252
+ elif input_data_format == ChannelDimension.LAST:
253
+ max_height, max_width, _ = max_across_indices([img.shape for img in images])
254
+ else:
255
+ raise ValueError(f"Invalid channel dimension format: {input_data_format}")
256
+ return (max_height, max_width)
257
+
258
+
259
+ def make_pixel_mask(
260
+ image: np.ndarray, output_size: Tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None
261
+ ) -> np.ndarray:
262
+ """
263
+ Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
264
+
265
+ Args:
266
+ image (`np.ndarray`):
267
+ Image to make the pixel mask for.
268
+ output_size (`Tuple[int, int]`):
269
+ Output size of the mask.
270
+ """
271
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
272
+ mask = np.zeros(output_size, dtype=np.int64)
273
+ mask[:input_height, :input_width] = 1
274
+ return mask
275
+
276
+
277
+ def convert_coco_poly_to_mask(segmentations, height: int, width: int) -> np.ndarray:
278
+ """
279
+ Convert a COCO polygon annotation to a mask.
280
+
281
+ Args:
282
+ segmentations (`List[List[float]]`):
283
+ List of polygons, each polygon represented by a list of x-y coordinates.
284
+ height (`int`):
285
+ Height of the mask.
286
+ width (`int`):
287
+ Width of the mask.
288
+ """
289
+ try:
290
+ from pycocotools import mask as coco_mask
291
+ except ImportError:
292
+ raise ImportError("Pycocotools is not installed in your environment.")
293
+
294
+ masks = []
295
+ for polygons in segmentations:
296
+ rles = coco_mask.frPyObjects(polygons, height, width)
297
+ mask = coco_mask.decode(rles)
298
+ if len(mask.shape) < 3:
299
+ mask = mask[..., None]
300
+ mask = np.asarray(mask, dtype=np.uint8)
301
+ mask = np.any(mask, axis=2)
302
+ masks.append(mask)
303
+ if masks:
304
+ masks = np.stack(masks, axis=0)
305
+ else:
306
+ masks = np.zeros((0, height, width), dtype=np.uint8)
307
+
308
+ return masks
309
+
310
+
311
+ def prepare_coco_detection_annotation(
312
+ image,
313
+ target,
314
+ return_segmentation_masks: bool = False,
315
+ input_data_format: Optional[Union[ChannelDimension, str]] = None,
316
+ ):
317
+ """
318
+ Convert the target in COCO format into the format expected by DETA.
319
+ """
320
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
321
+
322
+ image_id = target["image_id"]
323
+ image_id = np.asarray([image_id], dtype=np.int64)
324
+
325
+ # Get all COCO annotations for the given image.
326
+ annotations = target["annotations"]
327
+ annotations = [obj for obj in annotations if "iscrowd" not in obj or obj["iscrowd"] == 0]
328
+
329
+ classes = [obj["category_id"] for obj in annotations]
330
+ classes = np.asarray(classes, dtype=np.int64)
331
+
332
+ # for conversion to coco api
333
+ area = np.asarray([obj["area"] for obj in annotations], dtype=np.float32)
334
+ iscrowd = np.asarray([obj["iscrowd"] if "iscrowd" in obj else 0 for obj in annotations], dtype=np.int64)
335
+
336
+ boxes = [obj["bbox"] for obj in annotations]
337
+ # guard against no boxes via resizing
338
+ boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
339
+ boxes[:, 2:] += boxes[:, :2]
340
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
341
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
342
+
343
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
344
+
345
+ new_target = {}
346
+ new_target["image_id"] = image_id
347
+ new_target["class_labels"] = classes[keep]
348
+ new_target["boxes"] = boxes[keep]
349
+ new_target["area"] = area[keep]
350
+ new_target["iscrowd"] = iscrowd[keep]
351
+ new_target["orig_size"] = np.asarray([int(image_height), int(image_width)], dtype=np.int64)
352
+
353
+ if annotations and "keypoints" in annotations[0]:
354
+ keypoints = [obj["keypoints"] for obj in annotations]
355
+ # Converting the filtered keypoints list to a numpy array
356
+ keypoints = np.asarray(keypoints, dtype=np.float32)
357
+ # Apply the keep mask here to filter the relevant annotations
358
+ keypoints = keypoints[keep]
359
+ num_keypoints = keypoints.shape[0]
360
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
361
+ new_target["keypoints"] = keypoints
362
+
363
+ if return_segmentation_masks:
364
+ segmentation_masks = [obj["segmentation"] for obj in annotations]
365
+ masks = convert_coco_poly_to_mask(segmentation_masks, image_height, image_width)
366
+ new_target["masks"] = masks[keep]
367
+
368
+ return new_target
369
+
370
+
371
+ def masks_to_boxes(masks: np.ndarray) -> np.ndarray:
372
+ """
373
+ Compute the bounding boxes around the provided panoptic segmentation masks.
374
+
375
+ Args:
376
+ masks: masks in format `[number_masks, height, width]` where N is the number of masks
377
+
378
+ Returns:
379
+ boxes: bounding boxes in format `[number_masks, 4]` in xyxy format
380
+ """
381
+ if masks.size == 0:
382
+ return np.zeros((0, 4))
383
+
384
+ h, w = masks.shape[-2:]
385
+ y = np.arange(0, h, dtype=np.float32)
386
+ x = np.arange(0, w, dtype=np.float32)
387
+ # see https://github.com/pytorch/pytorch/issues/50276
388
+ y, x = np.meshgrid(y, x, indexing="ij")
389
+
390
+ x_mask = masks * np.expand_dims(x, axis=0)
391
+ x_max = x_mask.reshape(x_mask.shape[0], -1).max(-1)
392
+ x = np.ma.array(x_mask, mask=~(np.array(masks, dtype=bool)))
393
+ x_min = x.filled(fill_value=1e8)
394
+ x_min = x_min.reshape(x_min.shape[0], -1).min(-1)
395
+
396
+ y_mask = masks * np.expand_dims(y, axis=0)
397
+ y_max = y_mask.reshape(x_mask.shape[0], -1).max(-1)
398
+ y = np.ma.array(y_mask, mask=~(np.array(masks, dtype=bool)))
399
+ y_min = y.filled(fill_value=1e8)
400
+ y_min = y_min.reshape(y_min.shape[0], -1).min(-1)
401
+
402
+ return np.stack([x_min, y_min, x_max, y_max], 1)
403
+
404
+
405
+ def prepare_coco_panoptic_annotation(
406
+ image: np.ndarray,
407
+ target: Dict,
408
+ masks_path: Union[str, pathlib.Path],
409
+ return_masks: bool = True,
410
+ input_data_format: Union[ChannelDimension, str] = None,
411
+ ) -> Dict:
412
+ """
413
+ Prepare a coco panoptic annotation for DETA.
414
+ """
415
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
416
+ annotation_path = pathlib.Path(masks_path) / target["file_name"]
417
+
418
+ new_target = {}
419
+ new_target["image_id"] = np.asarray([target["image_id"] if "image_id" in target else target["id"]], dtype=np.int64)
420
+ new_target["size"] = np.asarray([image_height, image_width], dtype=np.int64)
421
+ new_target["orig_size"] = np.asarray([image_height, image_width], dtype=np.int64)
422
+
423
+ if "segments_info" in target:
424
+ masks = np.asarray(PIL.Image.open(annotation_path), dtype=np.uint32)
425
+ masks = rgb_to_id(masks)
426
+
427
+ ids = np.array([segment_info["id"] for segment_info in target["segments_info"]])
428
+ masks = masks == ids[:, None, None]
429
+ masks = masks.astype(np.uint8)
430
+ if return_masks:
431
+ new_target["masks"] = masks
432
+ new_target["boxes"] = masks_to_boxes(masks)
433
+ new_target["class_labels"] = np.array(
434
+ [segment_info["category_id"] for segment_info in target["segments_info"]], dtype=np.int64
435
+ )
436
+ new_target["iscrowd"] = np.asarray(
437
+ [segment_info["iscrowd"] for segment_info in target["segments_info"]], dtype=np.int64
438
+ )
439
+ new_target["area"] = np.asarray(
440
+ [segment_info["area"] for segment_info in target["segments_info"]], dtype=np.float32
441
+ )
442
+
443
+ return new_target
444
+
445
+
446
+ def resize_annotation(
447
+ annotation: Dict[str, Any],
448
+ orig_size: Tuple[int, int],
449
+ target_size: Tuple[int, int],
450
+ threshold: float = 0.5,
451
+ resample: PILImageResampling = PILImageResampling.NEAREST,
452
+ ):
453
+ """
454
+ Resizes an annotation to a target size.
455
+
456
+ Args:
457
+ annotation (`Dict[str, Any]`):
458
+ The annotation dictionary.
459
+ orig_size (`Tuple[int, int]`):
460
+ The original size of the input image.
461
+ target_size (`Tuple[int, int]`):
462
+ The target size of the image, as returned by the preprocessing `resize` step.
463
+ threshold (`float`, *optional*, defaults to 0.5):
464
+ The threshold used to binarize the segmentation masks.
465
+ resample (`PILImageResampling`, defaults to `PILImageResampling.NEAREST`):
466
+ The resampling filter to use when resizing the masks.
467
+ """
468
+ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(target_size, orig_size))
469
+ ratio_height, ratio_width = ratios
470
+
471
+ new_annotation = {}
472
+ new_annotation["size"] = target_size
473
+
474
+ for key, value in annotation.items():
475
+ if key == "boxes":
476
+ boxes = value
477
+ scaled_boxes = boxes * np.asarray([ratio_width, ratio_height, ratio_width, ratio_height], dtype=np.float32)
478
+ new_annotation["boxes"] = scaled_boxes
479
+ elif key == "area":
480
+ area = value
481
+ scaled_area = area * (ratio_width * ratio_height)
482
+ new_annotation["area"] = scaled_area
483
+ elif key == "masks":
484
+ masks = value[:, None]
485
+ masks = np.array([resize(mask, target_size, resample=resample) for mask in masks])
486
+ masks = masks.astype(np.float32)
487
+ masks = masks[:, 0] > threshold
488
+ new_annotation["masks"] = masks
489
+ elif key == "size":
490
+ new_annotation["size"] = target_size
491
+ else:
492
+ new_annotation[key] = value
493
+
494
+ return new_annotation
495
+
496
+
497
+ class DetaImageProcessor(BaseImageProcessor):
498
+ r"""
499
+ Constructs a Deformable DETR image processor.
500
+
501
+ Args:
502
+ format (`str`, *optional*, defaults to `"coco_detection"`):
503
+ Data format of the annotations. One of "coco_detection" or "coco_panoptic".
504
+ do_resize (`bool`, *optional*, defaults to `True`):
505
+ Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be
506
+ overridden by the `do_resize` parameter in the `preprocess` method.
507
+ size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 800, "longest_edge": 1333}`):
508
+ Size of the image's `(height, width)` dimensions after resizing. Can be overridden by the `size` parameter
509
+ in the `preprocess` method. Available options are:
510
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
511
+ Do NOT keep the aspect ratio.
512
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
513
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
514
+ less or equal to `longest_edge`.
515
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
516
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
517
+ `max_width`.
518
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
519
+ Resampling filter to use if resizing the image.
520
+ do_rescale (`bool`, *optional*, defaults to `True`):
521
+ Controls whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
522
+ `do_rescale` parameter in the `preprocess` method.
523
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
524
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
525
+ `preprocess` method.
526
+ do_normalize:
527
+ Controls whether to normalize the image. Can be overridden by the `do_normalize` parameter in the
528
+ `preprocess` method.
529
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN`):
530
+ Mean values to use when normalizing the image. Can be a single value or a list of values, one for each
531
+ channel. Can be overridden by the `image_mean` parameter in the `preprocess` method.
532
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_STD`):
533
+ Standard deviation values to use when normalizing the image. Can be a single value or a list of values, one
534
+ for each channel. Can be overridden by the `image_std` parameter in the `preprocess` method.
535
+ do_convert_annotations (`bool`, *optional*, defaults to `True`):
536
+ Controls whether to convert the annotations to the format expected by the DETR model. Converts the
537
+ bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`.
538
+ Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method.
539
+ do_pad (`bool`, *optional*, defaults to `True`):
540
+ Controls whether to pad the image. Can be overridden by the `do_pad` parameter in the `preprocess`
541
+ method. If `True`, padding will be applied to the bottom and right of the image with zeros.
542
+ If `pad_size` is provided, the image will be padded to the specified dimensions.
543
+ Otherwise, the image will be padded to the maximum height and width of the batch.
544
+ pad_size (`Dict[str, int]`, *optional*):
545
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
546
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
547
+ height and width in the batch.
548
+ """
549
+
550
+ model_input_names = ["pixel_values", "pixel_mask"]
551
+
552
+ def __init__(
553
+ self,
554
+ format: Union[str, AnnotationFormat] = AnnotationFormat.COCO_DETECTION,
555
+ do_resize: bool = True,
556
+ size: Dict[str, int] = None,
557
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
558
+ do_rescale: bool = True,
559
+ rescale_factor: Union[int, float] = 1 / 255,
560
+ do_normalize: bool = True,
561
+ image_mean: Union[float, List[float]] = None,
562
+ image_std: Union[float, List[float]] = None,
563
+ do_convert_annotations: bool = True,
564
+ do_pad: bool = True,
565
+ pad_size: Optional[Dict[str, int]] = None,
566
+ **kwargs,
567
+ ) -> None:
568
+ if "pad_and_return_pixel_mask" in kwargs:
569
+ do_pad = kwargs.pop("pad_and_return_pixel_mask")
570
+
571
+ size = size if size is not None else {"shortest_edge": 800, "longest_edge": 1333}
572
+ size = get_size_dict(size, default_to_square=False)
573
+
574
+ if do_convert_annotations is None:
575
+ do_convert_annotations = do_normalize
576
+
577
+ super().__init__(**kwargs)
578
+ self.format = format
579
+ self.do_resize = do_resize
580
+ self.size = size
581
+ self.resample = resample
582
+ self.do_rescale = do_rescale
583
+ self.rescale_factor = rescale_factor
584
+ self.do_normalize = do_normalize
585
+ self.do_convert_annotations = do_convert_annotations
586
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
587
+ self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
588
+ self.do_pad = do_pad
589
+ self.pad_size = pad_size
590
+
591
+ def prepare_annotation(
592
+ self,
593
+ image: np.ndarray,
594
+ target: Dict,
595
+ format: Optional[AnnotationFormat] = None,
596
+ return_segmentation_masks: Optional[bool] = None,
597
+ masks_path: Optional[Union[str, pathlib.Path]] = None,
598
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
599
+ ) -> Dict:
600
+ """
601
+ Prepare an annotation for feeding into DETA model.
602
+ """
603
+ format = format if format is not None else self.format
604
+
605
+ if format == AnnotationFormat.COCO_DETECTION:
606
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
607
+ target = prepare_coco_detection_annotation(
608
+ image, target, return_segmentation_masks, input_data_format=input_data_format
609
+ )
610
+ elif format == AnnotationFormat.COCO_PANOPTIC:
611
+ return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks
612
+ target = prepare_coco_panoptic_annotation(
613
+ image,
614
+ target,
615
+ masks_path=masks_path,
616
+ return_masks=return_segmentation_masks,
617
+ input_data_format=input_data_format,
618
+ )
619
+ else:
620
+ raise ValueError(f"Format {format} is not supported.")
621
+ return target
622
+
623
+ def resize(
624
+ self,
625
+ image: np.ndarray,
626
+ size: Dict[str, int],
627
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
628
+ data_format: Optional[ChannelDimension] = None,
629
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
630
+ **kwargs,
631
+ ) -> np.ndarray:
632
+ """
633
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
634
+ int, smaller edge of the image will be matched to this number.
635
+
636
+ Args:
637
+ image (`np.ndarray`):
638
+ Image to resize.
639
+ size (`Dict[str, int]`):
640
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
641
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
642
+ Do NOT keep the aspect ratio.
643
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
644
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
645
+ less or equal to `longest_edge`.
646
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
647
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
648
+ `max_width`.
649
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
650
+ Resampling filter to use if resizing the image.
651
+ data_format (`ChannelDimension`, *optional*):
652
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
653
+ image is used.
654
+ input_data_format (`ChannelDimension` or `str`, *optional*):
655
+ The channel dimension format of the input image. If not provided, it will be inferred from the input
656
+ image.
657
+ """
658
+ size = get_size_dict(size, default_to_square=False)
659
+ if "shortest_edge" in size and "longest_edge" in size:
660
+ new_size = get_resize_output_image_size(
661
+ image, size["shortest_edge"], size["longest_edge"], input_data_format=input_data_format
662
+ )
663
+ elif "height" in size and "width" in size:
664
+ new_size = (size["height"], size["width"])
665
+ elif "max_height" in size and "max_width" in size:
666
+ new_size = get_image_size_for_max_height_width(
667
+ image, size["max_height"], size["max_width"], input_data_format=input_data_format
668
+ )
669
+ else:
670
+ raise ValueError(
671
+ "Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got"
672
+ f" {size.keys()}."
673
+ )
674
+ image = resize(
675
+ image, size=new_size, resample=resample, data_format=data_format, input_data_format=input_data_format
676
+ )
677
+ return image
678
+
679
+ def resize_annotation(
680
+ self,
681
+ annotation,
682
+ orig_size,
683
+ size,
684
+ resample: PILImageResampling = PILImageResampling.NEAREST,
685
+ ) -> Dict:
686
+ """
687
+ Resize the annotation to match the resized image. If size is an int, smaller edge of the mask will be matched
688
+ to this number.
689
+ """
690
+ return resize_annotation(annotation, orig_size=orig_size, target_size=size, resample=resample)
691
+
692
+ def rescale(
693
+ self,
694
+ image: np.ndarray,
695
+ rescale_factor: float,
696
+ data_format: Optional[Union[str, ChannelDimension]] = None,
697
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
698
+ ) -> np.ndarray:
699
+ """
700
+ Rescale the image by the given factor. image = image * rescale_factor.
701
+
702
+ Args:
703
+ image (`np.ndarray`):
704
+ Image to rescale.
705
+ rescale_factor (`float`):
706
+ The value to use for rescaling.
707
+ data_format (`str` or `ChannelDimension`, *optional*):
708
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
709
+ image is used. Can be one of:
710
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
711
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
712
+ input_data_format (`str` or `ChannelDimension`, *optional*):
713
+ The channel dimension format for the input image. If unset, is inferred from the input image. Can be
714
+ one of:
715
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
716
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
717
+ """
718
+ return rescale(image, rescale_factor, data_format=data_format, input_data_format=input_data_format)
719
+
720
+ def normalize_annotation(self, annotation: Dict, image_size: Tuple[int, int]) -> Dict:
721
+ """
722
+ Normalize the boxes in the annotation from `[top_left_x, top_left_y, bottom_right_x, bottom_right_y]` to
723
+ `[center_x, center_y, width, height]` format and from absolute to relative pixel values.
724
+ """
725
+ return normalize_annotation(annotation, image_size=image_size)
726
+
727
+ def _update_annotation_for_padded_image(
728
+ self,
729
+ annotation: Dict,
730
+ input_image_size: Tuple[int, int],
731
+ output_image_size: Tuple[int, int],
732
+ padding,
733
+ update_bboxes,
734
+ ) -> Dict:
735
+ """
736
+ Update the annotation for a padded image.
737
+ """
738
+ new_annotation = {}
739
+ new_annotation["size"] = output_image_size
740
+
741
+ for key, value in annotation.items():
742
+ if key == "masks":
743
+ masks = value
744
+ masks = pad(
745
+ masks,
746
+ padding,
747
+ mode=PaddingMode.CONSTANT,
748
+ constant_values=0,
749
+ input_data_format=ChannelDimension.FIRST,
750
+ )
751
+ masks = safe_squeeze(masks, 1)
752
+ new_annotation["masks"] = masks
753
+ elif key == "boxes" and update_bboxes:
754
+ boxes = value
755
+ boxes *= np.asarray(
756
+ [
757
+ input_image_size[1] / output_image_size[1],
758
+ input_image_size[0] / output_image_size[0],
759
+ input_image_size[1] / output_image_size[1],
760
+ input_image_size[0] / output_image_size[0],
761
+ ]
762
+ )
763
+ new_annotation["boxes"] = boxes
764
+ elif key == "size":
765
+ new_annotation["size"] = output_image_size
766
+ else:
767
+ new_annotation[key] = value
768
+ return new_annotation
769
+
770
+ def _pad_image(
771
+ self,
772
+ image: np.ndarray,
773
+ output_size: Tuple[int, int],
774
+ annotation: Optional[Dict[str, Any]] = None,
775
+ constant_values: Union[float, Iterable[float]] = 0,
776
+ data_format: Optional[ChannelDimension] = None,
777
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
778
+ update_bboxes: bool = True,
779
+ ) -> np.ndarray:
780
+ """
781
+ Pad an image with zeros to the given size.
782
+ """
783
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
784
+ output_height, output_width = output_size
785
+
786
+ pad_bottom = output_height - input_height
787
+ pad_right = output_width - input_width
788
+ padding = ((0, pad_bottom), (0, pad_right))
789
+ padded_image = pad(
790
+ image,
791
+ padding,
792
+ mode=PaddingMode.CONSTANT,
793
+ constant_values=constant_values,
794
+ data_format=data_format,
795
+ input_data_format=input_data_format,
796
+ )
797
+ if annotation is not None:
798
+ annotation = self._update_annotation_for_padded_image(
799
+ annotation, (input_height, input_width), (output_height, output_width), padding, update_bboxes
800
+ )
801
+ return padded_image, annotation
802
+
803
+ def pad(
804
+ self,
805
+ images: List[np.ndarray],
806
+ annotations: Optional[Union[AnnotationType, List[AnnotationType]]] = None,
807
+ constant_values: Union[float, Iterable[float]] = 0,
808
+ return_pixel_mask: bool = True,
809
+ return_tensors: Optional[Union[str, TensorType]] = None,
810
+ data_format: Optional[ChannelDimension] = None,
811
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
812
+ update_bboxes: bool = True,
813
+ pad_size: Optional[Dict[str, int]] = None,
814
+ ) -> BatchFeature:
815
+ """
816
+ Pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width
817
+ in the batch and optionally returns their corresponding pixel mask.
818
+
819
+ Args:
820
+ images (List[`np.ndarray`]):
821
+ Images to pad.
822
+ annotations (`AnnotationType` or `List[AnnotationType]`, *optional*):
823
+ Annotations to transform according to the padding that is applied to the images.
824
+ constant_values (`float` or `Iterable[float]`, *optional*):
825
+ The value to use for the padding if `mode` is `"constant"`.
826
+ return_pixel_mask (`bool`, *optional*, defaults to `True`):
827
+ Whether to return a pixel mask.
828
+ return_tensors (`str` or `TensorType`, *optional*):
829
+ The type of tensors to return. Can be one of:
830
+ - Unset: Return a list of `np.ndarray`.
831
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
832
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
833
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
834
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
835
+ data_format (`str` or `ChannelDimension`, *optional*):
836
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
837
+ input_data_format (`ChannelDimension` or `str`, *optional*):
838
+ The channel dimension format of the input image. If not provided, it will be inferred.
839
+ update_bboxes (`bool`, *optional*, defaults to `True`):
840
+ Whether to update the bounding boxes in the annotations to match the padded images. If the
841
+ bounding boxes have not been converted to relative coordinates and `(centre_x, centre_y, width, height)`
842
+ format, the bounding boxes will not be updated.
843
+ pad_size (`Dict[str, int]`, *optional*):
844
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
845
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
846
+ height and width in the batch.
847
+ """
848
+ pad_size = pad_size if pad_size is not None else self.pad_size
849
+ if pad_size is not None:
850
+ padded_size = (pad_size["height"], pad_size["width"])
851
+ else:
852
+ padded_size = get_max_height_width(images, input_data_format=input_data_format)
853
+
854
+ annotation_list = annotations if annotations is not None else [None] * len(images)
855
+ padded_images = []
856
+ padded_annotations = []
857
+ for image, annotation in zip(images, annotation_list):
858
+ padded_image, padded_annotation = self._pad_image(
859
+ image,
860
+ padded_size,
861
+ annotation,
862
+ constant_values=constant_values,
863
+ data_format=data_format,
864
+ input_data_format=input_data_format,
865
+ update_bboxes=update_bboxes,
866
+ )
867
+ padded_images.append(padded_image)
868
+ padded_annotations.append(padded_annotation)
869
+
870
+ data = {"pixel_values": padded_images}
871
+
872
+ if return_pixel_mask:
873
+ masks = [
874
+ make_pixel_mask(image=image, output_size=padded_size, input_data_format=input_data_format)
875
+ for image in images
876
+ ]
877
+ data["pixel_mask"] = masks
878
+
879
+ encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
880
+
881
+ if annotations is not None:
882
+ encoded_inputs["labels"] = [
883
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in padded_annotations
884
+ ]
885
+
886
+ return encoded_inputs
887
+
888
+ def preprocess(
889
+ self,
890
+ images: ImageInput,
891
+ annotations: Optional[Union[List[Dict], List[List[Dict]]]] = None,
892
+ return_segmentation_masks: Optional[bool] = None,
893
+ masks_path: Optional[Union[str, pathlib.Path]] = None,
894
+ do_resize: Optional[bool] = None,
895
+ size: Optional[Dict[str, int]] = None,
896
+ resample=None, # PILImageResampling
897
+ do_rescale: Optional[bool] = None,
898
+ rescale_factor: Optional[Union[int, float]] = None,
899
+ do_normalize: Optional[bool] = None,
900
+ image_mean: Optional[Union[float, List[float]]] = None,
901
+ image_std: Optional[Union[float, List[float]]] = None,
902
+ do_convert_annotations: Optional[bool] = None,
903
+ do_pad: Optional[bool] = None,
904
+ format: Optional[Union[str, AnnotationFormat]] = None,
905
+ return_tensors: Optional[Union[TensorType, str]] = None,
906
+ data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
907
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
908
+ pad_size: Optional[Dict[str, int]] = None,
909
+ **kwargs,
910
+ ) -> BatchFeature:
911
+ """
912
+ Preprocess an image or a batch of images so that it can be used by the model.
913
+
914
+ Args:
915
+ images (`ImageInput`):
916
+ Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging
917
+ from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
918
+ annotations (`List[Dict]` or `List[List[Dict]]`, *optional*):
919
+ List of annotations associated with the image or batch of images. If annotation is for object
920
+ detection, the annotations should be a dictionary with the following keys:
921
+ - "image_id" (`int`): The image id.
922
+ - "annotations" (`List[Dict]`): List of annotations for an image. Each annotation should be a
923
+ dictionary. An image can have no annotations, in which case the list should be empty.
924
+ If annotation is for segmentation, the annotations should be a dictionary with the following keys:
925
+ - "image_id" (`int`): The image id.
926
+ - "segments_info" (`List[Dict]`): List of segments for an image. Each segment should be a dictionary.
927
+ An image can have no segments, in which case the list should be empty.
928
+ - "file_name" (`str`): The file name of the image.
929
+ return_segmentation_masks (`bool`, *optional*, defaults to self.return_segmentation_masks):
930
+ Whether to return segmentation masks.
931
+ masks_path (`str` or `pathlib.Path`, *optional*):
932
+ Path to the directory containing the segmentation masks.
933
+ do_resize (`bool`, *optional*, defaults to self.do_resize):
934
+ Whether to resize the image.
935
+ size (`Dict[str, int]`, *optional*, defaults to self.size):
936
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
937
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
938
+ Do NOT keep the aspect ratio.
939
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
940
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
941
+ less or equal to `longest_edge`.
942
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
943
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
944
+ `max_width`.
945
+ resample (`PILImageResampling`, *optional*, defaults to self.resample):
946
+ Resampling filter to use when resizing the image.
947
+ do_rescale (`bool`, *optional*, defaults to self.do_rescale):
948
+ Whether to rescale the image.
949
+ rescale_factor (`float`, *optional*, defaults to self.rescale_factor):
950
+ Rescale factor to use when rescaling the image.
951
+ do_normalize (`bool`, *optional*, defaults to self.do_normalize):
952
+ Whether to normalize the image.
953
+ image_mean (`float` or `List[float]`, *optional*, defaults to self.image_mean):
954
+ Mean to use when normalizing the image.
955
+ image_std (`float` or `List[float]`, *optional*, defaults to self.image_std):
956
+ Standard deviation to use when normalizing the image.
957
+ do_convert_annotations (`bool`, *optional*, defaults to self.do_convert_annotations):
958
+ Whether to convert the annotations to the format expected by the model. Converts the bounding
959
+ boxes from the format `(top_left_x, top_left_y, width, height)` to `(center_x, center_y, width, height)`
960
+ and in relative coordinates.
961
+ do_pad (`bool`, *optional*, defaults to self.do_pad):
962
+ Whether to pad the image. If `True`, padding will be applied to the bottom and right of
963
+ the image with zeros. If `pad_size` is provided, the image will be padded to the specified
964
+ dimensions. Otherwise, the image will be padded to the maximum height and width of the batch.
965
+ format (`str` or `AnnotationFormat`, *optional*, defaults to self.format):
966
+ Format of the annotations.
967
+ return_tensors (`str` or `TensorType`, *optional*, defaults to self.return_tensors):
968
+ Type of tensors to return. If `None`, will return the list of images.
969
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
970
+ The channel dimension format for the output image. Can be one of:
971
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
972
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
973
+ - Unset: Use the channel dimension format of the input image.
974
+ input_data_format (`ChannelDimension` or `str`, *optional*):
975
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
976
+ from the input image. Can be one of:
977
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
978
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
979
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
980
+ pad_size (`Dict[str, int]`, *optional*):
981
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
982
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
983
+ height and width in the batch.
984
+ """
985
+ if "pad_and_return_pixel_mask" in kwargs:
986
+ logger.warning_once(
987
+ "The `pad_and_return_pixel_mask` argument is deprecated and will be removed in a future version, "
988
+ "use `do_pad` instead.",
989
+ )
990
+ do_pad = kwargs.pop("pad_and_return_pixel_mask")
991
+
992
+ do_resize = self.do_resize if do_resize is None else do_resize
993
+ size = self.size if size is None else size
994
+ size = get_size_dict(size=size, default_to_square=False)
995
+ resample = self.resample if resample is None else resample
996
+ do_rescale = self.do_rescale if do_rescale is None else do_rescale
997
+ rescale_factor = self.rescale_factor if rescale_factor is None else rescale_factor
998
+ do_normalize = self.do_normalize if do_normalize is None else do_normalize
999
+ image_mean = self.image_mean if image_mean is None else image_mean
1000
+ image_std = self.image_std if image_std is None else image_std
1001
+ do_convert_annotations = (
1002
+ self.do_convert_annotations if do_convert_annotations is None else do_convert_annotations
1003
+ )
1004
+ do_pad = self.do_pad if do_pad is None else do_pad
1005
+ pad_size = self.pad_size if pad_size is None else pad_size
1006
+ format = self.format if format is None else format
1007
+
1008
+ # Here, the pad() method pads to the maximum of (width, height). It does not need to be validated.
1009
+
1010
+ validate_preprocess_arguments(
1011
+ do_rescale=do_rescale,
1012
+ rescale_factor=rescale_factor,
1013
+ do_normalize=do_normalize,
1014
+ image_mean=image_mean,
1015
+ image_std=image_std,
1016
+ do_resize=do_resize,
1017
+ size=size,
1018
+ resample=resample,
1019
+ )
1020
+
1021
+ if not is_batched(images):
1022
+ images = [images]
1023
+ annotations = [annotations] if annotations is not None else None
1024
+
1025
+ if not valid_images(images):
1026
+ raise ValueError(
1027
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
1028
+ "torch.Tensor, tf.Tensor or jax.ndarray."
1029
+ )
1030
+ if annotations is not None and len(images) != len(annotations):
1031
+ raise ValueError(
1032
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
1033
+ )
1034
+
1035
+ format = AnnotationFormat(format)
1036
+ if annotations is not None:
1037
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
1038
+
1039
+ if (
1040
+ masks_path is not None
1041
+ and format == AnnotationFormat.COCO_PANOPTIC
1042
+ and not isinstance(masks_path, (pathlib.Path, str))
1043
+ ):
1044
+ raise ValueError(
1045
+ "The path to the directory containing the mask PNG files should be provided as a"
1046
+ f" `pathlib.Path` or string object, but is {type(masks_path)} instead."
1047
+ )
1048
+
1049
+ # All transformations expect numpy arrays
1050
+ images = [to_numpy_array(image) for image in images]
1051
+
1052
+ if do_rescale and is_scaled_image(images[0]):
1053
+ logger.warning_once(
1054
+ "It looks like you are trying to rescale already rescaled images. If the input"
1055
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
1056
+ )
1057
+
1058
+ if input_data_format is None:
1059
+ # We assume that all images have the same channel dimension format.
1060
+ input_data_format = infer_channel_dimension_format(images[0])
1061
+
1062
+ # prepare (COCO annotations as a list of Dict -> DETR target as a single Dict per image)
1063
+ if annotations is not None:
1064
+ prepared_images = []
1065
+ prepared_annotations = []
1066
+ for image, target in zip(images, annotations):
1067
+ target = self.prepare_annotation(
1068
+ image,
1069
+ target,
1070
+ format,
1071
+ return_segmentation_masks=return_segmentation_masks,
1072
+ masks_path=masks_path,
1073
+ input_data_format=input_data_format,
1074
+ )
1075
+ prepared_images.append(image)
1076
+ prepared_annotations.append(target)
1077
+ images = prepared_images
1078
+ annotations = prepared_annotations
1079
+ del prepared_images, prepared_annotations
1080
+
1081
+ # transformations
1082
+ if do_resize:
1083
+ if annotations is not None:
1084
+ resized_images, resized_annotations = [], []
1085
+ for image, target in zip(images, annotations):
1086
+ orig_size = get_image_size(image, input_data_format)
1087
+ resized_image = self.resize(
1088
+ image, size=size, resample=resample, input_data_format=input_data_format
1089
+ )
1090
+ resized_annotation = self.resize_annotation(
1091
+ target, orig_size, get_image_size(resized_image, input_data_format)
1092
+ )
1093
+ resized_images.append(resized_image)
1094
+ resized_annotations.append(resized_annotation)
1095
+ images = resized_images
1096
+ annotations = resized_annotations
1097
+ del resized_images, resized_annotations
1098
+ else:
1099
+ images = [
1100
+ self.resize(image, size=size, resample=resample, input_data_format=input_data_format)
1101
+ for image in images
1102
+ ]
1103
+
1104
+ if do_rescale:
1105
+ images = [self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]
1106
+
1107
+ if do_normalize:
1108
+ images = [
1109
+ self.normalize(image, image_mean, image_std, input_data_format=input_data_format) for image in images
1110
+ ]
1111
+
1112
+ if do_convert_annotations and annotations is not None:
1113
+ annotations = [
1114
+ self.normalize_annotation(annotation, get_image_size(image, input_data_format))
1115
+ for annotation, image in zip(annotations, images)
1116
+ ]
1117
+
1118
+ if do_pad:
1119
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
1120
+ encoded_inputs = self.pad(
1121
+ images,
1122
+ annotations=annotations,
1123
+ return_pixel_mask=True,
1124
+ data_format=data_format,
1125
+ input_data_format=input_data_format,
1126
+ return_tensors=return_tensors,
1127
+ update_bboxes=do_convert_annotations,
1128
+ pad_size=pad_size,
1129
+ )
1130
+ else:
1131
+ images = [
1132
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
1133
+ for image in images
1134
+ ]
1135
+ encoded_inputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
1136
+ if annotations is not None:
1137
+ encoded_inputs["labels"] = [
1138
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
1139
+ ]
1140
+
1141
+ return encoded_inputs
1142
+
1143
+ def post_process_object_detection(
1144
+ self,
1145
+ outputs,
1146
+ threshold: float = 0.5,
1147
+ target_sizes: Union[TensorType, List[Tuple]] = None,
1148
+ nms_threshold: float = 0.7,
1149
+ ):
1150
+ """
1151
+ Converts the output of [`DetaForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
1152
+ bottom_right_x, bottom_right_y) format. Only supports PyTorch.
1153
+
1154
+ Args:
1155
+ outputs ([`DetrObjectDetectionOutput`]):
1156
+ Raw outputs of the model.
1157
+ threshold (`float`, *optional*, defaults to 0.5):
1158
+ Score threshold to keep object detection predictions.
1159
+ target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*):
1160
+ Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size
1161
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
1162
+ nms_threshold (`float`, *optional*, defaults to 0.7):
1163
+ NMS threshold.
1164
+
1165
+ Returns:
1166
+ `List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
1167
+ in the batch as predicted by the model.
1168
+ """
1169
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
1170
+ batch_size, num_queries, num_labels = out_logits.shape
1171
+
1172
+ if target_sizes is not None:
1173
+ if len(out_logits) != len(target_sizes):
1174
+ raise ValueError(
1175
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
1176
+ )
1177
+
1178
+ prob = out_logits.sigmoid()
1179
+
1180
+ all_scores = prob.view(batch_size, num_queries * num_labels).to(out_logits.device)
1181
+ all_indexes = torch.arange(num_queries * num_labels)[None].repeat(batch_size, 1).to(out_logits.device)
1182
+ all_boxes = torch.div(all_indexes, out_logits.shape[2], rounding_mode="floor")
1183
+ all_labels = all_indexes % out_logits.shape[2]
1184
+
1185
+ boxes = center_to_corners_format(out_bbox)
1186
+ boxes = torch.gather(boxes, 1, all_boxes.unsqueeze(-1).repeat(1, 1, 4))
1187
+
1188
+ # and from relative [0, 1] to absolute [0, height] coordinates
1189
+ if target_sizes is not None:
1190
+ if isinstance(target_sizes, List):
1191
+ img_h = torch.Tensor([i[0] for i in target_sizes])
1192
+ img_w = torch.Tensor([i[1] for i in target_sizes])
1193
+ else:
1194
+ img_h, img_w = target_sizes.unbind(1)
1195
+
1196
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
1197
+ boxes = boxes * scale_fct[:, None, :]
1198
+
1199
+ results = []
1200
+ for b in range(batch_size):
1201
+ box = boxes[b]
1202
+ score = all_scores[b]
1203
+ lbls = all_labels[b]
1204
+
1205
+ pre_topk = score.topk(min(10000, num_queries * num_labels)).indices
1206
+ box = box[pre_topk]
1207
+ score = score[pre_topk]
1208
+ lbls = lbls[pre_topk]
1209
+
1210
+ # apply NMS
1211
+ keep_inds = batched_nms(box, score, lbls, nms_threshold)[:100]
1212
+ score = score[keep_inds]
1213
+ lbls = lbls[keep_inds]
1214
+ box = box[keep_inds]
1215
+
1216
+ results.append(
1217
+ {
1218
+ "scores": score[score > threshold],
1219
+ "labels": lbls[score > threshold],
1220
+ "boxes": box[score > threshold],
1221
+ }
1222
+ )
1223
+
1224
+ return results
1225
+
1226
+
1227
+ __all__ = ["DetaImageProcessor"]
docs/transformers/build/lib/transformers/models/deprecated/deta/modeling_deta.py ADDED
The diff for this file is too large to render. See raw diff
 
docs/transformers/build/lib/transformers/models/deprecated/efficientformer/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ....utils import _LazyModule
17
+ from ....utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_efficientformer import *
22
+ from .image_processing_efficientformer import *
23
+ from .modeling_efficientformer import *
24
+ from .modeling_tf_efficientformer import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
docs/transformers/build/lib/transformers/models/deprecated/efficientformer/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Convert EfficientFormer checkpoints from the original repository.
17
+
18
+ URL: https://github.com/snap-research/EfficientFormer
19
+ """
20
+
21
+ import argparse
22
+ import re
23
+ from pathlib import Path
24
+
25
+ import requests
26
+ import torch
27
+ from PIL import Image
28
+ from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor
29
+
30
+ from transformers import (
31
+ EfficientFormerConfig,
32
+ EfficientFormerForImageClassificationWithTeacher,
33
+ EfficientFormerImageProcessor,
34
+ )
35
+ from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling
36
+
37
+
38
+ def rename_key(old_name, num_meta4D_last_stage):
39
+ new_name = old_name
40
+
41
+ if "patch_embed" in old_name:
42
+ _, layer, param = old_name.split(".")
43
+
44
+ if layer == "0":
45
+ new_name = old_name.replace("0", "convolution1")
46
+ elif layer == "1":
47
+ new_name = old_name.replace("1", "batchnorm_before")
48
+ elif layer == "3":
49
+ new_name = old_name.replace("3", "convolution2")
50
+ else:
51
+ new_name = old_name.replace("4", "batchnorm_after")
52
+
53
+ if "network" in old_name and re.search(r"\d\.\d", old_name):
54
+ two_digit_num = r"\b\d{2}\b"
55
+ if bool(re.search(two_digit_num, old_name)):
56
+ match = re.search(r"\d\.\d\d.", old_name).group()
57
+ else:
58
+ match = re.search(r"\d\.\d.", old_name).group()
59
+ if int(match[0]) < 6:
60
+ trimmed_name = old_name.replace(match, "")
61
+ trimmed_name = trimmed_name.replace("network", match[0] + ".meta4D_layers.blocks." + match[2:-1])
62
+ new_name = "intermediate_stages." + trimmed_name
63
+ else:
64
+ trimmed_name = old_name.replace(match, "")
65
+ if int(match[2]) < num_meta4D_last_stage:
66
+ trimmed_name = trimmed_name.replace("network", "meta4D_layers.blocks." + match[2])
67
+ else:
68
+ layer_index = str(int(match[2]) - num_meta4D_last_stage)
69
+ trimmed_name = trimmed_name.replace("network", "meta3D_layers.blocks." + layer_index)
70
+ if "norm1" in old_name:
71
+ trimmed_name = trimmed_name.replace("norm1", "layernorm1")
72
+ elif "norm2" in old_name:
73
+ trimmed_name = trimmed_name.replace("norm2", "layernorm2")
74
+ elif "fc1" in old_name:
75
+ trimmed_name = trimmed_name.replace("fc1", "linear_in")
76
+ elif "fc2" in old_name:
77
+ trimmed_name = trimmed_name.replace("fc2", "linear_out")
78
+
79
+ new_name = "last_stage." + trimmed_name
80
+
81
+ elif "network" in old_name and re.search(r".\d.", old_name):
82
+ new_name = old_name.replace("network", "intermediate_stages")
83
+
84
+ if "fc" in new_name:
85
+ new_name = new_name.replace("fc", "convolution")
86
+ elif ("norm1" in new_name) and ("layernorm1" not in new_name):
87
+ new_name = new_name.replace("norm1", "batchnorm_before")
88
+ elif ("norm2" in new_name) and ("layernorm2" not in new_name):
89
+ new_name = new_name.replace("norm2", "batchnorm_after")
90
+ if "proj" in new_name:
91
+ new_name = new_name.replace("proj", "projection")
92
+ if "dist_head" in new_name:
93
+ new_name = new_name.replace("dist_head", "distillation_classifier")
94
+ elif "head" in new_name:
95
+ new_name = new_name.replace("head", "classifier")
96
+ elif "patch_embed" in new_name:
97
+ new_name = "efficientformer." + new_name
98
+ elif new_name == "norm.weight" or new_name == "norm.bias":
99
+ new_name = new_name.replace("norm", "layernorm")
100
+ new_name = "efficientformer." + new_name
101
+ else:
102
+ new_name = "efficientformer.encoder." + new_name
103
+
104
+ return new_name
105
+
106
+
107
+ def convert_torch_checkpoint(checkpoint, num_meta4D_last_stage):
108
+ for key in checkpoint.copy().keys():
109
+ val = checkpoint.pop(key)
110
+ checkpoint[rename_key(key, num_meta4D_last_stage)] = val
111
+
112
+ return checkpoint
113
+
114
+
115
+ # We will verify our results on a COCO image
116
+ def prepare_img():
117
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
118
+ image = Image.open(requests.get(url, stream=True).raw)
119
+
120
+ return image
121
+
122
+
123
+ def convert_efficientformer_checkpoint(
124
+ checkpoint_path: Path, efficientformer_config_file: Path, pytorch_dump_path: Path, push_to_hub: bool
125
+ ):
126
+ orig_state_dict = torch.load(checkpoint_path, map_location="cpu", weights_only=True)["model"]
127
+ config = EfficientFormerConfig.from_json_file(efficientformer_config_file)
128
+ model = EfficientFormerForImageClassificationWithTeacher(config)
129
+ model_name = "_".join(checkpoint_path.split("/")[-1].split(".")[0].split("_")[:-1])
130
+
131
+ num_meta4D_last_stage = config.depths[-1] - config.num_meta3d_blocks + 1
132
+ new_state_dict = convert_torch_checkpoint(orig_state_dict, num_meta4D_last_stage)
133
+
134
+ model.load_state_dict(new_state_dict)
135
+ model.eval()
136
+
137
+ pillow_resamplings = {
138
+ "bilinear": PILImageResampling.BILINEAR,
139
+ "bicubic": PILImageResampling.BICUBIC,
140
+ "nearest": PILImageResampling.NEAREST,
141
+ }
142
+
143
+ # prepare image
144
+ image = prepare_img()
145
+ image_size = 256
146
+ crop_size = 224
147
+ processor = EfficientFormerImageProcessor(
148
+ size={"shortest_edge": image_size},
149
+ crop_size={"height": crop_size, "width": crop_size},
150
+ resample=pillow_resamplings["bicubic"],
151
+ )
152
+ pixel_values = processor(images=image, return_tensors="pt").pixel_values
153
+
154
+ # original processing pipeline
155
+ image_transforms = Compose(
156
+ [
157
+ Resize(image_size, interpolation=pillow_resamplings["bicubic"]),
158
+ CenterCrop(crop_size),
159
+ ToTensor(),
160
+ Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD),
161
+ ]
162
+ )
163
+ original_pixel_values = image_transforms(image).unsqueeze(0)
164
+
165
+ assert torch.allclose(original_pixel_values, pixel_values)
166
+
167
+ outputs = model(pixel_values)
168
+ logits = outputs.logits
169
+
170
+ expected_shape = (1, 1000)
171
+
172
+ if "l1" in model_name:
173
+ expected_logits = torch.Tensor(
174
+ [-0.1312, 0.4353, -1.0499, -0.5124, 0.4183, -0.6793, -1.3777, -0.0893, -0.7358, -2.4328]
175
+ )
176
+ assert torch.allclose(logits[0, :10], expected_logits, atol=1e-3)
177
+ assert logits.shape == expected_shape
178
+ elif "l3" in model_name:
179
+ expected_logits = torch.Tensor(
180
+ [-1.3150, -1.5456, -1.2556, -0.8496, -0.7127, -0.7897, -0.9728, -0.3052, 0.3751, -0.3127]
181
+ )
182
+ assert torch.allclose(logits[0, :10], expected_logits, atol=1e-3)
183
+ assert logits.shape == expected_shape
184
+ elif "l7" in model_name:
185
+ expected_logits = torch.Tensor(
186
+ [-1.0283, -1.4131, -0.5644, -1.3115, -0.5785, -1.2049, -0.7528, 0.1992, -0.3822, -0.0878]
187
+ )
188
+ assert logits.shape == expected_shape
189
+ else:
190
+ raise ValueError(
191
+ f"Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7"
192
+ )
193
+
194
+ # Save Checkpoints
195
+ Path(pytorch_dump_path).mkdir(exist_ok=True)
196
+ model.save_pretrained(pytorch_dump_path)
197
+ print(f"Checkpoint successfuly converted. Model saved at {pytorch_dump_path}")
198
+ processor.save_pretrained(pytorch_dump_path)
199
+ print(f"Processor successfuly saved at {pytorch_dump_path}")
200
+
201
+ if push_to_hub:
202
+ print("Pushing model to the hub...")
203
+
204
+ model.push_to_hub(
205
+ repo_id=f"Bearnardd/{pytorch_dump_path}",
206
+ commit_message="Add model",
207
+ use_temp_dir=True,
208
+ )
209
+ processor.push_to_hub(
210
+ repo_id=f"Bearnardd/{pytorch_dump_path}",
211
+ commit_message="Add image processor",
212
+ use_temp_dir=True,
213
+ )
214
+
215
+
216
+ if __name__ == "__main__":
217
+ parser = argparse.ArgumentParser()
218
+ # Required parameters
219
+ parser.add_argument(
220
+ "--pytorch_model_path",
221
+ default=None,
222
+ type=str,
223
+ required=True,
224
+ help="Path to EfficientFormer pytorch checkpoint.",
225
+ )
226
+ parser.add_argument(
227
+ "--config_file",
228
+ default=None,
229
+ type=str,
230
+ required=True,
231
+ help="The json file for EfficientFormer model config.",
232
+ )
233
+ parser.add_argument(
234
+ "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
235
+ )
236
+
237
+ parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub")
238
+ parser.add_argument(
239
+ "--no-push_to_hub",
240
+ dest="push_to_hub",
241
+ action="store_false",
242
+ help="Do not push model and image processor to the hub",
243
+ )
244
+ parser.set_defaults(push_to_hub=True)
245
+
246
+ args = parser.parse_args()
247
+ convert_efficientformer_checkpoint(
248
+ checkpoint_path=args.pytorch_model_path,
249
+ efficientformer_config_file=args.config_file,
250
+ pytorch_dump_path=args.pytorch_dump_path,
251
+ push_to_hub=args.push_to_hub,
252
+ )
docs/transformers/build/lib/transformers/models/depth_anything/convert_depth_anything_to_hf.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 Depth Anything checkpoints from the original repository. URL:
16
+ https://github.com/LiheYoung/Depth-Anything"""
17
+
18
+ import argparse
19
+ from pathlib import Path
20
+
21
+ import requests
22
+ import torch
23
+ from huggingface_hub import hf_hub_download
24
+ from PIL import Image
25
+
26
+ from transformers import DepthAnythingConfig, DepthAnythingForDepthEstimation, Dinov2Config, DPTImageProcessor
27
+ from transformers.utils import logging
28
+
29
+
30
+ logging.set_verbosity_info()
31
+ logger = logging.get_logger(__name__)
32
+
33
+
34
+ def get_dpt_config(model_name):
35
+ if "small" in model_name:
36
+ out_indices = [3, 6, 9, 12] if "v2" in model_name else [9, 10, 11, 12]
37
+ backbone_config = Dinov2Config.from_pretrained(
38
+ "facebook/dinov2-small", out_indices=out_indices, apply_layernorm=True, reshape_hidden_states=False
39
+ )
40
+ fusion_hidden_size = 64
41
+ neck_hidden_sizes = [48, 96, 192, 384]
42
+ elif "base" in model_name:
43
+ out_indices = [3, 6, 9, 12] if "v2" in model_name else [9, 10, 11, 12]
44
+ backbone_config = Dinov2Config.from_pretrained(
45
+ "facebook/dinov2-base", out_indices=out_indices, apply_layernorm=True, reshape_hidden_states=False
46
+ )
47
+ fusion_hidden_size = 128
48
+ neck_hidden_sizes = [96, 192, 384, 768]
49
+ elif "large" in model_name:
50
+ out_indices = [5, 12, 18, 24] if "v2" in model_name else [21, 22, 23, 24]
51
+ backbone_config = Dinov2Config.from_pretrained(
52
+ "facebook/dinov2-large", out_indices=out_indices, apply_layernorm=True, reshape_hidden_states=False
53
+ )
54
+ fusion_hidden_size = 256
55
+ neck_hidden_sizes = [256, 512, 1024, 1024]
56
+ else:
57
+ raise NotImplementedError(f"Model not supported: {model_name}")
58
+
59
+ if "metric" in model_name:
60
+ depth_estimation_type = "metric"
61
+ max_depth = 20 if "indoor" in model_name else 80
62
+ else:
63
+ depth_estimation_type = "relative"
64
+ max_depth = None
65
+
66
+ config = DepthAnythingConfig(
67
+ reassemble_hidden_size=backbone_config.hidden_size,
68
+ patch_size=backbone_config.patch_size,
69
+ backbone_config=backbone_config,
70
+ fusion_hidden_size=fusion_hidden_size,
71
+ neck_hidden_sizes=neck_hidden_sizes,
72
+ depth_estimation_type=depth_estimation_type,
73
+ max_depth=max_depth,
74
+ )
75
+
76
+ return config
77
+
78
+
79
+ def create_rename_keys(config):
80
+ rename_keys = []
81
+
82
+ # fmt: off
83
+ # stem
84
+ rename_keys.append(("pretrained.cls_token", "backbone.embeddings.cls_token"))
85
+ rename_keys.append(("pretrained.mask_token", "backbone.embeddings.mask_token"))
86
+ rename_keys.append(("pretrained.pos_embed", "backbone.embeddings.position_embeddings"))
87
+ rename_keys.append(("pretrained.patch_embed.proj.weight", "backbone.embeddings.patch_embeddings.projection.weight"))
88
+ rename_keys.append(("pretrained.patch_embed.proj.bias", "backbone.embeddings.patch_embeddings.projection.bias"))
89
+
90
+ # Transfomer encoder
91
+ for i in range(config.backbone_config.num_hidden_layers):
92
+ rename_keys.append((f"pretrained.blocks.{i}.ls1.gamma", f"backbone.encoder.layer.{i}.layer_scale1.lambda1"))
93
+ rename_keys.append((f"pretrained.blocks.{i}.ls2.gamma", f"backbone.encoder.layer.{i}.layer_scale2.lambda1"))
94
+ rename_keys.append((f"pretrained.blocks.{i}.norm1.weight", f"backbone.encoder.layer.{i}.norm1.weight"))
95
+ rename_keys.append((f"pretrained.blocks.{i}.norm1.bias", f"backbone.encoder.layer.{i}.norm1.bias"))
96
+ rename_keys.append((f"pretrained.blocks.{i}.norm2.weight", f"backbone.encoder.layer.{i}.norm2.weight"))
97
+ rename_keys.append((f"pretrained.blocks.{i}.norm2.bias", f"backbone.encoder.layer.{i}.norm2.bias"))
98
+ rename_keys.append((f"pretrained.blocks.{i}.mlp.fc1.weight", f"backbone.encoder.layer.{i}.mlp.fc1.weight"))
99
+ rename_keys.append((f"pretrained.blocks.{i}.mlp.fc1.bias", f"backbone.encoder.layer.{i}.mlp.fc1.bias"))
100
+ rename_keys.append((f"pretrained.blocks.{i}.mlp.fc2.weight", f"backbone.encoder.layer.{i}.mlp.fc2.weight"))
101
+ rename_keys.append((f"pretrained.blocks.{i}.mlp.fc2.bias", f"backbone.encoder.layer.{i}.mlp.fc2.bias"))
102
+ rename_keys.append((f"pretrained.blocks.{i}.attn.proj.weight", f"backbone.encoder.layer.{i}.attention.output.dense.weight"))
103
+ rename_keys.append((f"pretrained.blocks.{i}.attn.proj.bias", f"backbone.encoder.layer.{i}.attention.output.dense.bias"))
104
+
105
+ # Head
106
+ rename_keys.append(("pretrained.norm.weight", "backbone.layernorm.weight"))
107
+ rename_keys.append(("pretrained.norm.bias", "backbone.layernorm.bias"))
108
+
109
+ # activation postprocessing (readout projections + resize blocks)
110
+ # Depth Anything does not use CLS token => readout_projects not required
111
+
112
+ for i in range(4):
113
+ rename_keys.append((f"depth_head.projects.{i}.weight", f"neck.reassemble_stage.layers.{i}.projection.weight"))
114
+ rename_keys.append((f"depth_head.projects.{i}.bias", f"neck.reassemble_stage.layers.{i}.projection.bias"))
115
+
116
+ if i != 2:
117
+ rename_keys.append((f"depth_head.resize_layers.{i}.weight", f"neck.reassemble_stage.layers.{i}.resize.weight"))
118
+ rename_keys.append((f"depth_head.resize_layers.{i}.bias", f"neck.reassemble_stage.layers.{i}.resize.bias"))
119
+
120
+ # refinenet (tricky here)
121
+ mapping = {1:3, 2:2, 3:1, 4:0}
122
+
123
+ for i in range(1, 5):
124
+ j = mapping[i]
125
+ rename_keys.append((f"depth_head.scratch.refinenet{i}.out_conv.weight", f"neck.fusion_stage.layers.{j}.projection.weight"))
126
+ rename_keys.append((f"depth_head.scratch.refinenet{i}.out_conv.bias", f"neck.fusion_stage.layers.{j}.projection.bias"))
127
+ rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit1.conv1.weight", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution1.weight"))
128
+ rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit1.conv1.bias", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution1.bias"))
129
+ rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit1.conv2.weight", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution2.weight"))
130
+ rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit1.conv2.bias", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution2.bias"))
131
+ rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit2.conv1.weight", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution1.weight"))
132
+ rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit2.conv1.bias", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution1.bias"))
133
+ rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit2.conv2.weight", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution2.weight"))
134
+ rename_keys.append((f"depth_head.scratch.refinenet{i}.resConfUnit2.conv2.bias", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution2.bias"))
135
+
136
+ # scratch convolutions
137
+ for i in range(4):
138
+ rename_keys.append((f"depth_head.scratch.layer{i+1}_rn.weight", f"neck.convs.{i}.weight"))
139
+
140
+ # head
141
+ rename_keys.append(("depth_head.scratch.output_conv1.weight", "head.conv1.weight"))
142
+ rename_keys.append(("depth_head.scratch.output_conv1.bias", "head.conv1.bias"))
143
+ rename_keys.append(("depth_head.scratch.output_conv2.0.weight", "head.conv2.weight"))
144
+ rename_keys.append(("depth_head.scratch.output_conv2.0.bias", "head.conv2.bias"))
145
+ rename_keys.append(("depth_head.scratch.output_conv2.2.weight", "head.conv3.weight"))
146
+ rename_keys.append(("depth_head.scratch.output_conv2.2.bias", "head.conv3.bias"))
147
+
148
+ return rename_keys
149
+
150
+
151
+ # we split up the matrix of each encoder layer into queries, keys and values
152
+ def read_in_q_k_v(state_dict, config):
153
+ hidden_size = config.backbone_config.hidden_size
154
+ for i in range(config.backbone_config.num_hidden_layers):
155
+ # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
156
+ in_proj_weight = state_dict.pop(f"pretrained.blocks.{i}.attn.qkv.weight")
157
+ in_proj_bias = state_dict.pop(f"pretrained.blocks.{i}.attn.qkv.bias")
158
+ # next, add query, keys and values (in that order) to the state dict
159
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[:hidden_size, :]
160
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.query.bias"] = in_proj_bias[:hidden_size]
161
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
162
+ hidden_size : hidden_size * 2, :
163
+ ]
164
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.key.bias"] = in_proj_bias[
165
+ hidden_size : hidden_size * 2
166
+ ]
167
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[-hidden_size:, :]
168
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.value.bias"] = in_proj_bias[-hidden_size:]
169
+
170
+
171
+ def rename_key(dct, old, new):
172
+ val = dct.pop(old)
173
+ dct[new] = val
174
+
175
+
176
+ # We will verify our results on an image of cute cats
177
+ def prepare_img():
178
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
179
+ im = Image.open(requests.get(url, stream=True).raw)
180
+ return im
181
+
182
+
183
+ name_to_checkpoint = {
184
+ "depth-anything-small": "pytorch_model.bin",
185
+ "depth-anything-base": "pytorch_model.bin",
186
+ "depth-anything-large": "pytorch_model.bin",
187
+ "depth-anything-v2-small": "depth_anything_v2_vits.pth",
188
+ "depth-anything-v2-base": "depth_anything_v2_vitb.pth",
189
+ "depth-anything-v2-large": "depth_anything_v2_vitl.pth",
190
+ "depth-anything-v2-metric-indoor-small": "depth_anything_v2_metric_hypersim_vits.pth",
191
+ "depth-anything-v2-metric-indoor-base": "depth_anything_v2_metric_hypersim_vitb.pth",
192
+ "depth-anything-v2-metric-indoor-large": "depth_anything_v2_metric_hypersim_vitl.pth",
193
+ "depth-anything-v2-metric-outdoor-small": "depth_anything_v2_metric_vkitti_vits.pth",
194
+ "depth-anything-v2-metric-outdoor-base": "depth_anything_v2_metric_vkitti_vitb.pth",
195
+ "depth-anything-v2-metric-outdoor-large": "depth_anything_v2_metric_vkitti_vitl.pth",
196
+ # v2-giant pending
197
+ }
198
+
199
+
200
+ @torch.no_grad()
201
+ def convert_dpt_checkpoint(model_name, pytorch_dump_folder_path, push_to_hub, verify_logits):
202
+ """
203
+ Copy/paste/tweak model's weights to our DPT structure.
204
+ """
205
+
206
+ # define DPT configuration
207
+ config = get_dpt_config(model_name)
208
+
209
+ model_name_to_repo = {
210
+ "depth-anything-small": "LiheYoung/depth_anything_vits14",
211
+ "depth-anything-base": "LiheYoung/depth_anything_vitb14",
212
+ "depth-anything-large": "LiheYoung/depth_anything_vitl14",
213
+ "depth-anything-v2-small": "depth-anything/Depth-Anything-V2-Small",
214
+ "depth-anything-v2-base": "depth-anything/Depth-Anything-V2-Base",
215
+ "depth-anything-v2-large": "depth-anything/Depth-Anything-V2-Large",
216
+ "depth-anything-v2-metric-indoor-small": "depth-anything/Depth-Anything-V2-Metric-Hypersim-Small",
217
+ "depth-anything-v2-metric-indoor-base": "depth-anything/Depth-Anything-V2-Metric-Hypersim-Base",
218
+ "depth-anything-v2-metric-indoor-large": "depth-anything/Depth-Anything-V2-Metric-Hypersim-Large",
219
+ "depth-anything-v2-metric-outdoor-small": "depth-anything/Depth-Anything-V2-Metric-VKITTI-Small",
220
+ "depth-anything-v2-metric-outdoor-base": "depth-anything/Depth-Anything-V2-Metric-VKITTI-Base",
221
+ "depth-anything-v2-metric-outdoor-large": "depth-anything/Depth-Anything-V2-Metric-VKITTI-Large",
222
+ }
223
+
224
+ # load original state_dict
225
+ repo_id = model_name_to_repo[model_name]
226
+ filename = name_to_checkpoint[model_name]
227
+ filepath = hf_hub_download(
228
+ repo_id=repo_id,
229
+ filename=f"{filename}",
230
+ )
231
+
232
+ state_dict = torch.load(filepath, map_location="cpu", weights_only=True)
233
+ # rename keys
234
+ rename_keys = create_rename_keys(config)
235
+ for src, dest in rename_keys:
236
+ rename_key(state_dict, src, dest)
237
+ # read in qkv matrices
238
+ read_in_q_k_v(state_dict, config)
239
+
240
+ # load HuggingFace model
241
+ model = DepthAnythingForDepthEstimation(config)
242
+ model.load_state_dict(state_dict)
243
+ model.eval()
244
+
245
+ processor = DPTImageProcessor(
246
+ do_resize=True,
247
+ size={"height": 518, "width": 518},
248
+ ensure_multiple_of=14,
249
+ keep_aspect_ratio=True,
250
+ do_rescale=True,
251
+ do_normalize=True,
252
+ image_mean=[0.485, 0.456, 0.406],
253
+ image_std=[0.229, 0.224, 0.225],
254
+ )
255
+
256
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
257
+ image = Image.open(requests.get(url, stream=True).raw)
258
+
259
+ pixel_values = processor(image, return_tensors="pt").pixel_values
260
+
261
+ # Verify forward pass
262
+ with torch.no_grad():
263
+ outputs = model(pixel_values)
264
+ predicted_depth = outputs.predicted_depth
265
+
266
+ print("Shape of predicted depth:", predicted_depth.shape)
267
+ print("First values:", predicted_depth[0, :3, :3])
268
+
269
+ # assert logits
270
+ if verify_logits:
271
+ expected_shape = torch.Size([1, 518, 686])
272
+ if model_name == "depth-anything-small":
273
+ expected_slice = torch.tensor(
274
+ [[8.8204, 8.6468, 8.6195], [8.3313, 8.6027, 8.7526], [8.6526, 8.6866, 8.7453]],
275
+ )
276
+ elif model_name == "depth-anything-base":
277
+ expected_slice = torch.tensor(
278
+ [[26.3997, 26.3004, 26.3928], [26.2260, 26.2092, 26.3427], [26.0719, 26.0483, 26.1254]],
279
+ )
280
+ elif model_name == "depth-anything-large":
281
+ expected_slice = torch.tensor(
282
+ [[87.9968, 87.7493, 88.2704], [87.1927, 87.6611, 87.3640], [86.7789, 86.9469, 86.7991]]
283
+ )
284
+ elif model_name == "depth-anything-v2-small":
285
+ expected_slice = torch.tensor(
286
+ [[2.6751, 2.6211, 2.6571], [2.5820, 2.6138, 2.6271], [2.6160, 2.6141, 2.6306]]
287
+ )
288
+ elif model_name == "depth-anything-v2-base":
289
+ expected_slice = torch.tensor(
290
+ [[4.3576, 4.3723, 4.3908], [4.3231, 4.3146, 4.3611], [4.3016, 4.3170, 4.3121]]
291
+ )
292
+ elif model_name == "depth-anything-v2-large":
293
+ expected_slice = torch.tensor(
294
+ [[162.2751, 161.8504, 162.8788], [160.3138, 160.8050, 161.9835], [159.3812, 159.9884, 160.0768]]
295
+ )
296
+ elif model_name == "depth-anything-v2-metric-indoor-small":
297
+ expected_slice = torch.tensor(
298
+ [[1.3349, 1.2946, 1.2801], [1.2793, 1.2337, 1.2899], [1.2629, 1.2218, 1.2476]]
299
+ )
300
+ elif model_name == "depth-anything-v2-metric-indoor-base":
301
+ expected_slice = torch.tensor(
302
+ [[1.4601, 1.3824, 1.4904], [1.5031, 1.4349, 1.4274], [1.4570, 1.4578, 1.4200]]
303
+ )
304
+ elif model_name == "depth-anything-v2-metric-indoor-large":
305
+ expected_slice = torch.tensor(
306
+ [[1.5040, 1.5019, 1.5218], [1.5087, 1.5195, 1.5149], [1.5437, 1.5128, 1.5252]]
307
+ )
308
+ elif model_name == "depth-anything-v2-metric-outdoor-small":
309
+ expected_slice = torch.tensor(
310
+ [[9.5804, 8.0339, 7.7386], [7.9890, 7.2464, 7.7149], [7.7021, 7.2330, 7.3304]]
311
+ )
312
+ elif model_name == "depth-anything-v2-metric-outdoor-base":
313
+ expected_slice = torch.tensor(
314
+ [[10.2916, 9.0933, 8.8622], [9.1964, 9.3393, 9.0644], [8.9618, 9.4201, 9.2262]]
315
+ )
316
+ elif model_name == "depth-anything-v2-metric-outdoor-large":
317
+ expected_slice = torch.tensor(
318
+ [[14.0137, 13.3627, 13.1080], [13.2522, 13.3943, 13.3705], [13.0581, 13.4505, 13.3925]]
319
+ )
320
+ else:
321
+ raise ValueError("Not supported")
322
+
323
+ assert predicted_depth.shape == torch.Size(expected_shape)
324
+ assert torch.allclose(predicted_depth[0, :3, :3], expected_slice, atol=1e-4)
325
+ print("Looks ok!")
326
+
327
+ if pytorch_dump_folder_path is not None:
328
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
329
+ print(f"Saving model and processor to {pytorch_dump_folder_path}")
330
+ model.save_pretrained(pytorch_dump_folder_path)
331
+ processor.save_pretrained(pytorch_dump_folder_path)
332
+
333
+ if push_to_hub:
334
+ print("Pushing model and processor to hub...")
335
+ model.push_to_hub(repo_id=f"{model_name.title()}-hf")
336
+ processor.push_to_hub(repo_id=f"{model_name.title()}-hf")
337
+
338
+
339
+ if __name__ == "__main__":
340
+ parser = argparse.ArgumentParser()
341
+ # Required parameters
342
+ parser.add_argument(
343
+ "--model_name",
344
+ default="depth-anything-small",
345
+ type=str,
346
+ choices=name_to_checkpoint.keys(),
347
+ help="Name of the model you'd like to convert.",
348
+ )
349
+ parser.add_argument(
350
+ "--pytorch_dump_folder_path",
351
+ default=None,
352
+ type=str,
353
+ help="Path to the output PyTorch model directory.",
354
+ )
355
+ parser.add_argument(
356
+ "--push_to_hub",
357
+ action="store_true",
358
+ help="Whether to push the model to the hub after conversion.",
359
+ )
360
+ parser.add_argument(
361
+ "--verify_logits",
362
+ action="store_false",
363
+ required=False,
364
+ help="Whether to verify the logits after conversion.",
365
+ )
366
+
367
+ args = parser.parse_args()
368
+ convert_dpt_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.verify_logits)
docs/transformers/build/lib/transformers/models/depth_pro/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_depth_pro import *
22
+ from .image_processing_depth_pro import *
23
+ from .image_processing_depth_pro_fast import *
24
+ from .modeling_depth_pro import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
docs/transformers/build/lib/transformers/models/phi3/modeling_phi3.py ADDED
@@ -0,0 +1,1126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/phi3/modular_phi3.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_phi3.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+
23
+ from typing import Callable, Optional, Tuple, Union
24
+
25
+ import torch
26
+ from torch import nn
27
+
28
+ from ...activations import ACT2FN
29
+ from ...cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
30
+ from ...generation import GenerationMixin
31
+ from ...integrations import use_kernel_forward_from_hub
32
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
33
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
34
+ from ...modeling_layers import GradientCheckpointingLayer
35
+ from ...modeling_outputs import (
36
+ BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
+ from ...processing_utils import Unpack
44
+ from ...utils import (
45
+ LossKwargs,
46
+ add_code_sample_docstrings,
47
+ add_start_docstrings,
48
+ add_start_docstrings_to_model_forward,
49
+ can_return_tuple,
50
+ is_torch_flex_attn_available,
51
+ logging,
52
+ replace_return_docstrings,
53
+ )
54
+ from .configuration_phi3 import Phi3Config
55
+
56
+
57
+ if is_torch_flex_attn_available():
58
+ from torch.nn.attention.flex_attention import BlockMask
59
+
60
+ from ...integrations.flex_attention import make_flex_block_causal_mask
61
+
62
+
63
+ logger = logging.get_logger(__name__)
64
+
65
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
66
+ _CONFIG_FOR_DOC = "Phi3Config"
67
+
68
+
69
+ class Phi3MLP(nn.Module):
70
+ def __init__(self, config):
71
+ super().__init__()
72
+
73
+ self.config = config
74
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
75
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
76
+ self.activation_fn = ACT2FN[config.hidden_act]
77
+
78
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
79
+ up_states = self.gate_up_proj(hidden_states)
80
+
81
+ gate, up_states = up_states.chunk(2, dim=-1)
82
+ up_states = up_states * self.activation_fn(gate)
83
+
84
+ return self.down_proj(up_states)
85
+
86
+
87
+ def rotate_half(x):
88
+ """Rotates half the hidden dims of the input."""
89
+ x1 = x[..., : x.shape[-1] // 2]
90
+ x2 = x[..., x.shape[-1] // 2 :]
91
+ return torch.cat((-x2, x1), dim=-1)
92
+
93
+
94
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
95
+ """
96
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
97
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
98
+ """
99
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
100
+ if n_rep == 1:
101
+ return hidden_states
102
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
103
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
104
+
105
+
106
+ def eager_attention_forward(
107
+ module: nn.Module,
108
+ query: torch.Tensor,
109
+ key: torch.Tensor,
110
+ value: torch.Tensor,
111
+ attention_mask: Optional[torch.Tensor],
112
+ scaling: float,
113
+ dropout: float = 0.0,
114
+ **kwargs,
115
+ ):
116
+ key_states = repeat_kv(key, module.num_key_value_groups)
117
+ value_states = repeat_kv(value, module.num_key_value_groups)
118
+
119
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
120
+ if attention_mask is not None:
121
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
122
+ attn_weights = attn_weights + causal_mask
123
+
124
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
125
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
126
+ attn_output = torch.matmul(attn_weights, value_states)
127
+ attn_output = attn_output.transpose(1, 2).contiguous()
128
+
129
+ return attn_output, attn_weights
130
+
131
+
132
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
133
+ """Applies Rotary Position Embedding to the query and key tensors.
134
+
135
+ Args:
136
+ q (`torch.Tensor`): The query tensor.
137
+ k (`torch.Tensor`): The key tensor.
138
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
139
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
140
+ position_ids (`torch.Tensor`, *optional*):
141
+ Deprecated and unused.
142
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
143
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
144
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
145
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
146
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
147
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
148
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
149
+ Returns:
150
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
151
+ """
152
+ cos = cos.unsqueeze(unsqueeze_dim)
153
+ sin = sin.unsqueeze(unsqueeze_dim)
154
+
155
+ rotary_dim = cos.shape[-1]
156
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
157
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
158
+
159
+ q_embed = torch.cat([(q_rot * cos) + (rotate_half(q_rot) * sin), q_pass], dim=-1)
160
+ k_embed = torch.cat([(k_rot * cos) + (rotate_half(k_rot) * sin), k_pass], dim=-1)
161
+ return q_embed, k_embed
162
+
163
+
164
+ class Phi3Attention(nn.Module):
165
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
166
+
167
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
168
+ super().__init__()
169
+ self.config = config
170
+ self.layer_idx = layer_idx
171
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
172
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
173
+ self.num_key_value_heads = config.num_key_value_heads
174
+ self.scaling = self.head_dim**-0.5
175
+ self.attention_dropout = config.attention_dropout
176
+ self.is_causal = True
177
+
178
+ op_size = config.num_attention_heads * self.head_dim + 2 * (config.num_key_value_heads * self.head_dim)
179
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
180
+ self.qkv_proj = nn.Linear(config.hidden_size, op_size, bias=False)
181
+
182
+ def forward(
183
+ self,
184
+ hidden_states: torch.Tensor,
185
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
186
+ attention_mask: Optional[torch.Tensor],
187
+ past_key_value: Optional[Cache] = None,
188
+ cache_position: Optional[torch.LongTensor] = None,
189
+ **kwargs: Unpack[FlashAttentionKwargs],
190
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
191
+ input_shape = hidden_states.shape[:-1]
192
+ hidden_shape = (*input_shape, -1, self.head_dim)
193
+
194
+ qkv = self.qkv_proj(hidden_states)
195
+ query_pos = self.config.num_attention_heads * self.head_dim
196
+ query_states = qkv[..., :query_pos]
197
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
198
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
199
+
200
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
201
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
202
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
203
+
204
+ cos, sin = position_embeddings
205
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
206
+
207
+ if past_key_value is not None:
208
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
209
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
210
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
211
+
212
+ attention_interface: Callable = eager_attention_forward
213
+ if self.config._attn_implementation != "eager":
214
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
215
+ logger.warning_once(
216
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
217
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
218
+ )
219
+ else:
220
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
221
+
222
+ attn_output, attn_weights = attention_interface(
223
+ self,
224
+ query_states,
225
+ key_states,
226
+ value_states,
227
+ attention_mask,
228
+ dropout=0.0 if not self.training else self.attention_dropout,
229
+ scaling=self.scaling,
230
+ sliding_window=getattr(self.config, "sliding_window", None),
231
+ **kwargs,
232
+ )
233
+
234
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
235
+ attn_output = self.o_proj(attn_output)
236
+ return attn_output, attn_weights
237
+
238
+
239
+ @use_kernel_forward_from_hub("RMSNorm")
240
+ class Phi3RMSNorm(nn.Module):
241
+ def __init__(self, hidden_size, eps=1e-6):
242
+ """
243
+ Phi3RMSNorm is equivalent to T5LayerNorm
244
+ """
245
+ super().__init__()
246
+ self.weight = nn.Parameter(torch.ones(hidden_size))
247
+ self.variance_epsilon = eps
248
+
249
+ def forward(self, hidden_states):
250
+ input_dtype = hidden_states.dtype
251
+ hidden_states = hidden_states.to(torch.float32)
252
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
253
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
254
+ return self.weight * hidden_states.to(input_dtype)
255
+
256
+ def extra_repr(self):
257
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
258
+
259
+
260
+ class Phi3DecoderLayer(GradientCheckpointingLayer):
261
+ def __init__(self, config: Phi3Config, layer_idx: int):
262
+ super().__init__()
263
+ self.hidden_size = config.hidden_size
264
+ self.self_attn = Phi3Attention(config=config, layer_idx=layer_idx)
265
+ self.mlp = Phi3MLP(config)
266
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
267
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
268
+ self.config = config
269
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
270
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
271
+
272
+ def forward(
273
+ self,
274
+ hidden_states: torch.Tensor,
275
+ attention_mask: Optional[torch.Tensor] = None,
276
+ position_ids: Optional[torch.LongTensor] = None,
277
+ past_key_value: Optional[Cache] = None,
278
+ output_attentions: Optional[bool] = False,
279
+ use_cache: Optional[bool] = False,
280
+ cache_position: Optional[torch.LongTensor] = None,
281
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
282
+ **kwargs: Unpack[FlashAttentionKwargs],
283
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
284
+ """
285
+ Args:
286
+ hidden_states (`torch.FloatTensor`):
287
+ input to the layer of shape `(batch, seq_len, embed_dim)`
288
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
289
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
290
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
291
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
292
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
293
+ past_key_value (`Cache`, *optional*): cached past key and value projection states
294
+ output_attentions (`bool`, *optional*):
295
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
296
+ returned tensors for more detail.
297
+ use_cache (`bool`, *optional*):
298
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
299
+ (see `past_key_values`).
300
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
301
+ Indices depicting the position of the input sequence tokens in the sequence
302
+ kwargs (`dict`, *optional*):
303
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
304
+ into the model
305
+ """
306
+ residual = hidden_states
307
+
308
+ hidden_states = self.input_layernorm(hidden_states)
309
+
310
+ # Self Attention
311
+ hidden_states, self_attn_weights = self.self_attn(
312
+ hidden_states=hidden_states,
313
+ attention_mask=attention_mask,
314
+ position_ids=position_ids,
315
+ past_key_value=past_key_value,
316
+ output_attentions=output_attentions,
317
+ use_cache=use_cache,
318
+ cache_position=cache_position,
319
+ position_embeddings=position_embeddings,
320
+ **kwargs,
321
+ )
322
+ hidden_states = residual + self.resid_attn_dropout(hidden_states) # main diff with Llama
323
+
324
+ residual = hidden_states
325
+ hidden_states = self.post_attention_layernorm(hidden_states)
326
+ hidden_states = self.mlp(hidden_states)
327
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states) # main diff with Llama
328
+
329
+ outputs = (hidden_states,)
330
+ if output_attentions:
331
+ outputs += (self_attn_weights,)
332
+
333
+ return outputs
334
+
335
+
336
+ PHI3_START_DOCSTRING = r"""
337
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
338
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
339
+ etc.)
340
+
341
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
342
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
343
+ and behavior.
344
+
345
+ Parameters:
346
+ config ([`Phi3Config`]):
347
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
348
+ load the weights associated with the model, only the configuration. Check out the
349
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
350
+ """
351
+
352
+
353
+ @add_start_docstrings(
354
+ "The bare Phi3 Model outputting raw hidden-states without any specific head on top.",
355
+ PHI3_START_DOCSTRING,
356
+ )
357
+ class Phi3PreTrainedModel(PreTrainedModel):
358
+ config_class = Phi3Config
359
+ base_model_prefix = "model"
360
+ supports_gradient_checkpointing = True
361
+ _no_split_modules = ["Phi3DecoderLayer"]
362
+ _skip_keys_device_placement = ["past_key_values"]
363
+ _supports_flash_attn_2 = True
364
+ _supports_sdpa = True
365
+ _supports_flex_attn = True
366
+ _supports_cache_class = True
367
+ _supports_quantized_cache = True
368
+ _supports_static_cache = True
369
+ _supports_attention_backend = True
370
+ _version = "0.0.5"
371
+
372
+ def _init_weights(self, module):
373
+ std = self.config.initializer_range
374
+ if isinstance(module, nn.Linear):
375
+ module.weight.data.normal_(mean=0.0, std=std)
376
+ if module.bias is not None:
377
+ module.bias.data.zero_()
378
+ elif isinstance(module, nn.Embedding):
379
+ module.weight.data.normal_(mean=0.0, std=std)
380
+ if module.padding_idx is not None:
381
+ module.weight.data[module.padding_idx].zero_()
382
+ elif isinstance(module, Phi3RMSNorm):
383
+ module.weight.data.fill_(1.0)
384
+
385
+
386
+ class Phi3RotaryEmbedding(nn.Module):
387
+ def __init__(self, config: Phi3Config, device=None):
388
+ super().__init__()
389
+ # BC: "rope_type" was originally "type"
390
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
391
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
392
+ else:
393
+ self.rope_type = "default"
394
+ self.max_seq_len_cached = config.max_position_embeddings
395
+ self.original_max_seq_len = config.max_position_embeddings
396
+
397
+ self.config = config
398
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
399
+
400
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
401
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
402
+ self.original_inv_freq = self.inv_freq
403
+
404
+ @torch.no_grad()
405
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
406
+ def forward(self, x, position_ids):
407
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
408
+ position_ids_expanded = position_ids[:, None, :].float()
409
+
410
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
411
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
412
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
413
+ emb = torch.cat((freqs, freqs), dim=-1)
414
+ cos = emb.cos() * self.attention_scaling
415
+ sin = emb.sin() * self.attention_scaling
416
+
417
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
418
+
419
+
420
+ PHI3_INPUTS_DOCSTRING = r"""
421
+ Args:
422
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
423
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
424
+ it.
425
+
426
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
427
+ [`PreTrainedTokenizer.__call__`] for details.
428
+
429
+ [What are input IDs?](../glossary#input-ids)
430
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length) or `BlockMask`, *optional*):
431
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
432
+
433
+ - 1 for tokens that are **not masked**,
434
+ - 0 for tokens that are **masked**.
435
+
436
+ If the model is configured to use flex_attention, it will attempt to convert the mask Tensor into a BlockMask,
437
+ but you can also pass a `BlockMask` object directly here.
438
+
439
+ [What are attention masks?](../glossary#attention-mask)
440
+
441
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
442
+ [`PreTrainedTokenizer.__call__`] for details.
443
+
444
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
445
+ `past_key_values`).
446
+
447
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
448
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
449
+ information on the default strategy.
450
+
451
+ - 1 indicates the head is **not masked**,
452
+ - 0 indicates the head is **masked**.
453
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
454
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
455
+ config.n_positions - 1]`.
456
+
457
+ [What are position IDs?](../glossary#position-ids)
458
+ past_key_values (`Cache`, *optional*):
459
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
460
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
461
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
462
+
463
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
464
+
465
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
466
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
467
+ of shape `(batch_size, sequence_length)`.
468
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
469
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
470
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
471
+ model's internal embedding lookup matrix.
472
+ use_cache (`bool`, *optional*):
473
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
474
+ `past_key_values`).
475
+ output_attentions (`bool`, *optional*):
476
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
477
+ tensors for more detail.
478
+ output_hidden_states (`bool`, *optional*):
479
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
480
+ more detail.
481
+ return_dict (`bool`, *optional*):
482
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
483
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
484
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
485
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
486
+ the complete sequence length.
487
+ """
488
+
489
+
490
+ @add_start_docstrings(
491
+ "The bare Phi3 Model outputting raw hidden-states without any specific head on top.",
492
+ PHI3_START_DOCSTRING,
493
+ )
494
+ class Phi3Model(Phi3PreTrainedModel):
495
+ """
496
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
497
+
498
+ Args:
499
+ config: Phi3Config
500
+ """
501
+
502
+ def __init__(self, config: Phi3Config):
503
+ super().__init__(config)
504
+ self.padding_idx = config.pad_token_id
505
+ self.vocab_size = config.vocab_size
506
+
507
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
508
+ self.layers = nn.ModuleList(
509
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
510
+ )
511
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
512
+ self.rotary_emb = Phi3RotaryEmbedding(config=config)
513
+ self.gradient_checkpointing = False
514
+
515
+ # Initialize weights and apply final processing
516
+ self.post_init()
517
+
518
+ def get_input_embeddings(self):
519
+ return self.embed_tokens
520
+
521
+ def set_input_embeddings(self, value):
522
+ self.embed_tokens = value
523
+
524
+ @can_return_tuple
525
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
526
+ def forward(
527
+ self,
528
+ input_ids: Optional[torch.LongTensor] = None,
529
+ attention_mask: Optional[torch.Tensor] = None,
530
+ position_ids: Optional[torch.LongTensor] = None,
531
+ past_key_values: Optional[Cache] = None,
532
+ inputs_embeds: Optional[torch.FloatTensor] = None,
533
+ use_cache: Optional[bool] = None,
534
+ output_attentions: Optional[bool] = None,
535
+ output_hidden_states: Optional[bool] = None,
536
+ cache_position: Optional[torch.LongTensor] = None,
537
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
538
+ ) -> BaseModelOutputWithPast:
539
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
540
+ output_hidden_states = (
541
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
542
+ )
543
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
544
+
545
+ if (input_ids is None) ^ (inputs_embeds is not None):
546
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
547
+
548
+ if self.gradient_checkpointing and self.training and use_cache:
549
+ logger.warning_once(
550
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
551
+ )
552
+ use_cache = False
553
+
554
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
555
+ if not isinstance(past_key_values, (type(None), Cache)):
556
+ raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
557
+
558
+ if inputs_embeds is None:
559
+ inputs_embeds = self.embed_tokens(input_ids)
560
+
561
+ if use_cache and past_key_values is None:
562
+ past_key_values = DynamicCache()
563
+
564
+ if cache_position is None:
565
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
566
+ cache_position = torch.arange(
567
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
568
+ )
569
+
570
+ if position_ids is None:
571
+ position_ids = cache_position.unsqueeze(0)
572
+
573
+ causal_mask = self._update_causal_mask(
574
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
575
+ )
576
+
577
+ hidden_states = inputs_embeds
578
+
579
+ # create position embeddings to be shared across the decoder layers
580
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
581
+
582
+ # decoder layers
583
+ all_hidden_states = () if output_hidden_states else None
584
+ all_self_attns = () if output_attentions else None
585
+
586
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
587
+ if output_hidden_states:
588
+ all_hidden_states += (hidden_states,)
589
+
590
+ layer_outputs = decoder_layer(
591
+ hidden_states,
592
+ attention_mask=causal_mask,
593
+ position_ids=position_ids,
594
+ past_key_value=past_key_values,
595
+ output_attentions=output_attentions,
596
+ use_cache=use_cache,
597
+ cache_position=cache_position,
598
+ position_embeddings=position_embeddings,
599
+ **flash_attn_kwargs,
600
+ )
601
+
602
+ hidden_states = layer_outputs[0]
603
+
604
+ if output_attentions:
605
+ all_self_attns += (layer_outputs[1],)
606
+
607
+ hidden_states = self.norm(hidden_states)
608
+
609
+ # add hidden states from the last decoder layer
610
+ if output_hidden_states:
611
+ all_hidden_states += (hidden_states,)
612
+
613
+ return BaseModelOutputWithPast(
614
+ last_hidden_state=hidden_states,
615
+ past_key_values=past_key_values if use_cache else None,
616
+ hidden_states=all_hidden_states,
617
+ attentions=all_self_attns,
618
+ )
619
+
620
+ def _update_causal_mask(
621
+ self,
622
+ attention_mask: Union[torch.Tensor, "BlockMask"],
623
+ input_tensor: torch.Tensor,
624
+ cache_position: torch.Tensor,
625
+ past_key_values: Cache,
626
+ output_attentions: bool = False,
627
+ ):
628
+ if self.config._attn_implementation == "flash_attention_2":
629
+ if attention_mask is not None and past_key_values is not None:
630
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
631
+ if is_padding_right:
632
+ raise ValueError(
633
+ "You are attempting to perform batched generation with padding_side='right'"
634
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
635
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
636
+ )
637
+ if attention_mask is not None and 0.0 in attention_mask:
638
+ return attention_mask
639
+ return None
640
+ if self.config._attn_implementation == "flex_attention":
641
+ if isinstance(attention_mask, torch.Tensor):
642
+ attention_mask = make_flex_block_causal_mask(attention_mask)
643
+ return attention_mask
644
+
645
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
646
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
647
+ # to infer the attention mask.
648
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
649
+ using_static_cache = isinstance(past_key_values, StaticCache)
650
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
651
+
652
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
653
+ if (
654
+ self.config._attn_implementation == "sdpa"
655
+ and not (using_static_cache or using_sliding_window_cache)
656
+ and not output_attentions
657
+ ):
658
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
659
+ attention_mask,
660
+ inputs_embeds=input_tensor,
661
+ past_key_values_length=past_seen_tokens,
662
+ sliding_window=self.config.sliding_window,
663
+ is_training=self.training,
664
+ ):
665
+ return None
666
+
667
+ dtype, device = input_tensor.dtype, input_tensor.device
668
+ min_dtype = torch.finfo(dtype).min
669
+ sequence_length = input_tensor.shape[1]
670
+ # SlidingWindowCache or StaticCache
671
+ if using_sliding_window_cache or using_static_cache:
672
+ target_length = past_key_values.get_max_cache_shape()
673
+ # DynamicCache or no cache
674
+ else:
675
+ target_length = (
676
+ attention_mask.shape[-1]
677
+ if isinstance(attention_mask, torch.Tensor)
678
+ else past_seen_tokens + sequence_length + 1
679
+ )
680
+
681
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
682
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
683
+ attention_mask,
684
+ sequence_length=sequence_length,
685
+ target_length=target_length,
686
+ dtype=dtype,
687
+ device=device,
688
+ cache_position=cache_position,
689
+ batch_size=input_tensor.shape[0],
690
+ config=self.config,
691
+ past_key_values=past_key_values,
692
+ )
693
+
694
+ if (
695
+ self.config._attn_implementation == "sdpa"
696
+ and attention_mask is not None
697
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
698
+ and not output_attentions
699
+ ):
700
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
701
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
702
+ # Details: https://github.com/pytorch/pytorch/issues/110213
703
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
704
+
705
+ return causal_mask
706
+
707
+ @staticmethod
708
+ def _prepare_4d_causal_attention_mask_with_cache_position(
709
+ attention_mask: torch.Tensor,
710
+ sequence_length: int,
711
+ target_length: int,
712
+ dtype: torch.dtype,
713
+ device: torch.device,
714
+ cache_position: torch.Tensor,
715
+ batch_size: int,
716
+ config: Phi3Config,
717
+ past_key_values: Cache,
718
+ ):
719
+ """
720
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
721
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
722
+
723
+ Args:
724
+ attention_mask (`torch.Tensor`):
725
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
726
+ sequence_length (`int`):
727
+ The sequence length being processed.
728
+ target_length (`int`):
729
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
730
+ dtype (`torch.dtype`):
731
+ The dtype to use for the 4D attention mask.
732
+ device (`torch.device`):
733
+ The device to place the 4D attention mask on.
734
+ cache_position (`torch.Tensor`):
735
+ Indices depicting the position of the input sequence tokens in the sequence.
736
+ batch_size (`torch.Tensor`):
737
+ Batch size.
738
+ config (`Phi3Config`):
739
+ The model's configuration class
740
+ past_key_values (`Cache`):
741
+ The cache class that is being used currently to generate
742
+ """
743
+ if attention_mask is not None and attention_mask.dim() == 4:
744
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
745
+ causal_mask = attention_mask
746
+ else:
747
+ min_dtype = torch.finfo(dtype).min
748
+ causal_mask = torch.full(
749
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
750
+ )
751
+ diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
752
+ if config.get_text_config().sliding_window is not None:
753
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
754
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
755
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
756
+ sliding_attend_mask = torch.arange(target_length, device=device) <= (
757
+ cache_position.reshape(-1, 1) - config.get_text_config().sliding_window
758
+ )
759
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
760
+ causal_mask *= diagonal_attend_mask
761
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
762
+ if attention_mask is not None:
763
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
764
+ if attention_mask.shape[-1] > target_length:
765
+ attention_mask = attention_mask[:, :target_length]
766
+ mask_length = attention_mask.shape[-1]
767
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
768
+ causal_mask.device
769
+ )
770
+ padding_mask = padding_mask == 0
771
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
772
+ padding_mask, min_dtype
773
+ )
774
+ return causal_mask
775
+
776
+
777
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
778
+
779
+
780
+ class Phi3ForCausalLM(Phi3PreTrainedModel, GenerationMixin):
781
+ _tied_weights_keys = ["lm_head.weight"]
782
+ _tp_plan = {"lm_head": "colwise_rep"}
783
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
784
+
785
+ def __init__(self, config):
786
+ super().__init__(config)
787
+ self.model = Phi3Model(config)
788
+ self.vocab_size = config.vocab_size
789
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
790
+
791
+ # Initialize weights and apply final processing
792
+ self.post_init()
793
+
794
+ def get_input_embeddings(self):
795
+ return self.model.embed_tokens
796
+
797
+ def set_input_embeddings(self, value):
798
+ self.model.embed_tokens = value
799
+
800
+ def get_output_embeddings(self):
801
+ return self.lm_head
802
+
803
+ def set_output_embeddings(self, new_embeddings):
804
+ self.lm_head = new_embeddings
805
+
806
+ def set_decoder(self, decoder):
807
+ self.model = decoder
808
+
809
+ def get_decoder(self):
810
+ return self.model
811
+
812
+ @can_return_tuple
813
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
814
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
815
+ def forward(
816
+ self,
817
+ input_ids: Optional[torch.LongTensor] = None,
818
+ attention_mask: Optional[torch.Tensor] = None,
819
+ position_ids: Optional[torch.LongTensor] = None,
820
+ past_key_values: Optional[Cache] = None,
821
+ inputs_embeds: Optional[torch.FloatTensor] = None,
822
+ labels: Optional[torch.LongTensor] = None,
823
+ use_cache: Optional[bool] = None,
824
+ output_attentions: Optional[bool] = None,
825
+ output_hidden_states: Optional[bool] = None,
826
+ cache_position: Optional[torch.LongTensor] = None,
827
+ logits_to_keep: Union[int, torch.Tensor] = 0,
828
+ **kwargs: Unpack[KwargsForCausalLM],
829
+ ) -> CausalLMOutputWithPast:
830
+ r"""
831
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
832
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
833
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
834
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
835
+
836
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
837
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
838
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
839
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
840
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
841
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
842
+
843
+ Returns:
844
+
845
+ Example:
846
+
847
+ ```python
848
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
849
+
850
+ >>> model = Phi3ForCausalLM.from_pretrained("meta-phi3/Phi3-2-7b-hf")
851
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-phi3/Phi3-2-7b-hf")
852
+
853
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
854
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
855
+
856
+ >>> # Generate
857
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
858
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
859
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
860
+ ```"""
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
+
866
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
867
+ outputs: BaseModelOutputWithPast = self.model(
868
+ input_ids=input_ids,
869
+ attention_mask=attention_mask,
870
+ position_ids=position_ids,
871
+ past_key_values=past_key_values,
872
+ inputs_embeds=inputs_embeds,
873
+ use_cache=use_cache,
874
+ output_attentions=output_attentions,
875
+ output_hidden_states=output_hidden_states,
876
+ cache_position=cache_position,
877
+ **kwargs,
878
+ )
879
+
880
+ hidden_states = outputs.last_hidden_state
881
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
882
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
883
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
884
+
885
+ loss = None
886
+ if labels is not None:
887
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
888
+
889
+ return CausalLMOutputWithPast(
890
+ loss=loss,
891
+ logits=logits,
892
+ past_key_values=outputs.past_key_values,
893
+ hidden_states=outputs.hidden_states,
894
+ attentions=outputs.attentions,
895
+ )
896
+
897
+ def prepare_inputs_for_generation(
898
+ self,
899
+ input_ids,
900
+ past_key_values=None,
901
+ attention_mask=None,
902
+ inputs_embeds=None,
903
+ cache_position=None,
904
+ position_ids=None,
905
+ use_cache=True,
906
+ logits_to_keep=None,
907
+ **kwargs,
908
+ ):
909
+ # Overwritten -- this model may need to switch between short and long rope, invalidating the cache in the
910
+ # process
911
+
912
+ # When the first time input length reached long and short factor switching point, enforce re-compute cache
913
+ # It will cause downside of slower at this single token position, however, better than current failure.
914
+ if (
915
+ past_key_values
916
+ and self.config.rope_scaling
917
+ and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1
918
+ ):
919
+ past_length = cache_position[0]
920
+ if past_length <= self.config.original_max_position_embeddings:
921
+ past_key_values = None
922
+
923
+ model_inputs = super().prepare_inputs_for_generation(
924
+ input_ids=input_ids,
925
+ past_key_values=past_key_values,
926
+ attention_mask=attention_mask,
927
+ inputs_embeds=inputs_embeds,
928
+ cache_position=cache_position,
929
+ position_ids=position_ids,
930
+ use_cache=use_cache,
931
+ logits_to_keep=logits_to_keep,
932
+ **kwargs,
933
+ )
934
+ return model_inputs
935
+
936
+
937
+ @add_start_docstrings(
938
+ """
939
+ The Phi3 Model transformer with a sequence classification head on top (linear layer).
940
+
941
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
942
+ (e.g. GPT-2) do.
943
+
944
+ Since it does classification on the last token, it requires to know the position of the last token. If a
945
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
946
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
947
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
948
+ each row of the batch).
949
+ """,
950
+ PHI3_START_DOCSTRING,
951
+ )
952
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
953
+ def __init__(self, config):
954
+ super().__init__(config)
955
+ self.num_labels = config.num_labels
956
+ self.model = Phi3Model(config)
957
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
958
+
959
+ # Initialize weights and apply final processing
960
+ self.post_init()
961
+
962
+ def get_input_embeddings(self):
963
+ return self.model.embed_tokens
964
+
965
+ def set_input_embeddings(self, value):
966
+ self.model.embed_tokens = value
967
+
968
+ @can_return_tuple
969
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
970
+ def forward(
971
+ self,
972
+ input_ids: Optional[torch.LongTensor] = None,
973
+ attention_mask: Optional[torch.Tensor] = None,
974
+ position_ids: Optional[torch.LongTensor] = None,
975
+ past_key_values: Optional[Cache] = None,
976
+ inputs_embeds: Optional[torch.FloatTensor] = None,
977
+ labels: Optional[torch.LongTensor] = None,
978
+ use_cache: Optional[bool] = None,
979
+ output_attentions: Optional[bool] = None,
980
+ output_hidden_states: Optional[bool] = None,
981
+ ) -> SequenceClassifierOutputWithPast:
982
+ r"""
983
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
984
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
985
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
986
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
987
+ """
988
+
989
+ transformer_outputs: BaseModelOutputWithPast = self.model(
990
+ input_ids,
991
+ attention_mask=attention_mask,
992
+ position_ids=position_ids,
993
+ past_key_values=past_key_values,
994
+ inputs_embeds=inputs_embeds,
995
+ use_cache=use_cache,
996
+ output_attentions=output_attentions,
997
+ output_hidden_states=output_hidden_states,
998
+ )
999
+ hidden_states = transformer_outputs.last_hidden_state
1000
+ logits = self.score(hidden_states)
1001
+
1002
+ if input_ids is not None:
1003
+ batch_size = input_ids.shape[0]
1004
+ else:
1005
+ batch_size = inputs_embeds.shape[0]
1006
+
1007
+ if self.config.pad_token_id is None and batch_size != 1:
1008
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1009
+ if self.config.pad_token_id is None:
1010
+ last_non_pad_token = -1
1011
+ elif input_ids is not None:
1012
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
1013
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
1014
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
1015
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
1016
+ else:
1017
+ last_non_pad_token = -1
1018
+ logger.warning_once(
1019
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1020
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1021
+ )
1022
+
1023
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
1024
+
1025
+ loss = None
1026
+ if labels is not None:
1027
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
1028
+
1029
+ return SequenceClassifierOutputWithPast(
1030
+ loss=loss,
1031
+ logits=pooled_logits,
1032
+ past_key_values=transformer_outputs.past_key_values,
1033
+ hidden_states=transformer_outputs.hidden_states,
1034
+ attentions=transformer_outputs.attentions,
1035
+ )
1036
+
1037
+
1038
+ @add_start_docstrings(
1039
+ """
1040
+ The Phi3 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1041
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1042
+ """,
1043
+ PHI3_START_DOCSTRING,
1044
+ )
1045
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1046
+ def __init__(self, config):
1047
+ super().__init__(config)
1048
+ self.num_labels = config.num_labels
1049
+ self.model = Phi3Model(config)
1050
+ if getattr(config, "classifier_dropout", None) is not None:
1051
+ classifier_dropout = config.classifier_dropout
1052
+ elif getattr(config, "hidden_dropout", None) is not None:
1053
+ classifier_dropout = config.hidden_dropout
1054
+ else:
1055
+ classifier_dropout = 0.1
1056
+ self.dropout = nn.Dropout(classifier_dropout)
1057
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1058
+
1059
+ # Initialize weights and apply final processing
1060
+ self.post_init()
1061
+
1062
+ def get_input_embeddings(self):
1063
+ return self.model.embed_tokens
1064
+
1065
+ def set_input_embeddings(self, value):
1066
+ self.model.embed_tokens = value
1067
+
1068
+ @can_return_tuple
1069
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1070
+ @add_code_sample_docstrings(
1071
+ checkpoint=_CHECKPOINT_FOR_DOC,
1072
+ output_type=TokenClassifierOutput,
1073
+ config_class=_CONFIG_FOR_DOC,
1074
+ )
1075
+ def forward(
1076
+ self,
1077
+ input_ids: Optional[torch.LongTensor] = None,
1078
+ attention_mask: Optional[torch.Tensor] = None,
1079
+ position_ids: Optional[torch.LongTensor] = None,
1080
+ past_key_values: Optional[Cache] = None,
1081
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1082
+ labels: Optional[torch.LongTensor] = None,
1083
+ use_cache: Optional[bool] = None,
1084
+ output_attentions: Optional[bool] = None,
1085
+ output_hidden_states: Optional[bool] = None,
1086
+ ) -> TokenClassifierOutput:
1087
+ r"""
1088
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1089
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1090
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1091
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1092
+ """
1093
+
1094
+ outputs: BaseModelOutputWithPast = self.model(
1095
+ input_ids,
1096
+ attention_mask=attention_mask,
1097
+ position_ids=position_ids,
1098
+ past_key_values=past_key_values,
1099
+ inputs_embeds=inputs_embeds,
1100
+ use_cache=use_cache,
1101
+ output_attentions=output_attentions,
1102
+ output_hidden_states=output_hidden_states,
1103
+ )
1104
+ sequence_output = outputs.last_hidden_state
1105
+ sequence_output = self.dropout(sequence_output)
1106
+ logits = self.score(sequence_output)
1107
+
1108
+ loss = None
1109
+ if labels is not None:
1110
+ loss = self.loss_function(logits, labels, self.config)
1111
+
1112
+ return TokenClassifierOutput(
1113
+ loss=loss,
1114
+ logits=logits,
1115
+ hidden_states=outputs.hidden_states,
1116
+ attentions=outputs.attentions,
1117
+ )
1118
+
1119
+
1120
+ __all__ = [
1121
+ "Phi3PreTrainedModel",
1122
+ "Phi3Model",
1123
+ "Phi3ForCausalLM",
1124
+ "Phi3ForSequenceClassification",
1125
+ "Phi3ForTokenClassification",
1126
+ ]
docs/transformers/build/lib/transformers/models/phi4_multimodal/image_processing_phi4_multimodal_fast.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Microsoft and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Processor class for Phi4Multimodal
17
+ """
18
+
19
+ import math
20
+ from typing import List, Optional, Union
21
+
22
+ import torch
23
+ from torchvision.transforms import functional as F
24
+
25
+ from ...image_processing_utils_fast import (
26
+ BaseImageProcessorFast,
27
+ BatchFeature,
28
+ DefaultFastImageProcessorKwargs,
29
+ Unpack,
30
+ convert_to_rgb,
31
+ )
32
+ from ...image_utils import ImageInput, make_flat_list_of_images, valid_images
33
+ from ...utils import TensorType, logging
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ class Phi4MultimodalFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
40
+ image_size: Optional[int]
41
+ patch_size: Optional[int]
42
+ dynamic_hd: Optional[int]
43
+
44
+
45
+ class Phi4MultimodalImageProcessorFast(BaseImageProcessorFast):
46
+ r"""
47
+ Constructs a Phi4Multimodal image processor.
48
+ """
49
+
50
+ image_size = 448
51
+ patch_size = 14
52
+ dynamic_hd = 36
53
+ image_mean = [0.5, 0.5, 0.5]
54
+ image_std = [0.5, 0.5, 0.5]
55
+ valid_init_kwargs = Phi4MultimodalFastImageProcessorKwargs
56
+ model_input_names = ["image_pixel_values", "image_sizes", "image_attention_mask"]
57
+
58
+ def __init__(self, **kwargs: Unpack[Phi4MultimodalFastImageProcessorKwargs]):
59
+ super().__init__(**kwargs)
60
+
61
+ def find_closest_aspect_ratio(self, aspect_ratio, target_ratios, width, height):
62
+ best_ratio_diff = float("inf")
63
+ best_ratio = (1, 1)
64
+ area = width * height
65
+ for ratio in target_ratios:
66
+ target_aspect_ratio = ratio[0] / ratio[1]
67
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
68
+ if ratio_diff < best_ratio_diff:
69
+ best_ratio_diff = ratio_diff
70
+ best_ratio = ratio
71
+ elif ratio_diff == best_ratio_diff:
72
+ if area > 0.5 * self.image_size * self.image_size * ratio[0] * ratio[1]:
73
+ best_ratio = ratio
74
+ return best_ratio
75
+
76
+ def dynamic_preprocess(self, image, max_num=36, min_num=1):
77
+ image_size = self.image_size
78
+ patch_size = self.patch_size
79
+ mask_size = image_size // patch_size
80
+ orig_width, orig_height = image.size
81
+
82
+ w_crop_num = math.ceil(orig_width / float(image_size))
83
+ h_crop_num = math.ceil(orig_height / float(image_size))
84
+ if w_crop_num * h_crop_num > max_num:
85
+ aspect_ratio = orig_width / orig_height
86
+
87
+ # calculate the existing image aspect ratio
88
+ target_ratios = {
89
+ (i, j)
90
+ for n in range(min_num, max_num + 1)
91
+ for i in range(1, n + 1)
92
+ for j in range(1, n + 1)
93
+ if i * j <= max_num and i * j >= min_num
94
+ }
95
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
96
+
97
+ # find the closest aspect ratio to the target
98
+ target_aspect_ratio = self.find_closest_aspect_ratio(aspect_ratio, target_ratios, orig_width, orig_height)
99
+
100
+ # calculate the target width and height
101
+ target_width = image_size * target_aspect_ratio[0]
102
+ target_height = image_size * target_aspect_ratio[1]
103
+ else:
104
+ target_width = image_size * w_crop_num
105
+ target_height = image_size * h_crop_num
106
+ target_aspect_ratio = (w_crop_num, h_crop_num)
107
+
108
+ # Calculate the ratio
109
+ ratio_width = target_width / orig_width
110
+ ratio_height = target_height / orig_height
111
+ if ratio_width < ratio_height:
112
+ new_size = (target_width, int(orig_height * ratio_width))
113
+ padding_width = 0
114
+ padding_height = target_height - int(orig_height * ratio_width)
115
+ else:
116
+ new_size = (int(orig_width * ratio_height), target_height)
117
+ padding_width = target_width - int(orig_width * ratio_height)
118
+ padding_height = 0
119
+
120
+ attention_mask = torch.ones((int(mask_size * target_aspect_ratio[1]), int(mask_size * target_aspect_ratio[0])))
121
+ if padding_width >= patch_size:
122
+ attention_mask[:, -math.floor(padding_width / patch_size) :] = 0
123
+ if padding_height >= patch_size:
124
+ attention_mask[-math.floor(padding_height / patch_size) :, :] = 0
125
+
126
+ if min(new_size[1], target_height) < 10 or min(new_size[0], target_width) < 10:
127
+ raise ValueError(f"the aspect ratio is very extreme {new_size}")
128
+
129
+ image = F.resize(image, [new_size[1], new_size[0]])
130
+ resized_img = F.pad(image, [0, 0, padding_width, padding_height], fill=[255, 255, 255])
131
+
132
+ return resized_img, attention_mask
133
+
134
+ def pad_to_max_num_crops(self, images, max_crops=5):
135
+ """
136
+ images: B x 3 x H x W, B<=max_crops
137
+ """
138
+ B, _, H, W = images.shape
139
+ if B < max_crops:
140
+ pad = torch.zeros(max_crops - B, 3, H, W, dtype=images.dtype, device=images.device)
141
+ images = torch.cat([images, pad], dim=0)
142
+ return images
143
+
144
+ def pad_mask_to_max_num_crops(self, masks, max_crops=5):
145
+ B, H, W = masks.shape
146
+ if B < max_crops:
147
+ pad = torch.ones(max_crops - B, H, W, dtype=masks.dtype, device=masks.device)
148
+ masks = torch.cat([masks, pad], dim=0)
149
+ return masks
150
+
151
+ def preprocess(
152
+ self,
153
+ images: ImageInput,
154
+ image_mean: Optional[Union[float, List[float]]] = None,
155
+ image_std: Optional[Union[float, List[float]]] = None,
156
+ return_tensors: Optional[Union[str, TensorType]] = None,
157
+ ):
158
+ """
159
+ Args:
160
+ images (`ImageInput`):
161
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
162
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
163
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
164
+ Mean to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image.
165
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
166
+ Standard deviation to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image.
167
+ return_tensors (`str` or `TensorType`, *optional*):
168
+ The type of tensors to return. Can be one of:
169
+ - Unset: Return a list of `np.ndarray`.
170
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
171
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
172
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
173
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
174
+ """
175
+ image_mean = image_mean if image_mean is not None else self.image_mean
176
+ image_std = image_std if image_std is not None else self.image_std
177
+
178
+ images = make_flat_list_of_images(images)
179
+ if not valid_images(images):
180
+ raise ValueError(
181
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
182
+ "torch.Tensor, tf.Tensor or jax.ndarray."
183
+ )
184
+ images = [convert_to_rgb(image) for image in images]
185
+
186
+ image_size = self.image_size
187
+ patch_size = self.patch_size
188
+ mask_size = image_size // patch_size
189
+ imgs_and_masks = [self.dynamic_preprocess(image, max_num=self.dynamic_hd) for image in images]
190
+ images, image_attention_masks = [x[0] for x in imgs_and_masks], [x[1] for x in imgs_and_masks]
191
+
192
+ images = [F.to_tensor(image) for image in images]
193
+ hd_images = [F.normalize(image, image_mean, image_std) for image in images]
194
+ global_image = [
195
+ torch.nn.functional.interpolate(
196
+ image.unsqueeze(0).float(),
197
+ size=(image_size, image_size),
198
+ mode="bicubic",
199
+ ).to(image.dtype)
200
+ for image in hd_images
201
+ ]
202
+
203
+ shapes = [[image.size(1), image.size(2)] for image in hd_images]
204
+ mask_shapes = [[mask.size(0), mask.size(1)] for mask in image_attention_masks]
205
+ global_attention_mask = [torch.ones((1, mask_size, mask_size)) for _ in hd_images]
206
+
207
+ hd_images_reshape = []
208
+ for im, (h, w) in zip(hd_images, shapes):
209
+ im = im.reshape(1, 3, h // image_size, image_size, w // image_size, image_size)
210
+ im = im.permute(0, 2, 4, 1, 3, 5)
211
+ im = im.reshape(-1, 3, image_size, image_size)
212
+ hd_images_reshape.append(im.contiguous())
213
+
214
+ attention_masks_reshape = []
215
+ for mask, (h, w) in zip(image_attention_masks, mask_shapes):
216
+ mask = mask.reshape(h // mask_size, mask_size, w // mask_size, mask_size)
217
+ mask = mask.transpose(1, 2)
218
+ mask = mask.reshape(-1, mask_size, mask_size)
219
+ attention_masks_reshape.append(mask.contiguous())
220
+
221
+ downsample_attention_masks = []
222
+ for mask, (h, w) in zip(attention_masks_reshape, mask_shapes):
223
+ mask = mask[:, 0::2, 0::2]
224
+ mask = mask.reshape(
225
+ h // mask_size, w // mask_size, mask_size // 2 + mask_size % 2, mask_size // 2 + mask_size % 2
226
+ )
227
+ mask = mask.transpose(1, 2)
228
+ mask = mask.reshape(mask.size(0) * mask.size(1), mask.size(2) * mask.size(3))
229
+ downsample_attention_masks.append(mask)
230
+
231
+ num_img_tokens = [
232
+ 256 + 1 + int(mask.sum().item()) + int(mask[:, 0].sum().item()) + 16 for mask in downsample_attention_masks
233
+ ]
234
+
235
+ hd_images_reshape = [
236
+ torch.cat([_global_image] + [_im], dim=0) for _global_image, _im in zip(global_image, hd_images_reshape)
237
+ ]
238
+ hd_masks_reshape = [
239
+ torch.cat([_global_mask] + [_mask], dim=0)
240
+ for _global_mask, _mask in zip(global_attention_mask, attention_masks_reshape)
241
+ ]
242
+ max_crops = max([img.size(0) for img in hd_images_reshape])
243
+ image_transformed = [self.pad_to_max_num_crops(im, max_crops) for im in hd_images_reshape]
244
+ image_transformed = torch.stack(image_transformed, dim=0)
245
+ mask_transformed = [self.pad_mask_to_max_num_crops(mask, max_crops) for mask in hd_masks_reshape]
246
+ mask_transformed = torch.stack(mask_transformed, dim=0)
247
+
248
+ returned_input_image_embeds = image_transformed
249
+ returned_image_sizes = torch.tensor(shapes, dtype=torch.long)
250
+ returned_image_attention_mask = mask_transformed
251
+ returned_num_img_tokens = num_img_tokens
252
+
253
+ data = {
254
+ "image_pixel_values": returned_input_image_embeds,
255
+ "image_sizes": returned_image_sizes,
256
+ "image_attention_mask": returned_image_attention_mask,
257
+ "num_img_tokens": returned_num_img_tokens,
258
+ }
259
+
260
+ return BatchFeature(data=data, tensor_type=return_tensors)
261
+
262
+
263
+ __all__ = ["Phi4MultimodalImageProcessorFast"]
docs/transformers/build/lib/transformers/models/phi4_multimodal/modeling_phi4_multimodal.py ADDED
The diff for this file is too large to render. See raw diff
 
docs/transformers/build/lib/transformers/models/phi4_multimodal/modular_phi4_multimodal.py ADDED
@@ -0,0 +1,1850 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Microsoft and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ from typing import Callable, List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn.functional as F
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+
24
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
25
+
26
+ from ...activations import ACT2FN
27
+ from ...cache_utils import DynamicCache
28
+ from ...configuration_utils import PretrainedConfig
29
+ from ...modeling_outputs import (
30
+ BaseModelOutput,
31
+ BaseModelOutputWithPast,
32
+ BaseModelOutputWithPooling,
33
+ CausalLMOutputWithPast,
34
+ )
35
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
36
+ from ...utils import (
37
+ add_start_docstrings_to_model_forward,
38
+ can_return_tuple,
39
+ logging,
40
+ replace_return_docstrings,
41
+ )
42
+ from ..phi3.configuration_phi3 import Phi3Config
43
+ from ..phi3.modeling_phi3 import (
44
+ Phi3DecoderLayer,
45
+ Phi3ForCausalLM,
46
+ Phi3Model,
47
+ Phi3PreTrainedModel,
48
+ Phi3RMSNorm,
49
+ Phi3RotaryEmbedding,
50
+ )
51
+ from ..siglip.configuration_siglip import SiglipVisionConfig
52
+ from ..siglip.modeling_siglip import (
53
+ SiglipEncoder,
54
+ SiglipEncoderLayer,
55
+ SiglipMLP,
56
+ SiglipMultiheadAttentionPoolingHead,
57
+ SiglipPreTrainedModel,
58
+ SiglipVisionEmbeddings,
59
+ default_flax_embed_init,
60
+ lecun_normal_,
61
+ )
62
+
63
+
64
+ logger = logging.get_logger(__name__)
65
+
66
+
67
+ class Phi4MultimodalVisionConfig(SiglipVisionConfig):
68
+ r"""
69
+ This is the configuration class to store the configuration of a [`Phi4MultimodalVisionModel`]. It is used to instantiate a
70
+ Phi4Multimodal vision encoder according to the specified arguments, defining the model architecture. Instantiating a
71
+ configuration with the defaults will yield a similar configuration to that of the vision encoder of
72
+ [microsoft/Phi-4-multimodal-instruct](https://huggingface.co/microsoft/Phi-4-multimodal-instruct) architecture.
73
+
74
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
75
+ documentation from [`PretrainedConfig`] for more information.
76
+
77
+ Args:
78
+ hidden_size (`int`, *optional*, defaults to 1152):
79
+ Dimensionality of the encoder layers and the pooler layer.
80
+ intermediate_size (`int`, *optional*, defaults to 4304):
81
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
82
+ num_hidden_layers (`int`, *optional*, defaults to 27):
83
+ Number of hidden layers in the Transformer encoder.
84
+ num_attention_heads (`int`, *optional*, defaults to 16):
85
+ Number of attention heads for each attention layer in the Transformer encoder.
86
+ num_channels (`int`, *optional*, defaults to 3):
87
+ Number of channels in the input images.
88
+ image_size (`int`, *optional*, defaults to 448):
89
+ The size (resolution) of each image.
90
+ patch_size (`int`, *optional*, defaults to 14):
91
+ The size (resolution) of each patch.
92
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
93
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
94
+ `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
95
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
96
+ The epsilon used by the layer normalization layers.
97
+ attention_dropout (`float`, *optional*, defaults to 0.0):
98
+ The dropout ratio for the attention probabilities.
99
+ crop_size (`int`, *optional*, defaults to 448):
100
+ Crop size for the input images.
101
+ image_token_id (`int`, *optional*, defaults to 200010):
102
+ The image token id.
103
+ feature_layer (`int`, *optional*, defaults to -2):
104
+ The index of the layer of the encoder from which to extract image features.
105
+
106
+ Example:
107
+
108
+ ```python
109
+ >>> from transformers import Phi4MultimodalVisionConfig
110
+
111
+ >>> # Initializing a Phi4MultimodalVisionConfig with microsoft/Phi-4-multimodal-instruct style configuration
112
+ >>> configuration = Phi4MultimodalVisionConfig()
113
+ ```"""
114
+
115
+ model_type = "phi4_multimodal_vision"
116
+
117
+ def __init__(
118
+ self,
119
+ hidden_size=1152,
120
+ intermediate_size=4304,
121
+ num_hidden_layers=27,
122
+ num_attention_heads=16,
123
+ num_channels=3,
124
+ image_size=448,
125
+ patch_size=14,
126
+ hidden_act="gelu_pytorch_tanh",
127
+ layer_norm_eps=1e-6,
128
+ attention_dropout=0.0,
129
+ crop_size: int = 448,
130
+ image_token_id: int = 200010,
131
+ feature_layer: int = -2,
132
+ **kwargs,
133
+ ):
134
+ super().__init__(
135
+ hidden_size=hidden_size,
136
+ intermediate_size=intermediate_size,
137
+ num_hidden_layers=num_hidden_layers,
138
+ num_attention_heads=num_attention_heads,
139
+ num_channels=num_channels,
140
+ image_size=image_size,
141
+ patch_size=patch_size,
142
+ hidden_act=hidden_act,
143
+ layer_norm_eps=layer_norm_eps,
144
+ attention_dropout=attention_dropout,
145
+ **kwargs,
146
+ )
147
+ self.crop_size = crop_size
148
+ self.image_token_id = image_token_id
149
+ self.feature_layer = feature_layer
150
+
151
+
152
+ class Phi4MultimodalAudioConfig(PretrainedConfig):
153
+ r"""
154
+ This is the configuration class to store the configuration of a [`Phi4MultimodalAudioModel`]. It is used to instantiate a
155
+ Phi4Multimodal audio encoder according to the specified arguments, defining the model architecture. Instantiating a
156
+ configuration with the defaults will yield a similar configuration to that of the audio encoder of
157
+ [microsoft/Phi-4-multimodal-instruct](https://huggingface.co/microsoft/Phi-4-multimodal-instruct) architecture.
158
+
159
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
160
+ documentation from [`PretrainedConfig`] for more information.
161
+
162
+ Args:
163
+ hidden_size (`int`, *optional*, defaults to 1024):
164
+ Dimensionality of the encoder layers.
165
+ intermediate_size (`int`, *optional*, defaults to 1536):
166
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
167
+ num_blocks (`int`, *optional*, defaults to 24):
168
+ Number of hidden layers in the Transformer encoder.
169
+ num_attention_heads (`int`, *optional*, defaults to 16):
170
+ Number of attention heads for each attention layer in the Transformer encoder.
171
+ activation (`str`, *optional*, defaults to `"swish"`):
172
+ The non-linear activation function in the MLPs.
173
+ chunk_size (`int`, *optional*, defaults to -1):
174
+ The chunk size to create the masks.
175
+ left_chunk (`int`, *optional*, defaults to 18):
176
+ The left chunk to create the masks.
177
+ dropout_rate (`float`, *optional*, defaults to 0.0):
178
+ The dropout ratio.
179
+ ext_pw_out_channel (`int`, *optional*, defaults to 1024):
180
+ Number of out channels in the point-wise conv modules.
181
+ depthwise_seperable_out_channel (`int`, *optional*, defaults to 1024):
182
+ Number of out channels in the depth-wise separable conv modules.
183
+ depthwise_multiplier (`int`, *optional*, defaults to 1):
184
+ Input size multiplier for the depth-wise separable conv modules.
185
+ kernel_size (`int`, *optional*, defaults to 3):
186
+ Kernel size for the depth-wise separable conv modules.
187
+ conv_activation (`str`, *optional*, defaults to `"swish"`):
188
+ The non-linear activation function in the conv modules.
189
+ input_size (`int`, *optional*, defaults to 80):
190
+ Input size for the audio model.
191
+ conv_glu_type (`str`, *optional*, defaults to `"swish"`):
192
+ The non-linear activation function in the point-wise conv modules.
193
+ time_reduction (`int`, *optional*, defaults to 8):
194
+ Time reduction (subsampling factor).
195
+ bias_max_distance (`int`, *optional*, defaults to 1000):
196
+ Max distance for the relative attention bias module.
197
+ bias_symmetric (`bool`, *optional*, defaults to `False`):
198
+ Whether the relative attention bias should be symmetric or not.
199
+ nemo_activation (`str`, *optional*, defaults to `"relu"`):
200
+ The non-linear activation function in the nemo conv modules.
201
+ nemo_conv_channels (`int`, *optional*, defaults to 1024):
202
+ Number of channels in the nemo conv modules.
203
+ downsample_rate (`int`, *optional*, defaults to 1):
204
+ Downsample rate for the audio feature extractor.
205
+ initializer_range (`float`, *optional*, defaults to 0.02):
206
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
207
+ audio_token_id (`int`, *optional*, defaults to 200011):
208
+ The audio token id.
209
+ feature_layer (`int`, *optional*, defaults to -2):
210
+ The index of the layer of the encoder from which to extract audio features.
211
+
212
+ Example:
213
+
214
+ ```python
215
+ >>> from transformers import Phi4MultimodalAudioConfig
216
+
217
+ >>> # Initializing a Phi4MultimodalAudioConfig with microsoft/Phi-4-multimodal-instruct style configuration
218
+ >>> configuration = Phi4MultimodalAudioConfig()
219
+ ```"""
220
+
221
+ model_type = "phi4_multimodal_audio"
222
+
223
+ def __init__(
224
+ self,
225
+ hidden_size: int = 1024,
226
+ intermediate_size: int = 1536,
227
+ num_blocks: int = 24,
228
+ num_attention_heads: int = 16,
229
+ activation: str = "swish",
230
+ chunk_size: int = -1,
231
+ left_chunk: int = 18,
232
+ dropout_rate: float = 0.0,
233
+ ext_pw_out_channel: int = 1024,
234
+ depthwise_seperable_out_channel: int = 1024,
235
+ depthwise_multiplier: int = 1,
236
+ kernel_size: int = 3,
237
+ conv_activation: str = "swish",
238
+ input_size: int = 80,
239
+ conv_glu_type: str = "swish",
240
+ time_reduction: int = 8,
241
+ bias_max_distance: int = 1000,
242
+ bias_symmetric: bool = False,
243
+ nemo_activation: str = "relu",
244
+ nemo_conv_channels: int = 1024,
245
+ downsample_rate: int = 1,
246
+ initializer_range: float = 0.02,
247
+ audio_token_id: int = 200011,
248
+ feature_layer: int = -2,
249
+ **kwargs,
250
+ ):
251
+ super().__init__(**kwargs)
252
+ self.hidden_size = hidden_size
253
+ self.num_attention_heads = num_attention_heads
254
+ self.intermediate_size = intermediate_size
255
+ self.activation = activation
256
+ self.chunk_size = chunk_size
257
+ self.left_chunk = left_chunk
258
+ self.num_blocks = num_blocks
259
+ self.dropout_rate = dropout_rate
260
+ self.ext_pw_out_channel = ext_pw_out_channel
261
+ self.depthwise_seperable_out_channel = depthwise_seperable_out_channel
262
+ self.depthwise_multiplier = depthwise_multiplier
263
+ self.kernel_size = kernel_size
264
+ self.conv_activation = conv_activation
265
+ self.input_size = input_size
266
+ self.conv_glu_type = conv_glu_type
267
+ self.time_reduction = time_reduction
268
+ self.bias_max_distance = bias_max_distance
269
+ self.bias_symmetric = bias_symmetric
270
+ self.nemo_activation = nemo_activation
271
+ self.nemo_conv_channels = nemo_conv_channels
272
+ self.downsample_rate = downsample_rate
273
+ self.audio_token_id = audio_token_id
274
+ self.initializer_range = initializer_range
275
+ self.feature_layer = feature_layer
276
+
277
+ if time_reduction % 2 != 0:
278
+ raise ValueError("`time_reduction` should be a multiple of 2!")
279
+ length = input_size
280
+ for _ in range(int(math.log(time_reduction, 2))):
281
+ length = math.floor((length - 1) / 2 + 1)
282
+ self.nemo_final_size = length
283
+
284
+
285
+ class Phi4MultimodalConfig(Phi3Config):
286
+ r"""
287
+ This is the configuration class to store the configuration of a [`Phi4MultimodalModel`]. It is used to instantiate a
288
+ Phi4Multimodal model according to the specified arguments, defining the model architecture. Instantiating a configuration
289
+ with the defaults will yield a similar configuration to that of the
290
+ [microsoft/Phi-4-multimodal-instruct](https://huggingface.co/microsoft/Phi-4-multimodal-instruct) architecture.
291
+
292
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
293
+ documentation from [`PretrainedConfig`] for more information.
294
+
295
+ Args:
296
+ vocab_size (`int`, *optional*, defaults to 200064):
297
+ Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
298
+ `inputs_ids` passed when calling [`Phi3Model`].
299
+ hidden_size (`int`, *optional*, defaults to 3072):
300
+ Dimension of the hidden representations.
301
+ intermediate_size (`int`, *optional*, defaults to 8192):
302
+ Dimension of the MLP representations.
303
+ num_hidden_layers (`int`, *optional*, defaults to 32):
304
+ Number of hidden layers in the Transformer decoder.
305
+ num_attention_heads (`int`, *optional*, defaults to 32):
306
+ Number of attention heads for each attention layer in the Transformer decoder.
307
+ num_key_value_heads (`int`, *optional*, defaults to 8):
308
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
309
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
310
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
311
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
312
+ by meanpooling all the original heads within that group. For more details checkout [this
313
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
314
+ `num_attention_heads`.
315
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
316
+ Dropout probability for mlp outputs.
317
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
318
+ The dropout ratio for the embeddings.
319
+ attention_dropout (`float`, *optional*, defaults to 0.0):
320
+ The dropout ratio after computing the attention scores.
321
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
322
+ The non-linear activation function (function or string) in the decoder.
323
+ max_position_embeddings (`int`, *optional*, defaults to 131072):
324
+ The maximum sequence length that this model might ever be used with.
325
+ initializer_range (`float`, *optional*, defaults to 0.02):
326
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
327
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
328
+ The epsilon value used for the RMSNorm.
329
+ use_cache (`bool`, *optional*, defaults to `True`):
330
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
331
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
332
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
333
+ Whether to tie weight embeddings
334
+ rope_theta (`float`, *optional*, defaults to 10000.0):
335
+ The base period of the RoPE embeddings.
336
+ rope_scaling (`dict`, *optional*):
337
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
338
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be `longrope` and
339
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
340
+ divided by the number of attention heads divided by 2.
341
+ partial_rotary_factor (`float`, *optional*, defaults to `1.0`):
342
+ Percentage of the query and keys which will have rotary embedding. Must be between 0.0 and 1.0.
343
+ bos_token_id (`int`, *optional*, defaults to 199999):
344
+ The id of the "beginning-of-sequence" token.
345
+ eos_token_id (`int` or `list[int]`, *optional*, defaults to `[199999, 200020]`):
346
+ The id of the "end-of-sequence" token.
347
+ pad_token_id (`int`, *optional*, defaults to 199999):
348
+ The id of the padding token.
349
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
350
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
351
+ original RoPE embeddings when using long scaling.
352
+ sliding_window (`int`, *optional*):
353
+ Sliding window attention window size. If `None`, no sliding window is applied.
354
+ vision_config (`Phi4MultimodalVisionConfig` or `dict`, *optional*):
355
+ The vision config for the underlying image embedding model. If not provided, will default to the configuration
356
+ used to instantiate a model similar in architecture as
357
+ [microsoft/Phi-4-multimodal-instruct](https://huggingface.co/microsoft/Phi-4-multimodal-instruct).
358
+ audio_config (`Phi4MultimodalAudioConfig` or `dict`, *optional*):
359
+ The audio config for the underlying audio embedding model. If not provided, will default to the configuration
360
+ used to instantiate a model similar in architecture as
361
+ [microsoft/Phi-4-multimodal-instruct](https://huggingface.co/microsoft/Phi-4-multimodal-instruct).
362
+
363
+ Example:
364
+
365
+ ```python
366
+ >>> from transformers import Phi4MultimodalModel, Phi4MultimodalConfig
367
+
368
+ >>> # Initializing a Phi4Multimodal style configuration
369
+ >>> configuration = Phi4MultimodalConfig.from_pretrained("microsoft/Phi-4-multimodal-instruct")
370
+
371
+ >>> # Initializing a model from the configuration
372
+ >>> model = Phi4MultimodalModel(configuration)
373
+
374
+ >>> # Accessing the model configuration
375
+ >>> configuration = model.config
376
+ ```"""
377
+
378
+ sub_configs = {"audio_config": Phi4MultimodalAudioConfig, "vision_config": Phi4MultimodalVisionConfig}
379
+
380
+ def __init__(
381
+ self,
382
+ vocab_size=200064,
383
+ hidden_size=3072,
384
+ intermediate_size=8192,
385
+ num_hidden_layers=32,
386
+ num_attention_heads=32,
387
+ num_key_value_heads=8,
388
+ resid_pdrop=0.0,
389
+ embd_pdrop=0.0,
390
+ attention_dropout=0.0,
391
+ hidden_act="silu",
392
+ max_position_embeddings=131072,
393
+ initializer_range=0.02,
394
+ rms_norm_eps=1e-5,
395
+ use_cache=True,
396
+ tie_word_embeddings=False,
397
+ rope_theta=10000.0,
398
+ rope_scaling=None,
399
+ partial_rotary_factor=1,
400
+ bos_token_id=199999,
401
+ eos_token_id=[199999, 200020],
402
+ pad_token_id=199999,
403
+ original_max_position_embeddings=4096,
404
+ sliding_window=None,
405
+ vision_config=None,
406
+ audio_config=None,
407
+ **kwargs,
408
+ ):
409
+ super().__init__(
410
+ vocab_size=vocab_size,
411
+ hidden_size=hidden_size,
412
+ intermediate_size=intermediate_size,
413
+ num_hidden_layers=num_hidden_layers,
414
+ num_attention_heads=num_attention_heads,
415
+ num_key_value_heads=num_key_value_heads,
416
+ resid_pdrop=resid_pdrop,
417
+ embd_pdrop=embd_pdrop,
418
+ attention_dropout=attention_dropout,
419
+ hidden_act=hidden_act,
420
+ max_position_embeddings=max_position_embeddings,
421
+ initializer_range=initializer_range,
422
+ rms_norm_eps=rms_norm_eps,
423
+ use_cache=use_cache,
424
+ tie_word_embeddings=tie_word_embeddings,
425
+ rope_theta=rope_theta,
426
+ rope_scaling=rope_scaling,
427
+ partial_rotary_factor=partial_rotary_factor,
428
+ bos_token_id=bos_token_id,
429
+ eos_token_id=eos_token_id,
430
+ pad_token_id=pad_token_id,
431
+ original_max_position_embeddings=original_max_position_embeddings,
432
+ sliding_window=sliding_window,
433
+ **kwargs,
434
+ )
435
+
436
+ if isinstance(vision_config, dict):
437
+ vision_config = Phi4MultimodalVisionConfig(**vision_config)
438
+ elif vision_config is None:
439
+ Phi4MultimodalVisionConfig()
440
+ self.vision_config = vision_config
441
+
442
+ if isinstance(audio_config, dict):
443
+ audio_config = Phi4MultimodalAudioConfig(**audio_config)
444
+ elif vision_config is None:
445
+ audio_config = Phi4MultimodalAudioConfig()
446
+ self.audio_config = audio_config
447
+
448
+
449
+ class Phi4MultimodalVisionMLP(SiglipMLP):
450
+ pass
451
+
452
+
453
+ def simple_eager_attention_forward(
454
+ module: nn.Module,
455
+ query_states: torch.Tensor,
456
+ key_states: torch.Tensor,
457
+ value_states: torch.Tensor,
458
+ attention_mask: Optional[torch.Tensor],
459
+ scaling: float,
460
+ dropout: float = 0.0,
461
+ **kwargs,
462
+ ):
463
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * scaling
464
+ if attention_mask is not None:
465
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
466
+ attn_weights = attn_weights + causal_mask
467
+
468
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
469
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
470
+ attn_output = torch.matmul(attn_weights, value_states)
471
+ attn_output = attn_output.transpose(1, 2).contiguous()
472
+
473
+ return attn_output, attn_weights
474
+
475
+
476
+ class Phi4MultimodalVisionAttention(nn.Module):
477
+ def __init__(self, config: Phi4MultimodalVisionConfig):
478
+ super().__init__()
479
+ self.config = config
480
+ self.embed_dim = config.hidden_size
481
+ self.num_heads = config.num_attention_heads
482
+ self.head_dim = self.embed_dim // self.num_heads
483
+ self.scaling = self.head_dim**-0.5
484
+ self.is_causal = True
485
+ self.attention_dropout = config.attention_dropout
486
+
487
+ self.k_proj = nn.Linear(config.hidden_size, config.hidden_size)
488
+ self.v_proj = nn.Linear(config.hidden_size, config.hidden_size)
489
+ self.q_proj = nn.Linear(config.hidden_size, config.hidden_size)
490
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size)
491
+
492
+ def forward(
493
+ self,
494
+ hidden_states: torch.Tensor,
495
+ attention_mask: Optional[torch.Tensor] = None,
496
+ **kwargs,
497
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
498
+ """Input shape: Batch x Time x Channel"""
499
+ input_shape = hidden_states.shape[:-1]
500
+ hidden_shape = (*input_shape, -1, self.head_dim)
501
+
502
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
503
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
504
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
505
+
506
+ attention_interface: Callable = simple_eager_attention_forward
507
+ if self.config._attn_implementation != "eager":
508
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
509
+
510
+ attn_output, attn_weights = attention_interface(
511
+ self,
512
+ query_states,
513
+ key_states,
514
+ value_states,
515
+ attention_mask,
516
+ dropout=0.0 if not self.training else self.attention_dropout,
517
+ scaling=self.scaling,
518
+ **kwargs,
519
+ )
520
+
521
+ attn_output = attn_output.reshape(*input_shape, -1)
522
+ attn_output = self.out_proj(attn_output)
523
+ return attn_output, attn_weights
524
+
525
+
526
+ class Phi4MultimodalVisionEncoderLayer(SiglipEncoderLayer):
527
+ def __init__(self, config: Phi4MultimodalVisionConfig):
528
+ super().__init__(config)
529
+ self.self_attn = Phi4MultimodalVisionAttention(config)
530
+ self.mlp = Phi4MultimodalVisionMLP(config)
531
+
532
+
533
+ class Phi4MultimodalVisionEncoder(SiglipEncoder):
534
+ def __init__(self, config: Phi4MultimodalVisionConfig):
535
+ super().__init__()
536
+ self.layers = nn.ModuleList(
537
+ [Phi4MultimodalVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)]
538
+ )
539
+
540
+
541
+ class Phi4MultimodalVisionPreTrainedModel(SiglipPreTrainedModel):
542
+ config_class = Phi4MultimodalVisionConfig
543
+ base_model_prefix = "phi4_vision"
544
+ supports_gradient_checkpointing = True
545
+
546
+ _no_split_modules = ["Phi4MultimodalVisionEncoderLayer"]
547
+ _supports_flash_attn_2 = True
548
+ _supports_sdpa = True
549
+ _supports_flex_attn = True
550
+
551
+ def _init_weights(self, module):
552
+ """Initialize the weights"""
553
+ if isinstance(module, Phi4MultimodalVisionEmbeddings):
554
+ width = (
555
+ self.config.hidden_size
556
+ if isinstance(self.config, Phi4MultimodalVisionConfig)
557
+ else self.config.hidden_size
558
+ )
559
+ nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
560
+ elif isinstance(module, nn.Embedding):
561
+ default_flax_embed_init(module.weight)
562
+ elif isinstance(module, Phi4MultimodalVisionAttention):
563
+ nn.init.normal_(module.q_proj.weight)
564
+ nn.init.normal_(module.k_proj.weight)
565
+ nn.init.normal_(module.v_proj.weight)
566
+ nn.init.normal_(module.out_proj.weight)
567
+ nn.init.zeros_(module.q_proj.bias)
568
+ nn.init.zeros_(module.k_proj.bias)
569
+ nn.init.zeros_(module.v_proj.bias)
570
+ nn.init.zeros_(module.out_proj.bias)
571
+ elif isinstance(module, Phi4MultimodalVisionMLP):
572
+ nn.init.normal_(module.fc1.weight)
573
+ nn.init.normal_(module.fc2.weight)
574
+ nn.init.normal_(module.fc1.bias, std=1e-6)
575
+ nn.init.normal_(module.fc2.bias, std=1e-6)
576
+ elif isinstance(module, Phi4MultimodalVisionMultiheadAttentionPoolingHead):
577
+ nn.init.normal_(module.probe.data)
578
+ nn.init.normal_(module.attention.in_proj_weight.data)
579
+ nn.init.zeros_(module.attention.in_proj_bias.data)
580
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
581
+ lecun_normal_(module.weight)
582
+ if module.bias is not None:
583
+ nn.init.zeros_(module.bias)
584
+ elif isinstance(module, nn.LayerNorm):
585
+ module.bias.data.zero_()
586
+ module.weight.data.fill_(1.0)
587
+
588
+
589
+ class Phi4MultimodalVisionEmbeddings(SiglipVisionEmbeddings, nn.Module):
590
+ def __init__(self, config: Phi4MultimodalVisionConfig):
591
+ nn.Module.__init__()
592
+ self.config = config
593
+ self.patch_size = config.patch_size
594
+ self.num_patches_per_side = config.image_size // self.patch_size
595
+
596
+ self.patch_embedding = nn.Conv2d(
597
+ in_channels=config.num_channels,
598
+ out_channels=config.hidden_size,
599
+ kernel_size=self.patch_size,
600
+ stride=self.patch_size,
601
+ padding="valid",
602
+ )
603
+ self.position_embedding = nn.Embedding(self.num_patches_per_side**2, config.hidden_size)
604
+
605
+ def forward(self, pixel_values: torch.FloatTensor, patch_attention_mask: torch.BoolTensor) -> torch.Tensor:
606
+ batch_size = pixel_values.size(0)
607
+
608
+ patch_embeds = self.patch_embedding(pixel_values)
609
+ embeddings = patch_embeds.flatten(2).transpose(1, 2)
610
+
611
+ max_im_h, max_im_w = pixel_values.size(2), pixel_values.size(3)
612
+ max_nb_patches_h, max_nb_patches_w = max_im_h // self.patch_size, max_im_w // self.patch_size
613
+ boundaries = torch.arange(1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side)
614
+ position_ids = torch.full((batch_size, max_nb_patches_h * max_nb_patches_w), fill_value=0)
615
+
616
+ for batch_idx, p_attn_mask in enumerate(patch_attention_mask):
617
+ nb_patches_h = p_attn_mask[:, 0].sum()
618
+ nb_patches_w = p_attn_mask[0].sum()
619
+
620
+ fractional_coords_h = torch.arange(0, 1 - 1e-6, 1 / nb_patches_h)
621
+ fractional_coords_w = torch.arange(0, 1 - 1e-6, 1 / nb_patches_w)
622
+
623
+ bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True)
624
+ bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True)
625
+
626
+ pos_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten()
627
+ position_ids[batch_idx][p_attn_mask.view(-1).cpu()] = pos_ids
628
+
629
+ position_ids = position_ids.to(self.position_embedding.weight.device)
630
+
631
+ embeddings = embeddings + self.position_embedding(position_ids)
632
+ return embeddings
633
+
634
+
635
+ class Phi4MultimodalVisionMultiheadAttentionPoolingHead(SiglipMultiheadAttentionPoolingHead):
636
+ def __init__(self, config: Phi4MultimodalVisionConfig):
637
+ super().__init__(config)
638
+ self.mlp = Phi4MultimodalVisionMLP(config)
639
+
640
+ def forward(self, hidden_state, attention_mask):
641
+ batch_size = hidden_state.shape[0]
642
+ probe = self.probe.repeat(batch_size, 1, 1)
643
+
644
+ hidden_state = self.attention(
645
+ query=probe, key=hidden_state, value=hidden_state, key_padding_mask=~attention_mask
646
+ )[0]
647
+
648
+ residual = hidden_state
649
+ hidden_state = self.layernorm(hidden_state)
650
+ hidden_state = residual + self.mlp(hidden_state)
651
+
652
+ return hidden_state[:, 0]
653
+
654
+
655
+ class Phi4MultimodalVisionModel(Phi4MultimodalVisionPreTrainedModel):
656
+ config_class = Phi4MultimodalVisionConfig
657
+ main_input_name = "pixel_values"
658
+
659
+ def __init__(self, config: Phi4MultimodalVisionConfig):
660
+ super().__init__(config)
661
+ self.config = config
662
+
663
+ self.embeddings = Phi4MultimodalVisionEmbeddings(config)
664
+ self.encoder = Phi4MultimodalVisionEncoder(config)
665
+ self.post_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
666
+ self.head = Phi4MultimodalVisionMultiheadAttentionPoolingHead(config)
667
+
668
+ # Initialize weights and apply final processing
669
+ self.post_init()
670
+
671
+ def get_input_embeddings(self) -> nn.Module:
672
+ return self.embeddings.patch_embedding
673
+
674
+ def forward(
675
+ self,
676
+ pixel_values,
677
+ patch_attention_mask: Optional[torch.BoolTensor] = None,
678
+ output_attentions: Optional[bool] = None,
679
+ output_hidden_states: Optional[bool] = None,
680
+ ) -> BaseModelOutputWithPooling:
681
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
682
+ output_hidden_states = (
683
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
684
+ )
685
+
686
+ batch_size = pixel_values.size(0)
687
+ if patch_attention_mask is None:
688
+ patch_attention_mask = torch.ones(
689
+ size=(
690
+ batch_size,
691
+ pixel_values.size(2) // self.config.patch_size,
692
+ pixel_values.size(3) // self.config.patch_size,
693
+ ),
694
+ dtype=torch.bool,
695
+ device=pixel_values.device,
696
+ )
697
+
698
+ hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask)
699
+
700
+ patch_attention_mask = patch_attention_mask.view(batch_size, -1)
701
+ # The call to `_upad_input` in `_flash_attention_forward` is expensive
702
+ # So when the `patch_attention_mask` is full of 1s (i.e. attending to the whole sequence),
703
+ # avoiding passing the attention_mask, which is equivalent to attending to the full sequence
704
+ if not torch.any(~patch_attention_mask):
705
+ attention_mask = None
706
+ else:
707
+ attention_mask = (
708
+ _prepare_4d_attention_mask(patch_attention_mask, hidden_states.dtype)
709
+ if not self.config._attn_implementation == "flash_attention_2"
710
+ else patch_attention_mask
711
+ )
712
+
713
+ encoder_outputs: BaseModelOutput = self.encoder(
714
+ inputs_embeds=hidden_states,
715
+ attention_mask=attention_mask,
716
+ output_attentions=output_attentions,
717
+ output_hidden_states=output_hidden_states,
718
+ )
719
+
720
+ last_hidden_state = encoder_outputs.last_hidden_state
721
+ last_hidden_state = self.post_layernorm(last_hidden_state)
722
+
723
+ pooled_output = self.head(
724
+ hidden_state=last_hidden_state,
725
+ attention_mask=patch_attention_mask,
726
+ )
727
+
728
+ return BaseModelOutputWithPooling(
729
+ last_hidden_state=last_hidden_state,
730
+ pooler_output=pooled_output,
731
+ hidden_states=encoder_outputs.hidden_states,
732
+ attentions=encoder_outputs.attentions,
733
+ )
734
+
735
+
736
+ class Phi4MultimodalImageEmbedding(nn.Module):
737
+ """Image embedding."""
738
+
739
+ def __init__(self, config: Phi4MultimodalConfig):
740
+ super().__init__()
741
+ self.config = config
742
+ self.layer_idx = config.vision_config.feature_layer
743
+ self.crop_size = config.vision_config.crop_size
744
+ self.image_dim_out = config.vision_config.hidden_size
745
+
746
+ n_patches = config.vision_config.image_size // config.vision_config.patch_size
747
+ if n_patches % 2 != 0:
748
+ self.img_processor_padding = nn.ReflectionPad2d((0, 1, 0, 1))
749
+ n_patches += 1
750
+ self.num_img_tokens = (n_patches // 2) ** 2
751
+
752
+ self.drop = nn.Dropout(config.embd_pdrop)
753
+ self.img_processor = Phi4MultimodalVisionModel._from_config(config.vision_config)
754
+ self.image_token_compression = nn.AvgPool2d(kernel_size=2, stride=2)
755
+ self.img_projection_up = nn.Linear(self.image_dim_out, config.hidden_size)
756
+ self.img_projection_down = nn.Linear(config.hidden_size, config.hidden_size)
757
+ self.global_img_feature_extensor = nn.Parameter(torch.zeros([1, 1, self.image_dim_out]))
758
+ self.sub_img_feature_extensor = nn.Parameter(torch.zeros([1, 1, 1, self.image_dim_out]))
759
+
760
+ def get_img_features(self, img_embeds: torch.FloatTensor, attention_mask=None) -> torch.FloatTensor:
761
+ img_processor_output = self.img_processor(
762
+ img_embeds, patch_attention_mask=attention_mask, output_hidden_states=True
763
+ )
764
+ img_feature = img_processor_output.hidden_states[self.layer_idx]
765
+
766
+ patch_feature = img_feature
767
+ # reshape to 2D tensor
768
+ width = int(math.sqrt(patch_feature.size(1)))
769
+ patch_feature = patch_feature.view(-1, width, width, patch_feature.size(-1))
770
+ # convert to NCHW
771
+ patch_feature = patch_feature.permute(0, 3, 1, 2)
772
+ if getattr(self, "img_processor_padding", None) is not None:
773
+ patch_feature = self.img_processor_padding(patch_feature)
774
+ patch_feature = self.image_token_compression(patch_feature)
775
+ # convert to NHWC
776
+ patch_feature = patch_feature.permute(0, 2, 3, 1)
777
+ patch_feature = patch_feature.view(-1, patch_feature.size(1) * patch_feature.size(2), patch_feature.size(-1))
778
+ return patch_feature
779
+
780
+ def forward(
781
+ self,
782
+ input_ids: torch.LongTensor,
783
+ inputs_embeds: torch.Tensor,
784
+ image_pixel_values: torch.FloatTensor,
785
+ image_sizes: Optional[torch.Tensor] = None,
786
+ image_attention_mask: Optional[torch.Tensor] = None,
787
+ ) -> torch.FloatTensor:
788
+ image_pixel_values = image_pixel_values.to(self.img_processor.embeddings.patch_embedding.weight.dtype)
789
+
790
+ target_device = self.img_projection_up.bias.device
791
+ target_dtype = self.img_projection_up.bias.dtype
792
+
793
+ batch_size = image_pixel_values.shape[0]
794
+
795
+ img_features = self.get_img_features(
796
+ image_pixel_values.flatten(0, 1),
797
+ attention_mask=image_attention_mask.flatten(0, 1).to(dtype=bool, device=target_device),
798
+ )
799
+ base_feat_size = int(np.sqrt(img_features.shape[1]))
800
+ img_features = img_features.view(batch_size, -1, base_feat_size**2, self.image_dim_out)
801
+ image_sizes = image_sizes.view(-1, 2)
802
+
803
+ output_imgs = []
804
+ for idx in range(batch_size):
805
+ height, width = image_sizes[idx]
806
+ height_ratio = height // self.crop_size
807
+ width_ratio = width // self.crop_size
808
+ area_ratio = height_ratio * width_ratio
809
+
810
+ global_img = img_features[idx, :1]
811
+ global_img = global_img.reshape(1, base_feat_size, base_feat_size, self.image_dim_out).contiguous()
812
+ temporary_extensor = self.sub_img_feature_extensor.repeat(1, base_feat_size, 1, 1)
813
+ global_img = torch.cat([global_img, temporary_extensor], dim=2).reshape(1, -1, self.image_dim_out)
814
+
815
+ sub_img = img_features[idx, 1:]
816
+ sub_img = sub_img[:area_ratio]
817
+ sub_img = (
818
+ sub_img.reshape(height_ratio, width_ratio, base_feat_size, base_feat_size, self.image_dim_out)
819
+ .transpose(1, 2)
820
+ .reshape(1, height_ratio * base_feat_size, width_ratio * base_feat_size, self.image_dim_out)
821
+ .contiguous()
822
+ )
823
+
824
+ if image_attention_mask is not None:
825
+ reshaped_image_attention_mask = (
826
+ image_attention_mask[idx, 1 : area_ratio + 1, 0::2, 0::2]
827
+ .reshape(height_ratio, width_ratio, base_feat_size, base_feat_size)
828
+ .transpose(1, 2)
829
+ .reshape(1, height_ratio * base_feat_size, width_ratio * base_feat_size)
830
+ )
831
+ useful_height = int(reshaped_image_attention_mask[0, :, 0].sum().item())
832
+ useful_width = int(reshaped_image_attention_mask[0, 0, :].sum().item())
833
+ sub_img = sub_img[:, :useful_height, :useful_width]
834
+ temporary_extensor = self.sub_img_feature_extensor.repeat(1, useful_height, 1, 1)
835
+ else:
836
+ temporary_extensor = self.sub_img_feature_extensor.repeat(1, height_ratio * base_feat_size, 1, 1)
837
+
838
+ sub_img = torch.cat([sub_img, temporary_extensor], dim=2).reshape(1, -1, self.image_dim_out)
839
+
840
+ # Merge global and sub
841
+ output_imgs.append(torch.cat([sub_img, self.global_img_feature_extensor, global_img], dim=1))
842
+
843
+ img_set_tensor = []
844
+ for output_img in output_imgs:
845
+ output_img = output_img.to(device=target_device, dtype=target_dtype)
846
+ img_feature_proj = self.img_projection_up(output_img)
847
+ img_feature_proj = nn.functional.gelu(img_feature_proj)
848
+ img_feature_proj = self.img_projection_down(img_feature_proj)
849
+ img_set_tensor.append(img_feature_proj)
850
+
851
+ merged_img_set_tensor = torch.cat(img_set_tensor, dim=1).squeeze(0)
852
+ merged_img_set_tensor = merged_img_set_tensor.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
853
+
854
+ with torch.no_grad():
855
+ positions_tuple = torch.nonzero(input_ids == self.config.vision_config.image_token_id, as_tuple=True)
856
+
857
+ # Temporarily disable autocast to avoid issue on bf16 tensors
858
+ # Ref: https://github.com/pytorch/pytorch/issues/132715
859
+ with torch.autocast(device_type=inputs_embeds.device.type, enabled=False):
860
+ image_embeds = inputs_embeds.index_put(
861
+ indices=positions_tuple, values=merged_img_set_tensor, accumulate=False
862
+ )
863
+
864
+ image_embeds = self.drop(image_embeds)
865
+
866
+ return image_embeds
867
+
868
+
869
+ ########################################################## AUDIO #############################################
870
+
871
+
872
+ class Phi4MultimodalAudioMLP(nn.Module):
873
+ def __init__(self, config: Phi4MultimodalAudioConfig):
874
+ super().__init__()
875
+ self.layer_norm = nn.LayerNorm(config.hidden_size)
876
+ self.act_fn = ACT2FN[config.activation]
877
+ self.gate_up_proj = nn.Linear(config.hidden_size, config.intermediate_size * 2)
878
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size)
879
+ self.dropout = nn.Dropout(config.dropout_rate)
880
+
881
+ def forward(self, hidden_states):
882
+ hidden_states = self.layer_norm(hidden_states)
883
+ up_states = self.gate_up_proj(hidden_states)
884
+ up_states, gate = up_states.chunk(2, dim=-1)
885
+ up_states = up_states * self.act_fn(gate)
886
+ up_states = self.dropout(up_states)
887
+ hidden_states = self.down_proj(up_states)
888
+ out = self.dropout(hidden_states)
889
+
890
+ return out
891
+
892
+
893
+ class Phi4MultimodalAudioAttention(nn.Module):
894
+ def __init__(self, config: Phi4MultimodalAudioConfig):
895
+ super().__init__()
896
+ self.config = config
897
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
898
+ self.scaling = self.head_dim**-0.5
899
+ self.attention_dropout = config.dropout_rate
900
+ self.is_causal = True
901
+
902
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
903
+ self.k_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
904
+ self.v_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
905
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=True)
906
+
907
+ def forward(
908
+ self,
909
+ hidden_states: torch.Tensor,
910
+ attention_mask: torch.Tensor,
911
+ **kwargs,
912
+ ):
913
+ input_shape = hidden_states.shape[:-1]
914
+ hidden_shape = (*input_shape, -1, self.head_dim)
915
+
916
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
917
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
918
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
919
+
920
+ attention_interface: Callable = simple_eager_attention_forward
921
+ if self.config._attn_implementation != "eager":
922
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
923
+
924
+ attn_output, _ = attention_interface(
925
+ self,
926
+ query_states,
927
+ key_states,
928
+ value_states,
929
+ attention_mask,
930
+ dropout=0.0 if not self.training else self.attention_dropout,
931
+ scaling=self.scaling,
932
+ **kwargs,
933
+ )
934
+
935
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
936
+ attn_output = self.o_proj(attn_output)
937
+ return attn_output
938
+
939
+
940
+ class Phi4MultimodalAudioDepthWiseSeperableConv1d(nn.Module):
941
+ def __init__(self, config: Phi4MultimodalAudioConfig, padding: int = 0):
942
+ super().__init__()
943
+ self.dw_conv = nn.Conv1d(
944
+ config.hidden_size,
945
+ config.hidden_size * config.depthwise_multiplier,
946
+ config.kernel_size,
947
+ 1,
948
+ padding=padding,
949
+ groups=config.hidden_size,
950
+ )
951
+ self.pw_conv = nn.Conv1d(
952
+ config.hidden_size * config.depthwise_multiplier, config.depthwise_seperable_out_channel, 1, 1, 0
953
+ )
954
+
955
+ def forward(self, hidden_states):
956
+ return self.pw_conv(self.dw_conv(hidden_states))
957
+
958
+
959
+ class Phi4MultimodalAudioGluPointWiseConv(nn.Module):
960
+ def __init__(self, config: Phi4MultimodalAudioConfig):
961
+ super().__init__()
962
+ self.config = config
963
+ self.output_dim = config.ext_pw_out_channel
964
+
965
+ self.ext_pw_conv_1d = nn.Conv1d(config.hidden_size, config.ext_pw_out_channel * 2, kernel_size=1, stride=1)
966
+ self.glu_act = ACT2FN[config.conv_glu_type]
967
+ self.b1 = nn.Parameter(torch.zeros(1, config.ext_pw_out_channel, 1))
968
+ self.b2 = nn.Parameter(torch.zeros(1, config.ext_pw_out_channel, 1))
969
+
970
+ def forward(self, hidden_states):
971
+ # we assume the input always has the #channel (#dim) in the last dimension of the
972
+ # tensor, so need to switch the dimension first for 1D-Conv case
973
+ hidden_states = hidden_states.permute([0, 2, 1])
974
+ hidden_states = self.ext_pw_conv_1d(hidden_states)
975
+ out = hidden_states[:, 0 : self.output_dim, :] + self.b1
976
+ out = out * self.glu_act(hidden_states[:, self.output_dim : self.output_dim * 2, :] + self.b2)
977
+ return out.permute([0, 2, 1])
978
+
979
+
980
+ class Phi4MultimodalAudioConvModule(nn.Module):
981
+ def __init__(self, config: Phi4MultimodalAudioConfig):
982
+ super().__init__()
983
+ self.config = config
984
+ self.kernel_size = config.kernel_size
985
+
986
+ self.layer_norm = nn.LayerNorm(config.hidden_size)
987
+ self.glu = Phi4MultimodalAudioGluPointWiseConv(config)
988
+ self.dw_sep_conv_1d = Phi4MultimodalAudioDepthWiseSeperableConv1d(config, padding=config.kernel_size - 1)
989
+ self.act = ACT2FN[config.conv_activation]
990
+ self.ext_pw_conv_1d = nn.Conv1d(config.hidden_size, config.ext_pw_out_channel, kernel_size=1, stride=1)
991
+ self.dropout = nn.Dropout(config.dropout_rate)
992
+
993
+ def forward(self, hidden_states: torch.Tensor):
994
+ hidden_states = self.glu(self.layer_norm(hidden_states))
995
+ hidden_states = self.dw_sep_conv_1d(hidden_states.permute([0, 2, 1]))
996
+
997
+ if self.kernel_size > 1:
998
+ hidden_states = hidden_states[:, :, : -(self.kernel_size - 1)]
999
+
1000
+ hidden_states = self.act(hidden_states)
1001
+ hidden_states = self.ext_pw_conv_1d(hidden_states)
1002
+ out = self.dropout(hidden_states.permute([0, 2, 1]))
1003
+ return out
1004
+
1005
+
1006
+ class Phi4MultimodalAudioConformerEncoderLayer(nn.Module):
1007
+ def __init__(self, config: Phi4MultimodalAudioConfig):
1008
+ super().__init__()
1009
+
1010
+ self.feed_forward_in = Phi4MultimodalAudioMLP(config)
1011
+ self.self_attn = Phi4MultimodalAudioAttention(config)
1012
+ self.conv = Phi4MultimodalAudioConvModule(config)
1013
+ self.feed_forward_out = Phi4MultimodalAudioMLP(config)
1014
+ self.layer_norm_att = nn.LayerNorm(config.hidden_size)
1015
+ self.layer_norm = nn.LayerNorm(config.hidden_size)
1016
+
1017
+ def forward(
1018
+ self,
1019
+ hidden_states: torch.Tensor,
1020
+ attention_mask: torch.Tensor,
1021
+ ):
1022
+ residual = hidden_states + 0.5 * self.feed_forward_in(hidden_states)
1023
+ hidden_states = self.layer_norm_att(residual)
1024
+
1025
+ hidden_states = residual + self.self_attn(hidden_states, attention_mask)
1026
+ hidden_states = hidden_states + self.conv(hidden_states)
1027
+ hidden_states = hidden_states + 0.5 * self.feed_forward_out(hidden_states)
1028
+
1029
+ out = self.layer_norm(hidden_states)
1030
+
1031
+ return out
1032
+
1033
+
1034
+ class Phi4MultimodalAudioNemoConvSubsampling(torch.nn.Module):
1035
+ def __init__(self, config: Phi4MultimodalAudioConfig):
1036
+ super().__init__()
1037
+ self.subsampling_factor = config.time_reduction
1038
+ self.sampling_num = int(math.log(self.subsampling_factor, 2))
1039
+ self.act_fn = ACT2FN[config.nemo_activation]
1040
+ conv_channels = config.nemo_conv_channels
1041
+
1042
+ layers = [
1043
+ nn.Conv2d(1, conv_channels, kernel_size=3, stride=2, padding=1),
1044
+ self.act_fn,
1045
+ ]
1046
+ for _ in range(self.sampling_num - 1):
1047
+ layers.extend(
1048
+ [
1049
+ nn.Conv2d(conv_channels, conv_channels, kernel_size=3, stride=2, padding=1, groups=conv_channels),
1050
+ nn.Conv2d(conv_channels, conv_channels, kernel_size=1, stride=1, padding=0, groups=1),
1051
+ self.act_fn,
1052
+ ]
1053
+ )
1054
+
1055
+ # Aggregate the layers
1056
+ self.conv = torch.nn.Sequential(*layers)
1057
+ self.out = torch.nn.Linear(conv_channels * config.nemo_final_size, config.hidden_size)
1058
+
1059
+ def forward(self, hidden_states: torch.Tensor, mask: Optional[torch.Tensor]):
1060
+ # Unsqueeze Channel Axis
1061
+ hidden_states = hidden_states.unsqueeze(1)
1062
+ hidden_states = self.conv(hidden_states)
1063
+
1064
+ # Flatten Channel and Frequency Axes
1065
+ b, _, t, _ = hidden_states.size()
1066
+ hidden_states = self.out(hidden_states.transpose(1, 2).reshape(b, t, -1))
1067
+
1068
+ if mask is None:
1069
+ return hidden_states, None
1070
+
1071
+ max_audio_length = hidden_states.shape[1]
1072
+ feature_lens = mask.sum(1)
1073
+ padding_length = torch.ceil(feature_lens / self.subsampling_factor)
1074
+ arange_ = torch.arange(0, max_audio_length, device=hidden_states.device)
1075
+ pad_mask = arange_.expand(padding_length.size(0), -1) < padding_length.unsqueeze(1)
1076
+ return hidden_states, pad_mask.unsqueeze(1)
1077
+
1078
+
1079
+ class Phi4MultimodalAudioRelativeAttentionBias(nn.Module):
1080
+ def __init__(self, config: Phi4MultimodalAudioConfig):
1081
+ super().__init__()
1082
+
1083
+ self.max_distance = config.bias_max_distance
1084
+ self.symmetric = config.bias_symmetric
1085
+ self.num_buckets = self.max_distance
1086
+ if not config.bias_symmetric:
1087
+ self.num_buckets *= 2
1088
+ self.bias_values = nn.Embedding(self.num_buckets, config.num_attention_heads)
1089
+
1090
+ def forward(self, x):
1091
+ # instantiate bias compatible with shape of x
1092
+ max_pos = x.size(1)
1093
+ context_position = torch.arange(max_pos, device=x.device, dtype=torch.long)[:, None]
1094
+ memory_position = torch.arange(max_pos, device=x.device, dtype=torch.long)[None, :]
1095
+ relative_position = memory_position - context_position
1096
+ # clipping to a maximum distance using ops that play well with ONNX export
1097
+ relative_position = relative_position.masked_fill(relative_position < -self.max_distance, -self.max_distance)
1098
+ relative_position = relative_position.masked_fill(
1099
+ relative_position > self.max_distance - 1, self.max_distance - 1
1100
+ )
1101
+
1102
+ # mapping from relative position to index in the bias parameter
1103
+ bias_idx = relative_position
1104
+ bias_idx = bias_idx.abs() if self.symmetric else bias_idx + self.num_buckets // 2
1105
+
1106
+ att_bias = self.bias_values(bias_idx)
1107
+ att_bias = att_bias.permute(2, 0, 1).unsqueeze(0)
1108
+
1109
+ return att_bias
1110
+
1111
+
1112
+ class Phi4MultimodalAudioMeanVarianceNormLayer(nn.Module):
1113
+ def __init__(self, config: Phi4MultimodalAudioConfig):
1114
+ super().__init__()
1115
+ self.register_buffer("global_mean", torch.zeros(config.input_size))
1116
+ self.register_buffer("global_invstd", torch.ones(config.input_size))
1117
+
1118
+ def forward(self, x):
1119
+ return (x - self.global_mean) * self.global_invstd
1120
+
1121
+
1122
+ class Phi4MultimodalAudioPreTrainedModel(PreTrainedModel):
1123
+ config_class = Phi4MultimodalAudioConfig
1124
+ supports_gradient_checkpointing = True
1125
+ _no_split_modules = ["Phi4MultimodalAudioConformerEncoderLayer"]
1126
+ _supports_flash_attn_2 = True
1127
+ _supports_sdpa = True
1128
+ _supports_flex_attn = True
1129
+
1130
+ def _init_weights(self, module):
1131
+ std = self.config.initializer_range
1132
+ if isinstance(module, (nn.Linear, nn.Conv1d, nn.Conv2d)):
1133
+ module.weight.data.normal_(mean=0.0, std=std)
1134
+ if module.bias is not None:
1135
+ module.bias.data.zero_()
1136
+ elif isinstance(module, nn.Embedding):
1137
+ module.weight.data.normal_(mean=0.0, std=std)
1138
+ if module.padding_idx is not None:
1139
+ module.weight.data[module.padding_idx].zero_()
1140
+ elif isinstance(module, nn.LayerNorm):
1141
+ module.bias.data.zero_()
1142
+ module.weight.data.fill_(1.0)
1143
+ elif isinstance(module, Phi4MultimodalAudioGluPointWiseConv):
1144
+ module.b1.data.zero_()
1145
+ module.b2.data.zero_()
1146
+
1147
+
1148
+ class Phi4MultimodalAudioModel(Phi4MultimodalAudioPreTrainedModel):
1149
+ def __init__(self, config: Phi4MultimodalAudioConfig):
1150
+ super().__init__(config)
1151
+ self.config = config
1152
+
1153
+ self.encoder_embedding = Phi4MultimodalAudioMeanVarianceNormLayer(config)
1154
+ self.embed = Phi4MultimodalAudioNemoConvSubsampling(config)
1155
+ self.relative_attention_bias_layer = Phi4MultimodalAudioRelativeAttentionBias(config)
1156
+ self.encoders = nn.ModuleList(
1157
+ [Phi4MultimodalAudioConformerEncoderLayer(config) for _ in range(config.num_blocks)]
1158
+ )
1159
+ self.gradient_checkpointing = False
1160
+
1161
+ # Initialize weights and apply final processing
1162
+ self.post_init()
1163
+
1164
+ def _streaming_mask(self, seq_len, batch_size, chunk_size, left_chunk):
1165
+ # Create mask matrix for streaming
1166
+ # S stores start index. if chunksize is 18, s is [0,18,36,....]
1167
+ chunk_start_idx = np.arange(0, seq_len, chunk_size)
1168
+ # avoid randomness when run evaluation or decoding
1169
+ if self.training and np.random.rand() > 0.5:
1170
+ # Either first or last chunk is not complete.
1171
+ # If only the last one is not complete, EOS is not effective
1172
+ chunk_start_idx = seq_len - chunk_start_idx
1173
+ chunk_start_idx = chunk_start_idx[::-1]
1174
+ chunk_start_idx = chunk_start_idx[:-1]
1175
+ chunk_start_idx = np.insert(chunk_start_idx, 0, 0)
1176
+
1177
+ enc_streaming_mask = (
1178
+ adaptive_enc_mask(seq_len, chunk_start_idx, left_window=left_chunk)
1179
+ .unsqueeze(0)
1180
+ .expand([batch_size, -1, -1])
1181
+ )
1182
+ return enc_streaming_mask
1183
+
1184
+ def forward_embeddings(self, hidden_states, masks):
1185
+ """Forwarding the inputs through the top embedding layers"""
1186
+ seq_len = math.ceil(hidden_states.shape[1] / self.config.time_reduction)
1187
+ if seq_len <= 0:
1188
+ raise ValueError(
1189
+ f"The squence length after time reduction is invalid: {seq_len}. Your input feature is too short."
1190
+ )
1191
+
1192
+ batch_size = hidden_states.shape[0]
1193
+
1194
+ enc_streaming_mask = self._streaming_mask(seq_len, batch_size, self.config.chunk_size, self.config.left_chunk)
1195
+ enc_streaming_mask = enc_streaming_mask.to(hidden_states.device)
1196
+
1197
+ hidden_states, masks = self.embed(hidden_states, masks)
1198
+
1199
+ streaming_mask = enc_streaming_mask
1200
+ if streaming_mask is not None and masks is not None:
1201
+ hs_mask = masks & streaming_mask
1202
+ elif masks is not None:
1203
+ hs_mask = masks
1204
+ else:
1205
+ hs_mask = streaming_mask
1206
+
1207
+ return hidden_states, hs_mask, masks
1208
+
1209
+ def calculate_hs_mask(self, hidden_states, device, mask):
1210
+ max_audio_length = hidden_states.shape[1]
1211
+ batch_size = hidden_states.shape[0]
1212
+ enc_streaming_mask = self._streaming_mask(
1213
+ max_audio_length, batch_size, self.config.chunk_size, self.config.left_chunk
1214
+ )
1215
+ enc_streaming_mask = enc_streaming_mask.to(device)
1216
+ if mask is None:
1217
+ return enc_streaming_mask
1218
+
1219
+ feature_lens = mask.sum(1)
1220
+ padding_length = feature_lens
1221
+ pad_mask = torch.arange(0, max_audio_length, device=device).expand(
1222
+ padding_length.size(0), -1
1223
+ ) < padding_length.unsqueeze(1)
1224
+ pad_mask = pad_mask.unsqueeze(1)
1225
+ pad_mask = pad_mask & enc_streaming_mask
1226
+ return pad_mask
1227
+
1228
+ def forward(self, hidden_states: torch.Tensor, mask: Optional[torch.Tensor]):
1229
+ hidden_states = self.encoder_embedding(hidden_states)
1230
+ hidden_states, hs_mask, mask = self.forward_embeddings(hidden_states, mask)
1231
+
1232
+ unfolded = False
1233
+ bs, seq_len, _ = hidden_states.shape
1234
+ max_seq_len = 500 # maxium position for absolute positional encoding
1235
+ if seq_len > max_seq_len:
1236
+ # audio sequence is longer than max_seq_len, unfold it into chunks of max_seq_len
1237
+ unfolded = True
1238
+ # the unfold op will drop residual frames, pad it to the multiple of max_seq_len
1239
+ if seq_len % max_seq_len > 0:
1240
+ chunk_pad_size = max_seq_len - (seq_len % max_seq_len)
1241
+ else:
1242
+ chunk_pad_size = 0
1243
+ if chunk_pad_size > 0:
1244
+ hidden_states_pad = F.pad(hidden_states, (0, 0, 0, chunk_pad_size), "constant", 0)
1245
+ hidden_states = hidden_states_pad.to(hidden_states.device)
1246
+
1247
+ hidden_states = unfold_tensor(hidden_states, max_seq_len)
1248
+ masks_unfold = None
1249
+ if mask is not None:
1250
+ # revise hs_mask here because the previous calculated hs_mask did not consider extra pad
1251
+ subsampled_pad_mask = mask.squeeze(1) # [bz, subsampled_unmask_seq_len]
1252
+ extra_padded_subsamlped_pad_mask = F.pad(
1253
+ subsampled_pad_mask, (0, chunk_pad_size), "constant", False
1254
+ ) # extra padding to the pad mask
1255
+ extra_padded_subsamlped_pad_mask = extra_padded_subsamlped_pad_mask.unsqueeze(-1).float()
1256
+ masks_unfold = unfold_tensor(
1257
+ extra_padded_subsamlped_pad_mask, max_seq_len
1258
+ ) # unfold the pad mask like we did to the input tensor
1259
+ masks_unfold = masks_unfold.squeeze(-1).bool() # unfold op does not support bool tensor
1260
+ hs_mask = self.calculate_hs_mask(
1261
+ hidden_states, hidden_states.device, masks_unfold
1262
+ ) # calculate hs_mask based on the unfolded pad mask
1263
+
1264
+ relative_attention_bias = self.relative_attention_bias_layer(hidden_states)
1265
+ attention_mask = hs_mask.unsqueeze(1) + relative_attention_bias
1266
+
1267
+ for layer in self.encoders:
1268
+ hidden_states = layer(hidden_states, attention_mask)
1269
+
1270
+ if unfolded:
1271
+ embed_dim = hidden_states.shape[-1]
1272
+ hidden_states = hidden_states.reshape(bs, -1, embed_dim)
1273
+ # if we ever padded before unfolding, we need to remove the padding
1274
+ if chunk_pad_size > 0:
1275
+ hidden_states = hidden_states[:, :-chunk_pad_size, :]
1276
+
1277
+ return hidden_states
1278
+
1279
+
1280
+ def unfold_tensor(tensor, max_seq_len):
1281
+ """
1282
+ For a given tensor with shape of (N, T, D), if sequence length T is longer than max_seq_len,
1283
+ this function unfold it to a (NT', max_seq_len, D) where T' is T // max_seq_len.
1284
+ Args:
1285
+ tensor: N, T, D
1286
+ """
1287
+ _, _, D = tensor.shape
1288
+ tensor = tensor.transpose(-1, -2)
1289
+ # N x D x 1 x T => N x (D x max_seq_len) x T'
1290
+ tensor = F.unfold(tensor[..., None, :], kernel_size=(1, max_seq_len), stride=(1, max_seq_len))
1291
+
1292
+ new_bsz, _, slen = tensor.shape
1293
+ tensor = tensor.view(new_bsz, -1, max_seq_len, slen)
1294
+ tensor = tensor.permute(0, 3, 2, 1)
1295
+ tensor = tensor.view(-1, max_seq_len, D).contiguous()
1296
+ return tensor
1297
+
1298
+
1299
+ def adaptive_enc_mask(x_len, chunk_start_idx, left_window=0, right_window=0):
1300
+ """
1301
+ The function is very important for Transformer Transducer Streaming mode
1302
+ Args:
1303
+ xs_len (int): sequence length
1304
+ chunk_start_idx (list): first idx of each chunk, such as [0,18,36,48]. It also supports adaptive chunk size [0,10,15,45]
1305
+ left_window (int): how many left chunks can be seen
1306
+ right_window (int): how many right chunks can be seen. It is used for chunk overlap model.
1307
+ Returns:
1308
+ mask (torch.Tensor): a mask tensor for streaming model
1309
+ """
1310
+ chunk_start_idx = torch.Tensor(chunk_start_idx).long()
1311
+ start_pad = torch.nn.functional.pad(
1312
+ chunk_start_idx, (1, 0)
1313
+ ) # append 0 to the beginning, so it becomes [0, 0, 18, 36, 48]
1314
+ end_pad = torch.nn.functional.pad(
1315
+ chunk_start_idx, (0, 1), value=x_len
1316
+ ) # append x_len to the end, so it becomes [0,18,36,48, x_len]
1317
+ seq_range = torch.arange(0, x_len).unsqueeze(-1)
1318
+ idx = ((seq_range < end_pad) & (seq_range >= start_pad)).nonzero()[:, 1]
1319
+ seq_range_expand = torch.arange(0, x_len).unsqueeze(0).expand(x_len, -1)
1320
+ idx_left = idx - left_window
1321
+ idx_left[idx_left < 0] = 0
1322
+ boundary_left = start_pad[idx_left]
1323
+ mask_left = seq_range_expand >= boundary_left.unsqueeze(-1)
1324
+ idx_right = idx + right_window
1325
+ idx_right[idx_right > len(chunk_start_idx)] = len(chunk_start_idx)
1326
+ boundary_right = end_pad[idx_right]
1327
+ mask_right = seq_range_expand < boundary_right.unsqueeze(-1)
1328
+ return mask_left & mask_right
1329
+
1330
+
1331
+ class Phi4MultimodalAudioEmbedding(nn.Module):
1332
+ def __init__(self, config: Phi4MultimodalConfig):
1333
+ super().__init__()
1334
+ self.config = config
1335
+ self.layer_idx = config.audio_config.feature_layer
1336
+
1337
+ self.drop = nn.Dropout(config.embd_pdrop)
1338
+ self.encoder = Phi4MultimodalAudioModel._from_config(config.audio_config)
1339
+ self.up_proj_for_speech = nn.Linear(
1340
+ config.audio_config.hidden_size * config.audio_config.downsample_rate, config.hidden_size
1341
+ )
1342
+ self.down_proj_for_speech = nn.Linear(config.hidden_size, config.hidden_size)
1343
+ self.up_proj_for_vision_speech = nn.Linear(
1344
+ config.audio_config.hidden_size * config.audio_config.downsample_rate, config.hidden_size
1345
+ )
1346
+ self.down_proj_for_vision_speech = nn.Linear(config.hidden_size, config.hidden_size)
1347
+
1348
+ def forward(
1349
+ self,
1350
+ input_ids: torch.LongTensor,
1351
+ inputs_embeds: torch.Tensor,
1352
+ audio_input_features: torch.FloatTensor,
1353
+ audio_embed_sizes=None,
1354
+ audio_attention_mask=None,
1355
+ audio_projection_mode="speech",
1356
+ ) -> torch.FloatTensor:
1357
+ with torch.no_grad():
1358
+ positions_tuple = torch.nonzero(input_ids == self.config.audio_config.audio_token_id, as_tuple=True)
1359
+
1360
+ up_proj = self.up_proj_for_speech if audio_projection_mode == "speech" else self.up_proj_for_vision_speech
1361
+ down_proj = (
1362
+ self.down_proj_for_speech if audio_projection_mode == "speech" else self.down_proj_for_vision_speech
1363
+ )
1364
+
1365
+ target_device = up_proj.bias.device
1366
+ target_dtype = up_proj.bias.dtype
1367
+
1368
+ audio_input_features = audio_input_features.to(device=target_device, dtype=target_dtype)
1369
+
1370
+ audio_encoder_hidden_states = self.encoder(audio_input_features, audio_attention_mask)
1371
+ audio_encoder_hidden_states = up_proj(audio_encoder_hidden_states)
1372
+ audio_encoder_hidden_states = nn.functional.gelu(audio_encoder_hidden_states)
1373
+ audio_embeds = down_proj(audio_encoder_hidden_states)
1374
+
1375
+ merged_audio_embeds = torch.cat(
1376
+ [audio_embeds[i, : audio_embed_sizes[i], :] for i in range(len(audio_embed_sizes))], dim=0
1377
+ )
1378
+ merged_audio_embeds = merged_audio_embeds.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device)
1379
+ # Temporarily disable autocast to avoid issue on bf16 tensors
1380
+ # Ref: https://github.com/pytorch/pytorch/issues/132715
1381
+ with torch.autocast(device_type=inputs_embeds.device.type, enabled=False):
1382
+ audio_embeds = inputs_embeds.index_put(
1383
+ indices=positions_tuple, values=merged_audio_embeds, accumulate=False
1384
+ )
1385
+
1386
+ audio_embeds = self.drop(audio_embeds)
1387
+
1388
+ return audio_embeds
1389
+
1390
+
1391
+ #################################################### TEXT ####################################################
1392
+
1393
+
1394
+ class Phi4MultimodalRMSNorm(Phi3RMSNorm):
1395
+ pass
1396
+
1397
+
1398
+ class Phi4MultimodalDecoderLayer(Phi3DecoderLayer):
1399
+ pass
1400
+
1401
+
1402
+ class Phi4MultimodalFeatureEmbedding(nn.Module):
1403
+ """Image-audio embedding."""
1404
+
1405
+ def __init__(self, config: Phi4MultimodalConfig) -> None:
1406
+ super().__init__()
1407
+ self.config = config
1408
+ self.image_token_id = config.vision_config.image_token_id
1409
+ self.audio_token_id = config.audio_config.audio_token_id
1410
+ self.image_embed = Phi4MultimodalImageEmbedding(config)
1411
+ self.audio_embed = Phi4MultimodalAudioEmbedding(config)
1412
+
1413
+ def forward(
1414
+ self,
1415
+ input_ids: torch.LongTensor,
1416
+ inputs_embeds: torch.Tensor,
1417
+ image_pixel_values: Optional[torch.FloatTensor] = None,
1418
+ audio_input_features: Optional[torch.FloatTensor] = None,
1419
+ image_sizes=None,
1420
+ image_attention_mask=None,
1421
+ audio_embed_sizes=None,
1422
+ audio_attention_mask=None,
1423
+ ) -> torch.FloatTensor:
1424
+ with torch.no_grad():
1425
+ image_position_mask = (input_ids == self.config.vision_config.image_token_id).unsqueeze(-1)
1426
+ non_image_position_mask = ~image_position_mask
1427
+
1428
+ image_embeds = None
1429
+ audio_embeds = None
1430
+ if image_pixel_values is not None and (input_ids == self.image_token_id).any():
1431
+ image_embeds = self.image_embed(
1432
+ input_ids,
1433
+ inputs_embeds,
1434
+ image_pixel_values=image_pixel_values,
1435
+ image_sizes=image_sizes,
1436
+ image_attention_mask=image_attention_mask,
1437
+ )
1438
+ if audio_input_features is not None and (input_ids == self.audio_token_id).any():
1439
+ audio_projection_mode = "vision" if image_pixel_values is not None else "speech"
1440
+ audio_embeds = self.audio_embed(
1441
+ input_ids,
1442
+ inputs_embeds,
1443
+ audio_input_features=audio_input_features,
1444
+ audio_embed_sizes=audio_embed_sizes,
1445
+ audio_attention_mask=audio_attention_mask,
1446
+ audio_projection_mode=audio_projection_mode,
1447
+ )
1448
+
1449
+ # merge image and audio
1450
+ if image_embeds is not None and audio_embeds is not None:
1451
+ inputs_embeds = image_embeds * image_position_mask + audio_embeds * non_image_position_mask
1452
+ elif image_embeds is not None:
1453
+ inputs_embeds = image_embeds
1454
+ elif audio_embeds is not None:
1455
+ inputs_embeds = audio_embeds
1456
+
1457
+ return inputs_embeds
1458
+
1459
+
1460
+ PHI4_MULTIMODAL_MODEL_INPUTS_DOCSTRING = r"""
1461
+ Args:
1462
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1463
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1464
+ it.
1465
+
1466
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1467
+ [`PreTrainedTokenizer.__call__`] for details.
1468
+
1469
+ [What are input IDs?](../glossary#input-ids)
1470
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1471
+ Mask to avoid performing attention on padding indices in `input_values`. Mask values selected in `[0, 1]`:
1472
+ - 1 for tokens that are **not masked**,
1473
+ - 0 for tokens that are **masked**.
1474
+ [What are attention masks?](../glossary#attention-mask)
1475
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1476
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1477
+ config.n_positions - 1]`.
1478
+
1479
+ [What are position IDs?](../glossary#position-ids)
1480
+ past_key_values (`Cache`)`, *optional*):
1481
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1482
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1483
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1484
+ See our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
1485
+
1486
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1487
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1488
+ of shape `(batch_size, sequence_length)`.
1489
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1490
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1491
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1492
+ model's internal embedding lookup matrix.
1493
+ image_pixel_values (`torch.FloatTensor`, *optional*):
1494
+ If the input contains images, these correspond to the pixel values after transformations (as returned by
1495
+ the Processor)
1496
+ image_sizes (`torch.LongTensor`, *optional*):
1497
+ If the input contains images, these correspond to size of each image.
1498
+ image_attention_mask (`torch.LongTensor`, *optional*):
1499
+ Attention mask for the images.
1500
+ audio_input_features (`torch.FloatTensor`, *optional*):
1501
+ If the input contains audio samples, these correspond to the values after transformation (as returned by
1502
+ the Processor).
1503
+ audio_embed_sizes (`torch.Tensor`, *optional*):
1504
+ Size of the audio inputs.
1505
+ audio_attention_mask (`torch.Tensor, *optional*):
1506
+ Attention mask for the audio inputs.
1507
+ use_cache (`bool`, *optional*):
1508
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1509
+ `past_key_values`).
1510
+ output_attentions (`bool`, *optional*):
1511
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1512
+ tensors for more detail.
1513
+ output_hidden_states (`bool`, *optional*):
1514
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1515
+ more detail.
1516
+ return_dict (`bool`, *optional*):
1517
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1518
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1519
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1520
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1521
+ the complete sequence length.
1522
+ """
1523
+
1524
+
1525
+ class Phi4MultimodalRotaryEmbedding(Phi3RotaryEmbedding):
1526
+ pass
1527
+
1528
+
1529
+ class Phi4MultimodalPreTrainedModel(Phi3PreTrainedModel):
1530
+ def _init_weights(self, module):
1531
+ std = self.config.initializer_range
1532
+ if isinstance(module, nn.Linear):
1533
+ module.weight.data.normal_(mean=0.0, std=std)
1534
+ if module.bias is not None:
1535
+ module.bias.data.zero_()
1536
+ elif isinstance(module, nn.Embedding):
1537
+ module.weight.data.normal_(mean=0.0, std=std)
1538
+ if module.padding_idx is not None:
1539
+ module.weight.data[module.padding_idx].zero_()
1540
+ elif isinstance(module, Phi4MultimodalRMSNorm):
1541
+ module.weight.data.fill_(1.0)
1542
+ elif isinstance(module, Phi4MultimodalImageEmbedding):
1543
+ module.global_img_feature_extensor.data.zero_()
1544
+ module.sub_img_feature_extensor.data.zero_()
1545
+
1546
+
1547
+ class Phi4MultimodalModel(Phi3Model, nn.Module):
1548
+ """
1549
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi4MultimodalMMDecoderLayer`]
1550
+ Args:
1551
+ config: Phi4MultimodalMMConfig
1552
+ """
1553
+
1554
+ def __init__(self, config: Phi4MultimodalConfig):
1555
+ super().__init__(config)
1556
+ self.padding_idx = config.pad_token_id
1557
+ self.vocab_size = config.vocab_size
1558
+
1559
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1560
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1561
+
1562
+ self.embed_tokens_extend = Phi4MultimodalFeatureEmbedding(config)
1563
+
1564
+ self.layers = nn.ModuleList(
1565
+ [Phi4MultimodalDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1566
+ )
1567
+ self.norm = Phi4MultimodalRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1568
+
1569
+ self.gradient_checkpointing = False
1570
+ # Initialize weights and apply final processing
1571
+ self.post_init()
1572
+
1573
+ @can_return_tuple
1574
+ @add_start_docstrings_to_model_forward(PHI4_MULTIMODAL_MODEL_INPUTS_DOCSTRING)
1575
+ def forward(
1576
+ self,
1577
+ input_ids: Optional[torch.LongTensor] = None,
1578
+ attention_mask: Optional[torch.Tensor] = None,
1579
+ position_ids: Optional[torch.LongTensor] = None,
1580
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1581
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1582
+ image_pixel_values: Optional[torch.FloatTensor] = None,
1583
+ image_sizes: Optional[torch.LongTensor] = None,
1584
+ image_attention_mask=None,
1585
+ audio_input_features: Optional[torch.FloatTensor] = None,
1586
+ audio_embed_sizes=None,
1587
+ audio_attention_mask=None,
1588
+ use_cache: Optional[bool] = None,
1589
+ output_attentions: Optional[bool] = None,
1590
+ output_hidden_states: Optional[bool] = None,
1591
+ cache_position: Optional[torch.LongTensor] = None,
1592
+ **kwargs,
1593
+ ) -> BaseModelOutputWithPast:
1594
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1595
+ output_hidden_states = (
1596
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1597
+ )
1598
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1599
+
1600
+ if (input_ids is None) ^ (inputs_embeds is not None):
1601
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1602
+
1603
+ if self.gradient_checkpointing and self.training:
1604
+ if use_cache:
1605
+ logger.warning_once(
1606
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1607
+ )
1608
+ use_cache = False
1609
+
1610
+ if use_cache and past_key_values is None:
1611
+ past_key_values = DynamicCache()
1612
+
1613
+ if inputs_embeds is None:
1614
+ inputs_embeds = self.embed_tokens(input_ids)
1615
+ inputs_embeds = self.embed_tokens_extend(
1616
+ input_ids,
1617
+ inputs_embeds,
1618
+ image_pixel_values=image_pixel_values,
1619
+ audio_input_features=audio_input_features,
1620
+ image_sizes=image_sizes,
1621
+ image_attention_mask=image_attention_mask,
1622
+ audio_embed_sizes=audio_embed_sizes,
1623
+ audio_attention_mask=audio_attention_mask,
1624
+ )
1625
+
1626
+ if cache_position is None:
1627
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1628
+ cache_position = torch.arange(
1629
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1630
+ )
1631
+ if position_ids is None:
1632
+ position_ids = cache_position.unsqueeze(0)
1633
+
1634
+ causal_mask = self._update_causal_mask(
1635
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1636
+ )
1637
+
1638
+ hidden_states = inputs_embeds
1639
+
1640
+ # create position embeddings to be shared across the decoder layers
1641
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1642
+
1643
+ # decoder layers
1644
+ all_hidden_states = () if output_hidden_states else None
1645
+ all_self_attns = () if output_attentions else None
1646
+
1647
+ for decoder_layer in self.layers:
1648
+ if output_hidden_states:
1649
+ all_hidden_states += (hidden_states,)
1650
+
1651
+ layer_outputs = decoder_layer(
1652
+ hidden_states,
1653
+ attention_mask=causal_mask,
1654
+ position_ids=position_ids,
1655
+ past_key_value=past_key_values,
1656
+ output_attentions=output_attentions,
1657
+ use_cache=use_cache,
1658
+ cache_position=cache_position,
1659
+ position_embeddings=position_embeddings,
1660
+ **kwargs,
1661
+ )
1662
+
1663
+ hidden_states = layer_outputs[0]
1664
+
1665
+ if output_attentions:
1666
+ all_self_attns += (layer_outputs[1],)
1667
+
1668
+ hidden_states = self.norm(hidden_states)
1669
+
1670
+ # add hidden states from the last decoder layer
1671
+ if output_hidden_states:
1672
+ all_hidden_states += (hidden_states,)
1673
+
1674
+ return BaseModelOutputWithPast(
1675
+ last_hidden_state=hidden_states,
1676
+ past_key_values=past_key_values if use_cache else None,
1677
+ hidden_states=all_hidden_states,
1678
+ attentions=all_self_attns,
1679
+ )
1680
+
1681
+
1682
+ class Phi4MultimodalForCausalLM(Phi3ForCausalLM, nn.Module):
1683
+ _tied_weights_keys = ["lm_head.weight"]
1684
+
1685
+ def __init__(self, config):
1686
+ super().__init__(config)
1687
+ self.model = Phi4MultimodalModel(config)
1688
+ self.vocab_size = config.vocab_size
1689
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1690
+
1691
+ # Initialize weights and apply final processing
1692
+ self.post_init()
1693
+
1694
+ @can_return_tuple
1695
+ @add_start_docstrings_to_model_forward(PHI4_MULTIMODAL_MODEL_INPUTS_DOCSTRING)
1696
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=Phi4MultimodalConfig)
1697
+ def forward(
1698
+ self,
1699
+ input_ids: Optional[torch.LongTensor] = None,
1700
+ attention_mask: Optional[torch.Tensor] = None,
1701
+ position_ids: Optional[torch.LongTensor] = None,
1702
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1703
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1704
+ image_pixel_values: Optional[torch.FloatTensor] = None,
1705
+ image_sizes: Optional[torch.LongTensor] = None,
1706
+ image_attention_mask=None,
1707
+ audio_input_features: Optional[torch.FloatTensor] = None,
1708
+ audio_embed_sizes=None,
1709
+ audio_attention_mask=None,
1710
+ labels: Optional[torch.LongTensor] = None,
1711
+ use_cache: Optional[bool] = None,
1712
+ output_attentions: Optional[bool] = None,
1713
+ output_hidden_states: Optional[bool] = None,
1714
+ cache_position: Optional[torch.LongTensor] = None,
1715
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1716
+ **kwargs,
1717
+ ) -> CausalLMOutputWithPast:
1718
+ r"""
1719
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1720
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1721
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1722
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1723
+
1724
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
1725
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
1726
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1727
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1728
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
1729
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
1730
+ Returns:
1731
+
1732
+ Example:
1733
+ ```python
1734
+ >>> from transformers import AutoTokenizer, Phi4MultimodalForCausalLM
1735
+ >>> model = Phi4MultimodalForCausalLM.from_pretrained("TBA")
1736
+ >>> tokenizer = AutoTokenizer.from_pretrained("TBA")
1737
+ >>> prompt = "This is an example script ."
1738
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1739
+ >>> # Generate
1740
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1741
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1742
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1743
+ ```"""
1744
+
1745
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1746
+ output_hidden_states = (
1747
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1748
+ )
1749
+
1750
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1751
+ outputs: BaseModelOutputWithPast = self.model(
1752
+ input_ids=input_ids,
1753
+ attention_mask=attention_mask,
1754
+ position_ids=position_ids,
1755
+ past_key_values=past_key_values,
1756
+ inputs_embeds=inputs_embeds,
1757
+ image_pixel_values=image_pixel_values,
1758
+ image_sizes=image_sizes,
1759
+ image_attention_mask=image_attention_mask,
1760
+ audio_input_features=audio_input_features,
1761
+ audio_embed_sizes=audio_embed_sizes,
1762
+ audio_attention_mask=audio_attention_mask,
1763
+ use_cache=use_cache,
1764
+ output_attentions=output_attentions,
1765
+ output_hidden_states=output_hidden_states,
1766
+ cache_position=cache_position,
1767
+ **kwargs,
1768
+ )
1769
+
1770
+ hidden_states = outputs.last_hidden_state
1771
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1772
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1773
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1774
+
1775
+ loss = None
1776
+ if labels is not None:
1777
+ loss = self.loss_function(logits, labels, self.vocab_size)
1778
+
1779
+ return CausalLMOutputWithPast(
1780
+ loss=loss,
1781
+ logits=logits,
1782
+ past_key_values=outputs.past_key_values,
1783
+ hidden_states=outputs.hidden_states,
1784
+ attentions=outputs.attentions,
1785
+ )
1786
+
1787
+ def prepare_inputs_for_generation(
1788
+ self,
1789
+ input_ids,
1790
+ past_key_values=None,
1791
+ attention_mask=None,
1792
+ inputs_embeds=None,
1793
+ image_pixel_values=None,
1794
+ image_sizes=None,
1795
+ image_attention_mask=None,
1796
+ audio_input_features=None,
1797
+ audio_embed_sizes=None,
1798
+ audio_attention_mask=None,
1799
+ cache_position=None,
1800
+ position_ids=None,
1801
+ use_cache=True,
1802
+ logits_to_keep=0,
1803
+ **kwargs,
1804
+ ):
1805
+ # Overwritten -- this model may need to switch between short and long rope, invalidating the cache in the
1806
+ # process
1807
+
1808
+ # When the first time input length reached long and short factor switching point, enforce re-compute cache
1809
+ # It will cause downside of slower at this single token position, however, better than current failure.
1810
+ if (
1811
+ past_key_values
1812
+ and self.config.rope_scaling
1813
+ and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1
1814
+ ):
1815
+ past_length = cache_position[0]
1816
+ if past_length <= self.config.original_max_position_embeddings:
1817
+ past_key_values = None
1818
+
1819
+ model_inputs = super().prepare_inputs_for_generation(
1820
+ input_ids=input_ids,
1821
+ past_key_values=past_key_values,
1822
+ attention_mask=attention_mask,
1823
+ inputs_embeds=inputs_embeds,
1824
+ image_pixel_values=image_pixel_values,
1825
+ image_sizes=image_sizes,
1826
+ image_attention_mask=image_attention_mask,
1827
+ audio_input_features=audio_input_features,
1828
+ audio_embed_sizes=audio_embed_sizes,
1829
+ audio_attention_mask=audio_attention_mask,
1830
+ cache_position=cache_position,
1831
+ position_ids=position_ids,
1832
+ use_cache=use_cache,
1833
+ logits_to_keep=logits_to_keep,
1834
+ **kwargs,
1835
+ )
1836
+ return model_inputs
1837
+
1838
+
1839
+ __all__ = [
1840
+ "Phi4MultimodalAudioPreTrainedModel",
1841
+ "Phi4MultimodalAudioModel",
1842
+ "Phi4MultimodalVisionPreTrainedModel",
1843
+ "Phi4MultimodalVisionModel",
1844
+ "Phi4MultimodalPreTrainedModel",
1845
+ "Phi4MultimodalModel",
1846
+ "Phi4MultimodalForCausalLM",
1847
+ "Phi4MultimodalVisionConfig",
1848
+ "Phi4MultimodalAudioConfig",
1849
+ "Phi4MultimodalConfig",
1850
+ ]
docs/transformers/build/lib/transformers/models/phi4_multimodal/processing_phi4_multimodal.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Microsoft and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Processor class for Phi4Multimodal
17
+ """
18
+
19
+ import re
20
+ from typing import List, Optional, Union
21
+
22
+ from ...audio_utils import AudioInput
23
+ from ...image_processing_utils import BatchFeature
24
+ from ...image_utils import ImageInput
25
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
26
+ from ...tokenization_utils_base import TextInput
27
+ from ...utils import logging
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ class Phi4MultimodalProcessorKwargs(ProcessingKwargs, total=False):
34
+ _defaults = {
35
+ "audio_kwargs": {
36
+ "device": "cpu",
37
+ },
38
+ }
39
+
40
+
41
+ class Phi4MultimodalProcessor(ProcessorMixin):
42
+ r"""
43
+ Constructs a Phi4Multimodal processor which raps an image processor, a audio processor, and a GPT tokenizer into a single processor.
44
+
45
+ [`Phi4MultimodalProcessor`] offers all the functionalities of [`Phi4MultimodalImageProcessorFast`] and [`GPT2Tokenizer`]. See the
46
+ [`~Phi4MultimodalProcessor.__call__`] and [`~Phi4MultimodalProcessor.decode`] for more information.
47
+
48
+ Args:
49
+ image_processor (`Phi4MultimodalImageProcessorFast`):
50
+ The image processor to use for images.
51
+ audio_processor (`Phi4MultimodalFeatureExtractor`):
52
+ The audio processor to use for audio inputs.
53
+ tokenizer (`GPT2TokenizerFast`):
54
+ The tokenizer to use for text.
55
+ fake_image_token_pattern (`str`, *optional*, defaults to `r"<\|image_\d+\|>"`):
56
+ The fake image token pattern.
57
+ fake_audio_token_pattern (`str`, *optional*, defaults to `r"<\|audio_\d+\|>"`):
58
+ The fake audio token pattern.
59
+ """
60
+
61
+ attributes = ["image_processor", "audio_processor", "tokenizer"]
62
+ tokenizer_class = "GPT2TokenizerFast"
63
+ image_processor_class = "Phi4MultimodalImageProcessorFast"
64
+ audio_processor_class = "Phi4MultimodalFeatureExtractor"
65
+ valid_kwargs = ["chat_template"]
66
+
67
+ def __init__(
68
+ self,
69
+ image_processor,
70
+ audio_processor,
71
+ tokenizer,
72
+ **kwargs,
73
+ ):
74
+ self.image_token = tokenizer.image_token
75
+ self.image_token_id = tokenizer.image_token_id
76
+ self.audio_token = tokenizer.audio_token
77
+ self.audio_token_id = tokenizer.audio_token_id
78
+ super().__init__(image_processor, audio_processor, tokenizer, **kwargs)
79
+
80
+ def __call__(
81
+ self,
82
+ text: Union[TextInput, List[TextInput]],
83
+ images: Optional[ImageInput] = None,
84
+ audio: Optional[AudioInput] = None,
85
+ **kwargs: Unpack[ProcessingKwargs],
86
+ ) -> BatchFeature:
87
+ """
88
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forards the `text`
89
+ and `kwargs` arguments to GPT2Tokenizer's [`~GPT2Tokenizer.__call__`] if `text` is not `None` to encode
90
+ the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
91
+ Phi4MultimodalImageProcessorFast's [`~Phi4MultimodalImageProcessorFast.__call__`] if `images` is not `None`. Please refer to the doctsring
92
+ of the above two methods for more information.
93
+
94
+ Args:
95
+ text (`str`, `List[str]`, `List[List[str]]`):
96
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
97
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
98
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
99
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
100
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
101
+ tensor. Both channels-first and channels-last formats are supported.
102
+ audio (`List[Union[np.ndarray, torch.Tensor]]`):
103
+ List of the audios to be prepared.
104
+
105
+ Returns:
106
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
107
+
108
+ - **input_ids** -- List of token ids to be fed to a model.
109
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model.
110
+ - **input_image_embeds** -- Pixel values to be fed to a model.
111
+ - **image_sizes** -- List of tuples specifying the size of each image in `input_image_embeds`.
112
+ - **image_attention_mask** -- List of attention masks for each image in `input_image_embeds`.
113
+ - **input_audio_embeds** -- Audio embeddings to be fed to a model.
114
+ - **audio_embed_sizes** -- List of integers specifying the size of each audio in `input_audio_embeds`.
115
+ """
116
+
117
+ output_kwargs = self._merge_kwargs(Phi4MultimodalProcessorKwargs, self.tokenizer.init_kwargs, **kwargs)
118
+ image_kwargs = output_kwargs["images_kwargs"]
119
+ audio_kwargs = output_kwargs["audio_kwargs"]
120
+
121
+ image_inputs = self.image_processor(images, **image_kwargs) if images is not None else {}
122
+ audio_inputs = self.audio_processor(audio, **audio_kwargs) if audio is not None else {}
123
+
124
+ # We pop here for images as we don't need it later
125
+ num_img_tokens = image_inputs.pop("num_img_tokens", [])
126
+ audio_embed_sizes = audio_inputs.get("audio_embed_sizes", [])
127
+
128
+ # Replace certain special tokens for compatibility
129
+ if isinstance(text, str):
130
+ text = [text]
131
+ elif not isinstance(text, list) and not isinstance(text[0], str):
132
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
133
+
134
+ image_token = self.tokenizer.image_token
135
+ audio_token = self.tokenizer.audio_token
136
+
137
+ # Check that the number of special tokens is sound
138
+ concatenated_prompt = "".join(text)
139
+ if concatenated_prompt.count(image_token) != len(num_img_tokens):
140
+ raise ValueError(
141
+ "You should add as much image tokens `<|image|>` in your prompt as you pass `images` to the processor. ",
142
+ f"Input contains {concatenated_prompt.count(image_token)} tokens != {len(num_img_tokens)} images",
143
+ )
144
+ if concatenated_prompt.count(audio_token) != len(audio_embed_sizes):
145
+ raise ValueError(
146
+ "You should add as much audio tokens `<|audio|>` in your prompt as you pass `audios` to the processor. "
147
+ f"Input contains {concatenated_prompt.count(audio_token)} tokens != {len(audio_embed_sizes)} audios"
148
+ )
149
+
150
+ # Add appropriate number of image/audio tokens (note that the count of replacement is dynamic)
151
+ image_count_iter = iter(num_img_tokens)
152
+ audio_count_iter = iter(audio_embed_sizes)
153
+ processed_text = [
154
+ re.sub(re.escape(image_token), lambda _: image_token * next(image_count_iter), t) for t in text
155
+ ]
156
+ processed_text = [
157
+ re.sub(re.escape(audio_token), lambda _: audio_token * next(audio_count_iter), t) for t in processed_text
158
+ ]
159
+
160
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
161
+ text_inputs = self.tokenizer(processed_text, **output_kwargs["text_kwargs"])
162
+ self._check_special_mm_tokens(processed_text, text_inputs, modalities=["image"])
163
+
164
+ # prepare batch feature
165
+ data = {
166
+ **text_inputs,
167
+ **image_inputs,
168
+ **audio_inputs,
169
+ }
170
+
171
+ return BatchFeature(data=data, tensor_type=return_tensors)
172
+
173
+ def batch_decode(self, *args, **kwargs):
174
+ """
175
+ This method forwards all its arguments to GPT2Tokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
176
+ refer to the docstring of this method for more information.
177
+ """
178
+ return self.tokenizer.batch_decode(*args, **kwargs)
179
+
180
+ def decode(self, *args, **kwargs):
181
+ """
182
+ This method forwards all its arguments to GPT2Tokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
183
+ the docstring of this method for more information.
184
+ """
185
+ return self.tokenizer.decode(*args, **kwargs)
186
+
187
+ @property
188
+ def model_input_names(self):
189
+ tokenizer_input_names = self.tokenizer.model_input_names
190
+ image_processor_input_names = self.image_processor.model_input_names
191
+ audio_processor_input_names = self.audio_processor.model_input_names
192
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names + audio_processor_input_names))
193
+
194
+
195
+ __all__ = ["Phi4MultimodalProcessor"]
docs/transformers/build/lib/transformers/models/phimoe/configuration_phimoe.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft 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
+
16
+ """PyTorch Phi-MoE model."""
17
+
18
+ from ...configuration_utils import PretrainedConfig
19
+ from ...modeling_rope_utils import rope_config_validation
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class PhimoeConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`PhimoeModel`]. It is used to instantiate a Phi-moe
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the
31
+ [microsoft/Phi-3.5-MoE-instruct](https://huggingface.co/microsoft/Phi-3.5-MoE-instruct).
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 32064):
36
+ Vocabulary size of the Phimoe model. Defines the number of different tokens that can be represented by the
37
+ `inputs_ids` passed when calling [`PhimoeModel`]
38
+ hidden_size (`int`, *optional*, defaults to 4096):
39
+ Dimension of the hidden representations.
40
+ intermediate_size (`int`, *optional*, defaults to 6400):
41
+ Dimension of the MLP representations.
42
+ num_hidden_layers (`int`, *optional*, defaults to 32):
43
+ Number of hidden layers in the Transformer encoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 32):
45
+ Number of attention heads for each attention layer in the Transformer encoder.
46
+ num_key_value_heads (`int`, *optional*, defaults to 8):
47
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
48
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
49
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
50
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
51
+ by meanpooling all the original heads within that group. For more details checkout [this
52
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.
53
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
54
+ The non-linear activation function (function or string) in the decoder.
55
+ max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
56
+ The maximum sequence length that this model might ever be used with. Mixtral's sliding window attention
57
+ allows sequence of up to 4096*32 tokens.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ pad_token_id (`int`, *optional*):
66
+ The id of the padding token.
67
+ bos_token_id (`int`, *optional*, defaults to 1):
68
+ The id of the "beginning-of-sequence" token.
69
+ eos_token_id (`int`, *optional*, defaults to 2):
70
+ The id of the "end-of-sequence" token.
71
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
72
+ Whether the model's input and output word embeddings should be tied.
73
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
74
+ The base period of the RoPE embeddings.
75
+ rope_scaling (`dict`, *optional*):
76
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
77
+ contain the following keys: `type`, `short_factor`, `long_factor`, `short_mscale`, `long_mscale` and
78
+ `original_max_position_embeddings`. The `type` must be `longrope`, the `short_mscale` and `long_scale` must
79
+ be numbers, the `short_factor` and `long_factor` must be lists of numbers with the same length as half of
80
+ the attention head size and the `original_max_position_embeddings` must be an integer.
81
+ sliding_window (`int`, *optional*):
82
+ Sliding window attention window size. If not specified, will default to `262144`.
83
+ attention_dropout (`float`, *optional*, defaults to 0.0):
84
+ The dropout ratio for the attention probabilities.
85
+ num_experts_per_tok (`int`, *optional*, defaults to 2):
86
+ The number of experts to root per-token, can be also interpreted as the `top-p` routing
87
+ parameter
88
+ num_local_experts (`int`, *optional*, defaults to 16):
89
+ Number of experts per Sparse MLP layer.
90
+ output_router_logits (`bool`, *optional*, defaults to `False`):
91
+ Whether or not the router logits should be returned by the model. Enabling this will also
92
+ allow the model to output the auxiliary loss. See [here]() for more details
93
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
94
+ The aux loss factor for the total loss.
95
+ router_jitter_noise (`float`, *optional*, defaults to 0.01):
96
+ Amount of noise to add to the router.
97
+ input_jitter_noise (`float`, *optional*, defaults to 0.0): Input jitter noise
98
+ attention_bias (`bool`, *optional*, defaults to `False`): Attention bias
99
+ lm_head_bias (`bool`, *optional*, defaults to `False`): LM head bias
100
+
101
+ Example:
102
+
103
+ ```python
104
+ >>> from transformers import PhimoeModel, PhimoeConfig
105
+ >>> # Initializing a Phi-3 style configuration
106
+ >>> configuration = PhimoeConfig.from_pretrained("microsoft/Phi-3.5-MoE-instruct")
107
+ >>> # Initializing a model from the configuration
108
+ >>> model = PhimoeModel(configuration)
109
+ >>> # Accessing the model configuration
110
+ >>> configuration = model.config
111
+ ```"""
112
+
113
+ model_type = "phimoe"
114
+ keys_to_ignore_at_inference = ["past_key_values"]
115
+
116
+ def __init__(
117
+ self,
118
+ vocab_size=32064,
119
+ hidden_size=4096,
120
+ intermediate_size=6400,
121
+ num_hidden_layers=32,
122
+ num_attention_heads=32,
123
+ num_key_value_heads=8,
124
+ hidden_act="silu",
125
+ max_position_embeddings=4096 * 32,
126
+ initializer_range=0.02,
127
+ rms_norm_eps=1e-5,
128
+ use_cache=True,
129
+ pad_token_id=None,
130
+ bos_token_id=1,
131
+ eos_token_id=2,
132
+ tie_word_embeddings=False,
133
+ rope_theta=1e6,
134
+ rope_scaling=None,
135
+ sliding_window=None,
136
+ attention_dropout=0.0,
137
+ num_experts_per_tok=2,
138
+ num_local_experts=16,
139
+ output_router_logits=False,
140
+ router_aux_loss_coef=0.001,
141
+ router_jitter_noise=0.01,
142
+ input_jitter_noise=0.0,
143
+ attention_bias=False,
144
+ lm_head_bias=False,
145
+ **kwargs,
146
+ ):
147
+ self.vocab_size = vocab_size
148
+ self.max_position_embeddings = max_position_embeddings
149
+ self.hidden_size = hidden_size
150
+ self.intermediate_size = intermediate_size
151
+ self.num_hidden_layers = num_hidden_layers
152
+ self.num_attention_heads = num_attention_heads
153
+ self.sliding_window = sliding_window
154
+ self.attention_bias = attention_bias
155
+ self.lm_head_bias = lm_head_bias
156
+ # for backward compatibility
157
+ if num_key_value_heads is None:
158
+ num_key_value_heads = num_attention_heads
159
+
160
+ self.num_key_value_heads = num_key_value_heads
161
+ self.hidden_act = hidden_act
162
+ self.initializer_range = initializer_range
163
+ self.rms_norm_eps = rms_norm_eps
164
+ self.use_cache = use_cache
165
+ self.rope_theta = rope_theta
166
+ self.attention_dropout = attention_dropout
167
+
168
+ self.num_experts_per_tok = num_experts_per_tok
169
+ self.num_local_experts = num_local_experts
170
+ self.output_router_logits = output_router_logits
171
+ self.router_aux_loss_coef = router_aux_loss_coef
172
+ self.router_jitter_noise = router_jitter_noise
173
+ self.input_jitter_noise = input_jitter_noise
174
+
175
+ self.rope_scaling = rope_scaling
176
+ if isinstance(self.rope_scaling, dict):
177
+ if "rope_type" not in self.rope_scaling:
178
+ self.rope_scaling["rope_type"] = self.rope_scaling.get("type", None)
179
+ if "original_max_position_embeddings" in self.rope_scaling:
180
+ self.original_max_position_embeddings = self.rope_scaling["original_max_position_embeddings"]
181
+ rope_scaling_short_mscale = self.rope_scaling.get("short_mscale", None)
182
+ rope_scaling_long_mscale = self.rope_scaling.get("long_mscale", None)
183
+ if not isinstance(rope_scaling_short_mscale, (int, float)):
184
+ raise ValueError(
185
+ f"`rope_scaling`'s short_mscale field must be a number, got {rope_scaling_short_mscale}"
186
+ )
187
+ if not isinstance(rope_scaling_long_mscale, (int, float)):
188
+ raise ValueError(
189
+ f"`rope_scaling`'s long_mscale field must be a number, got {rope_scaling_long_mscale}"
190
+ )
191
+
192
+ rope_config_validation(self)
193
+
194
+ super().__init__(
195
+ pad_token_id=pad_token_id,
196
+ bos_token_id=bos_token_id,
197
+ eos_token_id=eos_token_id,
198
+ tie_word_embeddings=tie_word_embeddings,
199
+ **kwargs,
200
+ )
201
+
202
+
203
+ __all__ = ["PhimoeConfig"]
docs/transformers/build/lib/transformers/models/phimoe/modeling_phimoe.py ADDED
@@ -0,0 +1,1627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft 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
+
16
+ """PyTorch Phimoe model."""
17
+
18
+ import math
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+
25
+ from ...activations import ACT2FN
26
+ from ...cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
27
+ from ...generation import GenerationMixin
28
+ from ...modeling_attn_mask_utils import AttentionMaskConverter, _prepare_4d_causal_attention_mask
29
+ from ...modeling_flash_attention_utils import is_flash_attn_available
30
+ from ...modeling_outputs import (
31
+ MoeCausalLMOutputWithPast,
32
+ MoeModelOutputWithPast,
33
+ SequenceClassifierOutputWithPast,
34
+ )
35
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
36
+ from ...modeling_utils import PreTrainedModel
37
+ from ...utils import (
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ can_return_tuple,
41
+ is_torch_flex_attn_available,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from .configuration_phimoe import PhimoeConfig
46
+
47
+
48
+ if is_flash_attn_available():
49
+ from ...modeling_flash_attention_utils import _flash_attention_forward
50
+
51
+ if is_torch_flex_attn_available():
52
+ from torch.nn.attention.flex_attention import BlockMask
53
+
54
+ from ...integrations.flex_attention import make_flex_block_causal_mask
55
+
56
+
57
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
58
+ # It means that the function will not be traced through and simply appear as a node in the graph.
59
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
60
+
61
+
62
+ logger = logging.get_logger(__name__)
63
+
64
+ _CONFIG_FOR_DOC = "PhimoeConfig"
65
+
66
+
67
+ # Copied from transformers.models.mixtral.modeling_mixtral.load_balancing_loss_func
68
+ def load_balancing_loss_func(
69
+ gate_logits: Union[torch.Tensor, Tuple[torch.Tensor], None],
70
+ num_experts: Optional[int] = None,
71
+ top_k=2,
72
+ attention_mask: Optional[torch.Tensor] = None,
73
+ ) -> Union[torch.Tensor, int]:
74
+ r"""
75
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
76
+
77
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
78
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
79
+ experts is too unbalanced.
80
+
81
+ Args:
82
+ gate_logits:
83
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
84
+ shape [batch_size X sequence_length, num_experts].
85
+ num_experts:
86
+ Number of experts
87
+ top_k:
88
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
89
+ parameter.
90
+ attention_mask (`torch.Tensor`, *optional*):
91
+ The attention_mask used in forward function
92
+ shape [batch_size X sequence_length] if not None.
93
+
94
+ Returns:
95
+ The auxiliary loss.
96
+ """
97
+ if gate_logits is None or not isinstance(gate_logits, tuple):
98
+ return 0
99
+
100
+ if isinstance(gate_logits, tuple):
101
+ compute_device = gate_logits[0].device
102
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
103
+
104
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
105
+
106
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
107
+
108
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
109
+
110
+ if attention_mask is None:
111
+ # Compute the percentage of tokens routed to each experts
112
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
113
+
114
+ # Compute the average probability of routing to these experts
115
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
116
+ else:
117
+ batch_size, sequence_length = attention_mask.shape
118
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
119
+
120
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
121
+ expert_attention_mask = (
122
+ attention_mask[None, :, :, None, None]
123
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
124
+ .reshape(-1, top_k, num_experts)
125
+ .to(compute_device)
126
+ )
127
+
128
+ # Compute the percentage of tokens routed to each experts
129
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
130
+ expert_attention_mask, dim=0
131
+ )
132
+
133
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
134
+ router_per_expert_attention_mask = (
135
+ attention_mask[None, :, :, None]
136
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
137
+ .reshape(-1, num_experts)
138
+ .to(compute_device)
139
+ )
140
+
141
+ # Compute the average probability of routing to these experts
142
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
143
+ router_per_expert_attention_mask, dim=0
144
+ )
145
+
146
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
147
+ return overall_loss * num_experts
148
+
149
+
150
+ class PhimoeRotaryEmbedding(nn.Module):
151
+ def __init__(
152
+ self,
153
+ config: Optional[PhimoeConfig] = None,
154
+ ):
155
+ super().__init__()
156
+
157
+ self.config = config
158
+ if config.rope_scaling is not None:
159
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
160
+ self.short_mscale = config.rope_scaling.get("short_mscale")
161
+ self.long_mscale = config.rope_scaling.get("long_mscale")
162
+ else:
163
+ self.rope_type = "default"
164
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
165
+
166
+ def forward(self, x, seq_len=None):
167
+ mscale = None
168
+ if self.config.rope_scaling and seq_len:
169
+ mscale = (
170
+ self.long_mscale
171
+ if seq_len > self.config.rope_scaling["original_max_position_embeddings"]
172
+ else self.short_mscale
173
+ )
174
+ inv_freq, attention_scaling = self.rope_init_fn(self.config, x.device, seq_len)
175
+ mscale = attention_scaling if mscale is None else mscale
176
+ t = torch.arange(seq_len, device=x.device, dtype=torch.float32)
177
+ freqs = torch.outer(t, inv_freq)
178
+
179
+ emb = torch.cat((freqs, freqs), dim=-1)
180
+ return (emb.cos() * mscale).to(x.dtype), (emb.sin() * mscale).to(x.dtype)
181
+
182
+
183
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
184
+ def rotate_half(x):
185
+ """Rotates half the hidden dims of the input."""
186
+ x1 = x[..., : x.shape[-1] // 2]
187
+ x2 = x[..., x.shape[-1] // 2 :]
188
+ return torch.cat((-x2, x1), dim=-1)
189
+
190
+
191
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
192
+ """Applies Rotary Position Embedding to the query and key tensors.
193
+
194
+ Args:
195
+ q (`torch.Tensor`): The query tensor.
196
+ k (`torch.Tensor`): The key tensor.
197
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
198
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
199
+ position_ids (`torch.Tensor`):
200
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
201
+ used to pass offsetted position ids when working with a KV-cache.
202
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
203
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
204
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
205
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
206
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
207
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
208
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
209
+ Returns:
210
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
211
+ """
212
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
213
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
214
+ q_embed = (q * cos) + (rotate_half(q) * sin)
215
+ k_embed = (k * cos) + (rotate_half(k) * sin)
216
+ return q_embed, k_embed
217
+
218
+
219
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
220
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
221
+ """
222
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
223
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
224
+ """
225
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
226
+ if n_rep == 1:
227
+ return hidden_states
228
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
229
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
230
+
231
+
232
+ class PhimoeAttention(nn.Module):
233
+ """
234
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
235
+ and "Generating Long Sequences with Sparse Transformers".
236
+ """
237
+
238
+ def __init__(self, config: PhimoeConfig, layer_idx: Optional[int] = None):
239
+ super().__init__()
240
+ self.config = config
241
+ self.layer_idx = layer_idx
242
+ if layer_idx is None:
243
+ logger.warning_once(
244
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
245
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
246
+ "when creating this class."
247
+ )
248
+
249
+ self.hidden_size = config.hidden_size
250
+ self.num_heads = config.num_attention_heads
251
+ self.head_dim = self.hidden_size // self.num_heads
252
+ self.num_key_value_heads = config.num_key_value_heads
253
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
254
+ self.max_position_embeddings = config.max_position_embeddings
255
+ self.rope_theta = config.rope_theta
256
+ self.is_causal = True
257
+ self.attention_dropout = config.attention_dropout
258
+
259
+ if (self.head_dim * self.num_heads) != self.hidden_size:
260
+ raise ValueError(
261
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
262
+ f" and `num_heads`: {self.num_heads})."
263
+ )
264
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=self.config.attention_bias)
265
+ self.k_proj = nn.Linear(
266
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.config.attention_bias
267
+ )
268
+ self.v_proj = nn.Linear(
269
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.config.attention_bias
270
+ )
271
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=self.config.attention_bias)
272
+
273
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
274
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
275
+
276
+ def forward(
277
+ self,
278
+ hidden_states: torch.Tensor,
279
+ attention_mask: Optional[torch.Tensor] = None,
280
+ position_ids: Optional[torch.LongTensor] = None,
281
+ past_key_value: Optional[Cache] = None,
282
+ output_attentions: bool = False,
283
+ use_cache: bool = False,
284
+ cache_position: Optional[torch.LongTensor] = None,
285
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
286
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
287
+ bsz, q_len, _ = hidden_states.size()
288
+
289
+ query_states = self.q_proj(hidden_states)
290
+ key_states = self.k_proj(hidden_states)
291
+ value_states = self.v_proj(hidden_states)
292
+
293
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
294
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
295
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
296
+
297
+ cos, sin = position_embeddings
298
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
299
+
300
+ if past_key_value is not None:
301
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
302
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
303
+
304
+ # repeat k/v heads if n_kv_heads < n_heads
305
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
306
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
307
+
308
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
309
+
310
+ if attention_mask is not None: # no matter the length, we just slice it
311
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
312
+ attn_weights = attn_weights + causal_mask
313
+
314
+ # upcast attention to fp32
315
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
316
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
317
+ attn_output = torch.matmul(attn_weights, value_states)
318
+
319
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
320
+ raise ValueError(
321
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
322
+ f" {attn_output.size()}"
323
+ )
324
+
325
+ attn_output = attn_output.transpose(1, 2).contiguous()
326
+
327
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
328
+
329
+ attn_output = self.o_proj(attn_output)
330
+
331
+ if not output_attentions:
332
+ attn_weights = None
333
+
334
+ return attn_output, attn_weights, past_key_value
335
+
336
+
337
+ class PhimoeFlashAttention2(PhimoeAttention):
338
+ """
339
+ Phimoe flash attention module. This module inherits from `PhimoeAttention` as the weights of the module stays
340
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
341
+ flash attention and deal with padding tokens in case the input contains any of them.
342
+ """
343
+
344
+ def forward(
345
+ self,
346
+ hidden_states: torch.Tensor,
347
+ attention_mask: Optional[torch.Tensor] = None,
348
+ position_ids: Optional[torch.LongTensor] = None,
349
+ past_key_value: Optional[Cache] = None,
350
+ output_attentions: bool = False,
351
+ use_cache: bool = False,
352
+ cache_position: Optional[torch.LongTensor] = None,
353
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
354
+ ):
355
+ bsz, q_len, _ = hidden_states.size()
356
+
357
+ query_states = self.q_proj(hidden_states)
358
+ key_states = self.k_proj(hidden_states)
359
+ value_states = self.v_proj(hidden_states)
360
+
361
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
362
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
363
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
364
+
365
+ kv_seq_len = key_states.shape[-2]
366
+ if past_key_value is not None:
367
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
368
+
369
+ cos, sin = position_embeddings
370
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
371
+
372
+ if past_key_value is not None:
373
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
374
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
375
+
376
+ # repeat k/v heads if n_kv_heads < n_heads
377
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
378
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
379
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
380
+
381
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
382
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
383
+ # cast them back in float16 just to be sure everything works as expected.
384
+ input_dtype = query_states.dtype
385
+ if input_dtype == torch.float32:
386
+ if torch.is_autocast_enabled():
387
+ target_dtype = torch.get_autocast_gpu_dtype()
388
+ # Handle the case where the model is quantized
389
+ elif hasattr(self.config, "_pre_quantization_dtype"):
390
+ target_dtype = self.config._pre_quantization_dtype
391
+ else:
392
+ target_dtype = self.q_proj.weight.dtype
393
+
394
+ logger.warning_once(
395
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
396
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
397
+ f" {target_dtype}."
398
+ )
399
+
400
+ query_states = query_states.to(target_dtype)
401
+ key_states = key_states.to(target_dtype)
402
+ value_states = value_states.to(target_dtype)
403
+
404
+ # Reashape to the expected shape for Flash Attention
405
+ query_states = query_states.transpose(1, 2)
406
+ key_states = key_states.transpose(1, 2)
407
+ value_states = value_states.transpose(1, 2)
408
+
409
+ attn_output = _flash_attention_forward(
410
+ query_states,
411
+ key_states,
412
+ value_states,
413
+ attention_mask,
414
+ q_len,
415
+ position_ids=position_ids,
416
+ dropout=dropout_rate,
417
+ sliding_window=getattr(self.config, "sliding_window", None),
418
+ is_causal=self.is_causal,
419
+ )
420
+
421
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
422
+ attn_output = self.o_proj(attn_output)
423
+
424
+ if not output_attentions:
425
+ attn_weights = None
426
+
427
+ return attn_output, attn_weights, past_key_value
428
+
429
+
430
+ class PhimoeSdpaAttention(PhimoeAttention):
431
+ """
432
+ Phimoe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
433
+ `PhimoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
434
+ SDPA API.
435
+ """
436
+
437
+ # Adapted from PhimoeAttention.forward
438
+ def forward(
439
+ self,
440
+ hidden_states: torch.Tensor,
441
+ attention_mask: Optional[torch.Tensor] = None,
442
+ position_ids: Optional[torch.LongTensor] = None,
443
+ past_key_value: Optional[Cache] = None,
444
+ output_attentions: bool = False,
445
+ use_cache: bool = False,
446
+ cache_position: Optional[torch.LongTensor] = None,
447
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
448
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
449
+ if output_attentions:
450
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
451
+ logger.warning_once(
452
+ "PhimoeModel is using PhimoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
453
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
454
+ )
455
+ return super().forward(
456
+ hidden_states=hidden_states,
457
+ attention_mask=attention_mask,
458
+ position_ids=position_ids,
459
+ past_key_value=past_key_value,
460
+ output_attentions=output_attentions,
461
+ use_cache=use_cache,
462
+ position_embeddings=position_embeddings,
463
+ )
464
+
465
+ bsz, q_len, _ = hidden_states.size()
466
+
467
+ query_states = self.q_proj(hidden_states)
468
+ key_states = self.k_proj(hidden_states)
469
+ value_states = self.v_proj(hidden_states)
470
+
471
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
472
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
473
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
474
+
475
+ cos, sin = position_embeddings
476
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
477
+
478
+ if past_key_value is not None:
479
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
480
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
481
+
482
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
483
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
484
+
485
+ causal_mask = attention_mask
486
+ if attention_mask is not None: # no matter the length, we just slice it
487
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
488
+
489
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
490
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
491
+ if query_states.device.type == "cuda" and attention_mask is not None:
492
+ query_states = query_states.contiguous()
493
+ key_states = key_states.contiguous()
494
+ value_states = value_states.contiguous()
495
+
496
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
497
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
498
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
499
+ is_causal = True if causal_mask is None and q_len > 1 else False
500
+
501
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
502
+ query_states,
503
+ key_states,
504
+ value_states,
505
+ attn_mask=causal_mask,
506
+ dropout_p=self.attention_dropout if self.training else 0.0,
507
+ is_causal=is_causal,
508
+ )
509
+
510
+ attn_output = attn_output.transpose(1, 2).contiguous()
511
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
512
+
513
+ attn_output = self.o_proj(attn_output)
514
+
515
+ return attn_output, None, past_key_value
516
+
517
+
518
+ PHIMOE_ATTENTION_CLASSES = {
519
+ "eager": PhimoeAttention,
520
+ "flash_attention_2": PhimoeFlashAttention2,
521
+ "sdpa": PhimoeSdpaAttention,
522
+ }
523
+
524
+
525
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralBlockSparseTop2MLP with Mixtral->Phimoe
526
+ class PhimoeBlockSparseTop2MLP(nn.Module):
527
+ def __init__(self, config: PhimoeConfig):
528
+ super().__init__()
529
+ self.ffn_dim = config.intermediate_size
530
+ self.hidden_dim = config.hidden_size
531
+
532
+ self.w1 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
533
+ self.w2 = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False)
534
+ self.w3 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
535
+
536
+ self.act_fn = ACT2FN[config.hidden_act]
537
+
538
+ def forward(self, hidden_states):
539
+ current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3(hidden_states)
540
+ current_hidden_states = self.w2(current_hidden_states)
541
+ return current_hidden_states
542
+
543
+
544
+ class MultiplierProcessor(torch.autograd.Function):
545
+ @staticmethod
546
+ def forward(
547
+ ctx,
548
+ scores: torch.Tensor,
549
+ multiplier: torch.Tensor,
550
+ selected_experts: torch.Tensor,
551
+ masked_gates: torch.Tensor,
552
+ mask_for_one: torch.Tensor,
553
+ ):
554
+ """
555
+ Forward pass for the custom autograd function.
556
+
557
+ Args:
558
+ ctx: Context object to save information for backward computation.
559
+ scores (torch.Tensor): Input scores tensor.
560
+ multiplier (torch.Tensor): Multiplier tensor.
561
+ selected_experts (torch.Tensor): Tensor of selected experts.
562
+ masked_gates (torch.Tensor): Masked gates tensor.
563
+ mask_for_one (torch.Tensor): Mask for one tensor.
564
+
565
+ Returns:
566
+ torch.Tensor: Result of the forward pass.
567
+ """
568
+ ctx.save_for_backward(multiplier, selected_experts, masked_gates)
569
+ return multiplier * mask_for_one
570
+
571
+ @staticmethod
572
+ def backward(
573
+ ctx,
574
+ grad_at_output: torch.Tensor,
575
+ ):
576
+ """
577
+ Backward pass for the custom autograd function.
578
+
579
+ Args:
580
+ ctx: Context object with saved tensors from the forward pass.
581
+ grad_at_output (torch.Tensor): Gradient at the output.
582
+
583
+ Returns:
584
+ Tuple[torch.Tensor, None, None, None, None]: Gradients for the inputs.
585
+ """
586
+ multiplier, selected_experts, masked_gates = ctx.saved_tensors
587
+
588
+ grad_at_output = grad_at_output * multiplier
589
+
590
+ grad_at_scores_expanded = masked_gates * grad_at_output.mul(-1)
591
+ grad_at_scores_expanded.scatter_add_(
592
+ dim=-1,
593
+ index=selected_experts,
594
+ src=grad_at_output,
595
+ )
596
+
597
+ return (
598
+ grad_at_scores_expanded,
599
+ None,
600
+ None,
601
+ None,
602
+ None,
603
+ )
604
+
605
+
606
+ def sparsemixer(scores, jitter_eps, training, top_k=2):
607
+ """
608
+ Sparse mixer function to select top-k experts and compute multipliers.
609
+ Based on the paper: https://arxiv.org/pdf/2409.12136
610
+ We first replace the TopK(·) function as random sampling of discrete variables
611
+ in model training. Then, following Liu et al. (2023a) and Liu et al. (2023b), we apply Heun's
612
+ third order method to approximate the expert routing gradient and construct a modified
613
+ back-propagation to give a mathematically sound gradient estimation for expert routing.
614
+
615
+ Args:
616
+ scores (torch.Tensor): Input scores tensor.
617
+ jitter_eps (float): Jitter epsilon for numerical stability.
618
+ training (bool): Flag indicating if the model is in training mode.
619
+ top_k (int): Number of top experts to select.
620
+
621
+ Returns:
622
+ Tuple[torch.Tensor, torch.Tensor]: Multiplier and selected experts tensors.
623
+ """
624
+ if top_k != 2:
625
+ raise ValueError("top_k must be equal to 2")
626
+
627
+ # first expert
628
+
629
+ with torch.no_grad():
630
+ # Compute mask for sparsity
631
+ mask_logits_threshold, max_ind = scores.max(dim=-1, keepdim=True)
632
+ factor = scores.abs().clamp(min=mask_logits_threshold)
633
+ mask_logits_threshold = ((mask_logits_threshold - scores) / factor) > (2 * jitter_eps)
634
+
635
+ # Apply mask
636
+ masked_gates = scores.masked_fill(mask_logits_threshold, float("-inf"))
637
+ if training:
638
+ selected_experts = (
639
+ (
640
+ masked_gates
641
+ - torch.empty_like(masked_gates, memory_format=torch.legacy_contiguous_format).exponential_().log()
642
+ )
643
+ .max(dim=-1)[1]
644
+ .unsqueeze(-1)
645
+ ) # Gumbel sampling, more robust than the multinomial method
646
+ else:
647
+ selected_experts = max_ind
648
+
649
+ # Compute scores for gradients
650
+ masked_gates = torch.softmax(masked_gates, dim=-1)
651
+ multiplier_o = masked_gates.gather(dim=-1, index=selected_experts)
652
+
653
+ if training:
654
+ # Compute midpoint mask
655
+ max_scores, max_ind = masked_gates.max(dim=-1, keepdim=True)
656
+ mask_for_one = torch.logical_or(
657
+ selected_experts == max_ind,
658
+ torch.rand_like(max_scores) > 0.75, # Heun's third-order method
659
+ )
660
+ # 1 -> 1.0 & 0 -> 1./3: lambda x: (x + 0.5) / 1.5
661
+ mask_for_one = torch.add(0.3333, mask_for_one, alpha=0.6667).type_as(masked_gates)
662
+
663
+ multiplier = MultiplierProcessor.apply(
664
+ scores,
665
+ multiplier_o,
666
+ selected_experts,
667
+ masked_gates,
668
+ mask_for_one,
669
+ )
670
+ else:
671
+ multiplier = multiplier_o
672
+
673
+ # Masked out first expert
674
+ masked_scores = torch.scatter(
675
+ scores,
676
+ -1,
677
+ selected_experts,
678
+ float("-inf"),
679
+ )
680
+ with torch.no_grad():
681
+ # Compute mask for sparsity
682
+ mask_logits_threshold, max_ind = masked_scores.max(dim=-1, keepdim=True)
683
+ factor = scores.abs().clamp(min=mask_logits_threshold)
684
+ mask_logits_threshold = ((mask_logits_threshold - scores) / factor) > (2 * jitter_eps)
685
+
686
+ # Apply mask
687
+ masked_gates_top2 = masked_scores.masked_fill(mask_logits_threshold, float("-inf"))
688
+ if training:
689
+ selected_experts_top2 = (
690
+ (
691
+ masked_gates_top2
692
+ - torch.empty_like(masked_gates_top2, memory_format=torch.legacy_contiguous_format)
693
+ .exponential_()
694
+ .log()
695
+ )
696
+ .max(dim=-1)[1]
697
+ .unsqueeze(-1)
698
+ ) # Gumbel sampling, more robust than the multinomial method
699
+ else:
700
+ selected_experts_top2 = max_ind
701
+ # Compute scores for gradients
702
+ masked_gates_top2 = torch.softmax(masked_gates_top2, dim=-1)
703
+ multiplier_top2_o = masked_gates_top2.gather(dim=-1, index=selected_experts_top2)
704
+
705
+ if training:
706
+ # Compute midpoint mask
707
+ max_scores, max_ind = masked_gates_top2.max(dim=-1, keepdim=True)
708
+ mask_for_one_top2 = torch.logical_or(
709
+ selected_experts_top2 == max_ind,
710
+ torch.rand_like(max_scores).uniform_() > 0.75, # Heun's third-order method
711
+ )
712
+ # 1 -> 1.0 & 0 -> 1./3: lambda x: (x + 0.5) / 1.5
713
+ mask_for_one_top2 = torch.add(0.3333, mask_for_one_top2, alpha=0.6667).type_as(masked_gates_top2)
714
+
715
+ multiplier_top2 = MultiplierProcessor.apply(
716
+ scores,
717
+ multiplier_top2_o,
718
+ selected_experts_top2,
719
+ masked_gates_top2,
720
+ mask_for_one_top2,
721
+ )
722
+ else:
723
+ multiplier_top2 = multiplier_top2_o
724
+
725
+ multiplier = torch.concat((multiplier, multiplier_top2), dim=-1)
726
+ selected_experts = torch.concat((selected_experts, selected_experts_top2), dim=-1)
727
+
728
+ return (
729
+ multiplier,
730
+ selected_experts,
731
+ )
732
+
733
+
734
+ class PhimoeSparseMoeBlock(nn.Module):
735
+ """
736
+ This implementation is
737
+ strictly equivalent to standard MoE with full capacity (no
738
+ dropped tokens). It's faster since it formulates MoE operations
739
+ in terms of block-sparse operations to accommodate imbalanced
740
+ assignments of tokens to experts, whereas standard MoE either
741
+ (1) drop tokens at the cost of reduced performance or (2) set
742
+ capacity factor to number of experts and thus waste computation
743
+ and memory on padding.
744
+ """
745
+
746
+ def __init__(self, config):
747
+ super().__init__()
748
+ self.hidden_dim = config.hidden_size
749
+ self.ffn_dim = config.intermediate_size
750
+ self.num_experts = config.num_local_experts
751
+ self.top_k = config.num_experts_per_tok
752
+ # gating
753
+ self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False)
754
+
755
+ self.experts = nn.ModuleList([PhimoeBlockSparseTop2MLP(config) for _ in range(self.num_experts)])
756
+
757
+ # Jitter parameters
758
+ self.router_jitter_noise = config.router_jitter_noise
759
+ self.input_jitter_noise = config.input_jitter_noise
760
+
761
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
762
+ """ """
763
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
764
+ if self.training and self.input_jitter_noise > 0:
765
+ hidden_states *= torch.empty_like(hidden_states).uniform_(
766
+ 1.0 - self.input_jitter_noise, 1.0 + self.input_jitter_noise
767
+ )
768
+ hidden_states = hidden_states.view(-1, hidden_dim)
769
+ router_logits = self.gate(hidden_states)
770
+
771
+ routing_weights, selected_experts = sparsemixer(
772
+ router_logits,
773
+ jitter_eps=self.router_jitter_noise,
774
+ training=self.training,
775
+ )
776
+
777
+ final_hidden_states = torch.zeros(
778
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
779
+ )
780
+
781
+ # One hot encode the selected experts to create an expert mask
782
+ # this will be used to easily index which expert is going to be sollicitated
783
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
784
+
785
+ # Loop over all available experts in the model and perform the computation on each expert
786
+ for expert_idx in range(self.num_experts):
787
+ expert_layer = self.experts[expert_idx]
788
+ idx, top_x = torch.where(expert_mask[expert_idx])
789
+
790
+ if top_x.shape[0] == 0:
791
+ continue
792
+
793
+ # Index the correct hidden states and compute the expert hidden state for
794
+ # the current expert. We need to make sure to multiply the output hidden
795
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
796
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
797
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
798
+
799
+ # However `index_add_` only support torch tensors for indexing so we'll use
800
+ # the `top_x` tensor here.
801
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
802
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
803
+ return final_hidden_states, router_logits
804
+
805
+
806
+ class PhimoeDecoderLayer(nn.Module):
807
+ def __init__(self, config: PhimoeConfig, layer_idx: int):
808
+ super().__init__()
809
+ self.hidden_size = config.hidden_size
810
+
811
+ self.self_attn = PHIMOE_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
812
+
813
+ self.block_sparse_moe = PhimoeSparseMoeBlock(config)
814
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps, elementwise_affine=True)
815
+ self.post_attention_layernorm = nn.LayerNorm(
816
+ config.hidden_size, eps=config.rms_norm_eps, elementwise_affine=True
817
+ )
818
+
819
+ def forward(
820
+ self,
821
+ hidden_states: torch.Tensor,
822
+ attention_mask: Optional[torch.Tensor] = None,
823
+ position_ids: Optional[torch.LongTensor] = None,
824
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
825
+ output_attentions: Optional[bool] = False,
826
+ output_router_logits: Optional[bool] = False,
827
+ use_cache: Optional[bool] = False,
828
+ cache_position: Optional[torch.LongTensor] = None,
829
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
830
+ **kwargs,
831
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
832
+ """
833
+ Args:
834
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
835
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
836
+ `(batch, sequence_length)` where padding elements are indicated by 0.
837
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
838
+ output_attentions (`bool`, *optional*):
839
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
840
+ returned tensors for more detail.
841
+ output_router_logits (`bool`, *optional*):
842
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
843
+ should not be returned during inference.
844
+ use_cache (`bool`, *optional*):
845
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
846
+ (see `past_key_values`).
847
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
848
+ Indices depicting the position of the input sequence tokens in the sequence.
849
+ kwargs (`dict`, *optional*):
850
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
851
+ into the model
852
+ """
853
+
854
+ residual = hidden_states
855
+
856
+ hidden_states = self.input_layernorm(hidden_states)
857
+
858
+ # Self Attention
859
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
860
+ hidden_states=hidden_states,
861
+ attention_mask=attention_mask,
862
+ position_ids=position_ids,
863
+ past_key_value=past_key_value,
864
+ output_attentions=output_attentions,
865
+ use_cache=use_cache,
866
+ cache_position=cache_position,
867
+ position_embeddings=position_embeddings,
868
+ )
869
+ hidden_states = residual + hidden_states
870
+
871
+ # Fully Connected
872
+ residual = hidden_states
873
+ hidden_states = self.post_attention_layernorm(hidden_states)
874
+ hidden_states, router_logits = self.block_sparse_moe(hidden_states)
875
+ hidden_states = residual + hidden_states
876
+
877
+ outputs = (hidden_states,)
878
+
879
+ if output_attentions:
880
+ outputs += (self_attn_weights,)
881
+
882
+ if use_cache:
883
+ outputs += (present_key_value,)
884
+
885
+ if output_router_logits:
886
+ outputs += (router_logits,)
887
+
888
+ return outputs
889
+
890
+
891
+ PHIMOE_START_DOCSTRING = r"""
892
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
893
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
894
+ etc.)
895
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
896
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
897
+ and behavior.
898
+ Parameters:
899
+ config ([`PhimoeConfig`]):
900
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
901
+ load the weights associated with the model, only the configuration. Check out the
902
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
903
+ """
904
+
905
+
906
+ @add_start_docstrings(
907
+ "The bare Phimoe Model outputting raw hidden-states without any specific head on top.",
908
+ PHIMOE_START_DOCSTRING,
909
+ )
910
+ class PhimoePreTrainedModel(PreTrainedModel):
911
+ config_class = PhimoeConfig
912
+ base_model_prefix = "model"
913
+ supports_gradient_checkpointing = True
914
+ _no_split_modules = ["PhimoeDecoderLayer"]
915
+ _skip_keys_device_placement = ["past_key_values"]
916
+ _supports_flash_attn_2 = True
917
+ _supports_sdpa = True
918
+ _supports_cache_class = True
919
+ _supports_quantized_cache = True
920
+ _supports_static_cache = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
921
+
922
+ def _init_weights(self, module):
923
+ std = self.config.initializer_range
924
+ if isinstance(module, nn.Linear):
925
+ module.weight.data.normal_(mean=0.0, std=std)
926
+ if module.bias is not None:
927
+ module.bias.data.zero_()
928
+ elif isinstance(module, nn.Embedding):
929
+ module.weight.data.normal_(mean=0.0, std=std)
930
+ if module.padding_idx is not None:
931
+ module.weight.data[module.padding_idx].zero_()
932
+ elif isinstance(module, nn.LayerNorm):
933
+ module.bias.data.zero_()
934
+ module.weight.data.fill_(1.0)
935
+
936
+
937
+ PHIMOE_INPUTS_DOCSTRING = r"""
938
+ Args:
939
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
940
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
941
+ it.
942
+
943
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
944
+ [`PreTrainedTokenizer.__call__`] for details.
945
+
946
+ [What are input IDs?](../glossary#input-ids)
947
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
948
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
949
+
950
+ - 1 for tokens that are **not masked**,
951
+ - 0 for tokens that are **masked**.
952
+
953
+ [What are attention masks?](../glossary#attention-mask)
954
+
955
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
956
+ [`PreTrainedTokenizer.__call__`] for details.
957
+
958
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
959
+ `past_key_values`).
960
+
961
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
962
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
963
+ information on the default strategy.
964
+
965
+ - 1 indicates the head is **not masked**,
966
+ - 0 indicates the head is **masked**.
967
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
968
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
969
+ config.n_positions - 1]`.
970
+
971
+ [What are position IDs?](../glossary#position-ids)
972
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
973
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
974
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
975
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
976
+
977
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
978
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
979
+
980
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
981
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
982
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
983
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
984
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
985
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
986
+ model's internal embedding lookup matrix.
987
+ use_cache (`bool`, *optional*):
988
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
989
+ `past_key_values`).
990
+ output_attentions (`bool`, *optional*):
991
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
992
+ tensors for more detail.
993
+ output_hidden_states (`bool`, *optional*):
994
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
995
+ more detail.
996
+ output_router_logits (`bool`, *optional*):
997
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
998
+ should not be returned during inference.
999
+ return_dict (`bool`, *optional*):
1000
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1001
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1002
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1003
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1004
+ the complete sequence length.
1005
+ """
1006
+
1007
+
1008
+ @add_start_docstrings(
1009
+ "The bare Phimoe Model outputting raw hidden-states without any specific head on top.",
1010
+ PHIMOE_START_DOCSTRING,
1011
+ )
1012
+ class PhimoeModel(PhimoePreTrainedModel):
1013
+ """
1014
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhimoeDecoderLayer`]
1015
+ Args:
1016
+ config: PhimoeConfig
1017
+ """
1018
+
1019
+ def __init__(self, config: PhimoeConfig):
1020
+ super().__init__(config)
1021
+ self.padding_idx = config.pad_token_id
1022
+ self.vocab_size = config.vocab_size
1023
+
1024
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1025
+ self.layers = nn.ModuleList(
1026
+ [PhimoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1027
+ )
1028
+ self._attn_implementation = config._attn_implementation
1029
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps, elementwise_affine=True)
1030
+ self.rotary_emb = PhimoeRotaryEmbedding(config=config)
1031
+
1032
+ self.gradient_checkpointing = False
1033
+ # Initialize weights and apply final processing
1034
+ self.post_init()
1035
+
1036
+ def get_input_embeddings(self):
1037
+ return self.embed_tokens
1038
+
1039
+ def set_input_embeddings(self, value):
1040
+ self.embed_tokens = value
1041
+
1042
+ @can_return_tuple
1043
+ @add_start_docstrings_to_model_forward(PHIMOE_INPUTS_DOCSTRING)
1044
+ def forward(
1045
+ self,
1046
+ input_ids: Optional[torch.LongTensor] = None,
1047
+ attention_mask: Optional[torch.Tensor] = None,
1048
+ position_ids: Optional[torch.LongTensor] = None,
1049
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1050
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1051
+ use_cache: Optional[bool] = None,
1052
+ output_attentions: Optional[bool] = None,
1053
+ output_hidden_states: Optional[bool] = None,
1054
+ output_router_logits: Optional[bool] = None,
1055
+ cache_position: Optional[torch.LongTensor] = None,
1056
+ ) -> MoeModelOutputWithPast:
1057
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1058
+ output_router_logits = (
1059
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1060
+ )
1061
+ output_hidden_states = (
1062
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1063
+ )
1064
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1065
+
1066
+ if (input_ids is None) ^ (inputs_embeds is not None):
1067
+ raise ValueError(
1068
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1069
+ )
1070
+
1071
+ if self.gradient_checkpointing and self.training:
1072
+ if use_cache:
1073
+ logger.warning_once(
1074
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1075
+ )
1076
+ use_cache = False
1077
+
1078
+ # kept for BC (non `Cache` `past_key_values` inputs)
1079
+ return_legacy_cache = False
1080
+ if use_cache and not isinstance(past_key_values, Cache):
1081
+ return_legacy_cache = True
1082
+ if past_key_values is None:
1083
+ past_key_values = DynamicCache()
1084
+ else:
1085
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1086
+ logger.warning_once(
1087
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
1088
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
1089
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
1090
+ )
1091
+
1092
+ if inputs_embeds is None:
1093
+ inputs_embeds = self.embed_tokens(input_ids)
1094
+
1095
+ if cache_position is None:
1096
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1097
+ cache_position = torch.arange(
1098
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1099
+ )
1100
+ if position_ids is None:
1101
+ position_ids = cache_position.unsqueeze(0)
1102
+
1103
+ causal_mask = self._update_causal_mask(
1104
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1105
+ )
1106
+
1107
+ hidden_states = inputs_embeds
1108
+
1109
+ position_embeddings = self.rotary_emb(hidden_states, seq_len=cache_position[-1] + 1)
1110
+
1111
+ # decoder layers
1112
+ all_hidden_states = () if output_hidden_states else None
1113
+ all_self_attns = () if output_attentions else None
1114
+ all_router_logits = () if output_router_logits else None
1115
+ next_decoder_cache = None
1116
+
1117
+ for decoder_layer in self.layers:
1118
+ if output_hidden_states:
1119
+ all_hidden_states += (hidden_states,)
1120
+
1121
+ if self.gradient_checkpointing and self.training:
1122
+ layer_outputs = self._gradient_checkpointing_func(
1123
+ decoder_layer.__call__,
1124
+ hidden_states,
1125
+ causal_mask,
1126
+ position_ids,
1127
+ past_key_values,
1128
+ output_attentions,
1129
+ output_router_logits,
1130
+ use_cache,
1131
+ cache_position,
1132
+ position_embeddings,
1133
+ )
1134
+ else:
1135
+ layer_outputs = decoder_layer(
1136
+ hidden_states,
1137
+ attention_mask=causal_mask,
1138
+ position_ids=position_ids,
1139
+ past_key_value=past_key_values,
1140
+ output_attentions=output_attentions,
1141
+ output_router_logits=output_router_logits,
1142
+ use_cache=use_cache,
1143
+ cache_position=cache_position,
1144
+ position_embeddings=position_embeddings,
1145
+ )
1146
+
1147
+ hidden_states = layer_outputs[0]
1148
+
1149
+ if use_cache:
1150
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1151
+
1152
+ if output_attentions:
1153
+ all_self_attns += (layer_outputs[1],)
1154
+
1155
+ if output_router_logits:
1156
+ all_router_logits += (layer_outputs[-1],)
1157
+
1158
+ hidden_states = self.norm(hidden_states)
1159
+
1160
+ # add hidden states from the last decoder layer
1161
+ if output_hidden_states:
1162
+ all_hidden_states += (hidden_states,)
1163
+
1164
+ next_cache = next_decoder_cache if use_cache else None
1165
+ if return_legacy_cache:
1166
+ next_cache = next_cache.to_legacy_cache()
1167
+
1168
+ return MoeModelOutputWithPast(
1169
+ last_hidden_state=hidden_states,
1170
+ past_key_values=next_cache,
1171
+ hidden_states=all_hidden_states,
1172
+ attentions=all_self_attns,
1173
+ router_logits=all_router_logits,
1174
+ )
1175
+
1176
+ # Copied from transformers.models.phi3.modeling_phi3.Phi3Model._update_causal_mask with Phi3->Phimoe
1177
+ def _update_causal_mask(
1178
+ self,
1179
+ attention_mask: Union[torch.Tensor, "BlockMask"],
1180
+ input_tensor: torch.Tensor,
1181
+ cache_position: torch.Tensor,
1182
+ past_key_values: Cache,
1183
+ output_attentions: bool = False,
1184
+ ):
1185
+ if self.config._attn_implementation == "flash_attention_2":
1186
+ if attention_mask is not None and past_key_values is not None:
1187
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
1188
+ if is_padding_right:
1189
+ raise ValueError(
1190
+ "You are attempting to perform batched generation with padding_side='right'"
1191
+ " this may lead to unexpected behaviour for Flash Attention version of Phimoe. Make sure to "
1192
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1193
+ )
1194
+ if attention_mask is not None and 0.0 in attention_mask:
1195
+ return attention_mask
1196
+ return None
1197
+ if self.config._attn_implementation == "flex_attention":
1198
+ if isinstance(attention_mask, torch.Tensor):
1199
+ attention_mask = make_flex_block_causal_mask(attention_mask)
1200
+ return attention_mask
1201
+
1202
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1203
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1204
+ # to infer the attention mask.
1205
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1206
+ using_static_cache = isinstance(past_key_values, StaticCache)
1207
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
1208
+
1209
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1210
+ if (
1211
+ self.config._attn_implementation == "sdpa"
1212
+ and not (using_static_cache or using_sliding_window_cache)
1213
+ and not output_attentions
1214
+ ):
1215
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1216
+ attention_mask,
1217
+ inputs_embeds=input_tensor,
1218
+ past_key_values_length=past_seen_tokens,
1219
+ sliding_window=self.config.sliding_window,
1220
+ is_training=self.training,
1221
+ ):
1222
+ return None
1223
+
1224
+ dtype, device = input_tensor.dtype, input_tensor.device
1225
+ min_dtype = torch.finfo(dtype).min
1226
+ sequence_length = input_tensor.shape[1]
1227
+ # SlidingWindowCache or StaticCache
1228
+ if using_sliding_window_cache or using_static_cache:
1229
+ target_length = past_key_values.get_max_cache_shape()
1230
+ # DynamicCache or no cache
1231
+ else:
1232
+ target_length = (
1233
+ attention_mask.shape[-1]
1234
+ if isinstance(attention_mask, torch.Tensor)
1235
+ else past_seen_tokens + sequence_length + 1
1236
+ )
1237
+
1238
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1239
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1240
+ attention_mask,
1241
+ sequence_length=sequence_length,
1242
+ target_length=target_length,
1243
+ dtype=dtype,
1244
+ device=device,
1245
+ cache_position=cache_position,
1246
+ batch_size=input_tensor.shape[0],
1247
+ config=self.config,
1248
+ past_key_values=past_key_values,
1249
+ )
1250
+
1251
+ if (
1252
+ self.config._attn_implementation == "sdpa"
1253
+ and attention_mask is not None
1254
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
1255
+ and not output_attentions
1256
+ ):
1257
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1258
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1259
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1260
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1261
+
1262
+ return causal_mask
1263
+
1264
+ @staticmethod
1265
+ # Copied from transformers.models.mistral.modeling_mistral.MistralModel._prepare_4d_causal_attention_mask_with_cache_position with Mistral->Phimoe
1266
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1267
+ attention_mask: torch.Tensor,
1268
+ sequence_length: int,
1269
+ target_length: int,
1270
+ dtype: torch.dtype,
1271
+ device: torch.device,
1272
+ cache_position: torch.Tensor,
1273
+ batch_size: int,
1274
+ config: PhimoeConfig,
1275
+ past_key_values: Cache,
1276
+ ):
1277
+ """
1278
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1279
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1280
+
1281
+ Args:
1282
+ attention_mask (`torch.Tensor`):
1283
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
1284
+ sequence_length (`int`):
1285
+ The sequence length being processed.
1286
+ target_length (`int`):
1287
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
1288
+ dtype (`torch.dtype`):
1289
+ The dtype to use for the 4D attention mask.
1290
+ device (`torch.device`):
1291
+ The device to place the 4D attention mask on.
1292
+ cache_position (`torch.Tensor`):
1293
+ Indices depicting the position of the input sequence tokens in the sequence.
1294
+ batch_size (`torch.Tensor`):
1295
+ Batch size.
1296
+ config (`PhimoeConfig`):
1297
+ The model's configuration class
1298
+ past_key_values (`Cache`):
1299
+ The cache class that is being used currently to generate
1300
+ """
1301
+ if attention_mask is not None and attention_mask.dim() == 4:
1302
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1303
+ causal_mask = attention_mask
1304
+ else:
1305
+ min_dtype = torch.finfo(dtype).min
1306
+ causal_mask = torch.full(
1307
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1308
+ )
1309
+ diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1310
+ if config.get_text_config().sliding_window is not None:
1311
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
1312
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
1313
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
1314
+ sliding_attend_mask = torch.arange(target_length, device=device) <= (
1315
+ cache_position.reshape(-1, 1) - config.get_text_config().sliding_window
1316
+ )
1317
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
1318
+ causal_mask *= diagonal_attend_mask
1319
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1320
+ if attention_mask is not None:
1321
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1322
+ if attention_mask.shape[-1] > target_length:
1323
+ attention_mask = attention_mask[:, :target_length]
1324
+ mask_length = attention_mask.shape[-1]
1325
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
1326
+ causal_mask.device
1327
+ )
1328
+ padding_mask = padding_mask == 0
1329
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1330
+ padding_mask, min_dtype
1331
+ )
1332
+ return causal_mask
1333
+
1334
+
1335
+ class PhimoeForCausalLM(PhimoePreTrainedModel, GenerationMixin):
1336
+ _tied_weights_keys = ["lm_head.weight"]
1337
+
1338
+ def __init__(self, config):
1339
+ super().__init__(config)
1340
+ self.model = PhimoeModel(config)
1341
+ self.vocab_size = config.vocab_size
1342
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=self.config.lm_head_bias)
1343
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1344
+ self.num_experts = config.num_local_experts
1345
+ self.num_experts_per_tok = config.num_experts_per_tok
1346
+ # Initialize weights and apply final processing
1347
+ self.post_init()
1348
+
1349
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1350
+ def get_input_embeddings(self):
1351
+ return self.model.embed_tokens
1352
+
1353
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1354
+ def set_input_embeddings(self, value):
1355
+ self.model.embed_tokens = value
1356
+
1357
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1358
+ def get_output_embeddings(self):
1359
+ return self.lm_head
1360
+
1361
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1362
+ def set_output_embeddings(self, new_embeddings):
1363
+ self.lm_head = new_embeddings
1364
+
1365
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1366
+ def set_decoder(self, decoder):
1367
+ self.model = decoder
1368
+
1369
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1370
+ def get_decoder(self):
1371
+ return self.model
1372
+
1373
+ @can_return_tuple
1374
+ @add_start_docstrings_to_model_forward(PHIMOE_INPUTS_DOCSTRING)
1375
+ @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1376
+ # Ignore copy
1377
+ def forward(
1378
+ self,
1379
+ input_ids: Optional[torch.LongTensor] = None,
1380
+ attention_mask: Optional[torch.Tensor] = None,
1381
+ position_ids: Optional[torch.LongTensor] = None,
1382
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1383
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1384
+ labels: Optional[torch.LongTensor] = None,
1385
+ use_cache: Optional[bool] = None,
1386
+ output_attentions: Optional[bool] = None,
1387
+ output_hidden_states: Optional[bool] = None,
1388
+ output_router_logits: Optional[bool] = None,
1389
+ cache_position: Optional[torch.LongTensor] = None,
1390
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1391
+ **loss_kwargs,
1392
+ ) -> MoeCausalLMOutputWithPast:
1393
+ r"""
1394
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1395
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1396
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1397
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1398
+
1399
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
1400
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
1401
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1402
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1403
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
1404
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
1405
+ Returns:
1406
+ Example:
1407
+ ```python
1408
+ >>> from transformers import AutoTokenizer, PhimoeForCausalLM
1409
+ >>> model = PhimoeForCausalLM.from_pretrained("microsoft/Phi-3.5-MoE-instruct")
1410
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3.5-MoE-instruct")
1411
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1412
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1413
+ >>> # Generate
1414
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1415
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1416
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1417
+ ```"""
1418
+ if (
1419
+ use_cache
1420
+ and self.config.rope_scaling
1421
+ and cache_position is not None
1422
+ and cache_position[0] == self.config.original_max_position_embeddings
1423
+ ):
1424
+ logger.warning(
1425
+ f"If you are not using the generate method, you may encounter nonsensical outputs after the {self.config.original_max_position_embeddings}th token, as the KV cache needs to be recomputed."
1426
+ )
1427
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1428
+ output_router_logits = (
1429
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1430
+ )
1431
+
1432
+ output_hidden_states = (
1433
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1434
+ )
1435
+
1436
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1437
+ outputs: MoeModelOutputWithPast = self.model(
1438
+ input_ids=input_ids,
1439
+ attention_mask=attention_mask,
1440
+ position_ids=position_ids,
1441
+ past_key_values=past_key_values,
1442
+ inputs_embeds=inputs_embeds,
1443
+ use_cache=use_cache,
1444
+ output_attentions=output_attentions,
1445
+ output_hidden_states=output_hidden_states,
1446
+ output_router_logits=output_router_logits,
1447
+ cache_position=cache_position,
1448
+ )
1449
+
1450
+ hidden_states = outputs.last_hidden_state
1451
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1452
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1453
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1454
+
1455
+ loss = None
1456
+ if labels is not None:
1457
+ loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
1458
+
1459
+ aux_loss = None
1460
+ if output_router_logits:
1461
+ aux_loss = load_balancing_loss_func(
1462
+ outputs.router_logits,
1463
+ self.num_experts,
1464
+ self.num_experts_per_tok,
1465
+ attention_mask,
1466
+ )
1467
+ if labels is not None:
1468
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1469
+
1470
+ return MoeCausalLMOutputWithPast(
1471
+ loss=loss,
1472
+ aux_loss=aux_loss,
1473
+ logits=logits,
1474
+ past_key_values=outputs.past_key_values,
1475
+ hidden_states=outputs.hidden_states,
1476
+ attentions=outputs.attentions,
1477
+ router_logits=outputs.router_logits,
1478
+ )
1479
+
1480
+ # Copied from transformers.models.phi3.modeling_phi3.Phi3ForCausalLM.prepare_inputs_for_generation
1481
+ def prepare_inputs_for_generation(
1482
+ self,
1483
+ input_ids,
1484
+ past_key_values=None,
1485
+ attention_mask=None,
1486
+ inputs_embeds=None,
1487
+ cache_position=None,
1488
+ position_ids=None,
1489
+ use_cache=True,
1490
+ logits_to_keep=None,
1491
+ **kwargs,
1492
+ ):
1493
+ # Overwritten -- this model may need to switch between short and long rope, invalidating the cache in the
1494
+ # process
1495
+
1496
+ # When the first time input length reached long and short factor switching point, enforce re-compute cache
1497
+ # It will cause downside of slower at this single token position, however, better than current failure.
1498
+ if (
1499
+ past_key_values
1500
+ and self.config.rope_scaling
1501
+ and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1
1502
+ ):
1503
+ past_length = cache_position[0]
1504
+ if past_length <= self.config.original_max_position_embeddings:
1505
+ past_key_values = None
1506
+
1507
+ model_inputs = super().prepare_inputs_for_generation(
1508
+ input_ids=input_ids,
1509
+ past_key_values=past_key_values,
1510
+ attention_mask=attention_mask,
1511
+ inputs_embeds=inputs_embeds,
1512
+ cache_position=cache_position,
1513
+ position_ids=position_ids,
1514
+ use_cache=use_cache,
1515
+ logits_to_keep=logits_to_keep,
1516
+ **kwargs,
1517
+ )
1518
+ return model_inputs
1519
+
1520
+
1521
+ @add_start_docstrings(
1522
+ """
1523
+ The Phimoe Model transformer with a sequence classification head on top (linear layer).
1524
+ [`PhimoeForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1525
+ (e.g. GPT-2) do.
1526
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1527
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1528
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1529
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1530
+ each row of the batch).
1531
+ """,
1532
+ PHIMOE_START_DOCSTRING,
1533
+ )
1534
+
1535
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phimoe, LLAMA->PHIMOE, BaseModelOutputWithPast->MoeModelOutputWithPast
1536
+ class PhimoeForSequenceClassification(PhimoePreTrainedModel):
1537
+ def __init__(self, config):
1538
+ super().__init__(config)
1539
+ self.num_labels = config.num_labels
1540
+ self.model = PhimoeModel(config)
1541
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1542
+
1543
+ # Initialize weights and apply final processing
1544
+ self.post_init()
1545
+
1546
+ def get_input_embeddings(self):
1547
+ return self.model.embed_tokens
1548
+
1549
+ def set_input_embeddings(self, value):
1550
+ self.model.embed_tokens = value
1551
+
1552
+ @can_return_tuple
1553
+ @add_start_docstrings_to_model_forward(PHIMOE_INPUTS_DOCSTRING)
1554
+ def forward(
1555
+ self,
1556
+ input_ids: Optional[torch.LongTensor] = None,
1557
+ attention_mask: Optional[torch.Tensor] = None,
1558
+ position_ids: Optional[torch.LongTensor] = None,
1559
+ past_key_values: Optional[Cache] = None,
1560
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1561
+ labels: Optional[torch.LongTensor] = None,
1562
+ use_cache: Optional[bool] = None,
1563
+ output_attentions: Optional[bool] = None,
1564
+ output_hidden_states: Optional[bool] = None,
1565
+ ) -> SequenceClassifierOutputWithPast:
1566
+ r"""
1567
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1568
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1569
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1570
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1571
+ """
1572
+
1573
+ transformer_outputs: MoeModelOutputWithPast = self.model(
1574
+ input_ids,
1575
+ attention_mask=attention_mask,
1576
+ position_ids=position_ids,
1577
+ past_key_values=past_key_values,
1578
+ inputs_embeds=inputs_embeds,
1579
+ use_cache=use_cache,
1580
+ output_attentions=output_attentions,
1581
+ output_hidden_states=output_hidden_states,
1582
+ )
1583
+ hidden_states = transformer_outputs.last_hidden_state
1584
+ logits = self.score(hidden_states)
1585
+
1586
+ if input_ids is not None:
1587
+ batch_size = input_ids.shape[0]
1588
+ else:
1589
+ batch_size = inputs_embeds.shape[0]
1590
+
1591
+ if self.config.pad_token_id is None and batch_size != 1:
1592
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1593
+ if self.config.pad_token_id is None:
1594
+ last_non_pad_token = -1
1595
+ elif input_ids is not None:
1596
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
1597
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
1598
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
1599
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
1600
+ else:
1601
+ last_non_pad_token = -1
1602
+ logger.warning_once(
1603
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1604
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1605
+ )
1606
+
1607
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
1608
+
1609
+ loss = None
1610
+ if labels is not None:
1611
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
1612
+
1613
+ return SequenceClassifierOutputWithPast(
1614
+ loss=loss,
1615
+ logits=pooled_logits,
1616
+ past_key_values=transformer_outputs.past_key_values,
1617
+ hidden_states=transformer_outputs.hidden_states,
1618
+ attentions=transformer_outputs.attentions,
1619
+ )
1620
+
1621
+
1622
+ __all__ = [
1623
+ "PhimoePreTrainedModel",
1624
+ "PhimoeModel",
1625
+ "PhimoeForCausalLM",
1626
+ "PhimoeForSequenceClassification",
1627
+ ]
docs/transformers/build/lib/transformers/models/phobert/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .tokenization_phobert import *
22
+ else:
23
+ import sys
24
+
25
+ _file = globals()["__file__"]
26
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
docs/transformers/build/lib/transformers/models/phobert/tokenization_phobert.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) 2020, VinAI Research and the HuggingFace Inc. team.
3
+ # Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
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 PhoBERT"""
17
+
18
+ import os
19
+ import re
20
+ from shutil import copyfile
21
+ from typing import List, Optional, Tuple
22
+
23
+ from ...tokenization_utils import PreTrainedTokenizer
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {
30
+ "vocab_file": "vocab.txt",
31
+ "merges_file": "bpe.codes",
32
+ }
33
+
34
+
35
+ def get_pairs(word):
36
+ """
37
+ Return set of symbol pairs in a word.
38
+
39
+ Word is represented as tuple of symbols (symbols being variable-length strings).
40
+ """
41
+ pairs = set()
42
+ prev_char = word[0]
43
+ for char in word[1:]:
44
+ pairs.add((prev_char, char))
45
+ prev_char = char
46
+
47
+ pairs = set(pairs)
48
+ return pairs
49
+
50
+
51
+ class PhobertTokenizer(PreTrainedTokenizer):
52
+ """
53
+ Construct a PhoBERT tokenizer. Based on Byte-Pair-Encoding.
54
+
55
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
56
+ this superclass for more information regarding those methods.
57
+
58
+ Args:
59
+ vocab_file (`str`):
60
+ Path to the vocabulary file.
61
+ merges_file (`str`):
62
+ Path to the merges file.
63
+ bos_token (`st`, *optional*, defaults to `"<s>"`):
64
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
65
+
66
+ <Tip>
67
+
68
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
69
+ sequence. The token used is the `cls_token`.
70
+
71
+ </Tip>
72
+
73
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
74
+ The end of sequence token.
75
+
76
+ <Tip>
77
+
78
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
79
+ The token used is the `sep_token`.
80
+
81
+ </Tip>
82
+
83
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
84
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
85
+ sequence classification or for a text and a question for question answering. It is also used as the last
86
+ token of a sequence built with special tokens.
87
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
88
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
89
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
90
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
91
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
92
+ token instead.
93
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
94
+ The token used for padding, for example when batching sequences of different lengths.
95
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
96
+ The token used for masking values. This is the token used when training this model with masked language
97
+ modeling. This is the token which the model will try to predict.
98
+ """
99
+
100
+ vocab_files_names = VOCAB_FILES_NAMES
101
+
102
+ def __init__(
103
+ self,
104
+ vocab_file,
105
+ merges_file,
106
+ bos_token="<s>",
107
+ eos_token="</s>",
108
+ sep_token="</s>",
109
+ cls_token="<s>",
110
+ unk_token="<unk>",
111
+ pad_token="<pad>",
112
+ mask_token="<mask>",
113
+ **kwargs,
114
+ ):
115
+ self.vocab_file = vocab_file
116
+ self.merges_file = merges_file
117
+
118
+ self.encoder = {}
119
+ self.encoder[str(bos_token)] = 0
120
+ self.encoder[str(pad_token)] = 1
121
+ self.encoder[str(eos_token)] = 2
122
+ self.encoder[str(unk_token)] = 3
123
+
124
+ self.add_from_file(vocab_file)
125
+
126
+ self.decoder = {v: k for k, v in self.encoder.items()}
127
+
128
+ with open(merges_file, encoding="utf-8") as merges_handle:
129
+ merges = merges_handle.read().split("\n")[:-1]
130
+ merges = [tuple(merge.split()[:-1]) for merge in merges]
131
+
132
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
133
+ self.cache = {}
134
+
135
+ super().__init__(
136
+ bos_token=bos_token,
137
+ eos_token=eos_token,
138
+ unk_token=unk_token,
139
+ sep_token=sep_token,
140
+ cls_token=cls_token,
141
+ pad_token=pad_token,
142
+ mask_token=mask_token,
143
+ **kwargs,
144
+ )
145
+
146
+ def build_inputs_with_special_tokens(
147
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
148
+ ) -> List[int]:
149
+ """
150
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
151
+ adding special tokens. A PhoBERT sequence has the following format:
152
+
153
+ - single sequence: `<s> X </s>`
154
+ - pair of sequences: `<s> A </s></s> B </s>`
155
+
156
+ Args:
157
+ token_ids_0 (`List[int]`):
158
+ List of IDs to which the special tokens will be added.
159
+ token_ids_1 (`List[int]`, *optional*):
160
+ Optional second list of IDs for sequence pairs.
161
+
162
+ Returns:
163
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
164
+ """
165
+
166
+ if token_ids_1 is None:
167
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
168
+ cls = [self.cls_token_id]
169
+ sep = [self.sep_token_id]
170
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
171
+
172
+ def get_special_tokens_mask(
173
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
174
+ ) -> List[int]:
175
+ """
176
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
177
+ special tokens using the tokenizer `prepare_for_model` method.
178
+
179
+ Args:
180
+ token_ids_0 (`List[int]`):
181
+ List of IDs.
182
+ token_ids_1 (`List[int]`, *optional*):
183
+ Optional second list of IDs for sequence pairs.
184
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
185
+ Whether or not the token list is already formatted with special tokens for the model.
186
+
187
+ Returns:
188
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
189
+ """
190
+
191
+ if already_has_special_tokens:
192
+ return super().get_special_tokens_mask(
193
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
194
+ )
195
+
196
+ if token_ids_1 is None:
197
+ return [1] + ([0] * len(token_ids_0)) + [1]
198
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
199
+
200
+ def create_token_type_ids_from_sequences(
201
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
202
+ ) -> List[int]:
203
+ """
204
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. PhoBERT does not
205
+ make use of token type ids, therefore a list of zeros is returned.
206
+
207
+ Args:
208
+ token_ids_0 (`List[int]`):
209
+ List of IDs.
210
+ token_ids_1 (`List[int]`, *optional*):
211
+ Optional second list of IDs for sequence pairs.
212
+
213
+ Returns:
214
+ `List[int]`: List of zeros.
215
+ """
216
+
217
+ sep = [self.sep_token_id]
218
+ cls = [self.cls_token_id]
219
+
220
+ if token_ids_1 is None:
221
+ return len(cls + token_ids_0 + sep) * [0]
222
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
223
+
224
+ @property
225
+ def vocab_size(self):
226
+ return len(self.encoder)
227
+
228
+ def get_vocab(self):
229
+ return dict(self.encoder, **self.added_tokens_encoder)
230
+
231
+ def bpe(self, token):
232
+ if token in self.cache:
233
+ return self.cache[token]
234
+ word = tuple(token)
235
+ word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
236
+ pairs = get_pairs(word)
237
+
238
+ if not pairs:
239
+ return token
240
+
241
+ while True:
242
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
243
+ if bigram not in self.bpe_ranks:
244
+ break
245
+ first, second = bigram
246
+ new_word = []
247
+ i = 0
248
+ while i < len(word):
249
+ try:
250
+ j = word.index(first, i)
251
+ except ValueError:
252
+ new_word.extend(word[i:])
253
+ break
254
+ else:
255
+ new_word.extend(word[i:j])
256
+ i = j
257
+
258
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
259
+ new_word.append(first + second)
260
+ i += 2
261
+ else:
262
+ new_word.append(word[i])
263
+ i += 1
264
+ new_word = tuple(new_word)
265
+ word = new_word
266
+ if len(word) == 1:
267
+ break
268
+ else:
269
+ pairs = get_pairs(word)
270
+ word = "@@ ".join(word)
271
+ word = word[:-4]
272
+ self.cache[token] = word
273
+ return word
274
+
275
+ def _tokenize(self, text):
276
+ """Tokenize a string."""
277
+ split_tokens = []
278
+
279
+ words = re.findall(r"\S+\n?", text)
280
+
281
+ for token in words:
282
+ split_tokens.extend(list(self.bpe(token).split(" ")))
283
+ return split_tokens
284
+
285
+ def _convert_token_to_id(self, token):
286
+ """Converts a token (str) in an id using the vocab."""
287
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
288
+
289
+ def _convert_id_to_token(self, index):
290
+ """Converts an index (integer) in a token (str) using the vocab."""
291
+ return self.decoder.get(index, self.unk_token)
292
+
293
+ def convert_tokens_to_string(self, tokens):
294
+ """Converts a sequence of tokens (string) in a single string."""
295
+ out_string = " ".join(tokens).replace("@@ ", "").strip()
296
+ return out_string
297
+
298
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
299
+ if not os.path.isdir(save_directory):
300
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
301
+ return
302
+ out_vocab_file = os.path.join(
303
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
304
+ )
305
+ out_merge_file = os.path.join(
306
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
307
+ )
308
+
309
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
310
+ copyfile(self.vocab_file, out_vocab_file)
311
+ elif not os.path.isfile(self.vocab_file):
312
+ with open(out_vocab_file, "wb") as fi:
313
+ content_spiece_model = self.sp_model.serialized_model_proto()
314
+ fi.write(content_spiece_model)
315
+
316
+ if os.path.abspath(self.merges_file) != os.path.abspath(out_merge_file):
317
+ copyfile(self.merges_file, out_merge_file)
318
+
319
+ return out_vocab_file, out_merge_file
320
+
321
+ # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
322
+ # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
323
+ # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
324
+ # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
325
+ # return ''.join(tokens_generated_so_far)
326
+
327
+ def add_from_file(self, f):
328
+ """
329
+ Loads a pre-existing dictionary from a text file and adds its symbols to this instance.
330
+ """
331
+ if isinstance(f, str):
332
+ try:
333
+ with open(f, "r", encoding="utf-8") as fd:
334
+ self.add_from_file(fd)
335
+ except FileNotFoundError as fnfe:
336
+ raise fnfe
337
+ except UnicodeError:
338
+ raise Exception(f"Incorrect encoding detected in {f}, please rebuild the dataset")
339
+ return
340
+
341
+ lines = f.readlines()
342
+ for lineTmp in lines:
343
+ line = lineTmp.strip()
344
+ idx = line.rfind(" ")
345
+ if idx == -1:
346
+ raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'")
347
+ word = line[:idx]
348
+ self.encoder[word] = len(self.encoder)
349
+
350
+
351
+ __all__ = ["PhobertTokenizer"]
docs/transformers/build/lib/transformers/models/pix2struct/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_pix2struct import *
22
+ from .image_processing_pix2struct import *
23
+ from .modeling_pix2struct import *
24
+ from .processing_pix2struct import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)