andrevp commited on
Commit
37907d3
·
verified ·
1 Parent(s): 70f35aa

Upload Keye-VL 1.5 8B MLX 4-bit quantized model

Browse files
.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
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
added_tokens.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|box_end|>": 151649,
9
+ "<|box_start|>": 151648,
10
+ "<|clip_time_end|>": 151674,
11
+ "<|clip_time_start|>": 151673,
12
+ "<|endoftext|>": 151643,
13
+ "<|fast_end|>": 151680,
14
+ "<|fast_start|>": 151679,
15
+ "<|fast_video_pad|>": 151678,
16
+ "<|file_sep|>": 151664,
17
+ "<|fim_middle|>": 151660,
18
+ "<|fim_pad|>": 151662,
19
+ "<|fim_prefix|>": 151659,
20
+ "<|fim_suffix|>": 151661,
21
+ "<|frame|>": 151677,
22
+ "<|im_end|>": 151645,
23
+ "<|im_start|>": 151644,
24
+ "<|image_pad|>": 151655,
25
+ "<|object_ref_end|>": 151647,
26
+ "<|object_ref_start|>": 151646,
27
+ "<|ocr_text_end|>": 151672,
28
+ "<|ocr_text_start|>": 151671,
29
+ "<|point_end|>": 151670,
30
+ "<|point_start|>": 151669,
31
+ "<|polygon_end|>": 151676,
32
+ "<|polygon_start|>": 151675,
33
+ "<|quad_end|>": 151651,
34
+ "<|quad_start|>": 151650,
35
+ "<|repo_name|>": 151663,
36
+ "<|video_pad|>": 151656,
37
+ "<|vision_end|>": 151653,
38
+ "<|vision_pad|>": 151654,
39
+ "<|vision_start|>": 151652
40
+ }
chat_template.jinja ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {% 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
2
+ You are a helpful assistant.<|im_end|>
3
+ {% endif %}<|im_start|>{{ message['role'] }}
4
+ {% if message['content'] is string %}{{ message['content'] }}<|im_end|>
5
+ {% 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|>
6
+ {% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant
7
+ {% endif %}
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,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": null,
3
+ "architectures": [
4
+ "KeyeVL1_5ForConditionalGeneration"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_keye_vl_1_5.KeyeVL1_5Config",
10
+ "AutoModel": "modeling_keye_vl_1_5.KeyeVL1_5ForConditionalGeneration",
11
+ "AutoModelForCausalLM": "modeling_keye_vl_1_5.KeyeVL1_5ForConditionalGeneration"
12
+ },
13
+ "bos_token_id": 151643,
14
+ "eos_token_id": [
15
+ 151645,
16
+ 151643
17
+ ],
18
+ "fast_video_token_id": 151678,
19
+ "head_dim": 128,
20
+ "hidden_act": "silu",
21
+ "hidden_size": 4096,
22
+ "image_token_id": 151655,
23
+ "initializer_factor": 1.0,
24
+ "initializer_range": 0.02,
25
+ "intermediate_size": 12288,
26
+ "max_position_embeddings": 131072,
27
+ "max_window_layers": 36,
28
+ "model_type": "KeyeVL1_5",
29
+ "num_attention_heads": 32,
30
+ "num_hidden_layers": 36,
31
+ "num_key_value_heads": 8,
32
+ "quantization": {
33
+ "group_size": 64,
34
+ "bits": 4,
35
+ "mode": "affine"
36
+ },
37
+ "quantization_config": {
38
+ "group_size": 64,
39
+ "bits": 4,
40
+ "mode": "affine"
41
+ },
42
+ "rms_norm_eps": 1e-06,
43
+ "rope_scaling": {
44
+ "type": "mrope",
45
+ "mrope_section": [
46
+ 16,
47
+ 24,
48
+ 24
49
+ ]
50
+ },
51
+ "rope_theta": 8000000,
52
+ "sliding_window": null,
53
+ "tie_word_embeddings": false,
54
+ "transformers_version": "4.41.2",
55
+ "use_cache": true,
56
+ "use_sliding_window": false,
57
+ "video_token_id": 151656,
58
+ "vision_config": {
59
+ "_attn_implementation_autoset": true,
60
+ "add_cross_attention": false,
61
+ "architectures": [
62
+ "KeyeVL1_5VisionModel"
63
+ ],
64
+ "attention_dropout": 0.0,
65
+ "auto_map": {
66
+ "AutoConfig": "configuration_keye_vl_1_5.KeyeVL1_5VisionConfig",
67
+ "AutoModel": "modeling_keye_vl_1_5.KeyeVL1_5VisionModel"
68
+ },
69
+ "hidden_size": 1152,
70
+ "image_size": 384,
71
+ "intermediate_size": 4304,
72
+ "model_type": "keye_vl_1_5_vision_model",
73
+ "num_attention_heads": 16,
74
+ "num_hidden_layers": 27,
75
+ "patch_size": 14,
76
+ "spatial_merge_size": 2,
77
+ "tokens_per_second": 2,
78
+ "temporal_patch_size": 2,
79
+ "rope_theta": 10000,
80
+ "has_learnable_position_embedding": true
81
+ },
82
+ "vision_end_token_id": 151653,
83
+ "vision_start_token_id": 151652,
84
+ "vision_token_id": 151654,
85
+ "vocab_size": 151936
86
+ }
configuration_keye_vl_1_5.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The Kwai Keye Team 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
+ from transformers.configuration_utils import PretrainedConfig
21
+ from transformers.modeling_rope_utils import rope_config_validation
22
+
23
+
24
+
25
+ class KeyeVL1_5VisionConfig(PretrainedConfig):
26
+ model_type = "keye_vl_1_5_vision_model"
27
+ base_config_key = "vision_config"
28
+
29
+ def __init__(
30
+ self,
31
+ hidden_size=768,
32
+ intermediate_size=3072,
33
+ num_hidden_layers=12,
34
+ num_attention_heads=12,
35
+ num_channels=3,
36
+ image_size=224,
37
+ patch_size=14,
38
+ hidden_act="gelu_pytorch_tanh",
39
+ layer_norm_eps=1e-6,
40
+ attention_dropout=0.0,
41
+ spatial_merge_size=2,
42
+ temporal_patch_size=2,
43
+ tokens_per_second=2,
44
+ **kwargs,
45
+ ):
46
+ super().__init__(**kwargs)
47
+
48
+ self.hidden_size = hidden_size
49
+ self.intermediate_size = intermediate_size
50
+ self.num_hidden_layers = num_hidden_layers
51
+ self.num_attention_heads = num_attention_heads
52
+ self.num_channels = num_channels
53
+ self.patch_size = patch_size
54
+ self.image_size = image_size
55
+ self.attention_dropout = attention_dropout
56
+ self.layer_norm_eps = layer_norm_eps
57
+ self.hidden_act = hidden_act
58
+ self.spatial_merge_size = spatial_merge_size
59
+ self.temporal_patch_size = temporal_patch_size
60
+ self.tokens_per_second = tokens_per_second
61
+
62
+
63
+ class KeyeVL1_5Config(PretrainedConfig):
64
+ r"""
65
+ This is the configuration class to store the configuration of a [`KeyeVL1_5Model`]. It is used to instantiate a
66
+ Keye-VL-1.5 model according to the specified arguments, defining the model architecture. Instantiating a configuration
67
+ with the defaults will yield a similar configuration to that of
68
+ Keye-VL-1.5.
69
+
70
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
71
+ documentation from [`PretrainedConfig`] for more information.
72
+
73
+
74
+ Args:
75
+ vocab_size (`int`, *optional*, defaults to 152064):
76
+ Vocabulary size of the KeyeVL1_5 model. Defines the number of different tokens that can be represented by the
77
+ `inputs_ids` passed when calling [`KeyeVL1_5Model`]
78
+ hidden_size (`int`, *optional*, defaults to 8192):
79
+ Dimension of the hidden representations.
80
+ intermediate_size (`int`, *optional*, defaults to 29568):
81
+ Dimension of the MLP representations.
82
+ num_hidden_layers (`int`, *optional*, defaults to 80):
83
+ Number of hidden layers in the Transformer encoder.
84
+ num_attention_heads (`int`, *optional*, defaults to 64):
85
+ Number of attention heads for each attention layer in the Transformer encoder.
86
+ num_key_value_heads (`int`, *optional*, defaults to 8):
87
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
88
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
89
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
90
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
91
+ by meanpooling all the original heads within that group. For more details checkout [this
92
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
93
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
94
+ The non-linear activation function (function or string) in the decoder.
95
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
96
+ The maximum sequence length that this model might ever be used with.
97
+ initializer_range (`float`, *optional*, defaults to 0.02):
98
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
99
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
100
+ The epsilon used by the rms normalization layers.
101
+ use_cache (`bool`, *optional*, defaults to `True`):
102
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
103
+ relevant if `config.is_decoder=True`.
104
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
105
+ Whether the model's input and output word embeddings should be tied.
106
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
107
+ The base period of the RoPE embeddings.
108
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
109
+ Whether to use sliding window attention.
110
+ sliding_window (`int`, *optional*, defaults to 4096):
111
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
112
+ max_window_layers (`int`, *optional*, defaults to 80):
113
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
114
+ attention_dropout (`float`, *optional*, defaults to 0.0):
115
+ The dropout ratio for the attention probabilities.
116
+ vision_config (`Dict`, *optional*):
117
+ The config for the visual encoder initialization.
118
+ rope_scaling (`Dict`, *optional*):
119
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
120
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
121
+ accordingly.
122
+ Expected contents:
123
+ `rope_type` (`str`):
124
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
125
+ 'llama3'], with 'default' being the original RoPE implementation.
126
+ `factor` (`float`, *optional*):
127
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
128
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
129
+ original maximum pre-trained length.
130
+ `original_max_position_embeddings` (`int`, *optional*):
131
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
132
+ pretraining.
133
+ `attention_factor` (`float`, *optional*):
134
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
135
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
136
+ `factor` field to infer the suggested value.
137
+ `beta_fast` (`float`, *optional*):
138
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
139
+ ramp function. If unspecified, it defaults to 32.
140
+ `beta_slow` (`float`, *optional*):
141
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
142
+ ramp function. If unspecified, it defaults to 1.
143
+ `short_factor` (`List[float]`, *optional*):
144
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
145
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
146
+ size divided by the number of attention heads divided by 2
147
+ `long_factor` (`List[float]`, *optional*):
148
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
149
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
150
+ size divided by the number of attention heads divided by 2
151
+ `low_freq_factor` (`float`, *optional*):
152
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
153
+ `high_freq_factor` (`float`, *optional*):
154
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
155
+
156
+ ```python
157
+ >>> from transformers import KeyeVL1_5ForConditionalGeneration, KeyeVL1_5Config
158
+
159
+ >>> # Initializing a KeyeVL1_5 style configuration
160
+ >>> configuration = KeyeVL1_5Config()
161
+
162
+ >>> # Initializing a model from the Keye-VL-1.5-8B style configuration
163
+ >>> model = KeyeVL1_5ForConditionalGeneration(configuration)
164
+
165
+ >>> # Accessing the model configuration
166
+ >>> configuration = model.config
167
+ ```"""
168
+
169
+ model_type = "KeyeVL1_5"
170
+ sub_configs = {"vision_config": KeyeVL1_5VisionConfig}
171
+ keys_to_ignore_at_inference = ["past_key_values"]
172
+ # Default tensor parallel plan for base model `KeyeVL1_5`
173
+ base_model_tp_plan = {
174
+ "layers.*.self_attn.q_proj": "colwise",
175
+ "layers.*.self_attn.k_proj": "colwise",
176
+ "layers.*.self_attn.v_proj": "colwise",
177
+ "layers.*.self_attn.o_proj": "rowwise",
178
+ "layers.*.mlp.gate_proj": "colwise",
179
+ "layers.*.mlp.up_proj": "colwise",
180
+ "layers.*.mlp.down_proj": "rowwise",
181
+ }
182
+ base_model_pp_plan = {
183
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
184
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
185
+ "norm": (["hidden_states"], ["hidden_states"]),
186
+ }
187
+
188
+ def __init__(
189
+ self,
190
+ vocab_size=152064,
191
+ hidden_size=8192,
192
+ intermediate_size=29568,
193
+ num_hidden_layers=80,
194
+ num_attention_heads=64,
195
+ num_key_value_heads=8,
196
+ hidden_act="silu",
197
+ max_position_embeddings=131072,
198
+ initializer_range=0.02,
199
+ rms_norm_eps=1e-05,
200
+ use_cache=True,
201
+ tie_word_embeddings=False,
202
+ rope_theta=8000000.0,
203
+ use_sliding_window=False,
204
+ sliding_window=4096,
205
+ max_window_layers=80,
206
+ attention_dropout=0.0,
207
+ vision_config=None,
208
+ rope_scaling=None,
209
+ **kwargs,
210
+ ):
211
+ if isinstance(vision_config, dict):
212
+ self.vision_config = self.sub_configs["vision_config"](**vision_config)
213
+ elif vision_config is None:
214
+ self.vision_config = self.sub_configs["vision_config"]()
215
+
216
+ self.vocab_size = vocab_size
217
+ self.max_position_embeddings = max_position_embeddings
218
+ self.hidden_size = hidden_size
219
+ self.intermediate_size = intermediate_size
220
+ self.num_hidden_layers = num_hidden_layers
221
+ self.num_attention_heads = num_attention_heads
222
+ self.use_sliding_window = use_sliding_window
223
+ self.sliding_window = sliding_window
224
+ self.max_window_layers = max_window_layers
225
+
226
+ # for backward compatibility
227
+ if num_key_value_heads is None:
228
+ num_key_value_heads = num_attention_heads
229
+
230
+ self.num_key_value_heads = num_key_value_heads
231
+ self.hidden_act = hidden_act
232
+ self.initializer_range = initializer_range
233
+ self.rms_norm_eps = rms_norm_eps
234
+ self.use_cache = use_cache
235
+ self.rope_theta = rope_theta
236
+ self.attention_dropout = attention_dropout
237
+ self.rope_scaling = rope_scaling
238
+
239
+ # Validate the correctness of rotary position embeddings parameters
240
+ # BC: if there is a 'type' field, move it to 'rope_type'.
241
+ # and change type from 'mrope' to 'default' because `mrope` does default RoPE calculations
242
+ # one can set it to "linear"/"dynamic" etc. to have scaled RoPE
243
+ # TODO: @raushan update config in the hub
244
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
245
+ if self.rope_scaling["type"] == "mrope":
246
+ self.rope_scaling["type"] = "default"
247
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
248
+ rope_config_validation(self, ignore_keys={"mrope_section"})
249
+
250
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
251
+
252
+
253
+ __all__ = ["KeyeVL1_5Config"]
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "temperature": 0.6,
10
+ "top_k": 20,
11
+ "top_p": 0.95,
12
+ "transformers_version": "4.51.0"
13
+ }
image_processing_keye_vl_1_5.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Kwai Keye team, 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 Keye-VL-1.5."""
21
+
22
+ import math
23
+ from typing import Dict, List, Optional, Union
24
+ from PIL import Image
25
+
26
+ import numpy as np
27
+ import torch
28
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
29
+ from torchvision.transforms import functional as TF
30
+ from transformers.image_transforms import (
31
+ convert_to_rgb,
32
+ resize,
33
+ to_channel_dimension_format,
34
+ )
35
+ from transformers.image_utils import (
36
+ OPENAI_CLIP_MEAN,
37
+ OPENAI_CLIP_STD,
38
+ ChannelDimension,
39
+ ImageInput,
40
+ PILImageResampling,
41
+ get_image_size,
42
+ infer_channel_dimension_format,
43
+ is_scaled_image,
44
+ is_valid_image,
45
+ make_list_of_images,
46
+ to_numpy_array,
47
+ valid_images,
48
+ validate_preprocess_arguments,
49
+ )
50
+ from transformers.video_utils import VideoInput
51
+ from transformers.utils import TensorType, is_vision_available, logging
52
+
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+
57
+ if is_vision_available():
58
+ from PIL import Image
59
+
60
+
61
+ def make_batched_images(images) -> List[List[ImageInput]]:
62
+ """
63
+ Accepts images in list or nested list format, and makes a list of images for preprocessing.
64
+
65
+ Args:
66
+ images (`Union[List[List[ImageInput]], List[ImageInput], ImageInput]`):
67
+ The input image.
68
+
69
+ Returns:
70
+ list: A list of images.
71
+ """
72
+ if isinstance(images, (list, tuple)) and isinstance(images[0], (list, tuple)) and is_valid_image(images[0][0]):
73
+ return [img for img_list in images for img in img_list]
74
+
75
+ elif isinstance(images, (list, tuple)) and is_valid_image(images[0]):
76
+ return images
77
+
78
+ elif is_valid_image(images):
79
+ return [images]
80
+
81
+ raise ValueError(f"Could not make batched images from {images}")
82
+
83
+
84
+ def adjust_size(size, patch_size):
85
+ num_patches = size // patch_size
86
+ if num_patches % 2 != 0: # 如果是奇数,减1
87
+ num_patches -= 1
88
+ return num_patches * patch_size
89
+
90
+
91
+ def make_batched_videos(videos) -> List[VideoInput]:
92
+ if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0]):
93
+ return videos
94
+
95
+ elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
96
+ if isinstance(videos[0], Image.Image):
97
+ return [videos]
98
+ elif len(videos[0].shape) == 4:
99
+ return [list(video) for video in videos]
100
+
101
+ elif is_valid_image(videos) and len(videos.shape) == 4:
102
+ return [list(videos)]
103
+
104
+ raise ValueError(f"Could not make batched video from {videos}")
105
+
106
+
107
+ def smart_resize(
108
+ height: int, width: int, factor: int = 28, min_pixels: int = 56 * 56, max_pixels: int = 14 * 14 * 4096
109
+ ):
110
+ """Rescales the image so that the following conditions are met:
111
+
112
+ 1. Both dimensions (height and width) are divisible by 'factor'.
113
+
114
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
115
+
116
+ 3. The aspect ratio of the image is maintained as closely as possible.
117
+
118
+ """
119
+ #if height < factor or width < factor:
120
+ # raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}")
121
+ # if int(height < factor//4) + int(width < factor//4):
122
+ # raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor//4}")
123
+
124
+ if height < factor:
125
+ print(f"smart_resize: height={height} < factor={factor}, reset height=factor")
126
+ width = round((width * factor) / height)
127
+ height = factor
128
+
129
+ if width < factor:
130
+ print(f"smart_resize: width={width} < factor={factor}, reset width=factor")
131
+ height = round((height * factor) / width)
132
+ width = factor
133
+
134
+ if max(height, width) / min(height, width) > 200:
135
+ raise ValueError(
136
+ f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
137
+ )
138
+ h_bar = round(height / factor) * factor
139
+ w_bar = round(width / factor) * factor
140
+ if h_bar * w_bar > max_pixels:
141
+ beta = math.sqrt((height * width) / max_pixels)
142
+ h_bar = math.floor(height / beta / factor) * factor
143
+ w_bar = math.floor(width / beta / factor) * factor
144
+ elif h_bar * w_bar < min_pixels:
145
+ beta = math.sqrt(min_pixels / (height * width))
146
+ h_bar = math.ceil(height * beta / factor) * factor
147
+ w_bar = math.ceil(width * beta / factor) * factor
148
+ return h_bar, w_bar
149
+
150
+
151
+ class KeyeVL1_5ImageProcessor(BaseImageProcessor):
152
+ r"""
153
+ Constructs a Keye-VL-1.5 image processor that dynamically resizes images based on the original images.
154
+
155
+ Args:
156
+ do_resize (`bool`, *optional*, defaults to `True`):
157
+ Whether to resize the image's (height, width) dimensions.
158
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
159
+ Resampling filter to use when resizing the image.
160
+ do_rescale (`bool`, *optional*, defaults to `True`):
161
+ Whether to rescale the image by the specified scale `rescale_factor`.
162
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
163
+ Scale factor to use if rescaling the image.
164
+ do_normalize (`bool`, *optional*, defaults to `True`):
165
+ Whether to normalize the image.
166
+ image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
167
+ Mean to use if normalizing the image. This is a float or list of floats for each channel in the image.
168
+ image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
169
+ Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image.
170
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
171
+ Whether to convert the image to RGB.
172
+ min_pixels (`int`, *optional*, defaults to `56 * 56`):
173
+ The min pixels of the image to resize the image.
174
+ max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`):
175
+ The max pixels of the image to resize the image.
176
+ patch_size (`int`, *optional*, defaults to 14):
177
+ The spacial patch size of the vision encoder.
178
+ temporal_patch_size (`int`, *optional*, defaults to 2):
179
+ The temporal patch size of the vision encoder.
180
+ merge_size (`int`, *optional*, defaults to 2):
181
+ The merge size of the vision encoder to llm encoder.
182
+ """
183
+
184
+ model_input_names = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw"]
185
+
186
+ def __init__(
187
+ self,
188
+ do_resize: bool = True,
189
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
190
+ do_rescale: bool = True,
191
+ rescale_factor: Union[int, float] = 1 / 255,
192
+ do_normalize: bool = True,
193
+ image_mean: Optional[Union[float, List[float]]] = None,
194
+ image_std: Optional[Union[float, List[float]]] = None,
195
+ do_convert_rgb: bool = True,
196
+ min_pixels: int = 56 * 56,
197
+ max_pixels: int = 28 * 28 * 1280,
198
+ patch_size: int = 14,
199
+ temporal_patch_size: int = 1,
200
+ merge_size: int = 2,
201
+ **kwargs,
202
+ ) -> None:
203
+ super().__init__(**kwargs)
204
+ self.do_resize = do_resize
205
+ self.resample = resample
206
+ self.do_rescale = do_rescale
207
+ self.rescale_factor = rescale_factor
208
+ self.do_normalize = do_normalize
209
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
210
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
211
+ self.min_pixels = min_pixels
212
+ self.max_pixels = max_pixels
213
+ self.patch_size = patch_size
214
+ self.temporal_patch_size = temporal_patch_size
215
+ self.merge_size = merge_size
216
+ self.size = {"min_pixels": min_pixels, "max_pixels": max_pixels}
217
+ self.do_convert_rgb = do_convert_rgb
218
+
219
+ def mvit_rescale(
220
+ self, image: Image.Image, merge_size: int = 2
221
+ ) -> Image.Image:
222
+ try:
223
+ w, h = image.size
224
+ except:
225
+ raise ValueError(str((type(image), image)))
226
+ patch_size = self.patch_size
227
+
228
+ if (w // patch_size) * (h // patch_size) > self.in_token_limit:
229
+ scale = math.sqrt(self.in_token_limit / ((w // patch_size) * (h // patch_size)))
230
+ new_w, new_h = int(w * scale), int(h * scale)
231
+
232
+ image = image.resize((new_w, new_h), Image.Resampling.BILINEAR)
233
+ if self.pad_input:
234
+ new_w, new_h = image.size
235
+ pad_size_h = merge_size * patch_size
236
+ pad_size_w = merge_size * patch_size
237
+
238
+ pad_h = (pad_size_h - new_h % pad_size_h) % pad_size_h
239
+ pad_w = (pad_size_w - new_w % pad_size_w) % pad_size_w
240
+
241
+ image = TF.pad(image, (0, 0, pad_w, pad_h))
242
+ else:
243
+ new_w, new_h = image.size
244
+ new_w = new_w - new_w % patch_size
245
+ new_h = new_h - new_h % patch_size
246
+
247
+ new_w = adjust_size(new_w, patch_size)
248
+ new_h = adjust_size(new_h, patch_size)
249
+
250
+ image = TF.center_crop(image, (new_h, new_w))
251
+
252
+ w, h = image.size
253
+ if w // patch_size >= 512 or h // patch_size >= 512:
254
+ new_h = min(patch_size * 510, h)
255
+ new_w = min(patch_size * 510, w)
256
+ image = TF.center_crop(image, (new_h, new_w))
257
+ #raise ValueError("Exceed pos emb")
258
+ return image
259
+ def _preprocess(
260
+ self,
261
+ images: Union[ImageInput, VideoInput],
262
+ do_resize: bool = None,
263
+ size: Dict[str, int] = None,
264
+ resample: PILImageResampling = None,
265
+ do_rescale: bool = None,
266
+ rescale_factor: float = None,
267
+ do_normalize: bool = None,
268
+ image_mean: Optional[Union[float, List[float]]] = None,
269
+ image_std: Optional[Union[float, List[float]]] = None,
270
+ do_convert_rgb: bool = None,
271
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
272
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
273
+ ):
274
+ """
275
+ Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.
276
+
277
+ Args:
278
+ images (`ImageInput`):
279
+ 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`.
280
+ vision_info (`List[Dict]`, *optional*):
281
+ Optional list of dictionaries containing additional information about vision inputs.
282
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
283
+ Whether to resize the image.
284
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
285
+ Resampling filter to use if resizing the image. This can be one of the `PILImageResampling` enums.
286
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
287
+ Whether to rescale the image.
288
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
289
+ Scale factor to use if rescaling the image.
290
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
291
+ Whether to normalize the image.
292
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
293
+ 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.
294
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
295
+ 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.
296
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
297
+ Whether to convert the image to RGB.
298
+ data_format (`ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):
299
+ The channel dimension format for the output image. Can be one of:
300
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
301
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
302
+ - Unset: Use the channel dimension format of the input image.
303
+ input_data_format (`ChannelDimension` or `str`, *optional*):
304
+ The channel dimension format for the input image. Can be one of:
305
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
306
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
307
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
308
+ """
309
+ images = make_list_of_images(images)
310
+
311
+ if do_convert_rgb:
312
+ images = [convert_to_rgb(image) for image in images]
313
+
314
+ # All transformations expect numpy arrays.
315
+ images = [to_numpy_array(image) for image in images]
316
+
317
+ if is_scaled_image(images[0]) and do_rescale:
318
+ logger.warning_once(
319
+ "It looks like you are trying to rescale already rescaled images. If the input"
320
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
321
+ )
322
+ if input_data_format is None:
323
+ # We assume that all images have the same channel dimension format.
324
+ input_data_format = infer_channel_dimension_format(images[0])
325
+
326
+ height, width = get_image_size(images[0], channel_dim=input_data_format)
327
+ resized_height, resized_width = height, width
328
+ processed_images = []
329
+ for image in images:
330
+ # image = self.mvit_rescale(image, merge_size=self.merge_size)
331
+ if do_resize:
332
+ if size is not None and "height" in size.keys():
333
+ resized_height, resized_width = size["height"], size["width"]
334
+ else:
335
+ resized_height, resized_width = smart_resize(
336
+ height,
337
+ width,
338
+ factor=self.patch_size * self.merge_size,
339
+ min_pixels=self.min_pixels,
340
+ max_pixels=self.max_pixels,
341
+ )
342
+ image = resize(
343
+ image, size=(resized_height, resized_width), resample=resample, input_data_format=input_data_format
344
+ )
345
+
346
+ if do_rescale:
347
+ image = self.rescale(image, scale=rescale_factor, input_data_format=input_data_format)
348
+
349
+ if do_normalize:
350
+ image = self.normalize(
351
+ image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
352
+ )
353
+
354
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
355
+ processed_images.append(image)
356
+
357
+ patches = np.array(processed_images)
358
+ if data_format == ChannelDimension.LAST:
359
+ patches = patches.transpose(0, 3, 1, 2)
360
+ if patches.shape[0] == 1:
361
+ patches = np.tile(patches, (self.temporal_patch_size, 1, 1, 1))
362
+ init_patches = patches
363
+ channel = patches.shape[1]
364
+ grid_t = patches.shape[0] // self.temporal_patch_size
365
+ grid_h, grid_w = resized_height // self.patch_size, resized_width // self.patch_size
366
+ patches = patches.reshape(
367
+ grid_t,
368
+ self.temporal_patch_size,
369
+ channel,
370
+ grid_h,
371
+ self.patch_size,
372
+ grid_w,
373
+ self.patch_size,
374
+ )
375
+ patches = patches.transpose(0, 3, 5, 2, 1, 4, 6)
376
+ assert self.temporal_patch_size == 1
377
+ flatten_patches = patches.reshape(
378
+ grid_t * grid_h * grid_w, channel, self.patch_size, self.patch_size
379
+ )
380
+ return flatten_patches, (grid_t, grid_h, grid_w)
381
+
382
+ def preprocess(
383
+ self,
384
+ images: ImageInput,
385
+ videos: VideoInput = None,
386
+ do_resize: bool = None,
387
+ size: Dict[str, int] = None,
388
+ resample: PILImageResampling = None,
389
+ do_rescale: bool = None,
390
+ rescale_factor: float = None,
391
+ do_normalize: bool = None,
392
+ image_mean: Optional[Union[float, List[float]]] = None,
393
+ image_std: Optional[Union[float, List[float]]] = None,
394
+ do_convert_rgb: bool = None,
395
+ return_tensors: Optional[Union[str, TensorType]] = None,
396
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
397
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
398
+ ):
399
+ """
400
+ Args:
401
+ images (`ImageInput`):
402
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
403
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
404
+ videos (`VideoInput`):
405
+ Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If
406
+ passing in videos with pixel values between 0 and 1, set `do_rescale=False`.
407
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
408
+ Whether to resize the image.
409
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
410
+ Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
411
+ the longest edge resized to keep the input aspect ratio.
412
+ resample (`int`, *optional*, defaults to `self.resample`):
413
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
414
+ has an effect if `do_resize` is set to `True`.
415
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
416
+ Whether to rescale the image.
417
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
418
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
419
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
420
+ Whether to normalize the image.
421
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
422
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
423
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
424
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
425
+ `True`.
426
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
427
+ Whether to convert the image to RGB.
428
+ return_tensors (`str` or `TensorType`, *optional*):
429
+ The type of tensors to return. Can be one of:
430
+ - Unset: Return a list of `np.ndarray`.
431
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
432
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
433
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
434
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
435
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
436
+ The channel dimension format for the output image. Can be one of:
437
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
438
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
439
+ - Unset: Use the channel dimension format of the input image.
440
+ input_data_format (`ChannelDimension` or `str`, *optional*):
441
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
442
+ from the input image. Can be one of:
443
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
444
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
445
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
446
+
447
+ """
448
+ do_resize = do_resize if do_resize is not None else self.do_resize
449
+ size = size if size is not None else self.size
450
+ resample = resample if resample is not None else self.resample
451
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
452
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
453
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
454
+ image_mean = image_mean if image_mean is not None else self.image_mean
455
+ image_std = image_std if image_std is not None else self.image_std
456
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
457
+
458
+ if images is not None:
459
+ images = make_batched_images(images)
460
+ if videos is not None:
461
+ videos = make_batched_videos(videos)
462
+
463
+ if images is not None and not valid_images(images):
464
+ raise ValueError(
465
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
466
+ "torch.Tensor, tf.Tensor or jax.ndarray."
467
+ )
468
+
469
+ validate_preprocess_arguments(
470
+ rescale_factor=rescale_factor,
471
+ do_normalize=do_normalize,
472
+ image_mean=image_mean,
473
+ image_std=image_std,
474
+ do_resize=do_resize,
475
+ size=size,
476
+ resample=resample,
477
+ )
478
+
479
+ if images is not None:
480
+ pixel_values, vision_grid_thws = [], []
481
+ for image in images:
482
+ patches, image_grid_thw = self._preprocess(
483
+ image,
484
+ do_resize=do_resize,
485
+ size = size,
486
+ resample=resample,
487
+ do_rescale=do_rescale,
488
+ rescale_factor=rescale_factor,
489
+ do_normalize=do_normalize,
490
+ image_mean=image_mean,
491
+ image_std=image_std,
492
+ data_format=data_format,
493
+ do_convert_rgb=do_convert_rgb,
494
+ input_data_format=input_data_format,
495
+ )
496
+ pixel_values.extend(patches)
497
+ vision_grid_thws.append(image_grid_thw)
498
+ pixel_values = np.array(pixel_values)
499
+ vision_grid_thws = np.array(vision_grid_thws)
500
+ data = {"pixel_values": pixel_values, "image_grid_thw": vision_grid_thws}
501
+
502
+ if videos is not None:
503
+ pixel_values, vision_grid_thws = [], []
504
+ for images in videos:
505
+ patches, video_grid_thw = self._preprocess(
506
+ images,
507
+ do_resize=do_resize,
508
+ size = size,
509
+ resample=resample,
510
+ do_rescale=do_rescale,
511
+ rescale_factor=rescale_factor,
512
+ do_normalize=do_normalize,
513
+ image_mean=image_mean,
514
+ image_std=image_std,
515
+ data_format=data_format,
516
+ do_convert_rgb=do_convert_rgb,
517
+ input_data_format=input_data_format,
518
+ )
519
+ pixel_values.extend(patches)
520
+ vision_grid_thws.append(video_grid_thw)
521
+ pixel_values = np.array(pixel_values)
522
+ vision_grid_thws = np.array(vision_grid_thws)
523
+ data = {"pixel_values_videos": pixel_values, "video_grid_thw": vision_grid_thws}
524
+
525
+ return BatchFeature(data=data, tensor_type=return_tensors)
526
+
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f0df70edb9727cfa83e98f7acc2823cec2dcbc714b1cbf8790302108486ad06
3
+ size 5159314453
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2d1b463f53b0469c320cff557a7168394bbb008d83f8b036f049dc9b76a7e294
3
+ size 372658449
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_keye_vl_1_5.py ADDED
The diff for this file is too large to render. See raw diff
 
preprocessor_config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "min_pixels": 3136,
3
+ "max_pixels": 16056320,
4
+ "patch_size": 14,
5
+ "temporal_patch_size": 1,
6
+ "merge_size": 2,
7
+ "image_mean": [
8
+ 0.5,0.5,0.5
9
+ ],
10
+ "image_std": [
11
+ 0.5,0.5,0.5
12
+ ],
13
+ "processor_class": "KeyeVL1_5Processor",
14
+ "auto_map": {
15
+ "AutoProcessor": "processing_keye_vl_1_5.KeyeVL1_5Processor",
16
+ "AutoImageProcessor": "image_processing_keye_vl_1_5.KeyeVL1_5ImageProcessor"
17
+ },
18
+ "size":{
19
+ "height": 384,
20
+ "width": 384
21
+ }
22
+ }
processing_keye_vl_1_5.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The Kwai Keye Team 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
+ from typing import List, Union, Optional
21
+
22
+ from transformers.feature_extraction_utils import BatchFeature
23
+ from transformers.image_utils import ImageInput
24
+ from transformers.video_utils import VideoInput
25
+ from transformers.processing_utils import ProcessingKwargs, ProcessorMixin, Unpack, VideosKwargs
26
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
27
+ from .image_processing_keye_vl_1_5 import KeyeVL1_5ImageProcessor
28
+ import torch
29
+ import torch.nn as nn
30
+ import numpy as np
31
+ from itertools import chain
32
+
33
+ class KeyeVL1_5VideosProcessorKwargs(VideosKwargs, total=False):
34
+ fps: Optional[Union[List[float], float]]
35
+ # 准备reszie到的width(slow)
36
+ width: Optional[Union[List[int], int]]
37
+ # 准备reszie到的height(slow)
38
+ height: Optional[Union[List[int], int]]
39
+ # 准备resize到的width(fast)
40
+ fast_width: Optional[Union[List[int], int]]
41
+ # 准备resize到的height(fast)
42
+ fast_height: Optional[Union[List[int], int]]
43
+ # 用于标记每一帧的时间戳,数量和帧数相等
44
+ timestamps: Optional[Union[List[torch.Tensor], torch.Tensor]]
45
+ # 用于标记每一帧的类型是slow还是fast,slow=0, fast=1
46
+ frame_types: Optional[Union[List[torch.Tensor], torch.Tensor]]
47
+
48
+
49
+ class KeyeVL1_5ProcessorKwargs(ProcessingKwargs, total=False):
50
+ videos_kwargs: KeyeVL1_5VideosProcessorKwargs
51
+ _defaults = {
52
+ "text_kwargs": {
53
+ "padding": False,
54
+ },
55
+ "videos_kwargs": {"fps": 2.0},
56
+ }
57
+
58
+ def select_slow_fast_frames(frames: torch.Tensor, frame_types: torch.Tensor):
59
+ """
60
+ Selects frames from a tensor based on a mask list.
61
+
62
+ Args:
63
+ frames (torch.Tensor): A tensor of shape (nframes, c, h, w).
64
+ frame_types (torch.Tensor): A int tensor of shape (nframes,)
65
+
66
+ Returns:
67
+ tuple[torch.Tensor, torch.Tensor]: A tuple containing two tensors:
68
+ - slow_frames: Frames which the type is 0.
69
+ - fast_frames: Frames where the type is 1.
70
+ """
71
+ nframes, _, _, _ = frames.shape
72
+ if frame_types.shape[-1] != nframes:
73
+ raise ValueError("Length of mask must be equal to the number of frames.")
74
+
75
+ mask = (frame_types == 0)
76
+
77
+ slow_frames = frames[mask]
78
+ fast_frames = frames[~mask]
79
+
80
+ return slow_frames, fast_frames
81
+
82
+ def split_thw(tensor):
83
+ """Split grid_thw in t dimension, the result tensor should like [[1, h, w],...]"""
84
+ repeats = tensor[:, 0]
85
+ new_thw = torch.cat([
86
+ torch.ones(tensor.shape[0], 1, dtype=tensor.dtype,
87
+ device=tensor.device),
88
+ tensor[:, 1:]
89
+ ], dim=1)
90
+ return torch.repeat_interleave(new_thw, repeats, dim=0)
91
+
92
+ def merge_hws(hws):
93
+ """
94
+ 优化版本:使用更高效的方法合并张量
95
+ """
96
+ merged = []
97
+ last_hw = [-1, -1]
98
+
99
+ for hw in hws:
100
+ # 找到连续相同形状的张量
101
+ if hw[1:] == last_hw:
102
+ merged[-1][0] += 1
103
+ else:
104
+ merged.append(hw)
105
+ last_hw = hw[1:]
106
+
107
+ return torch.tensor(merged)
108
+
109
+ class KeyeVL1_5Processor(ProcessorMixin):
110
+ r"""
111
+ [`KeyeVL1_5Processor`] offers all the functionalities of [`KeyeVL1_5ImageProcessor`] and [`Qwen2TokenizerFast`]. See the
112
+ [`~KeyeVL1_5Processor.__call__`] and [`~KeyeVL1_5Processor.decode`] for more information.
113
+ Args:
114
+ image_processor ([`KeyeVL1_5ImageProcessor`], *optional*):
115
+ The image processor is a required input.
116
+ tokenizer ([`Qwen2TokenizerFast`], *optional*):
117
+ The tokenizer is a required input.
118
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
119
+ in a chat into a tokenizable string.
120
+ """
121
+
122
+ attributes = ["image_processor", "tokenizer"]
123
+ valid_kwargs = [
124
+ "chat_template","image_std", "min_pixels", "image_mean", "merge_size", "image_processor_type",
125
+ "temporal_patch_size", "patch_size", "max_pixels"
126
+ ]
127
+
128
+ image_processor_class = "AutoImageProcessor"
129
+ tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
130
+
131
+ def __init__(self, image_processor=None, tokenizer=None, chat_template=None, **kwargs):
132
+ self.image_token = "<|image_pad|>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
133
+ self.video_token = "<|video_pad|>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
134
+ self.frame_token = "<|frame|>" if not hasattr(tokenizer, "frame_token") else tokenizer.frame_token
135
+ self.fast_video_token = "<|fast_video_pad|>" if not hasattr(tokenizer, "fast_video_token") else tokenizer.fast_video_token
136
+ self.fast_start = "<|fast_start|>" if not hasattr(tokenizer, "fast_start") else tokenizer.fast_start
137
+ self.fast_end = "<|fast_end|>" if not hasattr(tokenizer, "fast_end") else tokenizer.fast_end
138
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
139
+
140
+ self.slowfast = True
141
+
142
+ def __call__(
143
+ self,
144
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
145
+ images: ImageInput = None,
146
+ videos: VideoInput = None,
147
+ **kwargs: Unpack[KeyeVL1_5ProcessorKwargs],
148
+ ) -> BatchFeature:
149
+ """
150
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
151
+ and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode
152
+ the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to
153
+ KeyeVL1_5ImageProcessor's [`~KeyeVL1_5ImageProcessor.__call__`] if `vision_infos` is not `None`.
154
+
155
+ Args:
156
+ text (`str`, `List[str]`, `List[List[str]]`):
157
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
158
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
159
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
160
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
161
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
162
+ tensor. Both channels-first and channels-last formats are supported.
163
+ videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
164
+ The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
165
+ tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
166
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
167
+ If set, will return tensors of a particular framework. Acceptable values are:
168
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
169
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
170
+ - `'np'`: Return NumPy `np.ndarray` objects.
171
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
172
+
173
+ Returns:
174
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
175
+
176
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
177
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
178
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
179
+ `None`).
180
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
181
+ - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
182
+ - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
183
+ - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
184
+ - **second_per_grid_ts** -- List of video seconds per time grid. Returned when `videos` is not `None`.
185
+ """
186
+ output_kwargs = self._merge_kwargs(
187
+ KeyeVL1_5ProcessorKwargs,
188
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
189
+ **kwargs,
190
+ )
191
+
192
+ if images is not None:
193
+ # slow_images = images
194
+ image_inputs = self.image_processor(images=images, return_tensors="pt")
195
+ image_inputs['pixel_values'] = image_inputs['pixel_values']
196
+ image_grid_thw = image_inputs["image_grid_thw"]
197
+ else:
198
+ image_inputs = {}
199
+ image_grid_thw = None
200
+
201
+ num_frames = []
202
+ if videos is not None:
203
+ batch_slow_frames = []
204
+ batch_fast_frames = []
205
+
206
+ videos_kwargs = output_kwargs["videos_kwargs"]
207
+ num_videos = len(videos)
208
+ batch_frame_types = videos_kwargs.get("frame_types", [None] * num_videos)
209
+ batch_timestamps = videos_kwargs.get("timestamps", [None] * num_videos)
210
+ batch_width = videos_kwargs.get("width", [None] * num_videos)
211
+ batch_height = videos_kwargs.get("height", [None] * num_videos)
212
+ batch_fast_width = videos_kwargs.get("fast_width", [None] * num_videos)
213
+ batch_fast_height = videos_kwargs.get("fast_height", [None] * num_videos)
214
+
215
+ for index, frames in enumerate(videos):
216
+ if isinstance(frames, np.ndarray):
217
+ frames = torch.from_numpy(frames)
218
+ nframes = frames.shape[0]
219
+ num_frames.append(nframes)
220
+ assert nframes > 0, "No frames in video"
221
+ if batch_frame_types[index] is None:
222
+ # default to all slow frames
223
+ batch_frame_types[index] = torch.zeros((nframes, ), dtype=torch.long)
224
+ frame_types = batch_frame_types[index]
225
+ slow_frames, fast_frames = select_slow_fast_frames(frames, frame_types)
226
+ has_fast_frames = fast_frames.shape[0] > 0
227
+ # resize slow frames
228
+ resized_width = batch_width[index]
229
+ resized_height = batch_height[index]
230
+ if resized_width is not None and resized_height is not None:
231
+ slow_frames = nn.functional.interpolate(
232
+ slow_frames,
233
+ [resized_height, resized_width],
234
+ mode="bilinear",
235
+ antialias=True,
236
+ ).float()
237
+ do_resize = False
238
+ else:
239
+ slow_frames = slow_frames.float()
240
+ do_resize = True
241
+ # Tensor(N, C, H, W) -> Tuple[Tensor(1, C, H, W)]
242
+ # slow_frames = list(slow_frames.split(1, dim=0)),不split,在模型里面做
243
+ slow_video_inputs = self.image_processor(
244
+ images=None, videos=[slow_frames], **output_kwargs["images_kwargs"], do_resize=do_resize)
245
+ slow_video_grid_thw = slow_video_inputs["video_grid_thw"]
246
+ batch_slow_frames.append(slow_video_inputs)
247
+ # # 当前这个视频每一帧的token数
248
+ # slow_frames_patch_nums[index] = int(slow_video_inputs["pixel_values_videos"].shape[0] / \
249
+ # slow_video_grid_thw.squeeze()[0])
250
+
251
+ if has_fast_frames:
252
+ # TODO: shrink fast_frames
253
+ fast_resized_width = batch_fast_width[index]
254
+ fast_resized_height = batch_fast_height[index]
255
+ if fast_resized_width is not None and fast_resized_height is not None:
256
+ fast_frames = nn.functional.interpolate(
257
+ fast_frames,
258
+ [fast_resized_height, fast_resized_width],
259
+ mode="bilinear",
260
+ antialias=True,
261
+ ).float()
262
+ do_fast_resize = False
263
+ else:
264
+ fast_frames = fast_frames.float()
265
+ do_fast_resize = True
266
+ # Tensor(N, C, H, W) -> Tuple[Tensor(1, C, H, W)]
267
+ # fast_frames = list(fast_frames.split(1, dim=0))
268
+ fast_video_inputs = self.image_processor(
269
+ images=None, videos=[fast_frames], **output_kwargs["images_kwargs"], do_resize=do_fast_resize)
270
+ fast_video_grid_thw = fast_video_inputs["video_grid_thw"]
271
+ batch_fast_frames.append(fast_video_inputs)
272
+ # # 当前这个视频的所有token数
273
+ # fast_frames_token_nums[index] = int(fast_video_inputs["pixel_values_videos"].shape[0] / \
274
+ # fast_video_grid_thw.squeeze()[0])
275
+
276
+ assert len(batch_slow_frames) > 0, "Slow frames should not be empty."
277
+ slow_pixel_values_videos_list = [
278
+ video["pixel_values_videos"] for video in batch_slow_frames if video is not None]
279
+ slow_video_grid_thw_list = [
280
+ video["video_grid_thw"] for video in batch_slow_frames if video is not None]
281
+
282
+ slow_pixel_values_videos = torch.concat(slow_pixel_values_videos_list, dim=0)
283
+ slow_video_grid_thw = torch.concat(slow_video_grid_thw_list, dim=0)
284
+
285
+ if has_fast_frames:
286
+ fast_pixel_values_videos_list = [
287
+ video["pixel_values_videos"] for video in batch_fast_frames \
288
+ if video is not None]
289
+ fast_video_grid_thw_list = [
290
+ video["video_grid_thw"] for video in batch_fast_frames \
291
+ if video is not None]
292
+
293
+ fast_pixel_values_videos = \
294
+ torch.concat(fast_pixel_values_videos_list, dim=0)
295
+ fast_video_grid_thw = \
296
+ torch.concat(fast_video_grid_thw_list, dim=0)
297
+ else:
298
+ fast_video_grid_thw = None
299
+ else:
300
+ slow_video_grid_thw = None
301
+ fast_video_grid_thw = None
302
+
303
+ if not isinstance(text, list):
304
+ text = [text]
305
+ if image_grid_thw is not None:
306
+ index = 0
307
+ for i in range(len(text)):
308
+ while self.image_token in text[i]:
309
+ image_place_holder_tempale = "<|placeholder|>" * (
310
+ image_grid_thw[index].prod() // self.image_processor.merge_size ** 2)
311
+ text[i] = text[i].replace(
312
+ self.image_token,
313
+ image_place_holder_tempale,
314
+ 1,
315
+ )
316
+ index += 1
317
+ text[i] = text[i].replace("<|placeholder|>", self.image_token)
318
+
319
+ pixel_values_videos = []
320
+ video_grid_thw = []
321
+ videos_inputs = {}
322
+ if slow_video_grid_thw is not None:
323
+ slow_video_grid_thw = split_thw(slow_video_grid_thw)
324
+ if fast_video_grid_thw is not None:
325
+ fast_video_grid_thw = split_thw(fast_video_grid_thw)
326
+ index = 0
327
+ slow_index = 0
328
+ fast_index = 0
329
+ slow_pixels_index = 0
330
+ fast_pixels_index = 0
331
+ for i in range(len(text)):
332
+ while self.video_token in text[i]:
333
+ video_place_holder_tempale = ""
334
+
335
+ for j in range(batch_frame_types[index].shape[-1]):
336
+ if batch_timestamps[index] is not None: # 如果有时间戳
337
+ video_place_holder_tempale += self.frame_token + format(batch_timestamps[index][j], ".1f")
338
+ else:
339
+ video_place_holder_tempale += self.frame_token
340
+
341
+ # 当前帧是slow
342
+ if batch_frame_types[index][j] == 0:
343
+ num_patches = int(slow_video_grid_thw[slow_index].prod())
344
+ video_place_holder_tempale += "<|placeholder|>" * (
345
+ num_patches // self.image_processor.merge_size ** 2)
346
+ pixel_values_videos.append(
347
+ slow_pixel_values_videos[slow_pixels_index:slow_pixels_index + num_patches])
348
+ slow_pixels_index = slow_pixels_index + num_patches
349
+ video_grid_thw.append(slow_video_grid_thw[slow_index].tolist())
350
+ slow_index += 1
351
+
352
+ # 当前帧是fast
353
+ elif batch_frame_types[index][j] == 1:
354
+ num_patches = int(fast_video_grid_thw[fast_index].prod())
355
+ video_place_holder_tempale += self.fast_start + "<|placeholder|>" * (
356
+ num_patches // self.image_processor.merge_size ** 2) + \
357
+ self.fast_end
358
+ pixel_values_videos.append(
359
+ fast_pixel_values_videos[fast_pixels_index:fast_pixels_index + num_patches])
360
+ fast_pixels_index = fast_pixels_index + num_patches
361
+ video_grid_thw.append(fast_video_grid_thw[fast_index].tolist())
362
+ fast_index += 1
363
+ text[i] = text[i].replace(
364
+ self.video_token,
365
+ video_place_holder_tempale,
366
+ 1,
367
+ )
368
+ index += 1
369
+ text[i] = text[i].replace("<|placeholder|>", self.video_token)
370
+
371
+ videos_inputs["pixel_values_videos"] = torch.cat(pixel_values_videos, dim=0)
372
+ videos_inputs["video_grid_thw"] = merge_hws(video_grid_thw)
373
+ videos_inputs["num_frames"] = torch.tensor(num_frames)
374
+
375
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
376
+
377
+ return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs})
378
+
379
+ def batch_decode(self, *args, **kwargs):
380
+ """
381
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
382
+ refer to the docstring of this method for more information.
383
+ """
384
+ return self.tokenizer.batch_decode(*args, **kwargs)
385
+
386
+ def decode(self, *args, **kwargs):
387
+ """
388
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
389
+ the docstring of this method for more information.
390
+ """
391
+ return self.tokenizer.decode(*args, **kwargs)
392
+
393
+ def post_process_image_text_to_text(
394
+ self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs
395
+ ):
396
+ """
397
+ Post-process the output of the model to decode the text.
398
+
399
+ Args:
400
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
401
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
402
+ or `(sequence_length,)`.
403
+ skip_special_tokens (`bool`, *optional*, defaults to `True`):
404
+ Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
405
+ Clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
406
+ Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.
407
+ **kwargs:
408
+ Additional arguments to be passed to the tokenizer's `batch_decode method`.
409
+
410
+ Returns:
411
+ `List[str]`: The decoded text.
412
+ """
413
+ return self.tokenizer.batch_decode(
414
+ generated_outputs,
415
+ skip_special_tokens=skip_special_tokens,
416
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
417
+ **kwargs,
418
+ )
419
+
420
+ @property
421
+ def model_input_names(self):
422
+ tokenizer_input_names = self.tokenizer.model_input_names
423
+ image_processor_input_names = self.image_processor.model_input_names
424
+ names_from_processor = list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
425
+ return names_from_processor
426
+
427
+
428
+
429
+ __all__ = ["KeyeVL1_5Processor"]
processor_config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_keye_vl_1_5.KeyeVL1_5Processor"
4
+ },
5
+ "image_processor": {
6
+ "auto_map": {
7
+ "AutoImageProcessor": "image_processing_keye_vl_1_5.KeyeVL1_5ImageProcessor",
8
+ "AutoProcessor": "processing_keye_vl_1_5.KeyeVL1_5Processor"
9
+ },
10
+ "do_convert_rgb": true,
11
+ "do_normalize": true,
12
+ "do_rescale": true,
13
+ "do_resize": true,
14
+ "image_mean": [
15
+ 0.5,
16
+ 0.5,
17
+ 0.5
18
+ ],
19
+ "image_processor_type": "KeyeVL1_5ImageProcessor",
20
+ "image_std": [
21
+ 0.5,
22
+ 0.5,
23
+ 0.5
24
+ ],
25
+ "max_pixels": 16056320,
26
+ "merge_size": 2,
27
+ "min_pixels": 3136,
28
+ "patch_size": 14,
29
+ "resample": 2,
30
+ "rescale_factor": 0.00392156862745098,
31
+ "size": {
32
+ "max_pixels": 16056320,
33
+ "min_pixels": 3136
34
+ },
35
+ "temporal_patch_size": 1
36
+ },
37
+ "processor_class": "KeyeVL1_5Processor"
38
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|vision_start|>",
6
+ "<|vision_end|>",
7
+ "<|vision_pad|>",
8
+ "<|image_pad|>",
9
+ "<|video_pad|>"
10
+ ],
11
+ "eos_token": {
12
+ "content": "<|im_end|>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false
17
+ },
18
+ "pad_token": {
19
+ "content": "<|endoftext|>",
20
+ "lstrip": false,
21
+ "normalized": false,
22
+ "rstrip": false,
23
+ "single_word": false
24
+ }
25
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:852176eb11b42e01c67097d2ea334863b3c414c78c3208c20311075339080d1f
3
+ size 11424979
tokenizer_config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "auto_map": {
4
+ "AutoProcessor": "processing_keye_vl_1_5.KeyeVL1_5Processor"
5
+ },
6
+ "backend": "tokenizers",
7
+ "bos_token": null,
8
+ "clean_up_tokenization_spaces": false,
9
+ "eos_token": "<|im_end|>",
10
+ "errors": "replace",
11
+ "extra_special_tokens": [
12
+ "<|im_start|>",
13
+ "<|im_end|>",
14
+ "<|vision_start|>",
15
+ "<|vision_end|>",
16
+ "<|vision_pad|>",
17
+ "<|image_pad|>",
18
+ "<|video_pad|>"
19
+ ],
20
+ "is_local": true,
21
+ "model_max_length": 131072,
22
+ "pad_token": "<|endoftext|>",
23
+ "processor_class": "KeyeVL1_5Processor",
24
+ "split_special_tokens": false,
25
+ "tokenizer_class": "TokenizersBackend",
26
+ "unk_token": null
27
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff