Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
38 changes: 38 additions & 0 deletions docs/features/multimodal_inputs.md
Original file line number Diff line number Diff line change
Expand Up @@ -816,6 +816,44 @@ Full example: [examples/generate/multimodal/openai_chat_completion_client_for_mu
export VLLM_VIDEO_FETCH_TIMEOUT=<timeout>
```

#### Video Decoding Backend

vLLM decodes video bytes into frames using a selectable decoding backend. Three
backends are supported:

- `opencv` (default): OpenCV-based decoder.
- `pyav`: PyAV decoder.
- `torchcodec`: TorchCodec (PyTorch-native) decoder.

All three backends are ultimately backed by FFmpeg. `torchcodec` lets
you choose which FFmpeg version is used while `opencv` and `pyav` rely on
whichever FFmpeg build they were linked against.

Select the backend by passing the `backend` parameter via `--media-io-kwargs`:

```bash
vllm serve Qwen/Qwen3-VL-30B-A3B-Instruct \
--media-io-kwargs '{"video": {"backend": "torchcodec"}}'
```

**TorchCodec-specific parameters:**

The following parameters only apply to the `torchcodec` backend:

- `num_ffmpeg_threads`: Number of FFmpeg decoding threads. `0` (default) relies
on the FFmpeg default, which is `min(cpu_count + 1, 16)`. This allows you to
control thread over-subscription.
- `seek_mode`: Seek mode for the decoder. `"exact"` (default) guarantees
frame-accurate sampling by scanning the file when the decoder is created.
`"approximate"` skips that scan for faster decoder creation, at the cost of
relying on the file's metadata (which may yield less accurate seeking).

```bash
# Example: TorchCodec with approximate seek mode and 4 FFmpeg threads
vllm serve Qwen/Qwen3-VL-30B-A3B-Instruct \
--media-io-kwargs '{"video": {"backend": "torchcodec", "seek_mode": "approximate", "num_ffmpeg_threads": 4}}'
```

#### Video Frame Recovery

For improved robustness when processing potentially corrupted or truncated video files, vLLM supports optional frame recovery using a dynamic window forward-scan approach. When enabled, if a target frame fails to load during sequential reading, the next successfully grabbed frame (before the next target frame) will be used in its place.
Expand Down
3 changes: 3 additions & 0 deletions requirements/cpu.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ torchaudio; platform_machine != "s390x" and platform_machine != "riscv64"
# required for the image processor of phi3v, this must be updated alongside torch
torchvision; platform_machine != "s390x" and platform_machine != "riscv64"

# required for the torchcodec video decoding backend
torchcodec >= 0.14; platform_machine != "s390x" and platform_machine != "riscv64" and platform_machine != "ppc64le"

# Intel Extension for PyTorch, only for x86_64 CPUs
intel-openmp==2024.2.1; platform_machine == "x86_64"

Expand Down
1 change: 1 addition & 0 deletions requirements/cuda.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ torch==2.11.0
torchaudio==2.11.0
# These must be updated alongside torch
torchvision==0.26.0 # Required for phi3v processor. See https://github.com/pytorch/vision?tab=readme-ov-file#installation for corresponding version
torchcodec >= 0.14
PyNvVideoCodec==2.1.0
# FlashInfer should be updated together with the Dockerfile
flashinfer-python==0.6.13
Expand Down
2 changes: 2 additions & 0 deletions requirements/test/cpu.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1133,6 +1133,8 @@ torchaudio==2.11.0+cpu
# -r requirements/test/cuda.in
# encodec
# vocos
torchcodec==0.14.0+cpu
# via -r requirements/test/cuda.in
torchvision==0.26.0+cpu
# via
# -r requirements/test/cuda.in
Expand Down
1 change: 1 addition & 0 deletions requirements/test/cuda.in
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pytest-cov
# testing utils
albumentations # required for Nemotron Parse in test_common.py
av # required for audio_in_video tests
torchcodec >= 0.14 # required for torchcodec video backend tests
backoff # required for phi4mm test
blobfile # required for kimi-vl test
httpx
Expand Down
4 changes: 4 additions & 0 deletions requirements/test/cuda.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1232,6 +1232,10 @@ torchaudio==2.11.0+cu130
# -r requirements/test/cuda.in
# encodec
# vocos
torchcodec==0.14.0+cu130
# via
# -c requirements/cuda.txt
# -r requirements/test/cuda.in
torchvision==0.26.0+cu130
# via
# -c requirements/cuda.txt
Expand Down
1 change: 1 addition & 0 deletions requirements/xpu.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ numba == 0.65.0 # Required for N-gram speculative decoding
torch==2.12.0
torchaudio
torchvision
torchcodec >= 0.14 # Required for the torchcodec video decoding backend

auto_round_lib>=0.13.3
vllm_xpu_kernels @ https://github.com/vllm-project/vllm-xpu-kernels/releases/download/v0.1.10.1/vllm_xpu_kernels-0.1.10.1-cp38-abi3-manylinux_2_28_x86_64.whl
150 changes: 150 additions & 0 deletions tests/multimodal/test_video.py
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,118 @@ def test_pyav_backend_returns_target_frames_not_keyframes():
)


# ============================================================================
# TorchCodec Backend Tests
# ============================================================================


def test_torchcodec_backend_loads_frames(
dummy_video_path, monkeypatch: pytest.MonkeyPatch
):
"""Test that the torchcodec codec backend can load frames."""
pytest.importorskip("torchcodec")
with monkeypatch.context() as m:
m.setenv("VLLM_VIDEO_LOADER_BACKEND", "opencv")

with open(dummy_video_path, "rb") as f:
video_data = f.read()

loader = VIDEO_LOADER_REGISTRY.load("opencv")
frames, metadata = loader.load_bytes(
video_data, num_frames=8, backend="torchcodec"
)

assert frames.ndim == 4
assert frames.shape[3] == 3 # RGB
assert frames.shape[0] == 8
assert frames.shape[0] == len(metadata["frames_indices"])
assert metadata["video_backend"] == "torchcodec"
assert "total_num_frames" in metadata
assert "fps" in metadata
assert "duration" in metadata


def test_torchcodec_dynamic_backend_loads_frames(
dummy_video_path, monkeypatch: pytest.MonkeyPatch
):
"""Test that the torchcodec codec with dynamic sampling can load frames."""
pytest.importorskip("torchcodec")
with monkeypatch.context() as m:
m.setenv("VLLM_VIDEO_LOADER_BACKEND", "opencv_dynamic")

with open(dummy_video_path, "rb") as f:
video_data = f.read()

loader = VIDEO_LOADER_REGISTRY.load("opencv_dynamic")
frames, metadata = loader.load_bytes(
video_data, fps=2, max_duration=10, backend="torchcodec"
)

assert frames.ndim == 4
assert frames.shape[3] == 3 # RGB
assert frames.shape[0] > 0
assert frames.shape[0] == len(metadata["frames_indices"])
assert metadata["video_backend"] == "torchcodec_dynamic"


def test_torchcodec_backend_rejects_frame_recovery(dummy_video_path):
"""frame_recovery is OpenCV-only; torchcodec must reject it."""
pytest.importorskip("torchcodec")
with open(dummy_video_path, "rb") as f:
video_data = f.read()

loader = VIDEO_LOADER_REGISTRY.load("opencv")
with pytest.raises(AssertionError):
loader.load_bytes(
video_data, num_frames=8, backend="torchcodec", frame_recovery=True
)


def test_torchcodec_backend_returns_target_frames_not_keyframes():
"""Regression test: torchcodec must return the requested frames, not the
GOP keyframe they seek back to.

Mirrors ``test_pyav_backend_returns_target_frames_not_keyframes``: a long
GOP (single keyframe at frame 0) with a per-frame green-channel marker.
With ``seek_mode="exact"`` torchcodec resolves each index to the exact
frame, so the returned markers must be distinct, ordered, and match the
requested indices.
"""
pytest.importorskip("torchcodec")
num_frames = 50
num_sampled = 4
height, width = 64, 64

video_bytes = create_long_gop_video(
num_frames=num_frames, width=width, height=height
)

loader = VIDEO_LOADER_REGISTRY.load("opencv")
frames, metadata = loader.load_bytes(
video_bytes, num_frames=num_sampled, backend="torchcodec"
)
assert frames.shape == (num_sampled, height, width, 3)

requested = list(metadata["frames_indices"])
assert len(requested) == num_sampled

actual = [int(f[height // 2, width // 2, 1]) for f in frames]

assert len(set(actual)) == num_sampled, (
f"torchcodec returned only {len(set(actual))} distinct frames for "
f"{num_sampled} requested indices: markers={actual}, "
f"requested={requested}. Keyframe-snap regression."
)

assert actual == sorted(actual), f"Returned frames out of order: markers={actual}"

for marker, want_idx in zip(actual, requested):
assert abs(marker - want_idx) <= 10, (
f"Frame mismatch: requested index {want_idx}, "
f"got marker {marker} (tolerance ±10)"
)


@pytest.mark.parametrize(
"loader_key, kwargs, expected_num_frames",
[
Expand Down Expand Up @@ -854,6 +966,42 @@ def test_pyav_backend_returns_target_frames_not_keyframes():
120,
id="glm46v-pyav-60s",
),
# uniform sampling + torchcodec codec (same frame counts as opencv)
pytest.param(
"opencv",
{"num_frames": 32, "backend": "torchcodec"},
32,
id="torchcodec-num_frames",
),
pytest.param(
"opencv", {"fps": 2, "backend": "torchcodec"}, 120, id="torchcodec-fps"
),
pytest.param(
"opencv",
{"num_frames": 500, "fps": 2, "backend": "torchcodec"},
120,
id="torchcodec-num_frames_wins_fps",
),
# dynamic sampling + torchcodec codec
pytest.param(
"opencv_dynamic",
{"fps": 1, "max_duration": 60, "backend": "torchcodec"},
60,
id="torchcodec_dynamic-within_max_duration",
),
pytest.param(
"opencv_dynamic",
{"fps": 2, "max_duration": 30, "backend": "torchcodec"},
60,
id="torchcodec_dynamic-exceeds_max_duration",
),
# glm46v dynamic FPS + torchcodec codec
pytest.param(
"glm46v",
{"backend": "torchcodec"},
120,
id="glm46v-torchcodec-60s",
),
],
)
def test_video_loader_frames_sampling(
Expand All @@ -864,6 +1012,8 @@ def test_video_loader_frames_sampling(
expected_num_frames: int,
):
"""Test video loader frames sampling functionality."""
if kwargs.get("backend") == "torchcodec":
pytest.importorskip("torchcodec")
monkeypatch.setenv("VLLM_VIDEO_LOADER_BACKEND", loader_key)
loader = VIDEO_LOADER_REGISTRY.load(loader_key)

Expand Down
Loading
Loading