"examples/vscode:/vscode.git/clone" did not exist on "88c830410468fa3549638cf78d6c354b13046921"
blip2.py 24.3 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
from collections.abc import Iterable, Mapping, Sequence
5
from typing import Annotated, Literal, TypeAlias
6
7
8

import torch
import torch.nn as nn
9
10
11
12
13
14
from transformers import (
    BatchFeature,
    Blip2Config,
    Blip2QFormerConfig,
    apply_chunking_to_forward,
)
15

16
from vllm.config import CacheConfig, VllmConfig
17
from vllm.config.multimodal import BaseDummyOptions
18
19
20
from vllm.model_executor.layers.activation import get_act_fn
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.multimodal import MULTIMODAL_REGISTRY
21
22
23
24
25
from vllm.multimodal.inputs import (
    MultiModalDataDict,
    MultiModalFieldConfig,
    MultiModalKwargsItems,
)
26
from vllm.multimodal.parse import MultiModalDataItems
27
from vllm.multimodal.processing import (
28
    BaseDummyInputsBuilder,
29
30
31
32
33
34
    BaseMultiModalProcessor,
    BaseProcessingInfo,
    PromptIndexTargets,
    PromptInsertion,
    PromptUpdate,
)
35
from vllm.sequence import IntermediateTensors
36
from vllm.utils.tensor_schema import TensorSchema, TensorShape
37

38
from .blip import BlipVisionModel, get_blip_num_patches
39
40
from .interfaces import (
    MultiModalEmbeddings,
41
    SupportsLoRA,
42
43
44
45
    SupportsMultiModal,
    SupportsPP,
    SupportsQuant,
)
46
from .module_mapping import MultiModelKeys
47
from .utils import AutoWeightsLoader, init_vllm_registered_model, maybe_prefix
48
49


50
51
52
53
54
55
56
57
class Blip2ImagePixelInputs(TensorSchema):
    """
    Dimensions:
        - bn: Batch size * number of images
        - c: Number of channels (3)
        - h: Height of each image
        - w: Width of each image
    """
58

59
    type: Literal["pixel_values"]
60
    data: Annotated[torch.Tensor, TensorShape("bn", 3, "h", "w")]
61
62


63
class Blip2ImageEmbeddingInputs(TensorSchema):
64
    """
65
66
67
68
69
    Dimensions:
        - bn: Batch size * number of images
        - f: Image feature size
        - h: Hidden size (must match the hidden size of language model backbone)
    """
70

71
72
    type: Literal["image_embeds"]
    data: Annotated[torch.Tensor, TensorShape("bn", "f", "h")]
73
74


75
Blip2ImageInputs: TypeAlias = Blip2ImagePixelInputs | Blip2ImageEmbeddingInputs
76
"""Alias for supported BLIP-2 image input types."""
77

78
79
80
81
82
83

class Blip2QFormerMultiHeadAttention(nn.Module):
    def __init__(
        self,
        config: Blip2QFormerConfig,
        *,
84
85
        quant_config: QuantizationConfig | None,
        cache_config: CacheConfig | None,
86
        is_cross_attention: bool = False,
87
        prefix: str = "",
88
89
90
91
92
93
94
95
96
97
98
99
    ) -> None:
        super().__init__()

        self.config = config

        if config.hidden_size % config.num_attention_heads != 0:
            raise ValueError(
                f"The hidden size ({config.hidden_size}) is not a multiple of "
                f"the number of attention heads ({config.num_attention_heads})"
            )

        self.num_attention_heads = config.num_attention_heads
100
        self.attention_head_size = config.hidden_size // config.num_attention_heads
101
102
103
104
105
106
107
108
109
110
111
        self.all_head_size = self.num_attention_heads * self.attention_head_size
        self.scaling = self.attention_head_size**-0.5

        self.query = nn.Linear(config.hidden_size, self.all_head_size)
        if is_cross_attention:
            kv_hidden_size = config.encoder_hidden_size
        else:
            kv_hidden_size = config.hidden_size
        self.key = nn.Linear(kv_hidden_size, self.all_head_size)
        self.value = nn.Linear(kv_hidden_size, self.all_head_size)

