interns1_vit.py 14.7 KB
Newer Older
Lyu Han's avatar
Lyu Han committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

# adapted from https://huggingface.co/OpenGVLab/InternVL2-4B/blob/main/modeling_intern_vit.py
# --------------------------------------------------------
# InternVL
# Copyright (c) 2023 OpenGVLab
# Licensed under The MIT License [see LICENSE for details]
# --------------------------------------------------------
from collections.abc import Iterable

import torch
import torch.nn as nn
from transformers import PretrainedConfig
from transformers.utils import torch_int

from vllm.model_executor.layers.activation import get_act_fn
18
from vllm.model_executor.layers.attention import MMEncoderAttention
19
from vllm.model_executor.layers.conv import Conv2dLayer
Lyu Han's avatar
Lyu Han committed
20
from vllm.model_executor.layers.layernorm import RMSNorm
21
from vllm.model_executor.layers.linear import ColumnParallelLinear, RowParallelLinear
Lyu Han's avatar
Lyu Han committed
22
23
24
25
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.model_loader.weight_utils import default_weight_loader

NORM2FN = {
26
27
    "rms_norm": RMSNorm,
    "layer_norm": nn.LayerNorm,
Lyu Han's avatar
Lyu Han committed
28
29
30
31
32
33
34
35
36
}


class InternS1VisionPatchEmbeddings(nn.Module):
    def __init__(self, config):
        super().__init__()
        image_size, patch_size = config.image_size, config.patch_size
        num_channels, hidden_size = config.num_channels, config.hidden_size

37
38
39
40
        num_patches = (image_size[1] // patch_size[1]) * (
            image_size[0] // patch_size[0]
        )
        patch_shape = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
Lyu Han's avatar
Lyu Han committed
41
42
43
44
45
46
        self.image_size = image_size
        self.patch_size = patch_size
        self.num_channels = num_channels
        self.num_patches = num_patches
        self.patch_shape = patch_shape

47
        self.projection = Conv2dLayer(
48
49
            num_channels, hidden_size, kernel_size=patch_size, stride=patch_size
        )
Lyu Han's avatar
Lyu Han committed
50
51
52
53
54
55

    def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
        batch_size, num_channels, height, width = pixel_values.shape
        if num_channels != self.num_channels:
            raise ValueError(
                "Make sure that the channel dimension of the pixel values "
56
57
                "match with the one set in the configuration."
            )
Lyu Han's avatar
Lyu Han committed
58

59
        embeddings = self.projection(pixel_values.to(self.projection.weight.dtype))
Lyu Han's avatar
Lyu Han committed
60
61
62
63
64
65
66
67
68
69
70
71
        patch_height, patch_width = embeddings.shape[2], embeddings.shape[3]
        embeddings = embeddings.flatten(2).transpose(1, 2)

        return embeddings, (patch_height, patch_width)


class InternS1VisionEmbeddings(nn.Module):
    def __init__(self, config: PretrainedConfig):
        super().__init__()
        self.config = config
        self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
        if config.use_mask_token:
72
            self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
Lyu Han's avatar
Lyu Han committed
73
74
75
76
        else:
            self.mask_token = None
        self.patch_embeddings = InternS1VisionPatchEmbeddings(config)
        self.patch_size = config.patch_size
77
78
79
80
81
        self.image_size = (
            config.image_size
            if isinstance(config.image_size, Iterable)
            else (config.image_size, config.image_size)
        )
Lyu Han's avatar
Lyu Han committed
82
83
84
        num_patches = self.patch_embeddings.num_patches
        if config.use_absolute_position_embeddings:
            self.position_embeddings = nn.Parameter(
85
86
                torch.zeros(1, num_patches + 1, config.hidden_size)
            )
Lyu Han's avatar
Lyu Han committed
87
88
89
        else:
            self.position_embeddings = None

90
91
92
    def interpolate_pos_encoding(
        self, embeddings: torch.Tensor, height: int, width: int
    ) -> torch.Tensor:
Lyu Han's avatar
Lyu Han committed
93
94
95
96
97
98
99
100
101
102
103
104
105
106
        """
        This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
        images. This method is also adapted to support torch.jit tracing.

        Adapted from:
        - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
        - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
        """  # noqa: E501

        num_patches = embeddings.shape[1] - 1
        num_positions = self.position_embeddings.shape[1] - 1

        # always interpolate when tracing to ensure the exported model
        # works for dynamic input shapes
