| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | import math |
| 5 | from collections.abc import Iterable, Mapping, Sequence |
| 6 | from typing import Annotated, Literal, Protocol, TypeAlias, TypedDict |
| 7 | |
| 8 | import torch |
| 9 | import torch.nn as nn |
| 10 | from transformers import BatchFeature, LlavaOnevisionConfig, LlavaOnevisionProcessor |
| 11 | from transformers.models.llava_onevision.modeling_llava_onevision import ( |
| 12 | get_anyres_image_grid_shape, |
| 13 | unpad_image, |
| 14 | ) |
| 15 | |
| 16 | from vllm.config import VllmConfig |
| 17 | from vllm.config.multimodal import MultiModalDummyOptions |
| 18 | from vllm.inputs import MultiModalDataDict |
| 19 | from vllm.model_executor.layers.activation import get_act_fn |
| 20 | from vllm.multimodal import MULTIMODAL_REGISTRY |
| 21 | from vllm.multimodal.inputs import ( |
| 22 | MultiModalFieldConfig, |
| 23 | MultiModalKwargsItems, |
| 24 | ) |
| 25 | from vllm.multimodal.parse import ( |
| 26 | ImageSize, |
| 27 | MultiModalDataItems, |
| 28 | VideoEmbeddingItems, |
| 29 | VideoProcessorItems, |
| 30 | ) |
| 31 | from vllm.multimodal.processing import PromptReplacement, PromptUpdate |
| 32 | from vllm.sequence import IntermediateTensors |
| 33 | from vllm.utils.tensor_schema import TensorSchema, TensorShape |
| 34 | |
| 35 | from .clip import CLIPVisionModel |
| 36 | from .interfaces import MultiModalEmbeddings, SupportsMultiModal, SupportsPP |
| 37 | from .llava import LlavaDummyInputsBuilder, init_vision_tower_for_llava |
| 38 | from .llava_next import ( |
| 39 | BaseLlavaNextMultiModalProcessor, |
| 40 | LlavaNextLikeConfig, |
| 41 | LlavaNextProcessingInfo, |
| 42 | ) |
| 43 | from .siglip import SiglipVisionModel |
| 44 | from .utils import ( |
| 45 | AutoWeightsLoader, |
| 46 | WeightsMapper, |
| 47 | init_vllm_registered_model, |
| 48 | maybe_prefix, |
| 49 | ) |
| 50 | |
| 51 | # For profile run |
| 52 | _MAX_FRAMES_PER_VIDEO = 16 |
| 53 | |
| 54 | |
| 55 | class LlavaOnevisionVideoPixelInputs(TensorSchema): |
| 56 | """Dimensions: |
| 57 | - bn: Batch size * number of videos |
| 58 | - f: Number of frames |
| 59 | - c: Number of channels (3) |
| 60 | - h: Height |
| 61 | - w: Width |
| 62 | |
| 63 | Note that `f` may be different for each batch, and 'num_frames' |
| 64 | may be different for each video, in which case the data is passed as a |
| 65 | list instead of a batched tensor. |
| 66 | """ |
| 67 | |
| 68 | type: Literal["pixel_values_videos"] = "pixel_values_videos" |
| 69 | |
| 70 | pixel_values_videos: Annotated[ |
| 71 | torch.Tensor | list[torch.Tensor], |
| 72 | TensorShape("bn", "f", 3, "h", "w", dynamic_dims={"f"}), |
| 73 | ] |
| 74 | |
| 75 | |
| 76 | class LlavaOnevisionImagePixelInputs(TensorSchema): |
| 77 | """Dimensions: |
| 78 | - bn: Batch size * number of images |
| 79 | - np: Number of patches (1 + num_patches) |
| 80 | - c: Number of channels (3) |
| 81 | - h: Height |
| 82 | - w: Width |
| 83 | |
| 84 | Note that `num_patches` may be different per batch and image, |
| 85 | in which case the data is passed as a list instead of a batched tensor. |
| 86 | """ |
| 87 | |
| 88 | type: Literal["pixel_values"] = "pixel_values" |
| 89 | |
| 90 | pixel_values: Annotated[ |
| 91 | torch.Tensor | list[torch.Tensor], |
| 92 | TensorShape("bn", "np", 3, "h", "w", dynamic_dims={"np"}), |
| 93 | ] |
| 94 | |
| 95 | image_sizes: Annotated[torch.Tensor | None, TensorShape("bn", 2)] |
| 96 | |
| 97 | |
| 98 | class LlavaOnevisionImageEmbeddingInputs(TensorSchema): |
| 99 | """Dimensions: |
| 100 | - bn: Batch size * number of images |
| 101 | - ifs: Image feature size |
| 102 | - hs: Hidden size (must match language model backbone) |
| 103 | """ |
| 104 | |
| 105 | type: Literal["image_embeds"] = "image_embeds" |
| 106 | |
| 107 | data: Annotated[ |
| 108 | torch.Tensor, |
| 109 | TensorShape("bn", "ifs", "hs"), |
| 110 | ] |
| 111 | |
| 112 | |
| 113 | LlavaOnevisionImageInputs: TypeAlias = ( |
| 114 | LlavaOnevisionImagePixelInputs | LlavaOnevisionImageEmbeddingInputs |
| 115 | ) |
| 116 | |
| 117 | LlavaOnevisionMultiInputs: TypeAlias = ( |
| 118 | LlavaOnevisionImageInputs | LlavaOnevisionVideoPixelInputs |
| 119 | ) |
| 120 | |
| 121 | |
| 122 | class LlavaOnevisionLikeConfig(LlavaNextLikeConfig, Protocol): |
| 123 | video_token_index: int |
| 124 | |
| 125 | |
| 126 | class LlavaOnevisionInputsByModality(TypedDict, total=False): |
| 127 | image: LlavaOnevisionImageInputs | None |
| 128 | video: LlavaOnevisionVideoPixelInputs | None |
| 129 | |
| 130 | |
| 131 | class LlavaOnevisionProcessingInfo(LlavaNextProcessingInfo): |
| 132 | def get_hf_config(self) -> LlavaOnevisionLikeConfig: |
| 133 | return self.ctx.get_hf_config(LlavaOnevisionConfig) |
| 134 | |
| 135 | def get_hf_processor(self, **kwargs: object): |
| 136 | return self.ctx.get_hf_processor(LlavaOnevisionProcessor, **kwargs) |
| 137 | |
| 138 | def get_supported_mm_limits(self) -> Mapping[str, int | None]: |
| 139 | return {"image": None, "video": None} |
| 140 | |
| 141 | # Based on: https://github.com/huggingface/text-generation-inference/blob/v3.0.1/server/text_generation_server/models/vlm_causal_lm.py#L86 |
| 142 | # with additional logic afterwards taken from LlavaOnevisionProcessor |
| 143 | def _get_num_unpadded_features( |
| 144 | self, |
| 145 | *, |
| 146 | original_height: int, |
| 147 | original_width: int, |
| 148 | npatches: int, |
| 149 | num_patch_height: int, |
| 150 | num_patch_width: int, |
| 151 | ) -> tuple[int, int]: |
| 152 | current_height = npatches * num_patch_height |
| 153 | current_width = npatches * num_patch_width |
| 154 | |
| 155 | aspect_ratio = original_width / original_height |
| 156 | current_aspect_ratio = current_width / current_height |
| 157 | |
| 158 | if aspect_ratio > current_aspect_ratio: |
| 159 | new_height = int( |
| 160 | round(original_height * (current_width / original_width), 7) |
| 161 | ) |
| 162 | padding = (current_height - new_height) // 2 |
| 163 | current_height = current_height - (2 * padding) |
| 164 | else: |
| 165 | new_width = int( |
| 166 | round(original_width * (current_height / original_height), 7) |
| 167 | ) |
| 168 | padding = (current_width - new_width) // 2 |
| 169 | current_width = current_width - (2 * padding) |
| 170 | |
| 171 | unpadded_features = current_height * current_width |
| 172 | newline_features = current_height |
| 173 | |
| 174 | ratio = math.sqrt(current_height * current_width / (9 * npatches**2)) |
| 175 | if ratio > 1.1: |
| 176 | height_factor = int(current_height // ratio) |
| 177 | width_factor = int(current_width // ratio) |
| 178 | unpadded_features = height_factor * width_factor |
| 179 | newline_features = height_factor |
| 180 | |
| 181 | return (unpadded_features, newline_features) |
| 182 | |
| 183 | def get_image_size_with_most_features(self) -> ImageSize: |
| 184 | # NOTE: This hardcoded value is found via processor tests |
| 185 | return ImageSize(width=1153, height=944) |
| 186 | |
| 187 | def _get_num_frame_tokens( |
| 188 | self, |
| 189 | *, |
| 190 | image_width: int, |
| 191 | image_height: int, |
| 192 | ) -> int: |
| 193 | hf_config = self.get_hf_config() |
| 194 | spatial_pool_stride = getattr(hf_config, "spatial_pool_stride", 2) |
| 195 | |
| 196 | vision_encoder_info = self.get_vision_encoder_info() |
| 197 | patch_grid_length = vision_encoder_info.get_patch_grid_length() |
| 198 | pooled_grid_length = math.ceil(patch_grid_length / spatial_pool_stride) |
| 199 | |
| 200 | return pooled_grid_length * pooled_grid_length |
| 201 | |
| 202 | def get_num_video_tokens( |
| 203 | self, |
| 204 | *, |
| 205 | image_width: int, |
| 206 | image_height: int, |
| 207 | num_frames: int, |
| 208 | ) -> int: |
| 209 | num_frame_tokens = self._get_num_frame_tokens( |
| 210 | image_width=image_width, |
| 211 | image_height=image_height, |
| 212 | ) |
| 213 | |
| 214 | return num_frame_tokens * num_frames + 1 # Newline token |
| 215 | |
| 216 | def _get_max_video_frames(self, max_tokens: int) -> int: |
| 217 | target_width, target_height = self.get_image_size_with_most_features() |
| 218 | |
| 219 | num_frames = 0 |
| 220 | |
| 221 | while True: |
| 222 | next_num_frames = num_frames + 1 |
| 223 | next_max_tokens = self.get_num_video_tokens( |
| 224 | image_width=target_width, |
| 225 | image_height=target_height, |
| 226 | num_frames=next_num_frames, |
| 227 | ) |
| 228 | |
| 229 | if next_max_tokens > max_tokens: |
| 230 | break |
| 231 | |
| 232 | num_frames = next_num_frames |
| 233 | |
| 234 | return num_frames |
| 235 | |
| 236 | def get_num_frames_with_most_features( |
| 237 | self, |
| 238 | seq_len: int, |
| 239 | mm_counts: Mapping[str, int], |
| 240 | ) -> int: |
| 241 | max_videos = mm_counts.get("video", 0) |
| 242 | |
| 243 | max_total_frames = self._get_max_video_frames(seq_len) |
| 244 | max_frames_per_video = min( |
| 245 | max_total_frames // max(max_videos, 1), _MAX_FRAMES_PER_VIDEO |
| 246 | ) |
| 247 | |
| 248 | return max(max_frames_per_video, 1) |
| 249 | |
| 250 | def get_max_video_tokens( |
| 251 | self, |
| 252 | seq_len: int, |
| 253 | mm_counts: Mapping[str, int], |
| 254 | ) -> int: |
| 255 | target_width, target_height = self.get_image_size_with_most_features() |
| 256 | |
| 257 | return self.get_num_video_tokens( |
| 258 | image_width=target_width, |
| 259 | image_height=target_height, |
| 260 | num_frames=self.get_num_frames_with_most_features(seq_len, mm_counts), |
| 261 | ) |
| 262 | |
| 263 | |
| 264 | class LlavaOnevisionDummyInputsBuilder( |
| 265 | LlavaDummyInputsBuilder[LlavaOnevisionProcessingInfo] |
| 266 | ): |
| 267 | def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str: |
| 268 | num_images = mm_counts.get("image", 0) |
| 269 | num_videos = mm_counts.get("video", 0) |
| 270 | |
| 271 | processor = self.info.get_hf_processor() |
| 272 | image_token = processor.image_token |
| 273 | video_token = processor.video_token |
| 274 | |
| 275 | return image_token * num_images + video_token * num_videos |
| 276 | |
| 277 | def get_dummy_mm_data( |
| 278 | self, |
| 279 | seq_len: int, |
| 280 | mm_counts: Mapping[str, int], |
| 281 | mm_options: MultiModalDummyOptions, |
| 282 | ) -> MultiModalDataDict: |
| 283 | target_width, target_height = self.info.get_image_size_with_most_features() |
| 284 | target_num_frames = self.info.get_num_frames_with_most_features( |
| 285 | seq_len, mm_counts |
| 286 | ) |
| 287 | |
| 288 | return { |
| 289 | "image": self._get_dummy_images( |
| 290 | width=target_width, |
| 291 | height=target_height, |
| 292 | num_images=mm_counts.get("image", 0), |
| 293 | overrides=mm_options.get("image"), |
| 294 | ), |
| 295 | "video": self._get_dummy_videos( |
| 296 | width=target_width, |
| 297 | height=target_height, |
| 298 | num_frames=target_num_frames, |
| 299 | num_videos=mm_counts.get("video", 0), |
| 300 | overrides=mm_options.get("video"), |
| 301 | ), |
| 302 | } |
| 303 | |
| 304 | |
| 305 | class LlavaOnevisionMultiModalProcessor( |
| 306 | BaseLlavaNextMultiModalProcessor[LlavaOnevisionProcessingInfo] |
| 307 | ): |
| 308 | def _get_mm_fields_config( |
| 309 | self, |
| 310 | hf_inputs: BatchFeature, |
| 311 | hf_processor_mm_kwargs: Mapping[str, object], |
| 312 | ) -> Mapping[str, MultiModalFieldConfig]: |
| 313 | return dict( |
| 314 | pixel_values=MultiModalFieldConfig.batched("image"), |
| 315 | image_sizes=MultiModalFieldConfig.batched("image", keep_on_cpu=True), |
| 316 | image_embeds=MultiModalFieldConfig.batched("image"), |
| 317 | pixel_values_videos=MultiModalFieldConfig.batched("video"), |
| 318 | ) |
| 319 | |
| 320 | def _get_hf_mm_text(self, mm_counts: Mapping[str, int]) -> str: |
| 321 | return self.dummy_inputs.get_dummy_text(mm_counts) |
| 322 | |
| 323 | def _apply_hf_processor_main( |
| 324 | self, |
| 325 | mm_items: MultiModalDataItems, |
| 326 | hf_kwargs: Mapping[str, object], |
| 327 | ) -> BatchFeature: |
| 328 | hf_data, hf_kwargs, passthrough_data = self._get_hf_mm_inputs( |
| 329 | mm_items, hf_kwargs |
| 330 | ) |
| 331 | |
| 332 | if not hf_data: |
| 333 | return self._finalize_hf_mm_data(hf_data, hf_kwargs, passthrough_data) |
| 334 | |
| 335 | prompt_text = hf_data.pop("text") |
| 336 | assert isinstance(prompt_text, str) |
| 337 | |
| 338 | videos = hf_data.pop("videos", []) |
| 339 | assert isinstance(videos, list) |
| 340 | |
| 341 | if not videos: |
| 342 | processed_data = self.info.ctx.call_hf_processor( |
| 343 | self.info.get_hf_processor(**hf_kwargs), |
| 344 | dict(text=prompt_text, **hf_data), |
| 345 | hf_kwargs, |
| 346 | ) |
| 347 | return self._finalize_hf_mm_data( |
| 348 | hf_data, hf_kwargs, passthrough_data, processed_data |
| 349 | ) |
| 350 | |
| 351 | # LLaVA-OneVision processor doesn't support multiple videos |
| 352 | # with different sizes when converting back to tensors |
| 353 | # So, we process each component separately |
| 354 | # NOTE: No prompt replacement is applied in this case |
| 355 | processor = self.info.get_hf_processor() |
| 356 | image_token = processor.image_token |
| 357 | video_token = processor.video_token |
| 358 | |
| 359 | images = hf_data.pop("images", []) |
| 360 | assert isinstance(images, list) |
| 361 | if images: |
| 362 | processor_outputs = self.info.ctx.call_hf_processor( |
| 363 | self.info.get_hf_processor(**hf_kwargs), |
| 364 | dict(text=image_token * len(images), **{"images": images}), |
| 365 | hf_kwargs, |
| 366 | ) |
| 367 | image_outputs = { |
| 368 | k: v |
| 369 | for k, v in processor_outputs.items() |
| 370 | if k in ("pixel_values", "image_sizes") |
| 371 | } |
| 372 | else: |
| 373 | image_outputs = {} |
| 374 | |
| 375 | pixel_values_videos = [] |
| 376 | for video in videos: |
| 377 | item_outputs = self.info.ctx.call_hf_processor( |
| 378 | self.info.get_hf_processor(**hf_kwargs), |
| 379 | dict(text=video_token, **{"videos": video}), |
| 380 | hf_kwargs, |
| 381 | ) |
| 382 | |
| 383 | pixel_values_videos.append(item_outputs["pixel_values_videos"][0]) |
| 384 | |
| 385 | video_outputs = {"pixel_values_videos": pixel_values_videos} |
| 386 | |
| 387 | combined_outputs = dict( |
| 388 | input_ids=prompt_text, |
| 389 | **image_outputs, |
| 390 | **video_outputs, |
| 391 | ) |
| 392 | processed_data = BatchFeature(combined_outputs) |
| 393 | return self._finalize_hf_mm_data( |
| 394 | hf_data, hf_kwargs, passthrough_data, processed_data |
| 395 | ) |
| 396 | |
| 397 | def _get_prompt_updates( |
| 398 | self, |
| 399 | mm_items: MultiModalDataItems, |
| 400 | hf_processor_mm_kwargs: Mapping[str, object], |
| 401 | out_mm_kwargs: MultiModalKwargsItems, |
| 402 | ) -> Sequence[PromptUpdate]: |
| 403 | image_repls = super()._get_prompt_updates( |
| 404 | mm_items=mm_items, |
| 405 | hf_processor_mm_kwargs=hf_processor_mm_kwargs, |
| 406 | out_mm_kwargs=out_mm_kwargs, |
| 407 | ) |
| 408 | |
| 409 | hf_config = self.info.get_hf_config() |
| 410 | video_token_id = hf_config.video_token_index |
| 411 | |
| 412 | def get_video_replacement(item_idx: int): |
| 413 | videos = mm_items.get_items( |
| 414 | "video", (VideoEmbeddingItems, VideoProcessorItems) |
| 415 | ) |
| 416 | |
| 417 | if isinstance(videos, VideoEmbeddingItems): |
| 418 | num_video_tokens = videos.get_feature_size(item_idx) |
| 419 | else: |
| 420 | assert isinstance(videos, VideoProcessorItems) |
| 421 | image_size = videos.get_frame_size(item_idx) |
| 422 | num_video_tokens = self.info.get_num_video_tokens( |
| 423 | image_width=image_size.width, |
| 424 | image_height=image_size.height, |
| 425 | num_frames=videos.get_num_frames(item_idx), |
| 426 | ) |
| 427 | |
| 428 | return [video_token_id] * num_video_tokens |
| 429 | |
| 430 | return [ |
| 431 | *image_repls, |
| 432 | PromptReplacement( |
| 433 | modality="video", |
| 434 | target=[video_token_id], |
| 435 | replacement=get_video_replacement, |
| 436 | ), |
| 437 | ] |
| 438 | |
| 439 | |
| 440 | class LlavaOnevisionMultiModalProjector(nn.Module): |
| 441 | def __init__(self, config: LlavaOnevisionConfig): |
| 442 | super().__init__() |
| 443 | |
| 444 | self.linear_1 = nn.Linear( |
| 445 | config.vision_config.hidden_size, |
| 446 | config.text_config.hidden_size, |
| 447 | bias=config.multimodal_projector_bias, |
| 448 | ) |
| 449 | self.act = get_act_fn(config.projector_hidden_act) |
| 450 | self.linear_2 = nn.Linear( |
| 451 | config.text_config.hidden_size, |
| 452 | config.text_config.hidden_size, |
| 453 | bias=config.multimodal_projector_bias, |
| 454 | ) |
| 455 | |
| 456 | def forward(self, image_features: torch.Tensor) -> torch.Tensor: |
| 457 | hidden_states = self.linear_1(image_features) |
| 458 | hidden_states = self.act(hidden_states) |
| 459 | hidden_states = self.linear_2(hidden_states) |
| 460 | return hidden_states |
| 461 | |
| 462 | |
| 463 | @MULTIMODAL_REGISTRY.register_processor( |
| 464 | LlavaOnevisionMultiModalProcessor, |
| 465 | info=LlavaOnevisionProcessingInfo, |
| 466 | dummy_inputs=LlavaOnevisionDummyInputsBuilder, |
| 467 | ) |
| 468 | class LlavaOnevisionForConditionalGeneration(nn.Module, SupportsMultiModal, SupportsPP): |
| 469 | hf_to_vllm_mapper = WeightsMapper( |
| 470 | orig_to_new_prefix={ |
| 471 | # mapping for new names in checkpoint saved after transformers v4.52 |
| 472 | "model.language_model.": "language_model.model.", |
| 473 | "model.vision_tower.": "vision_tower.", |
| 474 | "model.multi_modal_projector.": "multi_modal_projector.", |
| 475 | "model.image_newline": "image_newline", |
| 476 | "lm_head.": "language_model.lm_head.", |
| 477 | } |
| 478 | ) |
| 479 | |
| 480 | @classmethod |
| 481 | def get_placeholder_str(cls, modality: str, i: int) -> str | None: |
| 482 | if modality.startswith("image"): |
| 483 | return "<image>" |
| 484 | if modality.startswith("video"): |
| 485 | return "<video>" |
| 486 | |
| 487 | raise ValueError("Only image or video modality is supported") |
| 488 | |
| 489 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None: |
| 490 | super().__init__() |
| 491 | config = vllm_config.model_config.hf_config |
| 492 | quant_config = vllm_config.quant_config |
| 493 | multimodal_config = vllm_config.model_config.multimodal_config |
| 494 | |
| 495 | self.config = config |
| 496 | self.multimodal_config = multimodal_config |
| 497 | |
| 498 | with self._mark_tower_model(vllm_config, {"image", "video"}): |
| 499 | # Initialize the vision tower only up to the required feature layer |
| 500 | self.vision_tower = init_vision_tower_for_llava( |
| 501 | config, |
| 502 | quant_config=quant_config, |
| 503 | require_post_norm=False, |
| 504 | prefix=maybe_prefix(prefix, "vision_tower"), |
| 505 | ) |
| 506 | self.image_newline = nn.Parameter( |
| 507 | torch.empty(config.text_config.hidden_size) |
| 508 | ) |
| 509 | self.multi_modal_projector = LlavaOnevisionMultiModalProjector(config) |
| 510 | |
| 511 | with self._mark_language_model(vllm_config): |
| 512 | self.language_model = init_vllm_registered_model( |
| 513 | vllm_config=vllm_config, |
| 514 | hf_config=config.text_config, |
| 515 | prefix=maybe_prefix(prefix, "language_model"), |
| 516 | ) |
| 517 | |
| 518 | self.make_empty_intermediate_tensors = ( |
| 519 | self.language_model.model.make_empty_intermediate_tensors |
| 520 | ) |
| 521 | |
| 522 | def _parse_and_validate_image_input( |
| 523 | self, **kwargs: object |
| 524 | ) -> LlavaOnevisionImageInputs | None: |
| 525 | pixel_values = kwargs.pop("pixel_values", None) |
| 526 | image_sizes = kwargs.pop("image_sizes", None) |
| 527 | image_embeds = kwargs.pop("image_embeds", None) |
| 528 | |
| 529 | if pixel_values is None and image_embeds is None: |
| 530 | return None |
| 531 | |
| 532 | if pixel_values is not None: |
| 533 | return LlavaOnevisionImagePixelInputs( |
| 534 | type="pixel_values", |
| 535 | pixel_values=pixel_values, |
| 536 | image_sizes=image_sizes, |
| 537 | resolve_bindings={ |
| 538 | "h": self.config.vision_config.image_size, |
| 539 | "w": self.config.vision_config.image_size, |
| 540 | }, |
| 541 | ) |
| 542 | |
| 543 | if image_embeds is not None: |
| 544 | return LlavaOnevisionImageEmbeddingInputs( |
| 545 | type="image_embeds", |
| 546 | data=image_embeds, |
| 547 | ) |
| 548 | |
| 549 | raise AssertionError("This line should be unreachable.") |
| 550 | |
| 551 | def _parse_and_validate_video_input( |
| 552 | self, **kwargs: object |
| 553 | ) -> LlavaOnevisionVideoPixelInputs | None: |
| 554 | """A legal video input should have the following dimensions: |
| 555 | { |
| 556 | "pixel_values_videos" : |
| 557 | list[b, Tensor(nb_frames, nb_channels, height, width)] |
| 558 | } |
| 559 | """ |
| 560 | pixel_values_videos = kwargs.pop("pixel_values_videos", None) |
| 561 | if pixel_values_videos is None: |
| 562 | return None |
| 563 | |
| 564 | return LlavaOnevisionVideoPixelInputs( |
| 565 | type="pixel_values_videos", |
| 566 | pixel_values_videos=pixel_values_videos, |
| 567 | resolve_bindings={ |
| 568 | "h": self.config.vision_config.image_size, |
| 569 | "w": self.config.vision_config.image_size, |
| 570 | }, |
| 571 | ) |
| 572 | |
| 573 | def _parse_and_validate_multimodal_inputs( |
| 574 | self, **kwargs: object |
| 575 | ) -> LlavaOnevisionInputsByModality: |
| 576 | mm_input_by_modality = LlavaOnevisionInputsByModality() |
| 577 | |
| 578 | # Preserve the order of modalities if there are multiple of them |
| 579 | # from the order of kwargs. |
| 580 | for input_key in kwargs: |
| 581 | if ( |
| 582 | input_key in ("pixel_values", "image_embeds") |
| 583 | and "image" not in mm_input_by_modality |
| 584 | ): |
| 585 | mm_input_by_modality["image"] = self._parse_and_validate_image_input( |
| 586 | **kwargs |
| 587 | ) |
| 588 | if ( |
| 589 | input_key in ("pixel_values_videos", "video_embeds") |
| 590 | and "video" not in mm_input_by_modality |
| 591 | ): |
| 592 | mm_input_by_modality["video"] = self._parse_and_validate_video_input( |
| 593 | **kwargs |
| 594 | ) |
| 595 | |
| 596 | return mm_input_by_modality |
| 597 | |
| 598 | def _image_pixels_to_features( |
| 599 | self, |
| 600 | vision_tower: CLIPVisionModel | SiglipVisionModel, |
| 601 | pixel_values: torch.Tensor, |
| 602 | ) -> torch.Tensor: |
| 603 | # NOTE: we skip the step to select the vision feature layer since |
| 604 | # this is already done inside the vision tower |
| 605 | return vision_tower( |
| 606 | pixel_values, |
| 607 | feature_select_strategy=self.config.vision_feature_select_strategy, |
| 608 | ) |
| 609 | |
| 610 | # Based on: https://github.com/haotian-liu/LLaVA/blob/main/llava/model/llava_arch.py |
| 611 | def _merge_image_patch_embeddings( |
| 612 | self, |
| 613 | image_size: torch.Tensor, |
| 614 | patch_embeddings: torch.Tensor, |
| 615 | *, |
| 616 | image_newline=None, |
| 617 | vision_aspect_ratio="anyres_max_9", |
| 618 | strategy: str, |
| 619 | ) -> torch.Tensor: |
| 620 | if strategy == "flat": |
| 621 | return patch_embeddings.flatten(0, 1) |
| 622 | |
| 623 | if strategy.startswith("spatial"): |
| 624 | height = width = ( |
| 625 | self.config.vision_config.image_size |
| 626 | // self.config.vision_config.patch_size |
| 627 | ) |
| 628 | |
| 629 | base_patch_embeds = patch_embeddings[0] |
| 630 | if height * width != base_patch_embeds.shape[0]: |
| 631 | raise ValueError( |
| 632 | "The number of patches is not consistent with the image size." |
| 633 | ) |
| 634 | |
| 635 | if patch_embeddings.shape[0] > 1: |
| 636 | other_patch_embeds = patch_embeddings[1:] |
| 637 | |
| 638 | # Move to CPU to avoid floating-point errors |
| 639 | orig_height, orig_width = image_size.tolist() |
| 640 | |
| 641 | # image_aspect_ratio == "anyres" |
| 642 | num_patch_height, num_patch_width = get_anyres_image_grid_shape( |
| 643 | (orig_height, orig_width), |
| 644 | self.config.image_grid_pinpoints, |
| 645 | self.config.vision_config.image_size, |
| 646 | ) |
| 647 | num_patches = num_patch_height * num_patch_width |
| 648 | |
| 649 | # Image patches might be padded for batch processing |
| 650 | other_patch_embeds = other_patch_embeds[:num_patches].view( |
| 651 | num_patch_height, num_patch_width, height, width, -1 |
| 652 | ) |
| 653 | |
| 654 | if "unpad" in strategy: |
| 655 | other_patch_embeds = ( |
| 656 | other_patch_embeds.permute(4, 0, 2, 1, 3) |
| 657 | .contiguous() |
| 658 | .flatten(1, 2) |
| 659 | .flatten(2, 3) |
| 660 | ) |
| 661 | other_patch_embeds = unpad_image( |
| 662 | other_patch_embeds, (orig_height, orig_width) |
| 663 | ) |
| 664 | max_num_patches = int( |
| 665 | vision_aspect_ratio.removeprefix("anyres_max_") |
| 666 | ) |
| 667 | channels, curr_height, curr_width = other_patch_embeds.shape |
| 668 | ratio = math.sqrt( |
| 669 | curr_height * curr_width / (max_num_patches * height**2) |
| 670 | ) |
| 671 | if ratio > 1.1: |
| 672 | other_patch_embeds = other_patch_embeds[None] |
| 673 | other_patch_embeds = nn.functional.interpolate( |
| 674 | other_patch_embeds, |
| 675 | [int(curr_height // ratio), int(curr_width // ratio)], |
| 676 | mode="bilinear", |
| 677 | )[0] |
| 678 | if image_newline is not None: |
| 679 | other_patch_embeds = torch.cat( |
| 680 | ( |
| 681 | other_patch_embeds, |
| 682 | image_newline[:, None, None] |
| 683 | .expand(*other_patch_embeds.shape[:-1], 1) |
| 684 | .to(other_patch_embeds.device), |
| 685 | ), |
| 686 | dim=-1, |
| 687 | ) |
| 688 | other_patch_embeds = other_patch_embeds.flatten(1, 2).transpose( |
| 689 | 0, 1 |
| 690 | ) |
| 691 | else: |
| 692 | other_patch_embeds = ( |
| 693 | other_patch_embeds.permute(0, 2, 1, 3, 4) |
| 694 | .contiguous() |
| 695 | .flatten(0, 3) |
| 696 | ) |
| 697 | |
| 698 | merged_patch_embeddings = torch.cat( |
| 699 | (base_patch_embeds, other_patch_embeds), dim=0 |
| 700 | ) |
| 701 | else: |
| 702 | if "unpad" in strategy: |
| 703 | merged_patch_embeddings = torch.cat( |
| 704 | ( |
| 705 | base_patch_embeds, |
| 706 | self.image_newline[None].to(base_patch_embeds.device), |
| 707 | ), |
| 708 | dim=0, |
| 709 | ) |
| 710 | else: |
| 711 | merged_patch_embeddings = base_patch_embeds |
| 712 | |
| 713 | return merged_patch_embeddings |
| 714 | |
| 715 | raise ValueError(f"Unexpected patch merge strategy: {strategy}") |
| 716 | |
| 717 | def _process_image_pixels( |
| 718 | self, |
| 719 | inputs: LlavaOnevisionImagePixelInputs, |
| 720 | ) -> torch.Tensor | list[torch.Tensor]: |
| 721 | pixel_values = inputs["pixel_values"] |
| 722 | |
| 723 | if isinstance(pixel_values, torch.Tensor): |
| 724 | b, num_patches, c, h, w = pixel_values.shape |
| 725 | stacked_pixel_values = pixel_values.view(b * num_patches, c, h, w) |
| 726 | stacked_image_features = self._image_pixels_to_features( |
| 727 | self.vision_tower, stacked_pixel_values |
| 728 | ) |
| 729 | stacked_patch_embeddings = self.multi_modal_projector( |
| 730 | stacked_image_features |
| 731 | ) |
| 732 | |
| 733 | return stacked_patch_embeddings.view( |
| 734 | b, num_patches, *stacked_patch_embeddings.shape[1:] |
| 735 | ) |
| 736 | |
| 737 | num_patches_per_batch = [v.shape[0] for v in pixel_values] |
| 738 | stacked_pixel_values = torch.cat(pixel_values) |
| 739 | stacked_image_features = self._image_pixels_to_features( |
| 740 | self.vision_tower, stacked_pixel_values |
| 741 | ) |
| 742 | |
| 743 | return [ |
| 744 | self.multi_modal_projector(image_features) |
| 745 | for image_features in torch.split( |
| 746 | stacked_image_features, num_patches_per_batch |
| 747 | ) |
| 748 | ] |
| 749 | |
| 750 | def _process_image_input( |
| 751 | self, |
| 752 | image_input: LlavaOnevisionImageInputs, |
| 753 | ) -> torch.Tensor | list[torch.Tensor]: |
| 754 | if isinstance(image_input, LlavaOnevisionImageEmbeddingInputs): |
| 755 | return image_input["data"] |
| 756 | |
| 757 | patch_embeddings = self._process_image_pixels(image_input) |
| 758 | |
| 759 | image_sizes = image_input.get("image_sizes") |
| 760 | if image_sizes is None: |
| 761 | batch_size = len(image_input["pixel_values"]) |
| 762 | vision_config = self.config.vision_config |
| 763 | default_height = default_width = vision_config.image_size |
| 764 | image_sizes = torch.as_tensor( |
| 765 | [[default_height, default_width] for _ in range(batch_size)] |
| 766 | ) |
| 767 | |
| 768 | return [ |
| 769 | self._merge_image_patch_embeddings( |
| 770 | image_sizes[i], |
| 771 | patch_features_batch, |
| 772 | image_newline=self.image_newline, |
| 773 | strategy="spatial_unpad", |
| 774 | ) |
| 775 | for i, patch_features_batch in enumerate(patch_embeddings) |
| 776 | ] |
| 777 | |
| 778 | def _video_pixels_to_features( |
| 779 | self, |
| 780 | vision_tower: CLIPVisionModel | SiglipVisionModel, |
| 781 | pixel_values: torch.Tensor, |
| 782 | ) -> torch.Tensor: |
| 783 | # NOTE: we skip the step to select the vision feature layer since |
| 784 | # this is already done inside the vision tower |
| 785 | video_features = vision_tower( |
| 786 | pixel_values, |
| 787 | feature_select_strategy=self.config.vision_feature_select_strategy, |
| 788 | ) |
| 789 | video_features = self.multi_modal_projector(video_features) |
| 790 | video_features = self.apply_pooling(video_features) |
| 791 | return video_features |
| 792 | |
| 793 | def _process_video_pixels(self, inputs: LlavaOnevisionVideoPixelInputs): |
| 794 | video_pixels = inputs["pixel_values_videos"] |
| 795 | |
| 796 | if isinstance(video_pixels, torch.Tensor): |
| 797 | total_videos, frames, c, h, w = video_pixels.shape |
| 798 | video_pixels_flat = video_pixels.view(total_videos * frames, c, h, w) |
| 799 | |
| 800 | embeddings_flat = self._video_pixels_to_features( |
| 801 | self.vision_tower, video_pixels_flat |
| 802 | ) |
| 803 | |
| 804 | embeddings_flat = embeddings_flat.reshape( |
| 805 | total_videos, frames * embeddings_flat.shape[1], -1 |
| 806 | ) |
| 807 | |
| 808 | image_newline = self.image_newline[None, None, :].expand( |
| 809 | total_videos, -1, -1 |
| 810 | ) |
| 811 | return torch.cat((embeddings_flat, image_newline), dim=1) |
| 812 | |
| 813 | frames_per_video = [len(video) for video in video_pixels] |
| 814 | video_pixels_flat = torch.cat(video_pixels) |
| 815 | |
| 816 | embeddings_flat = self._video_pixels_to_features( |
| 817 | self.vision_tower, video_pixels_flat |
| 818 | ) |
| 819 | |
| 820 | image_newline = self.image_newline[None, None, :] |
| 821 | |
| 822 | return [ |
| 823 | torch.cat( |
| 824 | ( |
| 825 | embeds.reshape(1, num_frame * embeddings_flat.shape[1], -1), |
| 826 | image_newline, |
| 827 | ), |
| 828 | dim=1, |
| 829 | ) |
| 830 | for num_frame, embeds in zip( |
| 831 | frames_per_video, |
| 832 | torch.split(embeddings_flat, frames_per_video), |
| 833 | ) |
| 834 | ] |
| 835 | |
| 836 | def apply_pooling(self, image_features: torch.Tensor, stride: int = 2): |
| 837 | vision_config = self.config.vision_config |
| 838 | height = width = vision_config.image_size // vision_config.patch_size |
| 839 | batch_frames, _, dim = image_features.shape |
| 840 | image_features = image_features.view(batch_frames, height, width, -1) |
| 841 | image_features = image_features.permute(0, 3, 1, 2) |
| 842 | |
| 843 | # TODO support other pooling types config |
| 844 | height, width = image_features.shape[2:] |
| 845 | scaled_shape = [math.ceil(height / stride), math.ceil(width / stride)] |
| 846 | image_feature = nn.functional.interpolate( |
| 847 | image_features, size=scaled_shape, mode="bilinear" |
| 848 | ) |
| 849 | image_feature = image_feature.permute(0, 2, 3, 1) |
| 850 | image_feature = image_feature.view(batch_frames, -1, dim) |
| 851 | return image_feature |
| 852 | |
| 853 | def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings: |
| 854 | mm_input_by_modality = self._parse_and_validate_multimodal_inputs(**kwargs) |
| 855 | if not mm_input_by_modality: |
| 856 | return [] |
| 857 | |
| 858 | # The result multimodal_embeddings is tuple of tensors, with each |
| 859 | # tensor corresponding to a multimodal data item (image or video). |
| 860 | multimodal_embeddings: tuple[torch.Tensor, ...] = () |
| 861 | |
| 862 | # NOTE: It is important to iterate over the keys in this dictionary |
| 863 | # to preserve the order of the modalities. |
| 864 | for modality in mm_input_by_modality: |
| 865 | if modality == "image": |
| 866 | image_input = mm_input_by_modality["image"] |
| 867 | assert image_input is not None |
| 868 | image_embeddings = self._process_image_input(image_input) |
| 869 | multimodal_embeddings += tuple(image_embeddings) |
| 870 | if modality == "video": |
| 871 | video_input = mm_input_by_modality["video"] |
| 872 | assert video_input is not None |
| 873 | video_embeddings = self._process_video_pixels(video_input) |
| 874 | multimodal_embeddings += tuple(video_embeddings) |
| 875 | |
| 876 | return multimodal_embeddings |
| 877 | |
| 878 | def forward( |
| 879 | self, |
| 880 | input_ids: torch.Tensor | None, |
| 881 | positions: torch.Tensor, |
| 882 | intermediate_tensors: IntermediateTensors | None = None, |
| 883 | inputs_embeds: torch.Tensor | None = None, |
| 884 | **kwargs: object, |
| 885 | ) -> torch.Tensor | IntermediateTensors: |
| 886 | """Run forward pass for LlaVA-Onevision. |
| 887 | |
| 888 | Args: |
| 889 | input_ids: Flattened (concatenated) input_ids corresponding to a |
| 890 | batch. |
| 891 | positions: Flattened (concatenated) position ids corresponding to a |
| 892 | batch. |
| 893 | intermediate_tensors: Intermediate tensors from prior forward pass. |
| 894 | inputs_embeds: Optional tensor of input embeddings. |
| 895 | **kwargs: Multimodal inputs for this batch, forwarded to the |
| 896 | multimodal embedding path. |
| 897 | |
| 898 | """ |
| 899 | if intermediate_tensors is not None: |
| 900 | inputs_embeds = None |
| 901 | |
| 902 | hidden_states = self.language_model.model( |
| 903 | input_ids, positions, intermediate_tensors, inputs_embeds=inputs_embeds |
| 904 | ) |
| 905 | |
| 906 | return hidden_states |
| 907 | |
| 908 | def compute_logits( |
| 909 | self, |
| 910 | hidden_states: torch.Tensor, |
| 911 | ) -> torch.Tensor | None: |
| 912 | return self.language_model.compute_logits(hidden_states) |
| 913 | |
| 914 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 915 | loader = AutoWeightsLoader(self) |
| 916 | return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) |