112
113
114
        self.position_embedding_type = getattr(
            config, "position_embedding_type", "absolute"
        )
115
        if self.position_embedding_type != "absolute":
116
117
118
            raise NotImplementedError(
                f"Unsupported position_embedding_type: {self.position_embedding_type}"
            )
119
120
121
122

        self.dropout = nn.Dropout(config.attention_probs_dropout_prob)

    def transpose_for_scores(self, x):
123
        x = x.view(*x.size()[:-1], self.num_attention_heads, self.attention_head_size)
124
125
126
127
128
        return x.permute(0, 2, 1, 3)

    def forward(
        self,
        hidden_states: torch.Tensor,
129
        encoder_hidden_states: torch.FloatTensor | None = None,
130
131
132
133
    ):
        is_cross_attention = encoder_hidden_states is not None

        if is_cross_attention:
134
135
            key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
            value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
136
137
138
139
140
141
142
143
        else:
            key_layer = self.transpose_for_scores(self.key(hidden_states))
            value_layer = self.transpose_for_scores(self.value(hidden_states))

        mixed_query_layer = self.query(hidden_states)

        query_layer = self.transpose_for_scores(mixed_query_layer)

144
145
        attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
        attention_probs = torch.softmax(attention_scores * self.scaling, dim=-1)
146
147
148
149
150
151
152
153

        # This is actually dropping out entire tokens to attend to, which might
        # seem a bit unusual, but is taken from the original Transformer paper.
        attention_probs_dropped = self.dropout(attention_probs)

        context_layer = torch.matmul(attention_probs_dropped, value_layer)

        context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
154
155
156
        context_layer = context_layer.view(
            *context_layer.size()[:-2], self.all_head_size
        )
157
158
159
160
161

        return context_layer


class Blip2QFormerSelfOutput(nn.Module):
162
    def __init__(self, config: Blip2QFormerConfig, prefix: str = "") -> None:
163
164
165
        super().__init__()

        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
166
        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
        self.dropout = nn.Dropout(config.hidden_dropout_prob)

    def forward(
        self,
        hidden_states: torch.Tensor,
        input_tensor: torch.Tensor,
    ) -> torch.Tensor:
        hidden_states = self.dense(hidden_states)
        hidden_states = self.dropout(hidden_states)
        hidden_states = self.LayerNorm(hidden_states + input_tensor)
        return hidden_states


class Blip2QFormerAttention(nn.Module):
    def __init__(
        self,
        config: Blip2QFormerConfig,
        *,
185
186
        quant_config: QuantizationConfig | None,
        cache_config: CacheConfig | None,
187
        is_cross_attention: bool = False,
188
        prefix: str = "",
189
190
191
192
193
194
195
196
    ) -> None:
        super().__init__()

        self.attention = Blip2QFormerMultiHeadAttention(
            config,
            quant_config=quant_config,
            cache_config=cache_config,
            is_cross_attention=is_cross_attention,
197
            prefix=f"{prefix}.attention",
198
199
        )

200
        self.output = Blip2QFormerSelfOutput(config, prefix=f"{prefix}.output")
201
202
203
204

    def forward(
        self,
        hidden_states: torch.Tensor,
205
        encoder_hidden_states: torch.FloatTensor | None = None,
206
    ) -> tuple[torch.Tensor]:
207
208
209
210
211
212
213
214
215
216
        self_output = self.attention(
            hidden_states,
            encoder_hidden_states=encoder_hidden_states,
        )
        attention_output = self.output(self_output, hidden_states)

        return attention_output


class Blip2QFormerIntermediate(nn.Module):
217
    def __init__(self, config: Blip2QFormerConfig, prefix: str = "") -> None:
218
219
220
221
222
223
224
225
226
227
228
229
        super().__init__()

        self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
        self.intermediate_act_fn = get_act_fn(config.hidden_act)

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        hidden_states = self.dense(hidden_states)
        hidden_states = self.intermediate_act_fn(hidden_states)
        return hidden_states


class Blip2QFormerOutput(nn.Module):
230
    def __init__(self, config: Blip2QFormerConfig, prefix: str = "") -> None:
