lkeab commited on
Commit
a10fac4
·
verified ·
1 Parent(s): 5eb792c

Transfer from pg-team/pg-vl-2b-hf

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
README.md ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <p align="center">
2
+ <img src="assets/logo.png" width="160" />
3
+ </p>
4
+
5
+ <h2 align="center">PenguinVL</h2>
6
+ <h4 align="center">
7
+ Exploring the Efficiency Limits of VLM with LLM-based Vision Encoders
8
+ </h4>
9
+
10
+ ---
11
+
12
+ ## 📰 News
13
+
14
+ * **2025.03** — PenguinVL-Encoder now available for general use.
15
+ * **2025.03** — Released PenguinVL-2B, PenguinVL-8B.
16
+
17
+ ---
18
+
19
+ ## 🌟 Model Overview
20
+
21
+ PenguinVL is a compact Vision-Language Model, designed to explore the efficiency limits of small-scale VLMs.
22
+
23
+ Unlike most existing VLMs that rely on contrastive-pretrained vision encoders (e.g., CLIP/SigLIP), PG-VL initializes its vision encoder directly from a **text-only LLM**. This design avoids the objective mismatch between contrastive learning and autoregressive language modeling, enabling tighter alignment between visual representations and the language backbone.
24
+
25
+ ### Key Characteristics
26
+
27
+ - 🧠 **LLM-based Vision Encoder**
28
+ The vision encoder is adapted from a pretrained text LLM (Qwen3-0.6B), modified with bidirectional attention and 2D-RoPE for spatial modeling.
29
+ This provides strong semantic priors and native compatibility with the downstream LLM.
30
+
31
+ - 🎥 **Efficient Video Understanding**
32
+ A Temporal Redundancy-Aware (TRA) token compression strategy dynamically allocates token budgets across frames, enabling long-video reasoning within a limited context window.
33
+
34
+ - 🏗 Unified Architecture
35
+ The model consists of:
36
+ 1. LLM-initialized vision encoder
37
+ 2. Lightweight MLP projector
38
+ 3. Qwen3 language backbone
39
+
40
+ - 📊 Compact but Strong
41
+ At 2B scale, PG-VL achieves competitive performance across image, document, OCR, math, and video benchmarks while remaining deployment-friendly.
42
+
43
+ ---
44
+
45
+ ## 🧪 Quick Start — Transformers Inference
46
+
47
+ ```python
48
+ import torch
49
+ from transformers import AutoModelForCausalLM, AutoProcessor
50
+
51
+ model_name = "pg-team/pg-vl-2b-hf"
52
+
53
+ model = AutoModelForCausalLM.from_pretrained(
54
+ model_name,
55
+ trust_remote_code=True,
56
+ device_map="auto",
57
+ torch_dtype=torch.bfloat16,
58
+ )
59
+
60
+ processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True)
61
+
62
+ # Example: Image + Text
63
+ inputs = processor(
64
+ conversation=[
65
+ {"role": "system", "content": "You are a helpful assistant."},
66
+ {
67
+ "role": "user",
68
+ "content": [
69
+ {"type": "image", "image": {"image_path": "assets/example.jpg"}},
70
+ {"type": "text", "text": "Describe this image."}
71
+ ],
72
+ },
73
+ ],
74
+ return_tensors="pt",
75
+ )
76
+
77
+ inputs = {k: v.to("cuda") for k, v in inputs.items() if isinstance(v, torch.Tensor)}
78
+
79
+ output_ids = model.generate(**inputs, max_new_tokens=128)
80
+ response = processor.decode(output_ids[0], skip_special_tokens=True)
81
+
82
+ print(response)
83
+ ```
84
+
85
+ ## 🌎 Model Zoo
86
+ | Model | Base Model | HF Link |
87
+ | -------------------- | ------------ | ------------------------------------------------------------ |
88
+ | PenguinVL-8B | Qwen3-8B | [pg-team/pg-vl-8b-hf](https://huggingface.co/pg-team/pg-vl-8b-hf) |
89
+ | PenguinVL-2B | Qwen3-1.7B | [pg-team/pg-vl-2b-hf](https://huggingface.co/pg-team/pg-vl-2b-hf) |
90
+ | PenguinVL-Encoder | Qwen3-0.6B | [pg-team/pg-vision-encoder](https://huggingface.co/pg-team/pg-vision-encoder) |
91
+
92
+ ## 🚀 Main Results
93
+ xxx
94
+
95
+ ## Citation
96
+
97
+ If you find PenguinVL useful for your research and applications, please cite using this BibTeX:
98
+ ```bibtex
99
+ ...
100
+ ```
added_tokens.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<image>": 151669,
6
+ "<think>": 151667,
7
+ "<tool_call>": 151657,
8
+ "<tool_response>": 151665,
9
+ "<|audio_end|>": 151674,
10
+ "<|audio_start|>": 151673,
11
+ "<|audio|>": 151672,
12
+ "<|box_end|>": 151649,
13
+ "<|box_start|>": 151648,
14
+ "<|endoftext|>": 151643,
15
+ "<|file_sep|>": 151664,
16
+ "<|fim_middle|>": 151660,
17
+ "<|fim_pad|>": 151662,
18
+ "<|fim_prefix|>": 151659,
19
+ "<|fim_suffix|>": 151661,
20
+ "<|im_end|>": 151645,
21
+ "<|im_start|>": 151644,
22
+ "<|image_pad|>": 151655,
23
+ "<|object_ref_end|>": 151647,
24
+ "<|object_ref_start|>": 151646,
25
+ "<|quad_end|>": 151651,
26
+ "<|quad_start|>": 151650,
27
+ "<|repo_name|>": 151663,
28
+ "<|stream_end|>": 151671,
29
+ "<|stream_start|>": 151670,
30
+ "<|video_pad|>": 151656,
31
+ "<|vision_end|>": 151653,
32
+ "<|vision_pad|>": 151654,
33
+ "<|vision_start|>": 151652
34
+ }
chat_template.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "chat_template": "\n{%- set identifier = 'im' %}\n{% for message in messages %}\n {% if message['role'] == 'stream' %}\n {% set identifier = 'stream' %}\n {% else %}\n {% set identifier = 'im' %}\n {% endif %}\n {% if message['role'] is not none %}\n {{- '<|' + identifier + '_start|>' + message['role'] + '\n' -}}\n {% endif %}\n {% if message['content'] is string %}\n {{- message['content'] + '<|' + identifier + '_end|>\n' -}}\n {% else %}\n {% for content in message['content'] %}\n {% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}\n {% if 'time' in content %}\n {{- 'Time ' + content['time'] | round(1) | string + 's: ' -}}\n {% endif %}\n {{- image_token + '\n' -}}\n {% elif content['type'] == 'video' or 'video' in content or 'video_url' in content %}\n {% for i in range(content['num_frames']) %}\n {% if 'timestamps' in content and content['timestamps']|length > 0 %}\n {{- 'Time ' + content['timestamps'][i] | round(1) | string + 's:' -}}\n {% endif %}\n {% if i < content['num_frames'] - 1 %}\n {{- image_token + ',' -}}\n {% else %}\n {{- image_token + '\n' -}}\n {% endif %}\n {% endfor %}\n {% elif content['type'] == 'text' or 'text' in content %}\n {{- content['text'] -}}\n {% endif %}\n {% endfor %}\n {% if message['role'] is not none %}\n {{- '<|' + identifier + '_end|>\n' -}}\n {% endif %}\n {% endif %}\n{% endfor %}\n{% if add_generation_prompt %}\n {{- '<|im_start|>assistant\n' -}}\n {% if not add_think_prompt %}\n {{- '<think>\n\n</think>\n\n' -}}\n {% endif %}\n{% endif %}\n"
3
+ }
config.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "PenguinVLQwen3ForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_penguinvl.PenguinVLQwen3Config",
7
+ "AutoModelForCausalLM": "modeling_penguinvl_qwen3.PenguinVLQwen3ForCausalLM"
8
+ },
9
+ "attention_bias": false,
10
+ "attention_dropout": 0.0,
11
+ "bos_token_id": 151643,
12
+ "eos_token_id": 151645,
13
+ "head_dim": 128,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 2048,
16
+ "image_aspect_ratio": "square",
17
+ "image_token_index": 151669,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 6144,
20
+ "loss_reduction_scope": "batch",
21
+ "max_frames": 180,
22
+ "max_position_embeddings": 40960,
23
+ "max_window_layers": 28,
24
+ "model_type": "penguinvl_qwen3",
25
+ "num_attention_heads": 16,
26
+ "num_hidden_layers": 28,
27
+ "num_key_value_heads": 8,
28
+ "rms_norm_eps": 1e-06,
29
+ "rope_scaling": null,
30
+ "rope_theta": 1000000,
31
+ "sliding_window": null,
32
+ "tie_word_embeddings": true,
33
+ "tokenizer_model_max_length": 32768,
34
+ "tokenizer_padding_side": "right",
35
+ "torch_dtype": "bfloat16",
36
+ "transformers_version": "4.51.3",
37
+ "use_cache": true,
38
+ "use_sliding_window": false,
39
+ "vision_encoder": "pg-team/pg-vision-encoder",
40
+ "vision_hidden_size": 1024,
41
+ "vision_projector_type": "mlp2x_gelu",
42
+ "vocab_size": 151936,
43
+ "vision_encoder_config": {
44
+ "head_dim": 128,
45
+ "hidden_act": "silu",
46
+ "hidden_size": 1024,
47
+ "initializer_range": 0.02,
48
+ "intermediate_size": 3072,
49
+ "layer_norm_eps": 1e-06,
50
+ "max_window_layers": 28,
51
+ "num_attention_heads": 16,
52
+ "num_channels": 3,
53
+ "num_hidden_layers": 28,
54
+ "num_key_value_heads": 8,
55
+ "patch_size": 14,
56
+ "rms_norm_eps": 1e-06,
57
+ "rope_scaling": null,
58
+ "rope_theta": 1000000,
59
+ "sliding_window": null,
60
+ "torch_dtype": "bfloat16"
61
+ }
62
+ }
configuration_penguinvl.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PenguinVL model configuration."""
2
+
3
+ import importlib.util
4
+ import os.path as osp
5
+ from typing import Optional, Dict, Any
6
+
7
+ from transformers import PretrainedConfig, Qwen3Config
8
+
9
+ try:
10
+ from .configuration_penguinvl_encoder import PenguinVLVisionEncoderConfig
11
+ except ModuleNotFoundError:
12
+ spec = importlib.util.spec_from_file_location(
13
+ "configuration_penguinvl_encoder",
14
+ osp.join(osp.dirname(__file__), "configuration_penguinvl_encoder.py"),
15
+ )
16
+ configuration_penguinvl_encoder = importlib.util.module_from_spec(spec)
17
+ spec.loader.exec_module(configuration_penguinvl_encoder)
18
+ PenguinVLVisionEncoderConfig = getattr(
19
+ configuration_penguinvl_encoder,
20
+ "PenguinVLVisionEncoderConfig",
21
+ )
22
+
23
+
24
+ class PenguinVLQwen3Config(Qwen3Config):
25
+
26
+ model_type = "penguinvl_qwen3"
27
+ sub_configs = {"vision_encoder_config": PenguinVLVisionEncoderConfig}
28
+
29
+ def __init__(
30
+ self,
31
+ vision_encoder: Optional[str] = None,
32
+ vision_encoder_config: Dict[str, Any] = {},
33
+ vision_projector_type: str = "mlp2x_gelu",
34
+ use_token_compression: bool = True,
35
+ image_token_index: int = -1,
36
+ **kwargs,
37
+ ):
38
+ super().__init__(**kwargs)
39
+ self.model_type = "penguinvl_qwen3"
40
+
41
+ self.vision_encoder = vision_encoder
42
+ if vision_encoder_config is not None and not isinstance(vision_encoder_config, PretrainedConfig):
43
+ vision_encoder_config = PenguinVLVisionEncoderConfig(**vision_encoder_config)
44
+ self.vision_encoder_config = vision_encoder_config
45
+
46
+ self.vision_projector_type = vision_projector_type
47
+ self.use_token_compression = use_token_compression
48
+ self.image_token_index = image_token_index
configuration_penguinvl_encoder.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PenguinVL vision encoder model configuration."""
2
+
3
+ from transformers import Qwen3Config
4
+
5
+
6
+ class PenguinVLVisionEncoderConfig(Qwen3Config):
7
+
8
+ model_type = "penguinvl_vision_encoder"
9
+
10
+ def __init__(
11
+ self,
12
+ hidden_size=1536,
13
+ intermediate_size=8960,
14
+ num_hidden_layers=12,
15
+ num_attention_heads=12,
16
+ num_channels=3,
17
+ patch_size=14,
18
+ layer_norm_eps=1e-6,
19
+ attention_dropout=0.0,
20
+ num_key_value_heads=2,
21
+ **kwargs,
22
+ ):
23
+ super().__init__(**kwargs)
24
+
25
+ self.hidden_size = hidden_size
26
+ self.intermediate_size = intermediate_size
27
+ self.num_hidden_layers = num_hidden_layers
28
+ self.num_attention_heads = num_attention_heads
29
+ self.num_channels = num_channels
30
+ self.patch_size = patch_size
31
+ self.attention_dropout = attention_dropout
32
+ self.num_key_value_heads = num_key_value_heads
33
+ self.layer_norm_eps = layer_norm_eps
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.3"
13
+ }
image_processing_penguinvl.py ADDED
@@ -0,0 +1,548 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adopted from https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py.
2
+ # Below is the original copyright:
3
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
6
+ # and OPT implementations in this library. It has been modified from its
7
+ # original forms to accommodate minor architectural differences compared
8
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+ """Image processor class for PenguinVL."""
22
+
23
+ import math
24
+ from typing import Dict, List, Optional, Union
25
+
26
+ import numpy as np
27
+
28
+ import torch
29
+ from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
30
+ from transformers.image_utils import ImageInput
31
+ from transformers.image_transforms import (
32
+ convert_to_rgb,
33
+ resize,
34
+ to_channel_dimension_format,
35
+ )
36
+ from transformers.image_utils import (
37
+ OPENAI_CLIP_MEAN,
38
+ OPENAI_CLIP_STD,
39
+ ChannelDimension,
40
+ ImageInput,
41
+ PILImageResampling,
42
+ get_image_size,
43
+ infer_channel_dimension_format,
44
+ is_scaled_image,
45
+ is_valid_image,
46
+ make_list_of_images,
47
+ to_numpy_array,
48
+ )
49
+ try:
50
+ from transformers.image_utils import VideoInput
51
+ except:
52
+ from transformers.video_utils import VideoInput
53
+ from transformers.utils import TensorType, is_vision_available, logging
54
+
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+
59
+ if is_vision_available():
60
+ from PIL import Image
61
+
62
+
63
+ def is_valid_video(video) -> bool:
64
+ if isinstance(video, (list, tuple)):
65
+ return all(is_valid_image(frame) for frame in video)
66
+ elif isinstance(video, np.ndarray):
67
+ return video.ndim == 4
68
+ elif isinstance(video, torch.Tensor):
69
+ return video.ndim == 4
70
+ return False
71
+
72
+
73
+ def make_batched_images(images) -> List[List[ImageInput]]:
74
+ """
75
+ Normalize visual inputs to ``List[List[ImageInput]]`` – a list of *clips*,
76
+ where each clip is a list of frames.
77
+
78
+ Supported input formats::
79
+
80
+ Nested clips : [[image], [f1, f2, ...], ...] → returned as-is
81
+ Flat frames : [f1, f2, ...] → [[f1, f2, ...]]
82
+ Single image : image → [[image]]
83
+
84
+ Returns:
85
+ List of clips, where each clip is a list of valid images / frames.
86
+ """
87
+ if isinstance(images, (list, tuple)) and len(images) > 0:
88
+ if isinstance(images[0], (list, tuple)):
89
+ return [list(clip) for clip in images]
90
+ if all(is_valid_image(f) for f in images):
91
+ return [list(images)]
92
+ if is_valid_image(images):
93
+ return [[images]]
94
+ raise ValueError(f"Could not make batched images from {images}")
95
+
96
+
97
+ def simple_batched_resize(
98
+ images,
99
+ factor: int = 28,
100
+ min_tokens: int = 4 * 4,
101
+ max_tokens: int = 16384,
102
+ input_data_format: str = None,
103
+ frame_types=None
104
+ ):
105
+ """
106
+ Compute per-frame target (h, w) for a video frame list under a token budget (key/intermediate may differ).
107
+
108
+ Uses the Temporal Redundancy-Aware (TRA) token compression strategy: key and intermediate frames
109
+ can have different target areas (e.g. 1:16 ratio when compressing) to stay within max_tokens.
110
+
111
+ Args:
112
+ images: List of video frames (each PIL Image or ndarray).
113
+ factor: Alignment granularity (height and width are multiples of factor), default 28.
114
+ min_tokens: Minimum tokens per frame (used to derive min_pixels), default 16.
115
+ max_tokens: Token cap for total pixel budget, default 16384.
116
+ input_data_format: Channel format when not PIL, e.g. "channels_first".
117
+ frame_types: Per-frame type list, 0=key, 1=intermediate; None means all key.
118
+
119
+ Returns:
120
+ image_sizes: List of (h, w) per frame, one-to-one with images.
121
+ """
122
+ min_pixels = min_tokens * factor * factor * 1.5
123
+ max_pixels = max_tokens * factor * factor * 0.95
124
+
125
+ # --- Base info ---
126
+ first_image = images[0]
127
+ if isinstance(first_image, Image.Image):
128
+ width, height = first_image.size
129
+ else:
130
+ height, width = get_image_size(first_image, channel_dim=input_data_format)
131
+
132
+ aspect_ratio = height / width
133
+ raw_area = height * width
134
+
135
+ num_frames = len(images)
136
+ if frame_types is not None:
137
+ ft_list = frame_types.tolist() if hasattr(frame_types, 'tolist') else frame_types
138
+ num_intermediate = ft_list.count(1)
139
+ num_key = ft_list.count(0)
140
+ else:
141
+ num_key = num_frames
142
+ num_intermediate = 0
143
+ ft_list = [0] * num_frames
144
+
145
+ def get_dims_from_area(target_area, ar, fac):
146
+ """Compute aligned (h, w) from target area and aspect ratio; area = w²·ar => w = sqrt(area/ar)."""
147
+ w_new = math.sqrt(target_area / ar)
148
+ h_new = w_new * ar
149
+
150
+ h_bar = round(h_new / fac) * fac
151
+ w_bar = round(w_new / fac) * fac
152
+ h_bar = max(h_bar, fac)
153
+ w_bar = max(w_bar, fac)
154
+
155
+ return h_bar, w_bar
156
+
157
+ # --- Stage 1: No-downscale check ---
158
+ # If total pixels within budget, keep original size for both key and intermediate frames.
159
+ total_raw_pixels = num_frames * raw_area
160
+ target_key_area = raw_area
161
+ target_intermediate_area = raw_area
162
+
163
+ if total_raw_pixels > max_pixels:
164
+ # --- Stage 2: Sync compression ---
165
+ # Over budget: compress with 1:16 area ratio, intermediate_area = key_area / 16.
166
+ # Constraint: N_key·A_key + N_intermediate·(A_key/16) = max_pixels => A_key = max_pixels / (N_key + N_intermediate/16).
167
+ effective_count = num_key + (num_intermediate / 16.0)
168
+ calc_key_area = max_pixels / effective_count
169
+ calc_intermediate_area = calc_key_area / 16.0
170
+
171
+ # --- Stage 3: Intermediate-frame floor ---
172
+ # If computed intermediate area is below min_pixels, pin intermediate to min_pixels and give remaining budget to key.
173
+ if calc_intermediate_area >= min_pixels:
174
+ target_key_area = calc_key_area
175
+ target_intermediate_area = calc_intermediate_area
176
+ else:
177
+ target_intermediate_area = min_pixels
178
+ pixels_taken_by_intermediate = num_intermediate * min_pixels
179
+ remaining_for_key = max_pixels - pixels_taken_by_intermediate
180
+ target_key_area = remaining_for_key / num_key
181
+
182
+ # --- Stage 4: Key-frame hard floor ---
183
+ if target_key_area < min_pixels:
184
+ target_key_area = min_pixels
185
+
186
+ # --- Area to aligned dimensions ---
187
+ k_h, k_w = get_dims_from_area(target_key_area, aspect_ratio, factor)
188
+ if num_intermediate > 0:
189
+ i_h, i_w = get_dims_from_area(target_intermediate_area, aspect_ratio, factor)
190
+ else:
191
+ i_h, i_w = 0, 0
192
+
193
+ def ensure_min_hw(h, w, min_p, raw_ar):
194
+ """If area still below min_pixels after alignment (rounding), recompute from min area and align upward."""
195
+ if h * w < min_p:
196
+ w = math.sqrt(min_p / raw_ar)
197
+ h = w * raw_ar
198
+ h = math.ceil(h / factor) * factor
199
+ w = math.ceil(w / factor) * factor
200
+ return h, w
201
+
202
+ k_h, k_w = ensure_min_hw(k_h, k_w, min_pixels, aspect_ratio)
203
+ if num_intermediate > 0:
204
+ i_h, i_w = ensure_min_hw(i_h, i_w, min_pixels, aspect_ratio)
205
+
206
+ image_sizes = [
207
+ (i_h, i_w) if ft_list[i] == 1 else (k_h, k_w)
208
+ for i in range(num_frames)
209
+ ]
210
+ return image_sizes
211
+
212
+
213
+ class PenguinVLImageProcessor(BaseImageProcessor):
214
+ r"""
215
+ Constructs a PenguinVL image processor that dynamically resizes images based on the original images.
216
+
217
+ Args:
218
+ do_resize (`bool`, *optional*, defaults to `True`):
219
+ Whether to resize the image's (height, width) dimensions.
220
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
221
+ Resampling filter to use when resizing the image.
222
+ do_rescale (`bool`, *optional*, defaults to `True`):
223
+ Whether to rescale the image by the specified scale `rescale_factor`.
224
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
225
+ Scale factor to use if rescaling the image.
226
+ do_normalize (`bool`, *optional*, defaults to `True`):
227
+ Whether to normalize the image.
228
+ image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
229
+ Mean to use if normalizing the image. This is a float or list of floats for each channel in the image.
230
+ image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
231
+ Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image.
232
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
233
+ Whether to convert the image to RGB.
234
+ min_pixels (`int`, *optional*, defaults to `56 * 56`):
235
+ The min pixels of the image to resize the image.
236
+ max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`):
237
+ The max pixels of the image to resize the image.
238
+ patch_size (`int`, *optional*, defaults to 14):
239
+ The spacial patch size of the vision encoder.
240
+ """
241
+
242
+ model_input_names = ["pixel_values", "grid_sizes", "merge_sizes"]
243
+
244
+ def __init__(
245
+ self,
246
+ do_resize: bool = True,
247
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
248
+ do_rescale: bool = True,
249
+ rescale_factor: Union[int, float] = 1 / 255,
250
+ do_normalize: bool = True,
251
+ image_mean: Optional[Union[float, List[float]]] = None,
252
+ image_std: Optional[Union[float, List[float]]] = None,
253
+ do_convert_rgb: bool = True,
254
+ min_tokens: int = 4 * 4,
255
+ max_tokens: int = 16384,
256
+ patch_size: int = 14,
257
+ **kwargs,
258
+ ) -> None:
259
+ super().__init__(**kwargs)
260
+ self.do_resize = do_resize
261
+ self.resample = resample
262
+ self.do_rescale = do_rescale
263
+ self.rescale_factor = rescale_factor
264
+ self.do_normalize = do_normalize
265
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
266
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
267
+ self.min_tokens = min_tokens
268
+ self.max_tokens = max_tokens
269
+ self.patch_size = patch_size
270
+ self.do_convert_rgb = do_convert_rgb
271
+
272
+ def _allocate_token_budget(self, clips, clip_merge_sizes, input_data_format):
273
+ """Distribute self.max_tokens across clips proportionally to their raw token counts."""
274
+ clip_raw_tokens = []
275
+ for clip, ms in zip(clips, clip_merge_sizes):
276
+ first_frame = clip[0]
277
+ if isinstance(first_frame, Image.Image):
278
+ w, h = first_frame.size
279
+ else:
280
+ h, w = get_image_size(first_frame, channel_dim=input_data_format)
281
+ factor = self.patch_size * ms
282
+ clip_raw_tokens.append(len(clip) * h * w / (factor * factor))
283
+
284
+ total_raw_tokens = sum(clip_raw_tokens)
285
+ if total_raw_tokens <= self.max_tokens:
286
+ return [self.max_tokens] * len(clips)
287
+
288
+ return [
289
+ max(self.min_tokens * len(clip), raw * self.max_tokens / total_raw_tokens)
290
+ for clip, raw in zip(clips, clip_raw_tokens)
291
+ ]
292
+
293
+ def _preprocess(
294
+ self,
295
+ images: Union[ImageInput, VideoInput],
296
+ target_size: List[int],
297
+ merge_size: int = 1,
298
+ do_resize: bool = None,
299
+ resample: PILImageResampling = None,
300
+ do_rescale: bool = None,
301
+ rescale_factor: float = None,
302
+ do_normalize: bool = None,
303
+ image_mean: Optional[Union[float, List[float]]] = None,
304
+ image_std: Optional[Union[float, List[float]]] = None,
305
+ do_convert_rgb: bool = None,
306
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
307
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
308
+ ):
309
+ """
310
+ Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.
311
+
312
+ Args:
313
+ images (`ImageInput`):
314
+ 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`.
315
+ target_size (`List[int]`):
316
+ The target size to resize the image to. Should be a list of two integers: [target_height, target_width].
317
+ merge_size (`int`, *optional*, defaults to `1`):
318
+ The merge size after the vision encoder.
319
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
320
+ Whether to resize the image.
321
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
322
+ Resampling filter to use if resizing the image. This can be one of the `PILImageResampling` enums.
323
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
324
+ Whether to rescale the image.
325
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
326
+ Scale factor to use if rescaling the image.
327
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
328
+ Whether to normalize the image.
329
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
330
+ 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.
331
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
332
+ 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.
333
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
334
+ Whether to convert the image to RGB.
335
+ data_format (`ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):
336
+ The channel dimension format for the output image. Can be one of:
337
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
338
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
339
+ - Unset: Use the channel dimension format of the input image.
340
+ input_data_format (`ChannelDimension` or `str`, *optional*):
341
+ The channel dimension format for the input image. Can be one of:
342
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
343
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
344
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
345
+ """
346
+ images = make_list_of_images(images)
347
+
348
+ if do_convert_rgb:
349
+ images = [convert_to_rgb(image) for image in images]
350
+
351
+ # All transformations expect numpy arrays.
352
+ images = [to_numpy_array(image) for image in images]
353
+
354
+ if is_scaled_image(images[0]) and do_rescale:
355
+ logger.warning_once(
356
+ "It looks like you are trying to rescale already rescaled images. If the input"
357
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
358
+ )
359
+ if input_data_format is None:
360
+ # We assume that all images have the same channel dimension format.
361
+ input_data_format = infer_channel_dimension_format(images[0])
362
+
363
+ height, width = get_image_size(images[0], channel_dim=input_data_format)
364
+ resized_height, resized_width = height, width
365
+ processed_images = []
366
+ for image in images:
367
+ if do_resize:
368
+ resized_height, resized_width = target_size
369
+ image = resize(
370
+ image, size=(resized_height, resized_width), resample=resample, input_data_format=input_data_format
371
+ )
372
+
373
+ if do_rescale:
374
+ image = self.rescale(image, scale=rescale_factor, input_data_format=input_data_format)
375
+
376
+ if do_normalize:
377
+ image = self.normalize(
378
+ image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
379
+ )
380
+
381
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
382
+ processed_images.append(image)
383
+
384
+ patches = np.array(processed_images)
385
+ if data_format == ChannelDimension.LAST:
386
+ patches = patches.transpose(0, 3, 1, 2)
387
+ t = patches.shape[0]
388
+ channel = patches.shape[1]
389
+ grid_h, grid_w = resized_height // self.patch_size, resized_width // self.patch_size
390
+ patches = patches.reshape(
391
+ t,
392
+ channel,
393
+ grid_h // merge_size,
394
+ merge_size,
395
+ self.patch_size,
396
+ grid_w // merge_size,
397
+ merge_size,
398
+ self.patch_size,
399
+ )
400
+ patches = patches.transpose(0, 2, 5, 3, 6, 1, 4, 7)
401
+ flatten_patches = patches.reshape(
402
+ t * grid_h * grid_w, channel * self.patch_size * self.patch_size
403
+ )
404
+
405
+ return flatten_patches, (t, grid_h, grid_w)
406
+
407
+ def preprocess(
408
+ self,
409
+ images: ImageInput,
410
+ do_resize: bool = None,
411
+ resample: PILImageResampling = None,
412
+ do_rescale: bool = None,
413
+ rescale_factor: float = None,
414
+ do_normalize: bool = None,
415
+ image_mean: Optional[Union[float, List[float]]] = None,
416
+ image_std: Optional[Union[float, List[float]]] = None,
417
+ do_convert_rgb: bool = None,
418
+ merge_size: Optional[Union[int, List[int]]] = None,
419
+ frame_types: Optional[Union[int, List[int]]] = None,
420
+ return_tensors: Optional[Union[str, TensorType]] = None,
421
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
422
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
423
+ ):
424
+ """
425
+ Args:
426
+ images (`ImageInput`):
427
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
428
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
429
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
430
+ Whether to resize the image.
431
+ resample (`int`, *optional*, defaults to `self.resample`):
432
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
433
+ has an effect if `do_resize` is set to `True`.
434
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
435
+ Whether to rescale the image.
436
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
437
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
438
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
439
+ Whether to normalize the image.
440
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
441
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
442
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
443
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
444
+ `True`.
445
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
446
+ Whether to convert the image to RGB.
447
+ return_tensors (`str` or `TensorType`, *optional*):
448
+ The type of tensors to return. Can be one of:
449
+ - Unset: Return a list of `np.ndarray`.
450
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
451
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
452
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
453
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
454
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
455
+ The channel dimension format for the output image. Can be one of:
456
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
457
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
458
+ - Unset: Use the channel dimension format of the input image.
459
+ input_data_format (`ChannelDimension` or `str`, *optional*):
460
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
461
+ from the input image. Can be one of:
462
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
463
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
464
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
465
+
466
+ """
467
+ do_resize = do_resize if do_resize is not None else self.do_resize
468
+ resample = resample if resample is not None else self.resample
469
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
470
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
471
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
472
+ image_mean = image_mean if image_mean is not None else self.image_mean
473
+ image_std = image_std if image_std is not None else self.image_std
474
+ merge_size = merge_size if merge_size is not None else self.merge_size
475
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
476
+
477
+ clips = make_batched_images(images)
478
+ num_clips = len(clips)
479
+
480
+ if isinstance(merge_size, (list, tuple)):
481
+ assert len(merge_size) == num_clips, (
482
+ f"merge_size length ({len(merge_size)}) must match number of clips ({num_clips})"
483
+ )
484
+ clip_merge_sizes = list(merge_size)
485
+ else:
486
+ clip_merge_sizes = [merge_size] * num_clips
487
+
488
+ if frame_types is None:
489
+ clip_frame_types = [None] * num_clips
490
+ elif isinstance(frame_types, (list, tuple)) and len(frame_types) > 0:
491
+ if isinstance(frame_types[0], (list, tuple)) or frame_types[0] is None:
492
+ assert len(frame_types) == num_clips, (
493
+ f"frame_types length ({len(frame_types)}) must match number of clips ({num_clips})"
494
+ )
495
+ clip_frame_types = list(frame_types)
496
+ else:
497
+ assert num_clips == 1, "Flat frame_types is only supported for a single clip"
498
+ clip_frame_types = [frame_types]
499
+ else:
500
+ clip_frame_types = [None] * num_clips
501
+
502
+ pixel_values, grid_sizes, per_frame_merge_sizes = [], [], []
503
+
504
+ clip_max_tokens_list = self._allocate_token_budget(
505
+ clips, clip_merge_sizes, input_data_format,
506
+ )
507
+
508
+ for clip, ms, ft, clip_max_tokens in zip(clips, clip_merge_sizes, clip_frame_types, clip_max_tokens_list):
509
+ target_sizes = simple_batched_resize(
510
+ clip,
511
+ factor=self.patch_size * ms,
512
+ min_tokens=self.min_tokens,
513
+ max_tokens=clip_max_tokens,
514
+ input_data_format=input_data_format,
515
+ frame_types=ft,
516
+ )
517
+
518
+ for frame, target_size in zip(clip, target_sizes):
519
+ patches, grid_size = self._preprocess(
520
+ frame,
521
+ target_size=target_size,
522
+ merge_size=ms,
523
+ do_resize=do_resize,
524
+ resample=resample,
525
+ do_rescale=do_rescale,
526
+ rescale_factor=rescale_factor,
527
+ do_normalize=do_normalize,
528
+ image_mean=image_mean,
529
+ image_std=image_std,
530
+ data_format=data_format,
531
+ do_convert_rgb=do_convert_rgb,
532
+ input_data_format=input_data_format,
533
+ )
534
+ pixel_values.append(patches)
535
+ grid_sizes.append(grid_size)
536
+ per_frame_merge_sizes.append(ms)
537
+
538
+ pixel_values = np.concatenate(pixel_values, axis=0)
539
+ grid_sizes = np.array(grid_sizes)
540
+ merge_sizes = np.array(per_frame_merge_sizes)
541
+
542
+ data = {
543
+ "pixel_values": pixel_values,
544
+ "grid_sizes": grid_sizes,
545
+ "merge_sizes": merge_sizes,
546
+ }
547
+
548
+ return BatchFeature(data=data, tensor_type=return_tensors)
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:b13dc884fa52b873d861b32f3bcfa406b04964ec3412e69a1e0424950d5832d3
3
+ size 4335965984
modeling_penguinvl_encoder.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import nn
2
+ import torch
3
+ import math
4
+ import warnings
5
+ from functools import partial
6
+ from .configuration_penguinvl_encoder import PenguinVLVisionEncoderConfig
7
+ from transformers.modeling_utils import PreTrainedModel
8
+ from transformers.models.qwen3.modeling_qwen3 import Qwen3Model, Qwen3Attention, rotate_half, Qwen3DecoderLayer
9
+ from typing import List, Optional, Tuple, Union
10
+ from transformers.modeling_outputs import BaseModelOutputWithPast
11
+ from transformers.processing_utils import Unpack
12
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
13
+ from transformers.cache_utils import Cache, DynamicCache
14
+ from transformers.utils import logging, is_flash_attn_greater_or_equal_2_10, is_flash_attn_2_available
15
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
16
+ from torch.nn.init import _calculate_fan_in_and_fan_out
17
+ import torch.nn.functional as F
18
+ if is_flash_attn_2_available():
19
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
20
+ from flash_attn import flash_attn_varlen_func
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ class PenguinVLVisionEncoderEmbeddings(nn.Module):
25
+
26
+ def __init__(self, config: PenguinVLVisionEncoderConfig):
27
+ super().__init__()
28
+ self.config = config
29
+ self.embed_dim = config.hidden_size
30
+ self.patch_size = config.patch_size
31
+
32
+ self.patch_embedding = nn.Conv2d(
33
+ in_channels=config.num_channels,
34
+ out_channels=self.embed_dim,
35
+ kernel_size=self.patch_size,
36
+ stride=self.patch_size,
37
+ padding="valid",
38
+ )
39
+
40
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
41
+ hidden_states = hidden_states.view(
42
+ -1, self.config.num_channels, self.patch_size, self.patch_size
43
+ )
44
+ patch_embeds = self.patch_embedding(hidden_states)
45
+ embeddings = patch_embeds.view(-1, self.embed_dim)
46
+
47
+ return embeddings
48
+
49
+
50
+ # Adapted from Qwen2VLRotaryEmbedding in transformers/models/qwen2/modeling_qwen2.py
51
+ class VisualRotaryEmbedding(nn.Module):
52
+ def __init__(
53
+ self,
54
+ dim=None,
55
+ max_position_embeddings=2048,
56
+ base=10000,
57
+ device=None,
58
+ scaling_factor=1.0,
59
+ rope_type="default",
60
+ config = None,
61
+ ):
62
+ super().__init__()
63
+ # TODO (joao): remove the `if` below, only used for BC
64
+ self.rope_kwargs = {}
65
+ if config is None:
66
+ logger.warning_once(
67
+ "`Qwen2VLRotaryEmbedding` can now be fully parameterized by passing the model config through the "
68
+ "`config` argument. All other arguments will be removed in v4.46"
69
+ )
70
+ self.rope_kwargs = {
71
+ "rope_type": rope_type,
72
+ "factor": scaling_factor,
73
+ "dim": dim,
74
+ "base": base,
75
+ "max_position_embeddings": max_position_embeddings,
76
+ }
77
+ self.rope_type = rope_type
78
+ self.max_seq_len_cached = max_position_embeddings
79
+ self.original_max_seq_len = max_position_embeddings
80
+ else:
81
+ # BC: "rope_type" was originally "type"
82
+ if config.rope_scaling is not None:
83
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
84
+ else:
85
+ self.rope_type = "default"
86
+ self.max_seq_len_cached = config.max_position_embeddings
87
+ self.original_max_seq_len = config.max_position_embeddings
88
+
89
+ self.config = config
90
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
91
+
92
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
93
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
94
+ self.original_inv_freq = self.inv_freq
95
+
96
+ def _dynamic_frequency_update(self, position_ids, device):
97
+ """
98
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
99
+ 1 - growing beyond the cached sequence length (allow scaling)
100
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
101
+ """
102
+ seq_len = torch.max(position_ids) + 1
103
+ if seq_len > self.max_seq_len_cached: # growth
104
+ inv_freq, self.attention_scaling = self.rope_init_fn(
105
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
106
+ )
107
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
108
+ self.max_seq_len_cached = seq_len
109
+
110
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
111
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
112
+ self.max_seq_len_cached = self.original_max_seq_len
113
+
114
+ @torch.no_grad()
115
+ def forward(self, x, position_ids):
116
+ if "dynamic" in self.rope_type:
117
+ self._dynamic_frequency_update(position_ids, device=x.device)
118
+
119
+ inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(2, position_ids.shape[1], -1, 1)
120
+ position_ids_expanded = position_ids[:, :, None, :].float() # shape (2, bs, 1, positions)
121
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
122
+ device_type = x.device.type
123
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
124
+ with torch.autocast(device_type=device_type, enabled=False):
125
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
126
+ emb = torch.cat((freqs, freqs), dim=-1)
127
+ cos = emb.cos()
128
+ sin = emb.sin()
129
+
130
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
131
+ cos = cos * self.attention_scaling
132
+ sin = sin * self.attention_scaling
133
+
134
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
135
+
136
+
137
+ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
138
+ rope_section = [cos.shape[-1] // 2, cos.shape[-1] // 2]
139
+ cos = torch.cat([m[i % 2] for i, m in enumerate(cos.split(rope_section, dim=-1))], dim=-1).unsqueeze(unsqueeze_dim)
140
+ sin = torch.cat([m[i % 2] for i, m in enumerate(sin.split(rope_section, dim=-1))], dim=-1).unsqueeze(unsqueeze_dim)
141
+
142
+ q_embed = (q * cos) + (rotate_half(q) * sin)
143
+ k_embed = (k * cos) + (rotate_half(k) * sin)
144
+ return q_embed, k_embed
145
+
146
+
147
+ class PenguinVLAttention(Qwen3Attention):
148
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
149
+
150
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
151
+ def __init__(self, *args, **kwargs):
152
+ super().__init__(*args, **kwargs)
153
+ self.is_causal = False
154
+
155
+ def forward(
156
+ self,
157
+ hidden_states: torch.Tensor,
158
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
159
+ attention_mask: Optional[torch.Tensor],
160
+ past_key_value: Optional[Cache] = None,
161
+ cache_position: Optional[torch.LongTensor] = None,
162
+ cu_seqlens: Optional[torch.Tensor] = None,
163
+ **kwargs: Unpack[FlashAttentionKwargs],
164
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
165
+ input_shape = hidden_states.shape[:-1]
166
+ hidden_shape = (*input_shape, -1, self.head_dim)
167
+
168
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
169
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
170
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
171
+
172
+ cos, sin = position_embeddings
173
+ query_states, key_states = apply_multimodal_rotary_pos_emb(query_states, key_states, cos, sin)
174
+
175
+ if past_key_value is not None:
176
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
177
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
178
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
179
+
180
+ # This is before the transpose
181
+ seq_len = query_states.shape[2]
182
+
183
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
184
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
185
+ # cast them back in the correct dtype just to be sure everything works as expected.
186
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
187
+ # in fp32. (usually our RMSNorm modules handle it correctly)
188
+ target_dtype = None
189
+ if query_states.dtype == torch.float32:
190
+ if torch.is_autocast_enabled():
191
+ target_dtype = torch.get_autocast_gpu_dtype()
192
+ # Handle the case where the model is quantized
193
+ elif hasattr(self.config, "_pre_quantization_dtype"):
194
+ target_dtype = self.config._pre_quantization_dtype
195
+ else:
196
+ target_dtype = next(layer for layer in self.modules() if isinstance(layer, torch.nn.Linear)).weight.dtype
197
+
198
+ # FA2 always relies on the value set in the module, so remove it if present in kwargs to avoid passing it twice
199
+ kwargs.pop("is_causal", None)
200
+
201
+ # Reashape to the expected shape for Flash Attention
202
+ query_states = query_states.transpose(1, 2).squeeze(0)
203
+ key_states = key_states.transpose(1, 2).squeeze(0)
204
+ value_states = value_states.transpose(1, 2).squeeze(0)
205
+
206
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item()
207
+ attn_output = flash_attn_varlen_func(
208
+ query_states,
209
+ key_states,
210
+ value_states,
211
+ cu_seqlens_q=cu_seqlens,
212
+ cu_seqlens_k=cu_seqlens,
213
+ max_seqlen_q=max_seqlen,
214
+ max_seqlen_k=max_seqlen,
215
+ dropout_p=0.0 if not self.training else self.attention_dropout,
216
+ causal=self.is_causal
217
+ )
218
+
219
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
220
+ attn_output = self.o_proj(attn_output)
221
+ return attn_output, None
222
+
223
+
224
+ class PenguinVLDecoderLayer(Qwen3DecoderLayer):
225
+ def __init__(self, config: PenguinVLVisionEncoderConfig, layer_idx: int):
226
+ super(PenguinVLDecoderLayer, self).__init__(config, layer_idx)
227
+ self.self_attn = PenguinVLAttention(config, layer_idx)
228
+
229
+ def forward(
230
+ self,
231
+ hidden_states: torch.Tensor,
232
+ attention_mask: Optional[torch.Tensor] = None,
233
+ position_ids: Optional[torch.LongTensor] = None,
234
+ past_key_value: Optional[Cache] = None,
235
+ output_attentions: Optional[bool] = False,
236
+ use_cache: Optional[bool] = False,
237
+ cache_position: Optional[torch.LongTensor] = None,
238
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
239
+ cu_seqlens: Optional[torch.Tensor] = None,
240
+ **kwargs: Unpack[FlashAttentionKwargs],
241
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
242
+ residual = hidden_states
243
+
244
+ hidden_states = self.input_layernorm(hidden_states)
245
+
246
+ # Self Attention
247
+ hidden_states, self_attn_weights = self.self_attn(
248
+ hidden_states=hidden_states,
249
+ attention_mask=attention_mask,
250
+ position_ids=position_ids,
251
+ past_key_value=past_key_value,
252
+ output_attentions=output_attentions,
253
+ use_cache=use_cache,
254
+ cache_position=cache_position,
255
+ position_embeddings=position_embeddings,
256
+ cu_seqlens=cu_seqlens,
257
+ **kwargs,
258
+ )
259
+ hidden_states = residual + hidden_states
260
+
261
+ # Fully Connected
262
+ residual = hidden_states
263
+ hidden_states = self.post_attention_layernorm(hidden_states)
264
+ hidden_states = self.mlp(hidden_states)
265
+ hidden_states = residual + hidden_states
266
+
267
+ outputs = (hidden_states,)
268
+ if output_attentions:
269
+ outputs += (self_attn_weights,)
270
+
271
+ return outputs
272
+
273
+
274
+ class PenguinVLVisionEncoderFromQwen3Model(Qwen3Model):
275
+ config_class = PenguinVLVisionEncoderConfig
276
+ def __init__(self, config: PenguinVLVisionEncoderConfig):
277
+ super().__init__(config)
278
+ self.layers = nn.ModuleList(
279
+ [PenguinVLDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
280
+ )
281
+ self.rotary_emb = VisualRotaryEmbedding(config=config)
282
+ del self.embed_tokens
283
+
284
+ @staticmethod
285
+ def _prepare_4d_causal_attention_mask_with_cache_position(
286
+ attention_mask: torch.Tensor,
287
+ sequence_length: int,
288
+ target_length: int,
289
+ dtype: torch.dtype,
290
+ device: torch.device,
291
+ cache_position: torch.Tensor,
292
+ batch_size: int,
293
+ config: PenguinVLVisionEncoderConfig,
294
+ past_key_values: Cache,
295
+ ):
296
+ """
297
+ Override the original causal mask method to create full attention mask instead.
298
+ Creates a full attention 4D mask of shape `(batch_size, 1, query_length, key_value_length)`
299
+ from a 2D mask of shape `(batch_size, key_value_length)`.
300
+
301
+ For vision encoding, we want full attention between all patches, not causal attention.
302
+ """
303
+ if attention_mask is not None and attention_mask.dim() == 4:
304
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
305
+ full_attention_mask = attention_mask
306
+ else:
307
+ # Create full attention mask (all zeros, meaning attend to all positions)
308
+ # We only mask based on the provided attention_mask for padding
309
+ if attention_mask is not None:
310
+ # Use the provided attention_mask to handle padding
311
+ min_dtype = torch.finfo(dtype).min
312
+ full_attention_mask = torch.zeros(
313
+ (sequence_length, target_length), dtype=dtype, device=device
314
+ )
315
+ # Expand to 4D
316
+ full_attention_mask = full_attention_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
317
+
318
+ # Apply padding mask if provided
319
+ full_attention_mask = full_attention_mask.clone() # copy to contiguous memory for in-place edit
320
+ if attention_mask.shape[-1] > target_length:
321
+ attention_mask = attention_mask[:, :target_length]
322
+ mask_length = attention_mask.shape[-1]
323
+ padding_mask = attention_mask[:, None, None, :] == 0
324
+ full_attention_mask[:, :, :, :mask_length] = full_attention_mask[:, :, :, :mask_length].masked_fill(
325
+ padding_mask, min_dtype
326
+ )
327
+ else:
328
+ # No attention mask provided, create all-zeros mask (full attention)
329
+ full_attention_mask = torch.zeros(
330
+ (batch_size, 1, sequence_length, target_length), dtype=dtype, device=device
331
+ )
332
+ return full_attention_mask
333
+
334
+ def get_rope_index(self, grid_sizes, merge_sizes, position_ids):
335
+ position_ids = position_ids.contiguous()
336
+ batch_size = grid_sizes.shape[0]
337
+
338
+ # Vision Part: Generate 2D position indices for vision tokens
339
+ vision_pos_ids = []
340
+ for (t, h, w), merge_size in zip(grid_sizes, merge_sizes):
341
+ # Generate height position indices
342
+ hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w).to(position_ids.device)
343
+ hpos_ids = hpos_ids.reshape(
344
+ h // merge_size,
345
+ merge_size,
346
+ w // merge_size,
347
+ merge_size,
348
+ )
349
+ hpos_ids = hpos_ids.permute(0, 2, 1, 3)
350
+ hpos_ids = hpos_ids.flatten()
351
+
352
+ # Generate width position indices
353
+ wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1).to(position_ids.device)
354
+ wpos_ids = wpos_ids.reshape(
355
+ h // merge_size,
356
+ merge_size,
357
+ w // merge_size,
358
+ merge_size,
359
+ )
360
+ wpos_ids = wpos_ids.permute(0, 2, 1, 3)
361
+ wpos_ids = wpos_ids.flatten()
362
+
363
+ # Stack height and width to create 2D positions
364
+ vision_pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
365
+
366
+ num_start_idx = 0
367
+ for batch_idx in range(batch_size):
368
+ pos_len = vision_pos_ids[batch_idx].shape[0]
369
+ position_ids[:, 0, num_start_idx: num_start_idx+pos_len] = vision_pos_ids[batch_idx].permute(1, 0)
370
+ num_start_idx += pos_len
371
+
372
+ return position_ids
373
+
374
+
375
+ def forward(
376
+ self,
377
+ input_ids: Optional[torch.LongTensor] = None,
378
+ attention_mask: Optional[torch.Tensor] = None,
379
+ position_ids: Optional[torch.LongTensor] = None,
380
+ past_key_values: Optional[Cache] = None,
381
+ inputs_embeds: Optional[torch.FloatTensor] = None,
382
+ use_cache: Optional[bool] = None,
383
+ output_attentions: Optional[bool] = None,
384
+ output_hidden_states: Optional[bool] = None,
385
+ cache_position: Optional[torch.LongTensor] = None,
386
+ grid_sizes: Optional[torch.Tensor] = None,
387
+ merge_sizes: Optional[torch.Tensor] = None,
388
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
389
+ ) -> BaseModelOutputWithPast:
390
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
391
+ output_hidden_states = (
392
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
393
+ )
394
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
395
+
396
+ if (input_ids is None) ^ (inputs_embeds is not None):
397
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
398
+
399
+ if self.gradient_checkpointing and self.training and use_cache:
400
+ logger.warning_once(
401
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
402
+ )
403
+ use_cache = False
404
+
405
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
406
+ if not isinstance(past_key_values, (type(None), Cache)):
407
+ raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
408
+
409
+ if inputs_embeds is None:
410
+ inputs_embeds = self.embed_tokens(input_ids)
411
+
412
+ if use_cache and past_key_values is None:
413
+ past_key_values = DynamicCache()
414
+
415
+ if cache_position is None:
416
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
417
+ cache_position = torch.arange(
418
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
419
+ )
420
+
421
+ # the hard coded `2` is for temporal, height and width.
422
+ if position_ids is None:
423
+ position_ids = cache_position.view(1, 1, -1).expand(2, inputs_embeds.shape[0], -1)
424
+ elif position_ids.dim() == 2:
425
+ position_ids = position_ids[None, ...].expand(2, position_ids.shape[0], -1)
426
+ position_ids = self.get_rope_index(grid_sizes, merge_sizes, position_ids)
427
+
428
+ causal_mask = None
429
+
430
+ hidden_states = inputs_embeds
431
+
432
+ # create position embeddings to be shared across the decoder layers
433
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
434
+
435
+ # decoder layers
436
+ all_hidden_states = () if output_hidden_states else None
437
+ all_self_attns = () if output_attentions else None
438
+
439
+ # Calculate cumulative sequence lengths for the grid sizes
440
+ cu_seqlens = torch.repeat_interleave(grid_sizes[:, 1] * grid_sizes[:, 2], grid_sizes[:, 0]).cumsum(dim=0, dtype=torch.int32)
441
+ cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
442
+
443
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
444
+ if output_hidden_states:
445
+ all_hidden_states += (hidden_states,)
446
+
447
+ if self.gradient_checkpointing and self.training:
448
+ layer_outputs = self._gradient_checkpointing_func(
449
+ partial(decoder_layer.__call__, **flash_attn_kwargs),
450
+ hidden_states,
451
+ causal_mask,
452
+ position_ids,
453
+ past_key_values,
454
+ output_attentions,
455
+ use_cache,
456
+ cache_position,
457
+ position_embeddings,
458
+ cu_seqlens,
459
+ )
460
+ else:
461
+ layer_outputs = decoder_layer(
462
+ hidden_states,
463
+ attention_mask=causal_mask,
464
+ position_ids=position_ids,
465
+ past_key_value=past_key_values,
466
+ output_attentions=output_attentions,
467
+ use_cache=use_cache,
468
+ cache_position=cache_position,
469
+ position_embeddings=position_embeddings,
470
+ cu_seqlens=cu_seqlens,
471
+ **flash_attn_kwargs,
472
+ )
473
+
474
+ hidden_states = layer_outputs[0]
475
+
476
+ if output_attentions:
477
+ all_self_attns += (layer_outputs[1],)
478
+
479
+ hidden_states = self.norm(hidden_states)
480
+
481
+ # add hidden states from the last decoder layer
482
+ if output_hidden_states:
483
+ all_hidden_states += (hidden_states,)
484
+
485
+ return BaseModelOutputWithPast(
486
+ last_hidden_state=hidden_states,
487
+ past_key_values=past_key_values if use_cache else None,
488
+ hidden_states=all_hidden_states,
489
+ attentions=all_self_attns,
490
+ )
491
+
492
+
493
+ class PenguinVLVisionEncoderModel(PreTrainedModel):
494
+
495
+ config_class = PenguinVLVisionEncoderConfig
496
+ base_model_prefix = "penguinvl_vision_encoder"
497
+ main_input_name = "pixel_values"
498
+ supports_gradient_checkpointing = True
499
+ _no_split_modules = [
500
+ "PenguinVLVisionEncoderEmbeddings",
501
+ ]
502
+ _supports_flash_attn_2 = True
503
+ _supports_sdpa = True
504
+
505
+ def __init__(self, config: PenguinVLVisionEncoderConfig):
506
+ super().__init__(config=config)
507
+ self.embeddings = PenguinVLVisionEncoderEmbeddings(config)
508
+ self.encoder = PenguinVLVisionEncoderFromQwen3Model(config)
509
+
510
+ self.post_init()
511
+
512
+
513
+ def forward(self, pixel_values, grid_sizes, merge_sizes=None) -> torch.Tensor:
514
+ hidden_states = self.embeddings(pixel_values)
515
+ encoder_output = self.encoder(
516
+ inputs_embeds=hidden_states[None, ...],
517
+ grid_sizes=grid_sizes,
518
+ merge_sizes=merge_sizes,
519
+ output_hidden_states=True,
520
+ )
521
+ hidden_states = encoder_output.hidden_states
522
+ hidden_states = hidden_states[-1].squeeze(0)
523
+
524
+ hidden_states_chunks = hidden_states.split(grid_sizes.prod(dim=1).tolist(), dim=0)
525
+ outputs = []
526
+
527
+ for hidden_states, grid_size, merge_size in zip(hidden_states_chunks, grid_sizes, merge_sizes):
528
+ # NOTE: previous implementation, which supports downsampling with any factor
529
+ c = hidden_states.shape[-1]
530
+ hidden_states = hidden_states.view(
531
+ grid_size[0], grid_size[1] // merge_size, grid_size[2] // merge_size, merge_size, merge_size, c
532
+ ).permute(0, 1, 3, 2, 4, 5)
533
+ hidden_states = hidden_states.reshape(
534
+ grid_size[0], grid_size[1], grid_size[2], c
535
+ ).permute(0, 3, 1, 2)
536
+ hidden_states = torch.nn.functional.interpolate(
537
+ hidden_states,
538
+ size=(grid_size[1] // merge_size, grid_size[2] // merge_size),
539
+ mode='bilinear'
540
+ )
541
+ hidden_states = hidden_states.permute(0, 2, 3, 1).view(-1, c)
542
+
543
+ # NOTE: simplified implementation, which only supports downsampling with integer factor
544
+ # NOTE: this implementation is mathematically equivalent to the previous one when merge_size is 1 or 2 but may cause slightly different results
545
+ # hidden_states = hidden_states.view(-1, merge_size * merge_size, hidden_states.size(-1))
546
+ # hidden_states = hidden_states.mean(dim=1)
547
+
548
+ outputs.append(hidden_states)
549
+ return torch.cat(outputs, dim=0)
modeling_penguinvl_qwen3.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adopted from https://github.com/haotian-liu/LLaVA.
2
+ # Below is the original copyright:
3
+ # Copyright 2023 Haotian Liu
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch PenguinVL model."""
17
+
18
+ import importlib.util
19
+ import os.path as osp
20
+ import re
21
+ from abc import ABC, abstractmethod
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.utils.checkpoint
27
+ import math
28
+
29
+ from transformers import Qwen3ForCausalLM, Qwen3Model
30
+ from transformers.generation.utils import GenerateOutput
31
+ from transformers.modeling_outputs import CausalLMOutputWithPast
32
+
33
+ try:
34
+ from .configuration_penguinvl import PenguinVLQwen3Config
35
+ except ModuleNotFoundError:
36
+ spec = importlib.util.spec_from_file_location(
37
+ "configuration_penguinvl",
38
+ osp.join(osp.dirname(__file__), "configuration_penguinvl.py"),
39
+ )
40
+ configuration_penguinvl = importlib.util.module_from_spec(spec)
41
+ spec.loader.exec_module(configuration_penguinvl)
42
+ PenguinVLQwen3Config = getattr(
43
+ configuration_penguinvl,
44
+ "PenguinVLQwen3Config",
45
+ )
46
+
47
+ try:
48
+ from .configuration_penguinvl_encoder import PenguinVLVisionEncoderConfig
49
+ from .modeling_penguinvl_encoder import PenguinVLVisionEncoderModel
50
+ except ModuleNotFoundError:
51
+ enc_spec = importlib.util.spec_from_file_location(
52
+ "configuration_penguinvl_encoder",
53
+ osp.join(osp.dirname(__file__), "configuration_penguinvl_encoder.py"),
54
+ )
55
+ configuration_penguinvl_encoder = importlib.util.module_from_spec(enc_spec)
56
+ enc_spec.loader.exec_module(configuration_penguinvl_encoder)
57
+ PenguinVLVisionEncoderConfig = getattr(
58
+ configuration_penguinvl_encoder,
59
+ "PenguinVLVisionEncoderConfig",
60
+ )
61
+ enc_model_spec = importlib.util.spec_from_file_location(
62
+ "modeling_penguinvl_encoder",
63
+ osp.join(osp.dirname(__file__), "modeling_penguinvl_encoder.py"),
64
+ )
65
+ modeling_penguinvl_encoder = importlib.util.module_from_spec(enc_model_spec)
66
+ enc_model_spec.loader.exec_module(modeling_penguinvl_encoder)
67
+ PenguinVLVisionEncoderModel = getattr(
68
+ modeling_penguinvl_encoder,
69
+ "PenguinVLVisionEncoderModel",
70
+ )
71
+
72
+
73
+ def build_mlp(depth, hidden_size, output_hidden_size):
74
+ modules = [nn.Linear(hidden_size, output_hidden_size)]
75
+ for _ in range(1, depth):
76
+ modules.append(nn.GELU())
77
+ modules.append(nn.Linear(output_hidden_size, output_hidden_size))
78
+ return nn.Sequential(*modules)
79
+
80
+
81
+ def build_vision_projector(config, **kwargs):
82
+ projector_type = getattr(config, 'vision_projector_type', 'linear')
83
+ if projector_type == "linear":
84
+ return nn.Linear(config.mm_hidden_size, config.hidden_size)
85
+ elif projector_type.startswith("mlp"):
86
+ return MlpGeluProjector(config.vision_encoder_config.hidden_size, config.hidden_size, projector_type)
87
+ else:
88
+ raise ValueError(f'Unknown projector type: {projector_type}')
89
+
90
+
91
+ class MlpGeluProjector(nn.Module):
92
+
93
+ def __init__(self, mm_hidden_size, hidden_size, projector_type):
94
+ super().__init__()
95
+
96
+ mlp_gelu_match = re.match(r"^mlp(\d+)x_gelu$", projector_type)
97
+ mlp_depth = int(mlp_gelu_match.group(1))
98
+
99
+ self.readout = build_mlp(mlp_depth, mm_hidden_size, hidden_size)
100
+
101
+ def forward(self, x):
102
+ x = self.readout(x)
103
+ return x
104
+
105
+
106
+ class MlpGeluDownsampleProjector(nn.Module):
107
+ def __init__(self, mm_hidden_size, hidden_size, projector_type):
108
+ super().__init__()
109
+ self.downsample = nn.Linear(mm_hidden_size*8, mm_hidden_size)
110
+
111
+ mlp_gelu_match = re.match(r"^dmlp(\d+)x_gelu$", projector_type)
112
+ mlp_depth = int(mlp_gelu_match.group(1))
113
+
114
+ self.readout = build_mlp(mlp_depth, mm_hidden_size, hidden_size)
115
+
116
+ def forward(self, x):
117
+ B, S, D = x.shape
118
+
119
+ group = 8
120
+ S8 = (S // group) * group
121
+ x = x[:, :S8, :]
122
+ x = x.reshape(B, S8 // group, group * D)
123
+ x = self.downsample(x)
124
+ x = self.readout(x)
125
+ return x
126
+
127
+
128
+ class VLMMetaModel:
129
+
130
+ def __init__(self, config):
131
+ super(VLMMetaModel, self).__init__(config)
132
+ if config.vision_encoder is not None:
133
+ # Load with custom config/model so transformers doesn't need to know "penguinvl_vision_encoder"
134
+ encoder_config = PenguinVLVisionEncoderConfig.from_pretrained(config.vision_encoder)
135
+ self.vision_encoder = PenguinVLVisionEncoderModel.from_pretrained(
136
+ config.vision_encoder,
137
+ config=encoder_config,
138
+ attn_implementation=self.config._attn_implementation,
139
+ torch_dtype=self.dtype,
140
+ )
141
+ self.config.vision_encoder_config = self.vision_encoder.config
142
+ self.config.vision_encoder = None
143
+ elif config.vision_encoder_config is not None:
144
+ self.vision_encoder = PenguinVLVisionEncoderModel.from_config(
145
+ self.config.vision_encoder_config,
146
+ attn_implementation=self.config._attn_implementation,
147
+ torch_dtype=self.dtype,
148
+ )
149
+ else:
150
+ raise ValueError("Vision encoder is not provided in config")
151
+
152
+ self.vision_projector = build_vision_projector(config)
153
+
154
+ def get_vision_encoder(self):
155
+ return self.vision_encoder
156
+
157
+ def get_vision_projector(self):
158
+ return self.vision_projector
159
+
160
+
161
+ class PenguinVLQwen3Model(VLMMetaModel, Qwen3Model):
162
+
163
+ config_class = PenguinVLQwen3Config
164
+
165
+ def __init__(self, config: PenguinVLQwen3Config):
166
+ super(PenguinVLQwen3Model, self).__init__(config)
167
+
168
+
169
+ class VLMMetaForCausalLM(ABC):
170
+
171
+ @abstractmethod
172
+ def get_model(self):
173
+ pass
174
+
175
+ def get_vision_encoder(self):
176
+ return self.get_model().get_vision_encoder()
177
+
178
+ def get_vision_projector(self):
179
+ return self.get_model().get_vision_projector()
180
+
181
+ def encode_images(
182
+ self,
183
+ pixel_values: torch.FloatTensor,
184
+ grid_sizes: torch.LongTensor,
185
+ merge_sizes: torch.LongTensor,
186
+ ) -> torch.FloatTensor:
187
+ mm_features = self.get_model().get_vision_encoder()(
188
+ pixel_values=pixel_values,
189
+ grid_sizes=grid_sizes,
190
+ merge_sizes=merge_sizes,
191
+ )
192
+ mm_features = self.get_model().vision_projector(mm_features)
193
+ return mm_features
194
+
195
+ def _get_valid_visual_tokens(
196
+ self,
197
+ mm_features: torch.FloatTensor,
198
+ batched_num_patches: torch.LongTensor,
199
+ modals: List[str],
200
+ ):
201
+ valid_masks = []
202
+ for num_patches, modal in zip(batched_num_patches, modals):
203
+ valid_mask = torch.full((num_patches, ), modal != "text", dtype=torch.bool, device=mm_features.device)
204
+ valid_masks.append(valid_mask)
205
+ mm_features = mm_features[torch.cat(valid_masks)]
206
+ return mm_features
207
+
208
+ def prepare_inputs_labels_for_multimodal(
209
+ self,
210
+ input_ids: torch.LongTensor = None,
211
+ attention_mask: Optional[torch.Tensor] = None,
212
+ position_ids: Optional[torch.LongTensor] = None,
213
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
214
+ labels: Optional[torch.LongTensor] = None,
215
+ pixel_values: Optional[torch.FloatTensor] = None,
216
+ grid_sizes: Optional[torch.LongTensor] = None,
217
+ merge_sizes: Optional[torch.LongTensor] = None,
218
+ modals: Optional[List[str]] = None,
219
+ ):
220
+ vision_encoder = self.get_vision_encoder()
221
+ # NOTE: text-only situation
222
+ if vision_encoder is None or pixel_values is None or input_ids.shape[1] == 1:
223
+ return input_ids, attention_mask, position_ids, past_key_values, None, labels
224
+
225
+ # 1. flatten text inputs
226
+ B, N = input_ids.shape
227
+ input_ids = input_ids.view(B * N)
228
+ if attention_mask is not None:
229
+ attention_mask = attention_mask.view(B * N)
230
+ if position_ids is not None:
231
+ position_ids = position_ids.view(B * N)
232
+ if labels is not None:
233
+ labels = labels.view(B * N)
234
+
235
+ # 2. embed visual tokens
236
+ image_selected, mm_features_teacher = None, None
237
+ if pixel_values is not None:
238
+ # 2.1 encode images
239
+ batched_num_patches = grid_sizes.prod(dim=1).div(merge_sizes ** 2).long()
240
+ mm_features = self.encode_images(pixel_values, grid_sizes, merge_sizes)
241
+ mm_features = mm_features.to(input_ids.device)
242
+ mm_features = self._get_valid_visual_tokens(mm_features, batched_num_patches, modals)
243
+
244
+ # 2.2 get image selected
245
+ image_selected = (input_ids == self.config.image_token_index)
246
+ input_ids[image_selected] = 0
247
+
248
+ num_vision_tokens = image_selected.sum()
249
+ if mm_features.size(0) != num_vision_tokens:
250
+ print(f"Number of vision_features ({mm_features.size(0)}) does not match the number of image tokens ({num_vision_tokens}). Please check the inputs.")
251
+ mm_features = mm_features[:num_vision_tokens]
252
+
253
+ # 3. replace multimodal tokens with features
254
+ inputs_embeds = self.get_model().embed_tokens(input_ids).clone()
255
+ if image_selected is not None:
256
+ inputs_embeds[image_selected] = inputs_embeds[image_selected] * 0.0 + mm_features
257
+
258
+ # 4. reshape back to batched format
259
+ C = inputs_embeds.shape[-1]
260
+ inputs_embeds = inputs_embeds.reshape(B, -1, C)
261
+ if attention_mask is not None:
262
+ attention_mask = attention_mask.view(B, -1)
263
+ if labels is not None:
264
+ labels = labels.view(B, -1)
265
+ if position_ids is not None:
266
+ position_ids = position_ids.view(B, -1)
267
+
268
+ return None, attention_mask, position_ids, past_key_values, inputs_embeds, labels
269
+
270
+
271
+ class PenguinVLQwen3ForCausalLM(Qwen3ForCausalLM, VLMMetaForCausalLM):
272
+
273
+ config_class = PenguinVLQwen3Config
274
+
275
+ def __init__(self, config, **kwargs):
276
+ super(Qwen3ForCausalLM, self).__init__(config)
277
+ self.model = PenguinVLQwen3Model(config)
278
+ self.vocab_size = config.vocab_size
279
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
280
+
281
+ # Initialize weights and apply final processing
282
+ self.post_init()
283
+
284
+ def get_model(self):
285
+ return self.model
286
+
287
+ @classmethod
288
+ def _load_pretrained_model(
289
+ cls,
290
+ model,
291
+ state_dict,
292
+ checkpoint_files,
293
+ pretrained_model_name_or_path,
294
+ ignore_mismatched_sizes=False,
295
+ sharded_metadata=None,
296
+ device_map=None,
297
+ disk_offload_folder=None,
298
+ offload_state_dict=None,
299
+ dtype=None,
300
+ hf_quantizer=None,
301
+ keep_in_fp32_regex=None,
302
+ device_mesh=None,
303
+ key_mapping=None,
304
+ weights_only=True,
305
+ ):
306
+ """
307
+ Override to handle nested vision_encoder keys before calling parent's load method.
308
+ Remaps keys from 'model.vision_encoder.vision_encoder.*' to 'model.vision_encoder.*'
309
+ """
310
+ # If state_dict is provided and needs remapping, do it here
311
+ if state_dict is not None:
312
+ needs_remapping = any(k.startswith('model.vision_encoder.vision_encoder.') for k in state_dict.keys())
313
+ if needs_remapping:
314
+ print("Detected nested encoder keys, remapping 'model.vision_encoder.vision_encoder.*' -> 'model.vision_encoder.*'")
315
+ new_state_dict = {}
316
+ for k, v in state_dict.items():
317
+ if k.startswith('model.vision_encoder.vision_encoder.'):
318
+ # Remap: model.vision_encoder.vision_encoder.xxx -> model.vision_encoder.xxx
319
+ new_key = k.replace('model.vision_encoder.vision_encoder.', 'model.vision_encoder.')
320
+ new_state_dict[new_key] = v
321
+ else:
322
+ new_state_dict[k] = v
323
+ state_dict = new_state_dict
324
+
325
+ # For checkpoint files, we need to add key_mapping to remap the keys during loading
326
+ if checkpoint_files is not None and key_mapping is None:
327
+ # Check if we need remapping by loading the first checkpoint
328
+ from transformers.modeling_utils import load_state_dict
329
+ checkpoint = {}
330
+ checkpoint_files_list = checkpoint_files if isinstance(checkpoint_files, list) else [checkpoint_files]
331
+ for ckpt_file in checkpoint_files_list:
332
+ ckpt = load_state_dict(ckpt_file, map_location="cpu", weights_only=weights_only)
333
+ checkpoint.update(ckpt)
334
+ needs_remapping = any(k.startswith('model.vision_encoder.vision_encoder.') for k in checkpoint.keys())
335
+
336
+ if needs_remapping:
337
+ print("Detected nested encoder keys in checkpoint, adding key mapping for vision_encoder")
338
+ key_mapping = {}
339
+ for k in checkpoint.keys():
340
+ if k.startswith('model.vision_encoder.vision_encoder.'):
341
+ new_key = k.replace('model.vision_encoder.vision_encoder.', 'model.vision_encoder.')
342
+ key_mapping[k] = new_key
343
+ del checkpoint
344
+
345
+ return super()._load_pretrained_model(
346
+ model=model,
347
+ state_dict=state_dict,
348
+ checkpoint_files=checkpoint_files,
349
+ pretrained_model_name_or_path=pretrained_model_name_or_path,
350
+ ignore_mismatched_sizes=ignore_mismatched_sizes,
351
+ sharded_metadata=sharded_metadata,
352
+ device_map=device_map,
353
+ disk_offload_folder=disk_offload_folder,
354
+ offload_state_dict=offload_state_dict,
355
+ dtype=dtype,
356
+ hf_quantizer=hf_quantizer,
357
+ keep_in_fp32_regex=keep_in_fp32_regex,
358
+ device_mesh=device_mesh,
359
+ key_mapping=key_mapping,
360
+ weights_only=weights_only,
361
+ )
362
+
363
+ # NOTE: arguments are copied from transformers==4.51.3
364
+ def forward(
365
+ self,
366
+ input_ids: torch.LongTensor = None,
367
+ attention_mask: Optional[torch.Tensor] = None,
368
+ position_ids: Optional[torch.LongTensor] = None,
369
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
370
+ inputs_embeds: Optional[torch.FloatTensor] = None,
371
+ labels: Optional[torch.LongTensor] = None,
372
+ use_cache: Optional[bool] = None,
373
+ output_attentions: Optional[bool] = None,
374
+ output_hidden_states: Optional[bool] = None,
375
+ return_dict: Optional[bool] = None,
376
+ cache_position: Optional[torch.LongTensor] = None,
377
+ num_logits_to_keep: int = 0,
378
+ # multimodal inputs
379
+ pixel_values: Optional[torch.FloatTensor] = None,
380
+ grid_sizes: Optional[torch.LongTensor] = None,
381
+ merge_sizes: Optional[torch.LongTensor] = None,
382
+ modals: Optional[List[str]] = None,
383
+ **loss_kwargs,
384
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
385
+ if inputs_embeds is None:
386
+ (
387
+ input_ids,
388
+ attention_mask,
389
+ position_ids,
390
+ past_key_values,
391
+ inputs_embeds,
392
+ labels,
393
+ ) = self.prepare_inputs_labels_for_multimodal(
394
+ input_ids=input_ids,
395
+ attention_mask=attention_mask,
396
+ position_ids=position_ids,
397
+ past_key_values=past_key_values,
398
+ labels=labels,
399
+ pixel_values=pixel_values,
400
+ grid_sizes=grid_sizes,
401
+ merge_sizes=merge_sizes,
402
+ modals=modals,
403
+ )
404
+
405
+ return super().forward(
406
+ input_ids=input_ids,
407
+ attention_mask=attention_mask,
408
+ position_ids=position_ids,
409
+ past_key_values=past_key_values,
410
+ inputs_embeds=inputs_embeds,
411
+ labels=labels,
412
+ use_cache=use_cache,
413
+ output_attentions=output_attentions,
414
+ output_hidden_states=output_hidden_states,
415
+ return_dict=return_dict,
416
+ cache_position=cache_position,
417
+ num_logits_to_keep=num_logits_to_keep,
418
+ **loss_kwargs,
419
+ )
420
+
421
+ @torch.no_grad()
422
+ def generate(
423
+ self,
424
+ # multimodal inputs
425
+ pixel_values: Optional[torch.FloatTensor] = None,
426
+ grid_sizes: Optional[torch.LongTensor] = None,
427
+ merge_sizes: Optional[torch.LongTensor] = None,
428
+ modals: Optional[List[str]] = None,
429
+ **kwargs,
430
+ ) -> Union[GenerateOutput, torch.LongTensor]:
431
+ input_ids = kwargs.pop("input_ids", None)
432
+ attention_mask = kwargs.pop("attention_mask", None)
433
+ position_ids = kwargs.pop("position_ids", None)
434
+ past_key_values = kwargs.pop("past_key_values", None)
435
+
436
+ if "inputs_embeds" in kwargs:
437
+ raise NotImplementedError("`inputs_embeds` is not supported")
438
+
439
+ if pixel_values is not None:
440
+ (
441
+ input_ids,
442
+ attention_mask,
443
+ position_ids,
444
+ past_key_values,
445
+ inputs_embeds,
446
+ labels,
447
+ ) = self.prepare_inputs_labels_for_multimodal(
448
+ input_ids=input_ids,
449
+ attention_mask=attention_mask,
450
+ position_ids=position_ids,
451
+ past_key_values=past_key_values,
452
+ labels=None,
453
+ pixel_values=pixel_values,
454
+ grid_sizes=grid_sizes,
455
+ merge_sizes=merge_sizes,
456
+ modals=modals,
457
+ )
458
+ else:
459
+ inputs_embeds = self.get_model().embed_tokens(input_ids)
460
+
461
+ return super().generate(
462
+ position_ids=position_ids,
463
+ attention_mask=attention_mask,
464
+ inputs_embeds=inputs_embeds,
465
+ **kwargs
466
+ )
467
+
468
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
469
+ images = kwargs.pop("images", None)
470
+ _inputs = super().prepare_inputs_for_generation(
471
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
472
+ )
473
+ if images is not None:
474
+ _inputs['images'] = images
475
+ return _inputs
preprocessor_config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoImageProcessor": "image_processing_penguinvl.PenguinVLImageProcessor",
4
+ "AutoProcessor": "processing_penguinvl.PenguinVLQwen3Processor"
5
+ },
6
+ "do_convert_rgb": true,
7
+ "do_normalize": true,
8
+ "do_rescale": true,
9
+ "do_resize": true,
10
+ "image_mean": [
11
+ 0.5,
12
+ 0.5,
13
+ 0.5
14
+ ],
15
+ "image_processor_type": "PenguinVLImageProcessor",
16
+ "image_std": [
17
+ 0.5,
18
+ 0.5,
19
+ 0.5
20
+ ],
21
+ "max_tokens": 16384,
22
+ "min_tokens": 16,
23
+ "patch_size": 14,
24
+ "processor_class": "PenguinVLQwen3Processor",
25
+ "resample": 3,
26
+ "rescale_factor": 0.00392156862745098
27
+ }
processing_penguinvl.py ADDED
@@ -0,0 +1,1520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Processor class for PenguinVL."""
2
+
3
+ import copy
4
+ import importlib.util
5
+ import os
6
+ import os.path as osp
7
+ import warnings
8
+ from collections import defaultdict
9
+ from typing import Any, List, Union, Dict, Optional, Tuple, TypedDict
10
+
11
+ import cv2
12
+ import ffmpeg
13
+ import imageio
14
+ import json
15
+ import math
16
+ import numpy as np
17
+ import torch
18
+ import transformers
19
+ from decord import VideoReader, cpu
20
+ from einops import rearrange
21
+ from torch import nn
22
+ from PIL import Image
23
+ from transformers.feature_extraction_utils import BatchFeature
24
+ from transformers.image_utils import ImageInput
25
+ from transformers.processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
26
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
27
+
28
+ try:
29
+ from . import image_processing_penguinvl
30
+ from .image_processing_penguinvl import (
31
+ is_valid_image, is_valid_video,
32
+ )
33
+ except ModuleNotFoundError:
34
+ spec = importlib.util.spec_from_file_location(
35
+ "image_processing_penguinvl",
36
+ osp.join(osp.dirname(__file__), "image_processing_penguinvl.py"),
37
+ )
38
+ image_processing_penguinvl = importlib.util.module_from_spec(spec)
39
+ spec.loader.exec_module(image_processing_penguinvl)
40
+ is_valid_image = getattr(image_processing_penguinvl, "is_valid_image")
41
+ is_valid_video = getattr(image_processing_penguinvl, "is_valid_video")
42
+
43
+ # constants
44
+ DEFAULT_IMAGE_TOKEN = "<image>"
45
+ IGNORE_INDEX = -100
46
+
47
+ # Type aliases
48
+ Conversation = List[Dict[str, Any]]
49
+ SingleImage = Union[Image.Image, np.ndarray, torch.Tensor]
50
+ SingleVideo = Union[List[SingleImage], np.ndarray, torch.Tensor]
51
+ BatchedImage = List[Union[SingleImage, SingleVideo]]
52
+ BatchedNamedImage = List[Tuple[str, Union[SingleImage, SingleVideo]]]
53
+
54
+
55
+ def _custom_import(class_name: str):
56
+ try:
57
+ attribute_class = getattr(transformers, class_name)
58
+ except AttributeError:
59
+ if "image" in class_name.lower():
60
+ attribute_class = getattr(image_processing_penguinvl, class_name)
61
+ return attribute_class
62
+
63
+
64
+ def is_named_image(image) -> bool:
65
+ return isinstance(image, (list, tuple)) and \
66
+ len(image) == 2 and \
67
+ isinstance(image[0], str) and \
68
+ image[0] in ["image", "video"] and \
69
+ (is_valid_image(image[1]) or is_valid_video(image[1]))
70
+
71
+
72
+ def make_batched_images(images) -> List[List[ImageInput]]:
73
+ if isinstance(images, (list, tuple)) and all(is_named_image(image) for image in images):
74
+ # list of named images
75
+ return [image[0] for image in images], [image[1] for image in images]
76
+ elif isinstance(images, (list, tuple)) and all(is_valid_image(image) or is_valid_video(image) for image in images):
77
+ # list of images/videos
78
+ batch = []
79
+ for image in images:
80
+ if is_valid_video(image):
81
+ batch.append(("video", image))
82
+ elif is_valid_image(image):
83
+ batch.append(("image", image))
84
+ else:
85
+ raise ValueError(f"Could not make batched images from {images}")
86
+ return [x[0] for x in batch], [x[1] for x in batch]
87
+ elif is_named_image(images):
88
+ # named images
89
+ return [images[0]], [image[1]]
90
+ elif is_valid_video(images):
91
+ # single video
92
+ return ["video"], [images]
93
+ elif is_valid_image(images):
94
+ # single image
95
+ return ["image"], [images]
96
+
97
+ raise ValueError(f"Could not make batched images from {images}")
98
+
99
+
100
+ def frame_sample(duration, mode='uniform', num_frames=None, vid_fps=None, fps=None):
101
+ if mode == 'uniform':
102
+ assert num_frames is not None, "Number of frames must be provided for uniform sampling."
103
+ if duration <= num_frames:
104
+ return np.arange(duration).astype(int)
105
+ # NOTE: v1 version
106
+ # Calculate the size of each segment from which a frame will be extracted
107
+ # if duration <= num_frames:
108
+ # return np.arange(duration).astype(int)
109
+ # seg_size = float(duration - 1) / num_frames
110
+
111
+ # frame_ids = []
112
+ # for i in range(num_frames):
113
+ # # Calculate the start and end indices of each segment
114
+ # start = seg_size * i
115
+ # end = seg_size * (i + 1)
116
+ # # Append the middle index of the segment to the list
117
+ # frame_ids.append((start + end) / 2)
118
+
119
+ # return np.round(np.array(frame_ids) + 1e-6).astype(int)
120
+ # NOTE: v0 version
121
+ return np.linspace(0, duration-1, num_frames, dtype=int)
122
+ elif mode == 'fps':
123
+ assert vid_fps is not None, "FPS must be provided for FPS sampling."
124
+ assert fps is not None, "FPS must be provided for FPS sampling."
125
+ segment_len = min(vid_fps // fps, duration)
126
+ return np.arange(segment_len // 2, duration, segment_len, dtype=int)
127
+ else:
128
+ raise ImportError(f'Unsupported frame sampling mode: {mode}')
129
+
130
+
131
+ def load_video_from_ids(video_path, s=None, e=None, fps=None, max_frames=128, temporal_factor=1):
132
+ if s is not None and e is not None:
133
+ s = s if s >= 0. else 0.
134
+ e = e if e >= 0. else 0.
135
+ if s > e:
136
+ s, e = e, s
137
+ elif s == e:
138
+ e = s + 1
139
+
140
+ # 1. Loading Video
141
+ if os.path.isdir(video_path):
142
+ frame_files = sorted(os.listdir(video_path))
143
+
144
+ vid_fps = 3
145
+ num_frames_of_video = len(frame_files)
146
+ elif video_path.endswith('.gif'):
147
+ gif_reader = imageio.get_reader(video_path)
148
+
149
+ vid_fps = 25
150
+ num_frames_of_video = len(gif_reader)
151
+ else:
152
+ vreader = VideoReader(video_path, ctx=cpu(0), num_threads=2)
153
+ # vreader = VideoReader(video_path, ctx=cpu(0), num_threads=1)
154
+
155
+ vid_fps = vreader.get_avg_fps()
156
+ num_frames_of_video = len(vreader)
157
+
158
+ # 2. Determine frame range & Calculate frame indices
159
+ f_start = 0 if s is None else max(int(s * vid_fps) - 1, 0)
160
+ f_end = num_frames_of_video - 1 if e is None else min(int(e * vid_fps) - 1, num_frames_of_video - 1)
161
+ frame_indices = list(range(f_start, f_end + 1))
162
+
163
+ duration = len(frame_indices)
164
+ # 3. Sampling frame indices
165
+ if fps is not None and duration / vid_fps < max_frames:
166
+ sampled_frame_indices = [frame_indices[i] for i in frame_sample(duration, mode='fps', vid_fps=vid_fps, fps=fps)]
167
+ else:
168
+ sampled_frame_indices = [frame_indices[i] for i in frame_sample(duration, mode='uniform', num_frames=max_frames)]
169
+
170
+ # 4. Acquire frame data
171
+ if os.path.isdir(video_path):
172
+ frames = np.array([cv2.cvtColor(cv2.imread(os.path.join(video_path, frame_files[frame_idx])), cv2.COLOR_BGR2RGB) for frame_idx in sampled_frame_indices])
173
+ elif video_path.endswith('.gif'):
174
+ frames = np.array([cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB) for idx, frame in enumerate(gif_reader) if idx in sampled_frame_indices])
175
+ else:
176
+ frames = vreader.get_batch(sampled_frame_indices).asnumpy()
177
+
178
+ frames = frames.transpose(0, 3, 1, 2)
179
+ timestamps = [x / vid_fps for x in sampled_frame_indices]
180
+
181
+ if temporal_factor > 1:
182
+ pad_length = temporal_factor - len(frames) % temporal_factor
183
+ frames = np.concatenate([frames, frames[-1:].repeat(pad_length, axis=0)])
184
+ [timestamps.append(timestamps[-1] + 1 / fps) for _ in range(pad_length)]
185
+
186
+ frames = [frame for frame in frames]
187
+
188
+ return frames, timestamps
189
+
190
+
191
+
192
+ def round_by_factor(number: int, factor: int) -> int:
193
+ """Returns the closest integer to 'number' that is divisible by 'factor'."""
194
+ return round(number / factor) * factor
195
+
196
+
197
+ def ceil_by_factor(number: int, factor: int) -> int:
198
+ """Returns the smallest integer greater than or equal to 'number' that is divisible by 'factor'."""
199
+ return math.ceil(number / factor) * factor
200
+
201
+
202
+ def floor_by_factor(number: int, factor: int) -> int:
203
+ """Returns the largest integer less than or equal to 'number' that is divisible by 'factor'."""
204
+ return math.floor(number / factor) * factor
205
+
206
+ def smart_resize(
207
+ height: int, width: int,
208
+ factor: int = 14,
209
+ min_pixels: int = 0,
210
+ max_pixels: int = 16384):
211
+ """
212
+ Rescales the image so that the following conditions are met:
213
+
214
+ 1. Both dimensions (height and width) are divisible by 'factor'.
215
+
216
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
217
+
218
+ 3. The aspect ratio of the image is maintained as closely as possible.
219
+ """
220
+
221
+ if max(height, width) / min(height, width) > 200:
222
+ raise ValueError(
223
+ f"absolute aspect ratio must be smaller than {200}, got {max(height, width) / min(height, width)}"
224
+ )
225
+ h_bar = max(factor, round_by_factor(height, factor))
226
+ w_bar = max(factor, round_by_factor(width, factor))
227
+ if h_bar * w_bar > max_pixels:
228
+ beta = math.sqrt((height * width) / max_pixels)
229
+ h_bar = floor_by_factor(height / beta, factor)
230
+ w_bar = floor_by_factor(width / beta, factor)
231
+ elif h_bar * w_bar < min_pixels:
232
+ beta = math.sqrt(min_pixels / (height * width))
233
+ h_bar = ceil_by_factor(height * beta, factor)
234
+ w_bar = ceil_by_factor(width * beta, factor)
235
+ return max(h_bar, factor), max(w_bar, factor)
236
+
237
+ def get_frame_sim(frame1, frame2,
238
+ patch_size: int=14,
239
+ threshold: float = 0.7,
240
+ epsilon: float=1e-8):
241
+ assert frame1.dim() == 3 and frame2.dim() == 3, "输入必须是3D张量 [C, H, W]"
242
+
243
+ # 将PyTorch张量转换为OpenCV格式的numpy数组
244
+ def to_numpy_cvt(tensor):
245
+ # 确保张量在CPU上并转换为HWC格式
246
+ tensor = tensor.cpu().permute(1, 2, 0).numpy()
247
+ if tensor.dtype == np.float32 or tensor.dtype == np.float64:
248
+ tensor = (tensor).astype(np.uint8)
249
+ # 转换为HSV颜色空间
250
+ return cv2.cvtColor(tensor, cv2.COLOR_RGB2HSV)
251
+
252
+ # 转换颜色空间
253
+ frame1_hsv = to_numpy_cvt(frame1)
254
+ frame2_hsv = to_numpy_cvt(frame2)
255
+
256
+ # 将HSV图像转回PyTorch张量
257
+ frame1_tensor = torch.from_numpy(frame1_hsv).permute(2, 0, 1).to(frame1.device).float()
258
+ frame2_tensor = torch.from_numpy(frame2_hsv).permute(2, 0, 1).to(frame2.device).float()
259
+
260
+ # 分块处理
261
+ patch1 = rearrange(
262
+ frame1_tensor, "c (h p1) (w p2) -> h w (c p1 p2)", p1=patch_size, p2=patch_size).float()
263
+ patch2 = rearrange(
264
+ frame2_tensor, "c (h p1) (w p2) -> h w (c p1 p2)", p1=patch_size, p2=patch_size).float()
265
+
266
+ norm1 = torch.norm(patch1, p=2, dim=-1, keepdim=True) + epsilon
267
+ norm2 = torch.norm(patch2, p=2, dim=-1, keepdim=True) + epsilon
268
+
269
+ normalized1 = patch1 / norm1
270
+ normalized2 = patch2 / norm2
271
+ cos_sim = (normalized1 * normalized2).sum(dim=-1)
272
+
273
+ zero_vector_mask = (norm1.squeeze() < 0.01) & (norm2.squeeze() < 0.01) # 全黑图
274
+
275
+ similar = torch.ones_like(cos_sim) # 默认全部相似
276
+
277
+ non_zero_mask = ~zero_vector_mask
278
+ similar[non_zero_mask] = (cos_sim[non_zero_mask] > threshold).float()
279
+
280
+ return similar[non_zero_mask].float().mean().item()
281
+
282
+ def extract_slow_fast_frames(frames, threshold = 0.95):
283
+ def _extract_slow_indices(frames):
284
+ assert frames.dim() == 4, "输入必须是4D张量 [N, C, H, W]"
285
+
286
+ # 首帧一定是Slow
287
+ slow_indices = [0]
288
+ # 定位这里,检查和image[0]报错是不是同一视频
289
+ last_key_frame = frames[0]
290
+ for i in range(1, frames.size(0)):
291
+ current_frame = frames[i]
292
+ sim = get_frame_sim(last_key_frame, current_frame)
293
+
294
+ if sim < threshold:
295
+ slow_indices.append(i)
296
+ last_key_frame = current_frame # 更新关键帧
297
+
298
+ return slow_indices
299
+
300
+ _, _, height, width = frames.shape
301
+ resized_height, resized_width = smart_resize(
302
+ height,
303
+ width,
304
+ factor=14,
305
+ min_pixels=10 * 14 * 14,
306
+ max_pixels=10240 * 14 * 14,
307
+ )
308
+
309
+ resized_frames = nn.functional.interpolate(
310
+ frames,
311
+ [resized_height, resized_width],
312
+ mode="bilinear",
313
+ antialias=True,
314
+ ).float()
315
+
316
+ slow_indices = _extract_slow_indices(resized_frames)
317
+ frame_types = torch.ones(size=(frames.size(0), ), dtype=torch.int32)
318
+ frame_types[slow_indices] = 0
319
+
320
+ return list(frame_types)
321
+
322
+
323
+ class ChatTemplateKwargs(TypedDict, total=False):
324
+
325
+ chat_template: Optional[str]
326
+ add_system_prompt: Optional[bool]
327
+ add_generation_prompt: Optional[bool]
328
+
329
+
330
+ class PenguinVLQwen3ProcessorKwargs(ProcessingKwargs, ChatTemplateKwargs, total=False):
331
+
332
+ chat_template_kwargs: ChatTemplateKwargs = {
333
+ **ChatTemplateKwargs.__annotations__,
334
+ }
335
+
336
+ _defaults = {
337
+ "text_kwargs": {
338
+ "padding": False,
339
+ },
340
+ "image_kwargs": {
341
+ "merge_size": None,
342
+ },
343
+ "chat_template_kwargs": {
344
+ "chat_template": None,
345
+ "add_system_prompt": False,
346
+ "add_generation_prompt": False,
347
+ },
348
+ }
349
+
350
+
351
+ class PenguinVLQwen3Processor(ProcessorMixin):
352
+
353
+ attributes = ["image_processor", "tokenizer"]
354
+ image_processor_class = "PenguinVLImageProcessor"
355
+ tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast")
356
+ valid_kwargs = ["chat_template", "image_merge_size", "video_merge_size", "fps", "max_frames"]
357
+
358
+ def __init__(
359
+ self,
360
+ image_processor=None,
361
+ tokenizer=None,
362
+ chat_template: str = None,
363
+ image_merge_size: int = 1,
364
+ video_merge_size: int = 2,
365
+ fps: Optional[int] = 1,
366
+ max_frames: Optional[int] = 128,
367
+ use_codec = False,
368
+ ):
369
+ self.image_processor = image_processor
370
+ self.tokenizer = tokenizer
371
+ if chat_template is None:
372
+ chat_template = self.tokenizer.chat_template
373
+ self.chat_template = chat_template
374
+
375
+ self.image_merge_size = image_merge_size
376
+ self.video_merge_size = video_merge_size
377
+ self.fps = fps
378
+ self.max_frames = max_frames
379
+ self.use_codec = use_codec
380
+ self.generation_prompt = self._infer_generation_prompt()
381
+ self.generation_prompt_ids = self.tokenizer.encode(self.generation_prompt, return_tensors="pt")
382
+ self.generation_prompt_length = len(self.generation_prompt_ids[0])
383
+ self.image_token_id = self.tokenizer.convert_tokens_to_ids(DEFAULT_IMAGE_TOKEN)
384
+ self.eos_token_id = self.tokenizer.eos_token_id
385
+
386
+ @classmethod
387
+ def _get_arguments_from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
388
+ args = []
389
+ for attribute_name in cls.attributes:
390
+ class_name = getattr(cls, f"{attribute_name}_class")
391
+ if isinstance(class_name, tuple):
392
+ classes = tuple(_custom_import(n) if n is not None else None for n in class_name)
393
+ use_fast = kwargs.get("use_fast", True)
394
+ if use_fast and classes[1] is not None:
395
+ attribute_class = classes[1]
396
+ else:
397
+ attribute_class = classes[0]
398
+ else:
399
+ attribute_class = _custom_import(class_name)
400
+
401
+ args.append(attribute_class.from_pretrained(pretrained_model_name_or_path, **kwargs))
402
+ return args
403
+
404
+ def get_generation_prompt(self):
405
+ return self.generation_prompt
406
+
407
+ def get_generation_prompt_ids(self):
408
+ return self.generation_prompt_ids
409
+
410
+ def _infer_generation_prompt(self):
411
+ pseudo_message = [{"role": "user", "content": ""}]
412
+ instruction = self.apply_chat_template(pseudo_message, tokenize=False, add_generation_prompt=True)
413
+ conversation = self.apply_chat_template(pseudo_message, tokenize=False, add_generation_prompt=False)
414
+ return instruction.replace(conversation, "")
415
+
416
+ def _get_downsampled_grid_sizes(self, image_inputs: Dict[str, Any]):
417
+ grid_sizes = []
418
+ for grid_size, merge_size in zip(image_inputs.get("grid_sizes", []), image_inputs.get("merge_sizes", [])):
419
+ if not torch.all(grid_size[1:] % merge_size == 0):
420
+ warnings.warn(f"Grid size {grid_size} is not divisible by merge size. Some undesired errors may occur.")
421
+ if grid_size[0] == 1:
422
+ grid_sizes.append(grid_size[1:] / merge_size)
423
+ elif grid_size[0] > 1:
424
+ grid_sizes.extend([grid_size[1:] / merge_size] * grid_size[0])
425
+ return grid_sizes
426
+
427
+ def _get_visual_seq_len(self, grid_size: torch.Tensor):
428
+ num_tokens = int(grid_size.prod().item())
429
+ return num_tokens
430
+
431
+ def load_images(self, image_path: Union[str, List[str], Image.Image, List[Image.Image]]):
432
+ if isinstance(image_path, str) and os.path.isfile(image_path):
433
+ # images = [cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)]
434
+ images = [Image.open(image_path).convert('RGB')]
435
+ elif isinstance(image_path, str) and os.path.isdir(image_path):
436
+ # images = [cv2.cvtColor(cv2.imread(os.path.join(image_path, f)), cv2.COLOR_BGR2RGB) for f in sorted(os.listdir(image_path))]
437
+ images = [Image.open(os.path.join(image_path, f)).convert('RGB') for f in sorted(os.listdir(image_path))]
438
+ elif isinstance(image_path, list) and isinstance(image_path[0], str):
439
+ # images = [cv2.cvtColor(cv2.imread(f), cv2.COLOR_BGR2RGB) for f in image_path]
440
+ images = [Image.open(f).convert('RGB') for f in image_path]
441
+ elif isinstance(image_path, list) and isinstance(image_path[0], Image.Image):
442
+ images = [np.array(x) for x in image_path]
443
+ elif isinstance(image_path, Image.Image):
444
+ images = [np.array(image_path)]
445
+ else:
446
+ raise ValueError(f"Unsupported image path type: {type(image_path)}")
447
+ return images
448
+
449
+ def load_video(
450
+ self,
451
+ video_path: str,
452
+ start_time: Optional[float] = None,
453
+ end_time: Optional[float] = None,
454
+ fps: Optional[float] = None,
455
+ max_frames: Optional[float] = None,
456
+ size: Optional[int] = None,
457
+ size_divisible: int = 1,
458
+ precise_time: bool = False,
459
+ verbose: bool = False,
460
+ temporal_factor: int = 1
461
+ ):
462
+ """
463
+ Load and process a video file and return the frames and the timestamps of each frame.
464
+
465
+ Args:
466
+ video_path (str): Path to the video file.
467
+ start_time (float, optional): Start time in seconds. Defaults to None.
468
+ end_time (float, optional): End time in seconds. Defaults to None.
469
+ fps (float, optional): Frames per second. Defaults to None.
470
+ num_frames (float, optional): Number of frames to sample. Defaults to None.
471
+ size (int, optional): Size of the shortest side. Defaults to None.
472
+ size_divisible (int, optional): Size divisible by this number. Defaults to 1.
473
+ precise_time (bool, optional): Whether to use precise time. Defaults to False.
474
+ verbose (bool, optional): Print ffmpeg output. Defaults to False.
475
+
476
+ Returns:
477
+ frames (List[PIL.Image]): List of frames.
478
+ timestamps (List[float]): List of timestamps.
479
+ """
480
+ if self.use_codec:
481
+ return self.load_video_with_codec(**locals())
482
+ fps = self.fps if fps is None else fps
483
+ max_frames = self.max_frames if max_frames is None else max_frames
484
+
485
+ if start_time is not None and end_time is not None and end_time - start_time < 1:
486
+ return load_video_from_ids(video_path, start_time, end_time, fps=fps, max_frames=max_frames)
487
+ if os.path.isdir(video_path):
488
+ return load_video_from_ids(video_path, start_time, end_time, fps=fps, max_frames=max_frames)
489
+ if video_path.endswith('.gif'):
490
+ return load_video_from_ids(video_path, start_time, end_time, fps=fps, max_frames=max_frames)
491
+ probe = ffmpeg.probe(video_path)
492
+ duration = float(probe['format']['duration'])
493
+ video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
494
+ w, h = int(video_stream['width']), int(video_stream['height'])
495
+
496
+ kwargs, input_kwargs, output_kwargs = {}, {}, {}
497
+ do_trim = start_time is not None or end_time is not None
498
+ if start_time is not None:
499
+ new_start_time = max(float(video_stream['start_time']), start_time)
500
+ duration -= new_start_time - start_time
501
+ start_time = new_start_time
502
+ else:
503
+ start_time = float(video_stream['start_time'])
504
+ if end_time is not None:
505
+ duration = min(duration, end_time - start_time)
506
+ else:
507
+ duration = duration
508
+ if do_trim:
509
+ kwargs = {'ss': start_time, 't': duration}
510
+ if precise_time:
511
+ output_kwargs.update(kwargs)
512
+ else:
513
+ input_kwargs.update(kwargs)
514
+
515
+ if size is not None:
516
+ scale_factor = size / min(w, h)
517
+ new_w, new_h = round(w * scale_factor), round(h * scale_factor)
518
+ else:
519
+ new_w, new_h = w, h
520
+ new_w = new_w // size_divisible * size_divisible
521
+ new_h = new_h // size_divisible * size_divisible
522
+
523
+ # NOTE: It may result in unexpected number of frames in ffmpeg
524
+ # if calculate the fps directly according to max_frames
525
+ # if max_frames is not None and (fps is None or duration * fps > 2 * max_frames):
526
+ # fps = round(max_frames / duration * 2)
527
+
528
+ stream = ffmpeg.input(video_path, **input_kwargs)
529
+ if fps is not None:
530
+ stream = ffmpeg.filter(stream, "fps", fps=fps, round="down")
531
+ if new_w != w or new_h != h:
532
+ stream = ffmpeg.filter(stream, 'scale', new_w, new_h)
533
+ stream = ffmpeg.output(stream, "pipe:", format="rawvideo", pix_fmt="rgb24", **output_kwargs)
534
+ out, _ = ffmpeg.run(stream, capture_stdout=True, quiet=not verbose)
535
+
536
+ frames = np.frombuffer(out, np.uint8).reshape([-1, new_h, new_w, 3]).transpose([0, 3, 1, 2])
537
+
538
+ if fps is not None:
539
+ timestamps = np.arange(start_time, start_time + duration + 1 / fps, 1 / fps)[:len(frames)]
540
+ else:
541
+ timestamps = np.linspace(start_time, start_time + duration, len(frames))
542
+
543
+ if max_frames is not None and len(frames) > max_frames:
544
+ indices = np.linspace(0, len(frames) - 1, max_frames, dtype=int)
545
+ frames = frames[indices]
546
+ timestamps = timestamps[indices]
547
+
548
+ if temporal_factor > 1:
549
+ pad_length = temporal_factor - len(frames) % temporal_factor
550
+ frames = np.concatenate([frames, frames[-1:].repeat(pad_length, axis=0)])
551
+ timestamps = np.concatenate([timestamps, timestamps[-1:].repeat(pad_length) + np.arange(1, pad_length + 1) / fps])
552
+
553
+ frames_tensor = torch.from_numpy(frames.copy()).float()
554
+ frame_types = extract_slow_fast_frames(frames_tensor)
555
+
556
+ frames = [frame for frame in frames]
557
+ timestamps = [timestamp for timestamp in timestamps]
558
+
559
+ return frames, timestamps, frame_types
560
+
561
+ def load_video_with_codec(
562
+ self,
563
+ video_path: str,
564
+ start_time: Optional[float] = None,
565
+ end_time: Optional[float] = None,
566
+ fps: Optional[float] = None,
567
+ max_frames: Optional[float] = None,
568
+ size: Optional[int] = None,
569
+ size_divisible: int = 1,
570
+ precise_time: bool = False,
571
+ verbose: bool = False,
572
+ temporal_factor: int = 1,
573
+ slow_fast: bool = True
574
+ ):
575
+ """
576
+ Load a video by prioritizing I-frames (keyframes) and dynamically sampling
577
+ additional frames between adjacent I-frames up to `max_frames`.
578
+
579
+ Notes:
580
+ - Real codec I-frames (keyframes) are always used as-is and do NOT follow `fps`.
581
+ - If `fps` is provided, it controls how we sample additional non-I frames between
582
+ adjacent I-frames (and still respects `max_frames`).
583
+ - This function does NOT call `load_video_from_ids`.
584
+
585
+ Returns:
586
+ frames: List[np.ndarray] where each is CHW (3, H, W) uint8
587
+ timestamps: List[float] timestamps in seconds for each returned frame
588
+ frame_types: List[int] where 0 = I-frame (keyframe), 1 = non-I-frame (sampled)
589
+ """
590
+ return_frame_types = slow_fast
591
+ max_frames = int(max_frames if max_frames is not None else self.max_frames)
592
+ if max_frames <= 0:
593
+ return ([], [], []) if return_frame_types else ([], [])
594
+
595
+ def _coerce_range(s: Optional[float], e: Optional[float]):
596
+ if s is not None and e is not None:
597
+ s = s if s >= 0.0 else 0.0
598
+ e = e if e >= 0.0 else 0.0
599
+ if s > e:
600
+ s, e = e, s
601
+ elif s == e:
602
+ e = s + 1.0
603
+ return s, e
604
+
605
+ # Fallbacks for non-standard "videos"
606
+ if os.path.isdir(video_path):
607
+ # Directory input is a sequence of images; there is no keyframe/I-frame concept.
608
+ # We mimic `load_video_from_ids` semantics: interpret start/end in seconds using a
609
+ # small assumed FPS, then uniformly sample up to `max_frames` within that range.
610
+ start_time, end_time = _coerce_range(start_time, end_time)
611
+ dir_fps = 3.0
612
+
613
+ all_entries = sorted(os.listdir(video_path))
614
+ frame_files = []
615
+ for name in all_entries:
616
+ p = os.path.join(video_path, name)
617
+ if not os.path.isfile(p):
618
+ continue
619
+ if not name.lower().endswith((".jpg", ".jpeg", ".png", ".bmp", ".webp")):
620
+ continue
621
+ frame_files.append(name)
622
+
623
+ if len(frame_files) == 0:
624
+ return ([], [], []) if return_frame_types else ([], [])
625
+
626
+ num_frames_of_video = len(frame_files)
627
+ f_start = 0 if start_time is None else max(int(start_time * dir_fps) - 1, 0)
628
+ f_end = (num_frames_of_video - 1) if end_time is None else min(int(end_time * dir_fps) - 1, num_frames_of_video - 1)
629
+ if f_end < f_start:
630
+ return ([], [], []) if return_frame_types else ([], [])
631
+
632
+ frame_indices = list(range(f_start, f_end + 1))
633
+ duration = len(frame_indices)
634
+ sampled = frame_sample(duration, mode="uniform", num_frames=max_frames)
635
+ sampled_frame_indices = [frame_indices[i] for i in sampled.tolist()]
636
+
637
+ frames = []
638
+ timestamps = []
639
+ for i in sampled_frame_indices:
640
+ img = cv2.imread(os.path.join(video_path, frame_files[i]))
641
+ if img is None:
642
+ continue
643
+ frames.append(cv2.cvtColor(img, cv2.COLOR_BGR2RGB).transpose(2, 0, 1))
644
+ timestamps.append(float(i) / dir_fps)
645
+
646
+ # No keyframe concept for image directories; treat all as non-keyframes.
647
+ frame_types = [1] * len(frames)
648
+ return (frames, timestamps, frame_types) if return_frame_types else (frames, timestamps)
649
+
650
+ if video_path.endswith('.gif'):
651
+ gif_reader = imageio.get_reader(video_path)
652
+ num_frames_of_video = len(gif_reader)
653
+ if num_frames_of_video == 0:
654
+ return ([], [], []) if return_frame_types else ([], [])
655
+ n = min(max_frames, num_frames_of_video)
656
+ idxs = np.linspace(0, num_frames_of_video - 1, n, dtype=int).tolist()
657
+ frames = [
658
+ cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB).transpose(2, 0, 1)
659
+ for idx, frame in enumerate(gif_reader) if idx in set(idxs)
660
+ ]
661
+ # crude timestamps for gif; i-frame concept not applicable
662
+ timestamps = [float(i) for i in range(len(frames))]
663
+ # GIF frames are intra-coded; treat them as keyframes.
664
+ frame_types = [0] * len(frames)
665
+ return (frames, timestamps, frame_types) if return_frame_types else (frames, timestamps)
666
+
667
+ def _get_video_stream_info(path: str):
668
+ probe = ffmpeg.probe(path)
669
+ fmt_duration = float(probe["format"]["duration"])
670
+ vstream = next((st for st in probe["streams"] if st.get("codec_type") == "video"), None)
671
+ if vstream is None:
672
+ raise ValueError(f"No video stream found in: {path}")
673
+ w, h = int(vstream["width"]), int(vstream["height"])
674
+ stream_start = float(vstream.get("start_time") or 0.0)
675
+ return probe, vstream, fmt_duration, (w, h), stream_start
676
+
677
+ def _safe_float(x) -> Optional[float]:
678
+ if x is None:
679
+ return None
680
+ try:
681
+ return float(x)
682
+ except Exception:
683
+ return None
684
+
685
+ def _get_iframe_timestamps(path: str, s: float, e: float) -> List[float]:
686
+ """
687
+ Return sorted I-frame timestamps within [s, e].
688
+ Uses ffprobe with skip_frame=nokey to avoid scanning all frames.
689
+ """
690
+ try:
691
+ p = ffmpeg.probe(
692
+ path,
693
+ select_streams="v:0",
694
+ skip_frame="nokey",
695
+ show_frames=None,
696
+ show_entries="frame=pict_type,pkt_pts_time,best_effort_timestamp_time,key_frame,pkt_size",
697
+ of="json",
698
+ )
699
+ except ffmpeg.Error as ex:
700
+ print("ffprobe keyframe scan failed:", ex)
701
+ return []
702
+ frames_meta = p.get("frames") or []
703
+ out_ts = []
704
+ for fr in frames_meta:
705
+ # Prefer pict_type == I; fall back to key_frame == 1 if pict_type missing.
706
+ pict_type = fr.get("pict_type")
707
+ is_i = (pict_type == "I") or (pict_type is None and str(fr.get("key_frame")) == "1")
708
+ if not is_i:
709
+ continue
710
+ ts = _safe_float(fr.get("pkt_pts_time"))
711
+ if ts is None:
712
+ ts = _safe_float(fr.get("best_effort_timestamp_time"))
713
+ if ts is None:
714
+ continue
715
+ if ts < s or ts > e:
716
+ continue
717
+ size_bytes = int(fr.get("pkt_size", 0))
718
+ out_ts.append((ts, size_bytes))
719
+
720
+ out_ts.sort(key=lambda x: x[0])
721
+ out_sizes = [x[1] for x in out_ts]
722
+ return [x[0] for x in out_ts], out_sizes
723
+
724
+ def _normalize_uint8_nchw(data: torch.Tensor) -> torch.Tensor:
725
+ """
726
+ Ensure tensor is NCHW uint8 on CPU with values in [0, 255].
727
+ torchcodec may return float in [0,1] or [0,255] depending on backend.
728
+ """
729
+ if not isinstance(data, torch.Tensor):
730
+ raise TypeError(f"Expected torch.Tensor, got {type(data)}")
731
+ if data.ndim != 4:
732
+ raise ValueError(f"Expected NCHW tensor, got shape {tuple(data.shape)}")
733
+ if data.device.type != "cpu":
734
+ data = data.cpu()
735
+ if data.dtype != torch.uint8:
736
+ d = data
737
+ if d.is_floating_point():
738
+ mx = float(d.max().item()) if d.numel() > 0 else 0.0
739
+ if mx <= 1.0 + 1e-6:
740
+ d = d * 255.0
741
+ d = d.round()
742
+ data = d.clamp(0, 255).to(torch.uint8)
743
+ return data
744
+
745
+
746
+ def _allocate_remaining_floor_ratio(widths: np.ndarray, remaining: int) -> list[int]:
747
+ """
748
+ Allocate `remaining` frames across windows proportionally by window width using floor,
749
+ without redistributing leftover.
750
+
751
+ This matches the spec:
752
+ - prioritize large I-frame windows
753
+ - use floor so the sum does not exceed `remaining`
754
+ """
755
+ nwin = int(widths.shape[0])
756
+ if nwin == 0 or remaining <= 0:
757
+ return [0] * nwin
758
+ widths = np.maximum(widths.astype(float), 0.0)
759
+ wsum = float(widths.sum())
760
+ if wsum <= 0.0:
761
+ return [0] * nwin
762
+ alloc = np.floor(float(remaining) * (widths / wsum)).astype(int)
763
+ # Defensive clamp (should already be <= remaining by construction)
764
+ s = int(alloc.sum())
765
+ if s > remaining:
766
+ # remove extras from smallest windows first
767
+ order = np.argsort(widths) # ascending
768
+ i = 0
769
+ while s > remaining and i < nwin:
770
+ j = int(order[i])
771
+ if alloc[j] > 0:
772
+ alloc[j] -= 1
773
+ s -= 1
774
+ else:
775
+ i += 1
776
+ return alloc.tolist()
777
+
778
+ def _uniform_inside(a: float, b: float, k: int) -> List[float]:
779
+ """k points uniformly spaced inside (a, b), excluding endpoints."""
780
+ if k <= 0:
781
+ return []
782
+ if b <= a:
783
+ return []
784
+ step = (b - a) / (k + 1)
785
+ return [a + step * (j + 1) for j in range(k)]
786
+
787
+ def _sample_inside_fps(a: float, b: float, fps_val: float) -> List[float]:
788
+ """Sample points at `fps_val` within (a, b), excluding endpoints."""
789
+ if fps_val is None:
790
+ return []
791
+ try:
792
+ fps_f = float(fps_val)
793
+ except Exception:
794
+ return []
795
+ if not (fps_f > 0.0):
796
+ return []
797
+ if b <= a:
798
+ return []
799
+ step = 1.0 / fps_f
800
+ t = a + step
801
+ out = []
802
+ # avoid producing a huge list if `fps` is absurd; we'll downsample anyway,
803
+ # but keep a reasonable cap based on the window size.
804
+ # (This cap is still safe because we always keep I-frames.)
805
+ max_points = int(max(0.0, (b - a) * fps_f)) + 2
806
+ n = 0
807
+ while t < b and n < max_points:
808
+ out.append(float(t))
809
+ t += step
810
+ n += 1
811
+ return out
812
+
813
+ start_time, end_time = _coerce_range(start_time, end_time)
814
+ probe, video_stream, fmt_duration, (w, h), stream_start = _get_video_stream_info(video_path)
815
+
816
+ # Use absolute timestamps in seconds.
817
+ if start_time is None:
818
+ start_time = float(stream_start)
819
+ else:
820
+ start_time = max(float(stream_start), float(start_time))
821
+
822
+ if end_time is None:
823
+ end_time = float(stream_start) + float(fmt_duration)
824
+ else:
825
+ end_time = float(end_time)
826
+
827
+ if end_time <= start_time:
828
+ end_time = start_time + 1e-3
829
+
830
+ # Output scaling (same logic as `load_video`)
831
+ if size is not None:
832
+ scale_factor = size / min(w, h)
833
+ new_w, new_h = round(w * scale_factor), round(h * scale_factor)
834
+ else:
835
+ new_w, new_h = w, h
836
+ new_w = new_w // size_divisible * size_divisible
837
+ new_h = new_h // size_divisible * size_divisible
838
+
839
+ # 1) Extract all I-frames in [start_time, end_time]
840
+ iframe_ts, iframe_sizes = _get_iframe_timestamps(video_path, start_time, end_time)
841
+
842
+ # 2) Decide timestamps to decode, and frame_types aligned to timestamps
843
+ timestamps: List[float] = []
844
+ frame_types: List[int] = []
845
+
846
+ if len(iframe_ts) == 0:
847
+ # No I-frames detected by ffprobe (rare / container oddities). Fall back to uniform time sampling.
848
+ if end_time <= start_time:
849
+ return ([], [], []) if return_frame_types else ([], [])
850
+ if fps is None:
851
+ n = max_frames
852
+ timestamps = np.linspace(start_time, end_time, n, endpoint=False, dtype=float).tolist()
853
+ else:
854
+ try:
855
+ fps_f = float(fps)
856
+ except Exception:
857
+ fps_f = 0.0
858
+ if fps_f > 0.0:
859
+ step = 1.0 / fps_f
860
+ timestamps = np.arange(start_time, end_time, step, dtype=float).tolist()
861
+ if len(timestamps) > max_frames:
862
+ idxs = np.linspace(0, len(timestamps) - 1, max_frames, dtype=int).tolist()
863
+ idxs = list(dict.fromkeys(idxs))
864
+ timestamps = [timestamps[i] for i in idxs][:max_frames]
865
+ else:
866
+ timestamps = np.linspace(start_time, end_time, max_frames, endpoint=False, dtype=float).tolist()
867
+ # No I-frames detected; treat all as non-keyframes.
868
+ frame_types = [1] * len(timestamps)
869
+ elif len(iframe_ts) >= max_frames:
870
+ # Too many I-frames: uniformly sample among all available keyframes.
871
+ idxs = np.linspace(0, len(iframe_ts) - 1, max_frames, dtype=int).tolist()
872
+ idxs = list(dict.fromkeys(idxs))
873
+ if len(idxs) != max_frames:
874
+ missing = max_frames - len(idxs)
875
+ all_idxs = np.arange(len(iframe_ts), dtype=int).tolist()
876
+ remain = [i for i in all_idxs if i not in set(idxs)]
877
+ if len(remain) > 0 and missing > 0:
878
+ fill = np.linspace(0, len(remain) - 1, missing, dtype=int).tolist()
879
+ idxs.extend([remain[i] for i in fill])
880
+ idxs = sorted(idxs)[:max_frames]
881
+ timestamps = [iframe_ts[i] for i in idxs]
882
+ frame_types = [0] * len(timestamps)
883
+ else:
884
+ # Use all I-frames, then allocate remaining between adjacent I-frames.
885
+ timestamps = list(iframe_ts)
886
+ frame_types = [0] * len(iframe_ts)
887
+ remaining = max_frames - len(iframe_ts)
888
+
889
+ if len(iframe_ts) >= 2 and remaining > 0:
890
+ left = np.array(iframe_ts[:-1], dtype=float)
891
+ right = np.array(iframe_ts[1:], dtype=float)
892
+
893
+ widths = (right - left).astype(float)
894
+ extra_ts: List[float] = []
895
+ if fps is None:
896
+ # Spec: allocate remaining frames by window size ratio using floor (no leftover redistribution).
897
+ alloc = _allocate_remaining_floor_ratio(widths, remaining)
898
+ for a, b, k in zip(left.tolist(), right.tolist(), alloc):
899
+ extra_ts.extend(_uniform_inside(float(a), float(b), int(k)))
900
+ else:
901
+ # Spec: prioritize large windows; sample at fixed fps inside each window until `max_frames` is reached
902
+ # or all windows are exhausted.
903
+ order = np.argsort(-widths).tolist() # descending widths
904
+ rem = int(remaining)
905
+ for j in order:
906
+ if rem <= 0:
907
+ break
908
+ a = float(left[j])
909
+ b = float(right[j])
910
+ cand = _sample_inside_fps(a, b, fps)
911
+ if len(cand) == 0:
912
+ continue
913
+ if len(cand) > rem:
914
+ cand = cand[:rem]
915
+ extra_ts.extend(cand)
916
+ rem -= len(cand)
917
+
918
+ # Drop samples too close to any I-frame timestamp to avoid collisions at decode.
919
+ if len(extra_ts) > 0:
920
+ iframe_set = [float(x) for x in iframe_ts]
921
+ def _far_from_iframes(t: float) -> bool:
922
+ return all(abs(float(t) - it) > 1e-3 for it in iframe_set)
923
+ extra_ts = [t for t in extra_ts if _far_from_iframes(t)]
924
+
925
+ timestamps.extend(extra_ts)
926
+ frame_types.extend([1] * len(extra_ts))
927
+ elif remaining > 0:
928
+ # Only 1 I-frame: sample the rest uniformly across the range, avoiding exact collision.
929
+ if end_time > start_time:
930
+ it = float(iframe_ts[0])
931
+ if fps is None:
932
+ extra_ts = np.linspace(start_time, end_time, remaining + 2, endpoint=True, dtype=float)[1:-1].tolist()
933
+ else:
934
+ extra_ts = _sample_inside_fps(float(start_time), float(end_time), fps)
935
+ # Keep at most `remaining` samples.
936
+ if len(extra_ts) > remaining and remaining > 0:
937
+ idxs = np.linspace(0, len(extra_ts) - 1, remaining, dtype=int).tolist()
938
+ idxs = list(dict.fromkeys(idxs))
939
+ extra_ts = [extra_ts[i] for i in idxs][:remaining]
940
+ elif remaining <= 0:
941
+ extra_ts = []
942
+
943
+ # drop timestamps extremely close to the I-frame timestamp
944
+ extra_ts = [t for t in extra_ts if abs(float(t) - it) > 1e-3]
945
+ # if we dropped some, refill with tiny offsets (to preserve count behavior)
946
+ while len(extra_ts) < remaining:
947
+ extra_ts.append(min(end_time, max(start_time, it + 1e-3 * (len(extra_ts) + 1))))
948
+ timestamps.extend(extra_ts[:remaining])
949
+ frame_types.extend([1] * min(remaining, len(extra_ts)))
950
+
951
+ # Sort by time and keep types aligned
952
+ order = np.argsort(np.array(timestamps, dtype=float)).tolist()
953
+ timestamps = [float(timestamps[i]) for i in order]
954
+ frame_types = [int(frame_types[i]) for i in order]
955
+
956
+ # 3) Decode frames at chosen timestamps with torchcodec (batch decode).
957
+ # We keep the same return format: List[np.ndarray] CHW uint8.
958
+ if len(timestamps) == 0:
959
+ return ([], [], []) if return_frame_types else ([], [])
960
+
961
+ try:
962
+ from torchcodec.decoders import VideoDecoder # type: ignore
963
+ except Exception as ex:
964
+ raise ImportError(
965
+ "torchcodec is required for video decoding in mm_utils.load_video. "
966
+ "Please install torchcodec (https://github.com/pytorch/torchcodec)."
967
+ ) from ex
968
+
969
+ # if precise_time and verbose:
970
+ # # torchcodec selects frames at/around the requested playback times; there's no ffmpeg-style
971
+ # # input-vs-output seek mode. We keep the flag for API compatibility.
972
+ # print("[mm_utils.load_video_dynamic] note: `precise_time=True` has no special effect with torchcodec.")
973
+ if not os.path.exists(video_path):
974
+ raise FileNotFoundError(f"Video file not found: {video_path}")
975
+ data: torch.Tensor
976
+ decoder = VideoDecoder(video_path, seek_mode="exact" if precise_time else "approximate")
977
+ stream_end_time = decoder.metadata.end_stream_seconds
978
+ stream_start_time = decoder.metadata.begin_stream_seconds
979
+ # torchcodec accepts list[float] or a torch tensor.
980
+ if start_time != 0:
981
+ t_req = [max(stream_start_time + 0.001, min(float(t), stream_end_time - 0.001)) for t in timestamps]
982
+ else:
983
+ t_req = [min(float(t), stream_end_time - 0.001) for t in timestamps]
984
+ try:
985
+ batch = decoder.get_frames_played_at(torch.tensor(t_req, dtype=torch.float32))
986
+ except Exception:
987
+ batch = decoder.get_frames_played_at(t_req)
988
+
989
+ raw = getattr(batch, "data", None)
990
+ if raw is None:
991
+ raise RuntimeError("torchcodec FrameBatch missing `.data` attribute.")
992
+ if not isinstance(raw, torch.Tensor):
993
+ raise RuntimeError(f"torchcodec FrameBatch `.data` is not a torch.Tensor (got {type(raw)}).")
994
+ data = _normalize_uint8_nchw(raw)
995
+
996
+ # Optional resize to match existing `size` / `size_divisible` behavior.
997
+ _, _, H, W = data.shape
998
+ if int(new_h) != int(H) or int(new_w) != int(W):
999
+ data_f = data.to(torch.float32)
1000
+ data_f = torch.nn.functional.interpolate(
1001
+ data_f,
1002
+ size=(int(new_h), int(new_w)),
1003
+ mode="bilinear",
1004
+ align_corners=False,
1005
+ )
1006
+ data = data_f.round().clamp(0, 255).to(torch.uint8)
1007
+
1008
+ n_out = int(data.shape[0])
1009
+ # torchcodec should return 1:1 with requested timestamps, but be defensive.
1010
+ n_keep = min(n_out, len(t_req), len(frame_types))
1011
+ data = data[:n_keep]
1012
+ timestamps = t_req[:n_keep]
1013
+ frame_types = frame_types[:n_keep]
1014
+
1015
+ frames: List[np.ndarray] = [data[i].numpy() for i in range(n_keep)]
1016
+
1017
+ # 4) Temporal padding (keep types aligned)
1018
+ if temporal_factor > 1 and len(frames) > 0:
1019
+ pad_length = (temporal_factor - (len(frames) % temporal_factor)) % temporal_factor
1020
+ if pad_length > 0:
1021
+ if len(timestamps) >= 2:
1022
+ dt = float(timestamps[-1] - timestamps[-2])
1023
+ dt = dt if dt > 0 else 1e-3
1024
+ else:
1025
+ dt = 1e-3
1026
+ for _ in range(pad_length):
1027
+ frames.append(frames[-1].copy())
1028
+ timestamps.append(float(timestamps[-1] + dt))
1029
+ frame_types.append(int(frame_types[-1]))
1030
+
1031
+ return (frames, timestamps, frame_types) if return_frame_types else (frames, timestamps)
1032
+
1033
+ def _load_multimodal_data(self, conversation: Conversation):
1034
+ multimodal_info = defaultdict(list)
1035
+ new_conversation = []
1036
+ for message in conversation:
1037
+ new_message = {"role": message["role"]}
1038
+ if not isinstance(message["content"], (list, tuple)):
1039
+ new_message["content"] = message["content"]
1040
+ new_conversation.append(new_message)
1041
+ continue
1042
+
1043
+ new_contents = []
1044
+ for content in message["content"]:
1045
+ if not isinstance(content, dict):
1046
+ new_contents.append(content)
1047
+ continue
1048
+ assert "type" in content, "Content must have 'type' field."
1049
+ if content["type"] in ["image", "video"] and content["type"] in content and isinstance(content[content["type"]], dict):
1050
+ # TODO: support other types which are not compatible with json
1051
+ load_args = content[content["type"]]
1052
+ data_id = json.dumps({k: v for k, v in load_args.items() if not k in ["start_time", "end_time"]})
1053
+ new_content = copy.deepcopy(content)
1054
+ multimodal_info[data_id].append(new_content)
1055
+ new_contents.append(new_content)
1056
+ else:
1057
+ new_contents.append(content)
1058
+
1059
+ new_message["content"] = new_contents
1060
+ new_conversation.append(new_message)
1061
+
1062
+ for data_id, contents in multimodal_info.items():
1063
+ data_type = contents[0]["type"]
1064
+ if data_type == "image":
1065
+ image = self.load_images(contents[0][data_type]["image_path"])[0]
1066
+ for content in contents:
1067
+ content["image"] = [image.copy()]
1068
+
1069
+ elif data_type == "video":
1070
+ start_times = [content["video"].get("start_time", 0.) for content in contents]
1071
+ end_times = [content["video"].get("end_time", float("inf")) for content in contents]
1072
+
1073
+ load_args = contents[0][data_type]
1074
+ start_time, end_time = min(start_times), max(end_times)
1075
+ if start_time > 0:
1076
+ load_args["start_time"] = start_time
1077
+ if end_time < float("inf"):
1078
+ load_args["end_time"] = end_time
1079
+ images, timestamps, frame_types = self.load_video(**load_args)
1080
+
1081
+ for content, start_time, end_time in zip(contents, start_times, end_times):
1082
+ cur_images, cur_timestamps, cur_frame_types = [], [], []
1083
+ for image, timestamp, frame_type in zip(images, timestamps, frame_types):
1084
+ if start_time <= timestamp <= end_time:
1085
+ cur_images.append(image.copy())
1086
+ cur_timestamps.append(timestamp)
1087
+ cur_frame_types.append(frame_type)
1088
+
1089
+ content[data_type] = cur_images
1090
+ content["num_frames"] = len(cur_images)
1091
+ content["timestamps"] = cur_timestamps
1092
+ content["frame_types"] = cur_frame_types
1093
+
1094
+ return new_conversation
1095
+
1096
+ def _gather_multimodal_data(self, conversation: Conversation):
1097
+ images = []
1098
+ clip_frame_types = []
1099
+ for message in conversation:
1100
+ if not isinstance(message["content"], (list, tuple)):
1101
+ continue
1102
+ for content in message["content"]:
1103
+ if not isinstance(content, dict):
1104
+ continue
1105
+ if content["type"] == "video":
1106
+ video = content["video"]
1107
+ assert is_valid_video(video), f"Invalid video data: {video}."
1108
+ images.append(("video", video))
1109
+ clip_frame_types.append(content.get("frame_types", None))
1110
+ elif content["type"] == "image":
1111
+ image = content["image"]
1112
+ images.append(("image", image))
1113
+ clip_frame_types.append(None)
1114
+ if len(images) == 0:
1115
+ return None, None
1116
+ return images, clip_frame_types
1117
+
1118
+ def _process_conversation_with_label(
1119
+ self,
1120
+ conversation: Conversation,
1121
+ image_inputs: Dict[str, Any],
1122
+ **kwargs,
1123
+ ):
1124
+ assert kwargs.pop("return_tensors", "pt") == "pt", "Only PyTorch tensors are supported when return_labels=True."
1125
+ assert not "add_generation_prompt" in kwargs, "'add_generation_prompt' argument is not supported when return_labels=True."
1126
+
1127
+ output_kwargs = self._merge_kwargs(
1128
+ PenguinVLQwen3ProcessorKwargs,
1129
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
1130
+ **kwargs,
1131
+ )
1132
+ output_kwargs["chat_template_kwargs"].pop("add_generation_prompt")
1133
+
1134
+ grid_sizes = self._get_downsampled_grid_sizes(image_inputs)
1135
+ text_inputs = {"input_ids": [], "labels": []}
1136
+ sample_types_list = []
1137
+ image_idx = 0
1138
+
1139
+ for message_idx, message in enumerate(conversation):
1140
+ prompt = self.apply_chat_template(
1141
+ [message],
1142
+ tokenize=False,
1143
+ add_generation_prompt=False,
1144
+ **output_kwargs["chat_template_kwargs"],
1145
+ )
1146
+ prompt_chunks = prompt.split(DEFAULT_IMAGE_TOKEN)
1147
+ prompt = []
1148
+ for chunk_idx in range(len(prompt_chunks) - 1):
1149
+ prompt.append(prompt_chunks[chunk_idx])
1150
+ num_tokens = self._get_visual_seq_len(grid_sizes[image_idx])
1151
+ prompt.append(DEFAULT_IMAGE_TOKEN * num_tokens)
1152
+ image_idx += 1
1153
+ prompt.append(prompt_chunks[-1])
1154
+ prompt = "".join(prompt)
1155
+
1156
+ # TODO: support attention_mask, position_ids, etc.
1157
+ input_ids = self.tokenizer.encode(prompt, return_tensors="pt", **output_kwargs["text_kwargs"])[0]
1158
+ text_inputs["input_ids"].append(input_ids)
1159
+
1160
+ targets = torch.full_like(input_ids, IGNORE_INDEX)
1161
+ sample_types = torch.full_like(input_ids, IGNORE_INDEX)
1162
+ if message["role"] == "assistant":
1163
+ targets[self.generation_prompt_length:-1] = input_ids[self.generation_prompt_length:-1].clone()
1164
+ # elif message["role"] == "stream":
1165
+ # diff = torch.diff((input_ids == self.image_token_id).float())
1166
+ # image_end_indices = torch.nonzero(diff < 0)[:, 0]
1167
+ # targets[image_end_indices + 1] = input_ids[image_end_indices + 1]
1168
+ # sample_types = targets.clone()
1169
+ # sample_types[torch.logical_and(sample_types > 0, sample_types != self.eos_token_id)] = 0
1170
+ # targets[-2] = input_ids[-2] # <|im_end|>
1171
+
1172
+ if message_idx > 0 and conversation[message_idx - 1]["role"] == "stream":
1173
+ targets[0] = input_ids[0]
1174
+ # TODO: consider non-special tokens
1175
+ sample_types[0] = input_ids[0]
1176
+
1177
+ text_inputs["labels"].append(targets)
1178
+ sample_types_list.append(sample_types)
1179
+
1180
+ # Negative sampling for streaming data
1181
+ text_inputs = {k: torch.cat(v) for k, v in text_inputs.items()}
1182
+ sample_types = torch.cat(sample_types_list)
1183
+ types, counts = torch.unique(sample_types[sample_types > -1], return_counts=True)
1184
+
1185
+ if len(types) > 0:
1186
+ target_num_samples = counts.amin()
1187
+ for type_id, type_count in zip(types, counts):
1188
+ if type_count > target_num_samples:
1189
+ indices = torch.nonzero(sample_types == type_id)[:, 0]
1190
+ random_selector = torch.randperm(indices.size(0))[:-target_num_samples]
1191
+ text_inputs["labels"][indices[random_selector]] = IGNORE_INDEX
1192
+ # sample_types[indices[random_selector]] = -1
1193
+
1194
+ assert len(grid_sizes) == image_idx, "Number of images does not match the number of image tokens in the text."
1195
+
1196
+ return text_inputs
1197
+
1198
+ def _process_conversation_without_label(
1199
+ self,
1200
+ conversation: Conversation,
1201
+ image_inputs: Dict[str, Any],
1202
+ **kwargs,
1203
+ ):
1204
+ output_kwargs = self._merge_kwargs(
1205
+ PenguinVLQwen3ProcessorKwargs,
1206
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
1207
+ **kwargs,
1208
+ )
1209
+ prompt = self.apply_chat_template(
1210
+ conversation,
1211
+ tokenize=False,
1212
+ **output_kwargs["chat_template_kwargs"],
1213
+ )
1214
+ return self.process_text(prompt, image_inputs, **output_kwargs["text_kwargs"])
1215
+
1216
+ def _process_conversation(
1217
+ self,
1218
+ conversation: Conversation,
1219
+ images: Optional[Union[BatchedImage, BatchedNamedImage]] = None,
1220
+ return_labels: bool = False,
1221
+ **kwargs: Unpack[PenguinVLQwen3ProcessorKwargs],
1222
+ ) -> BatchFeature:
1223
+ assert isinstance(conversation, list), "Conversation must be a list of messages."
1224
+
1225
+ frame_types = None
1226
+ if images is None:
1227
+ conversation = self._load_multimodal_data(conversation)
1228
+ images, frame_types = self._gather_multimodal_data(conversation)
1229
+
1230
+ output_kwargs = self._merge_kwargs(
1231
+ PenguinVLQwen3ProcessorKwargs,
1232
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
1233
+ **kwargs,
1234
+ )
1235
+
1236
+ if images is not None:
1237
+ image_kwargs = output_kwargs["images_kwargs"]
1238
+ if frame_types is not None:
1239
+ image_kwargs["frame_types"] = frame_types
1240
+ image_inputs = self.process_images(images, **image_kwargs)
1241
+ else:
1242
+ image_inputs = {}
1243
+
1244
+ if return_labels:
1245
+ text_inputs = self._process_conversation_with_label(conversation, image_inputs, **kwargs)
1246
+ else:
1247
+ text_inputs = self._process_conversation_without_label(conversation, image_inputs, **kwargs)
1248
+
1249
+ return BatchFeature(data={**text_inputs, **image_inputs})
1250
+
1251
+ def _process_plain(
1252
+ self,
1253
+ text: Union[TextInput, PreTokenizedInput] = None,
1254
+ images: Optional[Union[BatchedImage, BatchedNamedImage]] = None,
1255
+ return_labels: bool = False,
1256
+ **kwargs: Unpack[PenguinVLQwen3ProcessorKwargs],
1257
+ ) -> BatchFeature:
1258
+ if text is None:
1259
+ raise ValueError("You must provide 'text' or 'message'.")
1260
+ if return_labels:
1261
+ raise ValueError("return_labels is not supported for plain text processing.")
1262
+
1263
+ output_kwargs = self._merge_kwargs(
1264
+ PenguinVLQwen3ProcessorKwargs,
1265
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
1266
+ **kwargs,
1267
+ )
1268
+
1269
+ if images is not None:
1270
+ image_inputs = self.process_images(images, **output_kwargs["images_kwargs"])
1271
+ else:
1272
+ image_inputs = {}
1273
+
1274
+ text_inputs = self.process_text(text, image_inputs, **output_kwargs["text_kwargs"])
1275
+
1276
+ return BatchFeature(data={**text_inputs, **image_inputs})
1277
+
1278
+ def process_images(self, images: Union[BatchedImage, BatchedNamedImage], **kwargs):
1279
+ modals, images = make_batched_images(images)
1280
+ if not "merge_size" in kwargs:
1281
+ kwargs["merge_size"] = [
1282
+ self.image_merge_size if modal == "image" else self.video_merge_size
1283
+ for modal in modals
1284
+ ]
1285
+ image_inputs = self.image_processor(images=images, **kwargs)
1286
+ expanded_modals = []
1287
+ for modal, img in zip(modals, images):
1288
+ num_frames = len(img) if is_valid_video(img) else 1
1289
+ expanded_modals.extend([modal] * num_frames)
1290
+ image_inputs["modals"] = expanded_modals
1291
+ return image_inputs
1292
+
1293
+ def process_text(
1294
+ self,
1295
+ text: TextInput,
1296
+ image_inputs: Dict[str, Any],
1297
+ **kwargs,
1298
+ ):
1299
+ grid_sizes = self._get_downsampled_grid_sizes(image_inputs)
1300
+
1301
+ kwargs.pop("padding")
1302
+ kwargs.pop("padding_side")
1303
+
1304
+ image_idx = 0
1305
+ while DEFAULT_IMAGE_TOKEN in text:
1306
+ num_tokens = self._get_visual_seq_len(grid_sizes[image_idx])
1307
+ text = text.replace(DEFAULT_IMAGE_TOKEN, "<placeholder>" * num_tokens, 1)
1308
+ image_idx += 1
1309
+ text = text.replace("<placeholder>", DEFAULT_IMAGE_TOKEN)
1310
+
1311
+ assert len(grid_sizes) == image_idx, "Number of images does not match the number of image tokens in the text."
1312
+
1313
+ text_inputs = self.tokenizer(text, **kwargs)
1314
+ return text_inputs
1315
+
1316
+ def __call__(
1317
+ self,
1318
+ text: Optional[TextInput] = None,
1319
+ conversation: Optional[Conversation] = None,
1320
+ images: Optional[Union[BatchedImage, BatchedNamedImage]] = None,
1321
+ return_labels: bool = False,
1322
+ **kwargs: Unpack[PenguinVLQwen3ProcessorKwargs],
1323
+ ) -> BatchFeature:
1324
+ if conversation is not None:
1325
+ if text is not None:
1326
+ raise ValueError("You cannot provide 'message' with 'text'.")
1327
+ return self._process_conversation(conversation, images, return_labels, **kwargs)
1328
+ return self._process_plain(text, images, return_labels, **kwargs)
1329
+
1330
+ def batch_decode(self, *args, **kwargs):
1331
+ return self.tokenizer.batch_decode(*args, **kwargs)
1332
+
1333
+ def decode(self, *args, **kwargs):
1334
+ return self.tokenizer.decode(*args, **kwargs)
1335
+
1336
+ def apply_chat_template(
1337
+ self,
1338
+ conversation: Conversation,
1339
+ chat_template: Optional[str] = None,
1340
+ tokenize: bool = False,
1341
+ add_system_prompt: bool = False,
1342
+ add_generation_prompt: bool = False,
1343
+ add_think_prompt: bool = False,
1344
+ image_token: Optional[str] = DEFAULT_IMAGE_TOKEN,
1345
+ **kwargs,
1346
+ ) -> str:
1347
+ """
1348
+ Similar to the `apply_chat_template` method on tokenizers, this method applies a Jinja template to input
1349
+ conversations to turn them into a single tokenizable string.
1350
+
1351
+ Args:
1352
+ conversation (`List[Dict, str, str]`):
1353
+ The conversation to format.
1354
+ chat_template (`Optional[str]`, *optional*):
1355
+ The Jinja template to use for formatting the conversation. If not provided, the tokenizer's
1356
+ chat template is used.
1357
+ tokenize (`bool`, *optional*, defaults to `False`):
1358
+ Whether to tokenize the output or not.
1359
+ add_system_prompt (`bool`, *optional*, defaults to `False`):
1360
+ Whether to add the system prompt to the output or not.
1361
+ add_generation_prompt (`bool`, *optional*, defaults to `False`):
1362
+ Whether to add the generation prompt to the output or not.
1363
+ image_token (`Optional[str]`, *optional*, defaults to `<image>`):
1364
+ The token to use for indicating images in the conversation.
1365
+ **kwargs:
1366
+ Additional keyword arguments
1367
+ """
1368
+
1369
+ if chat_template is None:
1370
+ if self.chat_template is not None:
1371
+ chat_template = self.chat_template
1372
+ else:
1373
+ raise ValueError(
1374
+ "No chat template is set for this processor. Please either set the `chat_template` attribute, "
1375
+ "or provide a chat template as an argument. See "
1376
+ "https://huggingface.co/docs/transformers/main/en/chat_templating for more information."
1377
+ )
1378
+ return self.tokenizer.apply_chat_template(
1379
+ conversation,
1380
+ chat_template=chat_template,
1381
+ tokenize=tokenize,
1382
+ add_system_prompt=add_system_prompt,
1383
+ add_generation_prompt=add_generation_prompt,
1384
+ add_think_prompt=add_think_prompt,
1385
+ image_token=image_token,
1386
+ **kwargs
1387
+ )
1388
+
1389
+ @property
1390
+ def model_input_names(self):
1391
+ tokenizer_input_names = self.tokenizer.model_input_names
1392
+ image_processor_input_names = self.image_processor.model_input_names
1393
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) + ["modals"]
1394
+
1395
+ # modified from transformers.ProcessorMixin
1396
+ def _merge_kwargs(
1397
+ self,
1398
+ ModelProcessorKwargs: ProcessingKwargs,
1399
+ tokenizer_init_kwargs: Optional[Dict] = None,
1400
+ **kwargs,
1401
+ ) -> Dict[str, Dict]:
1402
+ """
1403
+ Method to merge dictionaries of kwargs cleanly separated by modality within a Processor instance.
1404
+ The order of operations is as follows:
1405
+ 1) kwargs passed as before have highest priority to preserve BC.
1406
+ ```python
1407
+ high_priority_kwargs = {"crop_size" = {"height": 222, "width": 222}, "padding" = "max_length"}
1408
+ processor(..., **high_priority_kwargs)
1409
+ ```
1410
+ 2) kwargs passed as modality-specific kwargs have second priority. This is the recommended API.
1411
+ ```python
1412
+ processor(..., text_kwargs={"padding": "max_length"}, images_kwargs={"crop_size": {"height": 222, "width": 222}}})
1413
+ ```
1414
+ 3) kwargs passed during instantiation of a modality processor have fourth priority.
1415
+ ```python
1416
+ tokenizer = tokenizer_class(..., {"padding": "max_length"})
1417
+ image_processor = image_processor_class(...)
1418
+ processor(tokenizer, image_processor) # will pass max_length unless overriden by kwargs at call
1419
+ ```
1420
+ 4) defaults kwargs specified at processor level have lowest priority.
1421
+ ```python
1422
+ class MyProcessingKwargs(ProcessingKwargs, CommonKwargs, TextKwargs, ImagesKwargs, total=False):
1423
+ _defaults = {
1424
+ "text_kwargs": {
1425
+ "padding": "max_length",
1426
+ "max_length": 64,
1427
+ },
1428
+ }
1429
+ ```
1430
+ Args:
1431
+ ModelProcessorKwargs (`ProcessingKwargs`):
1432
+ Typed dictionary of kwargs specifically required by the model passed.
1433
+ tokenizer_init_kwargs (`Dict`, *optional*):
1434
+ Dictionary of kwargs the tokenizer was instantiated with and need to take precedence over defaults.
1435
+
1436
+ Returns:
1437
+ output_kwargs (`Dict`):
1438
+ Dictionary of per-modality kwargs to be passed to each modality-specific processor.
1439
+
1440
+ """
1441
+ # Initialize dictionaries
1442
+ output_kwargs = {
1443
+ "text_kwargs": {},
1444
+ "images_kwargs": {},
1445
+ "audio_kwargs": {},
1446
+ "videos_kwargs": {},
1447
+ "chat_template_kwargs": {},
1448
+ "common_kwargs": {},
1449
+ }
1450
+
1451
+ default_kwargs = {
1452
+ "text_kwargs": {},
1453
+ "images_kwargs": {},
1454
+ "audio_kwargs": {},
1455
+ "videos_kwargs": {},
1456
+ "chat_template_kwargs": {},
1457
+ "common_kwargs": {},
1458
+ }
1459
+
1460
+ used_keys = set()
1461
+
1462
+ # get defaults from set model processor kwargs if they exist
1463
+ for modality in default_kwargs:
1464
+ default_kwargs[modality] = ModelProcessorKwargs._defaults.get(modality, {}).copy()
1465
+ # update defaults with arguments from tokenizer init
1466
+ for modality_key in ModelProcessorKwargs.__annotations__[modality].__annotations__.keys():
1467
+ # init with tokenizer init kwargs if necessary
1468
+ if modality_key in tokenizer_init_kwargs:
1469
+ value = (
1470
+ getattr(self.tokenizer, modality_key)
1471
+ if hasattr(self.tokenizer, modality_key)
1472
+ else tokenizer_init_kwargs[modality_key]
1473
+ )
1474
+ default_kwargs[modality][modality_key] = value
1475
+ # now defaults kwargs are updated with the tokenizers defaults.
1476
+ # pass defaults to output dictionary
1477
+ output_kwargs.update(default_kwargs)
1478
+
1479
+ # update modality kwargs with passed kwargs
1480
+ non_modality_kwargs = set(kwargs) - set(output_kwargs)
1481
+ for modality in output_kwargs:
1482
+ for modality_key in ModelProcessorKwargs.__annotations__[modality].__annotations__.keys():
1483
+ # check if we received a structured kwarg dict or not to handle it correctly
1484
+ if modality in kwargs:
1485
+ kwarg_value = kwargs[modality].pop(modality_key, "__empty__")
1486
+ # check if this key was passed as a flat kwarg.
1487
+ if kwarg_value != "__empty__" and modality_key in non_modality_kwargs:
1488
+ raise ValueError(
1489
+ f"Keyword argument {modality_key} was passed two times:\n"
1490
+ f"in a dictionary for {modality} and as a **kwarg."
1491
+ )
1492
+ elif modality_key in kwargs:
1493
+ # we get a modality_key instead of popping it because modality-specific processors
1494
+ # can have overlapping kwargs
1495
+ kwarg_value = kwargs.get(modality_key, "__empty__")
1496
+ else:
1497
+ kwarg_value = "__empty__"
1498
+ if kwarg_value != "__empty__":
1499
+ output_kwargs[modality][modality_key] = kwarg_value
1500
+ used_keys.add(modality_key)
1501
+
1502
+ # Determine if kwargs is a flat dictionary or contains nested dictionaries
1503
+ if any(key in default_kwargs for key in kwargs):
1504
+ # kwargs is dictionary-based, and some keys match modality names
1505
+ for modality, subdict in kwargs.items():
1506
+ if modality in default_kwargs:
1507
+ for subkey, subvalue in subdict.items():
1508
+ if subkey not in used_keys:
1509
+ output_kwargs[modality][subkey] = subvalue
1510
+ used_keys.add(subkey)
1511
+ else:
1512
+ # kwargs is a flat dictionary
1513
+ for key in kwargs:
1514
+ if key not in used_keys:
1515
+ output_kwargs["common_kwargs"][key] = kwargs[key]
1516
+
1517
+ # all modality-specific kwargs are updated with common kwargs
1518
+ for modality in output_kwargs:
1519
+ output_kwargs[modality].update(output_kwargs["common_kwargs"])
1520
+ return output_kwargs
processor_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_penguinvl.PenguinVLQwen3Processor"
4
+ },
5
+ "fps": 1,
6
+ "image_merge_size": 1,
7
+ "max_frames": 180,
8
+ "processor_class": "PenguinVLQwen3Processor",
9
+ "video_merge_size": 2
10
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3de4265d6c1499ee2f7f7c2ec71004f59d8676ce0373cd32cbad37d40b945cbd
3
+ size 11423788
tokenizer_config.json ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": true,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": true,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ },
213
+ "151669": {
214
+ "content": "<image>",
215
+ "lstrip": false,
216
+ "normalized": false,
217
+ "rstrip": false,
218
+ "single_word": false,
219
+ "special": true
220
+ },
221
+ "151670": {
222
+ "content": "<|stream_start|>",
223
+ "lstrip": false,
224
+ "normalized": false,
225
+ "rstrip": false,
226
+ "single_word": false,
227
+ "special": true
228
+ },
229
+ "151671": {
230
+ "content": "<|stream_end|>",
231
+ "lstrip": false,
232
+ "normalized": false,
233
+ "rstrip": false,
234
+ "single_word": false,
235
+ "special": true
236
+ },
237
+ "151672": {
238
+ "content": "<|audio|>",
239
+ "lstrip": false,
240
+ "normalized": false,
241
+ "rstrip": false,
242
+ "single_word": false,
243
+ "special": true
244
+ },
245
+ "151673": {
246
+ "content": "<|audio_start|>",
247
+ "lstrip": false,
248
+ "normalized": false,
249
+ "rstrip": false,
250
+ "single_word": false,
251
+ "special": true
252
+ },
253
+ "151674": {
254
+ "content": "<|audio_end|>",
255
+ "lstrip": false,
256
+ "normalized": false,
257
+ "rstrip": false,
258
+ "single_word": false,
259
+ "special": true
260
+ }
261
+ },
262
+ "additional_special_tokens": [
263
+ "<|im_start|>",
264
+ "<|im_end|>",
265
+ "<|object_ref_start|>",
266
+ "<|object_ref_end|>",
267
+ "<|box_start|>",
268
+ "<|box_end|>",
269
+ "<|quad_start|>",
270
+ "<|quad_end|>",
271
+ "<|vision_start|>",
272
+ "<|vision_end|>",
273
+ "<|vision_pad|>",
274
+ "<|image_pad|>",
275
+ "<|video_pad|>"
276
+ ],
277
+ "bos_token": null,
278
+ "chat_template": "\n{%- set identifier = 'im' %}\n{% for message in messages %}\n {% if message['role'] == 'stream' %}\n {% set identifier = 'stream' %}\n {% else %}\n {% set identifier = 'im' %}\n {% endif %}\n {% if message['role'] is not none %}\n {{- '<|' + identifier + '_start|>' + message['role'] + '\n' -}}\n {% endif %}\n {% if message['content'] is string %}\n {{- message['content'] + '<|' + identifier + '_end|>\n' -}}\n {% else %}\n {% for content in message['content'] %}\n {% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}\n {% if 'time' in content %}\n {{- 'Time ' + content['time'] | round(1) | string + 's: ' -}}\n {% endif %}\n {{- image_token + '\n' -}}\n {% elif content['type'] == 'video' or 'video' in content or 'video_url' in content %}\n {% for i in range(content['num_frames']) %}\n {% if 'timestamps' in content and content['timestamps']|length > 0 %}\n {{- 'Time ' + content['timestamps'][i] | round(1) | string + 's:' -}}\n {% endif %}\n {% if i < content['num_frames'] - 1 %}\n {{- image_token + ',' -}}\n {% else %}\n {{- image_token + '\n' -}}\n {% endif %}\n {% endfor %}\n {% elif content['type'] == 'text' or 'text' in content %}\n {{- content['text'] -}}\n {% endif %}\n {% endfor %}\n {% if message['role'] is not none %}\n {{- '<|' + identifier + '_end|>\n' -}}\n {% endif %}\n {% endif %}\n{% endfor %}\n{% if add_generation_prompt %}\n {{- '<|im_start|>assistant\n' -}}\n {% if not add_think_prompt %}\n {{- '<think>\n\n</think>\n\n' -}}\n {% endif %}\n{% endif %}\n",
279
+ "clean_up_tokenization_spaces": false,
280
+ "eos_token": "<|im_end|>",
281
+ "errors": "replace",
282
+ "extra_special_tokens": {},
283
+ "model_max_length": 32768,
284
+ "pad_token": "<|endoftext|>",
285
+ "padding_side": "right",
286
+ "processor_class": "PenguinVLQwen3Processor",
287
+ "split_special_tokens": false,
288
+ "tokenizer_class": "Qwen2Tokenizer",
289
+ "unk_token": null
290
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff