| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """Implementation of SiglipVisionModel intended to be only used |
| 4 | within a vision language model.""" |
| 5 | |
| 6 | from collections.abc import Iterable |
| 7 | |
| 8 | import torch |
| 9 | from torch import nn |
| 10 | from torch.nn import functional as F |
| 11 | from transformers import Siglip2VisionConfig |
| 12 | from transformers.configuration_utils import PreTrainedConfig |
| 13 | |
| 14 | from vllm.distributed import divide, get_tensor_model_parallel_world_size |
| 15 | from vllm.model_executor.layers.activation import get_act_fn |
| 16 | from vllm.model_executor.layers.attention import MMEncoderAttention |
| 17 | from vllm.model_executor.layers.conv import Conv2dLayer |
| 18 | from vllm.model_executor.layers.linear import ( |
| 19 | ColumnParallelLinear, |
| 20 | LinearBase, |
| 21 | QKVParallelLinear, |
| 22 | ReplicatedLinear, |
| 23 | RowParallelLinear, |
| 24 | ) |
| 25 | from vllm.model_executor.layers.quantization import QuantizationConfig |
| 26 | from vllm.model_executor.layers.rotary_embedding.common import ( |
| 27 | ApplyRotaryEmb, |
| 28 | ) |
| 29 | from vllm.platforms import current_platform |
| 30 | |
| 31 | from .utils import AutoWeightsLoader, WeightsMapper, maybe_prefix |
| 32 | from .vision import is_vit_use_data_parallel |
| 33 | |
| 34 | |
| 35 | class VisionRotaryEmbedding(nn.Module): |
| 36 | def __init__(self, dim: int, theta: float = 10000.0) -> None: |
| 37 | super().__init__() |
| 38 | inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) |
| 39 | self.register_buffer("inv_freq", inv_freq, persistent=False) |
| 40 | |
| 41 | def forward(self, seqlen: int) -> torch.Tensor: |
| 42 | seq = torch.arange( |
| 43 | seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype |
| 44 | ) |
| 45 | freqs = torch.outer(seq, self.inv_freq) |
| 46 | return freqs |
| 47 | |
| 48 | |
| 49 | class Siglip2VisionEmbeddings(nn.Module): |
| 50 | def __init__(self, config: PreTrainedConfig): |
| 51 | super().__init__() |
| 52 | self.config = config |
| 53 | self.embed_dim = config.hidden_size |
| 54 | self.patch_size = config.patch_size |
| 55 | self.image_size = config.image_size |
| 56 | self.num_patches = config.num_patches |
| 57 | self.preserve_original_pe = config.preserve_original_pe |
| 58 | self.hidden_stride = config.hidden_stride |
| 59 | |
| 60 | # siglip2 naflex |
| 61 | if self.num_patches > 0: |
| 62 | self.patch_embedding = ReplicatedLinear( |
| 63 | input_size=config.num_channels * self.patch_size * self.patch_size, |
| 64 | output_size=self.embed_dim, |
| 65 | return_bias=False, |
| 66 | ) |
| 67 | if self.preserve_original_pe: |
| 68 | self.position_embedding_size = int(self.num_patches**0.5) |
| 69 | self.position_embedding = nn.Embedding(self.num_patches, self.embed_dim) |
| 70 | |
| 71 | else: |
| 72 | self.patch_embedding = Conv2dLayer( |
| 73 | in_channels=config.num_channels, |
| 74 | out_channels=self.embed_dim, |
| 75 | kernel_size=self.patch_size, |
| 76 | stride=self.patch_size, |
| 77 | padding="valid", |
| 78 | ) |
| 79 | if self.preserve_original_pe: |
| 80 | self.num_patches = (self.image_size // self.patch_size) ** 2 |
| 81 | self.position_embedding_size = self.image_size // self.patch_size |
| 82 | self.position_embedding = nn.Embedding(self.num_patches, self.embed_dim) |
| 83 | |
| 84 | def forward( |
| 85 | self, |
| 86 | pixel_values: torch.FloatTensor, |
| 87 | grid_thws: torch.LongTensor | None = None, |
| 88 | ) -> torch.Tensor: |
| 89 | """Args: |
| 90 | pixel_values (`torch.FloatTensor`): |
| 91 | Pixel values of shape ( |
| 92 | num_patches, |
| 93 | num_channels * temporal_patch_size * patch_size * patch_size |
| 94 | ) |
| 95 | grid_thws: (`torch.LongTensor`): |
| 96 | grid shape (num_patches, 3) |
| 97 | |
| 98 | """ |
| 99 | # Apply patch embeddings to already patchified pixel values |
| 100 | target_dtype = self.patch_embedding.weight.dtype |
| 101 | if isinstance(self.patch_embedding, LinearBase): |
| 102 | patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) |
| 103 | elif isinstance(self.patch_embedding, Conv2dLayer): |
| 104 | pixel_values = pixel_values.view( |
| 105 | -1, |
| 106 | self.config.num_channels * self.config.temporal_patch_size, |
| 107 | self.patch_size, |
| 108 | self.patch_size, |
| 109 | ) |
| 110 | patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) |
| 111 | patch_embeds = patch_embeds.reshape(-1, self.embed_dim) |
| 112 | |
| 113 | if self.preserve_original_pe: |
| 114 | assert grid_thws is not None |
| 115 | pos_embed_new = torch.zeros_like(patch_embeds) |
| 116 | positional_embeddings = ( |
| 117 | self.position_embedding.weight.reshape( |
| 118 | self.position_embedding_size, self.position_embedding_size, -1 |
| 119 | ) |
| 120 | .unsqueeze(0) |
| 121 | .permute(0, 3, 1, 2) |
| 122 | ) |
| 123 | cnt = 0 |
| 124 | for t, h, w in grid_thws: |
| 125 | volume = t * h * w |
| 126 | pe = F.interpolate( |
| 127 | positional_embeddings, |
| 128 | size=(h, w), |
| 129 | mode="bicubic", |
| 130 | align_corners=False, |
| 131 | ) |
| 132 | pe = pe.permute(0, 2, 3, 1).reshape(1, h * w, -1) |
| 133 | pe = pe[0].repeat(t, 1) |
| 134 | pe = pe.reshape( |
| 135 | t, |
| 136 | h // self.hidden_stride, |
| 137 | self.hidden_stride, |
| 138 | w // self.hidden_stride, |
| 139 | self.hidden_stride, |
| 140 | -1, |
| 141 | ) |
| 142 | pe = pe.permute(0, 1, 3, 2, 4, 5).reshape(volume, -1) |
| 143 | pos_embed_new[cnt : cnt + volume] = pe |
| 144 | cnt += volume |
| 145 | patch_embeds = patch_embeds + pos_embed_new |
| 146 | |
| 147 | return patch_embeds |
| 148 | |
| 149 | |
| 150 | def apply_rotary_pos_emb( |
| 151 | q: torch.Tensor, |
| 152 | k: torch.Tensor, |
| 153 | cos: torch.Tensor, |
| 154 | sin: torch.Tensor, |
| 155 | is_flash_attn_backend: bool, |
| 156 | apply_rotary_emb: ApplyRotaryEmb, |
| 157 | ) -> tuple[torch.Tensor, torch.Tensor]: |
| 158 | cos = cos.chunk(2, dim=-1)[0].contiguous() |
| 159 | sin = sin.chunk(2, dim=-1)[0].contiguous() |
| 160 | |
| 161 | if is_flash_attn_backend and current_platform.is_cuda(): |
| 162 | apply_rotary_emb_func = apply_rotary_emb.forward_cuda |
| 163 | elif is_flash_attn_backend and current_platform.is_rocm(): |
| 164 | apply_rotary_emb_func = apply_rotary_emb.forward_hip |
| 165 | else: |
| 166 | apply_rotary_emb_func = apply_rotary_emb.forward_native |
| 167 | |
| 168 | q_embed = apply_rotary_emb_func(q, cos, sin) |
| 169 | k_embed = apply_rotary_emb_func(k, cos, sin) |
| 170 | |
| 171 | return q_embed, k_embed |
| 172 | |
| 173 | |
| 174 | class Siglip2Attention(nn.Module): |
| 175 | """Multi-headed attention from 'Attention Is All You Need' paper.""" |
| 176 | |
| 177 | def __init__( |
| 178 | self, |
| 179 | config: Siglip2VisionConfig, |
| 180 | quant_config: QuantizationConfig | None = None, |
| 181 | prefix: str = "", |
| 182 | ): |
| 183 | super().__init__() |
| 184 | self.config = config |
| 185 | self.embed_dim = config.hidden_size |
| 186 | self.num_heads = config.num_attention_heads |
| 187 | self.head_dim = self.embed_dim // self.num_heads |
| 188 | if self.head_dim * self.num_heads != self.embed_dim: |
| 189 | raise ValueError( |
| 190 | f"embed_dim must be divisible by num_heads " |
| 191 | f"(got `embed_dim`: {self.embed_dim} and " |
| 192 | f"`num_heads`: {self.num_heads})." |
| 193 | ) |
| 194 | self.scale = self.head_dim**-0.5 |
| 195 | self.dropout = config.attention_dropout |
| 196 | |
| 197 | use_data_parallel = is_vit_use_data_parallel() |
| 198 | self.qkv_proj = QKVParallelLinear( |
| 199 | hidden_size=self.embed_dim, |
| 200 | head_size=self.head_dim, |
| 201 | total_num_heads=self.num_heads, |
| 202 | quant_config=quant_config, |
| 203 | prefix=f"{prefix}.qkv_proj", |
| 204 | disable_tp=use_data_parallel, |
| 205 | ) |
| 206 | self.out_proj = RowParallelLinear( |
| 207 | input_size=self.embed_dim, |
| 208 | output_size=self.embed_dim, |
| 209 | quant_config=quant_config, |
| 210 | prefix=f"{prefix}.out_proj", |
| 211 | disable_tp=use_data_parallel, |
| 212 | ) |
| 213 | |
| 214 | self.tp_size = ( |
| 215 | 1 if use_data_parallel else get_tensor_model_parallel_world_size() |
| 216 | ) |
| 217 | self.num_heads_per_partition = divide(self.num_heads, self.tp_size) |
| 218 | self.use_rope = config.use_rope |
| 219 | |
| 220 | self.attn = MMEncoderAttention( |
| 221 | num_heads=self.num_heads_per_partition, |
| 222 | head_size=self.head_dim, |
| 223 | scale=self.scale, |
| 224 | prefix=f"{prefix}.attn", |
| 225 | ) |
| 226 | |
| 227 | self.apply_rotary_emb = ApplyRotaryEmb( |
| 228 | enforce_enable=True, |
| 229 | enable_fp32_compute=True, |
| 230 | ) |
| 231 | |
| 232 | def forward( |
| 233 | self, |
| 234 | hidden_states: torch.Tensor, |
| 235 | cu_seqlens: torch.Tensor, |
| 236 | position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, |
| 237 | ) -> tuple[torch.Tensor, torch.Tensor | None]: |
| 238 | """Input shape: Batch x Time x Channel.""" |
| 239 | seq_length, embed_dim = hidden_states.shape |
| 240 | |
| 241 | qkv_states, _ = self.qkv_proj(hidden_states) |
| 242 | queries, keys, values = qkv_states.chunk(3, dim=-1) |
| 243 | |
| 244 | queries = queries.view(seq_length, self.num_heads_per_partition, self.head_dim) |
| 245 | keys = keys.view(seq_length, self.num_heads_per_partition, self.head_dim) |
| 246 | values = values.view(seq_length, self.num_heads_per_partition, self.head_dim) |
| 247 | |
| 248 | if self.use_rope: |
| 249 | assert position_embeddings is not None |
| 250 | cos, sin = position_embeddings |
| 251 | queries, keys = apply_rotary_pos_emb( |
| 252 | queries.unsqueeze(0), |
| 253 | keys.unsqueeze(0), |
| 254 | cos, |
| 255 | sin, |
| 256 | self.attn.is_flash_attn_backend, |
| 257 | self.apply_rotary_emb, |
| 258 | ) |
| 259 | queries = queries.squeeze(0) |
| 260 | keys = keys.squeeze(0) |
| 261 | |
| 262 | max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max() |
| 263 | attn_output = self.attn( |
| 264 | query=queries.unsqueeze(0), |
| 265 | key=keys.unsqueeze(0), |
| 266 | value=values.unsqueeze(0), |
| 267 | cu_seqlens=cu_seqlens, |
| 268 | max_seqlen=max_seqlen, |
| 269 | ) |
| 270 | attn_output = attn_output.reshape( |
| 271 | seq_length, self.num_heads_per_partition * self.head_dim |
| 272 | ) |
| 273 | |
| 274 | attn_output, _ = self.out_proj(attn_output) |
| 275 | return attn_output |
| 276 | |
| 277 | |
| 278 | class Siglip2MLP(nn.Module): |
| 279 | def __init__( |
| 280 | self, |
| 281 | config: Siglip2VisionConfig, |
| 282 | quant_config: QuantizationConfig | None = None, |
| 283 | prefix: str = "", |
| 284 | ): |
| 285 | super().__init__() |
| 286 | self.config = config |
| 287 | use_data_parallel = is_vit_use_data_parallel() |
| 288 | self.activation_fn = get_act_fn(config.hidden_act) |
| 289 | self.fc1 = ColumnParallelLinear( |
| 290 | config.hidden_size, |
| 291 | config.intermediate_size, |
| 292 | quant_config=quant_config, |
| 293 | prefix=f"{prefix}.fc1", |
| 294 | disable_tp=use_data_parallel, |
| 295 | ) |
| 296 | self.fc2 = RowParallelLinear( |
| 297 | config.intermediate_size, |
| 298 | config.hidden_size, |
| 299 | quant_config=quant_config, |
| 300 | prefix=f"{prefix}.fc2", |
| 301 | disable_tp=use_data_parallel, |
| 302 | ) |
| 303 | |
| 304 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 305 | hidden_states, _ = self.fc1(hidden_states) |
| 306 | hidden_states = self.activation_fn(hidden_states) |
| 307 | hidden_states, _ = self.fc2(hidden_states) |
| 308 | return hidden_states |
| 309 | |
| 310 | |
| 311 | class Siglip2EncoderLayer(nn.Module): |
| 312 | def __init__( |
| 313 | self, |
| 314 | config: Siglip2VisionConfig, |
| 315 | quant_config: QuantizationConfig | None = None, |
| 316 | prefix: str = "", |
| 317 | ): |
| 318 | super().__init__() |
| 319 | self.embed_dim = config.hidden_size |
| 320 | self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) |
| 321 | self.self_attn = Siglip2Attention( |
| 322 | config, |
| 323 | quant_config=quant_config, |
| 324 | prefix=f"{prefix}.self_attn", |
| 325 | ) |
| 326 | self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) |
| 327 | self.mlp = Siglip2MLP( |
| 328 | config, |
| 329 | quant_config=quant_config, |
| 330 | prefix=f"{prefix}.mlp", |
| 331 | ) |
| 332 | |
| 333 | def forward( |
| 334 | self, |
| 335 | hidden_states: torch.Tensor, |
| 336 | cu_seqlens: torch.Tensor, |
| 337 | position_embeddings: torch.Tensor, |
| 338 | ) -> tuple[torch.FloatTensor]: |
| 339 | """Args: |
| 340 | hidden_states: Input tensor of shape (batch, seq_len, embed_dim). |
| 341 | cu_seqlens: Cumulative sequence lengths tensor. |
| 342 | position_embeddings: Position embeddings tensor. |
| 343 | |
| 344 | """ |
| 345 | residual = hidden_states |
| 346 | |
| 347 | hidden_states = self.layer_norm1(hidden_states) |
| 348 | hidden_states = self.self_attn( |
| 349 | hidden_states=hidden_states, |
| 350 | cu_seqlens=cu_seqlens, |
| 351 | position_embeddings=position_embeddings, |
| 352 | ) |
| 353 | hidden_states = residual + hidden_states |
| 354 | |
| 355 | residual = hidden_states |
| 356 | hidden_states = self.layer_norm2(hidden_states) |
| 357 | hidden_states = self.mlp(hidden_states) |
| 358 | hidden_states = residual + hidden_states |
| 359 | return hidden_states |
| 360 | |
| 361 | |
| 362 | class Siglip2Encoder(nn.Module): |
| 363 | """Transformer encoder consisting of `config.num_hidden_layers` |
| 364 | self attention layers. Each layer is a [`Siglip2EncoderLayer`]. |
| 365 | |
| 366 | Args: |
| 367 | config: PreTrainedConfig |
| 368 | |
| 369 | """ |
| 370 | |
| 371 | def __init__( |
| 372 | self, |
| 373 | config: Siglip2VisionConfig, |
| 374 | quant_config: QuantizationConfig | None = None, |
| 375 | prefix: str = "", |
| 376 | ): |
| 377 | super().__init__() |
| 378 | self.config = config |
| 379 | self.layers = nn.ModuleList( |
| 380 | [ |
| 381 | Siglip2EncoderLayer( |
| 382 | config, |
| 383 | quant_config=quant_config, |
| 384 | prefix=f"{prefix}.layers.{idx}", |
| 385 | ) |
| 386 | for idx in range(config.num_hidden_layers) |
| 387 | ] |
| 388 | ) |
| 389 | |
| 390 | self.rotary_pos_emb = VisionRotaryEmbedding( |
| 391 | config.hidden_size // config.num_attention_heads // 2 |
| 392 | ) |
| 393 | self.patch_size = config.patch_size |
| 394 | self.hidden_stride = config.hidden_stride |
| 395 | self.window_size = config.window_size |
| 396 | self.spatial_merge_unit = config.hidden_stride * config.hidden_stride |
| 397 | if config.fullatt_block_indexes is None: |
| 398 | self.fullatt_block_indexes = None |
| 399 | else: |
| 400 | self.fullatt_block_indexes = [ |
| 401 | int(i) for i in config.fullatt_block_indexes.split("|") |
| 402 | ] |
| 403 | |
| 404 | # copied from qwen2.5_vl |
| 405 | def rot_pos_emb(self, grid_thw): |
| 406 | pos_ids = [] |
| 407 | for t, h, w in grid_thw: |
| 408 | hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w) |
| 409 | hpos_ids = hpos_ids.reshape( |
| 410 | h // self.hidden_stride, |
| 411 | self.hidden_stride, |
| 412 | w // self.hidden_stride, |
| 413 | self.hidden_stride, |
| 414 | ) |
| 415 | hpos_ids = hpos_ids.permute(0, 2, 1, 3) |
| 416 | hpos_ids = hpos_ids.flatten() |
| 417 | |
| 418 | wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1) |
| 419 | wpos_ids = wpos_ids.reshape( |
| 420 | h // self.hidden_stride, |
| 421 | self.hidden_stride, |
| 422 | w // self.hidden_stride, |
| 423 | self.hidden_stride, |
| 424 | ) |
| 425 | wpos_ids = wpos_ids.permute(0, 2, 1, 3) |
| 426 | wpos_ids = wpos_ids.flatten() |
| 427 | pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1)) |
| 428 | pos_ids = torch.cat(pos_ids, dim=0) |
| 429 | max_grid_size = grid_thw[:, 1:].max() |
| 430 | rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size) |
| 431 | rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1) |
| 432 | return rotary_pos_emb |
| 433 | |
| 434 | def get_window_index(self, grid_thw): |
| 435 | window_index: list = [] |
| 436 | cu_window_seqlens: list = [0] |
| 437 | window_index_id = 0 |
| 438 | # patch (after merge) number in each window |
| 439 | vit_merger_window_size = ( |
| 440 | self.window_size // self.hidden_stride // self.patch_size |
| 441 | ) |
| 442 | |
| 443 | for grid_t, grid_h, grid_w in grid_thw: |
| 444 | llm_grid_h, llm_grid_w = ( |
| 445 | grid_h // self.hidden_stride, # number of patch after merge |
| 446 | grid_w // self.hidden_stride, |
| 447 | ) |
| 448 | index = torch.arange(grid_t * llm_grid_h * llm_grid_w).reshape( |
| 449 | grid_t, llm_grid_h, llm_grid_w |
| 450 | ) |
| 451 | pad_h = vit_merger_window_size - llm_grid_h % vit_merger_window_size |
| 452 | pad_w = vit_merger_window_size - llm_grid_w % vit_merger_window_size |
| 453 | num_windows_h = (llm_grid_h + pad_h) // vit_merger_window_size |
| 454 | num_windows_w = (llm_grid_w + pad_w) // vit_merger_window_size |
| 455 | index_padded = F.pad(index, (0, pad_w, 0, pad_h), "constant", -100) |
| 456 | index_padded = index_padded.reshape( |
| 457 | grid_t, |
| 458 | num_windows_h, |
| 459 | vit_merger_window_size, |
| 460 | num_windows_w, |
| 461 | vit_merger_window_size, |
| 462 | ) |
| 463 | index_padded = index_padded.permute(0, 1, 3, 2, 4).reshape( |
| 464 | grid_t, |
| 465 | num_windows_h * num_windows_w, |
| 466 | vit_merger_window_size, |
| 467 | vit_merger_window_size, |
| 468 | ) |
| 469 | seqlens = (index_padded != -100).sum([2, 3]).reshape(-1) |
| 470 | index_padded = index_padded.reshape(-1) |
| 471 | index_new = index_padded[index_padded != -100] |
| 472 | window_index.append(index_new + window_index_id) |
| 473 | cu_seqlens_tmp = ( |
| 474 | seqlens.cumsum(0) * self.spatial_merge_unit + cu_window_seqlens[-1] |
| 475 | ) |
| 476 | cu_window_seqlens.extend(cu_seqlens_tmp.tolist()) |
| 477 | window_index_id += (grid_t * llm_grid_h * llm_grid_w).item() |
| 478 | window_index = torch.cat(window_index, dim=0) |
| 479 | |
| 480 | return window_index, cu_window_seqlens |
| 481 | |
| 482 | def forward( |
| 483 | self, |
| 484 | inputs_embeds: torch.Tensor, |
| 485 | grid_thws: torch.Tensor, |
| 486 | ) -> torch.Tensor: |
| 487 | r"""Args: |
| 488 | inputs_embeds: Input tensor of shape |
| 489 | (batch_size, sequence_length, hidden_size). |
| 490 | Embedded representation of the input tokens. |
| 491 | grid_thws: Grid tensor of shape (num_patches, 3) |
| 492 | containing grid dimensions. |
| 493 | Whether or not to return a [`~utils.ModelOutput`] instead of |
| 494 | a plain tuple. |
| 495 | |
| 496 | """ |
| 497 | rotary_pos_emb = self.rot_pos_emb(grid_thws) |
| 498 | window_index, cu_window_seqlens = self.get_window_index(grid_thws) |
| 499 | cu_window_seqlens = torch.tensor( |
| 500 | cu_window_seqlens, |
| 501 | device=inputs_embeds.device, |
| 502 | dtype=grid_thws.dtype if torch.jit.is_tracing() else torch.int32, |
| 503 | ) |
| 504 | cu_window_seqlens = torch.unique_consecutive(cu_window_seqlens) |
| 505 | |
| 506 | seq_len, _ = inputs_embeds.size() |
| 507 | inputs_embeds = inputs_embeds.reshape( |
| 508 | seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1 |
| 509 | ) |
| 510 | inputs_embeds = inputs_embeds[window_index, :, :] |
| 511 | inputs_embeds = inputs_embeds.reshape(seq_len, -1) |
| 512 | rotary_pos_emb = rotary_pos_emb.reshape( |
| 513 | seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1 |
| 514 | ) |
| 515 | rotary_pos_emb = rotary_pos_emb[window_index, :, :] |
| 516 | rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) |
| 517 | emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) |
| 518 | position_embeddings = (emb.cos(), emb.sin()) |
| 519 | |
| 520 | cu_seqlens = torch.repeat_interleave( |
| 521 | grid_thws[:, 1] * grid_thws[:, 2], grid_thws[:, 0] |
| 522 | ).cumsum( |
| 523 | dim=0, |
| 524 | # Select dtype based on the following factors: |
| 525 | # - FA2 requires that cu_seqlens_q must have dtype int32 |
| 526 | # - torch.onnx.export requires that cu_seqlens_q must have |
| 527 | # same dtype as grid_thw |
| 528 | # See https://github.com/huggingface/transformers/pull/34852 |
| 529 | # for more information |
| 530 | dtype=grid_thws.dtype if torch.jit.is_tracing() else torch.int32, |
| 531 | ) |
| 532 | cu_seqlens = torch.cat([cu_seqlens.new_zeros(1), cu_seqlens]) |
| 533 | |
| 534 | reverse_indices = torch.argsort(window_index) |
| 535 | |
| 536 | hidden_states = inputs_embeds |
| 537 | for index, block in enumerate(self.layers): |
| 538 | if not self.fullatt_block_indexes or index in self.fullatt_block_indexes: |
| 539 | cu_seqlens_tmp = cu_seqlens |
| 540 | else: |
| 541 | cu_seqlens_tmp = cu_window_seqlens |
| 542 | hidden_states = block(hidden_states, cu_seqlens_tmp, position_embeddings) |
| 543 | |
| 544 | hidden_states = hidden_states.reshape( |
| 545 | seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1 |
| 546 | ) |
| 547 | hidden_states = hidden_states[reverse_indices, :].reshape(seq_len, -1) |
| 548 | |
| 549 | return hidden_states |
| 550 | |
| 551 | |
| 552 | class Siglip2VisionTransformer(nn.Module): |
| 553 | def __init__( |
| 554 | self, |
| 555 | config: Siglip2VisionConfig, |
| 556 | quant_config: QuantizationConfig | None = None, |
| 557 | prefix: str = "", |
| 558 | ): |
| 559 | super().__init__() |
| 560 | self.config = config |
| 561 | embed_dim = config.hidden_size |
| 562 | |
| 563 | self.embeddings = Siglip2VisionEmbeddings(config) |
| 564 | self.encoder = Siglip2Encoder( |
| 565 | config, |
| 566 | quant_config=quant_config, |
| 567 | prefix=f"{prefix}.encoder", |
| 568 | ) |
| 569 | self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) |
| 570 | |
| 571 | def forward( |
| 572 | self, |
| 573 | pixel_values: torch.FloatTensor, |
| 574 | grid_thws: torch.LongTensor, |
| 575 | ) -> torch.Tensor: |
| 576 | r"""spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`): |
| 577 | Tensor containing the spatial dimensions (height, width) |
| 578 | of the input images. |
| 579 | """ |
| 580 | hidden_states = self.embeddings(pixel_values, grid_thws) |
| 581 | |
| 582 | last_hidden_state = self.encoder(hidden_states, grid_thws) |
| 583 | |
| 584 | return last_hidden_state |
| 585 | |
| 586 | |
| 587 | class Siglip2NavitModel(torch.nn.Module): |
| 588 | hf_to_vllm_mapper = WeightsMapper( |
| 589 | orig_to_new_stacked={ |
| 590 | ".q_proj": (".qkv_proj", "q"), |
| 591 | ".k_proj": (".qkv_proj", "k"), |
| 592 | ".v_proj": (".qkv_proj", "v"), |
| 593 | } |
| 594 | ) |
| 595 | |
| 596 | def __init__( |
| 597 | self, |
| 598 | config: Siglip2VisionConfig, |
| 599 | quant_config: QuantizationConfig | None = None, |
| 600 | prefix: str = "", |
| 601 | ): |
| 602 | super().__init__() |
| 603 | |
| 604 | self.vision_model = Siglip2VisionTransformer( |
| 605 | config, |
| 606 | quant_config=quant_config, |
| 607 | prefix=maybe_prefix(prefix, "vision_model"), |
| 608 | ) |
| 609 | |
| 610 | def forward( |
| 611 | self, |
| 612 | pixel_values: torch.FloatTensor, |
| 613 | grid_thws: torch.LongTensor, |
| 614 | ) -> torch.Tensor: |
| 615 | return self.vision_model( |
| 616 | pixel_values=pixel_values, |
| 617 | grid_thws=grid_thws, |
| 618 | ) |
| 619 | |
| 620 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 621 | loader = AutoWeightsLoader(self) |
| 622 | return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) |