231
232
233
        super().__init__()

        self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
234
        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
        self.dropout = nn.Dropout(config.hidden_dropout_prob)

    def forward(
        self,
        hidden_states: torch.Tensor,
        input_tensor: torch.Tensor,
    ) -> torch.Tensor:
        hidden_states = self.dense(hidden_states)
        hidden_states = self.dropout(hidden_states)
        hidden_states = self.LayerNorm(hidden_states + input_tensor)
        return hidden_states


class Blip2QFormerLayer(nn.Module):
    def __init__(
        self,
        config: Blip2QFormerConfig,
        *,
253
254
        quant_config: QuantizationConfig | None,
        cache_config: CacheConfig | None,
255
        layer_idx: int,
256
        prefix: str = "",
257
258
259
260
261
    ) -> None:
        super().__init__()

        self.chunk_size_feed_forward = config.chunk_size_feed_forward
        self.seq_len_dim = 1
262
263
264
265
266
267
        self.attention = Blip2QFormerAttention(
            config,
            quant_config=quant_config,
            cache_config=cache_config,
            prefix=f"{prefix}.attention",
        )
268
269
270
271
272
273
274
275

        self.layer_idx = layer_idx

        if layer_idx % config.cross_attention_frequency == 0:
            self.crossattention = Blip2QFormerAttention(
                config,
                quant_config=quant_config,
                cache_config=cache_config,
276
                is_cross_attention=True,
277
278
                prefix=f"{prefix}.crossattention",
            )
279
280
281
282
            self.has_cross_attention = True
        else:
            self.has_cross_attention = False

283
        self.intermediate_query = Blip2QFormerIntermediate(
284
285
286
            config, prefix=f"{prefix}.intermediate_query"
        )
        self.output_query = Blip2QFormerOutput(config, prefix=f"{prefix}.output_query")
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318

    def forward(
        self,
        hidden_states: torch.FloatTensor,
        encoder_hidden_states: torch.FloatTensor,
        query_length: int,
    ):
        attention_output = self.attention(hidden_states)

        if query_length > 0:
            query_attention_output = attention_output[:, :query_length, :]

            if self.has_cross_attention:
                query_attention_output = self.crossattention(
                    query_attention_output,
                    encoder_hidden_states=encoder_hidden_states,
                )

            layer_output = apply_chunking_to_forward(
                self.feed_forward_chunk_query,
                self.chunk_size_feed_forward,
                self.seq_len_dim,
                query_attention_output,
            )

            if attention_output.shape[1] > query_length:
                layer_output_text = apply_chunking_to_forward(
                    self.feed_forward_chunk,
                    self.chunk_size_feed_forward,
                    self.seq_len_dim,
                    attention_output[:, query_length:, :],
                )
319
                layer_output = torch.cat([layer_output, layer_output_text], dim=1)
320
321
322
323
324
325
326
327
328
329
        else:
            layer_output = apply_chunking_to_forward(
                self.feed_forward_chunk,
                self.chunk_size_feed_forward,
                self.seq_len_dim,
                attention_output,
            )

        return layer_output

330
    def feed_forward_chunk(self, attention_output: torch.Tensor) -> torch.Tensor:
331
332
333
334
        intermediate_output = self.intermediate(attention_output)
        layer_output = self.output(intermediate_output, attention_output)
        return layer_output

335
    def feed_forward_chunk_query(self, attention_output: torch.Tensor) -> torch.Tensor:
336
337
338
339
340
341
342
343
344
345
        intermediate_output = self.intermediate_query(attention_output)
        layer_output = self.output_query(intermediate_output, attention_output)
        return layer_output


class Blip2QFormerEncoder(nn.Module):
    def __init__(
        self,
        config: Blip2QFormerConfig,
        *,
346
347
        quant_config: QuantizationConfig | None,
        cache_config: CacheConfig | None,
348
        prefix: str = "",
349
350
351
352
353
    ) -> None:
        super().__init__()

        self.config = config

354
355
356
357
358
359
360
361
362
363
364
365
        self.layer = nn.ModuleList(
            [
                Blip2QFormerLayer(
                    config,
                    quant_config=quant_config,
                    cache_config=cache_config,
                    layer_idx=layer_idx,
                    prefix=f"{prefix}.layer.{layer_idx}",
                )
                for layer_idx in range(config.num_hidden_layers)
            ]
        )
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390

    def forward(
        self,
        hidden_states: torch.FloatTensor,
        encoder_hidden_states: torch.FloatTensor,
        query_length: int,
    ) -> torch.Tensor:
        for i in range(self.config.num_hidden_layers):
            layer_module = self.layer[i]

            hidden_states = layer_module(
                hidden_states,
                encoder_hidden_states=encoder_hidden_states,
                query_length=query_length,
            )

        return hidden_states


# Adapted from https://github.com/huggingface/transformers/blob/v4.41.2/src/transformers/models/blip_2/modeling_blip_2.py#L1025
class Blip2QFormerModel(nn.Module):
    def __init__(
        self,
        config: Blip2QFormerConfig,
        *,
391
392
        quant_config: QuantizationConfig | None,
        cache_config: CacheConfig | None,
393
        prefix: str = "",
394
395
396
397
398
    ) -> None:
        super().__init__()

        self.config = config

399
        self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
400
401
        self.dropout = nn.Dropout(config.hidden_dropout_prob)

402
403
404
405
406
407
        self.encoder = Blip2QFormerEncoder(
            config,
            quant_config=quant_config,
            cache_config=cache_config,
            prefix=f"{prefix}.encoder",
        )
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427

    def forward(
        self,
        query_embeds: torch.FloatTensor,
        encoder_hidden_states: torch.FloatTensor,
    ) -> torch.Tensor:
        query_length = query_embeds.shape[1]

        embedding_output = self.layernorm(query_embeds)
        embedding_output = self.dropout(embedding_output)

        sequence_output = self.encoder(
            embedding_output,
            encoder_hidden_states=encoder_hidden_states,
            query_length=query_length,
        )

        return sequence_output


428
429
class Blip2ProcessingInfo(BaseProcessingInfo):
    def get_hf_config(self):
430
        return self.ctx.get_hf_config(Blip2Config)
431

432
    def get_supported_mm_limits(self) -> Mapping[str, int | None]:
433
434
        return {"image": 1}

435
436
437
438
439
440
    def get_num_image_tokens(self) -> int:
        hf_config = self.get_hf_config()
        return hf_config.num_query_tokens


class Blip2DummyInputsBuilder(BaseDummyInputsBuilder[Blip2ProcessingInfo]):
441
442
443
444
    def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
        return ""

    def get_dummy_mm_data(
445
446
447
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
448
        mm_options: Mapping[str, BaseDummyOptions] | None = None,
449
        mm_processor_kwargs: Mapping[str, object] | None = None,
450
    ) -> MultiModalDataDict:
451
        hf_config = self.info.get_hf_config()
452
453
454
455
456
        vision_config = hf_config.vision_config

        max_image_size = vision_config.image_size
        num_images = mm_counts.get("image", 0)

457
458
        image_overrides = mm_options.get("image") if mm_options else None

459
        return {
460
461
462
463
464
465
            "image": self._get_dummy_images(
                width=max_image_size,
                height=max_image_size,
                num_images=num_images,
                overrides=image_overrides,
            )
466
467
468
        }


469
class Blip2MultiModalProcessor(BaseMultiModalProcessor[Blip2ProcessingInfo]):
470
471
472
473
474
    def _call_hf_processor(
        self,
        prompt: str,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
475
        tok_kwargs: Mapping[str, object],
476
477
478
479
480
481
482
483
484
485
486
    ) -> BatchFeature:
        if not mm_data:
            # HF processor always adds placeholders even when there's no image
            tokenizer = self.info.get_tokenizer()
            prompt_ids = tokenizer.encode(prompt)
            return BatchFeature(dict(input_ids=[prompt_ids]), tensor_type="pt")

        return super()._call_hf_processor(
            prompt=prompt,
            mm_data=mm_data,
            mm_kwargs=mm_kwargs,
487
            tok_kwargs=tok_kwargs,
488
489
        )

490
491
492
493
494
495
496
497
498
    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"),
        )
499

500
    def _get_prompt_updates(
501
502
503
        self,
        mm_items: MultiModalDataItems,
        hf_processor_mm_kwargs: Mapping[str, object],
504
        out_mm_kwargs: MultiModalKwargsItems,
505
    ) -> Sequence[PromptUpdate]:
506
507
508
        tokenizer = self.info.get_tokenizer()
        vocab = tokenizer.get_vocab()

509
        image_token_id = vocab["<image>"]
510
        num_image_tokens = self.info.get_num_image_tokens()
511
        image_tokens = [image_token_id] * num_image_tokens
512
513

        return [
514
            PromptInsertion(
515
                modality="image",
516
                target=PromptIndexTargets.start(),
517
                insertion=image_tokens,
518
519
            )
        ]
520
521


522
523
524
525
526
527
@MULTIMODAL_REGISTRY.register_processor(
    Blip2MultiModalProcessor,
    info=Blip2ProcessingInfo,
    dummy_inputs=Blip2DummyInputsBuilder,
)
class Blip2ForConditionalGeneration(
528
    nn.Module, SupportsLoRA, SupportsMultiModal, SupportsPP, SupportsQuant
529
):
530
    @classmethod
531
    def get_placeholder_str(cls, modality: str, i: int) -> str | None:
532
533
534
535
536
        if modality.startswith("image"):
            return None

        raise ValueError("Only image modality is supported")

537
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
538
        super().__init__()
539
540
541
542
        config = vllm_config.model_config.hf_config
        cache_config = vllm_config.cache_config
        quant_config = vllm_config.quant_config
        multimodal_config = vllm_config.model_config.multimodal_config
543
544
        self.config = config
        self.multimodal_config = multimodal_config
545
546
547
548
549
550
551
552
        vision_config = config.vision_config
        self._vision_tokens_per_image = (
            get_blip_num_patches(
                image_size=vision_config.image_size,
                patch_size=vision_config.patch_size,
            )
            + 1  # include class token
        )
553

554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
        with self._mark_tower_model(vllm_config, "image"):
            self.vision_model = BlipVisionModel(vision_config, quant_config)
            self.query_tokens = nn.Parameter(
                torch.zeros(
                    1, config.num_query_tokens, config.qformer_config.hidden_size
                )
            )
            self.qformer = Blip2QFormerModel(
                config.qformer_config,
                cache_config=cache_config,
                quant_config=quant_config,
                prefix=f"{prefix}.qformer",
            )
            self.language_projection = nn.Linear(
                config.qformer_config.hidden_size,
                config.text_config.hidden_size,
                bias=True,
            )
572

573
574
575
576
577
578
        with self._mark_language_model(vllm_config):
            self.language_model = init_vllm_registered_model(
                vllm_config=vllm_config,
                hf_config=config.text_config,
                prefix=maybe_prefix(prefix, "language_model"),
            )
579

580
        self.make_empty_intermediate_tensors = (
581
582
            self.language_model.make_empty_intermediate_tensors
        )
583

584
    def _parse_and_validate_image_input(
585
        self, **kwargs: object
586
    ) -> Blip2ImageInputs | None:
587
        pixel_values = kwargs.pop("pixel_values", None)
588
        image_embeds = kwargs.pop("image_embeds", None)
589

590
        if pixel_values is None and image_embeds is None:
591
592
            return None

593
        if pixel_values is not None:
594
            expected_h = expected_w = self.config.vision_config.image_size
595
596
597
598
599
            return Blip2ImagePixelInputs(
                type="pixel_values",
                data=pixel_values,
                resolve_bindings={"h": expected_h, "w": expected_w},
            )
600
601
602
603

        if image_embeds is not None:
            return Blip2ImageEmbeddingInputs(
                type="image_embeds",
604
                data=image_embeds,
605
606
607
            )

        raise AssertionError("This line should be unreachable.")
608

609
610
611
    def _image_pixels_to_features(
        self, vision_model: BlipVisionModel, pixel_values: torch.Tensor
    ) -> torch.Tensor:
612
613
614
615
616
617
        # NOTE: we skip the step to select the vision feature layer since
        # this is already done inside the vision tower
        image_features = vision_model(pixel_values)

        return image_features

