main
py 619 lines 23.1 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 import math
4 from collections.abc import Iterable
5
6 import torch
7 import torch.nn as nn
8 from transformers import AutoModel, PreTrainedConfig
9
10 from vllm.config import VllmConfig
11 from vllm.model_executor.layers.fusion.mm_input_norm import (
12 FusedMMInputNorm,
13 IdentityInputNorm,
14 )
15 from vllm.model_executor.layers.linear import ReplicatedLinear
16 from vllm.model_executor.layers.pooler import DispatchPooler
17 from vllm.model_executor.layers.quantization import QuantizationConfig
18 from vllm.model_executor.layers.quantization.auto_awq import AutoAWQConfig
19 from vllm.model_executor.models.internvl import (
20 BaseInternVLDummyInputsBuilder,
21 BaseInternVLMultiModalProcessor,
22 BaseInternVLProcessingInfo,
23 InternVLImageEmbeddingInputs,
24 InternVLImageInputs,
25 InternVLImagePixelInputs,
26 )
27 from vllm.model_executor.models.module_mapping import MultiModelKeys
28 from vllm.model_executor.models.siglip import SiglipVisionModel
29 from vllm.multimodal import MULTIMODAL_REGISTRY
30 from vllm.sequence import IntermediateTensors
31 from vllm.transformers_utils.processor import cached_image_processor_from_config
32 from vllm.transformers_utils.processors.nemotron_vl import (
33 SIGLIP_MEAN,
34 SIGLIP_STD,
35 LlamaNemotronNanoVLImageProcessor,
36 LlamaNemotronNanoVLProcessor,
37 LlamaNemotronVLEmbedImageProcessor,
38 LlamaNemotronVLEmbedProcessor,
39 )
40 from vllm.transformers_utils.repo_utils import get_hf_file_to_dict
41
42 from .interfaces import (
43 MultiModalEmbeddings,
44 SupportsCrossEncoding,
45 SupportsLoRA,
46 SupportsMultiModal,
47 SupportsPP,
48 )
49 from .interfaces_base import VllmModelForPooling
50 from .utils import (
51 AutoWeightsLoader,
52 WeightsMapper,
53 init_vllm_registered_model,
54 maybe_prefix,
55 )
56
57
58 class NemotronVLProcessingInfo(BaseInternVLProcessingInfo):
59 """Processing info for Nemotron VL models."""
60
61 def get_image_processor(self, **kwargs: object):
62 kwargs = self.ctx.get_merged_mm_kwargs(kwargs)
63 orig_processor = cached_image_processor_from_config(
64 self.ctx.model_config, **kwargs
65 )
66
67 return LlamaNemotronNanoVLImageProcessor(
68 image_size=orig_processor.image_size,
69 min_dynamic_patch=1,
70 max_dynamic_patch=orig_processor.max_num_tiles,
71 dynamic_image_size=True,
72 use_thumbnail=orig_processor.use_thumbnail,
73 )
74
75 def get_hf_processor(self, **kwargs: object) -> LlamaNemotronNanoVLProcessor:
76 config = self.get_hf_config()
77 vision_config = config.vision_config
78
79 image_processor = self.get_image_processor(**kwargs)
80 image_size = image_processor.image_size
81 patch_size = vision_config.patch_size
82 downsample_ratio = config.downsample_ratio
83 image_seq_length = int((image_size // patch_size) ** 2 * (downsample_ratio**2))
84
85 return LlamaNemotronNanoVLProcessor(
86 tokenizer=self.get_tokenizer(),
87 image_processor=image_processor,
88 image_seq_length=image_seq_length,
89 )
90
91
92 @MULTIMODAL_REGISTRY.register_processor(
93 BaseInternVLMultiModalProcessor[NemotronVLProcessingInfo],
94 info=NemotronVLProcessingInfo,
95 dummy_inputs=BaseInternVLDummyInputsBuilder[NemotronVLProcessingInfo],
96 )
97 class LlamaNemotronVLChatModel(nn.Module, SupportsMultiModal, SupportsPP, SupportsLoRA):
98 # Ignore registered buffers, see
99 # https://huggingface.co/nvidia/C-RADIOv2-H/blob/main/input_conditioner.py#L28
100 hf_to_vllm_mapper = WeightsMapper(
101 orig_to_new_substr={"norm_mean": None, "norm_std": None}
102 )
103
104 @classmethod
105 def get_placeholder_str(cls, modality: str, i: int) -> str | None:
106 if modality.startswith("image"):
107 return "<image>"
108
109 raise ValueError("Only image modality is supported")
110
111 def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
112 super().__init__()
113
114 config = vllm_config.model_config.hf_config
115 quant_config = vllm_config.quant_config
116 multimodal_config = vllm_config.model_config.multimodal_config
117
118 self.config = config
119 self.model_config = vllm_config.model_config
120 self.multimodal_config = multimodal_config
121 self._patch_quant_config(config, quant_config)
122
123 image_size = config.force_image_size or config.vision_config.image_size
124 patch_size = config.vision_config.patch_size
125 self.patch_size = patch_size
126 self.num_image_token = int(
127 (image_size // patch_size) ** 2 * (config.downsample_ratio**2)
128 )
129 self.downsample_ratio = config.downsample_ratio
130 self.ps_version = config.ps_version
131
132 with self._mark_tower_model(vllm_config, "image"):
133 self.vision_model = self._init_vision_model(
134 config,
135 quant_config=quant_config,
136 prefix=maybe_prefix(prefix, "vision_model"),
137 )
138 self.mlp1 = self._init_mlp1(config)
139
140 with self._mark_language_model(vllm_config):
141 self.language_model = init_vllm_registered_model(
142 vllm_config=vllm_config,
143 hf_config=config.get_text_config(),
144 prefix=maybe_prefix(prefix, "language_model"),
145 )
146
147 self.img_context_token_id: int | None = None
148
149 self.visual_token_mask = None
150 self.make_empty_intermediate_tensors = (
151 self.language_model.make_empty_intermediate_tensors
152 )
153
154 def _patch_quant_config(
155 self, config: PreTrainedConfig, quant_config: QuantizationConfig | None
156 ):
157 # the awq models from OpenGVLab missing `modules_to_not_convert`
158 # patch the quant_config to add `modules_to_not_convert` back
159 if isinstance(quant_config, AutoAWQConfig):
160 text_config = config.get_text_config()
161 llm_quant_config = getattr(text_config, "quantization_config", None)
162 if (not quant_config.modules_to_not_convert) and (
163 llm_quant_config is not None
164 ):
165 quant_config.modules_to_not_convert.append("vision_model")
166
167 def _init_vision_model(
168 self,
169 config: PreTrainedConfig,
170 quant_config: QuantizationConfig | None,
171 *,
172 prefix: str,
173 ):
174 return AutoModel.from_config(
175 config.vision_config,
176 trust_remote_code=self.model_config.trust_remote_code,
177 )
178
179 def _init_mlp1(
180 self,
181 config: PreTrainedConfig,
182 vit_hidden_size: int | None = None,
183 vision_projection_hidden_size: int | None = None,
184 ) -> nn.Module:
185 if vit_hidden_size is None:
186 vit_hidden_size = config.vit_hidden_size
187 if vision_projection_hidden_size is None:
188 vision_projection_hidden_size = config.projector_hidden_size
189 llm_hidden_size = config.get_text_config().hidden_size
190
191 return nn.Sequential(
192 nn.LayerNorm(
193 vit_hidden_size * int(1 / self.downsample_ratio) ** 2, bias=True
194 ),
195 nn.Linear(
196 vit_hidden_size * int(1 / self.downsample_ratio) ** 2,
197 vision_projection_hidden_size,
198 bias=True,
199 ),
200 nn.GELU(),
201 nn.Linear(vision_projection_hidden_size, llm_hidden_size),
202 )
203
204 def pixel_shuffle(self, x, scale_factor=0.5):
205 n, w, h, c = x.size()
206 # N, W, H, C --> N, W, H * scale, C // scale
207 x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
208 # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
209 x = x.permute(0, 2, 1, 3).contiguous()
210 x = x.view(
211 n,
212 int(h * scale_factor),
213 int(w * scale_factor),
214 int(c / (scale_factor * scale_factor)),
215 )
216 if self.ps_version == "v1":
217 pass
218 else:
219 x = x.permute(0, 2, 1, 3).contiguous()
220 return x
221
222 def _call_vision_model(self, pixel_values: torch.Tensor) -> torch.Tensor:
223 """Call vision model and return embeddings.
224
225 Override this method in subclasses to handle different vision model
226 interfaces (e.g., SigLIP vs C-RADIO).
227 """
228 vit_embeds = self.vision_model(x=pixel_values).features
229 return vit_embeds.to(dtype=torch.bfloat16)
230
231 def extract_feature(self, pixel_values: torch.Tensor) -> torch.Tensor:
232 # https://huggingface.co/nvidia/Llama-3.1-Nemotron-Nano-VL-8B-V1/blob/main/modeling.py#L177
233 vit_embeds = self._call_vision_model(pixel_values)
234
235 h = w = int(vit_embeds.shape[1] ** 0.5)
236 vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
237 vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
238 vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
239 vit_embeds = self.mlp1(vit_embeds)
240 return vit_embeds
241
242 def _parse_and_validate_image_input(
243 self, **kwargs: object
244 ) -> InternVLImageInputs | None:
245 pixel_values_flat = kwargs.pop("pixel_values_flat", None)
246 image_num_patches = kwargs.pop("image_num_patches", None)
247 image_embeds = kwargs.pop("image_embeds", None)
248
249 if pixel_values_flat is None and image_embeds is None:
250 return None
251
252 if image_embeds is not None:
253 return InternVLImageEmbeddingInputs(
254 type="image_embeds",
255 data=image_embeds,
256 )
257
258 image_token_id = kwargs["image_token_id"]
259 if isinstance(image_token_id, torch.Tensor):
260 image_token_id = image_token_id.flatten().unique().item()
261
262 assert isinstance(image_token_id, int)
263 self.img_context_token_id = image_token_id
264
265 if pixel_values_flat is not None:
266 return InternVLImagePixelInputs(
267 type="pixel_values",
268 pixel_values_flat=pixel_values_flat,
269 num_patches=image_num_patches,
270 resolve_bindings={
271 "h": self.config.force_image_size,
272 "w": self.config.force_image_size,
273 },
274 )
275
276 raise AssertionError("This line should be unreachable.")
277
278 def _process_image_input(
279 self,
280 image_input: InternVLImageInputs,
281 ) -> tuple[torch.Tensor, ...]:
282 if image_input["type"] == "image_embeds":
283 return image_input["data"]
284
285 image_embeds = self.extract_feature(image_input["pixel_values_flat"])
286
287 num_patches = image_input["num_patches"]
288 hidden_size = self.config.get_text_config().hidden_size
289
290 # Only one image in the current batch
291 if len(num_patches) == 1:
292 return (image_embeds.view(-1, hidden_size),)
293
294 # NOTE: Image embeddings are split into separate tensors for each image
295 # by the size of each embedding.
296 feature_size = image_embeds.shape[1]
297 image_embeds = image_embeds.view(-1, hidden_size)
298 image_feature_sizes = [
299 num_patches * feature_size for num_patches in num_patches
300 ]
301 return image_embeds.split(image_feature_sizes)
302
303 def _parse_and_validate_multimodal_inputs(self, **kwargs: object) -> dict:
304 modalities = {}
305
306 # Preserve the order of modalities if there are multiple of them
307 # from the order of kwargs.
308 for input_key in kwargs:
309 if (
310 input_key in ("pixel_values_flat", "image_embeds")
311 and "images" not in modalities
312 ):
313 modalities["images"] = self._parse_and_validate_image_input(**kwargs)
314
315 return modalities
316
317 def _set_visual_token_mask(self, input_ids: torch.Tensor) -> None:
318 self.visual_token_mask = None
319
320 def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings:
321 modalities = self._parse_and_validate_multimodal_inputs(**kwargs)
322 if not modalities:
323 return []
324
325 # The result multimodal_embeddings is tuple of tensors, with each
326 # tensor corresponding to a multimodal data item (image).
327 multimodal_embeddings: tuple[torch.Tensor, ...] = ()
328
329 # NOTE: It is important to iterate over the keys in this dictionary
330 # to preserve the order of the modalities.
331 for modality in modalities:
332 if modality == "images":
333 image_input = modalities["images"]
334 image_embeddings = self._process_image_input(image_input)
335 multimodal_embeddings += tuple(image_embeddings)
336
337 return multimodal_embeddings
338
339 def embed_input_ids(
340 self,
341 input_ids: torch.Tensor,
342 multimodal_embeddings: MultiModalEmbeddings | None = None,
343 *,
344 is_multimodal: torch.Tensor | None = None,
345 ) -> torch.Tensor:
346 if multimodal_embeddings is not None and len(multimodal_embeddings) > 0:
347 self._set_visual_token_mask(input_ids)
348
349 # This is to satisfy the type checker for each overload
350 if multimodal_embeddings is None or is_multimodal is None:
351 return super().embed_input_ids(input_ids)
352
353 return super().embed_input_ids(
354 input_ids,
355 multimodal_embeddings=multimodal_embeddings,
356 is_multimodal=is_multimodal,
357 )
358
359 def forward(
360 self,
361 input_ids: torch.Tensor | None,
362 positions: torch.Tensor,
363 intermediate_tensors: IntermediateTensors | None = None,
364 inputs_embeds: torch.Tensor | None = None,
365 **kwargs: object,
366 ) -> IntermediateTensors:
367 if intermediate_tensors is not None:
368 inputs_embeds = None
369
370 forward_kwargs = {
371 "input_ids": input_ids,
372 "positions": positions,
373 "intermediate_tensors": intermediate_tensors,
374 "inputs_embeds": inputs_embeds,
375 }
376
377 # Only required if the model is mono-architecture
378 if self.visual_token_mask is not None:
379 forward_kwargs.update({"visual_token_mask": self.visual_token_mask})
380 self.visual_token_mask = None
381
382 hidden_states = self.language_model.model(**forward_kwargs)
383 return hidden_states
384
385 def compute_logits(
386 self,
387 hidden_states: torch.Tensor,
388 ) -> torch.Tensor | None:
389 return self.language_model.compute_logits(hidden_states)
390
391 def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
392 loader = AutoWeightsLoader(self)
393 return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
394
395 def get_mm_mapping(self) -> MultiModelKeys:
396 """Get the module prefix in multimodal models."""
397 return MultiModelKeys.from_string_field(
398 language_model="language_model",
399 connector="mlp1",
400 tower_model="vision_model",
401 )
402
403
404 # --------------------------------------------------------
405 # LlamaNemotronVL Embedding Model (nvidia/llama-nemotron-embed-vl-1b-v2)
406 # Extends LlamaNemotronVLChatModel for embedding/pooling tasks:
407 # - SigLIP vision encoder (instead of C-RADIO)
408 # - Bidirectional (non-causal) LLaMA language model
409 # - Pooler output instead of generative logits
410 # --------------------------------------------------------
411
412
413 class LlamaNemotronVLEmbedProcessingInfo(BaseInternVLProcessingInfo):
414 """Processing info for LlamaNemotronVL embedding model."""
415
416 def get_image_processor(self, **kwargs):
417 model_config = self.ctx.model_config
418
419 config = self.get_hf_config()
420 processor_config = (
421 get_hf_file_to_dict(
422 "processor_config.json",
423 model_config.model,
424 model_config.revision,
425 )
426 or {}
427 )
428
429 min_dynamic_patch = processor_config.get(
430 "min_input_tiles",
431 getattr(config, "min_dynamic_patch", 1),
432 )
433 max_dynamic_patch = processor_config.get(
434 "max_input_tiles",
435 getattr(config, "max_dynamic_patch", 1),
436 )
437 dynamic_image_size = processor_config.get(
438 "dynamic_image_size",
439 getattr(config, "dynamic_image_size", True),
440 )
441
442 kwargs = self.ctx.get_merged_mm_kwargs(kwargs)
443 kwargs.setdefault("image_size", config.force_image_size)
444 kwargs.setdefault("min_dynamic_patch", min_dynamic_patch)
445 kwargs.setdefault("max_dynamic_patch", max_dynamic_patch)
446 kwargs.setdefault("dynamic_image_size", dynamic_image_size)
447 kwargs.setdefault("use_thumbnail", True)
448
449 return LlamaNemotronVLEmbedImageProcessor(**kwargs)
450
451 def get_hf_processor(self, **kwargs: object) -> LlamaNemotronVLEmbedProcessor:
452 config = self.get_hf_config()
453 vision_config = config.vision_config
454
455 image_processor = self.get_image_processor(**kwargs)
456 image_size = image_processor.image_size
457 patch_size = vision_config.patch_size
458 downsample_ratio = config.downsample_ratio
459 image_seq_length = int((image_size // patch_size) ** 2 * (downsample_ratio**2))
460
461 return LlamaNemotronVLEmbedProcessor(
462 tokenizer=self.get_tokenizer(),
463 image_processor=image_processor,
464 image_seq_length=image_seq_length,
465 )
466
467
468 @MULTIMODAL_REGISTRY.register_processor(
469 BaseInternVLMultiModalProcessor[LlamaNemotronVLEmbedProcessingInfo],
470 info=LlamaNemotronVLEmbedProcessingInfo,
471 dummy_inputs=BaseInternVLDummyInputsBuilder[LlamaNemotronVLEmbedProcessingInfo],
472 )
473 class LlamaNemotronVLForEmbedding(LlamaNemotronVLChatModel, VllmModelForPooling):
474 """LlamaNemotronVL model for embeddings.
475
476 Inherits from LlamaNemotronVLChatModel and specializes it for embedding tasks:
477 - Uses SigLIP vision encoder instead of C-RADIO
478 - Uses bidirectional LLaMA (via llm_config) instead of causal LLaMA
479 - Adds pooler for embedding output instead of generating logits
480 """
481
482 is_pooling_model = True
483 supports_mm_device_do_normalize = True
484
485 # Weight mapping from checkpoint format to vLLM format
486 # Different from parent class due to different vision model structure
487 hf_to_vllm_mapper = WeightsMapper(
488 orig_to_new_prefix={
489 # Language model mapping
490 "language_model.layers.": "language_model.model.layers.",
491 "language_model.embed_tokens.": "language_model.model.embed_tokens.",
492 "language_model.norm.": "language_model.model.norm.",
493 # Vision model mapping (SiglipVisionModel has nested vision_model)
494 "vision_model.encoder.": "vision_model.vision_model.encoder.",
495 "vision_model.embeddings.": "vision_model.vision_model.embeddings.",
496 "vision_model.post_layernorm.": "vision_model.vision_model.post_layernorm.",
497 }
498 )
499
500 def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
501 super().__init__(vllm_config=vllm_config, prefix=prefix)
502
503 config = vllm_config.model_config.hf_config
504
505 # Override: get img_context_token_id from config (parent sets None)
506 self.img_context_token_id = getattr(config, "img_context_token_id", None)
507
508 if self.model_config.get_multimodal_config().mm_device_do_normalize:
509 self.input_norm = FusedMMInputNorm(
510 image_mean=list(SIGLIP_MEAN),
511 image_std=list(SIGLIP_STD),
512 rescale_factor=1 / 255,
513 )
514 else:
515 self.input_norm = IdentityInputNorm()
516
517 # Initialize pooler for embedding output
518 pooler_config = vllm_config.model_config.pooler_config
519 assert pooler_config is not None
520 self.pooler = DispatchPooler.for_embedding(pooler_config)
521
522 def _init_vision_model(
523 self,
524 config: PreTrainedConfig,
525 quant_config,
526 *,
527 prefix: str,
528 ) -> nn.Module:
529 """Override to use SigLIP instead of C-RADIO."""
530 return SiglipVisionModel(
531 config.vision_config,
532 quant_config=quant_config,
533 prefix=prefix,
534 use_head=False,
535 )
536
537 def _init_mlp1(
538 self,
539 config: PreTrainedConfig,
540 vit_hidden_size: int | None = None,
541 vision_projection_hidden_size: int | None = None,
542 ) -> nn.Module:
543 """Override to use different MLP structure for embedding model."""
544 if vit_hidden_size is None:
545 vit_hidden_size = config.vision_config.hidden_size
546 if vision_projection_hidden_size is None:
547 vision_projection_hidden_size = config.get_text_config().hidden_size
548 return super()._init_mlp1(
549 config,
550 vit_hidden_size=vit_hidden_size,
551 vision_projection_hidden_size=vision_projection_hidden_size,
552 )
553
554 def _call_vision_model(self, pixel_values: torch.Tensor) -> torch.Tensor:
555 """Override to handle SigLIP interface."""
556 original_shape = pixel_values.shape
557 pixel_values = self.input_norm(
558 pixel_values.flatten(start_dim=1), self.vision_model.dtype
559 ).view(original_shape)
560 return self.vision_model(pixel_values)
561
562 def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
563 """Override to use different weight mapping for SigLIP."""
564 loader = AutoWeightsLoader(self)
565 return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
566
567
568 class LlamaNemotronVLForSequenceClassification(
569 LlamaNemotronVLForEmbedding, SupportsCrossEncoding
570 ):
571 """LlamaNemotronVL model variant for sequence classification / reranking."""
572
573 # Reranker checkpoint places base model weights under `model.*`,
574 # while `score.*` remains at the top level.
575 hf_to_vllm_mapper = WeightsMapper(orig_to_new_prefix={"model.": ""}) | (
576 LlamaNemotronVLForEmbedding.hf_to_vllm_mapper
577 )
578
579 def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
580 super().__init__(vllm_config=vllm_config, prefix=prefix)
581
582 text_config = vllm_config.model_config.hf_config.get_text_config()
583 model_config = vllm_config.model_config
584 quant_config = vllm_config.quant_config
585
586 self.score = ReplicatedLinear(
587 model_config.get_hidden_size(),
588 text_config.num_labels,
589 bias=False,
590 params_dtype=model_config.head_dtype,
591 quant_config=quant_config,
592 return_bias=False,
593 prefix=maybe_prefix(prefix, "score"),
594 )
595
596 pooler_config = model_config.pooler_config
597 assert pooler_config is not None
598 self.pooler = DispatchPooler.for_seq_cls(pooler_config, classifier=self.score)
599
600 def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
601 loaded_weights = super().load_weights(weights)
602
603 # reranker checkpoint omits the inner LM seq-cls head
604 # (`language_model.score.*`). It is unused by this outer model, but
605 # the default loader expects all parameters to be initialized.
606 for name, param in self.named_parameters():
607 if not name.startswith("language_model.score.") or name in loaded_weights:
608 continue
609
610 if name.endswith(".weight"):
611 torch.nn.init.kaiming_uniform_(param, a=math.sqrt(5))
612 elif name.endswith(".bias"):
613 torch.nn.init.zeros_(param)
614 else:
615 torch.nn.init.normal_(param, mean=0.0, std=0.02)
616
617 loaded_weights.add(name)
618
619 return loaded_weights