[MM][Perf][CG] Support ViT full CUDA graph for Qwen3-VL video inference (#38061)
Signed-off-by: shen-shanshan <467638484@qq.com> Signed-off-by: Shanshan Shen <87969357+shen-shanshan@users.noreply.github.com> Co-authored-by: Roger Wang <hey@rogerw.io>
This commit is contained in:
co-authored by
Roger Wang
parent
c0ecaed950
commit
80118853f4
@@ -1524,6 +1524,13 @@ class SupportsEncoderCudaGraph(Protocol):
|
||||
|
||||
def get_encoder_cudagraph_config(self) -> "EncoderCudaGraphConfig": ...
|
||||
|
||||
def get_input_modality(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
) -> str:
|
||||
"""Return the modality of the inputs."""
|
||||
...
|
||||
|
||||
def get_encoder_cudagraph_budget_range(
|
||||
self,
|
||||
vllm_config: "VllmConfig",
|
||||
@@ -1536,7 +1543,7 @@ class SupportsEncoderCudaGraph(Protocol):
|
||||
(e.g. max_num_batched_tokens)
|
||||
|
||||
Used when ``encoder_cudagraph_token_budgets`` and/or
|
||||
``encoder_cudagraph_max_images_per_batch`` are not explicitly
|
||||
``encoder_cudagraph_max_vision_items_per_batch`` are not explicitly
|
||||
specified by the user.
|
||||
"""
|
||||
...
|
||||
@@ -1590,6 +1597,7 @@ class SupportsEncoderCudaGraph(Protocol):
|
||||
self,
|
||||
token_budget: int,
|
||||
max_batch_size: int,
|
||||
max_frames_per_batch: int,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
) -> "EncoderCudaGraphCaptureInputs":
|
||||
@@ -1600,6 +1608,7 @@ class SupportsEncoderCudaGraph(Protocol):
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
max_batch_size: int,
|
||||
max_frames_per_batch: int,
|
||||
) -> "EncoderCudaGraphReplayBuffers":
|
||||
"""Compute buffer values from actual batch inputs for replay."""
|
||||
...
|
||||
|
||||
@@ -99,6 +99,7 @@ from vllm.tokenizers.registry import cached_tokenizer_from_config
|
||||
from vllm.triton_utils import HAS_TRITON, tl, triton
|
||||
from vllm.utils.collection_utils import is_list_of
|
||||
from vllm.utils.math_utils import round_up
|
||||
from vllm.v1.worker.encoder_cudagraph_defs import EncoderCudaGraphReplayBuffers
|
||||
|
||||
from .interfaces import (
|
||||
MultiModalEmbeddings,
|
||||
@@ -689,6 +690,7 @@ class Qwen3_VisionTransformer(nn.Module):
|
||||
grid_thw_list: list[list[int]],
|
||||
*,
|
||||
max_batch_size: int | None = None,
|
||||
max_frames_per_batch: int | None = None,
|
||||
max_seqlen_override: int | None = None,
|
||||
device: torch.device | None = None,
|
||||
) -> dict[str, torch.Tensor | None]:
|
||||
@@ -701,6 +703,10 @@ class Qwen3_VisionTransformer(nn.Module):
|
||||
grid_thw_list: Grid configurations as list of [t, h, w].
|
||||
max_batch_size: If set, pad cu_seqlens to this size
|
||||
(needed for CUDA graph capture/replay).
|
||||
max_frames_per_batch: If set, overrides max_batch_size for
|
||||
cu_seqlens padding. For video inputs each item contributes
|
||||
T attention sequences (frames); this sizes the buffer to
|
||||
the total frame budget so video replays never overflow.
|
||||
max_seqlen_override: If set, use this value for max_seqlen
|
||||
instead of computing from cu_seqlens (needed for CUDA
|
||||
graph capture to cover worst-case replay scenarios).
|
||||
@@ -725,15 +731,21 @@ class Qwen3_VisionTransformer(nn.Module):
|
||||
)
|
||||
cu_seqlens = np.concatenate([np.zeros(1, dtype=np.int32), cu_seqlens])
|
||||
|
||||
# Pad cu_seqlens if max_batch_size specified
|
||||
if max_batch_size is not None:
|
||||
# Pad cu_seqlens to the required number of sequences.
|
||||
# For videos each item contributes T frames = T attention sequences,
|
||||
# so the total can exceed max_batch_size. max_frames_per_batch
|
||||
# overrides the pad target when set.
|
||||
pad_to = (
|
||||
max_frames_per_batch if max_frames_per_batch is not None else max_batch_size
|
||||
)
|
||||
if pad_to is not None:
|
||||
num_seqs = len(cu_seqlens) - 1
|
||||
if num_seqs < max_batch_size:
|
||||
if num_seqs < pad_to:
|
||||
cu_seqlens = np.concatenate(
|
||||
[
|
||||
cu_seqlens,
|
||||
np.full(
|
||||
max_batch_size - num_seqs,
|
||||
pad_to - num_seqs,
|
||||
cu_seqlens[-1],
|
||||
dtype=np.int32,
|
||||
),
|
||||
@@ -1737,9 +1749,21 @@ class Qwen3VLForConditionalGeneration(
|
||||
EncoderCudaGraphConfig,
|
||||
)
|
||||
|
||||
modalities = ["image"]
|
||||
# NOTE: When EVS (Efficient Video Sampling) pruning is enabled, the number
|
||||
# of tokens becomes data-dependent (i.e., the retained tokens are
|
||||
# dynamically selected based on inter-frame differences) and therefore
|
||||
# cannot be captured by CUDA Graphs. As a result, video CUDA Graphs are
|
||||
# only enabled when EVS is disabled.
|
||||
if not self.is_multimodal_pruning_enabled:
|
||||
modalities.append("video")
|
||||
|
||||
return EncoderCudaGraphConfig(
|
||||
modalities=["image"],
|
||||
input_key="pixel_values",
|
||||
modalities=modalities,
|
||||
input_key_by_modality={
|
||||
"image": "pixel_values",
|
||||
"video": "pixel_values_videos",
|
||||
},
|
||||
buffer_keys=[
|
||||
"pos_embeds",
|
||||
"rotary_pos_emb_cos",
|
||||
@@ -1751,49 +1775,86 @@ class Qwen3VLForConditionalGeneration(
|
||||
out_hidden_size=self.visual.out_hidden_size,
|
||||
)
|
||||
|
||||
def get_input_modality(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
) -> str:
|
||||
if "image_grid_thw" in mm_kwargs:
|
||||
return "image"
|
||||
return "video"
|
||||
|
||||
def get_encoder_cudagraph_budget_range(
|
||||
self,
|
||||
vllm_config,
|
||||
) -> tuple[int, int]:
|
||||
# Min: estimated smallest possible encoder input.
|
||||
# 224x224 image → 16x16 patches, spatial_merge_size=2 → 8x8 = 64 tokens
|
||||
# 224x224 image → 16x16 patches (patch_size=14)
|
||||
# spatial_merge_size=2 → 8x8 = 64 tokens
|
||||
min_budget = 64
|
||||
# Max: capped by max_num_batched_tokens
|
||||
max_budget = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
return (min_budget, max_budget)
|
||||
|
||||
def _get_pixel_values_by_modality(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
) -> torch.Tensor:
|
||||
if self.get_input_modality(mm_kwargs) == "image":
|
||||
pixel_values = mm_kwargs["pixel_values"]
|
||||
else:
|
||||
pixel_values = mm_kwargs["pixel_values_videos"]
|
||||
return pixel_values
|
||||
|
||||
def _get_grid_thw_by_modality(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
) -> list[tuple[int, int, int]]:
|
||||
grid_thw_key = f"{self.get_input_modality(mm_kwargs)}_grid_thw"
|
||||
grid_thw = mm_kwargs[grid_thw_key]
|
||||
if not isinstance(grid_thw, list):
|
||||
grid_thw = grid_thw.tolist()
|
||||
return grid_thw
|
||||
|
||||
def get_encoder_cudagraph_num_items(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
) -> int:
|
||||
return len(mm_kwargs["image_grid_thw"])
|
||||
return len(self._get_grid_thw_by_modality(mm_kwargs))
|
||||
|
||||
def get_encoder_cudagraph_per_item_output_tokens(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
) -> list[int]:
|
||||
m = self.visual.spatial_merge_size
|
||||
return [t * (h // m) * (w // m) for t, h, w in mm_kwargs["image_grid_thw"]]
|
||||
grid_thw = self._get_grid_thw_by_modality(mm_kwargs)
|
||||
return [t * (h // m) * (w // m) for t, h, w in grid_thw]
|
||||
|
||||
def get_encoder_cudagraph_per_item_input_sizes(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
) -> list[int]:
|
||||
return [t * h * w for t, h, w in mm_kwargs["image_grid_thw"]]
|
||||
grid_thw = self._get_grid_thw_by_modality(mm_kwargs)
|
||||
return [t * h * w for t, h, w in grid_thw]
|
||||
|
||||
def select_encoder_cudagraph_items(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
indices: list[int],
|
||||
) -> dict[str, Any]:
|
||||
grid_thw = mm_kwargs["image_grid_thw"]
|
||||
pixel_values = mm_kwargs["pixel_values"]
|
||||
grid_thw = self._get_grid_thw_by_modality(mm_kwargs)
|
||||
pixel_values = self._get_pixel_values_by_modality(mm_kwargs)
|
||||
|
||||
if len(indices) == 0:
|
||||
return {
|
||||
"pixel_values": pixel_values[:0],
|
||||
"image_grid_thw": [],
|
||||
}
|
||||
if self.get_input_modality(mm_kwargs) == "image":
|
||||
return {
|
||||
"pixel_values": pixel_values[:0],
|
||||
"image_grid_thw": [],
|
||||
}
|
||||
else:
|
||||
return {
|
||||
"pixel_values_videos": pixel_values[:0],
|
||||
"video_grid_thw": [],
|
||||
}
|
||||
|
||||
# Compute cumulative patch offsets for slicing pixel_values
|
||||
patches_per_item = [t * h * w for t, h, w in grid_thw]
|
||||
@@ -1806,15 +1867,22 @@ class Qwen3VLForConditionalGeneration(
|
||||
)
|
||||
selected_grid = [grid_thw[i] for i in indices]
|
||||
|
||||
return {
|
||||
"pixel_values": selected_pv,
|
||||
"image_grid_thw": selected_grid,
|
||||
}
|
||||
if self.get_input_modality(mm_kwargs) == "image":
|
||||
return {
|
||||
"pixel_values": selected_pv,
|
||||
"image_grid_thw": selected_grid,
|
||||
}
|
||||
else:
|
||||
return {
|
||||
"pixel_values_videos": selected_pv,
|
||||
"video_grid_thw": selected_grid,
|
||||
}
|
||||
|
||||
def prepare_encoder_cudagraph_capture_inputs(
|
||||
self,
|
||||
token_budget: int,
|
||||
max_batch_size: int,
|
||||
max_frames_per_batch: int,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
):
|
||||
@@ -1823,14 +1891,35 @@ class Qwen3VLForConditionalGeneration(
|
||||
)
|
||||
|
||||
spatial_merge_size = self.visual.spatial_merge_size
|
||||
per_image_output = token_budget // max_batch_size
|
||||
per_mm_item_output = token_budget // max_batch_size
|
||||
|
||||
# Synthetic rectangular grid: [1, merge, per_image_output * merge]
|
||||
# produces exactly per_image_output tokens per image.
|
||||
grid_config = [
|
||||
[1, spatial_merge_size, per_image_output * spatial_merge_size]
|
||||
for _ in range(max_batch_size)
|
||||
]
|
||||
frames_per_item = max_frames_per_batch // max_batch_size
|
||||
if frames_per_item > 1:
|
||||
# Build the capture grid using a video-format layout so that
|
||||
# cu_seqlens is sized for video replays from the start.
|
||||
# cu_seqlens has one entry per attention sequence (one per frame),
|
||||
# so using T > 1 per item makes the buffer large enough without
|
||||
# relying solely on padding.
|
||||
# Ceiling ensures frames_per_item * tokens_per_frame >= per_mm_item_output
|
||||
# so the pixel_values buffer covers any valid single-item replay.
|
||||
tokens_per_frame = (
|
||||
per_mm_item_output + frames_per_item - 1
|
||||
) // frames_per_item
|
||||
# Video-format grid_config (T=frames_per_item).
|
||||
grid_config = [
|
||||
[
|
||||
frames_per_item,
|
||||
spatial_merge_size,
|
||||
tokens_per_frame * spatial_merge_size,
|
||||
]
|
||||
for _ in range(max_batch_size)
|
||||
]
|
||||
else:
|
||||
# Image-format grid_config (T=1).
|
||||
grid_config = [
|
||||
[1, spatial_merge_size, per_mm_item_output * spatial_merge_size]
|
||||
for _ in range(max_batch_size)
|
||||
]
|
||||
|
||||
# Create dummy pixel_values
|
||||
patch_embed = self.visual.patch_embed
|
||||
@@ -1848,15 +1937,18 @@ class Qwen3VLForConditionalGeneration(
|
||||
# Override max_seqlen with a safe upper bound for capture.
|
||||
# max_seqlen.item() gets baked into the CUDA graph (not replayed),
|
||||
# so the capture value must cover any replay scenario.
|
||||
# Worst case: 1 image consuming the full budget ->
|
||||
# Worst case: 1 item consuming the full budget ->
|
||||
# seq_len = token_budget * spatial_merge_size^2.
|
||||
buffers = self.visual.prepare_encoder_metadata(
|
||||
grid_config,
|
||||
max_batch_size=max_batch_size,
|
||||
max_frames_per_batch=max_frames_per_batch,
|
||||
max_seqlen_override=token_budget * (spatial_merge_size**2),
|
||||
device=device,
|
||||
)
|
||||
|
||||
# Just use image-modality dummy input_buffer for capturing, since it's also
|
||||
# compatible for video inputs (has the same shape: [num_patches, C*T*P*P]).
|
||||
mm_kwargs = {
|
||||
"pixel_values": dummy_pixel_values,
|
||||
"image_grid_thw": grid_config,
|
||||
@@ -1871,17 +1963,21 @@ class Qwen3VLForConditionalGeneration(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
max_batch_size: int,
|
||||
max_frames_per_batch: int,
|
||||
):
|
||||
from vllm.v1.worker.encoder_cudagraph_defs import (
|
||||
EncoderCudaGraphReplayBuffers,
|
||||
)
|
||||
modality = self.get_input_modality(mm_kwargs)
|
||||
grid_thw_list = self._get_grid_thw_by_modality(mm_kwargs)
|
||||
|
||||
grid_thw_list = mm_kwargs["image_grid_thw"]
|
||||
|
||||
buffers = self.visual.prepare_encoder_metadata(
|
||||
grid_thw_list,
|
||||
max_batch_size=max_batch_size,
|
||||
)
|
||||
if modality == "image":
|
||||
buffers = self.visual.prepare_encoder_metadata(
|
||||
grid_thw_list,
|
||||
max_batch_size=max_batch_size,
|
||||
)
|
||||
else:
|
||||
buffers = self.visual.prepare_encoder_metadata(
|
||||
grid_thw_list,
|
||||
max_frames_per_batch=max_frames_per_batch,
|
||||
)
|
||||
|
||||
return EncoderCudaGraphReplayBuffers(buffers=buffers)
|
||||
|
||||
@@ -1890,16 +1986,16 @@ class Qwen3VLForConditionalGeneration(
|
||||
mm_kwargs: dict[str, Any],
|
||||
buffers: dict[str, torch.Tensor],
|
||||
) -> torch.Tensor:
|
||||
pixel_values = mm_kwargs["pixel_values"]
|
||||
grid_thw = mm_kwargs["image_grid_thw"]
|
||||
pixel_values = self._get_pixel_values_by_modality(mm_kwargs)
|
||||
grid_thw = self._get_grid_thw_by_modality(mm_kwargs)
|
||||
return self.visual(pixel_values, grid_thw, encoder_metadata=buffers)
|
||||
|
||||
def encoder_eager_forward(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
) -> torch.Tensor:
|
||||
pixel_values = mm_kwargs["pixel_values"]
|
||||
grid_thw = mm_kwargs["image_grid_thw"]
|
||||
pixel_values = self._get_pixel_values_by_modality(mm_kwargs)
|
||||
grid_thw = self._get_grid_thw_by_modality(mm_kwargs)
|
||||
return self.visual(pixel_values, grid_thw)
|
||||
|
||||
def _parse_and_validate_image_input(
|
||||
|
||||
Reference in New Issue
Block a user