107
108
109
110
111
        if (
            not torch.jit.is_tracing()
            and num_patches == num_positions
            and height == width
        ):
Lyu Han's avatar
Lyu Han committed
112
113
114
115
116
117
118
119
120
121
122
            return self.position_embeddings

        class_pos_embed = self.position_embeddings[:, :1]
        patch_pos_embed = self.position_embeddings[:, 1:]

        dim = embeddings.shape[-1]

        new_height = height // self.patch_size[0]
        new_width = width // self.patch_size[1]

        sqrt_num_positions = torch_int(num_positions**0.5)
123
124
125
        patch_pos_embed = patch_pos_embed.reshape(
            1, sqrt_num_positions, sqrt_num_positions, dim
        )
Lyu Han's avatar
Lyu Han committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
        patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)

        patch_pos_embed = nn.functional.interpolate(
            patch_pos_embed,
            size=(new_height, new_width),
            mode="bicubic",
            align_corners=False,
        )

        patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)

        return torch.cat((class_pos_embed, patch_pos_embed), dim=1)

    def forward(
        self,
        pixel_values: torch.Tensor,
142
        bool_masked_pos: torch.BoolTensor | None = None,
Lyu Han's avatar
Lyu Han committed
143
144
    ) -> torch.Tensor:
        _, _, height, width = pixel_values.shape
145
        embeddings, (patch_height, patch_width) = self.patch_embeddings(pixel_values)
Lyu Han's avatar
Lyu Han committed
146
147
148
149
150
151
152
153
154
155
156
157
158
        batch_size, seq_len, _ = embeddings.size()

        if bool_masked_pos is not None:
            mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
            # replace the masked visual tokens by mask_tokens
            w = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
            embeddings = embeddings * (1 - w) + mask_tokens * w

        cls_tokens = self.cls_token.expand(batch_size, -1, -1)
        embeddings = torch.cat((cls_tokens, embeddings), dim=1)

        if self.position_embeddings is not None:
            embeddings = embeddings + self.interpolate_pos_encoding(
159
160
                embeddings, height, width
            )
Lyu Han's avatar
Lyu Han committed
161
162
163
164
165
166
167
168
169
170
171
172

        return embeddings, (patch_height, patch_width)


class InternSdpaAttention(nn.Module):
    """Multi-headed attention from 'Attention Is All You Need' paper"""

    def __init__(
        self,
        config: PretrainedConfig,
        *,
        num_dummy_heads: int = 0,
173
        prefix: str = "",
Lyu Han's avatar
Lyu Han committed
174
175
176
177
178
179
180
181
182
    ) -> None:
        super().__init__()

        self.config = config
        self.embed_dim = config.hidden_size
        self.num_heads = config.num_attention_heads
        self.head_dim = self.embed_dim // self.num_heads
        if self.head_dim * self.num_heads != self.embed_dim:
            raise ValueError(
183
184
185
186
                f"embed_dim must be divisible by num_heads "
                f"(got `embed_dim`: {self.embed_dim} and `num_heads`:"
                f" {self.num_heads})."
            )
Lyu Han's avatar
Lyu Han committed
187
188
189
190
191
192

        # Additional dummy heads are used to enable TP for common GPU counts.
        self.dummy_dim = (num_dummy_heads + self.num_heads) * self.head_dim

        self.scale = self.head_dim**-0.5

193
194
195
196
197
198
199
200
201
        self.q_proj = nn.Linear(
            self.embed_dim, self.num_heads * self.head_dim, bias=config.attention_bias
        )
        self.k_proj = nn.Linear(
            self.embed_dim, self.num_heads * self.head_dim, bias=config.attention_bias
        )
        self.v_proj = nn.Linear(
            self.embed_dim, self.num_heads * self.head_dim, bias=config.attention_bias
        )
Lyu Han's avatar
Lyu Han committed
202
203
204

        self.qk_normalization = config.use_qk_norm
        if self.qk_normalization:
205
206
207
208
209
210
211
212
213
214
            self.q_norm = RMSNorm(
                self.dummy_dim,
                eps=config.layer_norm_eps,
                var_hidden_size=self.embed_dim,
            )
            self.k_norm = RMSNorm(
                self.dummy_dim,
                eps=config.layer_norm_eps,
                var_hidden_size=self.embed_dim,
            )
