| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """Minimal implementation of BlipVisionModel intended to be only used |
| 4 | within a vision language model.""" |
| 5 | |
| 6 | from collections.abc import Iterable |
| 7 | |
| 8 | import torch |
| 9 | import torch.nn as nn |
| 10 | from transformers import Blip2VisionConfig, BlipVisionConfig |
| 11 | |
| 12 | from vllm.distributed import divide, get_tensor_model_parallel_world_size |
| 13 | from vllm.model_executor.layers.activation import get_act_fn |
| 14 | from vllm.model_executor.layers.attention import MMEncoderAttention |
| 15 | from vllm.model_executor.layers.conv import Conv2dLayer |
| 16 | from vllm.model_executor.layers.linear import ( |
| 17 | ColumnParallelLinear, |
| 18 | QKVParallelLinear, |
| 19 | RowParallelLinear, |
| 20 | ) |
| 21 | from vllm.model_executor.layers.quantization import QuantizationConfig |
| 22 | |
| 23 | from .interfaces import SupportsQuant |
| 24 | from .utils import AutoWeightsLoader, WeightsMapper |
| 25 | |
| 26 | |
| 27 | def get_blip_patch_grid_length(*, image_size: int, patch_size: int) -> int: |
| 28 | assert image_size % patch_size == 0 |
| 29 | return image_size // patch_size |
| 30 | |
| 31 | |
| 32 | def get_blip_num_patches(*, image_size: int, patch_size: int) -> int: |
| 33 | grid_length = get_blip_patch_grid_length( |
| 34 | image_size=image_size, patch_size=patch_size |
| 35 | ) |
| 36 | return grid_length * grid_length |
| 37 | |
| 38 | |
| 39 | # Adapted from https://github.com/huggingface/transformers/blob/v4.39.0/src/transformers/models/blip/modeling_blip.py#L164 # noqa |
| 40 | class BlipVisionEmbeddings(nn.Module): |
| 41 | def __init__(self, config: BlipVisionConfig | Blip2VisionConfig): |
| 42 | super().__init__() |
| 43 | |
| 44 | self.config = config |
| 45 | self.embed_dim = config.hidden_size |
| 46 | self.image_size = config.image_size |
| 47 | self.patch_size = config.patch_size |
| 48 | |
| 49 | self.class_embedding = nn.Parameter(torch.randn(1, 1, self.embed_dim)) |
| 50 | |
| 51 | self.patch_embedding = Conv2dLayer( |
| 52 | in_channels=3, |
| 53 | out_channels=self.embed_dim, |
| 54 | kernel_size=self.patch_size, |
| 55 | stride=self.patch_size, |
| 56 | ) |
| 57 | |
| 58 | self.num_patches = get_blip_num_patches( |
| 59 | image_size=self.image_size, patch_size=self.patch_size |
| 60 | ) |
| 61 | self.num_positions = self.num_patches + 1 |
| 62 | |
| 63 | self.position_embedding = nn.Parameter( |
| 64 | torch.randn(1, self.num_positions, self.embed_dim) |
| 65 | ) |
| 66 | |
| 67 | def forward(self, pixel_values: torch.Tensor) -> torch.Tensor: |
| 68 | batch_size = pixel_values.shape[0] |
| 69 | target_dtype = self.patch_embedding.weight.dtype |
| 70 | patch_embeds = self.patch_embedding( |
| 71 | pixel_values.to(dtype=target_dtype) |
| 72 | ) # shape = [*, width, grid, grid] |
| 73 | patch_embeds = patch_embeds.flatten(2).transpose(1, 2) |
| 74 | |
| 75 | class_embeds = self.class_embedding.expand(batch_size, 1, -1) |
| 76 | embeddings = torch.cat([class_embeds, patch_embeds], dim=1) |
| 77 | |
| 78 | position_embeds = self.position_embedding.to(target_dtype) |
| 79 | embeddings = embeddings + position_embeds[:, : embeddings.size(1), :] |
| 80 | |
| 81 | return embeddings |
| 82 | |
| 83 | |
| 84 | class BlipAttention(nn.Module): |
| 85 | """Multi-headed attention from 'Attention Is All You Need' paper.""" |
| 86 | |
| 87 | def __init__( |
| 88 | self, |
| 89 | config: BlipVisionConfig | Blip2VisionConfig, |
| 90 | quant_config: QuantizationConfig | None = None, |
| 91 | prefix: str = "", |
| 92 | ) -> None: |
| 93 | super().__init__() |
| 94 | self.config = config |
| 95 | self.embed_dim = config.hidden_size |
| 96 | self.num_heads = config.num_attention_heads |
| 97 | self.head_dim = self.embed_dim // self.num_heads |
| 98 | if self.head_dim * self.num_heads != self.embed_dim: |
| 99 | raise ValueError( |
| 100 | "embed_dim must be divisible by num_heads " |
| 101 | f"(got `embed_dim`: {self.embed_dim} and `num_heads`:" |
| 102 | f" {self.num_heads})." |
| 103 | ) |
| 104 | self.scale = self.head_dim**-0.5 |
| 105 | self.dropout = config.attention_dropout |
| 106 | |
| 107 | self.qkv = QKVParallelLinear( |
| 108 | self.embed_dim, |
| 109 | self.head_dim, |
| 110 | self.num_heads, |
| 111 | bias=config.qkv_bias, |
| 112 | quant_config=quant_config, |
| 113 | prefix=f"{prefix}.qkv", |
| 114 | ) |
| 115 | self.projection = RowParallelLinear( |
| 116 | self.embed_dim, |
| 117 | self.embed_dim, |
| 118 | quant_config=quant_config, |
| 119 | prefix=f"{prefix}.projection", |
| 120 | ) |
| 121 | |
| 122 | self.tp_size = get_tensor_model_parallel_world_size() |
| 123 | self.num_heads_per_partition = divide(self.num_heads, self.tp_size) |
| 124 | |
| 125 | self.attn = MMEncoderAttention( |
| 126 | self.num_heads_per_partition, |
| 127 | self.head_dim, |
| 128 | self.scale, |
| 129 | prefix=f"{prefix}.attn", |
| 130 | ) |
| 131 | |
| 132 | def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): |
| 133 | return ( |
| 134 | tensor.view(bsz, seq_len, self.num_heads, self.head_dim) |
| 135 | .transpose(1, 2) |
| 136 | .contiguous() |
| 137 | ) |
| 138 | |
| 139 | def forward( |
| 140 | self, |
| 141 | hidden_states: torch.Tensor, |
| 142 | ): |
| 143 | """Input shape: Batch x Time x Channel.""" |
| 144 | qkv_states, _ = self.qkv(hidden_states) |
| 145 | query_states, key_states, value_states = qkv_states.chunk(3, dim=-1) |
| 146 | out = self.attn(query_states, key_states, value_states) |
| 147 | attn_output, _ = self.projection(out) |
| 148 | |
| 149 | return attn_output, None |
| 150 | |
| 151 | |
| 152 | class BlipMLP(nn.Module): |
| 153 | def __init__( |
| 154 | self, |
| 155 | config: BlipVisionConfig, |
| 156 | quant_config: QuantizationConfig | None = None, |
| 157 | prefix: str = "", |
| 158 | ) -> None: |
| 159 | super().__init__() |
| 160 | |
| 161 | self.config = config |
| 162 | |
| 163 | self.activation_fn = get_act_fn(config.hidden_act) |
| 164 | self.fc1 = ColumnParallelLinear( |
| 165 | config.hidden_size, |
| 166 | config.intermediate_size, |
| 167 | bias=True, |
| 168 | quant_config=quant_config, |
| 169 | prefix=f"{prefix}.fc1", |
| 170 | ) |
| 171 | self.fc2 = RowParallelLinear( |
| 172 | config.intermediate_size, |
| 173 | config.hidden_size, |
| 174 | bias=True, |
| 175 | quant_config=quant_config, |
| 176 | prefix=f"{prefix}.fc2", |
| 177 | ) |
| 178 | |
| 179 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 180 | hidden_states, _ = self.fc1(hidden_states) |
| 181 | hidden_states = self.activation_fn(hidden_states) |
| 182 | hidden_states, _ = self.fc2(hidden_states) |
| 183 | |
| 184 | return hidden_states |
| 185 | |
| 186 | |
| 187 | class BlipEncoderLayer(nn.Module): |
| 188 | def __init__( |
| 189 | self, |
| 190 | config: BlipVisionConfig, |
| 191 | quant_config: QuantizationConfig | None = None, |
| 192 | prefix: str = "", |
| 193 | ) -> None: |
| 194 | super().__init__() |
| 195 | |
| 196 | # fallback to sdpa attention if tp unavailable |
| 197 | self.self_attn = BlipAttention( |
| 198 | config, |
| 199 | quant_config=quant_config, |
| 200 | prefix=f"{prefix}.self_attn", |
| 201 | ) |
| 202 | self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) |
| 203 | self.mlp = BlipMLP(config, quant_config=quant_config, prefix=f"{prefix}.mlp") |
| 204 | self.layer_norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) |
| 205 | |
| 206 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 207 | residual = hidden_states |
| 208 | |
| 209 | hidden_states = self.layer_norm1(hidden_states) |
| 210 | hidden_states, _ = self.self_attn(hidden_states=hidden_states) |
| 211 | hidden_states = residual + hidden_states |
| 212 | |
| 213 | residual = hidden_states |
| 214 | hidden_states = self.layer_norm2(hidden_states) |
| 215 | hidden_states = self.mlp(hidden_states) |
| 216 | hidden_states = residual + hidden_states |
| 217 | |
| 218 | return hidden_states |
| 219 | |
| 220 | |
| 221 | class BlipEncoder(nn.Module): |
| 222 | """Transformer encoder consisting of `config.num_hidden_layers` self |
| 223 | attention layers. Each layer is a [`BlipEncoderLayer`]. |
| 224 | |
| 225 | Args: |
| 226 | config: BlipConfig |
| 227 | |
| 228 | """ |
| 229 | |
| 230 | def __init__( |
| 231 | self, |
| 232 | config: BlipVisionConfig, |
| 233 | quant_config: QuantizationConfig | None = None, |
| 234 | num_hidden_layers_override: int | None = None, |
| 235 | prefix: str = "", |
| 236 | ) -> None: |
| 237 | super().__init__() |
| 238 | |
| 239 | self.config = config |
| 240 | |
| 241 | if num_hidden_layers_override is None: |
| 242 | num_hidden_layers = config.num_hidden_layers |
| 243 | else: |
| 244 | num_hidden_layers = num_hidden_layers_override |
| 245 | |
| 246 | self.layers = nn.ModuleList( |
| 247 | [ |
| 248 | BlipEncoderLayer( |
| 249 | config=config, |
| 250 | quant_config=quant_config, |
| 251 | prefix=f"{prefix}.layers.{layer_idx}", |
| 252 | ) |
| 253 | for layer_idx in range(num_hidden_layers) |
| 254 | ] |
| 255 | ) |
| 256 | |
| 257 | def forward(self, inputs_embeds: torch.Tensor): |
| 258 | hidden_states = inputs_embeds |
| 259 | for encoder_layer in self.layers: |
| 260 | hidden_states = encoder_layer(hidden_states) |
| 261 | |
| 262 | return hidden_states |
| 263 | |
| 264 | |
| 265 | class BlipVisionModel(nn.Module, SupportsQuant): |
| 266 | config_class = BlipVisionConfig |
| 267 | main_input_name = "pixel_values" |
| 268 | packed_modules_mapping = {"qkv_proj": ["q_proj", "k_proj", "v_proj"]} |
| 269 | |
| 270 | hf_to_vllm_mapper = WeightsMapper( |
| 271 | orig_to_new_stacked={ |
| 272 | ".q_proj": (".qkv", "q"), |
| 273 | ".k_proj": (".qkv", "k"), |
| 274 | ".v_proj": (".qkv", "v"), |
| 275 | } |
| 276 | ) |
| 277 | |
| 278 | def __init__( |
| 279 | self, |
| 280 | config: BlipVisionConfig, |
| 281 | quant_config: QuantizationConfig | None = None, |
| 282 | *, |
| 283 | num_hidden_layers_override: int | None = None, |
| 284 | require_post_norm: bool | None = None, |
| 285 | prefix: str = "", |
| 286 | ) -> None: |
| 287 | super().__init__() |
| 288 | self.config = config |
| 289 | |
| 290 | self.embeddings = BlipVisionEmbeddings(config) |
| 291 | self.encoder = BlipEncoder( |
| 292 | config=config, |
| 293 | quant_config=quant_config, |
| 294 | num_hidden_layers_override=num_hidden_layers_override, |
| 295 | prefix=f"{prefix}.encoder", |
| 296 | ) |
| 297 | |
| 298 | num_hidden_layers = config.num_hidden_layers |
| 299 | if len(self.encoder.layers) > config.num_hidden_layers: |
| 300 | raise ValueError( |
| 301 | f"The original encoder only has {num_hidden_layers} " |
| 302 | f"layers, but you requested {len(self.encoder.layers)} layers." |
| 303 | ) |
| 304 | |
| 305 | # If possible, skip post_layernorm to conserve memory |
| 306 | if require_post_norm is None: |
| 307 | require_post_norm = len(self.encoder.layers) == num_hidden_layers |
| 308 | |
| 309 | if require_post_norm: |
| 310 | self.post_layernorm = nn.LayerNorm( |
| 311 | config.hidden_size, eps=config.layer_norm_eps |
| 312 | ) |
| 313 | else: |
| 314 | self.post_layernorm = None |
| 315 | self.hf_to_vllm_mapper = self.hf_to_vllm_mapper | WeightsMapper( |
| 316 | orig_to_new_prefix={"post_layernorm.": None} |
| 317 | ) |
| 318 | |
| 319 | def forward(self, pixel_values: torch.Tensor) -> torch.Tensor: |
| 320 | hidden_states = self.embeddings(pixel_values) |
| 321 | hidden_states = self.encoder(inputs_embeds=hidden_states) |
| 322 | |
| 323 | if self.post_layernorm is None: |
| 324 | return hidden_states |
| 325 | |
| 326 | return self.post_layernorm(hidden_states) |
| 327 | |
| 328 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 329 | loader = AutoWeightsLoader(self) |
| 330 | |
| 331 | # omit layers when num_hidden_layers_override is set |
| 332 | def _filter(ws): |
| 333 | for name, weight in ws: |
| 334 | if name.startswith("encoder.layers.") and int( |
| 335 | name.split(".")[2] |
| 336 | ) >= len(self.encoder.layers): |
| 337 | continue |
| 338 | yield name, weight |
| 339 | |
| 340 | return loader.load_weights(_filter(weights), mapper=self.hf_to_vllm_mapper) |