|
2 | 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
3 | 3 |
|
4 | 4 | from collections.abc import Mapping |
| 5 | +from functools import partial |
5 | 6 | from types import SimpleNamespace |
6 | 7 |
|
7 | 8 | import numpy as np |
|
15 | 16 | Gemma4ForConditionalGeneration, |
16 | 17 | Gemma4ImagePixelInputs, |
17 | 18 | ) |
| 19 | +from vllm.model_executor.models.gemma4_vision import Gemma4VisionModel |
18 | 20 | from vllm.model_executor.models.interfaces import supports_multimodal |
19 | 21 | from vllm.multimodal import MULTIMODAL_REGISTRY |
20 | 22 | from vllm.multimodal.cache import MultiModalProcessorOnlyCache |
21 | 23 | from vllm.multimodal.inputs import MultiModalFieldConfig |
22 | | -from vllm.utils.mem_constants import GiB_bytes |
23 | | -from vllm.v1.worker.encoder_cudagraph_defs import ENCODER_CUDAGRAPH_AXIS_KEYS_KWARG |
| 24 | +from vllm.v1.attention.backends.registry import AttentionBackendEnum |
24 | 25 |
|
25 | 26 | from ....conftest import ImageTestAssets |
26 | 27 | from ...utils import build_model_context |
@@ -339,124 +340,98 @@ def test_limit_mm_per_prompt( |
339 | 340 | ) |
340 | 341 |
|
341 | 342 |
|
342 | | -# Regression guard for PR #43169 follow-up: the batched Gemma4 vision encoder |
343 | | -# admitted ``chunk ~= 53`` on a 22 GiB L4 with a 26B AWQ model loaded, |
344 | | -# allocating 2.43 GiB int64 inside |
345 | | -# ``F.one_hot(num_classes=position_embedding_size)`` and OOMing because only |
346 | | -# 2.41 GiB was actually free. The fix sizes ``chunk`` from currently-free GPU |
347 | | -# memory and counts the ``F.one_hot`` transient as the dominant cost. |
348 | | - |
349 | | -_encoder_chunk = Gemma4ForConditionalGeneration._encoder_chunk |
350 | | - |
351 | | -# Gemma4 vision config default (HF: configuration_gemma4.py). |
352 | | -_POSITION_EMBEDDING_SIZE = 10240 |
353 | | -# Video frame: max_soft_tokens=70, pooling_kernel_size=2 -> 70 * 4 patches. |
354 | | -_VIDEO_PATCHES_PER_FRAME = 280 |
355 | | - |
356 | | - |
357 | | -def test_encoder_chunk_tight_budget_fits_in_free(): |
358 | | - free = 3 * GiB_bytes # L4 22 GiB after 26B AWQ load. |
359 | | - total = 22 * GiB_bytes |
360 | | - chunk = _encoder_chunk( |
361 | | - _VIDEO_PATCHES_PER_FRAME, free, total, _POSITION_EMBEDDING_SIZE |
| 343 | +def _gemma4_for_encoder_cudagraph( |
| 344 | + attn_backend: AttentionBackendEnum = AttentionBackendEnum.TRITON_ATTN, |
| 345 | +) -> Gemma4ForConditionalGeneration: |
| 346 | + model = object.__new__(Gemma4ForConditionalGeneration) |
| 347 | + vision_config = SimpleNamespace( |
| 348 | + patch_size=16, |
| 349 | + pooling_kernel_size=3, |
| 350 | + default_output_length=280, |
| 351 | + position_embedding_size=10240, |
362 | 352 | ) |
363 | | - one_hot_bytes = chunk * _VIDEO_PATCHES_PER_FRAME * 2 * _POSITION_EMBEDDING_SIZE * 8 |
364 | | - assert one_hot_bytes <= free // 2 |
365 | | - |
366 | | - |
367 | | -def test_encoder_chunk_roomy_gpu_keeps_batching(): |
368 | | - chunk = _encoder_chunk( |
369 | | - _VIDEO_PATCHES_PER_FRAME, |
370 | | - 60 * GiB_bytes, |
371 | | - 80 * GiB_bytes, |
372 | | - _POSITION_EMBEDDING_SIZE, |
| 353 | + vision_tower = SimpleNamespace( |
| 354 | + config=vision_config, |
| 355 | + attn_backend=attn_backend, |
| 356 | + qkv_stride=64, |
| 357 | + device=torch.device("cpu"), |
373 | 358 | ) |
374 | | - assert chunk > 8 |
375 | | - |
376 | | - |
377 | | -def test_encoder_chunk_zero_patches_is_safe(): |
378 | | - assert ( |
379 | | - _encoder_chunk(0, 60 * GiB_bytes, 80 * GiB_bytes, _POSITION_EMBEDDING_SIZE) == 1 |
380 | | - ) |
381 | | - |
382 | | - |
383 | | -def test_encoder_chunk_zero_position_embedding_size_is_safe(): |
384 | | - # Degenerate config: must not raise ZeroDivisionError. |
385 | | - assert ( |
386 | | - _encoder_chunk(_VIDEO_PATCHES_PER_FRAME, 60 * GiB_bytes, 80 * GiB_bytes, 0) == 1 |
| 359 | + vision_tower.prepare_encoder_metadata = partial( |
| 360 | + Gemma4VisionModel.prepare_encoder_metadata, vision_tower |
387 | 361 | ) |
388 | | - |
389 | | - |
390 | | -def test_encoder_chunk_no_free_memory_falls_back_to_one(): |
391 | | - assert ( |
392 | | - _encoder_chunk( |
393 | | - _VIDEO_PATCHES_PER_FRAME, 0, 22 * GiB_bytes, _POSITION_EMBEDDING_SIZE |
394 | | - ) |
395 | | - == 1 |
| 362 | + model.vision_tower = vision_tower |
| 363 | + model.config = SimpleNamespace( |
| 364 | + vision_config=vision_config, text_config=SimpleNamespace(hidden_size=8) |
396 | 365 | ) |
| 366 | + return model |
397 | 367 |
|
398 | 368 |
|
399 | | -def _gemma4_for_encoder_cudagraph() -> Gemma4ForConditionalGeneration: |
400 | | - model = object.__new__(Gemma4ForConditionalGeneration) |
401 | | - vision_config = SimpleNamespace( |
402 | | - patch_size=16, pooling_kernel_size=3, default_output_length=280 |
403 | | - ) |
404 | | - model.vision_tower = SimpleNamespace(config=vision_config) |
405 | | - model.config = SimpleNamespace(vision_config=vision_config) |
406 | | - return model |
| 369 | +def _padded_image( |
| 370 | + columns: int, rows: int, max_patches: int = 2520 |
| 371 | +) -> tuple[torch.Tensor, torch.Tensor]: |
| 372 | + """Patches laid out like the processor's: row-major, padded at the end.""" |
| 373 | + grid = torch.meshgrid(torch.arange(columns), torch.arange(rows), indexing="xy") |
| 374 | + positions = torch.full((max_patches, 2), -1, dtype=torch.long) |
| 375 | + positions[: columns * rows] = torch.stack(grid, -1).reshape(-1, 2) |
| 376 | + return torch.zeros(max_patches, 768), positions |
407 | 377 |
|
408 | 378 |
|
409 | | -@pytest.mark.parametrize( |
410 | | - ("token_budget", "row_tokens"), [(4096, 70), (4096, 280), (70, 280)] |
411 | | -) |
412 | | -def test_encoder_cudagraph_capture_rows_fit_token_budget( |
413 | | - token_budget: int, row_tokens: int |
414 | | -): |
415 | | - # Regression for #61045: rows were max_frames_per_batch (58 * 32) at |
416 | | - # 280 tokens each, so the 4096-token buffer alone was 6.69 GiB. |
| 379 | +@pytest.mark.parametrize("token_budget", [70, 4480]) |
| 380 | +def test_encoder_cudagraph_capture_buffers_fit_token_budget(token_budget: int): |
| 381 | + # Regression for #61045: buffers sized by max_frames_per_batch rows |
| 382 | + # instead of the token budget took 6.69 GiB at a 4096-token budget. |
417 | 383 | model = _gemma4_for_encoder_cudagraph() |
418 | | - inputs = model.prepare_encoder_cudagraph_capture_inputs( |
| 384 | + values = model.prepare_encoder_cudagraph_capture_inputs( |
419 | 385 | token_budget=token_budget, |
420 | | - max_batch_size=58, |
421 | | - max_frames_per_batch=58 * 32, |
422 | | - device="meta", |
| 386 | + max_batch_size=1, |
| 387 | + max_frames_per_batch=32, |
| 388 | + device=torch.device("cpu"), |
423 | 389 | dtype=torch.bfloat16, |
424 | | - axis_keys=(row_tokens,), |
425 | | - ) |
| 390 | + ).values |
426 | 391 |
|
427 | | - num_rows, row_patches, _ = inputs.values["pixel_values"].shape |
428 | | - assert row_patches == row_tokens * 9 |
429 | | - assert num_rows == max(1, token_budget // row_tokens) |
| 392 | + assert values["pixel_values"].shape == (token_budget * 9, 768) |
| 393 | + assert values["pixel_position_ids"].shape == (token_budget * 9, 2) |
| 394 | + assert values["pool_gather_idx"].shape == (token_budget * 9,) |
| 395 | + # A slot per image or frame that fits, each of at least 35 tokens: the |
| 396 | + # manager does not bound frames, e.g. a 64-frame video in 4480 tokens. |
| 397 | + assert values["cu_seqlens"].shape == (max(1, token_budget // 35) + 1,) |
| 398 | + # The largest image of the configured max_soft_tokens (280). |
| 399 | + assert values["max_seqlen"].item() == min(token_budget, 280) * 9 |
430 | 400 |
|
431 | 401 |
|
432 | | -def test_encoder_cudagraph_mixed_width_images_pack_by_padded_width(): |
| 402 | +def test_encoder_cudagraph_replay_packs_images_without_padding(): |
433 | 403 | model = _gemma4_for_encoder_cudagraph() |
| 404 | + images = [ |
| 405 | + _padded_image(9, 6), |
| 406 | + _padded_image(60, 42), |
| 407 | + _padded_image(3, 3), |
| 408 | + _padded_image(90, 42, max_patches=3780), |
| 409 | + ] |
434 | 410 | mm_kwargs = { |
435 | | - "pixel_values": [torch.zeros(2520, 768), torch.zeros(630, 768)], |
436 | | - "pixel_position_ids": [ |
437 | | - torch.zeros(2520, 2, dtype=torch.long), |
438 | | - torch.zeros(630, 2, dtype=torch.long), |
439 | | - ], |
| 411 | + "pixel_values": [pixel_values for pixel_values, _ in images], |
| 412 | + "pixel_position_ids": [positions for _, positions in images], |
440 | 413 | } |
441 | 414 |
|
442 | 415 | specs = model.get_encoder_cudagraph_item_specs(mm_kwargs) |
443 | | - assert [spec.output_tokens for spec in specs] == [280, 70] |
444 | | - assert [spec.get_path_output_tokens("default") for spec in specs] == [280, 280] |
445 | | - |
446 | | - selected = model.select_encoder_cudagraph_items(mm_kwargs, [1]) |
447 | | - assert selected[ENCODER_CUDAGRAPH_AXIS_KEYS_KWARG] == (70,) |
448 | | - selected = model.select_encoder_cudagraph_items(mm_kwargs, [0, 1]) |
449 | | - assert selected[ENCODER_CUDAGRAPH_AXIS_KEYS_KWARG] == (280,) |
450 | | - |
451 | | - |
452 | | -@pytest.mark.parametrize( |
453 | | - "mm_processor_kwargs", |
454 | | - [{"max_soft_tokens": 560}, {"images_kwargs": {"max_soft_tokens": 560}}], |
455 | | -) |
456 | | -def test_encoder_cudagraph_config_respects_max_soft_tokens(mm_processor_kwargs): |
| 416 | + assert [spec.output_tokens for spec in specs] == [6, 280, 1, 420] |
| 417 | + # Below the 35 tokens the graphs' sequence slots assume, or above their |
| 418 | + # max_seqlen (configured 280 tokens): eager. |
| 419 | + assert [spec.eager_only for spec in specs] == [True, False, True, True] |
| 420 | + |
| 421 | + selected = model.select_encoder_cudagraph_items(mm_kwargs, [0, 2]) |
| 422 | + values = model.prepare_encoder_cudagraph_replay_buffers( |
| 423 | + selected, max_batch_size=4, max_frames_per_batch=4 |
| 424 | + ).values |
| 425 | + assert values["pixel_values"].shape == (54 + 9, 768) |
| 426 | + assert values["cu_seqlens"].tolist() == [0, 54, 63] |
| 427 | + # Each 3x3 block of the 9x6 image, then the 3x3 image. |
| 428 | + assert values["pool_gather_idx"][:9].tolist() == [0, 1, 2, 9, 10, 11, 18, 19, 20] |
| 429 | + assert values["pool_gather_idx"][9:18].tolist() == [3, 4, 5, 12, 13, 14, 21, 22, 23] |
| 430 | + assert values["pool_gather_idx"][54:].tolist() == list(range(54, 63)) |
| 431 | + |
| 432 | + |
| 433 | +def test_encoder_metadata_rejects_grids_not_divisible_by_pooling(): |
457 | 434 | model = _gemma4_for_encoder_cudagraph() |
458 | | - model.config.text_config = SimpleNamespace(hidden_size=8) |
459 | | - model.multimodal_config = SimpleNamespace(mm_processor_kwargs=mm_processor_kwargs) |
460 | | - |
461 | | - config = model.get_encoder_cudagraph_config() |
462 | | - assert config.capture_axes == ((70, 140, 280, 560),) |
| 435 | + _, positions = _padded_image(4, 3) |
| 436 | + with pytest.raises(ValueError, match="multiples of 3"): |
| 437 | + model.vision_tower.prepare_encoder_metadata([positions[:12].numpy()]) |
0 commit comments