Lyu Han's avatar
Lyu Han committed
215
216
217

        self.projection_layer = nn.Linear(self.dummy_dim, self.embed_dim)

218
        # Use unified MMEncoderAttention with automatic backend selection
219
220
221
222
        self.attn = MMEncoderAttention(
            self.num_heads,
            self.head_dim,
            self.scale,
223
            prefix=f"{prefix}.attn",
224
        )
225

Lyu Han's avatar
Lyu Han committed
226
    def forward(self, x: torch.Tensor) -> torch.Tensor:
227
        """x shape: (B, N, C)"""
Lyu Han's avatar
Lyu Han committed
228
229
230
231
232
233

        q = self.q_proj(x)
        k = self.k_proj(x)
        v = self.v_proj(x)

        if self.qk_normalization:
234
235
            q = self.q_norm(q)
            k = self.k_norm(k)
Lyu Han's avatar
Lyu Han committed
236

237
        # Use unified MMEncoderAttention with automatic backend selection
238
        x = self.attn(q, k, v)
Lyu Han's avatar
Lyu Han committed
239
240
241
242
243
244
245
246
247

        x = self.projection_layer(x)
        return x


class InternS1VisionMLP(nn.Module):
    def __init__(
        self,
        config: PretrainedConfig,
248
        quant_config: QuantizationConfig | None = None,
Lyu Han's avatar
Lyu Han committed
249
250
251
252
253
254
        prefix: str = "",
    ) -> None:
        super().__init__()

        self.config = config
        self.activation_fn = get_act_fn(config.hidden_act)
255
256
257
258
259
260
261
262
263
264
265
266
267
268
        self.fc1 = ColumnParallelLinear(
            config.hidden_size,
            config.intermediate_size,
            bias=True,
            quant_config=quant_config,
            prefix=f"{prefix}.fc1",
        )
        self.fc2 = RowParallelLinear(
            config.intermediate_size,
            config.hidden_size,
            bias=True,
            quant_config=quant_config,
            prefix=f"{prefix}.fc2",
        )
Lyu Han's avatar
Lyu Han committed
269
270
271
272
273
274
275
276
277
278
279
280
281

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        hidden_states, _ = self.fc1(hidden_states)
        hidden_states = self.activation_fn(hidden_states)
        hidden_states, _ = self.fc2(hidden_states)

        return hidden_states


class InternS1VisionLayer(nn.Module):
    def __init__(
        self,
        config: PretrainedConfig,
282
        quant_config: QuantizationConfig | None = None,
Lyu Han's avatar
Lyu Han committed
283
284
285
286
287
288
        *,
        num_dummy_heads: int = 0,
        prefix: str = "",
    ) -> None:
        super().__init__()

289
290
291
292
293
294
        self.attention = self._init_attn(
            config,
            quant_config,
            num_dummy_heads=num_dummy_heads,
            prefix=f"{prefix}.attention",
        )
Lyu Han's avatar
Lyu Han committed
295

296
297
298
        self.mlp = InternS1VisionMLP(
            config, quant_config=quant_config, prefix=f"{prefix}.mlp"
        )
Lyu Han's avatar
Lyu Han committed
299
        self.layernorm_before = NORM2FN[config.norm_type](
300
301
            config.hidden_size, eps=config.layer_norm_eps
        )
Lyu Han's avatar
Lyu Han committed
302
        self.layernorm_after = NORM2FN[config.norm_type](
303
304
            config.hidden_size, eps=config.layer_norm_eps
        )
Lyu Han's avatar
Lyu Han committed
305
306

        init_values = config.layer_scale_init_value
307
308
309
310
311
312
        self.lambda_1 = nn.Parameter(
            init_values * torch.ones(config.hidden_size), requires_grad=True
        )
        self.lambda_2 = nn.Parameter(
            init_values * torch.ones(config.hidden_size), requires_grad=True
        )
Lyu Han's avatar
Lyu Han committed
313
314
315
316

    def _init_attn(
        self,
        config: PretrainedConfig,
317
        quant_config: QuantizationConfig | None,
Lyu Han's avatar
Lyu Han committed
318
319
320
321
        *,
        num_dummy_heads: int,
        prefix: str = "",
    ):
322
323
324
325
326
        return InternSdpaAttention(
            config,
            num_dummy_heads=num_dummy_heads,
            prefix=prefix,
        )
Lyu Han's avatar
Lyu Han committed
327
328
329
330
331

    def forward(
        self,
        hidden_states: torch.Tensor,
    ):
332
333
334
335
        hidden_states = (
            hidden_states
            + self.attention(self.layernorm_before(hidden_states)) * self.lambda_1
        )
Lyu Han's avatar
Lyu Han committed
336

337
338
339
340
        hidden_states = (
            hidden_states
            + self.mlp(self.layernorm_after(hidden_states)) * self.lambda_2
        )
Lyu Han's avatar
Lyu Han committed
341
342
343
344
345
346
347
348

        return hidden_states


class InternS1VisionEncoder(nn.Module):
    def __init__(
        self,
        config: PretrainedConfig,
349
        quant_config: QuantizationConfig | None = None,
Lyu Han's avatar
Lyu Han committed
350
        *,
351
        num_hidden_layers_override: int | None = None,
Lyu Han's avatar
Lyu Han committed
352
353
354
355
356
357
358
359
360
361
362
363
        num_dummy_heads: int = 0,
        prefix: str = "",
    ):
        super().__init__()

        self.config = config

        if num_hidden_layers_override is None:
            num_hidden_layers = config.num_hidden_layers
        else:
            num_hidden_layers = num_hidden_layers_override

364
365
366
367
368
369
370
371
372
373
374
        self.layer = nn.ModuleList(
            [
                InternS1VisionLayer(
                    config,
                    quant_config,
                    num_dummy_heads=num_dummy_heads,
                    prefix=f"{prefix}.layer.{layer_idx}",
                )
                for layer_idx in range(num_hidden_layers)
            ]
        )
Lyu Han's avatar
Lyu Han committed
375
376
377
378
379
380
381
382
383
384
385
386
387

    def forward(self, inputs_embeds: torch.Tensor):
        hidden_states = inputs_embeds
        for encoder_layer in self.layer:
            hidden_states = encoder_layer(hidden_states)

        return hidden_states


class InternS1VisionModel(nn.Module):
    def __init__(
        self,
        config: PretrainedConfig,
388
        quant_config: QuantizationConfig | None = None,
Lyu Han's avatar
Lyu Han committed
389
        *,
390
        num_hidden_layers_override: int | None = None,
Lyu Han's avatar
Lyu Han committed
391
392
393
394
395
396
397
398
399
400
401
402
403
404
        num_dummy_heads: int = 0,
        prefix: str = "",
    ) -> None:
        super().__init__()

        self.config = config

        self.embeddings = InternS1VisionEmbeddings(config)
        self.encoder = InternS1VisionEncoder(
            config=config,
            num_hidden_layers_override=num_hidden_layers_override,
            num_dummy_heads=num_dummy_heads,
            prefix=f"{prefix}.encoder",
        )
405
406
407
408
409
        self.layernorm = (
            nn.Identity()
            if config.use_mean_pooling
            else nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        )
Lyu Han's avatar
Lyu Han committed
410
411
412
413
414
415

    def get_input_embeddings(self):
        return self.embeddings.patch_embeddings

    def forward(
        self,
416
417
        pixel_values: torch.Tensor | None = None,
        pixel_embeds: torch.Tensor | None = None,
Lyu Han's avatar
Lyu Han committed
418
419
    ) -> torch.FloatTensor:
        if pixel_values is None and pixel_embeds is None:
420
            raise ValueError("You have to specify pixel_values or pixel_embeds")
Lyu Han's avatar
Lyu Han committed
421
422
423
424
425
426
427

        if pixel_embeds is not None:
            hidden_states = pixel_embeds
        elif pixel_values is not None:
            if pixel_values.ndim == 4:
                hidden_states, _ = self.embeddings(pixel_values)
            else:
428
                raise ValueError(f"wrong pixel_values size: {pixel_values.shape}")
Lyu Han's avatar
Lyu Han committed
429
430
431
432
433
434

        encoder_outputs = self.encoder(inputs_embeds=hidden_states)
        encoder_outputs = self.layernorm(encoder_outputs)

        return encoder_outputs

435
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
Lyu Han's avatar
Lyu Han committed
436
437
438
439
        params_dict = dict(self.named_parameters())
        loaded_params: set[str] = set()
        for name, loaded_weight in weights:
            param = params_dict[name]
440
            weight_loader = getattr(param, "weight_loader", default_weight_loader)
Lyu Han's avatar
Lyu Han committed
441
442
443
            weight_loader(param, loaded_weight)
            loaded_params.add(name)
        return loaded_params