| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """GLM-5.3-Flash vision tower and multimodal processor.""" |
| 4 | |
| 5 | import math |
| 6 | from collections.abc import Mapping |
| 7 | from functools import partial |
| 8 | from typing import Any |
| 9 | |
| 10 | import numpy as np |
| 11 | import torch |
| 12 | import torch.nn as nn |
| 13 | from einops import rearrange |
| 14 | from transformers.video_utils import VideoMetadata |
| 15 | |
| 16 | from vllm.distributed import ( |
| 17 | get_tensor_model_parallel_world_size, |
| 18 | parallel_state, |
| 19 | ) |
| 20 | from vllm.distributed import utils as dist_utils |
| 21 | from vllm.model_executor.layers.activation import SiluAndMulWithClamp |
| 22 | from vllm.model_executor.layers.attention import MMEncoderAttention |
| 23 | from vllm.model_executor.layers.conv import Conv2dLayer, Conv3dLayer |
| 24 | from vllm.model_executor.layers.fusion.mm_input_norm import IdentityInputNorm |
| 25 | from vllm.model_executor.layers.layernorm import RMSNorm |
| 26 | from vllm.model_executor.layers.linear import ( |
| 27 | ColumnParallelLinear, |
| 28 | MergedColumnParallelLinear, |
| 29 | QKVParallelLinear, |
| 30 | RowParallelLinear, |
| 31 | ) |
| 32 | from vllm.model_executor.layers.quantization import QuantizationConfig |
| 33 | from vllm.model_executor.layers.rotary_embedding import get_rope |
| 34 | from vllm.model_executor.layers.rotary_embedding.common import ApplyRotaryEmb |
| 35 | from vllm.model_executor.models.glm4_1v import ( |
| 36 | Glm4vMultiModalProcessor, |
| 37 | Glm4vProcessingInfo, |
| 38 | ) |
| 39 | from vllm.model_executor.models.utils import ( |
| 40 | AutoWeightsLoader, |
| 41 | WeightsMapper, |
| 42 | ) |
| 43 | from vllm.model_executor.models.vision import ( |
| 44 | get_vit_attn_backend, |
| 45 | is_vit_use_data_parallel, |
| 46 | ) |
| 47 | from vllm.models.common.ops import fused_q_kv_rmsnorm |
| 48 | from vllm.multimodal.parse import ImageSize, MultiModalDataItems |
| 49 | from vllm.v1.attention.backends.registry import AttentionBackendEnum |
| 50 | |
| 51 | |
| 52 | class Glm5NextVisionPatchEmbed(nn.Module): |
| 53 | def __init__( |
| 54 | self, |
| 55 | patch_size: int = 14, |
| 56 | temporal_patch_size: int = 1, |
| 57 | in_channels: int = 3, |
| 58 | hidden_size: int = 1536, |
| 59 | ) -> None: |
| 60 | super().__init__() |
| 61 | self.patch_size = patch_size |
| 62 | self.temporal_patch_size = temporal_patch_size |
| 63 | self.hidden_size = hidden_size |
| 64 | |
| 65 | kernel_size = (temporal_patch_size, patch_size, patch_size) |
| 66 | self.proj = Conv3dLayer( |
| 67 | in_channels, |
| 68 | hidden_size, |
| 69 | kernel_size=kernel_size, |
| 70 | stride=kernel_size, |
| 71 | bias=True, |
| 72 | ) |
| 73 | |
| 74 | def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 75 | L, C = x.shape |
| 76 | x = x.view(L, -1, self.temporal_patch_size, self.patch_size, self.patch_size) |
| 77 | x = self.proj(x).view(L, self.hidden_size) |
| 78 | return x |
| 79 | |
| 80 | |
| 81 | class Glm5NextVisionMLP(nn.Module): |
| 82 | def __init__( |
| 83 | self, |
| 84 | in_features: int, |
| 85 | hidden_features: int, |
| 86 | swiglu_limit: float, |
| 87 | bias: bool = True, |
| 88 | quant_config: QuantizationConfig | None = None, |
| 89 | prefix: str = "", |
| 90 | ): |
| 91 | super().__init__() |
| 92 | use_data_parallel = is_vit_use_data_parallel() |
| 93 | self.gate_up_proj = MergedColumnParallelLinear( |
| 94 | input_size=in_features, |
| 95 | output_sizes=[hidden_features] * 2, |
| 96 | bias=bias, |
| 97 | quant_config=quant_config, |
| 98 | prefix=f"{prefix}.gate_up_proj", |
| 99 | disable_tp=use_data_parallel, |
| 100 | ) |
| 101 | self.down_proj = RowParallelLinear( |
| 102 | hidden_features, |
| 103 | in_features, |
| 104 | bias=bias, |
| 105 | quant_config=quant_config, |
| 106 | prefix=f"{prefix}.down_proj", |
| 107 | disable_tp=use_data_parallel, |
| 108 | ) |
| 109 | # GLM-5.3-Flash clamps the vision SwiGLU gate/up unlike GLM-OCR/GLM-4V. |
| 110 | self.act_fn = SiluAndMulWithClamp(swiglu_limit=swiglu_limit) |
| 111 | |
| 112 | def forward(self, x: torch.Tensor): |
| 113 | x, _ = self.gate_up_proj(x) |
| 114 | x = self.act_fn(x) |
| 115 | x, _ = self.down_proj(x) |
| 116 | return x |
| 117 | |
| 118 | |
| 119 | class Glm5NextVisionAttention(nn.Module): |
| 120 | def __init__( |
| 121 | self, |
| 122 | embed_dim: int, |
| 123 | num_heads: int, |
| 124 | projection_size: int, |
| 125 | quant_config: QuantizationConfig | None = None, |
| 126 | prefix: str = "", |
| 127 | ) -> None: |
| 128 | super().__init__() |
| 129 | use_data_parallel = is_vit_use_data_parallel() |
| 130 | self.tp_size = ( |
| 131 | 1 if use_data_parallel else get_tensor_model_parallel_world_size() |
| 132 | ) |
| 133 | self.tp_rank = ( |
| 134 | 0 if use_data_parallel else parallel_state.get_tensor_model_parallel_rank() |
| 135 | ) |
| 136 | self.hidden_size_per_attention_head = dist_utils.divide( |
| 137 | projection_size, num_heads |
| 138 | ) |
| 139 | self.num_attention_heads_per_partition = dist_utils.divide( |
| 140 | num_heads, self.tp_size |
| 141 | ) |
| 142 | |
| 143 | self.head_dim = embed_dim // num_heads |
| 144 | |
| 145 | # q/k norm eps hard-coded 1e-5 — distinct from block/post norm eps. |
| 146 | self.q_norm = RMSNorm(self.head_dim, eps=1e-5) |
| 147 | self.k_norm = RMSNorm(self.head_dim, eps=1e-5) |
| 148 | |
| 149 | self.qkv = QKVParallelLinear( |
| 150 | hidden_size=embed_dim, |
| 151 | head_size=self.hidden_size_per_attention_head, |
| 152 | total_num_heads=num_heads, |
| 153 | total_num_kv_heads=num_heads, |
| 154 | bias=True, |
| 155 | quant_config=quant_config, |
| 156 | prefix=f"{prefix}.qkv_proj" if quant_config else f"{prefix}.qkv", |
| 157 | disable_tp=use_data_parallel, |
| 158 | ) |
| 159 | self.proj = RowParallelLinear( |
| 160 | input_size=projection_size, |
| 161 | output_size=embed_dim, |
| 162 | quant_config=quant_config, |
| 163 | prefix=f"{prefix}.proj", |
| 164 | bias=True, |
| 165 | disable_tp=use_data_parallel, |
| 166 | ) |
| 167 | |
| 168 | self.attn = MMEncoderAttention( |
| 169 | num_heads=self.num_attention_heads_per_partition, |
| 170 | head_size=self.hidden_size_per_attention_head, |
| 171 | scale=self.hidden_size_per_attention_head**-0.5, |
| 172 | prefix=f"{prefix}.attn", |
| 173 | ) |
| 174 | self.apply_rotary_emb = ApplyRotaryEmb(enforce_enable=True) |
| 175 | |
| 176 | def split_qkv(self, qkv: torch.Tensor) -> tuple[torch.Tensor, ...]: |
| 177 | seq_len, bs, _ = qkv.shape |
| 178 | q, k, v = qkv.chunk(3, dim=2) |
| 179 | new_shape = ( |
| 180 | seq_len, |
| 181 | bs, |
| 182 | self.num_attention_heads_per_partition, |
| 183 | self.hidden_size_per_attention_head, |
| 184 | ) |
| 185 | q, k, v = (x.view(*new_shape) for x in (q, k, v)) |
| 186 | return q, k, v |
| 187 | |
| 188 | def forward( |
| 189 | self, |
| 190 | x: torch.Tensor, |
| 191 | cu_seqlens: torch.Tensor, |
| 192 | rotary_pos_emb_cos: torch.Tensor, |
| 193 | rotary_pos_emb_sin: torch.Tensor, |
| 194 | max_seqlen: torch.Tensor | None = None, |
| 195 | ) -> torch.Tensor: |
| 196 | x, _ = self.qkv(x) |
| 197 | q, k, v = self.split_qkv(x) |
| 198 | |
| 199 | # P1: fused q/k RMSNorm (two distinct weights, one launch; fp32, bit-identical). |
| 200 | q_shape, k_shape = q.shape, k.shape |
| 201 | q_flat = q.reshape(-1, self.head_dim) |
| 202 | k_flat = k.reshape(-1, self.head_dim) |
| 203 | q, k = fused_q_kv_rmsnorm( |
| 204 | q_flat, |
| 205 | k_flat, |
| 206 | self.q_norm.weight, |
| 207 | self.k_norm.weight, |
| 208 | self.q_norm.variance_epsilon, |
| 209 | ) |
| 210 | q = q.view(q_shape) |
| 211 | k = k.view(k_shape) |
| 212 | |
| 213 | q, k, v = (rearrange(t, "s b ... -> b s ...").contiguous() for t in (q, k, v)) |
| 214 | if rotary_pos_emb_cos is not None and rotary_pos_emb_sin is not None: |
| 215 | qk_concat = torch.cat([q, k], dim=0) |
| 216 | qk_rotated = self.apply_rotary_emb( |
| 217 | qk_concat, |
| 218 | rotary_pos_emb_cos, |
| 219 | rotary_pos_emb_sin, |
| 220 | ) |
| 221 | q, k = torch.chunk(qk_rotated, 2, dim=0) |
| 222 | |
| 223 | context_layer = self.attn( |
| 224 | query=q, |
| 225 | key=k, |
| 226 | value=v, |
| 227 | cu_seqlens=cu_seqlens, |
| 228 | max_seqlen=max_seqlen, |
| 229 | ) |
| 230 | context_layer = rearrange(context_layer, "b s h d -> s b (h d)").contiguous() |
| 231 | |
| 232 | output, _ = self.proj(context_layer) |
| 233 | return output |
| 234 | |
| 235 | |
| 236 | class Glm5NextVisionBlock(nn.Module): |
| 237 | def __init__( |
| 238 | self, |
| 239 | dim: int, |
| 240 | num_heads: int, |
| 241 | mlp_hidden_dim: int, |
| 242 | swiglu_limit: float, |
| 243 | norm_layer: partial[nn.Module] | None = None, |
| 244 | quant_config: QuantizationConfig | None = None, |
| 245 | prefix: str = "", |
| 246 | ) -> None: |
| 247 | super().__init__() |
| 248 | if norm_layer is None: |
| 249 | norm_layer = partial(nn.LayerNorm, eps=1e-6) |
| 250 | self.norm1 = norm_layer(dim) |
| 251 | self.norm2 = norm_layer(dim) |
| 252 | self.attn = Glm5NextVisionAttention( |
| 253 | embed_dim=dim, |
| 254 | num_heads=num_heads, |
| 255 | projection_size=dim, |
| 256 | quant_config=quant_config, |
| 257 | prefix=f"{prefix}.attn", |
| 258 | ) |
| 259 | self.mlp = Glm5NextVisionMLP( |
| 260 | dim, |
| 261 | mlp_hidden_dim, |
| 262 | swiglu_limit=swiglu_limit, |
| 263 | bias=True, |
| 264 | quant_config=quant_config, |
| 265 | prefix=f"{prefix}.mlp", |
| 266 | ) |
| 267 | |
| 268 | def forward( |
| 269 | self, |
| 270 | x: torch.Tensor, |
| 271 | cu_seqlens: torch.Tensor, |
| 272 | rotary_pos_emb_cos: torch.Tensor, |
| 273 | rotary_pos_emb_sin: torch.Tensor, |
| 274 | max_seqlen: int | None = None, |
| 275 | ) -> torch.Tensor: |
| 276 | x_attn = self.attn( |
| 277 | self.norm1(x), |
| 278 | cu_seqlens=cu_seqlens, |
| 279 | rotary_pos_emb_cos=rotary_pos_emb_cos, |
| 280 | rotary_pos_emb_sin=rotary_pos_emb_sin, |
| 281 | max_seqlen=max_seqlen, |
| 282 | ) |
| 283 | x_fused_norm, residual = self.norm2(x, residual=x_attn) |
| 284 | x = residual + self.mlp(x_fused_norm) |
| 285 | return x |
| 286 | |
| 287 | |
| 288 | class Glm5NextPatchMerger(nn.Module): |
| 289 | def __init__( |
| 290 | self, |
| 291 | d_model: int, |
| 292 | context_dim: int, |
| 293 | swiglu_limit: float, |
| 294 | quant_config: QuantizationConfig | None = None, |
| 295 | bias: bool = False, |
| 296 | prefix: str = "", |
| 297 | ) -> None: |
| 298 | super().__init__() |
| 299 | use_data_parallel = is_vit_use_data_parallel() |
| 300 | self.hidden_size = d_model |
| 301 | self.proj = ColumnParallelLinear( |
| 302 | self.hidden_size, |
| 303 | self.hidden_size, |
| 304 | bias=bias, |
| 305 | gather_output=True, |
| 306 | quant_config=quant_config, |
| 307 | prefix=f"{prefix}.proj", |
| 308 | disable_tp=use_data_parallel, |
| 309 | ) |
| 310 | self.post_projection_norm = nn.LayerNorm(self.hidden_size) |
| 311 | self.gate_up_proj = MergedColumnParallelLinear( |
| 312 | input_size=self.hidden_size, |
| 313 | output_sizes=[context_dim] * 2, |
| 314 | bias=bias, |
| 315 | quant_config=quant_config, |
| 316 | prefix=f"{prefix}.gate_up_proj", |
| 317 | disable_tp=use_data_parallel, |
| 318 | ) |
| 319 | self.down_proj = RowParallelLinear( |
| 320 | context_dim, |
| 321 | self.hidden_size, |
| 322 | bias=bias, |
| 323 | quant_config=quant_config, |
| 324 | prefix=f"{prefix}.down_proj", |
| 325 | disable_tp=use_data_parallel, |
| 326 | ) |
| 327 | # GLM-5.3-Flash also clamps the merger SwiGLU. |
| 328 | self.act_fn = SiluAndMulWithClamp(swiglu_limit=swiglu_limit) |
| 329 | self.extra_activation_func = nn.GELU() |
| 330 | |
| 331 | def forward(self, x: torch.Tensor): |
| 332 | x, _ = self.proj(x) |
| 333 | x = self.extra_activation_func(self.post_projection_norm(x)) |
| 334 | gate_up, _ = self.gate_up_proj(x) |
| 335 | x = self.act_fn(gate_up) |
| 336 | x, _ = self.down_proj(x) |
| 337 | return x |
| 338 | |
| 339 | |
| 340 | class Glm5NextVisionTransformer(nn.Module): |
| 341 | # Stacked-weight remap for the GLM-OCR/GLM-4V vision checkpoint layout. |
| 342 | hf_to_vllm_mapper = WeightsMapper( |
| 343 | orig_to_new_stacked={ |
| 344 | ".attn.q.": (".attn.qkv.", "q"), |
| 345 | ".attn.k.": (".attn.qkv.", "k"), |
| 346 | ".attn.v.": (".attn.qkv.", "v"), |
| 347 | ".gate_proj": (".gate_up_proj", 0), |
| 348 | ".up_proj": (".gate_up_proj", 1), |
| 349 | } |
| 350 | ) |
| 351 | |
| 352 | def __init__( |
| 353 | self, |
| 354 | text_config, # noqa: ANN001 |
| 355 | vision_config, |
| 356 | norm_eps: float = 1e-6, |
| 357 | quant_config: QuantizationConfig | None = None, |
| 358 | input_norm: nn.Module | None = None, |
| 359 | prefix: str = "", |
| 360 | ) -> None: |
| 361 | super().__init__() |
| 362 | use_data_parallel = is_vit_use_data_parallel() |
| 363 | self.tp_size = ( |
| 364 | 1 if use_data_parallel else get_tensor_model_parallel_world_size() |
| 365 | ) |
| 366 | |
| 367 | patch_size = vision_config.patch_size |
| 368 | temporal_patch_size = vision_config.temporal_patch_size |
| 369 | in_channels = vision_config.in_channels |
| 370 | depth = vision_config.depth |
| 371 | self.hidden_size = vision_config.hidden_size |
| 372 | self.num_heads = vision_config.num_heads |
| 373 | |
| 374 | self.patch_size = vision_config.patch_size |
| 375 | self.spatial_merge_size = vision_config.spatial_merge_size |
| 376 | self.out_hidden_size = vision_config.out_hidden_size |
| 377 | |
| 378 | swiglu_limit = vision_config.swiglu_limit |
| 379 | if swiglu_limit is None: |
| 380 | swiglu_limit = text_config.swiglu_limit |
| 381 | assert swiglu_limit is not None, ( |
| 382 | "GLM-5.3-Flash vision requires swiglu_limit (vision_config or text_config)" |
| 383 | ) |
| 384 | |
| 385 | # Single construction pass — no abs-pos embeddings / post-conv norm (OCR delta). |
| 386 | self.patch_embed = Glm5NextVisionPatchEmbed( |
| 387 | patch_size=patch_size, |
| 388 | temporal_patch_size=temporal_patch_size, |
| 389 | in_channels=in_channels, |
| 390 | hidden_size=self.hidden_size, |
| 391 | ) |
| 392 | self.input_norm = input_norm if input_norm is not None else IdentityInputNorm() |
| 393 | |
| 394 | norm_layer = partial(RMSNorm, eps=norm_eps) |
| 395 | head_dim = self.hidden_size // self.num_heads |
| 396 | self.rotary_pos_emb = get_rope( |
| 397 | head_size=head_dim, |
| 398 | max_position=8192, |
| 399 | is_neox_style=True, |
| 400 | rope_parameters={"partial_rotary_factor": 0.5}, |
| 401 | ) |
| 402 | self.blocks = nn.ModuleList( |
| 403 | [ |
| 404 | Glm5NextVisionBlock( |
| 405 | dim=self.hidden_size, |
| 406 | num_heads=self.num_heads, |
| 407 | mlp_hidden_dim=vision_config.intermediate_size, |
| 408 | swiglu_limit=swiglu_limit, |
| 409 | norm_layer=norm_layer, |
| 410 | quant_config=quant_config, |
| 411 | prefix=f"{prefix}.blocks.{layer_idx}", |
| 412 | ) |
| 413 | for layer_idx in range(depth) |
| 414 | ] |
| 415 | ) |
| 416 | # GLM-5.3-Flash merger bottleneck width. |
| 417 | self.merger = Glm5NextPatchMerger( |
| 418 | d_model=vision_config.out_hidden_size, |
| 419 | context_dim=vision_config.projection_intermediate_size, |
| 420 | swiglu_limit=swiglu_limit, |
| 421 | quant_config=quant_config, |
| 422 | bias=False, |
| 423 | prefix=f"{prefix}.merger", |
| 424 | ) |
| 425 | |
| 426 | self.downsample = Conv2dLayer( |
| 427 | in_channels=vision_config.hidden_size, |
| 428 | out_channels=vision_config.out_hidden_size, |
| 429 | kernel_size=vision_config.spatial_merge_size, |
| 430 | stride=vision_config.spatial_merge_size, |
| 431 | ) |
| 432 | self.post_layernorm = RMSNorm( |
| 433 | vision_config.hidden_size, eps=vision_config.rms_norm_eps |
| 434 | ) |
| 435 | |
| 436 | self.attn_backend = get_vit_attn_backend( |
| 437 | head_size=head_dim, |
| 438 | dtype=torch.get_default_dtype(), |
| 439 | ) |
| 440 | |
| 441 | @property |
| 442 | def dtype(self) -> torch.dtype: |
| 443 | return self.patch_embed.proj.weight.dtype |
| 444 | |
| 445 | @property |
| 446 | def device(self) -> torch.device: |
| 447 | return self.patch_embed.proj.weight.device |
| 448 | |
| 449 | def rot_pos_emb( |
| 450 | self, grid_thw: list[list[int]] |
| 451 | ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: |
| 452 | pos_ids = [] |
| 453 | for t, h, w in grid_thw: |
| 454 | hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w) |
| 455 | wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1) |
| 456 | hpos_ids = ( |
| 457 | hpos_ids.reshape( |
| 458 | h // self.spatial_merge_size, |
| 459 | self.spatial_merge_size, |
| 460 | w // self.spatial_merge_size, |
| 461 | self.spatial_merge_size, |
| 462 | ) |
| 463 | .permute(0, 2, 1, 3) |
| 464 | .flatten() |
| 465 | ) |
| 466 | wpos_ids = ( |
| 467 | wpos_ids.reshape( |
| 468 | h // self.spatial_merge_size, |
| 469 | self.spatial_merge_size, |
| 470 | w // self.spatial_merge_size, |
| 471 | self.spatial_merge_size, |
| 472 | ) |
| 473 | .permute(0, 2, 1, 3) |
| 474 | .flatten() |
| 475 | ) |
| 476 | pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1)) |
| 477 | pos_ids = torch.cat(pos_ids, dim=0) |
| 478 | max_grid_size = max(max(h, w) for _, h, w in grid_thw) |
| 479 | |
| 480 | cos, sin = self.rotary_pos_emb.get_cos_sin(max_grid_size) |
| 481 | |
| 482 | pos_ids = pos_ids.to(cos.device, non_blocking=True) |
| 483 | cos_combined = cos[pos_ids].flatten(1) |
| 484 | sin_combined = sin[pos_ids].flatten(1) |
| 485 | return cos_combined, sin_combined, pos_ids |
| 486 | |
| 487 | def compute_attn_mask_seqlen( |
| 488 | self, |
| 489 | cu_seqlens: torch.Tensor, |
| 490 | ) -> torch.Tensor | None: |
| 491 | max_seqlen = None |
| 492 | if self.attn_backend in { |
| 493 | AttentionBackendEnum.FLASH_ATTN, |
| 494 | AttentionBackendEnum.ROCM_AITER_FA, |
| 495 | AttentionBackendEnum.TRITON_ATTN, |
| 496 | }: |
| 497 | max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max() |
| 498 | return max_seqlen |
| 499 | |
| 500 | def prepare_encoder_metadata( |
| 501 | self, |
| 502 | grid_thw_list: list[list[int]], |
| 503 | *, |
| 504 | max_batch_size: int | None = None, |
| 505 | max_frames_per_batch: int | None = None, |
| 506 | max_seqlen_override: int | None = None, |
| 507 | device: torch.device | None = None, |
| 508 | ) -> dict[str, torch.Tensor | None]: |
| 509 | """Compute encoder metadata for eager and CUDA graph execution.""" |
| 510 | if device is None: |
| 511 | device = self.device |
| 512 | |
| 513 | metadata: dict[str, torch.Tensor | None] = {} |
| 514 | |
| 515 | rotary_cos, rotary_sin, _ = self.rot_pos_emb(grid_thw_list) |
| 516 | metadata["rotary_pos_emb_cos"] = rotary_cos |
| 517 | metadata["rotary_pos_emb_sin"] = rotary_sin |
| 518 | |
| 519 | grid_thw_np = np.array(grid_thw_list, dtype=np.int32) |
| 520 | patches_per_frame = grid_thw_np[:, 1] * grid_thw_np[:, 2] |
| 521 | cu_seqlens = np.repeat(patches_per_frame, grid_thw_np[:, 0]).cumsum( |
| 522 | dtype=np.int32 |
| 523 | ) |
| 524 | cu_seqlens = np.concatenate([np.zeros(1, dtype=np.int32), cu_seqlens]) |
| 525 | |
| 526 | pad_to = ( |
| 527 | max_frames_per_batch if max_frames_per_batch is not None else max_batch_size |
| 528 | ) |
| 529 | if pad_to is not None: |
| 530 | num_seqs = len(cu_seqlens) - 1 |
| 531 | if num_seqs < pad_to: |
| 532 | cu_seqlens = np.concatenate( |
| 533 | [ |
| 534 | cu_seqlens, |
| 535 | np.full( |
| 536 | pad_to - num_seqs, |
| 537 | cu_seqlens[-1], |
| 538 | dtype=np.int32, |
| 539 | ), |
| 540 | ] |
| 541 | ) |
| 542 | |
| 543 | metadata["sequence_lengths"] = MMEncoderAttention.maybe_compute_seq_lens( |
| 544 | self.attn_backend, cu_seqlens, device |
| 545 | ) |
| 546 | |
| 547 | if max_seqlen_override is not None: |
| 548 | max_seqlen_val = max_seqlen_override |
| 549 | else: |
| 550 | max_seqlen_val = MMEncoderAttention.compute_max_seqlen( |
| 551 | self.attn_backend, cu_seqlens |
| 552 | ) |
| 553 | metadata["max_seqlen"] = torch.tensor(max_seqlen_val, dtype=torch.int32) |
| 554 | |
| 555 | metadata["cu_seqlens"] = MMEncoderAttention.maybe_recompute_cu_seqlens( |
| 556 | self.attn_backend, |
| 557 | cu_seqlens, |
| 558 | self.hidden_size, |
| 559 | self.tp_size, |
| 560 | device, |
| 561 | ) |
| 562 | |
| 563 | return metadata |
| 564 | |
| 565 | def forward( |
| 566 | self, |
| 567 | x: torch.Tensor, |
| 568 | grid_thw: torch.Tensor | list[list[int]], |
| 569 | *, |
| 570 | encoder_metadata: dict[str, torch.Tensor] | None = None, |
| 571 | ) -> torch.Tensor: |
| 572 | # patchify |
| 573 | x = self.input_norm(x.to(device=self.device), self.dtype) |
| 574 | x = self.patch_embed(x) |
| 575 | |
| 576 | if encoder_metadata is not None: |
| 577 | # Encoder CUDA-graph path (PR #49852): rotary/cu_seqlens/max_seqlen are |
| 578 | # precomputed by prepare_encoder_metadata (which uses rot_pos_emb exactly |
| 579 | # as the eager rebuild does), so reuse them and skip the per-call CPU |
| 580 | # rebuild (the low-GPU-util culprit on multimodal workloads). |
| 581 | rotary_pos_emb_cos = encoder_metadata["rotary_pos_emb_cos"] |
| 582 | rotary_pos_emb_sin = encoder_metadata["rotary_pos_emb_sin"] |
| 583 | cu_seqlens = encoder_metadata["cu_seqlens"] |
| 584 | max_seqlen = encoder_metadata["max_seqlen"] |
| 585 | else: |
| 586 | if isinstance(grid_thw, list): |
| 587 | grid_thw = torch.tensor(grid_thw, dtype=torch.int32) |
| 588 | rotary_pos_emb_cos, rotary_pos_emb_sin, _ = self.rot_pos_emb(grid_thw) |
| 589 | cu_seqlens = torch.repeat_interleave( |
| 590 | grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0] |
| 591 | ).cumsum(dim=0, dtype=torch.int32) |
| 592 | cu_seqlens = torch.cat([cu_seqlens.new_zeros(1), cu_seqlens]) |
| 593 | cu_seqlens = cu_seqlens.to(self.device, non_blocking=True) |
| 594 | max_seqlen = self.compute_attn_mask_seqlen(cu_seqlens) |
| 595 | |
| 596 | # transformers |
| 597 | x = x.unsqueeze(1) |
| 598 | for blk in self.blocks: |
| 599 | x = blk( |
| 600 | x, |
| 601 | cu_seqlens=cu_seqlens, |
| 602 | rotary_pos_emb_cos=rotary_pos_emb_cos, |
| 603 | rotary_pos_emb_sin=rotary_pos_emb_sin, |
| 604 | max_seqlen=max_seqlen, |
| 605 | ) |
| 606 | |
| 607 | # adapter |
| 608 | x = self.post_layernorm(x) |
| 609 | x = x.view(-1, self.spatial_merge_size, self.spatial_merge_size, x.shape[-1]) |
| 610 | x = x.permute(0, 3, 1, 2) |
| 611 | x = self.downsample(x).view(-1, self.out_hidden_size) |
| 612 | x = self.merger(x) |
| 613 | return x |
| 614 | |
| 615 | def load_weights(self, weights) -> set[str]: |
| 616 | loader = AutoWeightsLoader(self) |
| 617 | return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) |
| 618 | |
| 619 | |
| 620 | _MAX_VIDEO_TOKENS = 30000 |
| 621 | |
| 622 | |
| 623 | class Glm5NextProcessingInfo(Glm4vProcessingInfo): |
| 624 | """Token-budget geometry for the multimodal checkpoint. |
| 625 | |
| 626 | This checkpoint's ``processor_config.json`` ships the token-budget style |
| 627 | (``min_image_tokens`` / ``max_image_tokens``) with no ``size`` key, so the |
| 628 | inherited Glm4v ``size.longest_edge`` path does not apply. |
| 629 | """ |
| 630 | |
| 631 | def get_hf_processor(self, **kwargs: object): |
| 632 | processor = super().get_hf_processor(**kwargs) |
| 633 | # Cap video inputs to keep encoder profiling from starving the KV cache. |
| 634 | video_processor = processor.video_processor |
| 635 | video_processor.max_image_tokens = min( |
| 636 | video_processor.max_image_tokens, _MAX_VIDEO_TOKENS |
| 637 | ) |
| 638 | return processor |
| 639 | |
| 640 | @staticmethod |
| 641 | def _alignment_factor(proc) -> int: |
| 642 | """Spatial factor canvases align to, as ``smart_resize`` takes it.""" |
| 643 | return proc.patch_size * proc.merge_size * proc.patch_expand_factor |
| 644 | |
| 645 | @classmethod |
| 646 | def _pixels_per_token(cls, proc) -> int: |
| 647 | """Pixels one vision token covers, matching ``smart_resize``'s own |
| 648 | ``temporal_factor * factor ** 2``.""" |
| 649 | return proc.temporal_patch_size * cls._alignment_factor(proc) ** 2 |
| 650 | |
| 651 | def _processor_pixel_budget(self, proc) -> tuple[int, int]: |
| 652 | """(min_pixels, max_pixels) from the processor's token bounds.""" |
| 653 | if proc.min_image_tokens is None or proc.max_image_tokens is None: |
| 654 | raise ValueError( |
| 655 | "min_image_tokens and max_image_tokens must be provided by " |
| 656 | "processor_config.json (or per-call kwargs)." |
| 657 | ) |
| 658 | pixels_per_token = self._pixels_per_token(proc) |
| 659 | return ( |
| 660 | proc.min_image_tokens * pixels_per_token, |
| 661 | proc.max_image_tokens * pixels_per_token, |
| 662 | ) |
| 663 | |
| 664 | def _get_image_max_pixels(self) -> int: |
| 665 | mm_kwargs = self.ctx.get_merged_mm_kwargs({}) |
| 666 | if (override := mm_kwargs.get("max_pixels")) is not None: |
| 667 | return int(override) |
| 668 | return self._processor_pixel_budget(self.get_hf_processor().image_processor)[1] |
| 669 | |
| 670 | def _get_video_max_pixels(self) -> int: |
| 671 | mm_kwargs = self.ctx.get_merged_mm_kwargs({}) |
| 672 | if (override := mm_kwargs.get("max_pixels")) is not None: |
| 673 | return int(override) |
| 674 | return self._processor_pixel_budget(self.get_hf_processor().video_processor)[1] |
| 675 | |
| 676 | def get_image_size_with_most_features(self) -> ImageSize: |
| 677 | # The inherited square probe strands budget whenever the token |
| 678 | # ceiling is not a perfect square: with max_image_tokens=8000 the |
| 679 | # square refits to 2492x2492 (89x89 = 7921 tokens) while a |
| 680 | # 2240x2800 canvas reaches 80x100 = 8000, so the encoder cache came |
| 681 | # up short of the processor's own maximum and refused valid images |
| 682 | # (#59539). Factor the ceiling exactly instead of probing a square. |
| 683 | vision_config = self.get_hf_config().vision_config |
| 684 | factor = ( |
| 685 | vision_config.patch_size |
| 686 | * vision_config.spatial_merge_size |
| 687 | * self.get_hf_processor().image_processor.patch_expand_factor |
| 688 | ) |
| 689 | pixels_per_token = vision_config.temporal_patch_size * factor * factor |
| 690 | max_tokens = max(1, self._get_image_max_pixels() // pixels_per_token) |
| 691 | short_side = math.isqrt(max_tokens) |
| 692 | while max_tokens % short_side: |
| 693 | short_side -= 1 |
| 694 | return ImageSize( |
| 695 | width=(max_tokens // short_side) * factor, |
| 696 | height=short_side * factor, |
| 697 | ) |
| 698 | |
| 699 | def _get_video_second_idx_glm46v( |
| 700 | self, metadata: dict[str, Any], total_frames: int |
| 701 | ) -> list[int]: |
| 702 | """Timestamps for the video placeholder, from the pixel path's sampler. |
| 703 | |
| 704 | The inherited GLM-4.6V timestamp sampling uses different constants |
| 705 | than this checkpoint's ``Glm5NextVideoProcessor`` pixel sampling, so |
| 706 | placeholder count and ``video_grid_thw`` disagree outside 30-300s |
| 707 | durations. Sampling with the pixel path's own policy makes one |
| 708 | timestamp per temporal patch == ``grid_t``. |
| 709 | """ |
| 710 | video_processor = self.get_video_processor() |
| 711 | temporal_patch_size = int( |
| 712 | getattr(video_processor, "temporal_patch_size", 1) or 1 |
| 713 | ) |
| 714 | video_fps = float(metadata["fps"]) |
| 715 | |
| 716 | if not metadata.get("do_sample_frames", True): |
| 717 | # The loader already picked the frames and the processor keeps them |
| 718 | # as they are, so the frame count is what was handed in and |
| 719 | # ``frames_indices`` only supplies the timestamp values. |
| 720 | frame_indices = [int(idx) for idx in metadata["frames_indices"]] |
| 721 | num_frames = int(total_frames) |
| 722 | else: |
| 723 | frame_indices = [ |
| 724 | int(idx) |
| 725 | for idx in video_processor.sample_frames( |
| 726 | VideoMetadata( |
| 727 | total_num_frames=int( |
| 728 | metadata.get("total_num_frames", total_frames) |
| 729 | ), |
| 730 | fps=video_fps, |
| 731 | duration=metadata.get("duration"), |
| 732 | ) |
| 733 | ) |
| 734 | ] |
| 735 | num_frames = len(frame_indices) |
| 736 | |
| 737 | if not frame_indices or num_frames <= 0: |
| 738 | # ``duration * fps < 1`` selects no frames at all; the |
| 739 | # pixel path raises an opaque IndexError on the same input a moment |
| 740 | # later, so say what happened while there is still a request. |
| 741 | raise ValueError( |
| 742 | "The GLM-5-Next frame sampler selected no frames for this " |
| 743 | f"video (fps={video_fps}, duration={metadata.get('duration')!r}," |
| 744 | f" total_num_frames={metadata.get('total_num_frames')!r}). " |
| 745 | "Clips shorter than one frame sampling interval cannot be " |
| 746 | "processed." |
| 747 | ) |
| 748 | |
| 749 | num_padded_frames = num_frames + (-num_frames % temporal_patch_size) |
| 750 | grid_t = max(num_padded_frames // temporal_patch_size, 1) |
| 751 | last = len(frame_indices) - 1 |
| 752 | return [ |
| 753 | int(frame_indices[min(i * temporal_patch_size, last)] / video_fps) |
| 754 | for i in range(grid_t) |
| 755 | ] |
| 756 | |
| 757 | def _get_vision_info( |
| 758 | self, |
| 759 | *, |
| 760 | image_width: int, |
| 761 | image_height: int, |
| 762 | num_frames: int = 16, |
| 763 | do_resize: bool = True, |
| 764 | max_image_pixels: int = 28 * 28 * 2 * 30000, |
| 765 | ) -> tuple[ImageSize, int]: |
| 766 | """GLM-5.3-Flash canvas geometry for token budgeting and dummy inputs. |
| 767 | |
| 768 | The inherited Glm4v path resolves the pixel budget from |
| 769 | ``size.longest_edge`` and resizes with GLM-4V's ``smart_resize``. This |
| 770 | checkpoint ships token bounds instead, and the alignment factor carries |
| 771 | ``patch_expand_factor`` — resolve both from the processor so profiling |
| 772 | matches runtime geometry. |
| 773 | """ |
| 774 | from transformers.models.glm5_next.image_processing_glm5_next import ( |
| 775 | smart_resize, |
| 776 | ) |
| 777 | |
| 778 | vision_config = self.get_hf_config().vision_config |
| 779 | patch_size = vision_config.patch_size |
| 780 | merge_size = vision_config.spatial_merge_size |
| 781 | temporal_patch_size = vision_config.temporal_patch_size |
| 782 | |
| 783 | image_processor = self.get_hf_processor().image_processor |
| 784 | factor = self._alignment_factor(image_processor) |
| 785 | temporal_factor = image_processor.temporal_patch_size |
| 786 | # `smart_resize` denominates its bounds in vision tokens. Round down, |
| 787 | # but keep the profiling search viable when the caller's budget is |
| 788 | # below one aligned canvas of the requested duration. |
| 789 | max_image_tokens = max( |
| 790 | max_image_pixels // self._pixels_per_token(image_processor), 1 |
| 791 | ) |
| 792 | |
| 793 | if do_resize: |
| 794 | t = num_frames if num_frames > temporal_factor else temporal_factor |
| 795 | resized_height, resized_width = smart_resize( |
| 796 | num_frames=t, |
| 797 | height=image_height, |
| 798 | width=image_width, |
| 799 | temporal_factor=temporal_factor, |
| 800 | factor=factor, |
| 801 | min_pixels=1, |
| 802 | max_pixels=max_image_tokens, |
| 803 | ) |
| 804 | preprocessed_size = ImageSize(width=resized_width, height=resized_height) |
| 805 | else: |
| 806 | preprocessed_size = ImageSize(width=image_width, height=image_height) |
| 807 | |
| 808 | padded_num_frames = num_frames + (-num_frames % temporal_patch_size) |
| 809 | grid_t = max(padded_num_frames // temporal_patch_size, 1) |
| 810 | grid_h = preprocessed_size.height // patch_size |
| 811 | grid_w = preprocessed_size.width // patch_size |
| 812 | |
| 813 | num_patches = grid_t * grid_h * grid_w |
| 814 | num_vision_tokens = num_patches // (merge_size**2) |
| 815 | |
| 816 | return preprocessed_size, num_vision_tokens |
| 817 | |
| 818 | |
| 819 | class Glm5NextMultiModalProcessor(Glm4vMultiModalProcessor): |
| 820 | """``Glm5NextProcessor`` extracts image/video features |
| 821 | only and passes the prompt text through unchanged, so prompt expansion |
| 822 | (image token repeat, video frame/timestamp structure) is owned by vLLM's |
| 823 | prompt-update machinery — the inherited ``_get_prompt_updates`` builds |
| 824 | the replacement content and the placeholder scan validates against |
| 825 | exactly that.""" |
| 826 | |
| 827 | def _hf_processor_applies_updates( |
| 828 | self, |
| 829 | prompt_text: str, |
| 830 | mm_items: MultiModalDataItems, |
| 831 | hf_processor_mm_kwargs: Mapping[str, object], |
| 832 | tokenization_kwargs: Mapping[str, object], |
| 833 | ) -> bool: |
| 834 | return False |