echarlaix HF Staff commited on
Commit
cd0ffce
·
1 Parent(s): 6856d56
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.json filter=lfs diff=lfs merge=lfs -text
added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7fa54985b58718a8fdb4f4d97484c4bd908db114847675e4bf3afe3e1d5d7bd4
3
+ size 392
chat_template.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94174d7176c52a7192f96fc34eb2cf23c7c2059d63cdbfadca1586ba89731fb7
3
+ size 1049
config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48b454873642fc802a58ae6aa8773836caa83b4e9e865bcd421ab72296217d67
3
+ size 2657
configuration_qwen2_5_vl.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_qwen2_5_vl.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
11
+ # and OPT implementations in this library. It has been modified from its
12
+ # original forms to accommodate minor architectural differences compared
13
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
14
+ #
15
+ # Licensed under the Apache License, Version 2.0 (the "License");
16
+ # you may not use this file except in compliance with the License.
17
+ # You may obtain a copy of the License at
18
+ #
19
+ # http://www.apache.org/licenses/LICENSE-2.0
20
+ #
21
+ # Unless required by applicable law or agreed to in writing, software
22
+ # distributed under the License is distributed on an "AS IS" BASIS,
23
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ # See the License for the specific language governing permissions and
25
+ # limitations under the License.
26
+ from transformers.configuration_utils import PretrainedConfig
27
+ from transformers.modeling_rope_utils import rope_config_validation
28
+
29
+
30
+ class Qwen2_5_VLVisionConfig(PretrainedConfig):
31
+ model_type = "qwen2_5_vl"
32
+ base_config_key = "vision_config"
33
+
34
+ def __init__(
35
+ self,
36
+ depth=32,
37
+ hidden_size=3584,
38
+ hidden_act="silu",
39
+ intermediate_size=3420,
40
+ num_heads=16,
41
+ in_channels=3,
42
+ patch_size=14,
43
+ spatial_merge_size=2,
44
+ temporal_patch_size=2,
45
+ tokens_per_second=4,
46
+ window_size=112,
47
+ out_hidden_size=3584,
48
+ fullatt_block_indexes=[7, 15, 23, 31],
49
+ **kwargs,
50
+ ):
51
+ super().__init__(**kwargs)
52
+
53
+ self.depth = depth
54
+ self.hidden_size = hidden_size
55
+ self.hidden_act = hidden_act
56
+ self.intermediate_size = intermediate_size
57
+ self.num_heads = num_heads
58
+ self.in_channels = in_channels
59
+ self.patch_size = patch_size
60
+ self.spatial_merge_size = spatial_merge_size
61
+ self.temporal_patch_size = temporal_patch_size
62
+ self.tokens_per_second = tokens_per_second
63
+ self.window_size = window_size
64
+ self.fullatt_block_indexes = fullatt_block_indexes
65
+ self.out_hidden_size = out_hidden_size
66
+
67
+
68
+ class Qwen2_5_VLConfig(PretrainedConfig):
69
+ r"""
70
+ This is the configuration class to store the configuration of a [`Qwen2_5_VLModel`]. It is used to instantiate a
71
+ Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration
72
+ with the defaults will yield a similar configuration to that of
73
+ Qwen2-VL-7B-Instruct [Qwen/Qwen2-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct).
74
+
75
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
76
+ documentation from [`PretrainedConfig`] for more information.
77
+
78
+
79
+ Args:
80
+ vocab_size (`int`, *optional*, defaults to 152064):
81
+ Vocabulary size of the Qwen2_5_VL model. Defines the number of different tokens that can be represented by the
82
+ `inputs_ids` passed when calling [`Qwen2_5_VLModel`]
83
+ hidden_size (`int`, *optional*, defaults to 8192):
84
+ Dimension of the hidden representations.
85
+ intermediate_size (`int`, *optional*, defaults to 29568):
86
+ Dimension of the MLP representations.
87
+ num_hidden_layers (`int`, *optional*, defaults to 80):
88
+ Number of hidden layers in the Transformer encoder.
89
+ num_attention_heads (`int`, *optional*, defaults to 64):
90
+ Number of attention heads for each attention layer in the Transformer encoder.
91
+ num_key_value_heads (`int`, *optional*, defaults to 8):
92
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
93
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
94
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
95
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
96
+ by meanpooling all the original heads within that group. For more details checkout [this
97
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
98
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
99
+ The non-linear activation function (function or string) in the decoder.
100
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
101
+ The maximum sequence length that this model might ever be used with.
102
+ initializer_range (`float`, *optional*, defaults to 0.02):
103
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
104
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
105
+ The epsilon used by the rms normalization layers.
106
+ use_cache (`bool`, *optional*, defaults to `True`):
107
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
108
+ relevant if `config.is_decoder=True`.
109
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
110
+ Whether the model's input and output word embeddings should be tied.
111
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
112
+ The base period of the RoPE embeddings.
113
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
114
+ Whether to use sliding window attention.
115
+ sliding_window (`int`, *optional*, defaults to 4096):
116
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
117
+ max_window_layers (`int`, *optional*, defaults to 80):
118
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
119
+ attention_dropout (`float`, *optional*, defaults to 0.0):
120
+ The dropout ratio for the attention probabilities.
121
+ vision_config (`Dict`, *optional*):
122
+ The config for the visual encoder initialization.
123
+ rope_scaling (`Dict`, *optional*):
124
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
125
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
126
+ accordingly.
127
+ Expected contents:
128
+ `rope_type` (`str`):
129
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
130
+ 'llama3'], with 'default' being the original RoPE implementation.
131
+ `factor` (`float`, *optional*):
132
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
133
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
134
+ original maximum pre-trained length.
135
+ `original_max_position_embeddings` (`int`, *optional*):
136
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
137
+ pretraining.
138
+ `attention_factor` (`float`, *optional*):
139
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
140
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
141
+ `factor` field to infer the suggested value.
142
+ `beta_fast` (`float`, *optional*):
143
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
144
+ ramp function. If unspecified, it defaults to 32.
145
+ `beta_slow` (`float`, *optional*):
146
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
147
+ ramp function. If unspecified, it defaults to 1.
148
+ `short_factor` (`List[float]`, *optional*):
149
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
150
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
151
+ size divided by the number of attention heads divided by 2
152
+ `long_factor` (`List[float]`, *optional*):
153
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
154
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
155
+ size divided by the number of attention heads divided by 2
156
+ `low_freq_factor` (`float`, *optional*):
157
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
158
+ `high_freq_factor` (`float`, *optional*):
159
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
160
+
161
+ ```python
162
+ >>> from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2_5_VLConfig
163
+
164
+ >>> # Initializing a Qwen2_5_VL style configuration
165
+ >>> configuration = Qwen2_5_VLConfig()
166
+
167
+ >>> # Initializing a model from the Qwen2-VL-7B style configuration
168
+ >>> model = Qwen2_5_VLForConditionalGeneration(configuration)
169
+
170
+ >>> # Accessing the model configuration
171
+ >>> configuration = model.config
172
+ ```"""
173
+
174
+ model_type = "qwen2_5_vl"
175
+ sub_configs = {"vision_config": Qwen2_5_VLVisionConfig}
176
+ keys_to_ignore_at_inference = ["past_key_values"]
177
+ # Default tensor parallel plan for base model `Qwen2_5_VL`
178
+ base_model_tp_plan = {
179
+ "layers.*.self_attn.q_proj": "colwise",
180
+ "layers.*.self_attn.k_proj": "colwise",
181
+ "layers.*.self_attn.v_proj": "colwise",
182
+ "layers.*.self_attn.o_proj": "rowwise",
183
+ "layers.*.mlp.gate_proj": "colwise",
184
+ "layers.*.mlp.up_proj": "colwise",
185
+ "layers.*.mlp.down_proj": "rowwise",
186
+ }
187
+ base_model_pp_plan = {
188
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
189
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
190
+ "norm": (["hidden_states"], ["hidden_states"]),
191
+ }
192
+
193
+ def __init__(
194
+ self,
195
+ vocab_size=152064,
196
+ hidden_size=8192,
197
+ intermediate_size=29568,
198
+ num_hidden_layers=80,
199
+ num_attention_heads=64,
200
+ num_key_value_heads=8,
201
+ hidden_act="silu",
202
+ max_position_embeddings=32768,
203
+ initializer_range=0.02,
204
+ rms_norm_eps=1e-05,
205
+ use_cache=True,
206
+ tie_word_embeddings=False,
207
+ rope_theta=1000000.0,
208
+ use_sliding_window=False,
209
+ sliding_window=4096,
210
+ max_window_layers=80,
211
+ attention_dropout=0.0,
212
+ vision_config=None,
213
+ rope_scaling=None,
214
+ **kwargs,
215
+ ):
216
+ if isinstance(vision_config, dict):
217
+ self.vision_config = self.sub_configs["vision_config"](**vision_config)
218
+ elif vision_config is None:
219
+ self.vision_config = self.sub_configs["vision_config"]()
220
+
221
+ self.vocab_size = vocab_size
222
+ self.max_position_embeddings = max_position_embeddings
223
+ self.hidden_size = hidden_size
224
+ self.intermediate_size = intermediate_size
225
+ self.num_hidden_layers = num_hidden_layers
226
+ self.num_attention_heads = num_attention_heads
227
+ self.use_sliding_window = use_sliding_window
228
+ self.sliding_window = sliding_window
229
+ self.max_window_layers = max_window_layers
230
+
231
+ # for backward compatibility
232
+ if num_key_value_heads is None:
233
+ num_key_value_heads = num_attention_heads
234
+
235
+ self.num_key_value_heads = num_key_value_heads
236
+ self.hidden_act = hidden_act
237
+ self.initializer_range = initializer_range
238
+ self.rms_norm_eps = rms_norm_eps
239
+ self.use_cache = use_cache
240
+ self.rope_theta = rope_theta
241
+ self.attention_dropout = attention_dropout
242
+ self.rope_scaling = rope_scaling
243
+
244
+ # Validate the correctness of rotary position embeddings parameters
245
+ # BC: if there is a 'type' field, move it to 'rope_type'.
246
+ # and change type from 'mrope' to 'default' because `mrope` does defeault RoPE calculations
247
+ # one can set it to "linear"/"dynamic" etc. to have scaled RoPE
248
+ # TODO: @raushan update config in the hub
249
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
250
+ if self.rope_scaling["type"] == "mrope":
251
+ self.rope_scaling["type"] = "default"
252
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
253
+ rope_config_validation(self, ignore_keys={"mrope_section"})
254
+
255
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
256
+
257
+
258
+ __all__ = ["Qwen2_5_VLConfig"]
generation_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55b2b4462aedccc5858edd8d7aa0fa7aebf8a3bf9245f9a095ddeba8a9a1650a
3
+ size 121
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06ee238aa6a4e71758c87d1cbaf67e460dda61adc15b14adbe7d524ce99c5c83
3
+ size 20962256
modeling_qwen2_5_vl.py ADDED
The diff for this file is too large to render. See raw diff
 
