JiahuanCao commited on
Commit
0e86fcc
·
verified ·
1 Parent(s): de7478b

Upload 13 files

Browse files
chat_template.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "chat_template": "{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n{% endif %}<|im_start|>{{ message['role'] }}\n{% if message['content'] is string %}{{ message['content'] }}<|im_end|>\n{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}"
3
+ }
config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "../models/Qwen2-VL-2B-Instruct",
3
+ "architectures": [
4
+ "Qwen2VLForConditionalGeneration"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_tonggu_vl.Qwen2VLConfig",
8
+ "AutoModel": "modeling_tonggu_vl.TongguVLForConditionalGeneration",
9
+ "AutoModelForCausalLM": "modeling_tonggu_vl.TongguVLForConditionalGeneration"
10
+ },
11
+ "attention_dropout": 0.0,
12
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151645,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 1536,
16
+ "image_token_id": 151655,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 8960,
19
+ "max_position_embeddings": 32768,
20
+ "max_window_layers": 28,
21
+ "model_type": "qwen2_vl",
22
+ "num_attention_heads": 12,
23
+ "num_hidden_layers": 28,
24
+ "num_key_value_heads": 2,
25
+ "rms_norm_eps": 1e-06,
26
+ "rope_scaling": {
27
+ "mrope_section": [
28
+ 16,
29
+ 24,
30
+ 24
31
+ ],
32
+ "rope_type": "default",
33
+ "type": "default"
34
+ },
35
+ "rope_theta": 1000000.0,
36
+ "sliding_window": 32768,
37
+ "tie_word_embeddings": true,
38
+ "tokenizer_padding_side": "right",
39
+ "torch_dtype": "bfloat16",
40
+ "transformers_version": "4.45.2",
41
+ "use_cache": true,
42
+ "use_sliding_window": false,
43
+ "video_token_id": 151656,
44
+ "vision_config": {
45
+ "hidden_size": 1536,
46
+ "in_chans": 3,
47
+ "model_type": "qwen2_vl",
48
+ "spatial_patch_size": 14
49
+ },
50
+ "vision_end_token_id": 151653,
51
+ "vision_lr": null,
52
+ "vision_start_token_id": 151652,
53
+ "vision_token_id": 151654,
54
+ "vocab_size": 151936
55
+ }
configuration_tonggu_vl.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group 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
+ """Qwen2VL model configuration"""
16
+
17
+ import os
18
+ from typing import Union
19
+
20
+ from transformers.configuration_utils import PretrainedConfig
21
+ from transformers.modeling_rope_utils import rope_config_validation
22
+ from transformers.utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class Qwen2VLVisionConfig(PretrainedConfig):
29
+ model_type = "qwen2_vl"
30
+
31
+ def __init__(
32
+ self,
33
+ depth=32,
34
+ embed_dim=1280,
35
+ hidden_size=3584,
36
+ hidden_act="quick_gelu",
37
+ mlp_ratio=4,
38
+ num_heads=16,
39
+ in_channels=3,
40
+ patch_size=14,
41
+ spatial_merge_size=2,
42
+ temporal_patch_size=2,
43
+ **kwargs,
44
+ ):
45
+ super().__init__(**kwargs)
46
+
47
+ self.depth = depth
48
+ self.embed_dim = embed_dim
49
+ self.hidden_size = hidden_size
50
+ self.hidden_act = hidden_act
51
+ self.mlp_ratio = mlp_ratio
52
+ self.num_heads = num_heads
53
+ self.in_channels = in_channels
54
+ self.patch_size = patch_size
55
+ self.spatial_merge_size = spatial_merge_size
56
+ self.temporal_patch_size = temporal_patch_size
57
+
58
+ @classmethod
59
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
60
+ cls._set_token_in_kwargs(kwargs)
61
+
62
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
63
+
64
+ if config_dict.get("model_type") == "qwen2_vl":
65
+ config_dict = config_dict["vision_config"]
66
+
67
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
68
+ logger.warning(
69
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
70
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
71
+ )
72
+
73
+ return cls.from_dict(config_dict, **kwargs)
74
+
75
+
76
+ class Qwen2VLConfig(PretrainedConfig):
77
+ r"""
78
+ This is the configuration class to store the configuration of a [`Qwen2VLModel`]. It is used to instantiate a
79
+ Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration
80
+ with the defaults will yield a similar configuration to that of
81
+ Qwen2-VL-7B-Instruct [Qwen/Qwen2-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct).
82
+
83
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
84
+ documentation from [`PretrainedConfig`] for more information.
85
+
86
+
87
+ Args:
88
+ vocab_size (`int`, *optional*, defaults to 152064):
89
+ Vocabulary size of the Qwen2VL model. Defines the number of different tokens that can be represented by the
90
+ `inputs_ids` passed when calling [`Qwen2VLModel`]
91
+ hidden_size (`int`, *optional*, defaults to 8192):
92
+ Dimension of the hidden representations.
93
+ intermediate_size (`int`, *optional*, defaults to 29568):
94
+ Dimension of the MLP representations.
95
+ num_hidden_layers (`int`, *optional*, defaults to 80):
96
+ Number of hidden layers in the Transformer encoder.
97
+ num_attention_heads (`int`, *optional*, defaults to 64):
98
+ Number of attention heads for each attention layer in the Transformer encoder.
99
+ num_key_value_heads (`int`, *optional*, defaults to 8):
100
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
101
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
102
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
103
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
104
+ by meanpooling all the original heads within that group. For more details checkout [this
105
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
106
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
107
+ The non-linear activation function (function or string) in the decoder.
108
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
109
+ The maximum sequence length that this model might ever be used with.
110
+ initializer_range (`float`, *optional*, defaults to 0.02):
111
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
112
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
113
+ The epsilon used by the rms normalization layers.
114
+ use_cache (`bool`, *optional*, defaults to `True`):
115
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
116
+ relevant if `config.is_decoder=True`.
117
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
118
+ Whether the model's input and output word embeddings should be tied.
119
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
120
+ The base period of the RoPE embeddings.
121
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
122
+ Whether to use sliding window attention.
123
+ sliding_window (`int`, *optional*, defaults to 4096):
124
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
125
+ max_window_layers (`int`, *optional*, defaults to 80):
126
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
127
+ attention_dropout (`float`, *optional*, defaults to 0.0):
128
+ The dropout ratio for the attention probabilities.
129
+ vision_config (`Dict`, *optional*):
130
+ The config for the visual encoder initialization.
131
+ rope_scaling (`Dict`, *optional*):
132
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
133
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
134
+ accordingly.
135
+ Expected contents:
136
+ `rope_type` (`str`):
137
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
138
+ 'llama3'], with 'default' being the original RoPE implementation.
139
+ `factor` (`float`, *optional*):
140
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
141
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
142
+ original maximum pre-trained length.
143
+ `original_max_position_embeddings` (`int`, *optional*):
144
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
145
+ pretraining.
146
+ `attention_factor` (`float`, *optional*):
147
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
148
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
149
+ `factor` field to infer the suggested value.
150
+ `beta_fast` (`float`, *optional*):
151
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
152
+ ramp function. If unspecified, it defaults to 32.
153
+ `beta_slow` (`float`, *optional*):
154
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
155
+ ramp function. If unspecified, it defaults to 1.
156
+ `short_factor` (`List[float]`, *optional*):
157
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
158
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
159
+ size divided by the number of attention heads divided by 2
160
+ `long_factor` (`List[float]`, *optional*):
161
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
162
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
163
+ size divided by the number of attention heads divided by 2
164
+ `low_freq_factor` (`float`, *optional*):
165
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
166
+ `high_freq_factor` (`float`, *optional*):
167
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
168
+
169
+ ```python
170
+ >>> from transformers import Qwen2VLForConditionalGeneration, Qwen2VLConfig
171
+
172
+ >>> # Initializing a Qwen2VL style configuration
173
+ >>> configuration = Qwen2VLConfig()
174
+
175
+ >>> # Initializing a model from the Qwen2-VL-7B style configuration
176
+ >>> model = Qwen2VLForConditionalGeneration(configuration)
177
+
178
+ >>> # Accessing the model configuration
179
+ >>> configuration = model.config
180
+ ```"""
181
+
182
+ model_type = "qwen2_vl"
183
+ keys_to_ignore_at_inference = ["past_key_values"]
184
+
185
+ def __init__(
186
+ self,
187
+ vocab_size=152064,
188
+ hidden_size=8192,
189
+ intermediate_size=29568,
190
+ num_hidden_layers=80,
191
+ num_attention_heads=64,
192
+ num_key_value_heads=8,
193
+ hidden_act="silu",
194
+ max_position_embeddings=32768,
195
+ initializer_range=0.02,
196
+ rms_norm_eps=1e-05,
197
+ use_cache=True,
198
+ tie_word_embeddings=False,
199
+ rope_theta=1000000.0,
200
+ use_sliding_window=False,
201
+ sliding_window=4096,
202
+ max_window_layers=80,
203
+ attention_dropout=0.0,
204
+ vision_config=None,
205
+ rope_scaling=None,
206
+ **kwargs,
207
+ ):
208
+ if isinstance(vision_config, dict):
209
+ self.vision_config = Qwen2VLVisionConfig(**vision_config)
210
+ elif vision_config is None:
211
+ self.vision_config = Qwen2VLVisionConfig()
212
+
213
+ self.vocab_size = vocab_size
214
+ self.max_position_embeddings = max_position_embeddings
215
+ self.hidden_size = hidden_size
216
+ self.intermediate_size = intermediate_size
217
+ self.num_hidden_layers = num_hidden_layers
218
+ self.num_attention_heads = num_attention_heads
219
+ self.use_sliding_window = use_sliding_window
220
+ self.sliding_window = sliding_window
221
+ self.max_window_layers = max_window_layers
222
+
223
+ # for backward compatibility
224
+ if num_key_value_heads is None:
225
+ num_key_value_heads = num_attention_heads
226
+
227
+ self.num_key_value_heads = num_key_value_heads
228
+ self.hidden_act = hidden_act
229
+ self.initializer_range = initializer_range
230
+ self.rms_norm_eps = rms_norm_eps
231
+ self.use_cache = use_cache
232
+ self.rope_theta = rope_theta
233
+ self.attention_dropout = attention_dropout
234
+ self.rope_scaling = rope_scaling
235
+
236
+ # Validate the correctness of rotary position embeddings parameters
237
+ # BC: if there is a 'type' field, move it to 'rope_type'.
238
+ # and change type from 'mrope' to 'default' because `mrope` does defeault RoPE calculations
239
+ # one can set it to "linear"/"dynamic" etc. to have scaled RoPE
240
+ # TODO: @raushan update config in the hub
241
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
242
+ if self.rope_scaling["type"] == "mrope":
243
+ self.rope_scaling["type"] = "default"
244
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
245
+ rope_config_validation(self, ignore_keys={"mrope_section"})
246
+
247
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attn_implementation": "sdpa",
3
+ "bos_token_id": 151643,
4
+ "do_sample": true,
5
+ "eos_token_id": [
6
+ 151645,
7
+ 151643
8
+ ],
9
+ "pad_token_id": 151643,
10
+ "temperature": 0.01,
11
+ "top_k": 1,
12
+ "top_p": 0.001,
13
+ "transformers_version": "4.45.2"
14
+ }
image_processing_tonggu_vl.py ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Image processor class for Qwen2-VL."""
2
+
3
+ import math
4
+ from typing import Dict, List, Optional, Union
5
+
6
+ import numpy as np
7
+
8
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
9
+ from transformers.image_transforms import (
10
+ convert_to_rgb,
11
+ resize,
12
+ to_channel_dimension_format,
13
+ )
14
+ from transformers.image_utils import (
15
+ OPENAI_CLIP_MEAN,
16
+ OPENAI_CLIP_STD,
17
+ ChannelDimension,
18
+ ImageInput,
19
+ PILImageResampling,
20
+ VideoInput,
21
+ get_image_size,
22
+ infer_channel_dimension_format,
23
+ is_scaled_image,
24
+ is_valid_image,
25
+ make_list_of_images,
26
+ to_numpy_array,
27
+ valid_images,
28
+ validate_preprocess_arguments,
29
+ )
30
+ from transformers.utils import TensorType, is_vision_available, logging
31
+
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ if is_vision_available():
37
+ from PIL import Image
38
+ # Image.MAX_IMAGE_PIXELS = None
39
+
40
+
41
+ # 将输入图片处理成列表
42
+ def make_batched_images(images) -> List[List[ImageInput]]:
43
+ """
44
+ Accepts images in list or nested list format, and makes a list of images for preprocessing.
45
+
46
+ Args:
47
+ images (`Union[List[List[ImageInput]], List[ImageInput], ImageInput]`):
48
+ The input image.
49
+
50
+ Returns:
51
+ list: A list of images.
52
+ """
53
+ if isinstance(images, (list, tuple)) and isinstance(images[0], (list, tuple)) and is_valid_image(images[0][0]):
54
+ return [img for img_list in images for img in img_list]
55
+
56
+ elif isinstance(images, (list, tuple)) and is_valid_image(images[0]):
57
+ return images
58
+
59
+ elif is_valid_image(images):
60
+ return [images]
61
+
62
+ raise ValueError(f"Could not make batched images from {images}")
63
+
64
+
65
+ # 将输入视频处理成列表
66
+ # Copied from transformers.models.llava_next_video.image_processing_llava_next_video.make_batched_videos
67
+ def make_batched_videos(videos) -> List[VideoInput]:
68
+ if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0]):
69
+ return videos
70
+
71
+ elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
72
+ if isinstance(videos[0], Image.Image):
73
+ return [videos]
74
+ elif len(videos[0].shape) == 4:
75
+ return [list(video) for video in videos]
76
+
77
+ elif is_valid_image(videos) and len(videos.shape) == 4:
78
+ return [list(videos)]
79
+
80
+ raise ValueError(f"Could not make batched video from {videos}")
81
+
82
+
83
+ def smart_resize(
84
+ height: int, width: int, factor: int = 28, min_pixels: int = 56 * 56, max_pixels: int = 14 * 14 * 4 * 1280
85
+ ):
86
+ """Rescales the image so that the following conditions are met:
87
+
88
+ 1. Both dimensions (height and width) are divisible by 'factor'.
89
+
90
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
91
+
92
+ 3. The aspect ratio of the image is maintained as closely as possible.
93
+
94
+ """
95
+ if height < factor or width < factor:
96
+ raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}")
97
+ elif max(height, width) / min(height, width) > 200:
98
+ raise ValueError(
99
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
100
+ )
101
+ h_bar = round(height / factor) * factor
102
+ w_bar = round(width / factor) * factor
103
+ if h_bar * w_bar > max_pixels:
104
+ beta = math.sqrt((height * width) / max_pixels)
105
+ h_bar = math.floor(height / beta / factor) * factor
106
+ w_bar = math.floor(width / beta / factor) * factor
107
+ elif h_bar * w_bar < min_pixels:
108
+ beta = math.sqrt(min_pixels / (height * width))
109
+ h_bar = math.ceil(height * beta / factor) * factor
110
+ w_bar = math.ceil(width * beta / factor) * factor
111
+ return h_bar, w_bar
112
+
113
+
114
+ class Qwen2VLImageProcessor(BaseImageProcessor):
115
+ r"""
116
+ Constructs a Qwen2-VL image processor that dynamically resizes images based on the original images.
117
+
118
+ Args:
119
+ do_resize (`bool`, *optional*, defaults to `True`):
120
+ Whether to resize the image's (height, width) dimensions.
121
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
122
+ Resampling filter to use when resizing the image.
123
+ do_rescale (`bool`, *optional*, defaults to `True`):
124
+ Whether to rescale the image by the specified scale `rescale_factor`.
125
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
126
+ Scale factor to use if rescaling the image.
127
+ do_normalize (`bool`, *optional*, defaults to `True`):
128
+ Whether to normalize the image.
129
+ image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
130
+ Mean to use if normalizing the image. This is a float or list of floats for each channel in the image.
131
+ image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
132
+ Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image.
133
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
134
+ Whether to convert the image to RGB.
135
+ min_pixels (`int`, *optional*, defaults to `56 * 56`):
136
+ The min pixels of the image to resize the image.
137
+ max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`):
138
+ The max pixels of the image to resize the image.
139
+ patch_size (`int`, *optional*, defaults to 14):
140
+ The spacial patch size of the vision encoder.
141
+ temporal_patch_size (`int`, *optional*, defaults to 2):
142
+ The temporal patch size of the vision encoder.
143
+ merge_size (`int`, *optional*, defaults to 2):
144
+ The merge size of the vision encoder to llm encoder.
145
+ """
146
+
147
+ model_input_names = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw"]
148
+
149
+ def __init__(
150
+ self,
151
+ do_resize: bool = True,
152
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
153
+ do_rescale: bool = True,
154
+ rescale_factor: Union[int, float] = 1 / 255,
155
+ do_normalize: bool = True,
156
+ image_mean: Optional[Union[float, List[float]]] = None,
157
+ image_std: Optional[Union[float, List[float]]] = None,
158
+ do_convert_rgb: bool = True,
159
+ min_pixels: int = 56 * 56,
160
+ max_pixels: int = 28 * 28 * 1280,
161
+ patch_size: int = 14,
162
+ temporal_patch_size: int = 2,
163
+ merge_size: int = 2,
164
+ **kwargs,
165
+ ) -> None:
166
+ super().__init__(**kwargs)
167
+ self.do_resize = do_resize
168
+ self.resample = resample
169
+ self.do_rescale = do_rescale
170
+ self.rescale_factor = rescale_factor
171
+ self.do_normalize = do_normalize
172
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
173
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
174
+ self.min_pixels = min_pixels
175
+ self.max_pixels = max_pixels
176
+ self.patch_size = patch_size
177
+ self.temporal_patch_size = temporal_patch_size
178
+ self.merge_size = merge_size
179
+ self.size = {"min_pixels": min_pixels, "max_pixels": max_pixels}
180
+ self.do_convert_rgb = do_convert_rgb
181
+
182
+ # RGB转换
183
+ # 调整图像尺寸
184
+ # 像素值缩放
185
+ # 标准化处理
186
+ # 调整通道维度数
187
+ # 分patch处理
188
+ def _preprocess(
189
+ self,
190
+ images: Union[ImageInput, VideoInput],
191
+ do_resize: bool = None,
192
+ resample: PILImageResampling = None,
193
+ do_rescale: bool = None,
194
+ rescale_factor: float = None,
195
+ do_normalize: bool = None,
196
+ image_mean: Optional[Union[float, List[float]]] = None,
197
+ image_std: Optional[Union[float, List[float]]] = None,
198
+ do_convert_rgb: bool = None,
199
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
200
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
201
+ ):
202
+ """
203
+ Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.
204
+
205
+ Args:
206
+ images (`ImageInput`):
207
+ 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`.
208
+ vision_info (`List[Dict]`, *optional*):
209
+ Optional list of dictionaries containing additional information about vision inputs.
210
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
211
+ Whether to resize the image.
212
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
213
+ Resampling filter to use if resizing the image. This can be one of the `PILImageResampling` enums.
214
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
215
+ Whether to rescale the image.
216
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
217
+ Scale factor to use if rescaling the image.
218
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
219
+ Whether to normalize the image.
220
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
221
+ 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.
222
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
223
+ 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.
224
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
225
+ Whether to convert the image to RGB.
226
+ data_format (`ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):
227
+ The channel dimension format for the output image. Can be one of:
228
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
229
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
230
+ - Unset: Use the channel dimension format of the input image.
231
+ input_data_format (`ChannelDimension` or `str`, *optional*):
232
+ The channel dimension format for the input 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
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
236
+ """
237
+ images = make_list_of_images(images)
238
+
239
+ if do_convert_rgb:
240
+ images = [convert_to_rgb(image) for image in images]
241
+
242
+ # All transformations expect numpy arrays.
243
+ images = [to_numpy_array(image) for image in images]
244
+
245
+ if is_scaled_image(images[0]) and do_rescale:
246
+ logger.warning_once(
247
+ "It looks like you are trying to rescale already rescaled images. If the input"
248
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
249
+ )
250
+ if input_data_format is None:
251
+ # We assume that all images have the same channel dimension format.
252
+ input_data_format = infer_channel_dimension_format(images[0])
253
+
254
+ height, width = get_image_size(images[0], channel_dim=input_data_format)
255
+ resized_height, resized_width = height, width
256
+ processed_images = []
257
+ for image in images:
258
+ if do_resize:
259
+ resized_height, resized_width = smart_resize(
260
+ height,
261
+ width,
262
+ factor=self.patch_size * self.merge_size,
263
+ min_pixels=self.min_pixels,
264
+ max_pixels=self.max_pixels,
265
+ )
266
+ image = resize(
267
+ image, size=(resized_height, resized_width), resample=resample, input_data_format=input_data_format
268
+ )
269
+
270
+ if do_rescale:
271
+ image = self.rescale(image, scale=rescale_factor, input_data_format=input_data_format)
272
+
273
+ if do_normalize:
274
+ image = self.normalize(
275
+ image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
276
+ )
277
+
278
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
279
+ processed_images.append(image)
280
+
281
+ patches = np.array(processed_images)
282
+ if data_format == ChannelDimension.LAST:
283
+ patches = patches.transpose(0, 3, 1, 2)
284
+ if patches.shape[0] == 1:
285
+ patches = np.tile(patches, (self.temporal_patch_size, 1, 1, 1))
286
+ channel = patches.shape[1]
287
+ grid_t = patches.shape[0] // self.temporal_patch_size
288
+ grid_h, grid_w = resized_height // self.patch_size, resized_width // self.patch_size
289
+ patches = patches.reshape(
290
+ grid_t,
291
+ self.temporal_patch_size,
292
+ channel,
293
+ grid_h // self.merge_size,
294
+ self.merge_size,
295
+ self.patch_size,
296
+ grid_w // self.merge_size,
297
+ self.merge_size,
298
+ self.patch_size,
299
+ )
300
+ patches = patches.transpose(0, 3, 6, 4, 7, 2, 1, 5, 8)
301
+ flatten_patches = patches.reshape(
302
+ grid_t * grid_h * grid_w, channel * self.temporal_patch_size * self.patch_size * self.patch_size
303
+ )
304
+
305
+ return flatten_patches, (grid_t, grid_h, grid_w)
306
+
307
+ def preprocess(
308
+ self,
309
+ images: ImageInput,
310
+ videos: VideoInput = None,
311
+ do_resize: bool = None,
312
+ size: Dict[str, int] = None,
313
+ resample: PILImageResampling = None,
314
+ do_rescale: bool = None,
315
+ rescale_factor: float = None,
316
+ do_normalize: bool = None,
317
+ image_mean: Optional[Union[float, List[float]]] = None,
318
+ image_std: Optional[Union[float, List[float]]] = None,
319
+ do_convert_rgb: bool = None,
320
+ return_tensors: Optional[Union[str, TensorType]] = None,
321
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
322
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
323
+ ):
324
+ """
325
+ Args:
326
+ images (`ImageInput`):
327
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
328
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
329
+ videos (`VideoInput`):
330
+ Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If
331
+ passing in videos with pixel values between 0 and 1, set `do_rescale=False`.
332
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
333
+ Whether to resize the image.
334
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
335
+ Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
336
+ the longest edge resized to keep the input aspect ratio.
337
+ resample (`int`, *optional*, defaults to `self.resample`):
338
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
339
+ has an effect if `do_resize` is set to `True`.
340
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
341
+ Whether to rescale the image.
342
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
343
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
344
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
345
+ Whether to normalize the image.
346
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
347
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
348
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
349
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
350
+ `True`.
351
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
352
+ Whether to convert the image to RGB.
353
+ return_tensors (`str` or `TensorType`, *optional*):
354
+ The type of tensors to return. Can be one of:
355
+ - Unset: Return a list of `np.ndarray`.
356
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
357
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
358
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
359
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
360
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
361
+ The channel dimension format for the output image. Can be one of:
362
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
363
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
364
+ - Unset: Use the channel dimension format of the input image.
365
+ input_data_format (`ChannelDimension` or `str`, *optional*):
366
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
367
+ from the input image. Can be one of:
368
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
369
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
370
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
371
+
372
+ """
373
+ do_resize = do_resize if do_resize is not None else self.do_resize
374
+ size = size if size is not None else self.size
375
+ resample = resample if resample is not None else self.resample
376
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
377
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
378
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
379
+ image_mean = image_mean if image_mean is not None else self.image_mean
380
+ image_std = image_std if image_std is not None else self.image_std
381
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
382
+
383
+ if images is not None:
384
+ images = make_batched_images(images)
385
+ if videos is not None:
386
+ videos = make_batched_videos(videos)
387
+
388
+ if images is not None and not valid_images(images):
389
+ raise ValueError(
390
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
391
+ "torch.Tensor, tf.Tensor or jax.ndarray."
392
+ )
393
+
394
+ validate_preprocess_arguments(
395
+ rescale_factor=rescale_factor,
396
+ do_normalize=do_normalize,
397
+ image_mean=image_mean,
398
+ image_std=image_std,
399
+ do_resize=do_resize,
400
+ size=size,
401
+ resample=resample,
402
+ )
403
+
404
+ if images is not None:
405
+ pixel_values, vision_grid_thws = [], []
406
+ for image in images:
407
+ patches, image_grid_thw = self._preprocess(
408
+ image,
409
+ do_resize=do_resize,
410
+ resample=resample,
411
+ do_rescale=do_rescale,
412
+ rescale_factor=rescale_factor,
413
+ do_normalize=do_normalize,
414
+ image_mean=image_mean,
415
+ image_std=image_std,
416
+ data_format=data_format,
417
+ do_convert_rgb=do_convert_rgb,
418
+ input_data_format=input_data_format,
419
+ )
420
+ pixel_values.extend(patches)
421
+ vision_grid_thws.append(image_grid_thw)
422
+ pixel_values = np.array(pixel_values)
423
+ vision_grid_thws = np.array(vision_grid_thws)
424
+ data = {"pixel_values": pixel_values, "image_grid_thw": vision_grid_thws}
425
+
426
+ if videos is not None:
427
+ pixel_values, vision_grid_thws = [], []
428
+ for images in videos:
429
+ patches, video_grid_thw = self._preprocess(
430
+ images,
431
+ do_resize=do_resize,
432
+ resample=resample,
433
+ do_rescale=do_rescale,
434
+ rescale_factor=rescale_factor,
435
+ do_normalize=do_normalize,
436
+ image_mean=image_mean,
437
+ image_std=image_std,
438
+ data_format=data_format,
439
+ do_convert_rgb=do_convert_rgb,
440
+ input_data_format=input_data_format,
441
+ )
442
+ pixel_values.extend(patches)
443
+ vision_grid_thws.append(video_grid_thw)
444
+ pixel_values = np.array(pixel_values)
445
+ vision_grid_thws = np.array(vision_grid_thws)
446
+ data = {"pixel_values_videos": pixel_values, "video_grid_thw": vision_grid_thws}
447
+
448
+ return BatchFeature(data=data, tensor_type=return_tensors)
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
modeling_tonggu_vl.py ADDED
The diff for this file is too large to render. See raw diff
 
preprocessor_config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "min_pixels": 3136,
3
+ "max_pixels": 12845056,
4
+ "patch_size": 14,
5
+ "temporal_patch_size": 2,
6
+ "merge_size": 2,
7
+ "image_mean": [
8
+ 0.48145466,
9
+ 0.4578275,
10
+ 0.40821073
11
+ ],
12
+ "image_std": [
13
+ 0.26862954,
14
+ 0.26130258,
15
+ 0.27577711
16
+ ],
17
+ "image_processor_type": "Qwen2VLImageProcessor",
18
+ "processor_class": "Qwen2VLProcessor"
19
+ }
processing_tonggu_vl.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Processor class for Qwen2-VL.
3
+ """
4
+
5
+ from typing import List, Union
6
+
7
+ from transformers.feature_extraction_utils import BatchFeature
8
+ from transformers.image_utils import ImageInput, VideoInput
9
+ from transformers.processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
10
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
11
+ from transformers.utils import logging
12
+
13
+
14
+ logger = logging.get_logger(__name__)
15
+
16
+
17
+ class Qwen2VLProcessorKwargs(ProcessingKwargs, total=False):
18
+ _defaults = {
19
+ "text_kwargs": {
20
+ "padding": False,
21
+ },
22
+ }
23
+
24
+
25
+ class Qwen2VLProcessor(ProcessorMixin):
26
+ r"""
27
+ Constructs a Qwen2-VL processor which wraps a Qwen2-VL image processor and a Qwen2 tokenizer into a single processor.
28
+ [`Qwen2VLProcessor`] offers all the functionalities of [`Qwen2VLImageProcessor`] and [`Qwen2TokenizerFast`]. See the
29
+ [`~Qwen2VLProcessor.__call__`] and [`~Qwen2VLProcessor.decode`] for more information.
30
+ Args:
31
+ image_processor ([`Qwen2VLImageProcessor`], *optional*):
32
+ The image processor is a required input.
33
+ tokenizer ([`Qwen2TokenizerFast`], *optional*):
34
+ The tokenizer is a required input.
35
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
36
+ in a chat into a tokenizable string.
37
+ """
38
+
39
+ attributes = ["image_processor", "tokenizer"]
40
+ valid_kwargs = ["chat_template"]
41
+ image_processor_class = "Qwen2VLImageProcessor"
42
+ tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
43
+
44
+ def __init__(self, image_processor=None, tokenizer=None, chat_template=None, **kwargs):
45
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
46
+
47
+ def __call__(
48
+ self,
49
+ images: ImageInput = None,
50
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
51
+ videos: VideoInput = None,
52
+ **kwargs: Unpack[Qwen2VLProcessorKwargs],
53
+ ) -> BatchFeature:
54
+ """
55
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
56
+ and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
57
+ the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to
58
+ Qwen2VLImageProcessor's [`~Qwen2VLImageProcessor.__call__`] if `vision_infos` is not `None`.
59
+
60
+ Args:
61
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
62
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
63
+ tensor. Both channels-first and channels-last formats are supported.
64
+ text (`str`, `List[str]`, `List[List[str]]`):
65
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
66
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
67
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
68
+ videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
69
+ The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
70
+ tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
71
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
72
+ If set, will return tensors of a particular framework. Acceptable values are:
73
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
74
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
75
+ - `'np'`: Return NumPy `np.ndarray` objects.
76
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
77
+
78
+ Returns:
79
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
80
+
81
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
82
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
83
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
84
+ `None`).
85
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
86
+ - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
87
+ - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
88
+ - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
89
+ """
90
+ output_kwargs = self._merge_kwargs(
91
+ Qwen2VLProcessorKwargs,
92
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
93
+ **kwargs,
94
+ )
95
+ if images is not None:
96
+ image_inputs = self.image_processor(images=images, videos=None, **output_kwargs["images_kwargs"])
97
+ image_grid_thw = image_inputs["image_grid_thw"]
98
+ else:
99
+ image_inputs = {}
100
+ image_grid_thw = None
101
+
102
+ if videos is not None:
103
+ videos_inputs = self.image_processor(images=None, videos=videos, **output_kwargs["videos_kwargs"])
104
+ video_grid_thw = videos_inputs["video_grid_thw"]
105
+ else:
106
+ videos_inputs = {}
107
+ video_grid_thw = None
108
+
109
+ if not isinstance(text, list):
110
+ text = [text]
111
+
112
+ if image_grid_thw is not None:
113
+ merge_length = self.image_processor.merge_size**2
114
+ # print(merge_length)
115
+ index = 0
116
+ for i in range(len(text)):
117
+ while "<|image_pad|>" in text[i]:
118
+ text[i] = text[i].replace(
119
+ "<|image_pad|>", "<|placeholder|>" * (image_grid_thw[index].prod() // merge_length), 1
120
+ )
121
+ index += 1
122
+ text[i] = text[i].replace("<|placeholder|>", "<|image_pad|>")
123
+ # print(text)
124
+
125
+ if video_grid_thw is not None:
126
+ merge_length = self.image_processor.merge_size**2
127
+ index = 0
128
+ for i in range(len(text)):
129
+ while "<|video_pad|>" in text[i]:
130
+ text[i] = text[i].replace(
131
+ "<|video_pad|>", "<|placeholder|>" * (video_grid_thw[index].prod() // merge_length), 1
132
+ )
133
+ index += 1
134
+ text[i] = text[i].replace("<|placeholder|>", "<|video_pad|>")
135
+
136
+ _ = output_kwargs["text_kwargs"].pop("padding_side", None)
137
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
138
+
139
+ return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs})
140
+
141
+ def batch_decode(self, *args, **kwargs):
142
+ """
143
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
144
+ refer to the docstring of this method for more information.
145
+ """
146
+ return self.tokenizer.batch_decode(*args, **kwargs)
147
+
148
+ def decode(self, *args, **kwargs):
149
+ """
150
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
151
+ the docstring of this method for more information.
152
+ """
153
+ return self.tokenizer.decode(*args, **kwargs)
154
+
155
+ @property
156
+ def model_input_names(self):
157
+ tokenizer_input_names = self.tokenizer.model_input_names
158
+ image_processor_input_names = self.image_processor.model_input_names
159
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77fac130e16167bc3986ce39563614982b8460592983641a7a79d4269ea81da7
3
+ size 9956911530
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "151646": {
29
+ "content": "<|object_ref_start|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "151647": {
37
+ "content": "<|object_ref_end|>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "151648": {
45
+ "content": "<|box_start|>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "151649": {
53
+ "content": "<|box_end|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "151650": {
61
+ "content": "<|quad_start|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "151651": {
69
+ "content": "<|quad_end|>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "151652": {
77
+ "content": "<|vision_start|>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "151653": {
85
+ "content": "<|vision_end|>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "151654": {
93
+ "content": "<|vision_pad|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "151655": {
101
+ "content": "<|image_pad|>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ },
108
+ "151656": {
109
+ "content": "<|video_pad|>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": true
115
+ }
116
+ },
117
+ "additional_special_tokens": ["<|im_start|>", "<|im_end|>", "<|object_ref_start|>","<|object_ref_end|>","<|box_start|>","<|box_end|>","<|quad_start|>","<|quad_end|>","<|vision_start|>","<|vision_end|>","<|vision_pad|>","<|image_pad|>","<|video_pad|>"],
118
+ "bos_token": null,
119
+ "chat_template": "{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n{% endif %}<|im_start|>{{ message['role'] }}\n{% if message['content'] is string %}{{ message['content'] }}<|im_end|>\n{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}",
120
+ "clean_up_tokenization_spaces": false,
121
+ "eos_token": "<|im_end|>",
122
+ "padding_side": "left",
123
+ "errors": "replace",
124
+ "model_max_length": 32768,
125
+ "pad_token": "<|endoftext|>",
126
+ "split_special_tokens": false,
127
+ "tokenizer_class": "Qwen2Tokenizer",
128
+ "unk_token": null
129
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff