qwen_vl.py 25.4 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
5
6
7
8
9
10
11

# Adapted from
# https://huggingface.co/Qwen/Qwen-VL/blob/main/modeling_qwen.py
# Copyright (c) Alibaba Cloud.
"""Inference-only Qwen-VL model compatible with HuggingFace weights."""

import copy
import math
import unicodedata
12
from collections.abc import Callable, Collection, Mapping, Sequence, Set
13
from functools import lru_cache, partial
14
from typing import Annotated, Literal, TypeAlias
15

16
import regex as re
17
18
19
20
import torch
from torch import nn
from torchvision import transforms
from torchvision.transforms import InterpolationMode
21
from transformers import BatchFeature, PretrainedConfig, PreTrainedTokenizer, TensorType
22
23
24
25
from transformers.image_utils import ImageInput
from transformers.tokenization_utils_base import TextInput

from vllm.config import VllmConfig
26
from vllm.config.multimodal import BaseDummyOptions
27
from vllm.model_executor.layers.activation import get_act_fn
28
from vllm.model_executor.layers.conv import Conv2dLayer
29
30
31
32
33
from vllm.model_executor.layers.linear import (
    ColumnParallelLinear,
    ReplicatedLinear,
    RowParallelLinear,
)
34
35
36
37
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.resampler import Resampler2, get_abs_pos
from vllm.model_executor.models.module_mapping import MultiModelKeys
from vllm.multimodal import MULTIMODAL_REGISTRY
38
39
40
41
42
from vllm.multimodal.inputs import (
    MultiModalDataDict,
    MultiModalFieldConfig,
    MultiModalKwargsItems,
)
43
from vllm.multimodal.parse import MultiModalDataItems
44
from vllm.multimodal.processing import (
45
    BaseDummyInputsBuilder,
46
47
48
49
50
51
    BaseMultiModalProcessor,
    BaseProcessingInfo,
    PromptReplacement,
    PromptUpdate,
    PromptUpdateDetails,
)
52
from vllm.sequence import IntermediateTensors
53
from vllm.utils.tensor_schema import TensorSchema, TensorShape
54

55
56
57
58
59
60
from .interfaces import (
    MultiModalEmbeddings,
    SupportsLoRA,
    SupportsMultiModal,
    SupportsPP,
)
61
from .qwen import QWenBaseModel, QWenBlock, QWenModel
62
63


64
class QwenImagePixelInputs(TensorSchema):
65
    """
66
67
68
69
70
    Dimensions:
        - bn: Batch size * number of images
        - c: Number of channels (3)
        - h: Height
        - w: Width
71

72
73
74
75
    Note that image_size is the value in the vision config to which we resize
    the image to in the normalization transform. Currently multi-image support
    can only be leveraged by passing image embeddings directly.
    """
76

77
78
    type: Literal["pixel_values"] = "pixel_values"
    data: Annotated[torch.Tensor, TensorShape("bn", 3, "h", "w")]
79
80


81
82
83
84
85
86
class QwenImageEmbeddingInputs(TensorSchema):
    """
    Dimensions:
        - bn: Batch size * number of images
        - ifs: Image feature size (256)
        - hs: Hidden size
87

88
89
90
    `hidden_size` must match the hidden size of the language model backbone
    and is stored in the visual config of the model if we have one.
    """
91

92
93
    type: Literal["image_embeds"] = "image_embeds"
    data: Annotated[torch.Tensor, TensorShape("bn", 256, "hs")]
94
95


96
QwenImageInputs: TypeAlias = QwenImagePixelInputs | QwenImageEmbeddingInputs
97
98
99
100
101
102
103
104
105
106
107
108
109


class VisualAttention(nn.Module):
    """self-attention layer class.
    Self-attention layer takes input with size [s, b, h]
    and returns output of the same size.
    """

    def __init__(
        self,
        embed_dim: int,
        num_heads: int,
        bias: bool = True,
110
111
        kdim: int | None = None,
        vdim: int | None = None,
112
        prefix: str = "",
113
114
115
116
117
    ):
        super().__init__()
        self.embed_dim = embed_dim
        self.kdim = kdim if kdim is not None else embed_dim
        self.vdim = vdim if vdim is not None else embed_dim
118
        self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
119
120
121
122
123
124
125
126
127
128

        self.num_heads = num_heads

        # Per attention head and per partition values.
        assert embed_dim % num_heads == 0
        self.hidden_size_per_attention_head = embed_dim // num_heads
        self.num_attention_heads_per_partition = num_heads
        self.hidden_size_per_partition = embed_dim

        # Strided linear layer.
129
130
131
        assert self._qkv_same_embed_dim, (
            "Visual Attention implementation only supports self-attention"
        )
132
133
134
135
136
137
        self.in_proj = ReplicatedLinear(
            embed_dim, 3 * embed_dim, prefix=f"{prefix}.in_proj"
        )
        self.out_proj = ReplicatedLinear(
            embed_dim, embed_dim, prefix=f"{prefix}.out_proj"
        )
138
139
140
141
142
        self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)

    def forward(
        self,
        x: torch.Tensor,
143
        attn_mask: torch.Tensor | None = None,
144
145
146
147
148
149
    ) -> torch.Tensor:
        # query/key/value: [sq, b, h]
        sq, b, _ = x.size()
        mixed_x_layer, _ = self.in_proj(x)

        # [sq, b, (np * 3 * hn)] --> [sq, b, np, 3 * hn]
150
151
152
153
        new_tensor_shape = mixed_x_layer.size()[:-1] + (
            self.num_attention_heads_per_partition,
            3 * self.hidden_size_per_attention_head,
        )
154
155
156
157
        mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)

        # [sq, b, np, 3 * hn] --> 3 [sq, b, np, hn]
        query_layer, key_layer, value_layer = mixed_x_layer.split(
158
159
            self.hidden_size_per_attention_head, dim=-1
        )
160
161
162

        # [sq, b, np, hn] -> [sq, b * np, hn]
        query_layer = query_layer.view(
163
164
165
166
            sq,
            b * self.num_attention_heads_per_partition,
            self.hidden_size_per_attention_head,
        ).transpose(0, 1)
167
168
        # [sk, b, np, hn] -> [sk, b * np, hn]
        key_layer = key_layer.view(
169
170
171
172
            sq,
            b * self.num_attention_heads_per_partition,
            self.hidden_size_per_attention_head,
        ).transpose(0, 1)
173
174
175

        q_scaled = query_layer / self.norm_factor
        if attn_mask is not None:
176
177
178
            attention_probs = torch.baddbmm(
                attn_mask, q_scaled, key_layer.transpose(-2, -1)
            )
179
180
181
182
183
        else:
            attention_probs = torch.bmm(q_scaled, key_layer.transpose(-2, -1))
        attention_probs = attention_probs.softmax(dim=-1)

        value_layer = value_layer.view(
184
185
186
187
            sq,
            b * self.num_attention_heads_per_partition,
            self.hidden_size_per_attention_head,
        ).transpose(0, 1)
188
189
190
191
192
193

        # matmul: [b * np, sq, hn]
        context_layer = torch.bmm(attention_probs, value_layer)

        # change view [b, np, sq, hn]
        context_layer = context_layer.view(
194
195
196
197
198
            b,
            self.num_attention_heads_per_partition,
            sq,
            self.hidden_size_per_attention_head,
        )
199
200
201
202
203

        # [b, np, sq, hn] --> [sq, b, np, hn]
        context_layer = context_layer.permute(2, 0, 1, 3).contiguous()

        # [sq, b, np, hn] --> [sq, b, hp]
204
205
206
        new_context_layer_shape = context_layer.size()[:-2] + (
            self.hidden_size_per_partition,
        )
207
208
209
210
211
212
213
214
215
216
217
218
219
220
        context_layer = context_layer.view(*new_context_layer_shape)

        output, _ = self.out_proj(context_layer)

        return output


class QwenVLMLP(nn.Module):
    """MLP for the visual component of the Qwen model."""

    def __init__(
        self,
        hidden_size: int,
        intermediate_size: int,
221
        quant_config: QuantizationConfig | None = None,
222
        prefix: str = "",
223
224
    ):
        super().__init__()
225
        self.c_fc = ColumnParallelLinear(
226
227
228
229
230
            hidden_size,
            intermediate_size,
            bias=True,
            quant_config=quant_config,
            prefix=f"{prefix}.c_fc",
231
        )
232
233
234
235
236
237
        self.act_fn = get_act_fn("gelu")
        self.c_proj = RowParallelLinear(
            intermediate_size,
            hidden_size,
            bias=True,
            quant_config=quant_config,
238
            prefix=f"{prefix}.c_proj",
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
        )

    def forward(self, x):
        x, _ = self.c_fc(x)
        x = self.act_fn(x)
        x, _ = self.c_proj(x)
        return x


class VisualAttentionBlock(nn.Module):
    def __init__(
        self,
        d_model: int,
        n_head: int,
        mlp_ratio: float = 4.0,
        norm_layer: Callable[[int], nn.Module] = nn.LayerNorm,
255
        quant_config: QuantizationConfig | None = None,
256
        prefix: str = "",
257
258
259
260
261
262
    ):
        super().__init__()

        self.ln_1 = norm_layer(d_model)
        self.ln_2 = norm_layer(d_model)
        mlp_width = int(d_model * mlp_ratio)
263
        self.attn = VisualAttention(d_model, n_head, prefix=f"{prefix}.attn")
264
265
266
267
        self.mlp = QwenVLMLP(
            hidden_size=d_model,
            intermediate_size=mlp_width,
            quant_config=quant_config,
268
            prefix=f"{prefix}.mlp",
269
270
271
272
273
        )

    def attention(
        self,
        x: torch.Tensor,
274
        attn_mask: torch.Tensor | None = None,
275
276
277
278
279
280
281
    ) -> torch.Tensor:
        attn_mask = attn_mask.to(x.dtype) if attn_mask is not None else None
        return self.attn(x, attn_mask=attn_mask)

    def forward(
        self,
        x: torch.Tensor,
282
        attn_mask: torch.Tensor | None = None,
283
284
285
286
287
288
289
290
291
292
293
294
295
296
    ) -> torch.Tensor:
        x = x + self.attention(self.ln_1(x), attn_mask=attn_mask)
        x = x + self.mlp(self.ln_2(x))
        return x


class TransformerBlock(nn.Module):
    def __init__(
        self,
        width: int,
        layers: int,
        heads: int,
        mlp_ratio: float = 4.0,
        norm_layer: Callable[[int], nn.Module] = nn.LayerNorm,
297
        quant_config: QuantizationConfig | None = None,
298
        prefix: str = "",
299
300
301
302
303
    ):
        super().__init__()
        self.width = width
        self.layers = layers

304
305
306
307
308
309
310
311
        self.resblocks = nn.ModuleList(
            [
                VisualAttentionBlock(
                    width,
                    heads,
                    mlp_ratio,
                    norm_layer=norm_layer,
                    quant_config=quant_config,
312
                    prefix=f"{prefix}.resblocks.{i}",
313
                )
314
                for i in range(layers)
315
316
            ]
        )
317
318
319
320
321
322
323

    def get_cast_dtype(self) -> torch.dtype:
        return self.resblocks[0].mlp.c_fc.weight.dtype

    def get_cast_device(self) -> torch.device:
        return self.resblocks[0].mlp.c_fc.weight.device

324
    def forward(
325
        self, x: torch.Tensor, attn_mask: torch.Tensor | None = None
326
    ) -> torch.Tensor:
327
328
329
330
331
332
        for r in self.resblocks:
            x = r(x, attn_mask=attn_mask)
        return x


class VisionTransformer(nn.Module):
333
334
335
336
337
338
339
340
341
342
343
    def __init__(
        self,
        image_size: int,
        patch_size: int,
        width: int,
        layers: int,
        heads: int,
        mlp_ratio: float,
        n_queries: int = 256,
        output_dim: int = 512,
        image_start_id: int = 151857,
344
        quant_config: QuantizationConfig | None = None,
345
        prefix: str = "",
346
347
        **kwargs,
    ):
348
349
350
        super().__init__()
        image_height, image_width = self.image_size = (image_size, image_size)
        patch_height, patch_width = self.patch_size = (patch_size, patch_size)
351
        self.grid_size = (image_height // patch_height, image_width // patch_width)
352
        self.output_dim = output_dim
353
        self.conv1 = Conv2dLayer(
354
355
356
357
358
359
            in_channels=3,
            out_channels=width,
            kernel_size=patch_size,
            stride=patch_size,
            bias=False,
        )
360
361
362

        # class embeddings and positional embeddings
        scale = width**-0.5
363
        self.positional_embedding = nn.Parameter(scale * torch.randn(256, width))
364
365
366
367

        norm_layer = partial(nn.LayerNorm, eps=1e-6)

        self.ln_pre = norm_layer(width)
368
369
370
371
372
373
374
        self.transformer = TransformerBlock(
            width,
            layers,
            heads,
            mlp_ratio,
            norm_layer=norm_layer,
            quant_config=quant_config,
375
            prefix=f"{prefix}.transformer",
376
        )
377
378
379
380
381
382
383
384
385

        self.attn_pool = Resampler2(
            grid_size=int(math.sqrt(n_queries)),
            embed_dim=output_dim,
            num_heads=output_dim // 128,
            kv_dim=width,
            norm_layer=norm_layer,
            adaptive=False,
            do_post_projection=False,
386
            prefix=f"{prefix}.attn_pool",
387
388
389
390
391
392
393
        ).to(
            device=self.positional_embedding.device,
            dtype=self.positional_embedding.dtype,
        )

        self.ln_post = norm_layer(output_dim)
        self.proj = nn.Parameter(
394
395
            (output_dim**-0.5) * torch.randn(output_dim, output_dim)
        )
396
397
398
399
400
401
402
403
404
405
406
407
408

        self.image_start_id = image_start_id
        self.image_end_id = image_start_id + 1
        self.image_pad_id = image_start_id + 2

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = x.to(
            dtype=self.transformer.get_cast_dtype(),
            device=self.transformer.get_cast_device(),
        )

        # to patches
        x = self.conv1(x)  # shape = [*, width, grid, grid]
409
        x = x.reshape(x.shape[0], x.shape[1], -1)  # shape = [*, width, grid ** 2]
410
411
        x = x.permute(0, 2, 1)  # shape = [*, grid ** 2, width]

412
        x = x + get_abs_pos(self.positional_embedding, int(math.sqrt(x.size(1))))
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433

        x = self.ln_pre(x)

        x = x.permute(1, 0, 2)  # NLD -> LND
        x = self.transformer(x)
        x = x.permute(1, 0, 2)  # LND -> NLD

        x = self.attn_pool(x)
        x = self.ln_post(x)
        x = x @ self.proj

        return x


class QwenVLModel(QWenModel):
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__(vllm_config=vllm_config, prefix=prefix)

        config = vllm_config.model_config.hf_config
        quant_config = vllm_config.quant_config

434
435
436
        self.visual = VisionTransformer(
            **config.visual, quant_config=quant_config, prefix=f"{prefix}.visual"
        )
437
438
439
440


@lru_cache(maxsize=1)
def _get_tokenizer_without_image_pad(
441
442
    tokenizer: PreTrainedTokenizer,
) -> PreTrainedTokenizer:
443
444
    """
    The logic of adding image pad tokens should only be applied in
445
446
    [`QwenVLProcessor`][vllm.model_executor.models.qwen_vl.QwenVLProcessor],
    so they are patched out here.
447
448
449
450
451
452
453
454
455
456

    The definition of the wrapped tokenizer can be found here:
    https://huggingface.co/Qwen/Qwen-VL/blob/main/tokenization_qwen.py
    """
    new_tokenizer = copy.deepcopy(tokenizer)

    class TokenizerWithoutImagePad(tokenizer.__class__):  # type: ignore
        def tokenize(
            self,
            text: str,
457
458
            allowed_special: Set[str] | str = "all",
            disallowed_special: Collection[str] | str = (),
459
            **kwargs,
460
        ) -> list[bytes | str]:
461
462
463
            text = unicodedata.normalize("NFC", text)

            return [
464
465
                self.decoder[t]
                for t in self.tokenizer.encode(
466
467
468
469
470
471
472
473
                    text,
                    allowed_special=allowed_special,
                    disallowed_special=disallowed_special,
                )
            ]

        def _decode(
            self,
474
            token_ids: int | list[int],
475
            skip_special_tokens: bool = False,
476
            errors: str | None = None,
477
478
479
480
481
482
483
484
485
486
            **kwargs,
        ) -> str:
            if isinstance(token_ids, int):
                token_ids = [token_ids]

            return self.tokenizer.decode(
                token_ids,
                errors=errors or self.errors,
            )

487
    TokenizerWithoutImagePad.__name__ = f"{tokenizer.__class__.__name__}WithoutImagePad"
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517

    new_tokenizer.__class__ = TokenizerWithoutImagePad
    return new_tokenizer


class QwenVLProcessor:
    """
    This model doesn't define its own HF processor,
    so we implement our own one here.

    We call the wrapped tokenizer to automatically insert image pad tokens:
    https://huggingface.co/Qwen/Qwen-VL/blob/main/tokenization_qwen.py#L245

    The image processor is defined here:
    https://huggingface.co/Qwen/Qwen-VL/blob/main/visual.py#L354
    """

    def __init__(
        self,
        config: PretrainedConfig,
        tokenizer: PreTrainedTokenizer,
    ) -> None:
        super().__init__()

        self.config = config
        self.tokenizer = tokenizer

        vision_config = config.visual
        image_size = vision_config["image_size"]

518
519
520
521
522
523
524
525
526
527
528
529
530
        self.image_transform = transforms.Compose(
            [
                transforms.Resize(
                    (image_size, image_size),
                    interpolation=InterpolationMode.BICUBIC,
                ),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=(0.48145466, 0.4578275, 0.40821073),
                    std=(0.26862954, 0.26130258, 0.27577711),
                ),
            ]
        )
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545

    @property
    def image_start_tag(self) -> str:
        return self.tokenizer.image_start_tag  # type: ignore

    @property
    def image_end_tag(self) -> str:
        return self.tokenizer.image_end_tag  # type: ignore

    @property
    def image_pad_tag(self) -> str:
        return self.tokenizer.image_pad_tag  # type: ignore

    def __call__(
        self,
546
547
548
        text: TextInput | list[TextInput] | None = None,
        images: ImageInput | list[ImageInput] | None = None,
        return_tensors: str | TensorType | None = None,
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
    ) -> BatchFeature:
        if text is None:
            text = []
        if not isinstance(text, list):
            text = [text]
        if images is None:
            images = []
        if not isinstance(images, list):
            images = [images]

        text_inputs = self.tokenizer(text)

        if len(images) == 0:
            image_inputs = {}
        else:
            pixel_values = [self.image_transform(image) for image in images]
            image_inputs = {"pixel_values": torch.stack(pixel_values)}

        return BatchFeature(
            {
                **text_inputs,
                **image_inputs,
            },
            tensor_type=return_tensors,
        )


class QwenVLProcessingInfo(BaseProcessingInfo):
    def get_tokenizer(self) -> PreTrainedTokenizer:
578
        tokenizer = self.ctx.get_tokenizer()
579
580
581
582
        assert isinstance(tokenizer, PreTrainedTokenizer)

        return _get_tokenizer_without_image_pad(tokenizer)

583
584
585
586
587
588
589
    def get_hf_processor(self, **kwargs: object) -> QwenVLProcessor:
        return self.ctx.init_processor(
            QwenVLProcessor,
            config=self.get_hf_config(),
            tokenizer=self.get_tokenizer(),
            **kwargs,
        )
590

591
    def get_supported_mm_limits(self) -> Mapping[str, int | None]:
592
593
594
595
596
597
598
599
600
601
602
603
604
        return {"image": None}

    def get_num_image_tokens(self) -> int:
        hf_config = self.get_hf_config()
        vision_config = hf_config.visual

        image_size = vision_config["image_size"]
        patch_size = vision_config["patch_size"]
        grid_length = image_size // patch_size // 2
        return grid_length * grid_length


class QwenVLDummyInputsBuilder(BaseDummyInputsBuilder[QwenVLProcessingInfo]):
605
606
607
608
609
610
611
    def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
        num_images = mm_counts.get("image", 0)

        hf_processor = self.info.get_hf_processor()
        img_start = hf_processor.image_start_tag
        img_end = hf_processor.image_end_tag

612
613
614
        return "".join(
            f"Picture {i}: {img_start}{img_end}\n" for i in range(1, num_images + 1)
        )
615
616

    def get_dummy_mm_data(
617
618
619
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
620
        mm_options: Mapping[str, BaseDummyOptions] | None = None,
621
        mm_processor_kwargs: Mapping[str, object] | None = None,
622
    ) -> MultiModalDataDict:
623
624
625
626
627
628
        hf_config = self.info.get_hf_config()
        vision_config = hf_config.visual

        target_width = target_height = vision_config["image_size"]
        num_images = mm_counts.get("image", 0)

629
630
        image_overrides = mm_options.get("image") if mm_options else None

631
        return {
632
633
634
635
636
637
            "image": self._get_dummy_images(
                width=target_width,
                height=target_height,
                num_images=num_images,
                overrides=image_overrides,
            )
638
639
640
641
642
643
644
645
646
        }


class QwenVLMultiModalProcessor(BaseMultiModalProcessor[QwenVLProcessingInfo]):
    def _call_hf_processor(
        self,
        prompt: str,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
647
        tok_kwargs: Mapping[str, object],
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
    ) -> BatchFeature:
        # Drops anything between <img>/</img> tags; encoding with the tokenizer
        # will automatically add the image pads for the context.
        prompt, num_matched_images = re.subn(
            r"(Picture \d*: <img>).*?(<\/img>\n)",
            r"\1\2",
            prompt,
        )

        image_data = mm_data.get("images")
        if image_data is not None:
            assert isinstance(image_data, list)

            num_images = len(image_data)
            assert num_matched_images == num_images

        return super()._call_hf_processor(
            prompt=prompt,
            mm_data=mm_data,
            mm_kwargs=mm_kwargs,
668
            tok_kwargs=tok_kwargs,
669
670
        )

671
    def _hf_processor_applies_updates(
672
673
674
675
        self,
        prompt_text: str,
        mm_items: MultiModalDataItems,
        hf_processor_mm_kwargs: Mapping[str, object],
676
        tokenization_kwargs: Mapping[str, object],
677
678
679
    ) -> bool:
        return False

680
681
682
683
684
685
686
687
688
689
    def _get_mm_fields_config(
        self,
        hf_inputs: BatchFeature,
        hf_processor_mm_kwargs: Mapping[str, object],
    ) -> Mapping[str, MultiModalFieldConfig]:
        return dict(
            pixel_values=MultiModalFieldConfig.batched("image"),
            image_embeds=MultiModalFieldConfig.batched("image"),
        )

690
    def _get_prompt_updates(
691
692
693
        self,
        mm_items: MultiModalDataItems,
        hf_processor_mm_kwargs: Mapping[str, object],
694
        out_mm_kwargs: MultiModalKwargsItems,
695
    ) -> Sequence[PromptUpdate]:
696
        tokenizer = self.info.get_tokenizer()
697
        special_tokens: dict[str, int] = tokenizer.special_tokens  # type: ignore
698
699
700
701
702
703
704
705
706
707
708
709
710

        processor = self.info.get_hf_processor()
        img_start_id = special_tokens[processor.image_start_tag]
        img_end_id = special_tokens[processor.image_end_tag]
        img_pad_id = special_tokens[processor.image_pad_tag]

        num_image_tokens = self.info.get_num_image_tokens()
        image_tokens = [img_pad_id] * num_image_tokens

        return [
            PromptReplacement(
                modality="image",
                target=[img_start_id, img_end_id],
711
712
713
                replacement=PromptUpdateDetails.select_token_id(
                    [img_start_id] + image_tokens + [img_end_id],
                    embed_token_id=img_pad_id,
714
715
716
717
718
                ),
            )
        ]


719
720
721
722
723
724
725
726
@MULTIMODAL_REGISTRY.register_processor(
    QwenVLMultiModalProcessor,
    info=QwenVLProcessingInfo,
    dummy_inputs=QwenVLDummyInputsBuilder,
)
class QwenVLForConditionalGeneration(
    QWenBaseModel, SupportsPP, SupportsLoRA, SupportsMultiModal
):
727
728
729
730
731
732
733
734
    packed_modules_mapping = {
        "c_attn": ["c_attn"],
        "gate_up_proj": [
            "w2",
            "w1",
        ],
    }

735
736
    embed_input_ids = SupportsMultiModal.embed_input_ids

737
738
739
740
741
742
743
    def get_mm_mapping(self) -> MultiModelKeys:
        """
        Get the module prefix in multimodal models
        """
        return MultiModelKeys.from_string_field(
            language_model="transformer.h",
            connector="transformer.visual.attn_pool",
744
745
            tower_model="transformer.visual.transformer",
        )
746

747
    @classmethod
748
    def get_placeholder_str(cls, modality: str, i: int) -> str | None:
749
750
751
752
753
        if modality.startswith("image"):
            return f"Picture {i}: <img></img>"

        raise ValueError("Only image modality is supported")

754
755
756
757
758
759
760
    def __init__(
        self,
        *,
        vllm_config: VllmConfig,
        prefix: str = "",
        transformer_type: type[QwenVLModel] = QwenVLModel,
    ) -> None:
761
762
763
764
765
766
767
768
769
770
        with self._mark_composite_model(
            vllm_config,
            language_targets=QWenBlock,
            tower_targets={"image": VisionTransformer},
        ):
            super().__init__(
                vllm_config=vllm_config,
                prefix=prefix,
                transformer_type=transformer_type,
            )
771
772
773
774

        self.transformer: QwenVLModel

    def _parse_and_validate_image_input(
775
        self, **kwargs: object
776
    ) -> QwenImageInputs | None:
777
778
779
780
        pixel_values = kwargs.pop("pixel_values", None)
        image_embeds = kwargs.pop("image_embeds", None)

        if pixel_values is not None:
781
782
783
            expected_h = expected_w = self.config.visual["image_size"]
            resolve_bindings = {"h": expected_h, "w": expected_w}

784
785
            return QwenImagePixelInputs(
                type="pixel_values",
786
                data=pixel_values,
787
                resolve_bindings=resolve_bindings,
788
789
790
791
792
            )

        if image_embeds is not None:
            return QwenImageEmbeddingInputs(
                type="image_embeds",
793
                data=image_embeds,
794
795
796
797
            )

        return None

798
    def _process_image_input(self, image_input: QwenImageInputs) -> torch.Tensor:
799
800
801
802
803
        if image_input["type"] == "image_embeds":
            return image_input["data"]

        return self.transformer.visual(image_input["data"])

804
    def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings:
805
806
        image_input = self._parse_and_validate_image_input(**kwargs)
        if image_input is None:
807
            return []
808
809
810
811
812
813

        vision_embeddings = self._process_image_input(image_input)
        return vision_embeddings

    def forward(
        self,
814
        input_ids: torch.Tensor | None,
815
        positions: torch.Tensor,
816
817
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
818
        **kwargs: object,
819
    ) -> torch.Tensor | IntermediateTensors:
820
821
822
        if intermediate_tensors is not None:
            inputs_embeds = None

823
824
825
        hidden_states = self.transformer(
            input_ids, positions, intermediate_tensors, inputs_embeds
        )
826
        return hidden_states