[multimodal] Make PyNvVideoCodec decoder concurrency configurable (#49753)

Signed-off-by: Brandon Pelfrey <bpelfrey@nvidia.com>
Co-authored-by: OpenAI Codex <noreply@openai.com>
This commit is contained in:
Brandon Pelfrey
2026-07-24 23:31:41 -07:00
committed by GitHub
co-authored by OpenAI Codex
parent 0ba2aa35a8
commit 94682b79f4
7 changed files with 189 additions and 23 deletions
+49 -8
View File
@@ -157,19 +157,43 @@ def reserve_mm_ipc_gpu_memory(
mm_config: "MultiModalConfig | None",
api_process_count: int = 1,
) -> int:
"""Carve frontend multimodal GPU memory out of the KV cache.
"""Return KV-cache memory remaining after frontend multimodal reservations.
Raw decoded frames are bounded by ``mm_ipc_gpu_memory_gb`` and acquired by
the frontend semaphore. Some decoders also keep persistent surfaces around;
reserve a fixed upper bound for those when a GPU backend is configured.
The reservation covers:
* The total ``mm_ipc_gpu_memory_gb`` budget for transient decoded-frame
buffers. This budget is divided among API processes, so it is not
multiplied by ``api_process_count``.
* For GPU video backends, a fixed upper bound for each API process's
retained decoder surfaces and CUDA context. The PyNvVideoCodec surface
reservation scales with its configured ``hw_decoders`` value, and the
entire decoder reservation scales with ``api_process_count`` because
these resources are not shared between processes.
Args:
available_kv_cache_memory_bytes: KV-cache capacity before reserving
memory for frontend multimodal processing.
mm_config: Multimodal configuration, or ``None`` when multimodal
processing is disabled.
api_process_count: Number of frontend API processes sharing the GPU.
Values below one are treated as one.
Returns:
KV-cache capacity after subtracting the frontend reservation.
Raises:
ValueError: If the reservation leaves no memory for the KV cache.
"""
if mm_config is None:
return available_kv_cache_memory_bytes
from vllm import envs
from vllm.multimodal.video import (
PYNVVIDEOCODEC_CUDA_CONTEXT_BYTES,
PYNVVIDEOCODEC_DECODER_GPU_MEMORY_BYTES,
PYNVVIDEOCODEC_MAX_RETAINED_DECODERS,
PYNVVIDEOCODEC_DEFAULT_HW_DECODERS,
PYNVVIDEOCODEC_VIDEO_BACKEND,
validate_pynvvideocodec_hw_decoders,
)
raw_frame_reserved_bytes = int(mm_config.mm_ipc_gpu_memory_gb * GiB_bytes)
@@ -177,8 +201,24 @@ def reserve_mm_ipc_gpu_memory(
# context on the GPU, outside the worker memory pool. Reserve that footprint
# per process so gpu_memory_utilization bounds total GPU usage across them.
num_api_servers = max(1, api_process_count)
video_kwargs = mm_config.media_io_kwargs.get("video", {})
video_loader_backend = (
video_kwargs.get("video_backend") or envs.VLLM_VIDEO_LOADER_BACKEND
)
codec_backend = video_kwargs.get("backend")
uses_pynvvideocodec = (
video_loader_backend == PYNVVIDEOCODEC_VIDEO_BACKEND
or codec_backend == PYNVVIDEOCODEC_VIDEO_BACKEND
)
hw_decoders = (
validate_pynvvideocodec_hw_decoders(
video_kwargs.get("hw_decoders", PYNVVIDEOCODEC_DEFAULT_HW_DECODERS)
)
if uses_pynvvideocodec
else 1
)
per_server_decoder_bytes = (
PYNVVIDEOCODEC_DECODER_GPU_MEMORY_BYTES * PYNVVIDEOCODEC_MAX_RETAINED_DECODERS
PYNVVIDEOCODEC_DECODER_GPU_MEMORY_BYTES * hw_decoders
+ PYNVVIDEOCODEC_CUDA_CONTEXT_BYTES
)
decoder_reserved_bytes = (
@@ -198,8 +238,9 @@ def reserve_mm_ipc_gpu_memory(
f"({format_gib(raw_frame_reserved_bytes)} GiB raw-frame budget, "
f"{format_gib(decoder_reserved_bytes)} GiB decoder cache budget), "
f"but only {format_gib(available_kv_cache_memory_bytes)} GiB is "
"available for the KV cache. Reduce mm_ipc_gpu_memory_gb, use a "
"different video backend, or increase gpu_memory_utilization."
"available for the KV cache. Reduce mm_ipc_gpu_memory_gb or "
"hw_decoders, use a different video backend, or increase "
"gpu_memory_utilization."
)
logger.info_once(
"Reserving %s GiB of GPU memory for frontend multimodal decoding "
+4
View File
@@ -32,6 +32,10 @@ class VideoMediaIO(MediaIO[tuple[npt.NDArray, dict[str, Any]]]):
runtime_kwargs: dict[str, Any] | None,
) -> dict[str, Any]:
if runtime_kwargs:
# Decoder GPU memory is reserved from the startup value.
runtime_kwargs = dict(runtime_kwargs)
runtime_kwargs.pop("hw_decoders", None)
# Block request-level selection of GPU video backends that
# were not configured (and VRAM-reserved) at startup.
for key in ("video_backend", "backend"):
+33 -3
View File
@@ -210,15 +210,25 @@ class VideoLoader:
VIDEO_LOADER_REGISTRY = VideoLoaderRegistry()
PYNVVIDEOCODEC_VIDEO_BACKEND: Literal["pynvvideocodec"] = "pynvvideocodec"
# Fixed upper bound reserved for persistent PyNvVideoCodec decoder surfaces.
# Per-decoder upper bound reserved for persistent PyNvVideoCodec surfaces.
PYNVVIDEOCODEC_DECODER_GPU_MEMORY_BYTES = 128 * MiB_bytes
PYNVVIDEOCODEC_DECODER_CACHE_SIZE = 2
PYNVVIDEOCODEC_MAX_RETAINED_DECODERS = 1
PYNVVIDEOCODEC_DEFAULT_HW_DECODERS = 2
# Per-API-server CUDA context and driver allocation, measured with
# PyNvVideoCodec 2.0.4 on H100.
PYNVVIDEOCODEC_CUDA_CONTEXT_BYTES = int(1.8 * 1024 * MiB_bytes)
def validate_pynvvideocodec_hw_decoders(hw_decoders: object) -> int:
if (
isinstance(hw_decoders, bool)
or not isinstance(hw_decoders, int)
or hw_decoders < 1
):
raise ValueError("hw_decoders must be a positive integer")
return hw_decoders
class PyNvVideoCodecDecoderSlot:
"""A retained PyNv decoder slot and its CUDA stream.
@@ -628,6 +638,7 @@ class PyNvVideoCodecVideoBackendMixin:
_decoder_slots: ClassVar[list[PyNvVideoCodecDecoderSlot]] = []
_active_decoder_slots: ClassVar[int] = 0
_decoder_slot_cond: ClassVar[threading.Condition] = threading.Condition()
_max_decoder_slots: ClassVar[int | None] = None
_DEVICE_INDEX: ClassVar[int] = 0
@classmethod
@@ -651,6 +662,18 @@ class PyNvVideoCodecVideoBackendMixin:
return PyNvVideoCodecDecoderSlot(torch.cuda.Stream(device=cls._DEVICE_INDEX))
@classmethod
def _configure_decoder_slots(cls, hw_decoders: object) -> None:
hw_decoders = validate_pynvvideocodec_hw_decoders(hw_decoders)
with cls._decoder_slot_cond:
if cls._max_decoder_slots is None:
cls._max_decoder_slots = hw_decoders
elif cls._max_decoder_slots != hw_decoders:
raise RuntimeError(
"PyNvVideoCodec decoder count is already configured as "
f"{cls._max_decoder_slots}, got {hw_decoders}"
)
@staticmethod
@contextmanager
def _torch_stream_context(stream):
@@ -669,11 +692,14 @@ class PyNvVideoCodecVideoBackendMixin:
def _borrow_decoder_slot(cls):
create_slot = False
with cls._decoder_slot_cond:
max_decoder_slots = cls._max_decoder_slots
if max_decoder_slots is None:
raise RuntimeError("PyNvVideoCodec decoder slots are not configured")
while True:
if cls._decoder_slots:
slot = cls._decoder_slots.pop()
break
if cls._active_decoder_slots < PYNVVIDEOCODEC_MAX_RETAINED_DECODERS:
if cls._active_decoder_slots < max_decoder_slots:
cls._active_decoder_slots += 1
create_slot = True
break
@@ -999,6 +1025,7 @@ class VideoBackend(
] = "opencv",
num_ffmpeg_threads: int = 0,
seek_mode: Literal["exact", "approximate"] = "exact",
hw_decoders: int = PYNVVIDEOCODEC_DEFAULT_HW_DECODERS,
**kwargs,
) -> tuple[npt.NDArray, dict[str, Any]]:
"""Load sampled frames from raw video bytes.
@@ -1025,6 +1052,8 @@ class VideoBackend(
at the cost of relying on the file's metadata. See
https://meta-pytorch.org/torchcodec/stable/generated_examples/decoding/approximate_mode.html
for details.
hw_decoders: Maximum number of concurrent PyNvVideoCodec decoder
slots. Defaults to 2 and must be a positive integer.
Returns:
Tuple of ``(frames_array, metadata_dict)``.
@@ -1088,6 +1117,7 @@ class VideoBackend(
"frame_recovery is not supported for "
f"`{PYNVVIDEOCODEC_VIDEO_BACKEND}` backend"
)
cls._configure_decoder_slots(hw_decoders)
frames, source, frame_idx, valid = cls.decode_frames_pynvvideocodec(
data,
target,