preprocessor_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e75a8a0ea4315702add896d4ad12215086e98735051c76613bf06e59c737d35
3
+ size 502
processing_qwen2_5_vl.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_qwen2_5_vl.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
11
+ # and OPT implementations in this library. It has been modified from its
12
+ # original forms to accommodate minor architectural differences compared
13
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
14
+ #
15
+ # Licensed under the Apache License, Version 2.0 (the "License");
16
+ # you may not use this file except in compliance with the License.
17
+ # You may obtain a copy of the License at
18
+ #
19
+ # http://www.apache.org/licenses/LICENSE-2.0
20
+ #
21
+ # Unless required by applicable law or agreed to in writing, software
22
+ # distributed under the License is distributed on an "AS IS" BASIS,
23
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ # See the License for the specific language governing permissions and
25
+ # limitations under the License.
26
+ from typing import List, Union
27
+
28
+ from transformers.feature_extraction_utils import BatchFeature
29
+ from transformers.image_utils import ImageInput, VideoInput
30
+ from transformers.processing_utils import ProcessingKwargs, ProcessorMixin, Unpack, VideosKwargs
31
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
32
+
33
+
34
+ class Qwen2_5_VLVideosProcessorKwargs(VideosKwargs, total=False):
35
+ fps: Union[List[float], float]
36
+
37
+
38
+ class Qwen2_5_VLProcessorKwargs(ProcessingKwargs, total=False):
39
+ videos_kwargs: Qwen2_5_VLVideosProcessorKwargs
40
+ _defaults = {
41
+ "text_kwargs": {
42
+ "padding": False,
43
+ },
44
+ "videos_kwargs": {"fps": 2.0},
45
+ }
46
+
47
+
48
+ class Qwen2_5_VLProcessor(ProcessorMixin):
49
+ r"""
50
+ Constructs a Qwen2.5-VL processor which wraps a Qwen2.5-VL image processor and a Qwen2 tokenizer into a single processor.
51
+ [`Qwen2_5_VLProcessor`] offers all the functionalities of [`Qwen2VLImageProcessor`] and [`Qwen2TokenizerFast`]. See the
52
+ [`~Qwen2_5_VLProcessor.__call__`] and [`~Qwen2_5_VLProcessor.decode`] for more information.
53
+ Args:
54
+ image_processor ([`Qwen2VLImageProcessor`], *optional*):
55
+ The image processor is a required input.
56
+ tokenizer ([`Qwen2TokenizerFast`], *optional*):
57
+ The tokenizer is a required input.
58
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
59
+ in a chat into a tokenizable string.
60
+ """
61
+
62
+ attributes = ["image_processor", "tokenizer"]
63
+ valid_kwargs = ["chat_template"]
64
+
65
+ image_processor_class = "AutoImageProcessor"
66
+ tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
67
+
68
+ def __init__(self, image_processor=None, tokenizer=None, chat_template=None, **kwargs):
69
+ self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
70
+ self.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
71
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
72
+
73
+ def __call__(
74
+ self,
75
+ images: ImageInput = None,
76
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
77
+ videos: VideoInput = None,
78
+ **kwargs: Unpack[Qwen2_5_VLProcessorKwargs],
79
+ ) -> BatchFeature:
80
+ """
81
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
82
+ and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
83
+ the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to
84
+ Qwen2VLImageProcessor's [`~Qwen2VLImageProcessor.__call__`] if `vision_infos` is not `None`.
85
+
86
+ Args:
87
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
88
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
89
+ tensor. Both channels-first and channels-last formats are supported.
90
+ text (`str`, `List[str]`, `List[List[str]]`):
91
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
92
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
93
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
94
+ videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
95
+ The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
96
+ tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
97
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
98
+ If set, will return tensors of a particular framework. Acceptable values are:
99
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
100
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
101
+ - `'np'`: Return NumPy `np.ndarray` objects.
102
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
103
+
104
+ Returns:
105
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
106
+
107
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
108
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
109
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
110
+ `None`).
111
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
112
+ - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
113
+ - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
114
+ - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
115
+ - **second_per_grid_ts** -- List of video seconds per time grid. Returned when `videos` is not `None`.
116
+ """
117
+ output_kwargs = self._merge_kwargs(
118
+ Qwen2_5_VLProcessorKwargs,
119
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
120
+ **kwargs,
121
+ )
122
+ if images is not None:
123
+ image_inputs = self.image_processor(images=images, videos=None, **output_kwargs["images_kwargs"])
124
+ image_grid_thw = image_inputs["image_grid_thw"]
125
+ else:
126
+ image_inputs = {}
127
+ image_grid_thw = None
128
+
129
+ if videos is not None:
130
+ videos_inputs = self.image_processor(images=None, videos=videos, **output_kwargs["images_kwargs"])
131
+ video_grid_thw = videos_inputs["video_grid_thw"]
132
+
133
+ fps = output_kwargs["videos_kwargs"].pop("fps", 2.0)
134
+ if isinstance(fps, (int, float)):
135
+ second_per_grid_ts = [self.image_processor.temporal_patch_size / fps] * len(video_grid_thw)
136
+ elif hasattr(fps, "__len__") and len(fps) == len(video_grid_thw):
137
+ second_per_grid_ts = [self.image_processor.temporal_patch_size / tmp for tmp in fps]
138
+ else:
139
+ raise ValueError(
140
+ f"The length of fps ({len(fps) if hasattr(fps, '__len__') else fps}) must be equal to the length of video_grid_thw ({len(video_grid_thw)}) or fps should be a single number."
141
+ )
142
+ videos_inputs.update({"second_per_grid_ts": second_per_grid_ts})
143
+
144
+ else:
145
+ videos_inputs = {}
146
+ video_grid_thw = None
147
+
148
+ if not isinstance(text, list):
149
+ text = [text]
150
+
151
+ if image_grid_thw is not None:
152
+ merge_length = self.image_processor.merge_size**2
153
+ index = 0
154
+ for i in range(len(text)):
155
+ while self.image_token in text[i]:
156
+ text[i] = text[i].replace(
157
+ self.image_token,
158
+ "<|placeholder|>" * (image_grid_thw[index].prod() // merge_length),
159
+ 1,
160
+ )
161
+ index += 1
162
+ text[i] = text[i].replace("<|placeholder|>", self.image_token)
163
+
164
+ if video_grid_thw is not None:
165
+ merge_length = self.image_processor.merge_size**2
166
+ index = 0
167
+ for i in range(len(text)):
168
+ while self.video_token in text[i]:
169
+ text[i] = text[i].replace(
170
+ self.video_token,
171
+ "<|placeholder|>" * (video_grid_thw[index].prod() // merge_length),
172
+ 1,
173
+ )
174
+ index += 1
175
+ text[i] = text[i].replace("<|placeholder|>", self.video_token)
176
+
177
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
178
+
179
+ return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs})
180
+
181
+ def batch_decode(self, *args, **kwargs):
182
+ """
183
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
184
+ refer to the docstring of this method for more information.
185
+ """
186
+ return self.tokenizer.batch_decode(*args, **kwargs)
187
+
188
+ def decode(self, *args, **kwargs):
189
+ """
190
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
191
+ the docstring of this method for more information.
192
+ """
193
+ return self.tokenizer.decode(*args, **kwargs)
194
+
195
+ def post_process_image_text_to_text(self, generated_outputs):
196
+ """
197
+ Post-process the output of the model to decode the text.
198
+
199
+ Args:
200
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
201
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
202
+ or `(sequence_length,)`.
203
+
204
+ Returns:
205
+ `List[str]`: The decoded text.
206
+ """
207
+ return self.tokenizer.batch_decode(
208
+ generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False
209
+ )
210
+
211
+ @property
212
+ def model_input_names(self):
213
+ tokenizer_input_names = self.tokenizer.model_input_names
214
+ image_processor_input_names = self.image_processor.model_input_names
215
+ names_from_processor = list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
216
+ return names_from_processor + ["second_per_grid_ts"]
217
+
218
+
219
+ __all__ = ["Qwen2_5_VLProcessor"]
special_tokens_map.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76862e765266b85aa9459767e33cbaf13970f327a0e88d1c65846c2ddd3a1ecd
3
+ size 613
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:091aa7594dc2fcfbfa06b9e3c22a5f0562ac14f30375c13af7309407a0e67b8a
3
+ size 11420371
tokenizer_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb3c5a310899d7d65feec0dee4dff9067d7bc4ad2a17e2005bc9163f1ace0531
3
+ size 4297
vocab.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910
3
+ size 2776833