618
    def _process_image_pixels(self, inputs: Blip2ImagePixelInputs) -> torch.Tensor:
619
620
621
622
        pixel_values = inputs["data"]

        return self._image_pixels_to_features(self.vision_model, pixel_values)

623
    def _process_image_input(self, image_input: Blip2ImageInputs) -> torch.Tensor:
624
625
626
        if image_input["type"] == "image_embeds":
            return image_input["data"]

627
628
        image_features = self._process_image_pixels(image_input)

629
        query_tokens = self.query_tokens.expand(image_features.shape[0], -1, -1)
630
631
632
633
634
635
636
        query_output = self.qformer(
            query_embeds=query_tokens,
            encoder_hidden_states=image_features,
        )

        return self.language_projection(query_output)

637
    def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings:
638
639
        image_input = self._parse_and_validate_image_input(**kwargs)
        if image_input is None:
640
            return []
641
642
643
        vision_embeddings = self._process_image_input(image_input)
        return vision_embeddings

644
645
    def forward(
        self,
646
        input_ids: torch.Tensor | None,
647
        positions: torch.Tensor,
648
649
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
650
        **kwargs: object,
651
    ) -> IntermediateTensors:
652
653
654
655
656
657
658
659
660
661
662
663
        """Run forward pass for BLIP-2.

        One key thing to understand is the `input_ids` already accounts for the
        positions of the to-be-inserted image embeddings.

        Concretely, consider a text prompt:
        `"Question: What's the content of the image? Answer:"`.

        Tokenizer outputs:
        `[2, 45641, 35, 653, 18, 5, 1383, 9, 5, 2274, 116, 31652, 35]`.

        To reserve space in KV cache, we have to insert placeholder tokens
664
        before they are inputted to the model, so the input processor prepends
665
666
667
668
669
670
671
672
673
674
675
676
        dummy tokens (denoted as `50265`), resulting in:
        `[50265, ..., 50265, 2, 45641, 35, ..., 31652, 35]`.

        We insert 32 tokens since it corresponds to the number of query
        embeddings outputted by the Q-Former and inputted to the language model.

        This way, the `positions` and `attn_metadata` are consistent
        with the `input_ids`.

        Args:
            input_ids: Flattened (concatenated) input_ids corresponding to a
                batch.
677

678
        Info:
samzong's avatar
samzong committed
679
            [`Blip2ImageInputs`][vllm.model_executor.models.blip2.Blip2ImageInputs]
680
        """
681

682
        if intermediate_tensors is not None:
683
            inputs_embeds = None
684

685
686
687
        hidden_states = self.language_model.model(
            input_ids, positions, intermediate_tensors, inputs_embeds=inputs_embeds
        )
688
689
690

        return hidden_states

691
692
693
    def compute_logits(
        self,
        hidden_states: torch.Tensor,
694
    ) -> torch.Tensor | None:
695
        return self.language_model.compute_logits(hidden_states)
696

697
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
698
        loader = AutoWeightsLoader(self)
699
        return loader.load_weights(weights)
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732

    def get_mm_mapping(self) -> MultiModelKeys:
        return MultiModelKeys.from_string_field(
            language_model="language_model",
            connector=["qformer", "language_projection"],
            tower_model="vision_model",
        )

    def get_num_mm_encoder_tokens(
        self,
        num_image_tokens: int,
    ) -> int:
        if num_image_tokens <= 0:
            return 0
        assert num_image_tokens % self.config.num_query_tokens == 0, (
            "The number of image tokens must be a multiple of "
            "the number of query tokens."
        )
        num_images = num_image_tokens / self.config.num_query_tokens
        return num_images * self._vision_tokens_per_image

    def get_num_mm_connector_tokens(
        self,
        num_vision_tokens: int,
    ) -> int:
        if num_vision_tokens <= 0:
            return 0
        assert num_vision_tokens % self._vision_tokens_per_image == 0, (
            "The number of vision tokens must be a multiple of "
            "the number of tokens per image."
        )
        num_images = num_vision_tokens / self._vision_tokens_per_image
        return num_images * self.config.num_query_tokens