Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
e431df5
[MM] Lazy media decode: move decoding into mm processor
Isotr0py Sep 19, 2026
473985d
[MM] Lazy decode refinements: per-modality IOs, vision_chunk, error s…
Isotr0py Sep 19, 2026
68fd9ee
[MM] Add lazy media decode design doc
Isotr0py Sep 19, 2026
4c35986
[MM] Fix hidden PNG decode on the lazy hash path; add benchmark
Isotr0py Sep 19, 2026
ed807a1
[MM] Fix uuid validation force-decoding lazy media on the mm worker
Isotr0py Sep 19, 2026
9f8b241
[MM] Two-phase apply: overlap lazy decode across requests
Isotr0py Sep 19, 2026
ca360b3
Merge branch 'main' into mm/processor-decode-refactor
DarkLight1337 Sep 23, 2026
ee0c2ab
[MM] Unify fetched media as MediaRef, resolve decoders in the processor
DarkLight1337 Sep 23, 2026
13d62e1
[MM] Report the item index in parser-side decode errors
DarkLight1337 Sep 23, 2026
5fbf2d4
Address comments
DarkLight1337 Sep 30, 2026
830e0d5
Merge branch 'main' into mm/processor-decode-refactor
DarkLight1337 Sep 30, 2026
d81c52f
Merge branch 'main' into mm/processor-decode-refactor
DarkLight1337 Sep 30, 2026
5f26f70
Address comment
DarkLight1337 Sep 30, 2026
36b67e8
Clean up code
DarkLight1337 Sep 30, 2026
849c4f1
More clean up
DarkLight1337 Sep 30, 2026
df35654
Fix lazy media cache identity, ownership, and cancellation
DarkLight1337 Sep 30, 2026
93518c2
Improve code quality
DarkLight1337 Sep 30, 2026
7effcc7
Merge branch 'main' into mm/processor-decode-refactor
DarkLight1337 Sep 30, 2026
ade1a91
Fix
DarkLight1337 Sep 30, 2026
248ac30
Unnecessary assert
DarkLight1337 Sep 30, 2026
4c15108
More cleanup
DarkLight1337 Sep 30, 2026
e05a51c
More clean up
DarkLight1337 Sep 30, 2026
436e470
Clean up
DarkLight1337 Sep 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
545 changes: 545 additions & 0 deletions benchmarks/benchmark_lazy_decode.py

Large diffs are not rendered by default.

471 changes: 471 additions & 0 deletions docs/design/lazy-media-decode.md

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
)
from vllm.logger import init_logger
from vllm.logprobs import Logprob
from vllm.multimodal.media import MediaWithBytes
from vllm.multimodal.media import LazyMedia, MediaWithBytes
from vllm.multimodal.utils import fetch_image
from vllm.outputs import RequestOutput
from vllm.platforms import current_platform
Expand Down Expand Up @@ -1715,8 +1715,8 @@ def url_for(self, name: str) -> str:

def get_image_asset(self, name: str) -> Image.Image:
image = fetch_image(self.url_for(name))
# Unwrap MediaWithBytes if present
if isinstance(image, MediaWithBytes):
# Unwrap LazyMedia / MediaWithBytes if present
while isinstance(image, (LazyMedia, MediaWithBytes)):
image = image.media
return image

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from tests.entrypoints.multimodal.conftest import TEST_IMAGE_ASSETS
from tests.utils import ROCM_EXTRA_ARGS, RemoteOpenAIServer
from vllm.multimodal.media import MediaWithBytes
from vllm.multimodal.media import LazyMedia, MediaWithBytes
from vllm.multimodal.utils import encode_image_url, fetch_image
from vllm.platforms import current_platform

Expand Down Expand Up @@ -198,8 +198,8 @@ def get_hf_prompt_tokens(model_name, content, image_url):
}
]
image = fetch_image(image_url)
# Unwrap MediaWithBytes if present
if isinstance(image, MediaWithBytes):
# Unwrap LazyMedia / MediaWithBytes if present
while isinstance(image, (LazyMedia, MediaWithBytes)):
image = image.media
images = [image]

Expand Down
6 changes: 3 additions & 3 deletions tests/entrypoints/pooling/embed/test_online_vision.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from tests.utils import VLLM_PATH, RemoteOpenAIServer
from vllm.entrypoints.pooling.embed.protocol import EmbeddingResponse
from vllm.multimodal.media import MediaWithBytes
from vllm.multimodal.media import LazyMedia, MediaWithBytes
from vllm.multimodal.utils import encode_image_url, fetch_image

MODEL_NAME = "TIGER-Lab/VLM2Vec-Full"
Expand Down Expand Up @@ -168,8 +168,8 @@ def get_hf_prompt_tokens(model_name, content, image_url):
placeholder = "<|image_1|> "
prompt = f"{placeholder}{content}"
image = fetch_image(image_url)
# Unwrap MediaWithBytes if present
if isinstance(image, MediaWithBytes):
# Unwrap LazyMedia / MediaWithBytes if present
while isinstance(image, (LazyMedia, MediaWithBytes)):
image = image.media
images = [image]
inputs = processor(prompt, images, return_tensors="pt")
Expand Down
85 changes: 84 additions & 1 deletion tests/entrypoints/unit_tests/test_chat_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

import asyncio
import threading
import warnings
from collections.abc import Mapping
from typing import Literal
Expand All @@ -18,15 +19,17 @@
MEDIA_CONNECTOR_REGISTRY,
AsyncMultiModalItemTracker,
ConversationMessage,
MultiModalItemTracker,
_load_embeds_dict,
_parse_metadata_array,
_postprocess_messages,
parse_chat_messages,
parse_chat_messages_async,
validate_chat_template,
)
from vllm.exceptions import VLLMValidationError
from vllm.exceptions import VLLMUnprocessableEntityError, VLLMValidationError
from vllm.inputs import MultiModalDataDict, MultiModalUUIDDict
from vllm.multimodal.media import LazyMedia
from vllm.multimodal.utils import (
encode_audio_url,
encode_image_url,
Expand Down Expand Up @@ -3070,6 +3073,86 @@ async def _fetch(should_fail: bool, delay: float):
)


@pytest.mark.asyncio
async def test_resolve_items_decodes_lazy_vision_chunk_off_event_loop():
"""Lazy vision_chunk items decode on the media thread pool, not the
event-loop thread, when use_unified_vision_chunk_modality is active."""
loop_thread_name = threading.current_thread().name
decode_thread_names: list[str] = []

def _decode():
decode_thread_names.append(threading.current_thread().name)
return "decoded-image"

lazy_item = LazyMedia(_decode, b"fake-image-bytes")

async def _fetch():
return lazy_item, "uuid-0"

tracker = AsyncMultiModalItemTracker(MagicMock())
tracker._model_config.is_multimodal_model = True
tracker._model_config.hf_config.use_unified_vision_chunk = True
tracker.__dict__["mm_processor"] = MagicMock()
tracker._items_by_modality["vision_chunk"] = [lambda: _fetch()]
tracker._modality_order["vision_chunk"] = ["image"]

mm_data, mm_uuids = await tracker.resolve_items()

assert decode_thread_names
assert all(name != loop_thread_name for name in decode_thread_names)
assert lazy_item.is_decoded
assert mm_data is not None
chunk = mm_data["vision_chunk"][0]
assert chunk["type"] == "image"
assert chunk["image"] == "decoded-image"
assert mm_uuids == {"vision_chunk": ["uuid-0"]}


@pytest.mark.asyncio
async def test_resolve_items_lazy_vision_chunk_decode_error_propagates_async():
"""A LazyMedia decode failure in a vision_chunk item must raise
VLLMUnprocessableEntityError, not be logged and swallowed."""

def _decode():
raise ValueError("corrupt media")

lazy_item = LazyMedia(_decode, b"corrupt-video-bytes")

async def _fetch():
return lazy_item, None

tracker = AsyncMultiModalItemTracker(MagicMock())
tracker._model_config.is_multimodal_model = True
tracker._model_config.hf_config.use_unified_vision_chunk = True
tracker.__dict__["mm_processor"] = MagicMock()
tracker._items_by_modality["vision_chunk"] = [lambda: _fetch()]
tracker._modality_order["vision_chunk"] = ["video"]

with pytest.raises(VLLMUnprocessableEntityError, match="corrupt media"):
await tracker.resolve_items()


def test_resolve_items_lazy_vision_chunk_decode_error_propagates_sync(caplog):
"""Sync path: a LazyMedia decode failure in a vision_chunk item must
propagate as VLLMUnprocessableEntityError instead of hitting the
"Failed to split video chunks" log-and-append fallback."""

def _decode():
raise ValueError("corrupt media")

lazy_item = LazyMedia(_decode, b"corrupt-video-bytes")

tracker = MultiModalItemTracker(MagicMock())
tracker._model_config.is_multimodal_model = True
tracker.__dict__["mm_processor"] = MagicMock()
tracker._items_by_modality["vision_chunk"] = [(lazy_item, None)]
tracker._modality_order["vision_chunk"] = ["video"]

with pytest.raises(VLLMUnprocessableEntityError, match="corrupt media"):
tracker.resolve_items()
assert "Failed to split video chunks" not in caplog.text


def _assistant_tool_call(arguments, name="write"):
return [
{
Expand Down
93 changes: 92 additions & 1 deletion tests/multimodal/media/test_audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
import pytest
import soundfile as sf

from vllm.multimodal.media import AudioMediaIO
from vllm.exceptions import VLLMValidationError
from vllm.multimodal.media import AudioMediaIO, LazyMedia
from vllm.multimodal.media import audio as audio_module
from vllm.multimodal.media.audio import (
load_audio,
Expand Down Expand Up @@ -177,6 +178,96 @@ def test_load_audio_threads_max_decode_bytes():
)


def test_audio_media_io_load_bytes_lazy_decode_matches_eager(dummy_audio_bytes):
"""The lazy handle must not decode at construction and must decode to
exactly what load_bytes returns."""
audio_io = AudioMediaIO()
lazy = audio_io.load_bytes_lazy(dummy_audio_bytes)
assert isinstance(lazy, LazyMedia)
assert lazy.original_bytes == dummy_audio_bytes
assert not lazy.is_decoded

ref_audio, ref_sr = audio_io.load_bytes(dummy_audio_bytes)
audio, sr = lazy.media
assert lazy.is_decoded
assert sr == ref_sr
np.testing.assert_array_equal(ref_audio, audio)


def test_audio_media_io_load_bytes_lazy_rejects_oversize_eagerly(
dummy_audio_bytes, monkeypatch
):
"""The encoded-size guard must run at fetch time, not at decode time."""
audio_io = AudioMediaIO()
monkeypatch.setattr(audio_io, "get_max_bytes", lambda: 4)
with pytest.raises(VLLMValidationError, match="Maximum file size exceeded"):
audio_io.load_bytes_lazy(dummy_audio_bytes)


def test_audio_media_io_load_bytes_lazy_corrupt_raises_on_access():
"""Corrupt bytes must construct a lazy handle; the decode error only
surfaces on first access (the processor wraps it as a 422)."""
audio_io = AudioMediaIO()
lazy = audio_io.load_bytes_lazy(b"garbage-not-audio")
assert not lazy.is_decoded
with pytest.raises(ValueError, match="Invalid or corrupted audio data"):
_ = lazy.media


def test_audio_media_io_load_base64_lazy(dummy_audio_bytes, monkeypatch):
"""The lazy base64 variant keeps the encoded-size guard eager and decodes
to the same samples as load_base64."""
encoded = base64.b64encode(dummy_audio_bytes).decode("utf-8")
audio_io = AudioMediaIO()

lazy = audio_io.load_base64_lazy("audio/wav", encoded)
assert not lazy.is_decoded
ref_audio, ref_sr = audio_io.load_base64("audio/wav", encoded)
audio, sr = lazy.media
assert sr == ref_sr
np.testing.assert_array_equal(ref_audio, audio)

monkeypatch.setattr(audio_io, "get_max_bytes", lambda: 4)
with pytest.raises(VLLMValidationError, match="Maximum file size exceeded"):
audio_io.load_base64_lazy("audio/wav", encoded)


def test_audio_media_io_load_file_lazy(audio_assets: AudioTestAssets, monkeypatch):
"""The lazy file variant keeps the size guard eager (rejecting before the
read) and decodes to the same samples as load_file."""
audio_io = AudioMediaIO()
path = audio_assets[0].get_local_path()

lazy = audio_io.load_file_lazy(path)
assert not lazy.is_decoded
ref_audio, ref_sr = audio_io.load_file(path)
audio, sr = lazy.media
assert sr == ref_sr
np.testing.assert_array_equal(ref_audio, audio)

monkeypatch.setattr(audio_io, "get_max_bytes", lambda: 4)
with pytest.raises(VLLMValidationError, match="Maximum file size exceeded"):
audio_io.load_file_lazy(path)


def test_audio_lazy_item_flows_through_parse_resample(dummy_audio_bytes):
"""A lazy item from AudioMediaIO must pass through the parser undecoded,
with resampling stacked onto the decode."""
from vllm.multimodal.parse import MultiModalDataParser

audio_io = AudioMediaIO()
parser = MultiModalDataParser(target_sr=8000, target_channels=1)

lazy = audio_io.load_bytes_lazy(dummy_audio_bytes)
items = parser.parse_mm_data({"audio": [lazy]})["audio"]
assert not lazy.is_decoded

ref_items = parser.parse_mm_data(
{"audio": [audio_io.load_bytes(dummy_audio_bytes)]}
)["audio"]
np.testing.assert_array_equal(items.get(0), ref_items.get(0))


@pytest.mark.parametrize("backend", ["soundfile", "pyav", "torchcodec"])
def test_load_audio_backend_matches_default(backend, dummy_audio_bytes):
"""Every explicit backend must decode to the same samples as `auto`."""
Expand Down
Loading
Loading