shilinxu commited on
Commit
0b59015
·
verified ·
1 Parent(s): dc970de

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen2ViTPreTrainedModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_qwen2_vit.Qwen2VLVisionConfig",
7
+ "AutoModel": "modeling_qwen2_vit.Qwen2ViTPreTrainedModel"
8
+ },
9
+ "depth": 32,
10
+ "embed_dim": 1280,
11
+ "hidden_act": "quick_gelu",
12
+ "hidden_size": 3584,
13
+ "in_channels": 3,
14
+ "in_chans": 3,
15
+ "mlp_ratio": 4,
16
+ "model_type": "qwen2_vit",
17
+ "num_heads": 16,
18
+ "patch_size": 14,
19
+ "spatial_merge_size": 2,
20
+ "spatial_patch_size": 14,
21
+ "temporal_patch_size": 2,
22
+ "torch_dtype": "bfloat16",
23
+ "transformers_version": "4.45.2"
24
+ }
configuration_qwen2_vit.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Any, Dict, List, Optional, Tuple, Union
3
+
4
+ from transformers import PretrainedConfig
5
+
6
+ from transformers.utils import logging
7
+
8
+ logger = logging.get_logger(__name__)
9
+
10
+ class Qwen2VLVisionConfig(PretrainedConfig):
11
+ model_type = "qwen2_vit"
12
+
13
+ def __init__(
14
+ self,
15
+ depth=32,
16
+ embed_dim=1280,
17
+ hidden_size=3584,
18
+ hidden_act="quick_gelu",
19
+ mlp_ratio=4,
20
+ num_heads=16,
21
+ in_channels=3,
22
+ patch_size=14,
23
+ spatial_merge_size=2,
24
+ temporal_patch_size=2,
25
+ **kwargs,
26
+ ):
27
+ super().__init__(**kwargs)
28
+
29
+ self.depth = depth
30
+ self.embed_dim = embed_dim
31
+ self.hidden_size = hidden_size
32
+ self.hidden_act = hidden_act
33
+ self.mlp_ratio = mlp_ratio
34
+ self.num_heads = num_heads
35
+ self.in_channels = in_channels
36
+ self.patch_size = patch_size
37
+ self.spatial_merge_size = spatial_merge_size
38
+ self.temporal_patch_size = temporal_patch_size
39
+
40
+ @classmethod
41
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
42
+ cls._set_token_in_kwargs(kwargs)
43
+
44
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
45
+
46
+ if config_dict.get("model_type") == "qwen2_vl":
47
+ config_dict = config_dict["vision_config"]
48
+
49
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
50
+ logger.warning(
51
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
52
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
53
+ )
54
+
55
+ return cls.from_dict(config_dict, **kwargs)
56
+
image_processing_qwen2_vl.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """Image processor class for Qwen2-VL."""
21
+
22
+ import math
23
+ from typing import Dict, List, Optional, Union
24
+
25
+ import numpy as np
26
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
27
+ from transformers.image_transforms import convert_to_rgb, resize, to_channel_dimension_format
28
+ from transformers.image_utils import (
29
+ OPENAI_CLIP_MEAN,
30
+ OPENAI_CLIP_STD,
31
+ ChannelDimension,
32
+ ImageInput,
33
+ PILImageResampling,
34
+ VideoInput,
35
+ get_image_size,
36
+ infer_channel_dimension_format,
37
+ is_scaled_image,
38
+ is_valid_image,
39
+ make_list_of_images,
40
+ to_numpy_array,
41
+ valid_images,
42
+ validate_preprocess_arguments,
43
+ )
44
+ from transformers.utils import TensorType, is_vision_available, logging
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ if is_vision_available():
51
+ from PIL import Image
52
+
53
+
54
+ def make_batched_images(images) -> List[List[ImageInput]]:
55
+ """
56
+ Accepts images in list or nested list format, and makes a list of images for preprocessing.
57
+
58
+ Args:
59
+ images (`Union[List[List[ImageInput]], List[ImageInput], ImageInput]`):
60
+ The input image.
61
+
62
+ Returns:
63
+ list: A list of images.
64
+ """
65
+ if isinstance(images, (list, tuple)) and isinstance(images[0], (list, tuple)) and is_valid_image(images[0][0]):
66
+ return [img for img_list in images for img in img_list]
67
+
68
+ elif isinstance(images, (list, tuple)) and is_valid_image(images[0]):
69
+ return images
70
+
71
+ elif is_valid_image(images):
72
+ return [images]
73
+
74
+ raise ValueError(f"Could not make batched images from {images}")
75
+
76
+
77
+ # Copied from transformers.models.llava_next_video.image_processing_llava_next_video.make_batched_videos
78
+ def make_batched_videos(videos) -> List[VideoInput]:
79
+ if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0]):
80
+ return videos
81
+
82
+ elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
83
+ if isinstance(videos[0], Image.Image):
84
+ return [videos]
85
+ elif len(videos[0].shape) == 4:
86
+ return [list(video) for video in videos]
87
+
88
+ elif is_valid_image(videos) and len(videos.shape) == 4:
89
+ return [list(videos)]
90
+
91
+ raise ValueError(f"Could not make batched video from {videos}")
92
+
93
+
94
+ def smart_resize(
95
+ height: int, width: int, factor: int = 28, min_pixels: int = 56 * 56, max_pixels: int = 14 * 14 * 4 * 1280
96
+ ):
97
+ """Rescales the image so that the following conditions are met:
98
+
99
+ 1. Both dimensions (height and width) are divisible by 'factor'.
100
+
101
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
102
+
103
+ 3. The aspect ratio of the image is maintained as closely as possible.
104
+
105
+ """
106
+ if height < factor or width < factor:
107
+ raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}")
108
+ elif max(height, width) / min(height, width) > 200:
109
+ raise ValueError(
110
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
111
+ )
112
+ h_bar = round(height / factor) * factor
113
+ w_bar = round(width / factor) * factor
114
+ if h_bar * w_bar > max_pixels:
115
+ beta = math.sqrt((height * width) / max_pixels)
116
+ h_bar = math.floor(height / beta / factor) * factor
117
+ w_bar = math.floor(width / beta / factor) * factor
118
+ elif h_bar * w_bar < min_pixels:
119
+ beta = math.sqrt(min_pixels / (height * width))
120
+ h_bar = math.ceil(height * beta / factor) * factor
121
+ w_bar = math.ceil(width * beta / factor) * factor
122
+ return h_bar, w_bar
123
+
124
+
125
+ class Qwen2ImageProcessor(BaseImageProcessor):
126
+ r"""
127
+ Constructs a Qwen2-VL image processor that dynamically resizes images based on the original images.
128
+
129
+ Args:
130
+ do_resize (`bool`, *optional*, defaults to `True`):
131
+ Whether to resize the image's (height, width) dimensions.
132
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
133
+ Resampling filter to use when resizing the image.
134
+ do_rescale (`bool`, *optional*, defaults to `True`):
135
+ Whether to rescale the image by the specified scale `rescale_factor`.
136
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
137
+ Scale factor to use if rescaling the image.
138
+ do_normalize (`bool`, *optional*, defaults to `True`):
139
+ Whether to normalize the image.
140
+ image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
141
+ Mean to use if normalizing the image. This is a float or list of floats for each channel in the image.
142
+ image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
143
+ Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image.
144
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
145
+ Whether to convert the image to RGB.
146
+ min_pixels (`int`, *optional*, defaults to `56 * 56`):
147
+ The min pixels of the image to resize the image.
148
+ max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`):
149
+ The max pixels of the image to resize the image.
150
+ patch_size (`int`, *optional*, defaults to 14):
151
+ The spacial patch size of the vision encoder.
152
+ temporal_patch_size (`int`, *optional*, defaults to 2):
153
+ The temporal patch size of the vision encoder.
154
+ merge_size (`int`, *optional*, defaults to 2):
155
+ The merge size of the vision encoder to llm encoder.
156
+ """
157
+
158
+ model_input_names = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw"]
159
+
160
+ def __init__(
161
+ self,
162
+ do_resize: bool = True,
163
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
164
+ do_rescale: bool = True,
165
+ rescale_factor: Union[int, float] = 1 / 255,
166
+ do_normalize: bool = True,
167
+ image_mean: Optional[Union[float, List[float]]] = None,
168
+ image_std: Optional[Union[float, List[float]]] = None,
169
+ do_convert_rgb: bool = True,
170
+ min_pixels: int = 56 * 56,
171
+ max_pixels: int = 28 * 28 * 1280,
172
+ patch_size: int = 14,
173
+ temporal_patch_size: int = 2,
174
+ merge_size: int = 2,
175
+ **kwargs,
176
+ ) -> None:
177
+ super().__init__(**kwargs)
178
+ self.do_resize = do_resize
179
+ self.resample = resample
180
+ self.do_rescale = do_rescale
181
+ self.rescale_factor = rescale_factor
182
+ self.do_normalize = do_normalize
183
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
184
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
185
+ self.min_pixels = min_pixels
186
+ self.max_pixels = max_pixels
187
+ self.patch_size = patch_size
188
+ self.temporal_patch_size = temporal_patch_size
189
+ self.merge_size = merge_size
190
+ self.size = {"min_pixels": min_pixels, "max_pixels": max_pixels}
191
+ self.do_convert_rgb = do_convert_rgb
192
+
193
+ def _preprocess(
194
+ self,
195
+ images: Union[ImageInput, VideoInput],
196
+ do_resize: bool = None,
197
+ resample: PILImageResampling = None,
198
+ do_rescale: bool = None,
199
+ rescale_factor: float = None,
200
+ do_normalize: bool = None,
201
+ image_mean: Optional[Union[float, List[float]]] = None,
202
+ image_std: Optional[Union[float, List[float]]] = None,
203
+ do_convert_rgb: bool = None,
204
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
205
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
206
+ ):
207
+ """
208
+ Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.
209
+
210
+ Args:
211
+ images (`ImageInput`):
212
+ Image or batch of images to preprocess. Expects pixel values ranging from 0 to 255. If pixel values range from 0 to 1, set `do_rescale=False`.
213
+ vision_info (`List[Dict]`, *optional*):
214
+ Optional list of dictionaries containing additional information about vision inputs.
215
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
216
+ Whether to resize the image.
217
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
218
+ Resampling filter to use if resizing the image. This can be one of the `PILImageResampling` enums.
219
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
220
+ Whether to rescale the image.
221
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
222
+ Scale factor to use if rescaling the image.
223
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
224
+ Whether to normalize the image.
225
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
226
+ 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.
227
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
228
+ 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.
229
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
230
+ Whether to convert the image to RGB.
231
+ data_format (`ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):
232
+ The channel dimension format for the output image. Can be one of:
233
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
234
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
235
+ - Unset: Use the channel dimension format of the input image.
236
+ input_data_format (`ChannelDimension` or `str`, *optional*):
237
+ The channel dimension format for the input image. Can be one of:
238
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
239
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
240
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
241
+ """
242
+ images = make_list_of_images(images)
243
+
244
+ if do_convert_rgb:
245
+ images = [convert_to_rgb(image) for image in images]
246
+
247
+ # All transformations expect numpy arrays.
248
+ images = [to_numpy_array(image) for image in images]
249
+
250
+ if is_scaled_image(images[0]) and do_rescale:
251
+ logger.warning_once(
252
+ "It looks like you are trying to rescale already rescaled images. If the input"
253
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
254
+ )
255
+ if input_data_format is None:
256
+ # We assume that all images have the same channel dimension format.
257
+ input_data_format = infer_channel_dimension_format(images[0])
258
+
259
+ height, width = get_image_size(images[0], channel_dim=input_data_format)
260
+ resized_height, resized_width = height, width
261
+ processed_images = []
262
+ for image in images:
263
+ if do_resize:
264
+ resized_height, resized_width = smart_resize(
265
+ height,
266
+ width,
267
+ factor=self.patch_size * self.merge_size,
268
+ min_pixels=self.min_pixels,
269
+ max_pixels=self.max_pixels,
270
+ )
271
+ image = resize(
272
+ image, size=(resized_height, resized_width), resample=resample, input_data_format=input_data_format
273
+ )
274
+
275
+ if do_rescale:
276
+ image = self.rescale(image, scale=rescale_factor, input_data_format=input_data_format)
277
+
278
+ if do_normalize:
279
+ image = self.normalize(
280
+ image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
281
+ )
282
+
283
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
284
+ processed_images.append(image)
285
+
286
+ patches = np.array(processed_images)
287
+ if data_format == ChannelDimension.LAST:
288
+ patches = patches.transpose(0, 3, 1, 2)
289
+ if patches.shape[0] == 1:
290
+ patches = np.tile(patches, (self.temporal_patch_size, 1, 1, 1))
291
+ channel = patches.shape[1]
292
+ grid_t = patches.shape[0] // self.temporal_patch_size
293
+ grid_h, grid_w = resized_height // self.patch_size, resized_width // self.patch_size
294
+ patches = patches.reshape(
295
+ grid_t,
296
+ self.temporal_patch_size,
297
+ channel,
298
+ grid_h // self.merge_size,
299
+ self.merge_size,
300
+ self.patch_size,
301
+ grid_w // self.merge_size,
302
+ self.merge_size,
303
+ self.patch_size,
304
+ )
305
+ patches = patches.transpose(0, 3, 6, 4, 7, 2, 1, 5, 8)
306
+ flatten_patches = patches.reshape(
307
+ grid_t * grid_h * grid_w, channel * self.temporal_patch_size * self.patch_size * self.patch_size
308
+ )
309
+
310
+ return flatten_patches, (grid_t, grid_h, grid_w)
311
+
312
+ def preprocess(
313
+ self,
314
+ images: ImageInput,
315
+ videos: VideoInput = None,
316
+ do_resize: bool = None,
317
+ size: Dict[str, int] = None,
318
+ resample: PILImageResampling = None,
319
+ do_rescale: bool = None,
320
+ rescale_factor: float = None,
321
+ do_normalize: bool = None,
322
+ image_mean: Optional[Union[float, List[float]]] = None,
323
+ image_std: Optional[Union[float, List[float]]] = None,
324
+ do_convert_rgb: bool = None,
325
+ return_tensors: Optional[Union[str, TensorType]] = None,
326
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
327
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
328
+ ):
329
+ """
330
+ Args:
331
+ images (`ImageInput`):
332
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
333
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
334
+ videos (`VideoInput`):
335
+ Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If
336
+ passing in videos with pixel values between 0 and 1, set `do_rescale=False`.
337
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
338
+ Whether to resize the image.
339
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
340
+ Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
341
+ the longest edge resized to keep the input aspect ratio.
342
+ resample (`int`, *optional*, defaults to `self.resample`):
343
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
344
+ has an effect if `do_resize` is set to `True`.
345
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
346
+ Whether to rescale the image.
347
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
348
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
349
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
350
+ Whether to normalize the image.
351
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
352
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
353
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
354
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
355
+ `True`.
356
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
357
+ Whether to convert the image to RGB.
358
+ return_tensors (`str` or `TensorType`, *optional*):
359
+ The type of tensors to return. Can be one of:
360
+ - Unset: Return a list of `np.ndarray`.
361
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
362
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
363
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
364
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
365
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
366
+ The channel dimension format for the output image. Can be one of:
367
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
368
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
369
+ - Unset: Use the channel dimension format of the input image.
370
+ input_data_format (`ChannelDimension` or `str`, *optional*):
371
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
372
+ from the input image. Can be one of:
373
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
374
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
375
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
376
+
377
+ """
378
+ do_resize = do_resize if do_resize is not None else self.do_resize
379
+ size = size if size is not None else self.size
380
+ resample = resample if resample is not None else self.resample
381
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
382
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
383
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
384
+ image_mean = image_mean if image_mean is not None else self.image_mean
385
+ image_std = image_std if image_std is not None else self.image_std
386
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
387
+
388
+ if images is not None:
389
+ images = make_batched_images(images)
390
+ if videos is not None:
391
+ videos = make_batched_videos(videos)
392
+
393
+ if images is not None and not valid_images(images):
394
+ raise ValueError(
395
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
396
+ "torch.Tensor, tf.Tensor or jax.ndarray."
397
+ )
398
+
399
+ validate_preprocess_arguments(
400
+ rescale_factor=rescale_factor,
401
+ do_normalize=do_normalize,
402
+ image_mean=image_mean,
403
+ image_std=image_std,
404
+ do_resize=do_resize,
405
+ size=size,
406
+ resample=resample,
407
+ )
408
+
409
+ if images is not None:
410
+ pixel_values, vision_grid_thws = [], []
411
+ for image in images:
412
+ patches, image_grid_thw = self._preprocess(
413
+ image,
414
+ do_resize=do_resize,
415
+ resample=resample,
416
+ do_rescale=do_rescale,
417
+ rescale_factor=rescale_factor,
418
+ do_normalize=do_normalize,
419
+ image_mean=image_mean,
420
+ image_std=image_std,
421
+ data_format=data_format,
422
+ do_convert_rgb=do_convert_rgb,
423
+ input_data_format=input_data_format,
424
+ )
425
+ pixel_values.extend(patches)
426
+ vision_grid_thws.append(image_grid_thw)
427
+ pixel_values = np.array(pixel_values)
428
+ vision_grid_thws = np.array(vision_grid_thws)
429
+ data = {"pixel_values": pixel_values, "image_grid_thw": vision_grid_thws}
430
+
431
+ if videos is not None:
432
+ pixel_values, vision_grid_thws = [], []
433
+ for images in videos:
434
+ patches, video_grid_thw = self._preprocess(
435
+ images,
436
+ do_resize=do_resize,
437
+ resample=resample,
438
+ do_rescale=do_rescale,
439
+ rescale_factor=rescale_factor,
440
+ do_normalize=do_normalize,
441
+ image_mean=image_mean,
442
+ image_std=image_std,
443
+ data_format=data_format,
444
+ do_convert_rgb=do_convert_rgb,
445
+ input_data_format=input_data_format,
446
+ )
447
+ pixel_values.extend(patches)
448
+ vision_grid_thws.append(video_grid_thw)
449
+ pixel_values = np.array(pixel_values)
450
+ vision_grid_thws = np.array(vision_grid_thws)
451
+ data = {"pixel_values_videos": pixel_values, "video_grid_thw": vision_grid_thws}
452
+
453
+ return BatchFeature(data=data, tensor_type=return_tensors)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:571d794b5614851cd52b423dadab31dbeeb3aca41eb706524ba65c30c8208605
3
+ size 1351555936
modeling_qwen2_vit.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """PyTorch Qwen2-VL model."""
21
+
22
+ import math
23
+ from dataclasses import dataclass
24
+ from typing import Any, Dict, List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+ import torch.utils.checkpoint
30
+ from torch.nn import CrossEntropyLoss, LayerNorm
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, StaticCache
34
+ from transformers.generation import GenerationMixin
35
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
36
+ from transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput
37
+ from transformers.modeling_utils import PreTrainedModel
38
+ from transformers.utils import (
39
+ add_start_docstrings,
40
+ add_start_docstrings_to_model_forward,
41
+ is_flash_attn_2_available,
42
+ is_flash_attn_greater_or_equal_2_10,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+
47
+ if is_flash_attn_2_available():
48
+ from flash_attn import flash_attn_varlen_func
49
+
50
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
51
+ else:
52
+ flash_attn_varlen_func = None
53
+
54
+ from .configuration_qwen2_vit import Qwen2VLVisionConfig
55
+
56
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
57
+ def rotate_half(x):
58
+ """Rotates half the hidden dims of the input."""
59
+ x1 = x[..., : x.shape[-1] // 2]
60
+ x2 = x[..., x.shape[-1] // 2 :]
61
+ return torch.cat((-x2, x1), dim=-1)
62
+
63
+ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
64
+ """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
65
+
66
+ Explanation:
67
+ Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
68
+ sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
69
+ vision embedding part, we apply rotary position embedding on temporal, height and width dimension seperately.
70
+ Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
71
+ For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
72
+ height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
73
+ difference with modern LLMs.
74
+
75
+ Args:
76
+ q (`torch.Tensor`): The query tensor.
77
+ k (`torch.Tensor`): The key tensor.
78
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
79
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
80
+ position_ids (`torch.Tensor`):
81
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
82
+ used to pass offsetted position ids when working with a KV-cache.
83
+ mrope_section(`List(int)`):
84
+ Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
85
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
86
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
87
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
88
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
89
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
90
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
91
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
92
+ Returns:
93
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
94
+ """
95
+ mrope_section = mrope_section * 2
96
+ cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
97
+ unsqueeze_dim
98
+ )
99
+ sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
100
+ unsqueeze_dim
101
+ )
102
+
103
+ q_embed = (q * cos) + (rotate_half(q) * sin)
104
+ k_embed = (k * cos) + (rotate_half(k) * sin)
105
+ return q_embed, k_embed
106
+
107
+ def apply_rotary_pos_emb_vision(tensor: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
108
+ orig_dtype = tensor.dtype
109
+ tensor = tensor.float()
110
+ cos = freqs.cos()
111
+ sin = freqs.sin()
112
+ cos = cos.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float()
113
+ sin = sin.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float()
114
+ output = (tensor * cos) + (rotate_half(tensor) * sin)
115
+ output = output.to(orig_dtype)
116
+ return output
117
+
118
+ class VisionRotaryEmbedding(nn.Module):
119
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
120
+ super().__init__()
121
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
122
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
123
+
124
+ def forward(self, seqlen: int) -> torch.Tensor:
125
+ seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
126
+ freqs = torch.outer(seq, self.inv_freq)
127
+ return freqs
128
+
129
+ class PatchEmbed(nn.Module):
130
+ def __init__(
131
+ self,
132
+ patch_size: int = 14,
133
+ temporal_patch_size: int = 2,
134
+ in_channels: int = 3,
135
+ embed_dim: int = 1152,
136
+ ) -> None:
137
+ super().__init__()
138
+ self.patch_size = patch_size
139
+ self.temporal_patch_size = temporal_patch_size
140
+ self.in_channels = in_channels
141
+ self.embed_dim = embed_dim
142
+
143
+ kernel_size = [temporal_patch_size, patch_size, patch_size]
144
+ self.proj = nn.Conv3d(in_channels, embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=False)
145
+
146
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
147
+ target_dtype = self.proj.weight.dtype
148
+ hidden_states = hidden_states.view(
149
+ -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size
150
+ )
151
+ hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim)
152
+ return hidden_states
153
+
154
+ class PatchMerger(nn.Module):
155
+ def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None:
156
+ super().__init__()
157
+ self.hidden_size = context_dim * (spatial_merge_size**2)
158
+ self.ln_q = LayerNorm(context_dim, eps=1e-6)
159
+ self.mlp = nn.Sequential(
160
+ nn.Linear(self.hidden_size, self.hidden_size),
161
+ nn.GELU(),
162
+ nn.Linear(self.hidden_size, dim),
163
+ )
164
+
165
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
166
+ x = self.mlp(self.ln_q(x).view(-1, self.hidden_size))
167
+ return x
168
+
169
+ class VisionMlp(nn.Module):
170
+ def __init__(self, dim: int, hidden_dim: int, hidden_act: str) -> None:
171
+ super().__init__()
172
+ self.fc1 = nn.Linear(dim, hidden_dim)
173
+ self.act = ACT2FN[hidden_act]
174
+ self.fc2 = nn.Linear(hidden_dim, dim)
175
+
176
+ def forward(self, x) -> torch.Tensor:
177
+ return self.fc2(self.act(self.fc1(x)))
178
+
179
+ class VisionAttention(nn.Module):
180
+ def __init__(self, dim: int, num_heads: int = 16) -> None:
181
+ super().__init__()
182
+ self.num_heads = num_heads
183
+ self.head_dim = dim // num_heads
184
+ self.qkv = nn.Linear(dim, dim * 3, bias=True)
185
+ self.proj = nn.Linear(dim, dim)
186
+
187
+ def forward(
188
+ self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb: torch.Tensor = None
189
+ ) -> torch.Tensor:
190
+ seq_length = hidden_states.shape[0]
191
+ q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
192
+ q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
193
+ k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
194
+
195
+ attention_mask = torch.full(
196
+ [1, seq_length, seq_length], torch.finfo(q.dtype).min, device=q.device, dtype=q.dtype
197
+ )
198
+ for i in range(1, len(cu_seqlens)):
199
+ attention_mask[..., cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i]] = 0
200
+
201
+ q = q.transpose(0, 1)
202
+ k = k.transpose(0, 1)
203
+ v = v.transpose(0, 1)
204
+ attn_weights = torch.matmul(q, k.transpose(1, 2)) / math.sqrt(self.head_dim)
205
+ attn_weights = attn_weights + attention_mask
206
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
207
+ attn_output = torch.matmul(attn_weights, v)
208
+ attn_output = attn_output.transpose(0, 1)
209
+ attn_output = attn_output.reshape(seq_length, -1)
210
+ attn_output = self.proj(attn_output)
211
+ return attn_output
212
+
213
+ class VisionFlashAttention2(nn.Module):
214
+ def __init__(self, dim: int, num_heads: int = 16) -> None:
215
+ super().__init__()
216
+ self.num_heads = num_heads
217
+ self.qkv = nn.Linear(dim, dim * 3, bias=True)
218
+ self.proj = nn.Linear(dim, dim)
219
+
220
+ def forward(
221
+ self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb: torch.Tensor = None
222
+ ) -> torch.Tensor:
223
+ seq_length = hidden_states.shape[0]
224
+ q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
225
+ q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
226
+ k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
227
+
228
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item()
229
+ attn_output = flash_attn_varlen_func(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen).reshape(
230
+ seq_length, -1
231
+ )
232
+ attn_output = self.proj(attn_output)
233
+ return attn_output
234
+
235
+ class VisionSdpaAttention(nn.Module):
236
+ def __init__(self, dim: int, num_heads: int = 16) -> None:
237
+ super().__init__()
238
+ self.num_heads = num_heads
239
+ self.qkv = nn.Linear(dim, dim * 3, bias=True)
240
+ self.proj = nn.Linear(dim, dim)
241
+
242
+ def forward(
243
+ self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb: torch.Tensor = None
244
+ ) -> torch.Tensor:
245
+ seq_length = hidden_states.shape[0]
246
+ q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
247
+ q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
248
+ k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
249
+
250
+ attention_mask = torch.zeros([1, seq_length, seq_length], device=q.device, dtype=torch.bool)
251
+ for i in range(1, len(cu_seqlens)):
252
+ attention_mask[..., cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i]] = True
253
+ q = q.transpose(0, 1)
254
+ k = k.transpose(0, 1)
255
+ v = v.transpose(0, 1)
256
+ attn_output = F.scaled_dot_product_attention(q, k, v, attention_mask, dropout_p=0.0)
257
+ attn_output = attn_output.transpose(0, 1)
258
+ attn_output = attn_output.reshape(seq_length, -1)
259
+ attn_output = self.proj(attn_output)
260
+ return attn_output
261
+
262
+ QWEN2_VL_VISION_ATTENTION_CLASSES = {
263
+ "eager": VisionAttention,
264
+ "flash_attention_2": VisionFlashAttention2,
265
+ "sdpa": VisionSdpaAttention,
266
+ }
267
+
268
+ class Qwen2VLVisionBlock(nn.Module):
269
+ def __init__(self, config, attn_implementation: str = "sdpa") -> None:
270
+ super().__init__()
271
+ self.norm1 = LayerNorm(config.embed_dim, eps=1e-6)
272
+ self.norm2 = LayerNorm(config.embed_dim, eps=1e-6)
273
+ mlp_hidden_dim = int(config.embed_dim * config.mlp_ratio)
274
+
275
+ self.attn = QWEN2_VL_VISION_ATTENTION_CLASSES[attn_implementation](
276
+ config.embed_dim, num_heads=config.num_heads
277
+ )
278
+ self.mlp = VisionMlp(dim=config.embed_dim, hidden_dim=mlp_hidden_dim, hidden_act=config.hidden_act)
279
+
280
+ def forward(self, hidden_states, cu_seqlens, rotary_pos_emb) -> torch.Tensor:
281
+ hidden_states = hidden_states + self.attn(
282
+ self.norm1(hidden_states), cu_seqlens=cu_seqlens, rotary_pos_emb=rotary_pos_emb
283
+ )
284
+ hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
285
+ return hidden_states
286
+
287
+ class Qwen2ViTPreTrainedModel(PreTrainedModel):
288
+ config_class = Qwen2VLVisionConfig
289
+ _no_split_modules = ["Qwen2VLVisionBlock"]
290
+
291
+ def __init__(self, config) -> None:
292
+ super().__init__(config)
293
+ self.spatial_merge_size = config.spatial_merge_size
294
+
295
+ self.patch_embed = PatchEmbed(
296
+ patch_size=config.patch_size,
297
+ temporal_patch_size=config.temporal_patch_size,
298
+ in_channels=config.in_channels,
299
+ embed_dim=config.embed_dim,
300
+ )
301
+
302
+ head_dim = config.embed_dim // config.num_heads
303
+ self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)
304
+
305
+ self.blocks = nn.ModuleList(
306
+ [Qwen2VLVisionBlock(config, config._attn_implementation) for _ in range(config.depth)]
307
+ )
308
+ self.merger = PatchMerger(
309
+ dim=config.hidden_size, context_dim=config.embed_dim, spatial_merge_size=config.spatial_merge_size
310
+ )
311
+
312
+ def get_dtype(self) -> torch.dtype:
313
+ return self.blocks[0].mlp.fc2.weight.dtype
314
+
315
+ def get_device(self) -> torch.device:
316
+ return self.blocks[0].mlp.fc2.weight.device
317
+
318
+ def rot_pos_emb(self, grid_thw):
319
+ pos_ids = []
320
+ for t, h, w in grid_thw:
321
+ hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
322
+ hpos_ids = hpos_ids.reshape(
323
+ h // self.spatial_merge_size,
324
+ self.spatial_merge_size,
325
+ w // self.spatial_merge_size,
326
+ self.spatial_merge_size,
327
+ )
328
+ hpos_ids = hpos_ids.permute(0, 2, 1, 3)
329
+ hpos_ids = hpos_ids.flatten()
330
+
331
+ wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
332
+ wpos_ids = wpos_ids.reshape(
333
+ h // self.spatial_merge_size,
334
+ self.spatial_merge_size,
335
+ w // self.spatial_merge_size,
336
+ self.spatial_merge_size,
337
+ )
338
+ wpos_ids = wpos_ids.permute(0, 2, 1, 3)
339
+ wpos_ids = wpos_ids.flatten()
340
+ pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
341
+ pos_ids = torch.cat(pos_ids, dim=0)
342
+ max_grid_size = grid_thw[:, 1:].max()
343
+ rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
344
+ rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
345
+ return rotary_pos_emb
346
+
347
+ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor) -> torch.Tensor:
348
+ hidden_states = self.patch_embed(hidden_states)
349
+ rotary_pos_emb = self.rot_pos_emb(grid_thw)
350
+
351
+ cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
352
+ dim=0, dtype=torch.int32
353
+ )
354
+ cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
355
+
356
+ for blk in self.blocks:
357
+ hidden_states = blk(hidden_states, cu_seqlens=cu_seqlens, rotary_pos_emb=rotary_pos_emb)
358
+
359
+ return self.merger(hidden_states)
360
+
preprocessor_config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoImageProcessor": "image_processing_qwen2_vl.Qwen2ImageProcessor"
4
+ },
5
+ "do_convert_rgb": true,
6
+ "do_normalize": true,
7
+ "do_rescale": true,
8
+ "do_resize": true,
9
+ "image_mean": [
10
+ 0.48145466,
11
+ 0.4578275,
12
+ 0.40821073
13
+ ],
14
+ "image_processor_type": "Qwen2ImageProcessor",
15
+ "image_std": [
16
+ 0.26862954,
17
+ 0.26130258,
18
+ 0.27577711
19
+ ],
20
+ "max_pixels": 12845056,
21
+ "merge_size": 2,
22
+ "min_pixels": 3136,
23
+ "patch_size": 14,
24
+ "resample": 3,
25
+ "rescale_factor": 0.00392156862745098,
26
+ "size": {
27
+ "max_pixels": 12845056,
28
+ "min_pixels": 3136
29
+ },
30
+ "temporal_patch_size": 2
31
+ }