exiawsh commited on
Commit
cf6360b
·
verified ·
1 Parent(s): 60f1e49

上传模型

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
+ training_log.txt filter=lfs diff=lfs merge=lfs -text
added_tokens.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</box>": 151673,
3
+ "</img>": 151671,
4
+ "</interval>": 151679,
5
+ "</quad>": 151675,
6
+ "</ref>": 151677,
7
+ "</think>": 151668,
8
+ "</tool_call>": 151658,
9
+ "</tool_response>": 151666,
10
+ "<IMG_CONTEXT>": 151669,
11
+ "<box>": 151672,
12
+ "<img>": 151670,
13
+ "<interval>": 151678,
14
+ "<quad>": 151674,
15
+ "<ref>": 151676,
16
+ "<think>": 151667,
17
+ "<tool_call>": 151657,
18
+ "<tool_response>": 151665,
19
+ "<|box_end|>": 151649,
20
+ "<|box_start|>": 151648,
21
+ "<|endoftext|>": 151643,
22
+ "<|file_sep|>": 151664,
23
+ "<|fim_middle|>": 151660,
24
+ "<|fim_pad|>": 151662,
25
+ "<|fim_prefix|>": 151659,
26
+ "<|fim_suffix|>": 151661,
27
+ "<|im_end|>": 151645,
28
+ "<|im_start|>": 151644,
29
+ "<|image_pad|>": 151655,
30
+ "<|object_ref_end|>": 151647,
31
+ "<|object_ref_start|>": 151646,
32
+ "<|quad_end|>": 151651,
33
+ "<|quad_start|>": 151650,
34
+ "<|repo_name|>": 151663,
35
+ "<|video_pad|>": 151656,
36
+ "<|vision_end|>": 151653,
37
+ "<|vision_pad|>": 151654,
38
+ "<|vision_start|>": 151652
39
+ }
all_results.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 1.0,
3
+ "total_flos": 5.461479216500315e+20,
4
+ "train_loss": 0.09150631395949999,
5
+ "train_runtime": 9502.0046,
6
+ "train_samples": 166521,
7
+ "train_samples_per_second": 17.525,
8
+ "train_steps_per_second": 0.617
9
+ }
chat_template.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "chat_template": "{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n{% endif %}<|im_start|>{{ message['role'] }}\n{% if message['content'] is string %}{{ message['content'] }}<|im_end|>\n{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}<image {{ image_count.value }}>{% endif %}<image-{{ image_count.value }}>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}<video {{ video_count.value }}>{% endif %}<video-{{ video_count.value }}>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}"
3
+ }
config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_attn_implementation": "flash_attention_2",
3
+ "_commit_hash": null,
4
+ "architectures": [
5
+ "Eagle3_VLForConditionalGeneration"
6
+ ],
7
+ "downsample_ratio": 0.5,
8
+ "dynamic_image_size": false,
9
+ "image_token_index": 151669,
10
+ "loss_version": "efficient_v2_cp_head",
11
+ "max_dynamic_tiles": 12,
12
+ "min_dynamic_tiles": 1,
13
+ "mlp_checkpoint": false,
14
+ "mlp_connector_layers": 2,
15
+ "model_type": "eagle_3_vl",
16
+ "pad2square": false,
17
+ "select_layer": -1,
18
+ "text_config": {
19
+ "_attn_implementation_autoset": true,
20
+ "_name_or_path": "Qwen/Qwen3-1.7B",
21
+ "architectures": [
22
+ "Qwen3ForCausalLM"
23
+ ],
24
+ "attention_bias": false,
25
+ "attention_dropout": 0.0,
26
+ "bos_token_id": 151643,
27
+ "eos_token_id": 151645,
28
+ "head_dim": 128,
29
+ "hidden_act": "silu",
30
+ "hidden_size": 2048,
31
+ "initializer_range": 0.02,
32
+ "intermediate_size": 6144,
33
+ "max_position_embeddings": 40960,
34
+ "max_window_layers": 28,
35
+ "model_type": "qwen3",
36
+ "num_attention_heads": 16,
37
+ "num_hidden_layers": 28,
38
+ "num_key_value_heads": 8,
39
+ "rms_norm_eps": 1e-06,
40
+ "rope_scaling": null,
41
+ "rope_theta": 1000000,
42
+ "sliding_window": null,
43
+ "tie_word_embeddings": true,
44
+ "torch_dtype": "bfloat16",
45
+ "use_cache": false,
46
+ "use_sliding_window": false,
47
+ "vocab_size": 151680
48
+ },
49
+ "torch_dtype": "bfloat16",
50
+ "transformers_version": null,
51
+ "use_backbone_lora": 0,
52
+ "use_llm_lora": 0,
53
+ "use_pixel_shuffle": true,
54
+ "use_thumbnail": false,
55
+ "vision_config": {
56
+ "_attn_implementation_autoset": true,
57
+ "attention_dropout": 0.0,
58
+ "full_attention_indexes": [
59
+ 7,
60
+ 14,
61
+ 21,
62
+ 26
63
+ ],
64
+ "hidden_act": "gelu_pytorch_tanh",
65
+ "hidden_size": 1152,
66
+ "intermediate_size": 4304,
67
+ "layer_norm_eps": 1e-06,
68
+ "model_type": "siglip2_vision_model",
69
+ "num_attention_heads": 16,
70
+ "num_channels": 3,
71
+ "num_hidden_layers": 27,
72
+ "num_patches": 256,
73
+ "patch_size": 14,
74
+ "torch_dtype": "bfloat16",
75
+ "use_rope": false,
76
+ "use_windows_attn": true,
77
+ "window_size": 14
78
+ }
79
+ }
configuration_eagle3_vl.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+
3
+ from eaglevl.model.phi3.configuration_phi3 import Phi3Config
4
+ from eaglevl.model.llama.configuration_llama import LlamaConfig
5
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
6
+ from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
7
+ from transformers.configuration_utils import PretrainedConfig
8
+ from transformers.utils import logging
9
+ from transformers.models.siglip.configuration_siglip import SiglipVisionConfig
10
+ from .modeling_siglip2 import Siglip2VisionConfig
11
+ from eaglevl.model.c_radio.radio_model import RADIOConfig
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ class Eagle3_VLConfig(PretrainedConfig):
16
+ model_type = 'eagle_3_vl'
17
+ is_composition = True
18
+ sub_configs = {"vision_config": SiglipVisionConfig, "text_config": Qwen2Config}
19
+ def __init__(
20
+ self,
21
+ vision_config=None,
22
+ text_config=None,
23
+ use_backbone_lora=0,
24
+ use_llm_lora=0,
25
+ pad2square=False,
26
+ select_layer=-4,
27
+ downsample_ratio=0.5,
28
+ template=None,
29
+ loss_version='v1',
30
+ mlp_checkpoint=False,
31
+ image_token_index=151667,
32
+ **kwargs):
33
+ super().__init__(**kwargs)
34
+
35
+ if vision_config is None:
36
+ vision_config = {'model_type': 'siglip_vision_model'}
37
+ logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')
38
+
39
+ if text_config is None:
40
+ text_config = {'architectures': ['Qwen2ForCausalLM']}
41
+ logger.info('text_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
42
+
43
+ if vision_config['model_type'] == 'siglip_vision_model':
44
+ self.vision_config = SiglipVisionConfig(**vision_config)
45
+ elif vision_config['model_type'] == 'siglip2_vision_model':
46
+ self.vision_config = Siglip2VisionConfig(**vision_config)
47
+ elif vision_config['model_type'] == 'intern_vit_6b':
48
+ self.vision_config = InternVisionConfig(**vision_config)
49
+ elif vision_config['model_type'] == 'radio':
50
+ self.vision_config = RADIOConfig(**vision_config)
51
+ else:
52
+ raise ValueError('Unsupported model_type: {}'.format(vision_config['model_type']))
53
+
54
+
55
+ if text_config['architectures'][0] == 'LlamaForCausalLM':
56
+ self.text_config = LlamaConfig(**text_config)
57
+ elif text_config['architectures'][0] == 'Phi3ForCausalLM':
58
+ self.text_config = Phi3Config(**text_config)
59
+ elif text_config['architectures'][0] == 'Qwen2ForCausalLM':
60
+ self.text_config = Qwen2Config(**text_config)
61
+ elif text_config['architectures'][0] == 'Qwen3ForCausalLM':
62
+ self.text_config = Qwen3Config(**text_config)
63
+ else:
64
+ raise ValueError('Unsupported architecture: {}'.format(text_config['architectures'][0]))
65
+ self.use_backbone_lora = use_backbone_lora
66
+ self.use_llm_lora = use_llm_lora
67
+ self.mlp_checkpoint = mlp_checkpoint
68
+ self.pad2square = pad2square
69
+ self.select_layer = select_layer
70
+ self.downsample_ratio = downsample_ratio
71
+ self.template = template
72
+ self.loss_version = loss_version
73
+ self.tie_word_embeddings = self.text_config.tie_word_embeddings
74
+ self.image_token_index = image_token_index
75
+
76
+ def to_dict(self):
77
+ """
78
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
79
+
80
+ Returns:
81
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
82
+ """
83
+ output = copy.deepcopy(self.__dict__)
84
+ output['vision_config'] = self.vision_config.to_dict()
85
+ output['text_config'] = self.text_config.to_dict()
86
+ output['model_type'] = self.__class__.model_type
87
+ output['use_backbone_lora'] = self.use_backbone_lora
88
+ output['use_llm_lora'] = self.use_llm_lora
89
+ output['select_layer'] = self.select_layer
90
+ output['downsample_ratio'] = self.downsample_ratio
91
+ output['template'] = self.template
92
+ output['image_token_index'] = self.image_token_index
93
+ output['_attn_implementation'] = self._attn_implementation
94
+ output['_attn_implementation_autoset'] = self._attn_implementation_autoset
95
+ return output
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151645,
5
+ "transformers_version": "4.51.0"
6
+ }
image_processing_eagle3_vl_fast.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # NVIDIA
3
+ # Copyright (c) 2025 NVIDIA
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+
7
+ # copy from https://github.com/huggingface/transformers/blob/main/src/transformers/models/llava_onevision/image_processing_llava_onevision_fast.py
8
+ from typing import List, Optional, Union
9
+
10
+ from transformers.image_processing_utils import BatchFeature, get_patch_output_size, select_best_resolution
11
+ from transformers.image_processing_utils_fast import (
12
+ BASE_IMAGE_PROCESSOR_FAST_DOCSTRING,
13
+ BASE_IMAGE_PROCESSOR_FAST_DOCSTRING_PREPROCESS,
14
+ BaseImageProcessorFast,
15
+ DefaultFastImageProcessorKwargs,
16
+ divide_to_patches,
17
+ group_images_by_shape,
18
+ reorder_images,
19
+ )
20
+ from transformers.image_utils import (
21
+ OPENAI_CLIP_MEAN,
22
+ OPENAI_CLIP_STD,
23
+ IMAGENET_STANDARD_MEAN, # 0.5, 0.5, 0.5
24
+ IMAGENET_STANDARD_STD, # 0.5, 0.5, 0.5
25
+ ChannelDimension,
26
+ ImageInput,
27
+ VideoInput,
28
+ PILImageResampling,
29
+ SizeDict,
30
+ get_image_size,
31
+ make_flat_list_of_images,
32
+ make_batched_videos,
33
+ validate_kwargs
34
+ )
35
+ from transformers.processing_utils import Unpack
36
+ from transformers.utils import TensorType, add_start_docstrings, is_torch_available, is_torchvision_v2_available
37
+
38
+
39
+ if is_torch_available():
40
+ import torch
41
+ if is_torchvision_v2_available():
42
+ from transformers.image_utils import pil_torch_interpolation_mapping
43
+
44
+ from torchvision.transforms.v2 import functional as F
45
+ else:
46
+ from torchvision.transforms import functional as F
47
+
48
+ def crop(img: torch.Tensor, left: int, top: int, right: int, bottom: int) -> torch.Tensor:
49
+ """Crop the given numpy array.
50
+
51
+ Args:
52
+ img (torch.Tensor): Image to be cropped. Format should be (C, H, W).
53
+ left (int): The left coordinate of the crop box.
54
+ top (int): The top coordinate of the crop box.
55
+ right (int): The right coordinate of the crop box.
56
+ bottom (int): The bottom coordinate of the crop box.
57
+
58
+ Returns:
59
+ torch.Tensor: Cropped image.
60
+ """
61
+ if not isinstance(img, torch.Tensor):
62
+ raise TypeError('img should be torch.Tensor. Got {}'.format(type(img)))
63
+
64
+ if img.ndim not in [2, 3]:
65
+ raise ValueError('Image should have 2 or 3 dimensions. Got {}'.format(img.ndim))
66
+
67
+ img_height = img.shape[1]
68
+ img_width = img.shape[2]
69
+ if top < 0 or left < 0 or bottom > img_height or right > img_width:
70
+ raise ValueError('Crop coordinates out of bounds')
71
+
72
+ if top >= bottom or left >= right:
73
+ raise ValueError('Invalid crop coordinates')
74
+
75
+ return img[:, top:bottom, left:right]
76
+
77
+
78
+ class Eagle3_VLFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
79
+ do_pad: Optional[bool]
80
+
81
+
82
+ @add_start_docstrings(
83
+ "Constructs a fast ConvNeXT image processor. Based on [`SiglipImageProcessor`] with incorporation of processing each video frame.",
84
+ BASE_IMAGE_PROCESSOR_FAST_DOCSTRING,
85
+ """
86
+ image_grid_pinpoints (`List[List[int]]`, *optional*):
87
+ A list of possible resolutions to use for processing high resolution images. The best resolution is selected
88
+ based on the original size of the image. Can be overridden by `image_grid_pinpoints` in the `preprocess`
89
+ method. Not used for processing videos.
90
+ do_pad (`bool`, *optional*):
91
+ Whether to pad the image. If `True`, will pad the patch dimension of the images in the batch to the largest
92
+ number of patches in the batch. Padding will be applied to the bottom and right with zeros.
93
+ """,
94
+ )
95
+ class Eagle3_VLImageProcessorFast(BaseImageProcessorFast):
96
+ resample = PILImageResampling.BICUBIC
97
+ image_mean = IMAGENET_STANDARD_MEAN
98
+ image_std = IMAGENET_STANDARD_STD
99
+ size = {"height": 448, "width": 448}
100
+ default_to_square = False
101
+ crop_size = None
102
+ do_resize = True
103
+ do_center_crop = None
104
+ do_rescale = True
105
+ do_normalize = True
106
+ do_convert_rgb = True
107
+ do_pad = True
108
+ valid_kwargs = Eagle3_VLFastImageProcessorKwargs
109
+ model_input_names = ["pixel_values_videos"]
110
+
111
+ def __init__(self, **kwargs: Unpack[Eagle3_VLFastImageProcessorKwargs]):
112
+ super().__init__(**kwargs)
113
+
114
+ @add_start_docstrings(
115
+ BASE_IMAGE_PROCESSOR_FAST_DOCSTRING_PREPROCESS,
116
+ """
117
+ do_pad (`bool`, *optional*):
118
+ Whether to pad the image. If `True`, will pad the patch dimension of the images in the batch to the largest
119
+ number of patches in the batch. Padding will be applied to the bottom and right with zeros.
120
+ """,
121
+ )
122
+ def preprocess(self, images: ImageInput, **kwargs: Unpack[Eagle3_VLFastImageProcessorKwargs]) -> BatchFeature:
123
+ return super().preprocess(images, **kwargs)
124
+
125
+ def _prepare_images_structure(
126
+ self,
127
+ images: ImageInput,
128
+ ) -> ImageInput:
129
+ """
130
+ Prepare the images structure for processing.
131
+
132
+ Args:
133
+ images (`ImageInput`):
134
+ The input images to process.
135
+
136
+ Returns:
137
+ `ImageInput`: The images with a valid nesting.
138
+ """
139
+ return make_flat_list_of_images(images)
140
+
141
+ def _preprocess(
142
+ self,
143
+ images: List["torch.Tensor"],
144
+ do_resize: bool,
145
+ size: SizeDict,
146
+ interpolation: Optional["F.InterpolationMode"],
147
+ do_center_crop: bool,
148
+ crop_size: SizeDict,
149
+ do_rescale: bool,
150
+ rescale_factor: float,
151
+ do_normalize: bool,
152
+ image_mean: Optional[Union[float, List[float]]],
153
+ image_std: Optional[Union[float, List[float]]],
154
+ do_pad: bool,
155
+ return_tensors: Optional[Union[str, TensorType]],
156
+ ) -> BatchFeature:
157
+
158
+ image_sizes = [get_image_size(image, channel_dim=ChannelDimension.FIRST) for image in images]
159
+
160
+ # Group images by size for further processing
161
+ # Needed in case do_resize is False, or resize returns images with different sizes
162
+ grouped_images, grouped_images_index = group_images_by_shape(images)
163
+ processed_images_grouped = {}
164
+ for shape, stacked_images in grouped_images.items():
165
+ # Fused rescale and normalize
166
+ stacked_images = self.rescale_and_normalize(
167
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
168
+ )
169
+ processed_images_grouped[shape] = stacked_images
170
+
171
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
172
+ processed_images = torch.stack(processed_images)
173
+
174
+ return BatchFeature(
175
+ data={"pixel_values": processed_images, "image_sizes": image_sizes}, tensor_type=return_tensors
176
+ )
177
+
178
+
179
+ def preprocess(self, images: ImageInput, videos: VideoInput=None, **kwargs: Unpack[Eagle3_VLFastImageProcessorKwargs]) -> BatchFeature:
180
+ validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self.valid_kwargs.__annotations__.keys())
181
+ # Set default kwargs from self. This ensures that if a kwarg is not provided
182
+ # by the user, it gets its default value from the instance, or is set to None.
183
+ for kwarg_name in self.valid_kwargs.__annotations__:
184
+ kwargs.setdefault(kwarg_name, getattr(self, kwarg_name, None))
185
+
186
+ # Extract parameters that are only used for preparing the input images
187
+ do_convert_rgb = kwargs.pop("do_convert_rgb")
188
+ input_data_format = kwargs.pop("input_data_format")
189
+ device = kwargs.pop("device")
190
+ # Prepare input images
191
+ if images is not None:
192
+ images = self._prepare_input_images(
193
+ images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
194
+ )
195
+
196
+ if videos is not None:
197
+ videos = self._prepare_input_images(
198
+ images=videos, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
199
+ )
200
+
201
+ # Update kwargs that need further processing before being validated
202
+ kwargs = self._further_process_kwargs(**kwargs)
203
+
204
+ # Validate kwargs
205
+ self._validate_preprocess_kwargs(**kwargs)
206
+
207
+ # torch resize uses interpolation instead of resample
208
+ resample = kwargs.pop("resample")
209
+ kwargs["interpolation"] = (
210
+ pil_torch_interpolation_mapping[resample] if isinstance(resample, (PILImageResampling, int)) else resample
211
+ )
212
+
213
+ # Pop kwargs that are not needed in _preprocess
214
+ kwargs.pop("default_to_square")
215
+ kwargs.pop("data_format")
216
+ if images is not None:
217
+ return self._preprocess(images, **kwargs)
218
+ elif videos is not None:
219
+ return self._preprocess(videos, **kwargs)
220
+
221
+ __all__ = ["Eagle3_VLImageProcessorFast"]
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ddd1319bb78e5dd3852b19fe670926403a9dd22127927b66fd019efdcac43fb4
3
+ size 4944136416
modeling_eagle3_vl.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # NVIDIA
3
+ # Copyright (c) 2025 NVIDIA
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+
7
+ import warnings
8
+ import inspect
9
+ from typing import Any, List, Optional, Tuple, Union
10
+ import torch
11
+ from torch import nn
12
+ import torch.distributed as dist
13
+ from torch.nn import CrossEntropyLoss
14
+ import torch.nn.functional as F
15
+ from transformers.models.qwen2.modeling_qwen2 import Qwen2ForCausalLM
16
+ from transformers.models.qwen3.modeling_qwen3 import Qwen3ForCausalLM
17
+ from transformers.models.llama.modeling_llama import LlamaForCausalLM
18
+ import torch.utils.checkpoint as cp
19
+ from transformers.models.siglip.modeling_siglip import SiglipVisionModel
20
+ from .modeling_siglip2 import Siglip2VisionModel
21
+ from peft import LoraConfig, get_peft_model
22
+ from transformers.generation import GenerationMixin
23
+ from transformers import GenerationConfig
24
+ from transformers.modeling_outputs import CausalLMOutputWithPast
25
+ from transformers.modeling_utils import PreTrainedModel
26
+ from transformers.utils import ModelOutput, logging
27
+ from .configuration_eagle3_vl import Eagle3_VLConfig
28
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
29
+ from collections import defaultdict
30
+ logger = logging.get_logger(__name__)
31
+
32
+ # copy from https://github.com/huggingface/transformers/blob/main/src/transformers/models/llava_onevision/modeling_llava_onevision.py#L241C1-L280C1
33
+ EAGLE3_VL_START_DOCSTRING = r"""
34
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
35
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
36
+ etc.)
37
+
38
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
39
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
40
+ and behavior.
41
+
42
+ Parameters:
43
+ config ([`Eagle3_VLConfig`]):
44
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
45
+ load the weights associated with the model, only the configuration. Check out the
46
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
47
+ """
48
+
49
+ @add_start_docstrings(
50
+ "The bare Eagle3_VL Model outputting raw hidden-states without any specific head on top.",
51
+ EAGLE3_VL_START_DOCSTRING,
52
+ )
53
+ class Eagle3_VLPreTrainedModel(PreTrainedModel):
54
+ config_class = Eagle3_VLConfig
55
+ base_model_prefix = "model"
56
+ main_input_name = 'input_ids'
57
+ supports_gradient_checkpointing = True
58
+ _no_split_modules = ["Qwen2DecoderLayer", "LlamaDecoderLayer" ,"Siglip2EncoderLayer", "SiglipEncoderLayer"]
59
+ _skip_keys_device_placement = "past_key_values"
60
+ _supports_flash_attn_2 = True
61
+ _supports_cache_class = True
62
+ _supports_static_cache = True
63
+ _supports_quantized_cache = True
64
+ _supports_sdpa = True
65
+
66
+ def _init_weights(self, module):
67
+ std = self.config.initializer_range
68
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
69
+ module.weight.data.normal_(mean=0.0, std=std)
70
+ if module.bias is not None:
71
+ module.bias.data.zero_()
72
+ elif isinstance(module, nn.Embedding):
73
+ module.weight.data.normal_(mean=0.0, std=std)
74
+ if module.padding_idx is not None:
75
+ module.weight.data[module.padding_idx].zero_()
76
+
77
+
78
+ class Eagle3_VLForConditionalGeneration(Eagle3_VLPreTrainedModel, GenerationMixin):
79
+ config_class = Eagle3_VLConfig
80
+ def __init__(self, config: Eagle3_VLConfig, vision_model=None, language_model=None):
81
+ super().__init__(config)
82
+
83
+ self.select_layer = config.select_layer
84
+ self.template = config.template
85
+ self.downsample_ratio = config.downsample_ratio
86
+ self.loss_version = config.loss_version
87
+ self.mlp_checkpoint = config.mlp_checkpoint
88
+
89
+ logger.info(f'mlp_checkpoint: {self.mlp_checkpoint}')
90
+ if vision_model is not None:
91
+ self.vision_model = vision_model
92
+ else:
93
+ if config.vision_config.model_type == 'intern_vit_6b':
94
+ self.vision_model = InternVisionModel(config.vision_config)
95
+ elif config.vision_config.model_type == 'siglip_vision_model':
96
+ config.vision_config._attn_implementation = 'flash_attention_2'
97
+ self.vision_model = SiglipVisionModel(config.vision_config)
98
+ elif config.vision_config.model_type == 'siglip2_vision_model':
99
+ config.vision_config._attn_implementation = 'flash_attention_2'
100
+ self.vision_model = Siglip2VisionModel(config.vision_config)
101
+ elif config.vision_config.model_type == 'radio':
102
+ self.vision_model = RADIOModel(config.vision_config)
103
+
104
+ if language_model is not None:
105
+ self.language_model = language_model
106
+ else:
107
+ if config.text_config.architectures[0] == 'LlamaForCausalLM':
108
+ self.language_model = LlamaForCausalLM(config.text_config)
109
+ elif config.text_config.architectures[0] == 'Phi3ForCausalLM':
110
+ self.language_model = Phi3ForCausalLM(config.text_config)
111
+ elif config.text_config.architectures[0] == 'Qwen2ForCausalLM':
112
+ assert config.text_config._attn_implementation == 'flash_attention_2', f"Qwen2 must use flash_attention_2 but got {config.text_config._attn_implementation}"
113
+ self.language_model = Qwen2ForCausalLM(config.text_config)
114
+ elif config.text_config.architectures[0] == 'Qwen3ForCausalLM':
115
+ assert config.text_config._attn_implementation == 'flash_attention_2', f"Qwen3 must use flash_attention_2 but got {config.text_config._attn_implementation}"
116
+ self.language_model = Qwen3ForCausalLM(config.text_config)
117
+ else:
118
+ raise NotImplementedError(f'{config.text_config.architectures[0]} is not implemented.')
119
+
120
+ vit_hidden_size = config.vision_config.hidden_size
121
+ llm_hidden_size = config.text_config.hidden_size
122
+
123
+ self.mlp1 = nn.Sequential(
124
+ nn.LayerNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2),
125
+ nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, llm_hidden_size),
126
+ nn.GELU(),
127
+ nn.Linear(llm_hidden_size, llm_hidden_size)
128
+ )
129
+ self.image_token_index = config.image_token_index
130
+ self.neftune_alpha = None
131
+
132
+
133
+ if config.use_backbone_lora:
134
+ self.wrap_backbone_lora(r=config.use_backbone_lora, lora_alpha=2 * config.use_backbone_lora)
135
+
136
+ self.use_llm_lora = config.use_llm_lora
137
+ if config.use_llm_lora:
138
+ self.wrap_llm_lora(r=config.use_llm_lora, lora_alpha=2 * config.use_llm_lora)
139
+
140
+ self.check_forward_kwargs()
141
+
142
+ def check_forward_kwargs(self):
143
+ # We intentionally avoid using **kwargs in forward because Hugging Face Transformers
144
+ # has special handling for functions with **kwargs parameters that would affect
145
+ # how our model is processed during training and inference.
146
+ forward_params = inspect.signature(self.forward).parameters
147
+ assert not any(k.kind == inspect.Parameter.VAR_KEYWORD for k in forward_params.values())
148
+
149
+
150
+ def wrap_backbone_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
151
+ lora_config = LoraConfig(
152
+ r=r,
153
+ target_modules=['self_attn.q_proj', 'self_attn.k_proj', 'self_attn.v_proj', 'self_attn.out_proj',
154
+ 'mlp.fc1', 'mlp.fc2'],
155
+ lora_alpha=lora_alpha,
156
+ lora_dropout=lora_dropout,
157
+ )
158
+ self.vision_model = get_peft_model(self.vision_model, lora_config)
159
+ self.vision_model.print_trainable_parameters()
160
+
161
+ def wrap_llm_lora(self, r=128, lora_alpha=256, lora_dropout=0.05):
162
+ lora_config = LoraConfig(
163
+ r=r,
164
+ target_modules=['self_attn.q_proj', 'self_attn.k_proj', 'self_attn.v_proj', 'self_attn.o_proj',
165
+ 'mlp.gate_proj', 'mlp.down_proj', 'mlp.up_proj'],
166
+ lora_alpha=lora_alpha,
167
+ lora_dropout=lora_dropout,
168
+ task_type='CAUSAL_LM'
169
+ )
170
+ self.language_model = get_peft_model(self.language_model, lora_config)
171
+ self.language_model.enable_input_require_grads()
172
+ self.language_model.print_trainable_parameters()
173
+ self.use_llm_lora = True
174
+
175
+ def forward(
176
+ self,
177
+ pixel_values: List[torch.FloatTensor],
178
+ input_ids: torch.LongTensor = None,
179
+ attention_mask: Optional[torch.Tensor] = None,
180
+ position_ids: Optional[torch.LongTensor] = None,
181
+ image_flags: Optional[torch.LongTensor] = None,
182
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
183
+ labels: Optional[torch.LongTensor] = None,
184
+ use_cache: Optional[bool] = None,
185
+ output_attentions: Optional[bool] = None,
186
+ output_hidden_states: Optional[bool] = None,
187
+ return_dict: Optional[bool] = None,
188
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
189
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
190
+
191
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
192
+
193
+ num_images = len(pixel_values)
194
+
195
+ if image_flags is not None:
196
+ image_flags = image_flags.view(-1)
197
+
198
+ vit_embeds = self.extract_feature(pixel_values, image_flags)
199
+
200
+
201
+ B, N, C = input_embeds.shape
202
+ input_embeds = input_embeds.reshape(B * N, C)
203
+
204
+ input_ids = input_ids.reshape(B * N)
205
+ selected = (input_ids == self.image_token_index)
206
+ try:
207
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds
208
+ except Exception as e:
209
+ print(f'warning: {e}, input_embeds[selected].shape={input_embeds[selected].shape}, '
210
+ f'vit_embeds.shape={vit_embeds.shape}')
211
+ n_token = selected.sum()
212
+ input_embeds[selected] = input_embeds[selected] * 0.0 + vit_embeds[:n_token]
213
+
214
+ input_embeds = input_embeds.reshape(B, N, C)
215
+
216
+ outputs = self.language_model(
217
+ inputs_embeds=input_embeds,
218
+ attention_mask=attention_mask,
219
+ position_ids=position_ids,
220
+ past_key_values=past_key_values,
221
+ use_cache=use_cache,
222
+ output_attentions=output_attentions,
223
+ output_hidden_states=output_hidden_states,
224
+ )
225
+ logits = outputs.logits
226
+
227
+ loss = None
228
+ if labels is not None:
229
+ # Shift so that tokens < n predict n
230
+ shift_logits = logits[..., :-1, :].contiguous()
231
+ shift_labels = labels[..., 1:].contiguous()
232
+ # Flatten the tokens
233
+ loss_fct = CrossEntropyLoss()
234
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
235
+ shift_labels = shift_labels.view(-1)
236
+ # Enable model parallelism
237
+ shift_labels = shift_labels.to(shift_logits.device)
238
+ loss = loss_fct(shift_logits, shift_labels)
239
+
240
+ if not return_dict:
241
+ output = (logits,) + outputs[1:]
242
+ return (loss,) + output if loss is not None else output
243
+
244
+ return CausalLMOutputWithPast(
245
+ loss=loss,
246
+ logits=logits,
247
+ past_key_values=outputs.past_key_values,
248
+ hidden_states=outputs.hidden_states,
249
+ attentions=outputs.attentions,
250
+ )
251
+
252
+ def pixel_shuffle_back(self, vit_embeds, spatial_shapes):
253
+ # Assume vit_embeds: [1, 15020, 1152], spatial_shapes: [(h1,w1), (h2,w2), ...] length 64
254
+ B, N, C = vit_embeds.shape
255
+ shapes = spatial_shapes.tolist() # List of (h, w)
256
+
257
+ # 1) Split at once
258
+ lengths = [h * w for (h, w) in shapes] # Number of patches per image
259
+ slices = torch.split(vit_embeds.view(-1, C), lengths, dim=0)
260
+ # slices[i]: [hi*wi, C]
261
+
262
+ # 2) Convert to [C, H, W]
263
+ features = [
264
+ sl.transpose(0, 1).reshape(C, h, w)
265
+ for sl, (h, w) in zip(slices, shapes)
266
+ ] # Each item [C, hi, wi]
267
+ # visualize_tensor_list(features, 'features.jpg')
268
+
269
+ # 3) Group by scale and batch unshuffle
270
+ down_feats = [None] * len(features)
271
+ grouped: dict = defaultdict(list)
272
+ for idx, (h, w) in enumerate(shapes):
273
+ grouped[(h, w)].append(idx)
274
+
275
+ for (h, w), idxs in grouped.items():
276
+ # Stack features of the same scale -> [n, C, H, W]
277
+ grp = torch.stack([features[i] for i in idxs], dim=0)
278
+ # Pixel Unshuffle at once
279
+ out = F.pixel_unshuffle(grp, downscale_factor=int(1/self.downsample_ratio)) # [n, C*4, H//2, W//2]
280
+ out = out.flatten(start_dim=2).transpose(1, 2) # [n, H//2 * W//2, C*4]
281
+ # Split back to respective positions
282
+ for i, feat in zip(idxs, out):
283
+ down_feats[i] = feat
284
+
285
+ down_feats = torch.cat(down_feats, dim=0).unsqueeze(0)
286
+ return down_feats, (spatial_shapes*self.downsample_ratio).to(torch.int32)
287
+
288
+ def mask_valid_tokens(self, vit_embeds, spatial_shapes, image_flags):
289
+ """
290
+ vit_embeds: Tensor, shape [1, N, C] or [N, C]
291
+ spatial_shapes: Tensor of shape [num_images, 2], each row is (H, W)
292
+ image_flags: list[int], e.g. [1, 0, 1, ...]
293
+ Returns:
294
+ valid_tokens: Tensor [num_valid_tokens, C]
295
+ """
296
+
297
+ lengths = spatial_shapes[:, 0] * spatial_shapes[:, 1] # [num_images]
298
+ valid_mask = []
299
+ for flag, length in zip(image_flags, lengths):
300
+ valid_mask.extend([flag] * length)
301
+
302
+ valid_mask = torch.tensor(valid_mask, dtype=torch.bool, device=vit_embeds.device)
303
+ valid_tokens = vit_embeds[valid_mask] # [num_valid_tokens, C]
304
+
305
+ return valid_tokens
306
+
307
+ def extract_feature(self, pixel_values, image_flags=None):
308
+
309
+ if self.select_layer == -1:
310
+ vision_model_output = self.vision_model(
311
+ pixel_values=pixel_values,
312
+ output_hidden_states=False,
313
+ return_dict=True)
314
+ if hasattr(vision_model_output, 'last_hidden_state'):
315
+ vit_embeds = vision_model_output.last_hidden_state
316
+ if hasattr(vision_model_output, 'spatial_shapes'):
317
+ spatial_shapes = vision_model_output.spatial_shapes
318
+ else:
319
+ vit_embeds = self.vision_model(
320
+ pixel_values=pixel_values,
321
+ output_hidden_states=True,
322
+ return_dict=True).hidden_states[self.select_layer]
323
+
324
+ vit_embeds, spatial_shapes = self.pixel_shuffle_back(vit_embeds, spatial_shapes)
325
+
326
+
327
+ if self.mlp_checkpoint and vit_embeds.requires_grad:
328
+ vit_embeds = cp.checkpoint(self.mlp1, vit_embeds)
329
+ else:
330
+ vit_embeds = self.mlp1(vit_embeds)
331
+
332
+ B, N, C = vit_embeds.shape
333
+ vit_embeds = vit_embeds.reshape(B * N, C)
334
+
335
+ if image_flags is not None and any(image_flags==0):
336
+ vit_embeds = self.mask_valid_tokens(vit_embeds, spatial_shapes, image_flags)
337
+
338
+ return vit_embeds
339
+
340
+ @torch.no_grad()
341
+ def generate(
342
+ self,
343
+ pixel_values: Optional[torch.FloatTensor] = None,
344
+ input_ids: Optional[torch.FloatTensor] = None,
345
+ attention_mask: Optional[torch.LongTensor] = None,
346
+ visual_features: Optional[torch.FloatTensor] = None,
347
+ generation_config: Optional[GenerationConfig] = None,
348
+ output_hidden_states: Optional[bool] = None,
349
+ image_sizes: Optional[List[Tuple[int, int]]] = None,
350
+ **generate_kwargs,
351
+ ) -> torch.LongTensor:
352
+
353
+ if pixel_values is not None:
354
+ if visual_features is not None:
355
+ vit_embeds = visual_features
356
+ else:
357
+ pixel_values = [each.to(self.device) for each in pixel_values]
358
+ import time
359
+ torch.cuda.synchronize()
360
+ begin_time = time.time()
361
+ for _ in range(10):
362
+ vit_embeds = self.extract_feature(pixel_values)
363
+ torch.cuda.synchronize()
364
+ end_time = time.time()
365
+ print(f'extract_feature time: {(end_time - begin_time) / 10}')
366
+
367
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
368
+ B, N, C = input_embeds.shape
369
+ input_embeds = input_embeds.reshape(B * N, C)
370
+
371
+ input_ids = input_ids.reshape(B * N)
372
+ selected = (input_ids == self.config.image_token_index)
373
+ assert selected.sum() != 0
374
+ input_embeds[selected] = vit_embeds.to(input_embeds.device)
375
+
376
+ input_embeds = input_embeds.reshape(B, N, C)
377
+ else:
378
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
379
+
380
+ if 'use_cache' not in generate_kwargs:
381
+ generate_kwargs['use_cache'] = True
382
+
383
+ outputs = self.language_model.generate(
384
+ inputs_embeds=input_embeds,
385
+ attention_mask=attention_mask,
386
+ generation_config=generation_config,
387
+ output_hidden_states=output_hidden_states,
388
+ **generate_kwargs,
389
+ )
390
+
391
+ return outputs
392
+
393
+ # Copied from transformers.models.llava_next.modeling_llava_next.LlavaNextForConditionalGeneration.get_input_embeddings
394
+ def get_input_embeddings(self):
395
+ return self.language_model.get_input_embeddings()
396
+
397
+ # Copied from transformers.models.llava_next.modeling_llava_next.LlavaNextForConditionalGeneration.set_input_embeddings
398
+ def set_input_embeddings(self, value):
399
+ self.language_model.set_input_embeddings(value)
400
+
401
+ # Copied from transformers.models.llava_next.modeling_llava_next.LlavaNextForConditionalGeneration.get_output_embeddings
402
+ def get_output_embeddings(self):
403
+ return self.language_model.get_output_embeddings()
404
+
405
+ # Copied from transformers.models.llava_next.modeling_llava_next.LlavaNextForConditionalGeneration.set_output_embeddings
406
+ def set_output_embeddings(self, new_embeddings):
407
+ self.language_model.set_output_embeddings(new_embeddings)
408
+
409
+ # Copied from transformers.models.llava_next.modeling_llava_next.LlavaNextForConditionalGeneration.set_decoder
410
+ def set_decoder(self, decoder):
411
+ self.language_model.set_decoder(decoder)
412
+
413
+ # Copied from transformers.models.llava_next.modeling_llava_next.LlavaNextForConditionalGeneration.get_decoder
414
+ def get_decoder(self):
415
+ return self.language_model.get_decoder()
416
+
modeling_siglip2.py ADDED
@@ -0,0 +1,1419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/siglip2/modular_siglip2.py.
3
+ # Copyright 2025 The HuggingFace Inc. team.
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
+ import math
17
+ import warnings
18
+ from dataclasses import dataclass
19
+ from typing import Any, Callable, Optional, Tuple, Union, List
20
+
21
+ import numpy as np
22
+ import torch
23
+ import torch.nn as nn
24
+ import torch.nn.functional as F
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+ from torch.nn.init import _calculate_fan_in_and_fan_out
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
30
+ from transformers.configuration_utils import PretrainedConfig
31
+
32
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
33
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
34
+ from transformers.utils import (
35
+ ModelOutput,
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ can_return_tuple,
39
+ logging,
40
+ replace_return_docstrings,
41
+ )
42
+ from transformers.models.siglip2.configuration_siglip2 import Siglip2Config, Siglip2TextConfig
43
+ from collections import defaultdict
44
+ from itertools import accumulate
45
+ from math import isqrt
46
+ from typing import Dict
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+
52
+ import inspect
53
+ import os
54
+ from typing import Optional, Tuple
55
+
56
+ import torch
57
+ import torch.nn.functional as F
58
+
59
+ from transformers.utils import is_flash_attn_2_available, is_flash_attn_greater_or_equal, logging
60
+ from transformers.integrations.flash_attention import flash_attention_forward as original_flash_attention_forward
61
+ flash_241 = is_flash_attn_greater_or_equal("2.4.1")
62
+ deterministic_g = os.environ.get("FLASH_ATTENTION_DETERMINISTIC", "0") == "1"
63
+
64
+
65
+ logger = logging.get_logger(__name__)
66
+
67
+
68
+ if is_flash_attn_2_available():
69
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
70
+ from flash_attn import flash_attn_func, flash_attn_varlen_func, flash_attn_varlen_qkvpacked_func
71
+
72
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
73
+
74
+
75
+ def _flash_attention_forward(
76
+ query_states: torch.Tensor,
77
+ key_states: torch.Tensor,
78
+ value_states: torch.Tensor,
79
+ attention_mask: torch.Tensor,
80
+ query_length: int,
81
+ is_causal: bool,
82
+ dropout: float = 0.0,
83
+ position_ids: Optional[torch.Tensor] = None,
84
+ softmax_scale: Optional[float] = None,
85
+ sliding_window: Optional[int] = None,
86
+ use_top_left_mask: bool = False,
87
+ softcap: Optional[float] = None,
88
+ deterministic: bool = None,
89
+ cu_seq_lens_q: Optional[torch.LongTensor] = None,
90
+ cu_seq_lens_k: Optional[torch.LongTensor] = None,
91
+ max_length_q: Optional[int] = None,
92
+ max_length_k: Optional[int] = None,
93
+ target_dtype: Optional[torch.dtype] = None,
94
+ **kwargs,
95
+ ):
96
+ """
97
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
98
+ first unpad the input, then computes the attention scores and pad the final attention scores.
99
+ Args:
100
+ query_states (`torch.Tensor`):
101
+ Input query states to be passed to Flash Attention API
102
+ key_states (`torch.Tensor`):
103
+ Input key states to be passed to Flash Attention API
104
+ value_states (`torch.Tensor`):
105
+ Input value states to be passed to Flash Attention API
106
+ attention_mask (`torch.Tensor`):
107
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
108
+ position of padding tokens and 1 for the position of non-padding tokens.
109
+ dropout (`int`, *optional*):
110
+ Attention dropout
111
+ softmax_scale (`float`, *optional*):
112
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
113
+ use_sliding_windows (`bool`, *optional*):
114
+ Whether to activate sliding window attention.
115
+ """
116
+
117
+ if not use_top_left_mask:
118
+ causal = is_causal
119
+ else:
120
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
121
+ causal = is_causal and query_length != 1
122
+ # Assuming 4D tensors, key_states.shape[1] is the key/value sequence length (source length).
123
+ use_sliding_windows = (
124
+ _flash_supports_window_size and sliding_window is not None and key_states.shape[1] > sliding_window
125
+ )
126
+ flash_kwargs = {"window_size": (sliding_window, sliding_window)} if use_sliding_windows else {}
127
+ if flash_241:
128
+ if deterministic is None:
129
+ deterministic = deterministic_g
130
+ flash_kwargs["deterministic"] = deterministic
131
+
132
+ if softcap is not None:
133
+ flash_kwargs["softcap"] = softcap
134
+
135
+ attn_output = flash_attn_varlen_func(
136
+ query_states[0],
137
+ key_states[0],
138
+ value_states[0],
139
+ cu_seqlens_q=cu_seq_lens_q,
140
+ cu_seqlens_k=cu_seq_lens_k,
141
+ max_seqlen_q=max_length_q,
142
+ max_seqlen_k=max_length_k,
143
+ dropout_p=dropout,
144
+ softmax_scale=softmax_scale,
145
+ causal=causal,
146
+ **flash_kwargs,
147
+ )
148
+
149
+
150
+ return attn_output
151
+
152
+
153
+ from transformers.utils import is_flash_attn_greater_or_equal_2_10
154
+ _use_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
155
+
156
+ def flash_attention_forward_for_packing(
157
+ module: torch.nn.Module,
158
+ query: torch.Tensor,
159
+ key: torch.Tensor,
160
+ value: torch.Tensor,
161
+ attention_mask: Optional[torch.Tensor]=None,
162
+ dropout: float = 0.0,
163
+ scaling: Optional[float] = None,
164
+ sliding_window: Optional[int] = None,
165
+ softcap: Optional[float] = None,
166
+ seq_len_list: Optional[List[int]] = None,
167
+ **kwargs,
168
+ ) -> Tuple[torch.Tensor, None]:
169
+
170
+ # This is before the transpose
171
+ seq_len = query.shape[2]
172
+
173
+ # FA2 uses non-transposed inputs
174
+ query = query.transpose(1, 2)
175
+ key = key.transpose(1, 2)
176
+ value = value.transpose(1, 2)
177
+
178
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
179
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
180
+ # cast them back in the correct dtype just to be sure everything works as expected.
181
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
182
+ # in fp32. (usually our RMSNorm modules handle it correctly)
183
+ target_dtype = None
184
+ if query.dtype == torch.float32:
185
+ if torch.is_autocast_enabled():
186
+ target_dtype = torch.get_autocast_gpu_dtype()
187
+ # Handle the case where the model is quantized
188
+ elif hasattr(module.config, "_pre_quantization_dtype"):
189
+ target_dtype = module.config._pre_quantization_dtype
190
+ else:
191
+ target_dtype = next(layer for layer in module.modules() if isinstance(layer, torch.nn.Linear)).weight.dtype
192
+
193
+ # FA2 always relies on the value set in the module, so remove it if present in kwargs to avoid passing it twice
194
+ kwargs.pop("is_causal", None)
195
+
196
+
197
+ cu_seqlens = F.pad(torch.cumsum(torch.tensor(seq_len_list, device=query.device, dtype=torch.int32), dim=0), (1, 0))
198
+ cu_seqlens = cu_seqlens.to(torch.int32)
199
+ max_seq_len = max(seq_len_list)
200
+ attn_output = _flash_attention_forward(
201
+ query,
202
+ key,
203
+ value,
204
+ attention_mask,
205
+ query_length=seq_len,
206
+ is_causal=module.is_causal,
207
+ dropout=dropout,
208
+ softmax_scale=scaling,
209
+ sliding_window=sliding_window,
210
+ softcap=softcap,
211
+ use_top_left_mask=_use_top_left_mask,
212
+ target_dtype=target_dtype,
213
+ cu_seq_lens_q=cu_seqlens,
214
+ cu_seq_lens_k=cu_seqlens,
215
+ max_length_q=max_seq_len,
216
+ max_length_k=max_seq_len,
217
+ **kwargs,
218
+ )
219
+ return attn_output.squeeze(0), None
220
+
221
+ # General docstring
222
+ _CONFIG_FOR_DOC = "Siglip2Config"
223
+
224
+
225
+
226
+ class Siglip2VisionConfig(PretrainedConfig):
227
+ r"""
228
+ This is the configuration class to store the configuration of a [`Siglip2VisionModel`]. It is used to instantiate a
229
+ Siglip2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a
230
+ configuration with the defaults will yield a similar configuration to that of the vision encoder of the Siglip2
231
+ [google/siglip2-base-patch16-naflex](https://huggingface.co/google/siglip2-base-patch16-naflex) architecture.
232
+
233
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
234
+ documentation from [`PretrainedConfig`] for more information.
235
+
236
+ Args:
237
+ hidden_size (`int`, *optional*, defaults to 768):
238
+ Dimensionality of the encoder layers and the pooler layer.
239
+ intermediate_size (`int`, *optional*, defaults to 3072):
240
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
241
+ num_hidden_layers (`int`, *optional*, defaults to 12):
242
+ Number of hidden layers in the Transformer encoder.
243
+ num_attention_heads (`int`, *optional*, defaults to 12):
244
+ Number of attention heads for each attention layer in the Transformer encoder.
245
+ num_channels (`int`, *optional*, defaults to 3):
246
+ Number of channels in the input images.
247
+ num_patches (`int`, *optional*, defaults to 256):
248
+ The number of patches in the image with the size of (`patch_size`, `patch_size`).
249
+ The image is resized to fill maximum of this number of patches, and to preserve
250
+ the aspect ratio. In case the resulted number of patches is lower, the image is
251
+ padded in "patch" dimension.
252
+ patch_size (`int`, *optional*, defaults to 16):
253
+ The size (resolution) of each patch.
254
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
255
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
256
+ `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
257
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
258
+ The epsilon used by the layer normalization layers.
259
+ attention_dropout (`float`, *optional*, defaults to 0.0):
260
+ The dropout ratio for the attention probabilities.
261
+
262
+ Example:
263
+
264
+ ```python
265
+ >>> from transformers import Siglip2VisionConfig, Siglip2VisionModel
266
+
267
+ >>> # Initializing a Siglip2VisionConfig with google/siglip2-base-patch16-naflex style configuration
268
+ >>> configuration = Siglip2VisionConfig()
269
+
270
+ >>> # Initializing a Siglip2VisionModel (with random weights) from the google/siglip2-base-patch16-naflex style configuration
271
+ >>> model = Siglip2VisionModel(configuration)
272
+
273
+ >>> # Accessing the model configuration
274
+ >>> configuration = model.config
275
+ ```"""
276
+
277
+ model_type = "siglip2_vision_model"
278
+ base_config_key = "vision_config"
279
+
280
+ def __init__(
281
+ self,
282
+ hidden_size=1152,
283
+ intermediate_size=4304,
284
+ num_hidden_layers=27,
285
+ num_attention_heads=16,
286
+ num_channels=3,
287
+ num_patches=256,
288
+ patch_size=14, # manully modified
289
+ hidden_act="gelu_pytorch_tanh",
290
+ layer_norm_eps=1e-6,
291
+ attention_dropout=0.0,
292
+ window_size=14, #
293
+ full_attention_indexes=[7, 14, 21, 26],
294
+ use_rope=True,
295
+ use_windows_attn=True,
296
+ **kwargs,
297
+ ):
298
+ super().__init__(**kwargs)
299
+
300
+ self.hidden_size = hidden_size
301
+ self.intermediate_size = intermediate_size
302
+ self.num_hidden_layers = num_hidden_layers
303
+ self.num_attention_heads = num_attention_heads
304
+ self.num_channels = num_channels
305
+ self.patch_size = patch_size
306
+ self.attention_dropout = attention_dropout
307
+ self.layer_norm_eps = layer_norm_eps
308
+ self.hidden_act = hidden_act
309
+ self.num_patches = num_patches
310
+ self.window_size = window_size
311
+ self.full_attention_indexes = full_attention_indexes
312
+ self.use_windows_attn = use_windows_attn
313
+ self.use_rope = use_rope
314
+
315
+
316
+ @dataclass
317
+ class Siglip2VisionOutput(ModelOutput):
318
+ """
319
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
320
+
321
+ Args:
322
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
323
+ The image embeddings obtained by applying the projection layer to the pooler_output.
324
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
325
+ Sequence of hidden-states at the output of the last layer of the model.
326
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
327
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
328
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
329
+
330
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
331
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
332
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
333
+ sequence_length)`.
334
+
335
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
336
+ heads.
337
+ """
338
+
339
+ image_embeds: Optional[torch.FloatTensor] = None
340
+ last_hidden_state: Optional[torch.FloatTensor] = None
341
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
342
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
343
+ spatial_shapes: Optional[torch.LongTensor] = None
344
+
345
+
346
+ def convert_image_to_patches(image: "torch.Tensor", patch_size: int) -> "torch.Tensor":
347
+ """
348
+ Convert 3D tensor image of shape (num_channels, image_height, image_width) into 2D tensor of patches of shape
349
+ (num_patches_height * num_patches_width, patch_size * patch_size * num_channels).
350
+ """
351
+ num_channels, image_height, image_width = image.shape
352
+ num_patches_height = image_height // patch_size
353
+ num_patches_width = image_width // patch_size
354
+ patched_image = image.reshape(num_channels, num_patches_height, patch_size, num_patches_width, patch_size)
355
+ patched_image = patched_image.permute(1, 3, 2, 4, 0)
356
+ patched_image = patched_image.reshape(num_patches_height * num_patches_width, -1)
357
+ return patched_image
358
+
359
+ def convert_images_to_patches(image: "torch.Tensor", patch_size: int) -> "torch.Tensor":
360
+ """
361
+ Convert 4D tensor image of shape (batch_size, num_channels, image_height, image_width) into 2D tensor of patches of shape
362
+ (batch_size, num_patches_height * num_patches_width, patch_size * patch_size * num_channels).
363
+ """
364
+ batch_size, num_channels, image_height, image_width = image.shape
365
+ assert image_height % patch_size == 0 and image_width % patch_size == 0, f"image_height % patch_size == 0 and image_width % patch_size == 0"
366
+ num_patches_height = image_height // patch_size
367
+ num_patches_width = image_width // patch_size
368
+ patched_image = image.reshape(batch_size, num_channels, num_patches_height, patch_size, num_patches_width, patch_size)
369
+ patched_image = patched_image.permute(0, 2, 4, 3, 5, 1) # (batch_size, num_patches_height, num_patches_width, patch_size, patch_size, num_channels)
370
+
371
+ patched_image = patched_image.reshape(batch_size * num_patches_height * num_patches_width, -1)
372
+ return patched_image
373
+
374
+
375
+ class Siglip2VisionEmbeddings(nn.Module):
376
+ def __init__(self, config: Siglip2VisionConfig):
377
+ super().__init__()
378
+ self.config = config
379
+ self.embed_dim = config.hidden_size
380
+ self.patch_size = config.patch_size
381
+ self.window_size = config.window_size
382
+
383
+ self.patch_embedding = nn.Linear(
384
+ in_features=config.num_channels * self.patch_size * self.patch_size,
385
+ out_features=self.embed_dim,
386
+ )
387
+
388
+ self.num_patches = config.num_patches
389
+ self.position_embedding_size = int(self.num_patches**0.5)
390
+ self.position_embedding = nn.Embedding(self.num_patches, self.embed_dim)
391
+
392
+
393
+ def split_patch_embeddings_to_windows_with_meta(self, patch_embeds, batch_hw, window_size):
394
+ """
395
+ Args:
396
+ patch_embeds: Tensor, shape (1, sum(H_i*W_i), C)
397
+ batch_hw: List[(H_i, W_i)]
398
+ window_size: int
399
+
400
+ Returns:
401
+ windows_tensor: Tensor, shape (total_windows, window_size*window_size, C)
402
+ win_meta_list: List[dict] with keys:
403
+ - img_idx: index in batch_hw
404
+ - patch_hw: original (H, W)
405
+ - win_xy: (h0, w0) 左上角相对于原图
406
+ - win_hw: 原图内有效窗口大小 (h_eff, w_eff)
407
+ """
408
+
409
+ # 1. 计算每张图在 flat tensor 中的起始位置
410
+ batch_hw = batch_hw.tolist()
411
+ counts = [H * W for (H, W) in batch_hw]
412
+ starts = [0] + list(accumulate(counts))[:-1]
413
+
414
+ # 2. 按 (H,W) 分组,同一尺寸一起处理
415
+ size2info = defaultdict(list)
416
+ for img_idx, ((H, W), start) in enumerate(zip(batch_hw, starts)):
417
+ size2info[(H, W)].append((img_idx, start))
418
+
419
+ all_windows = []
420
+ all_meta = []
421
+ # print(size2info)
422
+ # 3. 对每个尺寸组做 batch unfold + pad
423
+ for (H, W), info in size2info.items():
424
+ H, W = int(H), int(W)
425
+ B = len(info)
426
+ C = patch_embeds.shape[-1]
427
+ img_idxs, img_starts = zip(*info)
428
+
429
+ # 3.1 取出并 reshape 成 (B, C, H, W)
430
+ imgs = []
431
+ for st in img_starts:
432
+ flat = patch_embeds[0, st: st + H * W] # (H*W, C)
433
+ imgs.append(flat.transpose(0,1).reshape(C, H, W))
434
+ batch_tensor = torch.stack(imgs, dim=0) # (B, C, H, W)
435
+ # 3.2 计算 pad 大小 (bottom, right),保证能被 window_size 整除
436
+ pad_h = (window_size - H % window_size) % window_size
437
+ pad_w = (window_size - W % window_size) % window_size
438
+
439
+ # pad 格式: (left, right, top, bottom) for last two dims
440
+ batch_padded = F.pad(batch_tensor, (0, pad_w, 0, pad_h))
441
+
442
+ H_pad, W_pad = H + pad_h, W + pad_w
443
+ n_h = H_pad // window_size
444
+ n_w = W_pad // window_size
445
+ n_windows = n_h * n_w
446
+
447
+ # 3.3 batched unfold -> (B, C*ws*ws, n_windows)
448
+ patches_unf = F.unfold(
449
+ batch_padded,
450
+ kernel_size=(window_size, window_size),
451
+ stride=(window_size, window_size)
452
+ )
453
+
454
+ # 3.4 reshape到 (B*n_windows, ws*ws, C)
455
+ patches = (
456
+ patches_unf
457
+ .view(B, C, window_size * window_size, n_windows) # (B, C, ws*ws, n_win)
458
+ .permute(0, 3, 2, 1) # (B, n_win, ws*ws, C)
459
+ .reshape(-1, window_size * window_size, C) # (B*n_win, ws*ws, C)
460
+ )
461
+ all_windows.append(patches)
462
+
463
+ # 3.5 生成 meta:记录原图内有效窗口大小
464
+ for b, img_idx in enumerate(img_idxs):
465
+ for win_id in range(n_windows):
466
+ i, j = divmod(win_id, n_w)
467
+ h0, w0 = i * window_size, j * window_size
468
+ # 在原图内的实际结束坐标
469
+ h1 = min(h0 + window_size, H)
470
+ w1 = min(w0 + window_size, W)
471
+ all_meta.append({
472
+ 'img_idx': img_idx,
473
+ 'patch_hw': (H, W),
474
+ 'win_xy': (h0, w0),
475
+ 'win_hw': (h1 - h0, w1 - w0), # 有效区域大小
476
+ })
477
+
478
+ # 4. 拼接并根据 img_idx + win_xy 排序,恢复输入顺序
479
+ sorted_idx = sorted(
480
+ range(len(all_meta)),
481
+ key=lambda k: (
482
+ all_meta[k]['img_idx'],
483
+ all_meta[k]['win_xy'][0],
484
+ all_meta[k]['win_xy'][1]
485
+ )
486
+ )
487
+ all_windows = torch.cat(all_windows, dim=0)
488
+ all_windows = all_windows[sorted_idx]
489
+ win_meta_list = [all_meta[i] for i in sorted_idx]
490
+
491
+ windows_list = []
492
+ for meta, win in zip(win_meta_list, all_windows):
493
+ h_eff, w_eff = meta['win_hw']
494
+ valid_num = h_eff * w_eff
495
+ # 只保留真正来自原图的 patch tokens
496
+ if valid_num == window_size * window_size:
497
+ windows_list.append(win)
498
+ else:
499
+ win = win.view(window_size, window_size, -1)[:h_eff, :w_eff, :].reshape(h_eff * w_eff, -1)
500
+ windows_list.append(win) # shape (valid_num, C)
501
+
502
+ # 如果你需要一个单一 tensor,可以再 cat 一次:
503
+ all_tokens = torch.cat(windows_list, dim=0).unsqueeze(0) # shape (sum(valid_num), C)
504
+
505
+
506
+ # 1. 先重算每张图在原始 flat tensor 中的起始位置
507
+ counts = [H * W for H, W in batch_hw]
508
+ starts = [0] + list(accumulate(counts))[:-1]
509
+ total_patches = sum(counts)
510
+
511
+ # 2. 构造映射:mapping[orig_idx] = new_idx
512
+ mapping = [None] * total_patches
513
+ offset = 0 # all_tokens 维度上的游标
514
+
515
+ for meta in win_meta_list:
516
+ img_idx = meta['img_idx']
517
+ H, W = meta['patch_hw']
518
+ h0, w0 = meta['win_xy']
519
+ h_eff, w_eff = meta['win_hw']
520
+ base = starts[img_idx]
521
+
522
+ # 对该窗口内所有真正来自原图的 patch token 计算映射
523
+ for u in range(h_eff):
524
+ for v in range(w_eff):
525
+ # 原始 flat 坐标
526
+ orig_idx = base + (h0+u) * W + (w0) + v
527
+ # 在 all_tokens 里的位置:在该窗口区段里按 row-major 展平
528
+ p = u * w_eff + v
529
+ mapping[orig_idx] = offset + p
530
+
531
+ # 窗口结束后,offset 推进该窗口的有效 token 数
532
+ offset += h_eff * w_eff
533
+ reverse_mapping = torch.tensor(mapping, dtype=torch.long)
534
+
535
+ return all_tokens, win_meta_list, reverse_mapping
536
+
537
+ @staticmethod
538
+ def resize_positional_embeddings(
539
+ positional_embeddings: torch.Tensor,
540
+ spatial_shapes: torch.LongTensor,
541
+ ) -> torch.Tensor:
542
+ """
543
+ Resize positional embeddings to image-specific size and pad to a fixed size.
544
+
545
+ Args:
546
+ positional_embeddings (`torch.Tensor`):
547
+ Position embeddings of shape (height, width, embed_dim)
548
+ spatial_shapes (`torch.LongTensor`):
549
+ Spatial shapes of shape (batch_size, 2) to resize the positional embeddings to
550
+ max_length (`int`):
551
+ Maximum length of the positional embeddings to pad resized positional embeddings to
552
+
553
+ Returns:
554
+ `torch.Tensor`: Embeddings of shape (batch_size, max_length, embed_dim)
555
+ """
556
+ batch_size = spatial_shapes.shape[0]
557
+ embed_dim = positional_embeddings.shape[-1]
558
+ source_dtype = positional_embeddings.dtype
559
+
560
+ resulted_positional_embeddings = []
561
+
562
+ # (height, width, embed_dim) -> (1, embed_dim, height, width) for interpolation
563
+ positional_embeddings = positional_embeddings.permute(2, 0, 1).unsqueeze(0)
564
+
565
+ # Upcast to float32 on CPU because antialias is not supported for bfloat16/float16 on CPU
566
+ if positional_embeddings.device.type == "cpu":
567
+ positional_embeddings = positional_embeddings.to(torch.float32)
568
+
569
+ for i in range(batch_size):
570
+ # (1, dim, height, width) -> (1, dim, target_height, target_width)
571
+ height, width = spatial_shapes[i]
572
+ resized_embeddings = F.interpolate(
573
+ positional_embeddings,
574
+ size=(height, width),
575
+ mode="bilinear",
576
+ align_corners=False,
577
+ antialias=True,
578
+ )
579
+
580
+ # (1, dim, target_height, target_width) -> (target_height * target_width, dim)
581
+ resized_embeddings = resized_embeddings.reshape(embed_dim, height * width).transpose(0, 1)
582
+
583
+ # Cast to original dtype
584
+ resized_embeddings = resized_embeddings.to(source_dtype)
585
+
586
+ resulted_positional_embeddings.append(resized_embeddings)
587
+
588
+ return torch.cat(resulted_positional_embeddings, dim=0).unsqueeze(0)
589
+
590
+ def get_spatial_shapes(self, bchw_list: List[torch.Tensor]) -> torch.Tensor:
591
+ hw_list = []
592
+ for shape in bchw_list:
593
+ b, _, h, w = shape
594
+ hw_list.extend([(h//self.patch_size, w//self.patch_size)] * b)
595
+ hw_tensor = torch.tensor(hw_list)
596
+ return hw_tensor
597
+
598
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
599
+ """
600
+ Args:
601
+ pixel_values (`torch.FloatTensor`):
602
+ Pixel values of shape (batch_size, num_channels, height, width)
603
+ """
604
+
605
+ bchw_list = [each.shape for each in pixel_values]
606
+
607
+ pixel_values = torch.cat([convert_images_to_patches(each, self.patch_size) for each in pixel_values], dim=0)
608
+
609
+ # Apply patch embeddings to already patchified pixel values
610
+ target_dtype = self.patch_embedding.weight.dtype
611
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype))
612
+
613
+ # Get positional resized and padded positional embeddings
614
+ positional_embeddings = self.position_embedding.weight.reshape(
615
+ self.position_embedding_size, self.position_embedding_size, -1
616
+ )
617
+ spatial_shapes = self.get_spatial_shapes(bchw_list)
618
+
619
+ resized_positional_embeddings = self.resize_positional_embeddings(
620
+ positional_embeddings, spatial_shapes
621
+ )
622
+ # Add positional embeddings to patch embeddings
623
+ embeddings = patch_embeds + resized_positional_embeddings
624
+
625
+ windows_tensor, win_meta_list, reverse_mapping = self.split_patch_embeddings_to_windows_with_meta(embeddings, spatial_shapes, self.window_size)
626
+
627
+ return windows_tensor, win_meta_list, spatial_shapes, reverse_mapping
628
+
629
+
630
+ class Rope2DPosEmb(nn.Module):
631
+
632
+ """
633
+ copy from https://huggingface.co/moonshotai/Kimi-VL-A3B-Thinking/blob/main/modeling_kimi_vl.py#L324
634
+ 2D rotary position embedding with multi-resolution support.
635
+ This class is intended to be used in the following way:
636
+ 1. Before training, create an instance of Rope2DPosEmb. This instance will hold the precomputed cis.
637
+ 2. Before each forward pass, call `get_freqs_cis_by_*` to get the `freqs_cis` tensor for this iteration.
638
+ 3. During the forward pass, pass the `freqs_cis` tensor to each attention layer, and call `apply` just before each attention operation.
639
+ The rope is shared across all attention layers and all heads.
640
+ Refs:
641
+ - RoFormer: https://arxiv.org/abs/2104.09864
642
+ - VisionLLaMA: https://arxiv.org/abs/2403.00522
643
+ - https://github.com/Meituan-AutoML/VisionLLaMA/blob/main/dit/models.py
644
+ Args:
645
+ dim (int): usually the multi-head attention dimension, should be divisible by 4 (TODO: relax this constraint if needed)
646
+ max_height (int): the maximum height of the 2D grid
647
+ max_width (int): the maximum width of the 2D grid
648
+ theta_base (float): the base of the theta
649
+ device (str): the device to store the precomputed cis
650
+ """
651
+
652
+ def __init__(self, dim: int, max_height: int, max_width: int, theta_base=10000, window_size=14):
653
+ super().__init__()
654
+ self.dim = dim
655
+ assert self.dim % 4 == 0, "dim must be divisible by 4"
656
+ self.max_height = max_height
657
+ self.max_width = max_width
658
+ self.theta_base = theta_base
659
+ self.window_size = window_size
660
+
661
+ self.freqs_cis = None
662
+
663
+ def extra_repr(self):
664
+ return f"dim={self.dim}, max_height={self.max_height}, max_width={self.max_width}, theta_base={self.theta_base}"
665
+
666
+ def _precompute_freqs_cis(self, device: torch.device) -> torch.Tensor:
667
+ """Calculate the cis(freqs) for each position in the 2D grid.
668
+ Return: complex tensor of shape (max_height, max_width, dim//2) and value:
669
+ height axis: ret[h, w, 2*i] = cis(h * theta_base**(-4*i/dim))
670
+ weight axis: ret[h, w, 2*i+1] = cis(w * theta_base**(-4*i/dim)) with (i in [0, dim//4))
671
+ note: `cis` is a mathematical notation defined by cis x = cos x + i sin x,
672
+ """
673
+ N = self.max_height * self.max_width
674
+ flat_pos = torch.arange(0, N).float().to(device)
675
+ x_pos = flat_pos % self.max_width
676
+ y_pos = flat_pos // self.max_width
677
+ dim_range = (
678
+ torch.arange(0, self.dim, 4)[: (self.dim // 4)].float().to(device)
679
+ ) # C/4
680
+ freqs = 1.0 / (self.theta_base ** (dim_range / self.dim))
681
+ x_freqs = torch.outer(x_pos, freqs).float() # N, C/4
682
+ y_freqs = torch.outer(y_pos, freqs).float() # N, C/4
683
+ x_cis = torch.polar(torch.ones_like(x_freqs), x_freqs) # N, C/4
684
+ y_cis = torch.polar(torch.ones_like(y_freqs), y_freqs) # N, C/4
685
+ # N, C/4, 2
686
+ freqs_cis = torch.cat(
687
+ [x_cis.unsqueeze(dim=-1), y_cis.unsqueeze(dim=-1)], dim=-1
688
+ )
689
+ # max_height, max_width, C/2
690
+ freqs_cis = freqs_cis.reshape(self.max_height, self.max_width, -1)
691
+ return freqs_cis
692
+
693
+ def get_freqs_cis(self, win_meta_list: List[Dict], device: torch.device) -> torch.Tensor:
694
+ """
695
+ Args:
696
+ win_meta_list (List[Dict]): window meta list
697
+ Returns:
698
+ freqs_cis: tensor of shape (sum(t * height * width), dim//2)
699
+ """
700
+ if self.freqs_cis is None:
701
+ self.freqs_cis = self._precompute_freqs_cis(device)
702
+
703
+ # assert all xy <512
704
+ assert all(win_meta['win_xy'][0] + win_meta['win_hw'][0] < 512 and win_meta['win_xy'][1] + win_meta['win_hw'][1] < 512 for win_meta in win_meta_list)
705
+ freqs_cis = torch.cat([self.freqs_cis[win_meta['win_xy'][0]:win_meta['win_xy'][0] + win_meta['win_hw'][0], win_meta['win_xy'][1]: win_meta['win_xy'][1] + win_meta['win_hw'][1]].reshape(-1, self.dim // 2) for win_meta in win_meta_list], dim=0)
706
+ freqs_cis = freqs_cis.unsqueeze(0)
707
+ return freqs_cis
708
+
709
+
710
+ def eager_attention_forward(
711
+ module: nn.Module,
712
+ query: torch.Tensor,
713
+ key: torch.Tensor,
714
+ value: torch.Tensor,
715
+ attention_mask: Optional[torch.Tensor],
716
+ scaling: float,
717
+ dropout: float = 0.0,
718
+ **kwargs,
719
+ ):
720
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
721
+ if attention_mask is not None:
722
+ attn_weights = attn_weights + attention_mask
723
+
724
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
725
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
726
+
727
+ attn_output = torch.matmul(attn_weights, value)
728
+ attn_output = attn_output.transpose(1, 2).contiguous()
729
+
730
+ return attn_output, attn_weights
731
+
732
+
733
+
734
+ def _apply_rope_input_validation(x, freqs_cis):
735
+ assert x.ndim == freqs_cis.ndim + 1, (x.shape, freqs_cis.shape)
736
+ assert x.shape[:-2] == freqs_cis.shape[:-1], (x.shape, freqs_cis.shape)
737
+ assert x.shape[-1] == 2 * freqs_cis.shape[-1], (x.shape, freqs_cis.shape)
738
+ assert freqs_cis.dtype == torch.complex64, freqs_cis.dtype
739
+
740
+
741
+ def apply_rope(
742
+ xq: torch.Tensor, xk: torch.Tensor, freqs_cis: torch.Tensor
743
+ ) -> tuple[torch.Tensor, torch.Tensor]:
744
+ """
745
+ Args: (The leading dimensions of all inputs should be the same)
746
+ xq: query, tensor of shape (..., num_heads, head_dim)
747
+ xk: key, tensor of shape (..., num_heads, head_dim)
748
+ freqs_cis: tensor of shape (..., head_dim/2), dtype=torch.complex64. It contains the precomputed cis(freqs) for each position in the 2D grid.
749
+ Returns:
750
+ xq_out, xk_out: tensors of shape (..., num_heads, head_dim)
751
+ """
752
+ _apply_rope_input_validation(xq, freqs_cis)
753
+ _apply_rope_input_validation(xk, freqs_cis)
754
+
755
+ freqs_cis = freqs_cis.unsqueeze(-2) # ..., 1, head_dim/2
756
+ # ..., num_heads, head_dim/2
757
+ xq_ = torch.view_as_complex(xq.float().view(*xq.shape[:-1], -1, 2))
758
+ xk_ = torch.view_as_complex(xk.float().view(*xq.shape[:-1], -1, 2))
759
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(-2) # ..., num_heads, head_dim
760
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(-2) # ..., num_heads, head_dim
761
+ return xq_out.type_as(xq), xk_out.type_as(xk)
762
+
763
+
764
+ class Siglip2Attention(nn.Module):
765
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
766
+
767
+ def __init__(self, config: Union[Siglip2VisionConfig, Siglip2TextConfig]):
768
+ super().__init__()
769
+ self.config = config
770
+ self.embed_dim = config.hidden_size
771
+ self.num_heads = config.num_attention_heads
772
+ self.head_dim = self.embed_dim // self.num_heads
773
+ if self.head_dim * self.num_heads != self.embed_dim:
774
+ raise ValueError(
775
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
776
+ f" {self.num_heads})."
777
+ )
778
+ self.scale = self.head_dim**-0.5
779
+ self.dropout = config.attention_dropout
780
+ self.is_causal = False
781
+
782
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
783
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
784
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
785
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
786
+
787
+ self.use_windows_attn = config.use_windows_attn
788
+ self.use_rope = config.use_rope
789
+
790
+ def forward(
791
+ self,
792
+ hidden_states: torch.Tensor,
793
+ output_attentions: Optional[bool] = False,
794
+ rope_freqs_cis: Optional[torch.Tensor] = None,
795
+ win_meta_list: Optional[List[Dict]] = None,
796
+ windows_attn: Optional[bool] = False,
797
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
798
+ """Input shape: Batch x Time x Channel"""
799
+
800
+
801
+ batch_size, seq_length, embed_dim = hidden_states.shape
802
+
803
+ queries = self.q_proj(hidden_states)
804
+ keys = self.k_proj(hidden_states)
805
+ values = self.v_proj(hidden_states)
806
+
807
+
808
+ queries = queries.view(batch_size, seq_length, self.num_heads, self.head_dim) # .transpose(1, 2)
809
+ keys = keys.view(batch_size, seq_length, self.num_heads, self.head_dim) # .transpose(1, 2)
810
+ values = values.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
811
+
812
+ if self.use_rope:
813
+ queries, keys = apply_rope(queries, keys, rope_freqs_cis)
814
+
815
+ queries = queries.transpose(1, 2)
816
+ keys = keys.transpose(1, 2)
817
+
818
+ attention_interface: Callable = eager_attention_forward
819
+ if self.config._attn_implementation != "eager":
820
+ if self.config._attn_implementation == "sdpa" and output_attentions:
821
+ logger.warning_once(
822
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
823
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
824
+ )
825
+ if self.config._attn_implementation == "flash_attention_2":
826
+ from transformers.modeling_utils import AttentionInterface
827
+ AttentionInterface._global_mapping['flash_attention_2_packing'] = flash_attention_forward_for_packing
828
+ setattr(AttentionInterface, 'flash_attention_2_packing', flash_attention_forward_for_packing)
829
+ attention_interface = ALL_ATTENTION_FUNCTIONS['flash_attention_2_packing']
830
+ else:
831
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
832
+
833
+ if windows_attn and self.use_windows_attn:
834
+ seq_len_list = [win_meta['win_hw'][0] * win_meta['win_hw'][1] for win_meta in win_meta_list]
835
+ else:
836
+ mapper = defaultdict(lambda: 0)
837
+ for win_meta in win_meta_list:
838
+ mapper[win_meta['img_idx']] += win_meta['win_hw'][0] * win_meta['win_hw'][1]
839
+ seq_len_list = [mapper[i] for i in range(len(mapper))]
840
+
841
+ attention_mask = None
842
+ attn_output, attn_weights = attention_interface(
843
+ self,
844
+ queries,
845
+ keys,
846
+ values,
847
+ attention_mask,
848
+ is_causal=self.is_causal,
849
+ scaling=self.scale,
850
+ dropout=0.0 if not self.training else self.dropout,
851
+ seq_len_list=seq_len_list,
852
+ )
853
+ attn_output = attn_output.reshape(batch_size, seq_length, embed_dim).contiguous()
854
+ attn_output = self.out_proj(attn_output)
855
+
856
+ if not output_attentions:
857
+ attn_weights = None
858
+
859
+ return attn_output, attn_weights
860
+
861
+
862
+ class Siglip2MLP(nn.Module):
863
+ def __init__(self, config):
864
+ super().__init__()
865
+ self.config = config
866
+ self.activation_fn = ACT2FN[config.hidden_act]
867
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
868
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
869
+
870
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
871
+ hidden_states = self.fc1(hidden_states)
872
+ hidden_states = self.activation_fn(hidden_states)
873
+ hidden_states = self.fc2(hidden_states)
874
+ return hidden_states
875
+
876
+
877
+ class Siglip2EncoderLayer(nn.Module):
878
+ def __init__(self, config: Union[Siglip2VisionConfig, Siglip2TextConfig]):
879
+ super().__init__()
880
+ self.embed_dim = config.hidden_size
881
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
882
+ self.self_attn = Siglip2Attention(config)
883
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
884
+ self.mlp = Siglip2MLP(config)
885
+
886
+ def forward(
887
+ self,
888
+ hidden_states: torch.Tensor,
889
+ output_attentions: Optional[bool] = False,
890
+ rope_freqs_cis: Optional[torch.Tensor] = None,
891
+ win_meta_list: Optional[List[Dict]] = None,
892
+ windows_attn: Optional[bool] = False,
893
+ ) -> Tuple[torch.FloatTensor]:
894
+ """
895
+ Args:
896
+ hidden_states (`torch.FloatTensor`):
897
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
898
+ attention_mask (`torch.FloatTensor`):
899
+ Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
900
+ output_attentions (`bool`, *optional*, defaults to `False`):
901
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
902
+ returned tensors for more detail.
903
+ """
904
+ residual = hidden_states
905
+
906
+ hidden_states = self.layer_norm1(hidden_states)
907
+ hidden_states, attn_weights = self.self_attn(
908
+ hidden_states=hidden_states,
909
+ output_attentions=output_attentions,
910
+ rope_freqs_cis=rope_freqs_cis,
911
+ win_meta_list=win_meta_list,
912
+ windows_attn=windows_attn,
913
+ )
914
+ hidden_states = residual + hidden_states
915
+
916
+ residual = hidden_states
917
+ hidden_states = self.layer_norm2(hidden_states)
918
+ hidden_states = self.mlp(hidden_states)
919
+ hidden_states = residual + hidden_states
920
+
921
+ outputs = (hidden_states,)
922
+
923
+ if output_attentions:
924
+ outputs += (attn_weights,)
925
+
926
+ return outputs
927
+
928
+
929
+ class Siglip2Encoder(nn.Module):
930
+ """
931
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
932
+ [`Siglip2EncoderLayer`].
933
+
934
+ Args:
935
+ config: Siglip2Config
936
+ """
937
+
938
+ def __init__(self, config: Siglip2Config):
939
+ super().__init__()
940
+ self.config = config
941
+
942
+ self.rope_2d = Rope2DPosEmb(
943
+ config.hidden_size // config.num_attention_heads, 512, 512, config.window_size
944
+ )
945
+ self.layers = nn.ModuleList([Siglip2EncoderLayer(config) for _ in range(config.num_hidden_layers)])
946
+ self.gradient_checkpointing = False
947
+ self.full_attention_indexes = config.full_attention_indexes
948
+
949
+
950
+ # Ignore copy
951
+ @can_return_tuple
952
+ def forward(
953
+ self,
954
+ inputs_embeds,
955
+ output_attentions: Optional[bool] = None,
956
+ output_hidden_states: Optional[bool] = None,
957
+ win_meta_list: Optional[List[Dict]] = None,
958
+ spatial_shapes: Optional[torch.Tensor] = None,
959
+ ) -> BaseModelOutput:
960
+ r"""
961
+ Args:
962
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
963
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
964
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
965
+ than the model's internal embedding lookup matrix.
966
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
967
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
968
+
969
+ - 1 for tokens that are **not masked**,
970
+ - 0 for tokens that are **masked**.
971
+
972
+ [What are attention masks?](../glossary#attention-mask)
973
+ output_attentions (`bool`, *optional*):
974
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
975
+ returned tensors for more detail.
976
+ output_hidden_states (`bool`, *optional*):
977
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
978
+ for more detail.
979
+ return_dict (`bool`, *optional*):
980
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
981
+ """
982
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
983
+ output_hidden_states = (
984
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
985
+ )
986
+
987
+ encoder_states = () if output_hidden_states else None
988
+ all_attentions = () if output_attentions else None
989
+
990
+ rope_freqs_cis = self.rope_2d.get_freqs_cis(win_meta_list=win_meta_list, device=inputs_embeds.device)
991
+
992
+ hidden_states = inputs_embeds
993
+ for win_idx, encoder_layer in enumerate(self.layers):
994
+
995
+ if win_idx not in self.full_attention_indexes:
996
+ windows_attn = True
997
+ else:
998
+ windows_attn = False
999
+
1000
+ if output_hidden_states:
1001
+ encoder_states = encoder_states + (hidden_states,)
1002
+ if self.gradient_checkpointing and self.training:
1003
+ layer_outputs = self._gradient_checkpointing_func(
1004
+ encoder_layer.__call__,
1005
+ hidden_states,
1006
+ output_attentions,
1007
+ rope_freqs_cis,
1008
+ win_meta_list,
1009
+ windows_attn
1010
+ )
1011
+ else:
1012
+ layer_outputs = encoder_layer(
1013
+ hidden_states,
1014
+ output_attentions=output_attentions,
1015
+ rope_freqs_cis=rope_freqs_cis,
1016
+ win_meta_list=win_meta_list,
1017
+ windows_attn=windows_attn
1018
+ )
1019
+
1020
+ hidden_states = layer_outputs[0]
1021
+
1022
+ if output_attentions:
1023
+ all_attentions = all_attentions + (layer_outputs[1],)
1024
+
1025
+ if output_hidden_states:
1026
+ encoder_states = encoder_states + (hidden_states,)
1027
+
1028
+ return BaseModelOutput(
1029
+ last_hidden_state=hidden_states,
1030
+ hidden_states=encoder_states,
1031
+ attentions=all_attentions,
1032
+ )
1033
+
1034
+
1035
+ def reconstruct_patch_embeddings(last_hidden_state: torch.Tensor, win_meta_list: list[dict], spatial_shapes: torch.Tensor) -> torch.Tensor:
1036
+
1037
+ idx_map = build_idx_map(win_meta_list, spatial_shapes)
1038
+ last_hidden_state = last_hidden_state[:, idx_map, :]
1039
+ return last_hidden_state
1040
+
1041
+ SIGLIP2_VISION_INPUTS_DOCSTRING = r"""
1042
+ Args:
1043
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
1044
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
1045
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
1046
+ output_attentions (`bool`, *optional*):
1047
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1048
+ tensors for more detail.
1049
+ output_hidden_states (`bool`, *optional*):
1050
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1051
+ more detail.
1052
+ interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
1053
+ Whether to interpolate the pre-trained position encodings.
1054
+ return_dict (`bool`, *optional*):
1055
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1056
+ """
1057
+
1058
+
1059
+ class Siglip2VisionTransformer(nn.Module):
1060
+ def __init__(self, config: Siglip2VisionConfig):
1061
+ super().__init__()
1062
+ self.config = config
1063
+ embed_dim = config.hidden_size
1064
+
1065
+ self.embeddings = Siglip2VisionEmbeddings(config)
1066
+ self.encoder = Siglip2Encoder(config)
1067
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
1068
+ self.use_head = True if not hasattr(config, "vision_use_head") else config.vision_use_head
1069
+ if self.use_head:
1070
+ self.head = Siglip2MultiheadAttentionPoolingHead(config)
1071
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1072
+
1073
+ @can_return_tuple
1074
+ @add_start_docstrings_to_model_forward(SIGLIP2_VISION_INPUTS_DOCSTRING)
1075
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=Siglip2VisionConfig)
1076
+ def forward(
1077
+ self,
1078
+ pixel_values: torch.FloatTensor,
1079
+ output_attentions: Optional[bool] = None,
1080
+ output_hidden_states: Optional[bool] = None,
1081
+ ) -> BaseModelOutputWithPooling:
1082
+ r"""
1083
+ Returns:
1084
+
1085
+ """
1086
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1087
+ output_hidden_states = (
1088
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1089
+ )
1090
+
1091
+ windows_tensor, win_meta_list, spatial_shapes, reverse_mapping = self.embeddings(pixel_values)
1092
+
1093
+ encoder_outputs: BaseModelOutput = self.encoder(
1094
+ inputs_embeds=windows_tensor,
1095
+ output_attentions=output_attentions,
1096
+ output_hidden_states=output_hidden_states,
1097
+ win_meta_list=win_meta_list,
1098
+ spatial_shapes=spatial_shapes,
1099
+ )
1100
+
1101
+ last_hidden_state = encoder_outputs.last_hidden_state
1102
+ last_hidden_state = self.post_layernorm(last_hidden_state)
1103
+ last_hidden_state = last_hidden_state[:, reverse_mapping, :]
1104
+ return Siglip2VisionOutput(
1105
+ last_hidden_state=last_hidden_state,
1106
+ hidden_states=encoder_outputs.hidden_states,
1107
+ attentions=encoder_outputs.attentions,
1108
+ spatial_shapes=spatial_shapes,
1109
+ )
1110
+
1111
+
1112
+ def _trunc_normal_(tensor, mean, std, a, b):
1113
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
1114
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
1115
+ def norm_cdf(x):
1116
+ # Computes standard normal cumulative distribution function
1117
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
1118
+
1119
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
1120
+ warnings.warn(
1121
+ "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
1122
+ "The distribution of values may be incorrect.",
1123
+ stacklevel=2,
1124
+ )
1125
+
1126
+ # Values are generated by using a truncated uniform distribution and
1127
+ # then using the inverse CDF for the normal distribution.
1128
+ # Get upper and lower cdf values
1129
+ l = norm_cdf((a - mean) / std)
1130
+ u = norm_cdf((b - mean) / std)
1131
+
1132
+ # Uniformly fill tensor with values from [l, u], then translate to
1133
+ # [2l-1, 2u-1].
1134
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
1135
+
1136
+ # Use inverse cdf transform for normal distribution to get truncated
1137
+ # standard normal
1138
+ tensor.erfinv_()
1139
+
1140
+ # Transform to proper mean, std
1141
+ tensor.mul_(std * math.sqrt(2.0))
1142
+ tensor.add_(mean)
1143
+
1144
+ # Clamp to ensure it's in the proper range
1145
+ tensor.clamp_(min=a, max=b)
1146
+
1147
+
1148
+ def trunc_normal_tf_(
1149
+ tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
1150
+ ) -> torch.Tensor:
1151
+ """Fills the input Tensor with values drawn from a truncated
1152
+ normal distribution. The values are effectively drawn from the
1153
+ normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
1154
+ with values outside :math:`[a, b]` redrawn until they are within
1155
+ the bounds. The method used for generating the random values works
1156
+ best when :math:`a \\leq \text{mean} \\leq b`.
1157
+
1158
+ NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
1159
+ bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
1160
+ and the result is subsequently scaled and shifted by the mean and std args.
1161
+
1162
+ Args:
1163
+ tensor: an n-dimensional `torch.Tensor`
1164
+ mean: the mean of the normal distribution
1165
+ std: the standard deviation of the normal distribution
1166
+ a: the minimum cutoff value
1167
+ b: the maximum cutoff value
1168
+ """
1169
+ with torch.no_grad():
1170
+ _trunc_normal_(tensor, 0, 1.0, a, b)
1171
+ tensor.mul_(std).add_(mean)
1172
+
1173
+
1174
+ def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
1175
+ fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
1176
+ if mode == "fan_in":
1177
+ denom = fan_in
1178
+ elif mode == "fan_out":
1179
+ denom = fan_out
1180
+ elif mode == "fan_avg":
1181
+ denom = (fan_in + fan_out) / 2
1182
+
1183
+ variance = scale / denom
1184
+
1185
+ if distribution == "truncated_normal":
1186
+ # constant is stddev of standard normal truncated to (-2, 2)
1187
+ trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
1188
+ elif distribution == "normal":
1189
+ with torch.no_grad():
1190
+ tensor.normal_(std=math.sqrt(variance))
1191
+ elif distribution == "uniform":
1192
+ bound = math.sqrt(3 * variance)
1193
+ with torch.no_grad():
1194
+ tensor.uniform_(-bound, bound)
1195
+ else:
1196
+ raise ValueError(f"invalid distribution {distribution}")
1197
+
1198
+
1199
+ def lecun_normal_(tensor):
1200
+ variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
1201
+
1202
+
1203
+ def default_flax_embed_init(tensor):
1204
+ variance_scaling_(tensor, mode="fan_in", distribution="normal")
1205
+
1206
+
1207
+ SIGLIP2_START_DOCSTRING = r"""
1208
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1209
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1210
+ etc.)
1211
+
1212
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1213
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1214
+ and behavior.
1215
+
1216
+ Parameters:
1217
+ config ([`Siglip2Config`]): Model configuration class with all the parameters of the model.
1218
+ Initializing with a config file does not load the weights associated with the model, only the
1219
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1220
+ """
1221
+
1222
+ SIGLIP2_INPUTS_DOCSTRING = r"""
1223
+ Args:
1224
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1225
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1226
+ it.
1227
+
1228
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1229
+ [`PreTrainedTokenizer.__call__`] for details.
1230
+
1231
+ [What are input IDs?](../glossary#input-ids)
1232
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1233
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1234
+
1235
+ - 1 for tokens that are **not masked**,
1236
+ - 0 for tokens that are **masked**.
1237
+
1238
+ [What are attention masks?](../glossary#attention-mask)
1239
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1240
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1241
+ config.max_position_embeddings - 1]`.
1242
+
1243
+ [What are position IDs?](../glossary#position-ids)
1244
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
1245
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
1246
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
1247
+ return_loss (`bool`, *optional*):
1248
+ Whether or not to return the contrastive loss.
1249
+ output_attentions (`bool`, *optional*):
1250
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1251
+ tensors for more detail.
1252
+ output_hidden_states (`bool`, *optional*):
1253
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1254
+ more detail.
1255
+ interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
1256
+ Whether to interpolate the pre-trained position encodings.
1257
+ return_dict (`bool`, *optional*):
1258
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1259
+ """
1260
+
1261
+
1262
+ class Siglip2PreTrainedModel(PreTrainedModel):
1263
+ """
1264
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1265
+ models.
1266
+ """
1267
+
1268
+ config_class = Siglip2Config
1269
+ base_model_prefix = "siglip2"
1270
+ supports_gradient_checkpointing = True
1271
+
1272
+ _no_split_modules = [
1273
+ "Siglip2TextEmbeddings",
1274
+ "Siglip2EncoderLayer",
1275
+ "Siglip2VisionEmbeddings",
1276
+ "Siglip2EncoderLayer",
1277
+ "Siglip2MultiheadAttentionPoolingHead",
1278
+ ]
1279
+ _supports_flash_attn_2 = True
1280
+ _supports_sdpa = True
1281
+
1282
+ def _init_weights(self, module):
1283
+ """Initialize the weights"""
1284
+ if isinstance(module, Siglip2VisionEmbeddings):
1285
+ width = (
1286
+ self.config.vision_config.hidden_size
1287
+ if isinstance(self.config, Siglip2Config)
1288
+ else self.config.hidden_size
1289
+ )
1290
+ nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
1291
+ elif isinstance(module, nn.Embedding):
1292
+ default_flax_embed_init(module.weight)
1293
+ elif isinstance(module, Siglip2Attention):
1294
+ nn.init.xavier_uniform_(module.q_proj.weight)
1295
+ nn.init.xavier_uniform_(module.k_proj.weight)
1296
+ nn.init.xavier_uniform_(module.v_proj.weight)
1297
+ nn.init.xavier_uniform_(module.out_proj.weight)
1298
+ nn.init.zeros_(module.q_proj.bias)
1299
+ nn.init.zeros_(module.k_proj.bias)
1300
+ nn.init.zeros_(module.v_proj.bias)
1301
+ nn.init.zeros_(module.out_proj.bias)
1302
+ elif isinstance(module, Siglip2MLP):
1303
+ nn.init.xavier_uniform_(module.fc1.weight)
1304
+ nn.init.xavier_uniform_(module.fc2.weight)
1305
+ nn.init.normal_(module.fc1.bias, std=1e-6)
1306
+ nn.init.normal_(module.fc2.bias, std=1e-6)
1307
+ elif isinstance(module, Siglip2MultiheadAttentionPoolingHead):
1308
+ nn.init.xavier_uniform_(module.probe.data)
1309
+ nn.init.xavier_uniform_(module.attention.in_proj_weight.data)
1310
+ nn.init.zeros_(module.attention.in_proj_bias.data)
1311
+ elif isinstance(module, Siglip2Model):
1312
+ logit_scale_init = torch.log(torch.tensor(1.0))
1313
+ module.logit_scale.data.fill_(logit_scale_init)
1314
+ module.logit_bias.data.zero_()
1315
+ elif isinstance(module, Siglip2ForImageClassification):
1316
+ nn.init.normal_(
1317
+ module.classifier.weight,
1318
+ std=self.config.vision_config.hidden_size**-0.5 * self.config.initializer_factor,
1319
+ )
1320
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
1321
+ lecun_normal_(module.weight)
1322
+ if module.bias is not None:
1323
+ nn.init.zeros_(module.bias)
1324
+ elif isinstance(module, nn.LayerNorm):
1325
+ module.bias.data.zero_()
1326
+ module.weight.data.fill_(1.0)
1327
+
1328
+
1329
+ class Siglip2MultiheadAttentionPoolingHead(nn.Module):
1330
+ """Multihead Attention Pooling."""
1331
+
1332
+ def __init__(self, config: Siglip2VisionConfig):
1333
+ super().__init__()
1334
+
1335
+ self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
1336
+ self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
1337
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
1338
+ self.mlp = Siglip2MLP(config)
1339
+ self.num_heads = config.num_attention_heads
1340
+
1341
+ def forward(self, hidden_state: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
1342
+ batch_size = hidden_state.shape[0]
1343
+ probe = self.probe.repeat(batch_size, 1, 1)
1344
+
1345
+ if attention_mask is not None:
1346
+ target_len, source_len = probe.shape[1], hidden_state.shape[1]
1347
+ attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_state.dtype, target_len)
1348
+ attention_mask = attention_mask.repeat(1, self.num_heads, target_len, 1)
1349
+ attention_mask = attention_mask.reshape(-1, target_len, source_len)
1350
+
1351
+ hidden_state = self.attention(probe, hidden_state, hidden_state, attn_mask=attention_mask)[0]
1352
+
1353
+ residual = hidden_state
1354
+ hidden_state = self.layernorm(hidden_state)
1355
+ hidden_state = residual + self.mlp(hidden_state)
1356
+
1357
+ return hidden_state[:, 0]
1358
+
1359
+
1360
+ @add_start_docstrings(
1361
+ """The vision model from Siglip2 without any head or projection on top.""",
1362
+ SIGLIP2_START_DOCSTRING,
1363
+ )
1364
+ class Siglip2VisionModel(Siglip2PreTrainedModel):
1365
+ config_class = Siglip2VisionConfig
1366
+ main_input_name = "pixel_values"
1367
+
1368
+ def __init__(self, config: Siglip2VisionConfig):
1369
+ super().__init__(config)
1370
+
1371
+ self.vision_model = Siglip2VisionTransformer(config)
1372
+
1373
+ # Initialize weights and apply final processing
1374
+ self.post_init()
1375
+
1376
+ def get_input_embeddings(self) -> nn.Module:
1377
+ return self.vision_model.embeddings.patch_embedding
1378
+
1379
+ @can_return_tuple
1380
+ @add_start_docstrings_to_model_forward(SIGLIP2_VISION_INPUTS_DOCSTRING)
1381
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=Siglip2VisionConfig)
1382
+ def forward(
1383
+ self,
1384
+ pixel_values: torch.FloatTensor,
1385
+ output_attentions: Optional[bool] = None,
1386
+ output_hidden_states: Optional[bool] = None,
1387
+ ) -> BaseModelOutputWithPooling:
1388
+ r"""
1389
+ Returns:
1390
+
1391
+ Examples:
1392
+
1393
+ ```python
1394
+ >>> from PIL import Image
1395
+ >>> import requests
1396
+ >>> from transformers import AutoProcessor, Siglip2VisionModel
1397
+
1398
+ >>> model = Siglip2VisionModel.from_pretrained("google/siglip2-base-patch16-224")
1399
+ >>> processor = AutoProcessor.from_pretrained("google/siglip2-base-patch16-224")
1400
+
1401
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1402
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1403
+
1404
+ >>> inputs = processor(images=image, return_tensors="pt")
1405
+
1406
+ >>> outputs = model(**inputs)
1407
+ >>> last_hidden_state = outputs.last_hidden_state
1408
+ >>> pooled_output = outputs.pooler_output # pooled features
1409
+ ```"""
1410
+ return self.vision_model(
1411
+ pixel_values=pixel_values,
1412
+ output_attentions=output_attentions,
1413
+ output_hidden_states=output_hidden_states,
1414
+ )
1415
+
1416
+
1417
+ __all__ = [
1418
+ "Siglip2VisionModel",
1419
+ ]
preprocessor_config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoImageProcessor": "image_processing_eagle3_vl_fast.Eagle3_VLImageProcessorFast",
4
+ "AutoProcessor": "processing_eagle3_vl.Eagle3_VLProcessor"
5
+ },
6
+ "crop_size": null,
7
+ "data_format": "channels_first",
8
+ "default_to_square": false,
9
+ "device": null,
10
+ "do_center_crop": null,
11
+ "do_convert_rgb": true,
12
+ "do_normalize": true,
13
+ "do_pad": false,
14
+ "do_rescale": true,
15
+ "do_resize": false,
16
+ "image_mean": [
17
+ 0.5,
18
+ 0.5,
19
+ 0.5
20
+ ],
21
+ "image_processor_type": "Eagle3_VLImageProcessorFast",
22
+ "image_std": [
23
+ 0.5,
24
+ 0.5,
25
+ 0.5
26
+ ],
27
+ "input_data_format": null,
28
+ "processor_class": "Eagle3_VLProcessor",
29
+ "resample": 3,
30
+ "rescale_factor": 0.00392156862745098,
31
+ "return_tensors": null,
32
+ "size": {
33
+ "height": 448,
34
+ "width": 448
35
+ }
36
+ }
processing_eagle3_vl.py ADDED
@@ -0,0 +1,868 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Processor class for Eagle3_VL.
17
+ copy from https://github.com/huggingface/transformers/blob/main/src/transformers/models/llava_onevision/processing_llava_onevision.py
18
+ """
19
+
20
+ import math
21
+ import os
22
+ from typing import Iterable, List, Union, Literal
23
+ import base64
24
+ import sys
25
+ import time
26
+ import warnings
27
+ from functools import lru_cache
28
+ from io import BytesIO
29
+ import re
30
+ import requests
31
+ import torch
32
+ import torchvision
33
+ from packaging import version
34
+ from PIL import Image
35
+ from torchvision import io
36
+ from torchvision import transforms
37
+ from torch.nn import functional as F
38
+ from torchvision.transforms import InterpolationMode
39
+ from typing import Optional, Any
40
+ import numpy as np
41
+
42
+ from transformers.feature_extraction_utils import BatchFeature
43
+ from transformers.image_processing_utils import select_best_resolution
44
+ from transformers.image_utils import ImageInput, VideoInput, get_image_size, to_numpy_array
45
+ from transformers.processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
46
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
47
+ from transformers.utils import logging
48
+ from transformers.models.auto import AutoImageProcessor
49
+ import lmdb
50
+ import cv2
51
+ import pickle
52
+ logger = logging.get_logger(__name__)
53
+
54
+ # Highly inspired by https://github.com/QwenLM/Qwen2.5-VL/blob/main/qwen-vl-utils/src/qwen_vl_utils/vision_process.py
55
+
56
+ FRAME_FACTOR = 2
57
+ FPS = 2.0
58
+ FPS_MIN_FRAMES = 4
59
+ FPS_MAX_FRAMES = 256
60
+
61
+ IMAGE_FACTOR = 28
62
+ MIN_PIXELS = 4 * 28 * 28
63
+ MAX_PIXELS = 4096 * 28 * 28
64
+ MAX_RATIO = 200
65
+ IMAGE_MAX_SIZE = 500 * 14
66
+
67
+
68
+ VIDEO_MIN_PIXELS = 128 * 28 * 28
69
+ VIDEO_MAX_PIXELS = 768 * 28 * 28
70
+
71
+ # Set the maximum number of video token inputs.
72
+ # Here, 128K represents the maximum number of input tokens for the VLLM model.
73
+ # Remember to adjust it according to your own configuration.
74
+ VIDEO_TOTAL_PIXELS = int(float(os.environ.get('VIDEO_MAX_PIXELS', 128000 * 28 * 28 * 0.9)))
75
+ logger.info(f"set VIDEO_TOTAL_PIXELS: {VIDEO_TOTAL_PIXELS}")
76
+
77
+
78
+
79
+
80
+ def adjust_by_factor(number: int, factor: int, method: Literal['round', 'ceil', 'floor'] = 'round') -> int:
81
+ """Adjusts 'number' to the nearest, ceiling, or floor multiple of 'factor'."""
82
+ op = {'round': round, 'ceil': math.ceil, 'floor': math.floor}[method]
83
+ return op(number / factor) * factor
84
+
85
+
86
+ def to_rgb(pil_image: Image.Image) -> Image.Image:
87
+ if pil_image.mode == 'RGBA':
88
+ white_background = Image.new("RGB", pil_image.size, (255, 255, 255))
89
+ white_background.paste(pil_image, mask=pil_image.split()[3]) # Use alpha channel as mask
90
+ return white_background
91
+ else:
92
+ return pil_image.convert("RGB")
93
+
94
+ def smart_resize(
95
+ height: int, width: int, factor: int = IMAGE_FACTOR, min_pixels: int = MIN_PIXELS, max_pixels: int = MAX_PIXELS
96
+ ) -> tuple[int, int]:
97
+ """
98
+ Rescales the image so that the following conditions are met:
99
+
100
+ 1. Both dimensions (height and width) are divisible by 'factor'.
101
+
102
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
103
+
104
+ 3. The aspect ratio of the image is maintained as closely as possible.
105
+ """
106
+ if max(height, width) / min(height, width) > MAX_RATIO:
107
+ raise ValueError(
108
+ f"absolute aspect ratio must be smaller than {MAX_RATIO}, got {max(height, width) / min(height, width)}"
109
+ )
110
+
111
+
112
+ h_bar = min(max(factor, adjust_by_factor(height, factor, method='round')), IMAGE_MAX_SIZE)
113
+ w_bar = min(max(factor, adjust_by_factor(width, factor, method='round')), IMAGE_MAX_SIZE)
114
+ if h_bar * w_bar > max_pixels:
115
+ beta = math.sqrt((h_bar * w_bar) / max_pixels)
116
+ h_bar = adjust_by_factor(h_bar / beta, factor, method='floor')
117
+ w_bar = adjust_by_factor(w_bar / beta, factor, method='floor')
118
+ elif h_bar * w_bar < min_pixels:
119
+ beta = math.sqrt(min_pixels / (height * width))
120
+ h_bar = adjust_by_factor(height * beta, factor, method='ceil')
121
+ w_bar = adjust_by_factor(width * beta, factor, method='ceil')
122
+
123
+ return h_bar, w_bar
124
+
125
+
126
+ def read_img_from_lmdb_v2(image_data):
127
+ # special case for AgiBotWorld
128
+ lmdb_file, lmdb_key = image_data['lmdb_file'], image_data['lmdb_key']
129
+ key = lmdb_key.encode('ascii')
130
+ env = lmdb.open(lmdb_file, max_readers=10240, readonly=True, lock=False, readahead=False, meminit=False)
131
+ txn = env.begin()
132
+ value = txn.get(key)
133
+ if value is None:
134
+ print(f"Warning: Key {key} not found.")
135
+ return None
136
+ record = pickle.loads(value)
137
+ image_bgr = cv2.imdecode(np.frombuffer(record['image'], dtype=np.uint8), cv2.IMREAD_COLOR)
138
+ image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
139
+ image = Image.fromarray(image_rgb)
140
+
141
+ return image
142
+
143
+ def parse_lmdb_image_data(image_data):
144
+ lmdb_file = image_data['lmdb_file']
145
+ if not os.path.exists(lmdb_file):
146
+ if "/home/zhidingy/workspace/libs/eagle/Eagle2/" in lmdb_file:
147
+ lmdb_file = lmdb_file.replace("/home/zhidingy/workspace/libs/eagle/Eagle2/", "")
148
+ else:
149
+ raise ValueError(f"LMDB file {lmdb_file} does not exist")
150
+
151
+ # special case for AgiBotWorld, will remove it later
152
+ if 'AgiBotWorld' in image_data['lmdb_file']:
153
+ return read_img_from_lmdb_v2(image_data)
154
+
155
+
156
+ try:
157
+ env = lmdb.open(image_data['lmdb_file'], readonly=True, lock=False, max_readers=10240)
158
+ except Exception as e:
159
+ print(f"Failed to open lmdb file {image_data['lmdb_file']}. Error message: {e}", flush=True)
160
+ raise e
161
+
162
+ with env.begin(write=False) as txn:
163
+ try:
164
+ image_bin = txn.get(image_data['lmdb_key'].encode('ascii'))
165
+ buf = BytesIO(image_bin)
166
+ except Exception as e:
167
+ print(f"Failed to get image from lmdb file {image_data['lmdb_file']}. Error message: {e}", flush=True)
168
+ raise e
169
+ try:
170
+ image = Image.open(buf)
171
+ except Exception as e:
172
+ image_np = np.frombuffer(image_bin, dtype=np.uint8)
173
+ image_bgr = cv2.imdecode(image_np, cv2.IMREAD_COLOR)
174
+ image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
175
+ image = Image.fromarray(image_rgb)
176
+ return image
177
+
178
+ def fetch_image(ele: dict[str, str | Image.Image], size_factor: int = IMAGE_FACTOR) -> Image.Image:
179
+ if "image" in ele:
180
+ image = ele["image"]
181
+ else:
182
+ image = ele["image_url"]
183
+ image_obj = None
184
+ if isinstance(image, Image.Image):
185
+ image_obj = image
186
+ elif isinstance(image, dict) and 'lmdb_file' in image:
187
+ image_obj = parse_lmdb_image_data(image)
188
+ elif image.startswith("http://") or image.startswith("https://"):
189
+ response = requests.get(image, stream=True)
190
+ image_obj = Image.open(BytesIO(response.content))
191
+ elif image.startswith("file://"):
192
+ image_obj = Image.open(image[7:])
193
+ elif image.startswith("data:image"):
194
+ if "base64," in image:
195
+ _, base64_data = image.split("base64,", 1)
196
+ data = base64.b64decode(base64_data)
197
+ image_obj = Image.open(BytesIO(data))
198
+ else:
199
+ image_obj = Image.open(image)
200
+ if image_obj is None:
201
+ raise ValueError(f"Unrecognized image input, support local path, http url, base64 and PIL.Image, got {image}")
202
+ image = to_rgb(image_obj)
203
+ # if 'scale_factor' in ele:
204
+ # scale_factor = ele['scale_factor']
205
+ # image = image.resize((image.width * scale_factor, image.height * scale_factor), Image.BILINEAR)
206
+
207
+ if "resized_height" in ele and "resized_width" in ele:
208
+ resized_height, resized_width = smart_resize(
209
+ ele["resized_height"],
210
+ ele["resized_width"],
211
+ factor=size_factor,
212
+ )
213
+ else:
214
+ width, height = image.size
215
+ min_pixels = ele.get("min_pixels", MIN_PIXELS)
216
+ max_pixels = ele.get("max_pixels", MAX_PIXELS)
217
+ resized_height, resized_width = smart_resize(
218
+ height,
219
+ width,
220
+ factor=size_factor,
221
+ min_pixels=min_pixels,
222
+ max_pixels=max_pixels,
223
+ )
224
+ image = image.resize((resized_width, resized_height))
225
+
226
+ return image
227
+
228
+
229
+ def smart_nframes(
230
+ ele: dict,
231
+ total_frames: int,
232
+ video_fps: int | float,
233
+ ) -> int:
234
+ """calculate the number of frames for video used for model inputs.
235
+
236
+ Args:
237
+ ele (dict): a dict contains the configuration of video.
238
+ support either `fps` or `nframes`:
239
+ - nframes: the number of frames to extract for model inputs.
240
+ - fps: the fps to extract frames for model inputs.
241
+ - min_frames: the minimum number of frames of the video, only used when fps is provided.
242
+ - max_frames: the maximum number of frames of the video, only used when fps is provided.
243
+ total_frames (int): the original total number of frames of the video.
244
+ video_fps (int | float): the original fps of the video.
245
+
246
+ Raises:
247
+ ValueError: nframes should in interval [FRAME_FACTOR, total_frames].
248
+
249
+ Returns:
250
+ int: the number of frames for video used for model inputs.
251
+ """
252
+ assert not ("fps" in ele and "nframes" in ele), "Only accept either `fps` or `nframes`"
253
+ if "nframes" in ele:
254
+ nframes = adjust_by_factor(ele["nframes"], FRAME_FACTOR, method='round')
255
+ else:
256
+ fps = ele.get("fps", FPS)
257
+ min_frames = adjust_by_factor(ele.get("min_frames", FPS_MIN_FRAMES), FRAME_FACTOR, method='ceil')
258
+ max_frames = adjust_by_factor(ele.get("max_frames", min(FPS_MAX_FRAMES, total_frames)), FRAME_FACTOR, method='floor')
259
+ nframes = total_frames / video_fps * fps
260
+ if nframes > total_frames:
261
+ logger.warning(f"smart_nframes: nframes[{nframes}] > total_frames[{total_frames}]")
262
+ nframes = min(min(max(nframes, min_frames), max_frames), total_frames)
263
+ nframes = adjust_by_factor(nframes, FRAME_FACTOR, method='floor')
264
+ if not (FRAME_FACTOR <= nframes and nframes <= total_frames):
265
+ # raise ValueError(f"nframes should in interval [{FRAME_FACTOR}, {total_frames}], but got {nframes}.")
266
+ nframes = total_frames
267
+ return nframes
268
+
269
+ def _read_video_torchvision(
270
+ ele: dict,
271
+ ) -> (torch.Tensor, float, list):
272
+ """read video using torchvision.io.read_video and return also per-frame timestamps"""
273
+ video_path = ele["video"]
274
+ if version.parse(torchvision.__version__) < version.parse("0.19.0"):
275
+ if "http://" in video_path or "https://" in video_path:
276
+ warnings.warn("torchvision < 0.19.0 does not support http/https video path, please upgrade to 0.19.0.")
277
+ if "file://" in video_path:
278
+ video_path = video_path[7:]
279
+ st = time.time()
280
+ video, audio, info = io.read_video(
281
+ video_path,
282
+ start_pts=ele.get("video_start", 0.0),
283
+ end_pts=ele.get("video_end", None),
284
+ pts_unit="sec",
285
+ output_format="TCHW",
286
+ )
287
+ total_frames, video_fps = video.size(0), info["video_fps"]
288
+ logger.info(f"torchvision: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s")
289
+ nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
290
+ # Calculate frame indices and corresponding timestamps (based on video start time)
291
+ idx = torch.linspace(0, total_frames - 1, nframes).round().long()
292
+ start_time = ele.get("video_start", 0.0)
293
+ timestamps = (start_time + idx.to(torch.float32) / video_fps).tolist()
294
+ sample_fps = nframes / max(total_frames, 1e-6) * video_fps
295
+ video = video[idx]
296
+ return video, sample_fps, timestamps
297
+
298
+
299
+
300
+ def is_decord_available() -> bool:
301
+ import importlib.util
302
+
303
+ return importlib.util.find_spec("decord") is not None
304
+
305
+ def _read_video_decord(
306
+ ele: dict,
307
+ ) -> (torch.Tensor, float, list):
308
+ """read video using decord.VideoReader and return also per-frame timestamps"""
309
+ import decord
310
+ video_path = ele["video"]
311
+ st = time.time()
312
+ vr = decord.VideoReader(video_path)
313
+ if 'video_start' in ele or 'video_end' in ele:
314
+ raise NotImplementedError("not support start_pts and end_pts in decord for now.")
315
+ total_frames, video_fps = len(vr), vr.get_avg_fps()
316
+ logger.info(f"decord: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s")
317
+ nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
318
+ idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
319
+ start_time = ele.get("video_start", 0.0) # TODO:
320
+ timestamps = [start_time + i / video_fps for i in idx]
321
+ video = vr.get_batch(idx).asnumpy()
322
+ video = torch.tensor(video).permute(0, 3, 1, 2) # Convert to TCHW format
323
+ sample_fps = nframes / max(total_frames, 1e-6) * video_fps
324
+ return video, sample_fps, timestamps
325
+
326
+
327
+ VIDEO_READER_BACKENDS = {
328
+ "decord": _read_video_decord,
329
+ "torchvision": _read_video_torchvision,
330
+ }
331
+
332
+
333
+ @lru_cache(maxsize=1)
334
+ def get_video_reader_backend() -> str:
335
+ if is_decord_available():
336
+ video_reader_backend = "decord"
337
+ else:
338
+ video_reader_backend = "torchvision"
339
+ return video_reader_backend
340
+
341
+
342
+
343
+
344
+ def fetch_video(ele: dict, image_factor: int = IMAGE_FACTOR, return_video_sample_fps: bool = False) -> torch.Tensor | list[Image.Image]:
345
+
346
+ if isinstance(ele["video"], str):
347
+ video_reader_backend = get_video_reader_backend()
348
+ try:
349
+ video, sample_fps, timestamps = VIDEO_READER_BACKENDS[video_reader_backend](ele)
350
+ except Exception as e:
351
+ logger.warning(f"video_reader_backend {video_reader_backend} error, use torchvision as default, msg: {e}")
352
+ video, sample_fps, timestamps = VIDEO_READER_BACKENDS["torchvision"](ele)
353
+
354
+ nframes, _, height, width = video.shape
355
+
356
+ min_pixels = ele.get("min_pixels", VIDEO_MIN_PIXELS)
357
+ total_pixels = ele.get("total_pixels", VIDEO_TOTAL_PIXELS)
358
+ max_pixels = max(min(VIDEO_MAX_PIXELS, total_pixels / nframes * FRAME_FACTOR), int(min_pixels * 1.05))
359
+ max_pixels_supposed = ele.get("max_pixels", max_pixels)
360
+ if max_pixels_supposed > max_pixels:
361
+ logger.warning(f"The given max_pixels[{max_pixels_supposed}] exceeds limit[{max_pixels}].")
362
+ max_pixels = min(max_pixels_supposed, max_pixels)
363
+ if "resized_height" in ele and "resized_width" in ele:
364
+ resized_height, resized_width = smart_resize(
365
+ ele["resized_height"],
366
+ ele["resized_width"],
367
+ factor=image_factor,
368
+ )
369
+ else:
370
+ resized_height, resized_width = smart_resize(
371
+ height,
372
+ width,
373
+ factor=image_factor,
374
+ min_pixels=min_pixels,
375
+ max_pixels=max_pixels,
376
+ )
377
+ video = transforms.functional.resize(
378
+ video,
379
+ [resized_height, resized_width],
380
+ interpolation=InterpolationMode.BICUBIC,
381
+ antialias=True,
382
+ ).float()
383
+ if return_video_sample_fps:
384
+ return video, sample_fps, timestamps
385
+ return video
386
+
387
+ else:
388
+ assert isinstance(ele["video"], (list, tuple))
389
+ process_info = ele.copy()
390
+ process_info.pop("type", None)
391
+ process_info.pop("video", None)
392
+ images = [
393
+ fetch_image({"image": video_element, **process_info}, size_factor=image_factor)
394
+ for video_element in ele["video"]
395
+ ]
396
+ nframes = adjust_by_factor(len(images), FRAME_FACTOR, method='ceil')
397
+ if len(images) < nframes:
398
+ images.extend([images[-1]] * (nframes - len(images)))
399
+
400
+ timestamps = [-1 for i in range(nframes)] # not sure about this
401
+ if return_video_sample_fps:
402
+ return images, process_info.pop("fps", 2.0), timestamps
403
+ return images
404
+
405
+ class Eagle3_VLProcessorKwargs(ProcessingKwargs, total=False):
406
+ # see processing_utils.ProcessingKwargs documentation for usage.
407
+ _defaults = {
408
+ "text_kwargs": {
409
+ "padding": False,
410
+ },
411
+ "images_kwargs": {},
412
+ "videos_kwargs": {},
413
+ }
414
+
415
+
416
+ class Eagle3_VLProcessor(ProcessorMixin):
417
+ r"""
418
+ Constructs a Eagle3_VL processor which wraps a Eagle3_VL video processor, Eagle3_VL image processor and a Eagle3_VL tokenizer into a single processor.
419
+
420
+ [`Eagle3_VLProcessor`] offers all the functionalities of [`Eagle3_VLVideoProcessor`], [`Eagle3_VLImageProcessor`] and [`Eagle3_VLTokenizer`]. See the
421
+ [`~Eagle3_VLVideoProcessor.__call__`], [`~Eagle3_VLProcessor.__call__`] and [`~Eagle3_VLProcessor.decode`] for more information.
422
+
423
+ Args:
424
+ image_processor ([`LlavaOnevisionImageProcessor`], *optional*):
425
+ The image processor is a required input.
426
+ tokenizer ([`LlamaTokenizerFast`], *optional*):
427
+ The tokenizer is a required input.
428
+ num_image_tokens (`int`, *optional*):
429
+ Number of image tokens for one imagethat will be returned by vision tower.
430
+ vision_feature_select_strategy (`str`, *optional*):
431
+ The feature selection strategy used to select the vision feature from the vision backbone.
432
+ Shoudl be same as in model's config
433
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
434
+ in a chat into a tokenizable string.
435
+ image_token (`str`, *optional*, defaults to `"<image>"`):
436
+ Special token used to denote image location.
437
+ video_token (`str`, *optional*, defaults to `"<video>"`):
438
+ Special token used to denote video location.
439
+ """
440
+
441
+ attributes = ["image_processor", "tokenizer"]
442
+ valid_kwargs = [
443
+ "chat_template",
444
+ "num_image_tokens",
445
+ "vision_feature_select_strategy",
446
+ "image_token",
447
+ "video_token",
448
+ "images_kwargs",
449
+ "videos_kwargs",
450
+ "text_kwargs",
451
+ ]
452
+ image_processor_class = "AutoImageProcessor"
453
+ tokenizer_class = "AutoTokenizer"
454
+
455
+ def __init__(
456
+ self,
457
+ image_processor=None,
458
+ tokenizer=None,
459
+ vision_feature_select_strategy=None,
460
+ chat_template=None,
461
+ image_token='<IMG_CONTEXT>',
462
+ video_token='<IMG_CONTEXT>',
463
+ pixels_per_token=28*28,
464
+ image_placeholder='image',
465
+ video_placeholder='video',
466
+ image_start_token='<img>',
467
+ image_end_token='</img>',
468
+ **kwargs,
469
+ ):
470
+ self.vision_feature_select_strategy = vision_feature_select_strategy
471
+ self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token
472
+ self.video_token = tokenizer.video_token if hasattr(tokenizer, "video_token") else video_token
473
+ self.image_token_id = (
474
+ tokenizer.image_token_id
475
+ if getattr(tokenizer, "image_token_id", None)
476
+ else tokenizer.convert_tokens_to_ids(self.image_token)
477
+ )
478
+ self.video_token_id = (
479
+ tokenizer.video_token_id
480
+ if getattr(tokenizer, "video_token_id", None)
481
+ else tokenizer.convert_tokens_to_ids(self.video_token)
482
+ )
483
+ self.image_placeholder = image_placeholder
484
+ self.video_placeholder = video_placeholder
485
+ self.pixels_per_token = pixels_per_token
486
+ self.image_start_token = image_start_token
487
+ self.image_end_token = image_end_token
488
+ if 'auto_map' in kwargs:
489
+ self.auto_map = kwargs['auto_map']
490
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
491
+
492
+
493
+ def replace_media_placeholder(self, text, image_list, video_list, timestamps_list, fps_list, **output_kwargs):
494
+
495
+ num_of_images_in_this_sample = 0
496
+ num_of_videos_in_this_sample = 0
497
+ # Regular expression pattern to match formats like <image-1> or <video-2>
498
+ pattern = re.compile(rf"<({self.image_placeholder}|{self.video_placeholder})-(\d+)>")
499
+ unified_frame_list = []
500
+
501
+ # Function to replace tags in a single text
502
+ def replace_in_text(text):
503
+ # repl callback function for each match replacement operation
504
+ def repl(match):
505
+ nonlocal unified_frame_list
506
+ nonlocal num_of_images_in_this_sample
507
+ nonlocal num_of_videos_in_this_sample
508
+ media_type = match.group(1) # 'image' or 'video'
509
+ idx_in_list = int(match.group(2)) - 1 # Convert to list index (0-based)
510
+ # Select the corresponding path based on media type
511
+ idx_mapper = {0: "first", 1: "second", 2: "third", 3: "fourth", 4: "fifth", 5: "sixth", 6: "seventh", 7: "eighth", 8: "ninth", 9: "tenth"}
512
+ if media_type == 'image':
513
+ image_inputs = self.image_processor(images=[image_list[idx_in_list]], videos=None, **output_kwargs["images_kwargs"])
514
+ image_height, image_width = image_inputs['image_sizes'][0]
515
+ assert image_height <= IMAGE_MAX_SIZE and image_width <= IMAGE_MAX_SIZE, f"image_height: {image_height}, image_width: {image_width}"
516
+ image_tokens = image_height * image_width // self.pixels_per_token
517
+ special_placeholder = f"<image {idx_in_list+1}>{self.image_start_token}{self.image_token * image_tokens}{self.image_end_token}"
518
+ unified_frame_list.append(image_inputs)
519
+ num_of_images_in_this_sample += 1
520
+
521
+ elif media_type == 'video':
522
+
523
+ video_inputs = self.image_processor(images=None, videos=video_list[idx_in_list], **output_kwargs["videos_kwargs"])
524
+ N, C, image_height, image_width = video_inputs['pixel_values'].shape
525
+ image_tokens = image_height * image_width // self.pixels_per_token
526
+
527
+ assert image_height <= IMAGE_MAX_SIZE and image_width <= IMAGE_MAX_SIZE, f"image_height: {image_height}, image_width: {image_width}"
528
+
529
+ if timestamps_list is not None and -1 not in timestamps_list:
530
+ frame_timestamps = timestamps_list[idx_in_list]
531
+ else:
532
+ frame_timestamps = None
533
+ sampled_fps = fps_list[idx_in_list] if fps_list is not None else None
534
+
535
+ num_of_tokens_list = [image_tokens] * N
536
+
537
+ if frame_timestamps is not None:
538
+ assert len(frame_timestamps) == len(num_of_tokens_list), f"The number of timestamps is not equal to the number of frames: {len(frame_timestamps)} != {len(num_of_tokens_list)}"
539
+ special_placeholder = [f"Frame {i+1} sample at {frame_timestamps[i]:.2f}s: {self.image_start_token}{self.image_token * num_of_tokens}{self.image_end_token}" for i, num_of_tokens in enumerate(num_of_tokens_list)]
540
+ else:
541
+ special_placeholder = [f"Frame {i+1}: {self.image_start_token}{self.image_token * num_of_tokens}{self.image_end_token}" for i, num_of_tokens in enumerate(num_of_tokens_list)]
542
+
543
+ if sampled_fps is not None:
544
+ special_placeholder = f"The {idx_mapper[idx_in_list]} video sampled with {sampled_fps:.2f} fps: " + "".join(special_placeholder)
545
+ else:
546
+ special_placeholder = f"The {idx_mapper[idx_in_list]} video: " + "".join(special_placeholder)
547
+ unified_frame_list.append(video_inputs)
548
+ num_of_videos_in_this_sample += 1
549
+ else:
550
+ raise ValueError(f'Unknown media type: {media_type}')
551
+ return special_placeholder
552
+ return pattern.sub(repl, text)
553
+ text = replace_in_text(text)
554
+ if len(unified_frame_list) > 0:
555
+ pixel_values = [frame['pixel_values'] for frame in unified_frame_list]
556
+ image_sizes = torch.cat([frame['image_sizes'] for frame in unified_frame_list], dim=0)
557
+ else:
558
+ pixel_values = []
559
+ image_sizes = []
560
+ return text, pixel_values, image_sizes, num_of_images_in_this_sample, num_of_videos_in_this_sample
561
+
562
+ def __call__(
563
+ self,
564
+ images: ImageInput = None,
565
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
566
+ audio=None,
567
+ videos: VideoInput = None,
568
+ **kwargs: Unpack[Eagle3_VLProcessorKwargs],
569
+ ) -> BatchFeature:
570
+ """
571
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
572
+ and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
573
+ the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
574
+ LlavaNextImageProcessor's [`~LlavaNextImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
575
+ of the above two methods for more information.
576
+
577
+ Args:
578
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
579
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
580
+ tensor. Both channels-first and channels-last formats are supported.
581
+ text (`str`, `List[str]`, `List[List[str]]`):
582
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
583
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
584
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
585
+ videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
586
+ The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
587
+
588
+ Returns:
589
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
590
+
591
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
592
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
593
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
594
+ `None`).
595
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
596
+ - **pixel_values_videos** -- Pixel values of a video input to be fed to a model. Returned when `videos` is not `None`.
597
+ - **image_sizes** -- Size of each image that will be used to unpad an image. Returned when `images` is not `None`.
598
+ """
599
+
600
+
601
+ output_kwargs = self._merge_kwargs(
602
+ Eagle3_VLProcessorKwargs,
603
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
604
+ **kwargs,
605
+ )
606
+
607
+ if isinstance(text, str):
608
+ text_list = [text]
609
+ elif not isinstance(text, list) and not isinstance(text[0], str):
610
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
611
+ elif isinstance(text, list) and isinstance(text[0], str):
612
+ text_list = text
613
+
614
+ if images is None: images = []
615
+ if videos is None: videos = []
616
+
617
+ pixel_values_list = []
618
+ image_sizes_list = []
619
+ new_sample_list = []
620
+ image_start_idx = 0
621
+ video_start_idx = 0
622
+ timestamps_batch = output_kwargs['videos_kwargs'].pop("timestamps", None)
623
+ fps_batch = output_kwargs['videos_kwargs'].pop("fps", None)
624
+ for sample in text_list:
625
+ timestamps_list = timestamps_batch[video_start_idx:] if timestamps_batch is not None else None
626
+ fps_list = fps_batch[video_start_idx:] if fps_batch is not None else None
627
+ sample, pixel_values, image_sizes, num_of_images_in_this_sample, num_of_videos_in_this_sample = self.replace_media_placeholder(sample, images[image_start_idx:], videos[video_start_idx:], timestamps_list, fps_list, **output_kwargs)
628
+ new_sample_list.append(sample)
629
+ pixel_values_list.extend(pixel_values)
630
+ image_sizes_list.extend(image_sizes)
631
+
632
+ image_start_idx += num_of_images_in_this_sample
633
+ video_start_idx += num_of_videos_in_this_sample
634
+
635
+ if len(pixel_values) > 0:
636
+ image_inputs = {
637
+ 'pixel_values':pixel_values_list,
638
+ 'image_sizes': torch.stack(image_sizes_list, dim=0)
639
+ }
640
+ else:
641
+ image_inputs = {}
642
+ video_inputs = {}
643
+ text_inputs = self.tokenizer(new_sample_list, **output_kwargs["text_kwargs"])
644
+ return BatchFeature(data={**text_inputs, **image_inputs, **video_inputs})
645
+
646
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
647
+ def batch_decode(self, *args, **kwargs):
648
+ """
649
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
650
+ refer to the docstring of this method for more information.
651
+ """
652
+ return self.tokenizer.batch_decode(*args, **kwargs)
653
+
654
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
655
+ def decode(self, *args, **kwargs):
656
+ """
657
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
658
+ the docstring of this method for more information.
659
+ """
660
+ return self.tokenizer.decode(*args, **kwargs)
661
+
662
+ @property
663
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
664
+ def model_input_names(self):
665
+ tokenizer_input_names = self.tokenizer.model_input_names
666
+ image_processor_input_names = self.image_processor.model_input_names
667
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
668
+
669
+ # override to save video-config in a separate config file
670
+ def save_pretrained(self, save_directory, **kwargs):
671
+ if os.path.isfile(save_directory):
672
+ raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file")
673
+ os.makedirs(save_directory, exist_ok=True)
674
+
675
+ outputs = super().save_pretrained(save_directory, **kwargs)
676
+ return outputs
677
+
678
+ # override to load video-config from a separate config file
679
+ @classmethod
680
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
681
+ processor = super().from_pretrained(pretrained_model_name_or_path, **kwargs)
682
+
683
+ # if return_unused_kwargs a tuple is returned where the second element is 'unused_kwargs'
684
+ if isinstance(processor, tuple):
685
+ processor = processor[0]
686
+ return processor
687
+
688
+ # Copy from https://github.com/QwenLM/Qwen2.5-VL/blob/main/qwen-vl-utils/src/qwen_vl_utils/vision_process.py
689
+ def process_vision_info(
690
+ self,
691
+ conversations: list[dict] | list[list[dict]],
692
+ return_video_kwargs: bool = False,
693
+ ) -> tuple[list[Image.Image] | None, list[torch.Tensor | list[Image.Image]] | None, Optional[dict]]:
694
+
695
+ vision_infos = self.extract_vision_info(conversations)
696
+ ## Read images or videos
697
+ image_inputs = []
698
+ video_inputs = []
699
+ video_sample_fps_list = []
700
+ video_timestamps_list = []
701
+ for vision_info in vision_infos:
702
+ if "image" in vision_info or "image_url" in vision_info:
703
+ image_inputs.append(fetch_image(vision_info))
704
+ elif "video" in vision_info:
705
+ video_input, video_sample_fps, video_timestamps = fetch_video(vision_info, return_video_sample_fps=True)
706
+ video_sample_fps_list.append(video_sample_fps)
707
+ video_inputs.append(video_input)
708
+ video_timestamps_list.append(video_timestamps)
709
+ else:
710
+ raise ValueError("image, image_url or video should in content.")
711
+ if len(image_inputs) == 0:
712
+ image_inputs = None
713
+ if len(video_inputs) == 0:
714
+ video_inputs = None
715
+ if return_video_kwargs:
716
+ return image_inputs, video_inputs, {'fps': video_sample_fps_list, 'timestamps': video_timestamps_list}
717
+ return image_inputs, video_inputs
718
+
719
+ def extract_vision_info(self, conversations: list[dict] | list[list[dict]]) -> list[dict]:
720
+ vision_infos = []
721
+ if isinstance(conversations[0], dict):
722
+ conversations = [conversations]
723
+ for conversation in conversations:
724
+ for message in conversation:
725
+ if isinstance(message["content"], list):
726
+ for ele in message["content"]:
727
+ if (
728
+ "image" in ele
729
+ or "image_url" in ele
730
+ or "video" in ele
731
+ or ele["type"] in ("image", "image_url", "video")
732
+ ):
733
+ vision_infos.append(ele)
734
+ return vision_infos
735
+
736
+ def py_apply_chat_template(self, messages, tokenize=False, add_generation_prompt=False):
737
+ """
738
+ Renders a chat conversation using a custom template with verification of tokens.
739
+
740
+ The purpose is to check for the existence of tokens like "<image-1>" or "<video-1>"
741
+ in the message text and skip adding them if they already exist.
742
+
743
+ Args:
744
+ messages (list): A list of message dictionaries. Each message should contain:
745
+ - 'role': The role of the speaker (e.g., 'system', 'user', 'assistant').
746
+ - 'content': Either a string or a list of content blocks. In the list each block may contain:
747
+ * 'type': The type of content, such as 'image' or 'video'.
748
+ * 'text': The actual text if present.
749
+ * Other keys such as 'image', 'image_url', or 'video'.
750
+ add_generation_prompt (bool): If True, appends "<|im_start|>assistant" at the end of the rendered string.
751
+ tokenize (bool): If True, tokenize the rendered string.
752
+ Returns:
753
+ str: The final rendered chat string according to the specified template.
754
+ """
755
+ assert tokenize == False, "tokenize is not supported yet"
756
+ result = ""
757
+ image_count = 0
758
+ video_count = 0
759
+
760
+ message_text = ""
761
+ for idx, message in enumerate(messages):
762
+ if message.get('role') != 'user': continue
763
+ # If content is a string, simply output it.
764
+ content = message.get('content')
765
+ if isinstance(content, str):
766
+ message_text += content
767
+ elif isinstance(content, list):
768
+ # Process each content item.
769
+ for item in content:
770
+ # If the block is a dictionary and contains text, add it to message_text.
771
+ if isinstance(item, dict) and "text" in item:
772
+ message_text += item["text"]
773
+ # If an item is already a string in the list, add it directly.
774
+ elif isinstance(item, str):
775
+ message_text += item
776
+
777
+ for idx, message in enumerate(messages):
778
+ # If the first message is not from the system, prepend a default system message.
779
+ if idx == 0 and message.get('role') != 'system':
780
+ result += "<|im_start|>system\n"
781
+ result += "You are a helpful assistant.\n"
782
+ result += "<|im_end|>\n"
783
+
784
+ # Start the current message block with its role.
785
+ result += f"<|im_start|>{message.get('role', '')}\n"
786
+ content = message.get('content')
787
+
788
+ # If content is a string, simply output it.
789
+ if isinstance(content, str):
790
+ result += content
791
+ result += "<|im_end|>\n"
792
+ else:
793
+ # Process each content item.
794
+ for item in content:
795
+ # Check if the item is an image (explicitly by type or by key presence).
796
+ if (isinstance(item, dict) and (item.get('type') == 'image' or 'image' in item or 'image_url' in item)):
797
+ image_count += 1
798
+ candidate_token = f"<image-{image_count}>"
799
+ # Only add the token if it is not already present in the collected text.
800
+ if candidate_token not in message_text:
801
+ result += candidate_token
802
+ # Check if the item is a video.
803
+ elif (isinstance(item, dict) and (item.get('type') == 'video' or 'video' in item)):
804
+ video_count += 1
805
+ candidate_token = f"<video-{video_count}>"
806
+ # Only add the token if it is not already present.
807
+ if candidate_token not in message_text:
808
+ result += candidate_token
809
+ # If the item contains text, add it.
810
+ elif isinstance(item, dict) and 'text' in item:
811
+ result += item['text']
812
+ # If the item is a string (and not handled already), add it.
813
+ elif isinstance(item, str):
814
+ result += item
815
+ result += "<|im_end|>\n"
816
+
817
+ # Optionally add assistant generation prompt at the end.
818
+ if add_generation_prompt:
819
+ result += "<|im_start|>assistant\n"
820
+
821
+ return result
822
+
823
+
824
+ @classmethod
825
+ def from_args_and_dict(cls, args, processor_dict: dict[str, Any], **kwargs):
826
+ """
827
+ Instantiates a type of [`~processing_utils.ProcessingMixin`] from a Python dictionary of parameters.
828
+
829
+ Args:
830
+ processor_dict (`Dict[str, Any]`):
831
+ Dictionary that will be used to instantiate the processor object. Such a dictionary can be
832
+ retrieved from a pretrained checkpoint by leveraging the
833
+ [`~processing_utils.ProcessingMixin.to_dict`] method.
834
+ kwargs (`Dict[str, Any]`):
835
+ Additional parameters from which to initialize the processor object.
836
+
837
+ Returns:
838
+ [`~processing_utils.ProcessingMixin`]: The processor object instantiated from those
839
+ parameters.
840
+ """
841
+ processor_dict = processor_dict.copy()
842
+ return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
843
+
844
+ # We have to pop up some unused (but specific) kwargs and then validate that it doesn't contain unused kwargs
845
+ # If we don't pop, some specific kwargs will raise a warning
846
+ if "processor_class" in processor_dict:
847
+ del processor_dict["processor_class"]
848
+
849
+ #if "auto_map" in processor_dict:
850
+ # del processor_dict["auto_map"]
851
+
852
+ unused_kwargs = cls.validate_init_kwargs(processor_config=processor_dict, valid_kwargs=cls.valid_kwargs)
853
+ processor = cls(*args, **processor_dict)
854
+
855
+ # Update processor with kwargs if needed
856
+ for key in set(kwargs.keys()):
857
+ if hasattr(processor, key):
858
+ setattr(processor, key, kwargs.pop(key))
859
+
860
+ kwargs.update(unused_kwargs)
861
+ logger.info(f"Processor {processor}")
862
+ if return_unused_kwargs:
863
+ return processor, kwargs
864
+ else:
865
+ return processor
866
+
867
+
868
+ __all__ = ["Eagle3_VLProcessor"]
processor_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "processing_eagle3_vl.Eagle3_VLProcessor"
4
+ },
5
+ "image_end_token": "</img>",
6
+ "image_placeholder": "image",
7
+ "image_start_token": "<img>",
8
+ "image_token": "<IMG_CONTEXT>",
9
+ "pixels_per_token": 784,
10
+ "processor_class": "Eagle3_VLProcessor",
11
+ "video_placeholder": "video",
12
+ "video_token": "<IMG_CONTEXT>",
13
+ "vision_feature_select_strategy": null
14
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "<IMG_CONTEXT>",
17
+ "<img>",
18
+ "</img>",
19
+ "<box>",
20
+ "</box>",
21
+ "<quad>",
22
+ "</quad>",
23
+ "<ref>",
24
+ "</ref>",
25
+ "<interval>",
26
+ "</interval>"
27
+ ],
28
+ "eos_token": {
29
+ "content": "<|im_end|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false
34
+ },
35
+ "pad_token": {
36
+ "content": "<|endoftext|>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false
41
+ }
42
+ }
tokenizer_config.json ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": false,
5
+ "added_tokens_decoder": {
6
+ "151643": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "151644": {
15
+ "content": "<|im_start|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "151645": {
23
+ "content": "<|im_end|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "151646": {
31
+ "content": "<|object_ref_start|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "151647": {
39
+ "content": "<|object_ref_end|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "151648": {
47
+ "content": "<|box_start|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "151649": {
55
+ "content": "<|box_end|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "151650": {
63
+ "content": "<|quad_start|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "151651": {
71
+ "content": "<|quad_end|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "151652": {
79
+ "content": "<|vision_start|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "151653": {
87
+ "content": "<|vision_end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "151654": {
95
+ "content": "<|vision_pad|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "151655": {
103
+ "content": "<|image_pad|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "151656": {
111
+ "content": "<|video_pad|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": true
117
+ },
118
+ "151657": {
119
+ "content": "<tool_call>",
120
+ "lstrip": false,
121
+ "normalized": false,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": false
125
+ },
126
+ "151658": {
127
+ "content": "</tool_call>",
128
+ "lstrip": false,
129
+ "normalized": false,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": false
133
+ },
134
+ "151659": {
135
+ "content": "<|fim_prefix|>",
136
+ "lstrip": false,
137
+ "normalized": false,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": false
141
+ },
142
+ "151660": {
143
+ "content": "<|fim_middle|>",
144
+ "lstrip": false,
145
+ "normalized": false,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": false
149
+ },
150
+ "151661": {
151
+ "content": "<|fim_suffix|>",
152
+ "lstrip": false,
153
+ "normalized": false,
154
+ "rstrip": false,
155
+ "single_word": false,
156
+ "special": false
157
+ },
158
+ "151662": {
159
+ "content": "<|fim_pad|>",
160
+ "lstrip": false,
161
+ "normalized": false,
162
+ "rstrip": false,
163
+ "single_word": false,
164
+ "special": false
165
+ },
166
+ "151663": {
167
+ "content": "<|repo_name|>",
168
+ "lstrip": false,
169
+ "normalized": false,
170
+ "rstrip": false,
171
+ "single_word": false,
172
+ "special": false
173
+ },
174
+ "151664": {
175
+ "content": "<|file_sep|>",
176
+ "lstrip": false,
177
+ "normalized": false,
178
+ "rstrip": false,
179
+ "single_word": false,
180
+ "special": false
181
+ },
182
+ "151665": {
183
+ "content": "<tool_response>",
184
+ "lstrip": false,
185
+ "normalized": false,
186
+ "rstrip": false,
187
+ "single_word": false,
188
+ "special": false
189
+ },
190
+ "151666": {
191
+ "content": "</tool_response>",
192
+ "lstrip": false,
193
+ "normalized": false,
194
+ "rstrip": false,
195
+ "single_word": false,
196
+ "special": false
197
+ },
198
+ "151667": {
199
+ "content": "<think>",
200
+ "lstrip": false,
201
+ "normalized": false,
202
+ "rstrip": false,
203
+ "single_word": false,
204
+ "special": false
205
+ },
206
+ "151668": {
207
+ "content": "</think>",
208
+ "lstrip": false,
209
+ "normalized": false,
210
+ "rstrip": false,
211
+ "single_word": false,
212
+ "special": false
213
+ },
214
+ "151669": {
215
+ "content": "<IMG_CONTEXT>",
216
+ "lstrip": false,
217
+ "normalized": false,
218
+ "rstrip": false,
219
+ "single_word": false,
220
+ "special": true
221
+ },
222
+ "151670": {
223
+ "content": "<img>",
224
+ "lstrip": false,
225
+ "normalized": false,
226
+ "rstrip": false,
227
+ "single_word": false,
228
+ "special": true
229
+ },
230
+ "151671": {
231
+ "content": "</img>",
232
+ "lstrip": false,
233
+ "normalized": false,
234
+ "rstrip": false,
235
+ "single_word": false,
236
+ "special": true
237
+ },
238
+ "151672": {
239
+ "content": "<box>",
240
+ "lstrip": false,
241
+ "normalized": false,
242
+ "rstrip": false,
243
+ "single_word": false,
244
+ "special": true
245
+ },
246
+ "151673": {
247
+ "content": "</box>",
248
+ "lstrip": false,
249
+ "normalized": false,
250
+ "rstrip": false,
251
+ "single_word": false,
252
+ "special": true
253
+ },
254
+ "151674": {
255
+ "content": "<quad>",
256
+ "lstrip": false,
257
+ "normalized": false,
258
+ "rstrip": false,
259
+ "single_word": false,
260
+ "special": true
261
+ },
262
+ "151675": {
263
+ "content": "</quad>",
264
+ "lstrip": false,
265
+ "normalized": false,
266
+ "rstrip": false,
267
+ "single_word": false,
268
+ "special": true
269
+ },
270
+ "151676": {
271
+ "content": "<ref>",
272
+ "lstrip": false,
273
+ "normalized": false,
274
+ "rstrip": false,
275
+ "single_word": false,
276
+ "special": true
277
+ },
278
+ "151677": {
279
+ "content": "</ref>",
280
+ "lstrip": false,
281
+ "normalized": false,
282
+ "rstrip": false,
283
+ "single_word": false,
284
+ "special": true
285
+ },
286
+ "151678": {
287
+ "content": "<interval>",
288
+ "lstrip": false,
289
+ "normalized": false,
290
+ "rstrip": false,
291
+ "single_word": false,
292
+ "special": true
293
+ },
294
+ "151679": {
295
+ "content": "</interval>",
296
+ "lstrip": false,
297
+ "normalized": false,
298
+ "rstrip": false,
299
+ "single_word": false,
300
+ "special": true
301
+ }
302
+ },
303
+ "additional_special_tokens": [
304
+ "<|im_start|>",
305
+ "<|im_end|>",
306
+ "<|object_ref_start|>",
307
+ "<|object_ref_end|>",
308
+ "<|box_start|>",
309
+ "<|box_end|>",
310
+ "<|quad_start|>",
311
+ "<|quad_end|>",
312
+ "<|vision_start|>",
313
+ "<|vision_end|>",
314
+ "<|vision_pad|>",
315
+ "<|image_pad|>",
316
+ "<|video_pad|>",
317
+ "<IMG_CONTEXT>",
318
+ "<img>",
319
+ "</img>",
320
+ "<box>",
321
+ "</box>",
322
+ "<quad>",
323
+ "</quad>",
324
+ "<ref>",
325
+ "</ref>",
326
+ "<interval>",
327
+ "</interval>"
328
+ ],
329
+ "auto_map": {
330
+ "AutoProcessor": "processing_eagle3_vl.Eagle3_VLProcessor"
331
+ },
332
+ "bos_token": null,
333
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if message.content is string %}\n {%- set content = message.content %}\n {%- else %}\n {%- set content = '' %}\n {%- endif %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in content %}\n {%- set reasoning_content = content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- set content = content.split('</think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}",
334
+ "clean_up_tokenization_spaces": false,
335
+ "eos_token": "<|im_end|>",
336
+ "errors": "replace",
337
+ "extra_special_tokens": {},
338
+ "model_max_length": 32768,
339
+ "pad_token": "<|endoftext|>",
340
+ "processor_class": "Eagle3_VLProcessor",
341
+ "split_special_tokens": false,
342
+ "tokenizer_class": "Qwen2Tokenizer",
343
+ "unk_token": null
344
+ }
train_results.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epoch": 1.0,
3
+ "total_flos": 5.461479216500315e+20,
4
+ "train_loss": 0.09150631395949999,
5
+ "train_runtime": 9502.0046,
6
+ "train_samples": 166521,
7
+ "train_samples_per_second": 17.525,
8
+ "train_steps_per_second": 0.617
9
+ }
trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ada0e77f0909ed3123bc44aa18a7b80ab583a478c366421ce26ab09d2944f6d5
3
+ size 7160
training_log.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:599fce10530a172251643e7a65d4374016355261a8b2d32d4b2712fd20da674a
3
+ size 203679795
vocab.json ADDED
The diff for this file is too large to render. See raw diff