# SPDX-FileCopyrightText: Copyright (c) 2024-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import concurrent.futures import contextlib import copy import hashlib import json import math import os import random import re import shutil import string import threading import time import traceback import uuid from typing import List, Optional import numpy import torch import torchvision.transforms.functional as TF from filelock import FileLock from PIL import Image, ImageDraw, ImageFont from common.chunk_info import ChunkInfo from common.logger import TimeMeasure, logger from common.service_exception import ServiceException from models.base_vlm_model import ( BaseVlmModel, InputConfig, VlmGenerationConfig, VlmModelOutput, ) from models.vllm_compatible.adaptive_preprocess_limiter import ( AdaptivePreprocessConfig, AdaptivePreprocessLimiter, PreprocessAdmissionTimeout, ) from utils.env_validation import get_video_pruning_rate, get_vllm_mm_tensor_ipc _RTVI_VLLM_ENV_ALIASES = { "VLLM_GPU_MEMORY_UTILIZATION": "RTVI_VLLM_GPU_MEMORY_UTILIZATION", "VLLM_MAX_NUM_BATCHED_TOKENS": "RTVI_VLLM_MAX_NUM_BATCHED_TOKENS", "VLLM_ENABLE_PREFIX_CACHING": "RTVI_VLLM_ENABLE_PREFIX_CACHING", "VLLM_ENFORCE_EAGER": "RTVI_VLLM_ENFORCE_EAGER", "VLLM_CUDAGRAPH_MODE": "RTVI_VLLM_CUDAGRAPH_MODE", "VLLM_DISABLE_MM_PREPROCESSOR_CACHE": "RTVI_VLLM_DISABLE_MM_PREPROCESSOR_CACHE", "VLLM_MM_PROCESSOR_CACHE_GB": "RTVI_VLLM_MM_PROCESSOR_CACHE_GB", "VLLM_MM_PROCESSOR_CACHE_TYPE": "RTVI_VLLM_MM_PROCESSOR_CACHE_TYPE", "VLLM_MM_ENCODER_ATTN_BACKEND": "RTVI_VLLM_MM_ENCODER_ATTN_BACKEND", "VLLM_MM_TENSOR_IPC": "RTVI_VLLM_MM_TENSOR_IPC", "VLLM_MULTIMODAL_TENSOR_IPC": "RTVI_VLLM_MULTIMODAL_TENSOR_IPC", "VLLM_MOE_BACKEND": "RTVI_VLLM_MOE_BACKEND", "VLLM_IGNORE_EOS": "RTVI_VLLM_IGNORE_EOS", "VLLM_MM_PROCESSOR_VIDEO_NUM_FRAMES": "RTVI_VLLM_MM_PROCESSOR_VIDEO_NUM_FRAMES", "VLLM_ATTENTION_BACKEND": "RTVI_VLLM_ATTENTION_BACKEND", "VLLM_DEFAULT_REPETITION_PENALTY": "RTVI_VLLM_DEFAULT_REPETITION_PENALTY", "VLLM_DEFAULT_TOP_K": "RTVI_VLLM_DEFAULT_TOP_K", "VLLM_KV_CACHE_DTYPE": "RTVI_VLLM_KV_CACHE_DTYPE", "VLLM_KV_CACHE_MEMORY_BYTES": "RTVI_VLLM_KV_CACHE_MEMORY_BYTES", "VLLM_LIMIT_MM_PER_PROMPT_IMAGE": "RTVI_VLLM_LIMIT_MM_PER_PROMPT_IMAGE", "VLLM_LIMIT_MM_PER_PROMPT_VIDEO": "RTVI_VLLM_LIMIT_MM_PER_PROMPT_VIDEO", "VLLM_LIMIT_MM_PER_PROMPT_AUDIO": "RTVI_VLLM_LIMIT_MM_PER_PROMPT_AUDIO", "VLLM_MAX_NUM_SEQS": "RTVI_VLLM_MAX_NUM_SEQS", "VLLM_MULTI_IMAGE_CHUNK_INPUT": "RTVI_VLLM_MULTI_IMAGE_CHUNK_INPUT", "VLLM_NO_REPEAT_NGRAM_SIZE": "RTVI_VLLM_NO_REPEAT_NGRAM_SIZE", "VLLM_NUM_SCHEDULER_STEPS": "RTVI_VLLM_NUM_SCHEDULER_STEPS", "VLLM_NUM_PREPROCESS_WORKERS": "RTVI_VLLM_NUM_PREPROCESS_WORKERS", "VLLM_EVS_SIMILARITY_THRESHOLD": "RTVI_VLLM_EVS_SIMILARITY_THRESHOLD", "VLLM_RAW_IMAGE_TENSOR_INPUT": "RTVI_VLLM_RAW_IMAGE_TENSOR_INPUT", "VLLM_ROOT": "RTVI_VLLM_ROOT", } _DEFAULT_VLLM_NUM_PREPROCESS_WORKERS = 16 _VLLM_CUDAGRAPH_MODES = frozenset( {"NONE", "PIECEWISE", "FULL", "FULL_DECODE_ONLY", "FULL_AND_PIECEWISE"} ) # Legacy admission serializes frontend preprocessing so transient allocations do not overlap. _LEGACY_MAX_CONCURRENT_CUDA_MM_PREPROCESS = 1 # Keep at most one c128 2K-equivalent wave of CUDA-IPC multimodal inputs resident # until EngineCore produces the first output (which proves encoder consumption). # A 4K request consumes two units and an 8K request four, so the residency limits # become 64 and 32 respectively without changing the logical 128-request queue. _MAX_RESIDENT_CUDA_MM_2K_EQUIVALENT_UNITS = 128 _CUDA_MM_2K_REFERENCE_FRAMES = 10 _BLANK_DEFAULT_VLLM_IMPORT_ENV_VARS = ( "VLLM_CONFIGURE_LOGGING", "VLLM_LOGGING_LEVEL", "VLLM_NVFP4_GEMM_BACKEND", ) def _is_cuda_oom_error(error: object) -> bool: oom_error_type = getattr(torch, "OutOfMemoryError", None) return ( oom_error_type is not None and isinstance(error, oom_error_type) ) or "CUDA out of memory" in str(error) def _get_rtvi_vllm_env(name: str, default: str | None = None) -> str | None: alias = _RTVI_VLLM_ENV_ALIASES.get(name) if alias and alias in os.environ: return os.environ[alias] return os.environ.get(name, default) def _sanitize_rtvi_vllm_env() -> None: """Hide or normalize env values that vLLM reads during import.""" blank_native = [] for name in _BLANK_DEFAULT_VLLM_IMPORT_ENV_VARS: value = os.environ.get(name) if value is not None and not value.strip(): os.environ.pop(name, None) blank_native.append(name) moved = [] for source, target in _RTVI_VLLM_ENV_ALIASES.items(): value = os.environ.pop(source, None) if value is None: continue if target not in os.environ: os.environ[target] = value moved.append(source) if blank_native: logger.debug( "Unset blank vLLM import env vars before vLLM import: %s", ", ".join(sorted(blank_native)), ) if moved: logger.debug( "Moved RTVI-owned vLLM env aliases before vLLM import: %s", ", ".join(sorted(moved)), ) def _parse_int_env(name: str, default: int) -> int: value = _get_rtvi_vllm_env(name, "") or "" if not value.strip(): return default try: return int(value) except ValueError: raise ValueError(f"Invalid value for {name}: '{value}' is not a valid integer") def _parse_nonnegative_int_env(name: str, default: int) -> int: parsed = _parse_int_env(name, default) if parsed < 0: raise ValueError(f"Invalid value for {name}: '{parsed}' must be greater than or equal to 0") return parsed def _parse_mm_limit_env(name: str, nim_alias: str, default: int) -> int: """Parse a vLLM multimodal limit, accepting NIM's equivalent env name.""" if (_get_rtvi_vllm_env(name, "") or "").strip(): return _parse_nonnegative_int_env(name, default) nim_value = os.environ.get(nim_alias, "") or "" if not nim_value.strip(): return default try: parsed = int(nim_value) except ValueError as exc: raise ValueError( f"Invalid value for {nim_alias}: '{nim_value}' is not a valid integer" ) from exc if parsed < 0: raise ValueError( f"Invalid value for {nim_alias}: '{parsed}' must be greater than or equal to 0" ) return parsed def _get_limit_mm_per_prompt(vlm_supports_audio: bool) -> dict[str, int]: """Build vLLM multimodal count limits while preserving RTVI defaults.""" limit_mm_per_prompt = { "image": _parse_mm_limit_env( "VLLM_LIMIT_MM_PER_PROMPT_IMAGE", "NIM_MAX_IMAGES_PER_PROMPT", 1 ), "video": _parse_mm_limit_env( "VLLM_LIMIT_MM_PER_PROMPT_VIDEO", "NIM_MAX_VIDEOS_PER_PROMPT", 1 ), } if vlm_supports_audio: limit_mm_per_prompt["audio"] = _parse_nonnegative_int_env( "VLLM_LIMIT_MM_PER_PROMPT_AUDIO", 1 ) return limit_mm_per_prompt def _get_default_top_k() -> int: """Service-level default top-k for requests that use RTVI's config default.""" return _parse_nonnegative_int_env("VLLM_DEFAULT_TOP_K", VlmGenerationConfig.top_k) def _get_default_repetition_penalty() -> float: """Service-level default repetition penalty for RTVI-defaulted requests.""" return _parse_float_env( "VLLM_DEFAULT_REPETITION_PENALTY", VlmGenerationConfig.repetition_penalty, ) def _get_no_repeat_ngram_size() -> int: """CR2/CR3 no-repeat-ngram default; set 0 to match vanilla vLLM/NIM.""" return _parse_nonnegative_int_env("VLLM_NO_REPEAT_NGRAM_SIZE", 3) def _resolve_sampling_top_k(config: VlmGenerationConfig) -> int: if config.top_k == VlmGenerationConfig.top_k: return _get_default_top_k() return int(config.top_k) def _resolve_repetition_penalty(config: VlmGenerationConfig) -> float: if config.repetition_penalty == VlmGenerationConfig.repetition_penalty: return _get_default_repetition_penalty() return float(config.repetition_penalty) def _parse_optional_int_env(name: str) -> int | None: value = _get_rtvi_vllm_env(name, "") or "" if not value.strip(): return None try: parsed = int(value) except ValueError as exc: raise ValueError(f"Invalid value for {name}: '{value}' is not a valid integer") from exc if parsed < 0: raise ValueError(f"Invalid value for {name}: '{value}' must be greater than or equal to 0") return parsed def _get_num_preprocess_workers() -> int: num_workers = _parse_int_env( "VLLM_NUM_PREPROCESS_WORKERS", _DEFAULT_VLLM_NUM_PREPROCESS_WORKERS, ) if num_workers < 1: raise ValueError( f"Invalid value for VLLM_NUM_PREPROCESS_WORKERS: " f"'{num_workers}' must be greater than or equal to 1" ) return num_workers def _get_vllm_compilation_config( model_architecture: str, vlm_model_type: str = "", enforce_eager: bool = False, ) -> dict[str, object] | None: raw_mode = (_get_rtvi_vllm_env("VLLM_CUDAGRAPH_MODE", "") or "").strip() stabilize_cr3 = ( not enforce_eager and vlm_model_type == "cosmos-reason3" and model_architecture in _QWEN3VL_ARCHS ) if not raw_mode: if _is_cosmos3_edge_arch(model_architecture): return { "mode": "VLLM_COMPILE", "cudagraph_mode": "PIECEWISE", } if stabilize_cr3: return { "inductor_compile_config": { "combo_kernels": True, "benchmark_combo_kernel": False, }, } return None cudagraph_mode = raw_mode.upper() if cudagraph_mode not in _VLLM_CUDAGRAPH_MODES: supported = ", ".join(sorted(_VLLM_CUDAGRAPH_MODES)) raise ValueError( f"Invalid value for VLLM_CUDAGRAPH_MODE: '{raw_mode}'; " f"expected one of: {supported}" ) config: dict[str, object] = { "mode": "VLLM_COMPILE", "cudagraph_mode": cudagraph_mode, } if stabilize_cr3: config["inductor_compile_config"] = { "combo_kernels": True, "benchmark_combo_kernel": False, } return config def _get_adaptive_preprocess_config() -> AdaptivePreprocessConfig: env_name = "RTVI_VLLM_ADAPTIVE_PREPROCESS" raw_config = (os.environ.get(env_name) or "disabled").strip() executor_max_workers = _get_num_preprocess_workers() mode = raw_config.lower() overrides = {} if raw_config.startswith("{"): try: parsed = json.loads(raw_config) except json.JSONDecodeError as exc: raise ValueError(f"Invalid value for {env_name}: malformed JSON: {exc.msg}") from exc if not isinstance(parsed, dict): raise ValueError(f"Invalid value for {env_name}: JSON value must be an object") mode = parsed.pop("mode", "shadow") if not isinstance(mode, str): raise ValueError(f"Invalid value for {env_name}: 'mode' must be a string") mode = mode.strip().lower() integer_fields = { "min_workers", "max_workers", "gpu_headroom_mb", "initial_estimated_request_mb", "healthy_completions_for_increase", "calibration_samples_required", } number_fields = { "estimate_safety_factor", "admission_timeout_seconds", "estimate_ewma_alpha", "poll_interval_seconds", "scale_up_cooldown_seconds", "scale_up_gpu_utilization_threshold_percent", } unknown_fields = set(parsed) - integer_fields - number_fields if unknown_fields: unknown = ", ".join(sorted(unknown_fields)) raise ValueError(f"Invalid value for {env_name}: unknown field(s): {unknown}") for field in integer_fields & set(parsed): value = parsed[field] if isinstance(value, bool) or not isinstance(value, int): raise ValueError(f"Invalid value for {env_name}: '{field}' must be an integer") for field in number_fields & set(parsed): value = parsed[field] if ( isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) ): raise ValueError(f"Invalid value for {env_name}: '{field}' must be a number") overrides = parsed if mode not in {"disabled", "shadow", "enforced"}: raise ValueError( f"Invalid value for {env_name}: mode must be disabled, shadow, or enforced" ) overrides["max_workers"] = min( overrides.get("max_workers", executor_max_workers), executor_max_workers, ) return AdaptivePreprocessConfig( enabled=mode != "disabled", shadow_mode=mode != "enforced", **overrides, ) def _apply_kv_cache_dtype_override( engine_args_kwargs: dict[str, object], supported_params: set[str], ) -> bool: kv_cache_dtype = (_get_rtvi_vllm_env("VLLM_KV_CACHE_DTYPE", "") or "").strip() if not kv_cache_dtype: return False if "kv_cache_dtype" not in supported_params: logger.warning( "VLLM_KV_CACHE_DTYPE=%s ignored; installed vLLM does not support " "kv_cache_dtype", kv_cache_dtype, ) return False engine_args_kwargs["kv_cache_dtype"] = kv_cache_dtype logger.info("VLLM KV cache dtype override: %s", kv_cache_dtype) return True def _apply_attention_backend_override( engine_args_kwargs: dict[str, object], supported_params: set[str], model_architecture: str = "", ) -> bool: attention_backend = (_get_rtvi_vllm_env("VLLM_ATTENTION_BACKEND", "") or "").strip() if not attention_backend: if not _is_cosmos3_edge_arch(model_architecture): return False attention_backend = "TRITON_ATTN" logger.info("Defaulting Cosmos3 Edge attention backend to %s", attention_backend) if "attention_backend" not in supported_params: logger.warning( "VLLM_ATTENTION_BACKEND=%s ignored; installed vLLM does not support " "attention_backend", attention_backend, ) return False engine_args_kwargs["attention_backend"] = attention_backend logger.info("VLLM attention backend override: %s", attention_backend) return True def _parse_bool_env(name: str, default: bool) -> bool: value = _get_rtvi_vllm_env(name) if value is None: return default return value.strip().lower() in ("1", "true", "yes", "on") def _parse_float_env(name: str, default: float) -> float: value = _get_rtvi_vllm_env(name, "") or "" if not value.strip(): return default try: parsed = float(value) except ValueError as exc: raise ValueError(f"Invalid value for {name}: '{value}' is not a valid float") from exc if parsed < 0: raise ValueError(f"Invalid value for {name}: '{value}' must be greater than or equal to 0") return parsed def _get_evs_token_budget() -> int: """Visual-token budget an EVS session accumulates before forcing generation. Defaults to 1: generate on every clip rather than packing tokens across clips, which keeps caption counts aligned with the non-EVS path. """ value = (os.environ.get("VIA_EVS_TOKEN_BUDGET") or "").strip() return int(value or "1") def _get_evs_similarity_threshold() -> float: """Server default for EVS session-mode cosine-dissimilarity pruning. Read through the alias: _sanitize_rtvi_vllm_env() renames the variable out of the VLLM_ namespace before vLLM is imported, so a raw os.environ lookup here would silently fall back to the default. """ value = (_get_rtvi_vllm_env("VLLM_EVS_SIMILARITY_THRESHOLD", "") or "").strip() return float(value or "0.4") def _get_mm_processor_cache_gb() -> float: if (_get_rtvi_vllm_env("VLLM_MM_PROCESSOR_CACHE_GB", "") or "").strip(): return _parse_float_env("VLLM_MM_PROCESSOR_CACHE_GB", 1.0) return _parse_float_env("VLLM_MM_INPUT_CACHE_GIB", 1.0) def _get_mm_processor_cache_type() -> str: cache_type = ( (_get_rtvi_vllm_env("VLLM_MM_PROCESSOR_CACHE_TYPE", "shm") or "shm").strip().lower() ) if cache_type not in {"lru", "shm"}: raise ValueError( "Invalid value for VLLM_MM_PROCESSOR_CACHE_TYPE: " f"'{cache_type}' must be 'lru' or 'shm'" ) return cache_type def _apply_mm_processor_cache_engine_args( engine_args_kwargs: dict[str, object], supported_params: set[str], ) -> None: """Build the multimodal processor cache engine args for the installed vLLM. vLLM 0.17.1 removed ``disable_mm_preprocessor_cache``, so on that build the only way to keep the engine from creating the cache is the size: ``mm_processor_cache_gb=0``. Leaving it enabled is not equivalent, because the ``shm`` backend unlinks its POSIX object from ``__del__``, which a SIGKILL skips. """ disable_mm_cache = _parse_bool_env( "VLLM_DISABLE_MM_PREPROCESSOR_CACHE", default=True, ) if "disable_mm_preprocessor_cache" in supported_params: engine_args_kwargs["disable_mm_preprocessor_cache"] = disable_mm_cache elif disable_mm_cache: logger.warning( "VLLM_DISABLE_MM_PREPROCESSOR_CACHE=true honored via " "mm_processor_cache_gb=0; installed vLLM does not support " "disable_mm_preprocessor_cache" ) if "mm_processor_cache_gb" in supported_params: engine_args_kwargs["mm_processor_cache_gb"] = ( 0.0 if disable_mm_cache else _get_mm_processor_cache_gb() ) if "mm_processor_cache_type" in supported_params: cache_type = _get_mm_processor_cache_type() engine_args_kwargs["mm_processor_cache_type"] = cache_type logger.info("VLLM MM processor cache type: %s", cache_type) CPU_COPY_OTHER_THREAD = True # Fallback edges for a request that supplies only one half of `size`, per the # NIM docs. Used when the calling path has no `size` default of its own. _NIM_DEFAULT_LONGEST_EDGE = 12845056 _NIM_DEFAULT_SHORTEST_EDGE = 3136 # Preprocessing defaults for the EVS session path. # # No `size` here, matching the regular path: the model's own # video_preprocessor_config.json min/max pixels govern. EVS previously pinned # {longest_edge: 180000000, shortest_edge: 4096}, which was inert — RTVI resizes # frames at decode time (608x320 for CR2/CR3, or VLM_INPUT_WIDTH/HEIGHT), so # neither that bound nor the model's own (25165824 for CR3) is ever reached, and # max_pixels only ever downscales, never upscales. # # `do_sample_frames` must stay False: EVS hands vLLM a frame list paired with # explicit per-frame timestamps, and processor-side resampling would # desynchronise the two. _EVS_MM_PROCESSOR_DEFAULTS = { "do_sample_frames": False, } # Qwen3-VL's video processor rejects a clip shorter than its temporal factor # ("t:1 must be larger than temporal_factor:2" from smart_resize), so an EVS # clip is padded up to this many frames before it is handed to the session. _EVS_MIN_CLIP_FRAMES = 2 _DEFAULT_MAX_VIDEO_FRAMES = "256" def _get_max_video_frames() -> int: """Per-chunk frame cap from ``VLLM_MM_PROCESSOR_VIDEO_NUM_FRAMES``.""" value = _get_rtvi_vllm_env( "VLLM_MM_PROCESSOR_VIDEO_NUM_FRAMES", _DEFAULT_MAX_VIDEO_FRAMES, ) return int(value or _DEFAULT_MAX_VIDEO_FRAMES) def _cap_video_frames(images, video_frames_times, max_frames: int): """Uniformly subsample *images* down to *max_frames*, timestamps in step. fps-based chunking can produce far more frames than the vLLM processor accepts (10 fps x 60 s = 600). Returns the inputs untouched when the clip is already within the cap. ``video_frames_times`` is subsampled with the same indices so each kept frame keeps its own timestamp; passing ``None`` is allowed for callers that have no timestamps. """ if len(images) <= 1 or len(images) <= max_frames: return images, video_frames_times if isinstance(images, torch.Tensor): indices = torch.linspace(0, len(images) - 1, max_frames).long() capped_images = images[indices] index_list = indices.tolist() else: indices = numpy.linspace(0, len(images) - 1, max_frames).astype(int) index_list = indices.tolist() capped_images = ( [images[index] for index in index_list] if isinstance(images, list) else images[indices] ) if video_frames_times is not None: video_frames_times = [video_frames_times[i] for i in index_list] return capped_images, video_frames_times def _frame_batch_as_numpy(images): if isinstance(images, torch.Tensor): return images.cpu().numpy() return numpy.asarray(images) def _merge_mm_processor_kwargs(base: dict, requested: dict | None) -> dict: """Merge a request's ``mm_processor_kwargs`` over a path's defaults. The HF processor needs both edges of ``size``, so a request that names only one gets the other filled in — from *base*'s own ``size`` when it has one, otherwise from the NIM defaults. Neither input is mutated: the request dict belongs to the caller and ``base`` may be a shared module-level default. """ merged = copy.deepcopy(base) if not requested: return merged requested = copy.deepcopy(requested) size = requested.get("size") if isinstance(size, dict): base_size = base.get("size") if isinstance(base.get("size"), dict) else {} if "shortest_edge" in size and "longest_edge" not in size: size["longest_edge"] = base_size.get("longest_edge", _NIM_DEFAULT_LONGEST_EDGE) elif "longest_edge" in size and "shortest_edge" not in size: size["shortest_edge"] = base_size.get("shortest_edge", _NIM_DEFAULT_SHORTEST_EDGE) merged.update(requested) return merged def _freeze_evs_session_config(value): """Return a hashable, stable representation of EVS session config.""" if isinstance(value, dict): return tuple( sorted( (key, _freeze_evs_session_config(nested_value)) for key, nested_value in value.items() ) ) if isinstance(value, (list, tuple)): return tuple(_freeze_evs_session_config(item) for item in value) return value def _evs_session_cache_stream_id(cache_key): """Extract the stream id from new composite or old string cache keys.""" if isinstance(cache_key, tuple) and len(cache_key) == 2: return cache_key[0] return cache_key # Both the EA checkpoint (NemotronH_Nano_VL_V2) and the GA checkpoint # (NemotronH_Nano_Omni_Reasoning_V3) share the same model executor and # require identical special-casing throughout the inference path. _NEMOTRON_OMNI_ARCHS = frozenset({"NemotronH_Nano_VL_V2", "NemotronH_Nano_Omni_Reasoning_V3"}) def _use_raw_image_tensor_input(model_architecture: str | None) -> bool: return ( _parse_bool_env("VLLM_RAW_IMAGE_TENSOR_INPUT", False) and model_architecture not in _NEMOTRON_OMNI_ARCHS ) _QWEN35_ARCHS = frozenset( { "Qwen3_5ForConditionalGeneration", "Qwen3_5MoeForConditionalGeneration", } ) _QWEN3VL_ARCHS = frozenset( { "Qwen3VLForConditionalGeneration", "Qwen3VLMoeForConditionalGeneration", } ) _QWEN3_OMNI_ARCHS = frozenset({"Qwen3OmniMoeForConditionalGeneration"}) _COSMOS3_DIFFUSERS_ARCHS = frozenset({"Cosmos3ForConditionalGeneration"}) _COSMOS3_EDGE_ARCHS = frozenset( { "Cosmos3EdgeForConditionalGeneration", } ) # Synthetic source_fps for absolute-timestamp video metadata: 1000 makes # round(t * fps) / fps reconstruct the real timestamp (ms resolution). _ABSOLUTE_TIMESTAMP_SOURCE_FPS = 1000.0 def _is_evs_session_enabled() -> bool: return os.environ.get("VIA_EVS_SESSION", "").lower() in ("1", "true") def _get_evs_max_inflight_clips() -> int | None: env_name = "VIA_EVS_MAX_INFLIGHT_CLIPS" if not (_get_rtvi_vllm_env(env_name, "") or "").strip(): return None max_inflight = _parse_int_env(env_name, 0) if max_inflight < 1: raise ValueError( "Invalid value for VIA_EVS_MAX_INFLIGHT_CLIPS: " f"'{max_inflight}' must be greater than or equal to 1" ) return max_inflight def _build_evs_sampling_kwargs(max_tokens, generation_config): """Build the kwargs for an EVS session's ``VideoSessionSamplingParams``. The EVS event detector triggers generations server-side with no per-call request body, so the session must carry the same sampling policy the non-EVS path applies. In particular ``VLLM_IGNORE_EOS`` (or a config-level ``ignore_eos``) must be forwarded, otherwise event-gated generations stop at the natural EOS instead of reaching the requested output length (the behavior seen as gen_tokens=2 vs max_tokens under perf/OSL runs). Mirrors the non-EVS sampling-params construction in ``generate``/``generate_stream``. ``ignore_eos`` and ``min_tokens`` are only added when set so omitting them preserves vLLM ``SamplingParams`` defaults after ``model_dump(exclude_none)``. """ def _gc(name, default): if isinstance(generation_config, dict): return generation_config.get(name, default) return getattr(generation_config, name, default) top_k = int(_gc("top_k", VlmGenerationConfig.top_k)) if top_k == VlmGenerationConfig.top_k: top_k = _get_default_top_k() repetition_penalty = float(_gc("repetition_penalty", VlmGenerationConfig.repetition_penalty)) if repetition_penalty == VlmGenerationConfig.repetition_penalty: repetition_penalty = _get_default_repetition_penalty() kwargs = dict( max_tokens=max_tokens, temperature=float(_gc("temperature", 0.4)), top_p=float(_gc("top_p", 0.8)), top_k=top_k, repetition_penalty=repetition_penalty, seed=_gc("seed", 1), ) # Event-gated generations have no request body, so the schema constraint # must ride on the session's sampling policy like everything else here. structured_outputs = _structured_outputs_kwargs(_gc("response_format", None)) env_ignore_eos = _get_rtvi_vllm_env("VLLM_IGNORE_EOS", "false").lower() == "true" cfg_ignore_eos = _gc("ignore_eos", None) if structured_outputs is not None: kwargs["structured_outputs"] = structured_outputs kwargs["ignore_eos"] = False elif env_ignore_eos or cfg_ignore_eos is not None: kwargs["ignore_eos"] = env_ignore_eos or bool(cfg_ignore_eos) min_tokens = _gc("min_tokens", None) if min_tokens is not None: kwargs["min_tokens"] = int(min_tokens) return kwargs def _structured_outputs_kwargs(response_format) -> dict | None: """Map a ``response_format`` to ``StructuredOutputsParams`` kwargs. Returns ``None`` for plain text. Shared by the regular and EVS paths so both constrain decoding the same way. """ response_format = response_format or {} response_type = response_format.get("type") if response_type == "json_object": return {"json_object": True} if response_type == "json_schema": return {"json": response_format["json_schema"]["schema"]} if response_type == "choice": return {"choice": response_format["choices"]} return None def _build_vllm_sampling_kwargs(config: VlmGenerationConfig) -> dict: """Build regular vLLM sampling kwargs without dropping greedy decoding.""" kwargs = { "temperature": config.temperature, "top_p": config.top_p, "top_k": _resolve_sampling_top_k(config), "max_tokens": config.max_new_tokens, "repetition_penalty": _resolve_repetition_penalty(config), "seed": config.seed, } if config.min_tokens is not None: kwargs["min_tokens"] = config.min_tokens structured_outputs = _structured_outputs_kwargs(config.response_format) env_ignore_eos = _get_rtvi_vllm_env("VLLM_IGNORE_EOS", "false").lower() == "true" if structured_outputs is not None: from vllm.sampling_params import StructuredOutputsParams kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs) kwargs["ignore_eos"] = False elif env_ignore_eos or config.ignore_eos is not None: kwargs["ignore_eos"] = env_ignore_eos or bool(config.ignore_eos) return kwargs def _configure_structured_outputs(engine_args_kwargs: dict, supported_params: set[str]) -> None: if "structured_outputs_config" not in supported_params: return from vllm.config import StructuredOutputsConfig engine_args_kwargs["structured_outputs_config"] = StructuredOutputsConfig( backend="xgrammar", disable_fallback=True, disable_any_whitespace=True, ) def _set_cosmos_no_repeat_ngram_size(sampling_params, model_type: str) -> None: no_repeat_ngram_size = _get_no_repeat_ngram_size() if ( no_repeat_ngram_size and model_type in ("cosmos-reason2", "cosmos-reason3") and not getattr(sampling_params, "structured_outputs", None) ): sampling_params.no_repeat_ngram_size = no_repeat_ngram_size # Absolute video metadata changes the temporal positions seen by the model. Keep # it operator-controlled for non-EVS paths, but enable it internally for EVS so # EVS++ keeps the same timestamp behavior as dev/aa/evs. _VIDEO_METADATA_ABSOLUTE_TIMESTAMPS = os.getenv( "RTVI_VIDEO_METADATA_ABSOLUTE_TIMESTAMPS", "" ).lower() in ("1", "true") # Common parameters FACTOR = 28 MAX_PIXELS = 16384 * 2 * FACTOR * FACTOR MIN_PIXELS = 4 * 2 * FACTOR * FACTOR ADD_TIMESTAMP_TO_PROMPT = ( os.environ.get("RTVI_ADD_TIMESTAMP_TO_VLM_PROMPT", "true").lower() == "true" ) # Optional prefix/suffix overrides for the timestamp prompt injected before the # user query. Supported placeholders: {timestamps}, {query}, {first_ts}, {last_ts}. # Separate vars for file and RTSP sources. When unset, the legacy # "These are images sampled from the same video at times ..." format is used. # Applied to any vllm-compatible model (no per-model guard). _TIMESTAMP_PROMPT_ALLOWED_PLACEHOLDERS = frozenset({"timestamps", "query", "first_ts", "last_ts"}) def _validate_timestamp_prompt_template(env_var: str, template: str) -> str: """Validate an operator-supplied timestamp prompt template at load time. Rejects templates with malformed braces or unknown placeholder names so a misconfigured env var fails once at startup instead of raising on every caption request inside ``str.format``. A rejected template is dropped (treated as unset) after logging a warning. """ if not template: return template try: fields = [ field_name for _, field_name, _, _ in string.Formatter().parse(template) if field_name is not None ] except ValueError as exc: logger.warning("Ignoring %s: malformed prompt template %r (%s)", env_var, template, exc) return "" unknown = [ f for f in fields if (f.split(".")[0].split("[")[0] or "") not in _TIMESTAMP_PROMPT_ALLOWED_PLACEHOLDERS ] if unknown: logger.warning( "Ignoring %s: unknown placeholder(s) %s in template %r; allowed: %s", env_var, sorted(set(unknown)), template, sorted(_TIMESTAMP_PROMPT_ALLOWED_PLACEHOLDERS), ) return "" return template _TIMESTAMP_PROMPT_PREFIX_FILE = _validate_timestamp_prompt_template( "RTVI_TIMESTAMP_PROMPT_PREFIX_FILE_SOURCE", os.environ.get("RTVI_TIMESTAMP_PROMPT_PREFIX_FILE_SOURCE", "").strip("\"'"), ) _TIMESTAMP_PROMPT_SUFFIX_FILE = _validate_timestamp_prompt_template( "RTVI_TIMESTAMP_PROMPT_SUFFIX_FILE_SOURCE", os.environ.get("RTVI_TIMESTAMP_PROMPT_SUFFIX_FILE_SOURCE", "").strip("\"'"), ) _TIMESTAMP_PROMPT_PREFIX_RTSP = _validate_timestamp_prompt_template( "RTVI_TIMESTAMP_PROMPT_PREFIX_RTSP_SOURCE", os.environ.get("RTVI_TIMESTAMP_PROMPT_PREFIX_RTSP_SOURCE", "").strip("\"'"), ) _TIMESTAMP_PROMPT_SUFFIX_RTSP = _validate_timestamp_prompt_template( "RTVI_TIMESTAMP_PROMPT_SUFFIX_RTSP_SOURCE", os.environ.get("RTVI_TIMESTAMP_PROMPT_SUFFIX_RTSP_SOURCE", "").strip("\"'"), ) # EVS default timestamp-grounding instruction. This intentionally matches the # dev/aa/evs default, but is applied only when VIA_EVS_SESSION is enabled and no # operator prefix/suffix template is configured for the current source type. _DEFAULT_EVS_TIMESTAMP_INSTRUCTION = ( " IMPORTANT: Frame 1 corresponds to timestamp {first_ts} seconds, and the " "last frame corresponds to timestamp {last_ts} seconds. All timestamps in " "your response MUST be between {first_ts} and {last_ts} seconds. Do NOT use " "timestamps starting from 0. The video segment starts at {first_ts} seconds " "in the original video." ) def _get_timestamp_prompt_templates(is_rtsp: bool, use_evs_default: bool = False): prefix_tpl = _TIMESTAMP_PROMPT_PREFIX_RTSP if is_rtsp else _TIMESTAMP_PROMPT_PREFIX_FILE suffix_tpl = _TIMESTAMP_PROMPT_SUFFIX_RTSP if is_rtsp else _TIMESTAMP_PROMPT_SUFFIX_FILE used_evs_default = False if use_evs_default and not prefix_tpl and not suffix_tpl: suffix_tpl = _DEFAULT_EVS_TIMESTAMP_INSTRUCTION used_evs_default = True return prefix_tpl, suffix_tpl, used_evs_default DEFAULT_SYSTEM_PROMPT_CR1 = ( "Please provide captions of all the events in the video with timestamps using the following format:" " caption of event 1.\n caption of event 2.\n" "At each frame, the timestamp is embedded at the bottom of the video. You need to extract" " the timestamp and answer the user question." ) def start_loop(loop): asyncio.set_event_loop(loop) loop.run_forever() def _is_cosmos3_diffusers_shim_arch(model_architecture: str) -> bool: return model_architecture in _COSMOS3_DIFFUSERS_ARCHS def _is_cosmos3_edge_arch(model_architecture: str) -> bool: return model_architecture in _COSMOS3_EDGE_ARCHS def _build_video_message_content(query_text, vlm_model_type, model_architecture): text = {"type": "text", "text": query_text} video = {"type": "video", "video": "sample.mp4"} if ( vlm_model_type in ("cosmos-reason2", "cosmos-reason3") or model_architecture in _QWEN3VL_ARCHS or _is_cosmos3_edge_arch(model_architecture) ): return [video, text] return [text, video] def _default_mm_processor_kwargs( vlm_model_type: str, model_architecture: str, has_audio: bool, ) -> dict: """Return model-required multimodal processor arguments. Qwen3-Omni's vLLM processor unconditionally reads ``use_audio_in_video`` for every video item. Supplying ``False`` for a video-only request is therefore required, not merely an audio opt-in. """ kwargs = {} if vlm_model_type == "cosmos-reason1": kwargs["chain_of_thought"] = True if model_architecture in _QWEN3_OMNI_ARCHS: kwargs["use_audio_in_video"] = has_audio return kwargs def _uses_cosmos3_vllm_plugin(model_architecture: str) -> bool: return _is_cosmos3_diffusers_shim_arch(model_architecture) or _is_cosmos3_edge_arch( model_architecture ) def _maybe_register_cosmos3_vllm_shim(model_architecture: str) -> bool: if not _uses_cosmos3_vllm_plugin(model_architecture): return False os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0") try: import vllm_cosmos3 vllm_cosmos3.register() except Exception as exc: raise RuntimeError( "Cosmos3 checkpoints require the vllm_cosmos3 shim package. " "Ensure the RTVI VLM image includes src/vllm_cosmos3 from the Cosmos3 " "vLLM shim layer." ) from exc logger.info( "Enabled Cosmos3 vLLM plugin for architecture %s", model_architecture, ) return True def _get_vlm_trust_remote_code(model_architecture: str) -> bool: trust_remote_code = _parse_bool_env("VLM_TRUST_REMOTE_CODE", False) if _uses_cosmos3_vllm_plugin(model_architecture): if not trust_remote_code: logger.info( "Enabling trust_remote_code for Cosmos3 architecture %s", model_architecture, ) return True return trust_remote_code def _cosmos3_edge_cache_module_name(model_path: str) -> str: model_dir_name = os.path.basename(os.path.normpath(model_path)) return model_dir_name.replace("-", "_hyphen_").replace(".", "_dot_") def _clear_cosmos3_edge_transformers_module_cache(model_path: str) -> None: try: from transformers.dynamic_module_utils import HF_MODULES_CACHE except Exception: return module_dir = os.path.join( HF_MODULES_CACHE, "transformers_modules", _cosmos3_edge_cache_module_name(model_path), ) if os.path.isdir(module_dir): shutil.rmtree(module_dir) logger.info("Cleared cached Cosmos3-Edge remote-code module at %s", module_dir) def _patch_cosmos3_edge_modeling_file(model_path: str, model_architecture: str) -> None: if not _is_cosmos3_edge_arch(model_architecture): return modeling_path = os.path.join(model_path, "modeling_nemotron_siglip2_h.py") try: with open(modeling_path, encoding="utf-8") as modeling_file: modeling_source = modeling_file.read() except FileNotFoundError: return updated_source = modeling_source patch_descriptions = [] fallback_marker = "def _rtvi_cosmos3_edge_rmsnorm_fn" old_source = """try: #from mamba_ssm.ops.triton.layernorm_gated import RMSNorm as RMSNormGated from mamba_ssm.ops.triton.layernorm_gated import rmsnorm_fn except ImportError: raise ImportError("mamba-ssm is required by the Mamba model but cannot be imported") """ new_source = """try: #from mamba_ssm.ops.triton.layernorm_gated import RMSNorm as RMSNormGated from mamba_ssm.ops.triton.layernorm_gated import rmsnorm_fn except ImportError: def _rtvi_cosmos3_edge_rmsnorm_fn( x, weight, bias=None, z=None, eps=1e-5, group_size=None, norm_before_gate=False, ): dtype = x.dtype hidden_states = x.float() gate = None if z is None else torch.nn.functional.silu(z.float()) if gate is not None and not norm_before_gate: hidden_states = hidden_states * gate if group_size: original_shape = hidden_states.shape hidden_states = hidden_states.reshape(*original_shape[:-1], -1, group_size) variance = hidden_states.pow(2).mean(dim=-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + eps) hidden_states = hidden_states.reshape(original_shape) else: variance = hidden_states.pow(2).mean(dim=-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + eps) if gate is not None and norm_before_gate: hidden_states = hidden_states * gate hidden_states = hidden_states * weight.float() if bias is not None: hidden_states = hidden_states + bias.float() return hidden_states.to(dtype) rmsnorm_fn = _rtvi_cosmos3_edge_rmsnorm_fn """ if fallback_marker not in updated_source and old_source in updated_source: updated_source = updated_source.replace(old_source, new_source, 1) patch_descriptions.append("pure-Torch RMSNorm fallback") elif fallback_marker not in updated_source: logger.warning( "Could not patch Cosmos3-Edge modeling.py; mamba RMSNorm import marker was not found" ) mamba_mask_marker = "RTVI_COSMOS3_EDGE_MAMBA_MASK_PATCH" old_mamba_mask_source = ''' def _update_mamba_mask(self, attention_mask, cache_position): """ No need for zeroing states when 1. Cached forward 2. Attending to all inputs """ mamba_mask = attention_mask if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)): mamba_mask = None return mamba_mask ''' new_mamba_mask_source = ''' def _update_mamba_mask(self, attention_mask, cache_position): """ No need for zeroing states when 1. Cached forward 2. Attending to all inputs """ # RTVI_COSMOS3_EDGE_MAMBA_MASK_PATCH: vLLM's non-eager compile path # fullgraph-traces this method. Avoid the data-dependent tensor branch # when no mamba mask is needed, and avoid graph-breaking control flow # during TorchDynamo capture. if attention_mask is None: return None if torch.compiler.is_compiling(): return attention_mask if cache_position[0] > 0 or torch.all(attention_mask == 1): return None return attention_mask ''' if mamba_mask_marker not in updated_source and old_mamba_mask_source in updated_source: updated_source = updated_source.replace( old_mamba_mask_source, new_mamba_mask_source, 1, ) patch_descriptions.append("TorchDynamo-safe mamba mask") elif mamba_mask_marker not in updated_source: logger.warning("Could not patch Cosmos3-Edge modeling.py; mamba mask marker was not found") default_stream_marker = "RTVI_COSMOS3_EDGE_DEFAULT_STREAM_PATCH" old_default_stream_source = ( " with torch.cuda.stream(torch.cuda.default_stream(hidden_states.device)):\n" ) new_default_stream_source = ( " # RTVI_COSMOS3_EDGE_DEFAULT_STREAM_PATCH: the default CUDA stream\n" " # context manager returns a Stream object that TorchDynamo cannot\n" " # fullgraph trace. Keep the block structure without entering the\n" " # explicit default-stream context.\n" " if True:\n" ) if default_stream_marker not in updated_source and old_default_stream_source in updated_source: updated_source = updated_source.replace( old_default_stream_source, new_default_stream_source, 1, ) patch_descriptions.append("TorchDynamo-safe default stream block") elif default_stream_marker not in updated_source: logger.warning( "Could not patch Cosmos3-Edge modeling.py; default stream marker was not found" ) if updated_source == modeling_source: return tmp_path = modeling_path + ".tmp" with open(tmp_path, "w", encoding="utf-8") as modeling_file: modeling_file.write(updated_source) os.replace(tmp_path, modeling_path) _clear_cosmos3_edge_transformers_module_cache(model_path) logger.info( "Patched Cosmos3-Edge modeling.py with %s", " and ".join(patch_descriptions), ) def _prepare_cosmos3_edge_weight_layout(model_path: str, model_architecture: str) -> None: if not _is_cosmos3_edge_arch(model_architecture): return index_path = os.path.join(model_path, "model.safetensors.index.json") backup_path = os.path.join(model_path, "model.safetensors.index.cosmos3_edge_original.json") if not os.path.exists(index_path): return if not os.path.exists(backup_path): with open(index_path, "rb") as index_file: index_data = index_file.read() backup_tmp_path = backup_path + ".tmp" with open(backup_tmp_path, "wb") as backup_file: backup_file.write(index_data) os.replace(backup_tmp_path, backup_path) with open(backup_path, encoding="utf-8") as index_file: index_json = json.load(index_file) shard_rewrite = { "transformer/diffusion_pytorch_model-00001-of-00002.safetensors": ( "diffusion_pytorch_model-00001-of-00002.safetensors" ), "transformer/diffusion_pytorch_model-00002-of-00002.safetensors": ( "diffusion_pytorch_model-00002-of-00002.safetensors" ), "vision_encoder/model.safetensors": "model.safetensors", } for weight_name, shard_name in list(index_json.get("weight_map", {}).items()): index_json["weight_map"][weight_name] = shard_rewrite.get(shard_name, shard_name) index_tmp_path = index_path + ".tmp" with open(index_tmp_path, "w", encoding="utf-8") as index_file: json.dump(index_json, index_file, indent=2, sort_keys=True) index_file.write("\n") os.replace(index_tmp_path, index_path) links = { "diffusion_pytorch_model-00001-of-00002.safetensors": ( "transformer/diffusion_pytorch_model-00001-of-00002.safetensors" ), "diffusion_pytorch_model-00002-of-00002.safetensors": ( "transformer/diffusion_pytorch_model-00002-of-00002.safetensors" ), "model.safetensors": "vision_encoder/model.safetensors", } for link_name, target_name in links.items(): link_path = os.path.join(model_path, link_name) target_path = os.path.join(model_path, target_name) if not os.path.exists(target_path): logger.warning("Cosmos3-Edge weight target missing: %s", target_path) continue if os.path.lexists(link_path): if os.path.islink(link_path) and os.readlink(link_path) == target_name: continue if os.path.islink(link_path): os.unlink(link_path) else: continue os.symlink(target_name, link_path) logger.info("Prepared Cosmos3-Edge root safetensors layout for vLLM") def _is_nvfp4_quantized(model_config: dict) -> bool: quantization_config = model_config.get("quantization_config") or {} quantization_format = str(quantization_config.get("format", "")).lower() if "nvfp4" in quantization_format: return True for group in (quantization_config.get("config_groups") or {}).values(): for section_name in ("weights", "input_activations", "output_activations"): section = group.get(section_name) or {} if section.get("num_bits") == 4 and section.get("type") == "float": return True return False def _is_fp8_quantized(model_config: dict) -> bool: quantization_config = model_config.get("quantization_config") or {} quantization_format = str(quantization_config.get("format", "")).lower() if "fp8" in quantization_format: return True for group in (quantization_config.get("config_groups") or {}).values(): for section_name in ("weights", "input_activations", "output_activations"): section = group.get(section_name) or {} if section.get("num_bits") == 8 and section.get("type") == "float": return True return False def _is_cr3_quantized_qwen3vl(model_architecture: str, model_config: dict) -> bool: if model_architecture not in _QWEN3VL_ARCHS: return False return _is_nvfp4_quantized(model_config) or _is_fp8_quantized(model_config) # Canonical Qwen3-VL extra_special_tokens role mapping. Some Qwen3-VL-arch # checkpoints (e.g. CR3 nano-reasoner modelopt-quantized FP8/NVFP4 builds) # ship extra_special_tokens as a flat list of token strings, which transformers # >=4.55 rejects with `AttributeError: 'list' object has no attribute 'keys'` # in _set_model_specific_special_tokens. vLLM 0.17's new HF renderer # (vllm/renderers/hf.py) trips this during AsyncLLMEngine init. # Model vocabulary special tokens (not credentials). The `*_token` key names # trip the secrets scanner's (secret|token) regex, so each entry carries an # inline `guardrail-ignore` to silence the false positive. _QWEN3VL_EXTRA_SPECIAL_TOKENS = { "image_token": "<|image_pad|>", # guardrail-ignore: model vocab token, not a secret "video_token": "<|video_pad|>", # guardrail-ignore: model vocab token, not a secret "vision_bos_token": "<|vision_start|>", # guardrail-ignore: model vocab token, not a secret "vision_eos_token": "<|vision_end|>", # guardrail-ignore: model vocab token, not a secret } def _normalize_cosmos3_diffusers_config(model_path: str) -> None: """Rewrite the top-level Cosmos3 omni-diffusers-pipeline config.json into a Transformers-loadable Qwen3-VL config that vLLM's ModelConfig can validate. Post-04/17 revisions of nvidia-cosmos-ea/Cosmos3-{Nano,Super} ship a top-level config with model_type=cosmos3_omni and the full OmniMoTModel diffusion config nested under the `model` key. Transformers doesn't know cosmos3_omni and the repo ships no auto_map, so vLLM's ModelConfig pydantic validation aborts via AutoConfig before architecture-based dispatch reaches the Cosmos3ForConditionalGeneration shim. The same checkpoint already carries top-level text_config (qwen3_vl_text) and vision_config (qwen3_vl) alongside image/video/vision token IDs, so synthesis is a structural rename: - drop the `model` key (OmniMoTModel diffusion config, unused by the shim) - flip model_type from `cosmos3_omni` to `qwen3_vl` Other top-level keys (architectures, *_token_id, tie_word_embeddings, allow_patterns_overrides, transformers_version) are preserved verbatim. The original is preserved at config.cosmos3_omni.json so diffusers consumers of the same checkpoint dir keep a usable pipeline config. Idempotent: re-runs no-op once model_type has been flipped.""" cfg_path = os.path.join(model_path, "config.json") if not os.path.exists(cfg_path): return try: with open(cfg_path) as f: cfg = json.load(f) if cfg.get("model_type") != "cosmos3_omni": return if "text_config" not in cfg or "vision_config" not in cfg: logger.warning( "Cosmos3 omni config at %s lacks text_config/vision_config; " "cannot synthesize Qwen3-VL config", cfg_path, ) return backup_path = os.path.join(model_path, "config.cosmos3_omni.json") if not os.path.exists(backup_path): with open(backup_path, "w") as f: json.dump(cfg, f, indent=2, ensure_ascii=False) f.write("\n") synthesized = {k: v for k, v in cfg.items() if k != "model"} synthesized["model_type"] = "qwen3_vl" tmp_path = cfg_path + ".tmp" with open(tmp_path, "w") as f: json.dump(synthesized, f, indent=2, ensure_ascii=False) f.write("\n") os.replace(tmp_path, cfg_path) logger.warning( "Synthesized Qwen3-VL config at %s from cosmos3_omni omni-diffusers " "checkpoint (original preserved at %s)", cfg_path, backup_path, ) except Exception: logger.exception("Failed to synthesize Cosmos3 Qwen3-VL config at %s", cfg_path) def _normalize_qwen3vl_tokenizer_config(model_path: str) -> None: """Rewrite a malformed list-shaped extra_special_tokens to the canonical Qwen3-VL role->token dict, in-place in the model dir. No-op when already a dict or absent. Only intended for CR3 FP8/NVFP4 Qwen3-VL checkpoints.""" cfg_path = os.path.join(model_path, "tokenizer_config.json") if not os.path.exists(cfg_path): return try: with open(cfg_path) as f: cfg = json.load(f) cur = cfg.get("extra_special_tokens") if not isinstance(cur, list): return present = set(cur) mapped = {k: v for k, v in _QWEN3VL_EXTRA_SPECIAL_TOKENS.items() if v in present} cfg["extra_special_tokens"] = mapped with open(cfg_path, "w") as f: json.dump(cfg, f, indent=2, ensure_ascii=False) f.write("\n") logger.warning( "Normalized %s: extra_special_tokens list -> dict %s", cfg_path, sorted(mapped.keys()), ) except Exception: logger.exception("Failed to normalize tokenizer_config at %s", cfg_path) def _empty_vllm_worker_cuda_cache(_worker): """Release cached CUDA blocks in each vLLM worker process.""" torch.cuda.synchronize() torch.cuda.ipc_collect() torch.cuda.empty_cache() free_bytes, total_bytes = torch.cuda.mem_get_info() return { "free_mib": free_bytes // (1024 * 1024), "total_mib": total_bytes // (1024 * 1024), } class VllmCompatible(BaseVlmModel): def _initialize_model(self, vlm_model_type="", **kwargs): """Initialize the VllmCompatible model""" # Initialize model-specific attributes self._vlm_model_type = vlm_model_type self._use_cuda_mm_tensor_ipc = False self._cuda_mm_legacy_preprocess_semaphore = None self._multimodal_preprocess_limiter = None self._adaptive_preprocess_pending_submission_ids = set() self._cuda_mm_pending_submission_ids = set() self._cuda_mm_resident_units_by_request = {} self._cuda_mm_residency_lock = threading.Lock() self._cuda_ipc_collect_event = threading.Event() self._cuda_ipc_collect_thread = None self.model_dir_name = os.path.basename(os.path.normpath(self.model_path)) self._live_request_ids: dict[str, set[str]] = {} self._live_request_futures: dict[str, concurrent.futures.Future] = {} self._live_stream_abort_requested: set[str] = set() self._live_request_ids_lock = threading.Lock() # Set resize parameters self._max_pixels = MAX_PIXELS self._min_pixels = MIN_PIXELS self._model_architecture = "" try: with open(os.path.join(self.model_path, "config.json")) as f: model_config = json.load(f) self._model_architecture = model_config.get("architectures", [""])[0] if _is_cr3_quantized_qwen3vl(self._model_architecture, model_config): _normalize_qwen3vl_tokenizer_config(self.model_path) if _is_cosmos3_diffusers_shim_arch(self._model_architecture): _normalize_cosmos3_diffusers_config(self.model_path) except Exception: logger.debug("Failed to get model architecture from config.json") if self._vlm_model_type == "cosmos-reason1": self._system_prompt = DEFAULT_SYSTEM_PROMPT_CR1 else: self._system_prompt = "" if self._system_prompt: logger.info("VllmCompatible default system prompt: %s", self._system_prompt) if _is_evs_session_enabled(): if not _VIDEO_METADATA_ABSOLUTE_TIMESTAMPS: logger.info( "VIA_EVS_SESSION enabled: internally enabling " "RTVI_VIDEO_METADATA_ABSOLUTE_TIMESTAMPS for EVS metadata" ) if self._vlm_model_type != "cosmos-reason1" and ADD_TIMESTAMP_TO_PROMPT: _, _, file_uses_default = _get_timestamp_prompt_templates( is_rtsp=False, use_evs_default=True, ) _, _, rtsp_uses_default = _get_timestamp_prompt_templates( is_rtsp=True, use_evs_default=True, ) if file_uses_default or rtsp_uses_default: logger.info( "VIA_EVS_SESSION enabled: using dev/aa/evs-compatible " "default EVS timestamp prompt where no RTVI_TIMESTAMP_PROMPT_* " "override is configured" ) else: logger.info( "VIA_EVS_SESSION enabled: using configured " "RTVI_TIMESTAMP_PROMPT_* templates for EVS timestamp prompt" ) # Initialize the actual model components logger.info("Using VLLM model for vllm-compatible") os.environ["VLLM_CACHE_ROOT"] = os.path.join(self.model_path, ".vllm") _sanitize_rtvi_vllm_env() _maybe_register_cosmos3_vllm_shim(self._model_architecture) from transformers import AutoProcessor from vllm.engine.arg_utils import AsyncEngineArgs from vllm.engine.async_llm_engine import AsyncLLMEngine self._num_time_tokens = 0 self._model_name = "vllm-compatible" model_lock_path = self.model_path + "/.lock" with FileLock(model_lock_path): _prepare_cosmos3_edge_weight_layout(self.model_path, self._model_architecture) _patch_cosmos3_edge_modeling_file(self.model_path, self._model_architecture) logger.info("Initializing VllmCompatible model from: %s", self.model_path) gpu_memory_utilization_env = _get_rtvi_vllm_env("VLLM_GPU_MEMORY_UTILIZATION", "0.7") if not gpu_memory_utilization_env.strip(): gpu_memory_utilization_env = "0.7" try: gpu_memory_utilization = float(gpu_memory_utilization_env) except ValueError: raise ValueError( f"Invalid value for VLLM_GPU_MEMORY_UTILIZATION: " f"'{gpu_memory_utilization_env}' is not a valid float" ) logger.debug( "VLLM GPU memory utilization requirement set to: %s%%", gpu_memory_utilization * 100, ) max_num_batched_tokens_env = _get_rtvi_vllm_env("VLLM_MAX_NUM_BATCHED_TOKENS", "") max_num_batched_tokens = None if max_num_batched_tokens_env.strip(): try: max_num_batched_tokens = int(max_num_batched_tokens_env) except ValueError: raise ValueError( f"Invalid value for VLLM_MAX_NUM_BATCHED_TOKENS: " f"'{max_num_batched_tokens_env}' is not a valid integer" ) try: # Check if model supports audio via environment variable vlm_supports_audio = ( os.environ.get("VLM_MODEL_SUPPORTS_AUDIO", "false").lower() == "true" ) limit_mm_per_prompt = _get_limit_mm_per_prompt(vlm_supports_audio) import inspect _engine_supported_params = set( inspect.signature(AsyncEngineArgs.__init__).parameters ) # Build engine args, only including params supported by the installed vLLM version engine_args_kwargs = { "model": self.model_path, "max_model_len": _parse_int_env("VLM_MAX_MODEL_LEN", 32768), "limit_mm_per_prompt": limit_mm_per_prompt, "gpu_memory_utilization": gpu_memory_utilization, "max_num_seqs": self._max_batch_size, "tensor_parallel_size": torch.cuda.device_count(), } kv_cache_memory_bytes = _parse_optional_int_env("VLLM_KV_CACHE_MEMORY_BYTES") if kv_cache_memory_bytes is not None: if "kv_cache_memory_bytes" in _engine_supported_params: engine_args_kwargs["kv_cache_memory_bytes"] = kv_cache_memory_bytes logger.info( "VLLM KV cache memory bytes override: %s", kv_cache_memory_bytes, ) else: logger.warning( "VLLM_KV_CACHE_MEMORY_BYTES=%s ignored; installed vLLM does not " "support kv_cache_memory_bytes", kv_cache_memory_bytes, ) _apply_kv_cache_dtype_override( engine_args_kwargs, _engine_supported_params, ) _apply_attention_backend_override( engine_args_kwargs, _engine_supported_params, self._model_architecture, ) _configure_structured_outputs(engine_args_kwargs, _engine_supported_params) if "enable_prefix_caching" in _engine_supported_params: prefix_caching_env = _get_rtvi_vllm_env( "VLLM_ENABLE_PREFIX_CACHING", "true", ) enable_prefix_caching = prefix_caching_env.lower() == "true" engine_args_kwargs["enable_prefix_caching"] = enable_prefix_caching _apply_mm_processor_cache_engine_args( engine_args_kwargs, _engine_supported_params, ) mm_tensor_ipc = get_vllm_mm_tensor_ipc(engine_args_kwargs["tensor_parallel_size"]) if mm_tensor_ipc: if "mm_tensor_ipc" in _engine_supported_params: engine_args_kwargs["mm_tensor_ipc"] = mm_tensor_ipc logger.info("VLLM MM tensor IPC mode: %s", mm_tensor_ipc) self._use_cuda_mm_tensor_ipc = ( mm_tensor_ipc == "torch_shm" and self._model_architecture in _QWEN3VL_ARCHS ) if self._use_cuda_mm_tensor_ipc: logger.info("Passing raw Qwen3-VL video tensors to vLLM on CUDA") else: logger.warning( "VLLM_MM_TENSOR_IPC=%s ignored; installed vLLM does not support " "mm_tensor_ipc", mm_tensor_ipc, ) multimodal_tensor_ipc = ( _get_rtvi_vllm_env("VLLM_MULTIMODAL_TENSOR_IPC", "") or "" ).strip() if multimodal_tensor_ipc: if "multimodal_tensor_ipc" in _engine_supported_params: engine_args_kwargs["multimodal_tensor_ipc"] = ( multimodal_tensor_ipc.lower() == "true" ) logger.info( "VLLM multimodal tensor IPC enabled: %s", engine_args_kwargs["multimodal_tensor_ipc"], ) else: logger.warning( "VLLM_MULTIMODAL_TENSOR_IPC=%s ignored; installed vLLM does not " "support multimodal_tensor_ipc", multimodal_tensor_ipc, ) mm_encoder_attn_backend = ( _get_rtvi_vllm_env("VLLM_MM_ENCODER_ATTN_BACKEND", "") or "" ).strip() if mm_encoder_attn_backend: if "mm_encoder_attn_backend" in _engine_supported_params: engine_args_kwargs["mm_encoder_attn_backend"] = mm_encoder_attn_backend logger.info( "VLLM MM encoder attention backend override: %s", mm_encoder_attn_backend, ) else: logger.warning( "VLLM_MM_ENCODER_ATTN_BACKEND=%s ignored; installed vLLM does not " "support mm_encoder_attn_backend", mm_encoder_attn_backend, ) if "enable_chunked_prefill" in _engine_supported_params: engine_args_kwargs["enable_chunked_prefill"] = True enforce_eager = False if "enforce_eager" in _engine_supported_params: enforce_eager = ( _get_rtvi_vllm_env("VLLM_ENFORCE_EAGER", "false").lower() == "true" ) engine_args_kwargs["enforce_eager"] = enforce_eager if enforce_eager: logger.info("VLLM enforce_eager enabled via VLLM_ENFORCE_EAGER") compilation_config = _get_vllm_compilation_config( self._model_architecture, self._vlm_model_type, enforce_eager, ) if compilation_config: if enforce_eager: raise ValueError( "vLLM compilation cannot be enabled when VLLM_ENFORCE_EAGER=true" ) if "compilation_config" in _engine_supported_params: engine_args_kwargs["compilation_config"] = compilation_config logger.info( "VLLM compilation config: %s", compilation_config, ) else: logger.warning( "vLLM compilation config %s ignored; installed vLLM does not " "support compilation_config", compilation_config, ) vlm_trust_remote_code = _get_vlm_trust_remote_code(self._model_architecture) if "trust_remote_code" in _engine_supported_params: engine_args_kwargs["trust_remote_code"] = vlm_trust_remote_code if max_num_batched_tokens is not None: engine_args_kwargs["max_num_batched_tokens"] = max_num_batched_tokens else: engine_args_kwargs["max_num_batched_tokens"] = engine_args_kwargs[ "max_model_len" ] moe_backend = (_get_rtvi_vllm_env("VLLM_MOE_BACKEND", "") or "").strip() moe_backend_source = "override" if not moe_backend and self._model_architecture in _QWEN35_ARCHS: gpu_names = [ torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count()) ] if any("B200" in name for name in gpu_names): moe_backend = "triton" moe_backend_source = "B200 default" logger.info( "Defaulting Qwen3.5 MoE backend to triton on B200; " "set VLLM_MOE_BACKEND to override" ) if moe_backend and "moe_backend" in _engine_supported_params: engine_args_kwargs["moe_backend"] = moe_backend logger.info("Using vLLM MoE backend %s: %s", moe_backend_source, moe_backend) # EVS (Efficient Video Sampling): prune redundant video tokens. # Invalid configured values are fatal rather than silently disabling EVS. video_pruning_rate = get_video_pruning_rate() if video_pruning_rate is not None: if "video_pruning_rate" in _engine_supported_params: engine_args_kwargs["video_pruning_rate"] = video_pruning_rate logger.info( "EVS enabled: video_pruning_rate=%.2f", video_pruning_rate ) else: logger.warning( "VLM_VIDEO_PRUNING_RATE is set but the installed vLLM engine " "does not support video_pruning_rate" ) # EVS extra engine args (similarity threshold, mm-embeds passthrough, # preprocess worker pool). Gated on the engine actually supporting them. # Similarity-based (content-dependent) pruning only applies on # the EVS session/encode path, so gate it on VIA_EVS_SESSION. # When session mode is on: use VLLM_EVS_SIMILARITY_THRESHOLD if # provided, else default 0.4. When session mode is off: leave # evs_similarity_threshold=None so the engine uses deterministic # fixed-rate pruning (video_pruning_rate) instead. _evs_session_on = os.environ.get("VIA_EVS_SESSION", "").lower() in ( "true", "1", ) if self._model_architecture in _NEMOTRON_OMNI_ARCHS and _evs_session_on: logger.error( "EVS session mode is not supported for NemotronH_Nano_Omni_Reasoning_V3" ) raise ValueError( "EVS session mode is not supported for NemotronH_Nano_Omni_Reasoning_V3" ) if "evs_similarity_threshold" in _engine_supported_params and _evs_session_on: engine_args_kwargs["evs_similarity_threshold"] = _get_evs_similarity_threshold() if "enable_mm_embeds" in _engine_supported_params: engine_args_kwargs["enable_mm_embeds"] = True if "num_preprocess_workers" in _engine_supported_params: engine_args_kwargs["num_preprocess_workers"] = _get_num_preprocess_workers() engine_args = AsyncEngineArgs(**engine_args_kwargs) self._llm = AsyncLLMEngine.from_engine_args(engine_args) self._processor = AutoProcessor.from_pretrained( self.model_path, trust_remote_code=vlm_trust_remote_code ) except Exception as e: logger.error("Error initializing VLLM model: %s", e) if _get_rtvi_vllm_env("VLLM_ENFORCE_EAGER", "false").lower() != "true": logger.warning( "If this vLLM initialization failure is in the torch.compile/CUDA graph " "path, retry with VLLM_ENFORCE_EAGER=true to disable CUDA graph capture." ) raise self._event_loop = asyncio.new_event_loop() logger.debug("Event loop created") self._event_loop_thread = threading.Thread(target=start_loop, args=(self._event_loop,)) logger.debug("Starting event loop thread") self._event_loop_thread.start() logger.debug("Event loop thread started") logger.info("VllmCompatible VLLM model initialized successfully") # EVS session handler — uses vLLM's serving layer directly (no HTTP) self._evs_handler = None # OpenAIServingVideoSessions, created lazily # Per-stream/config EVS sessions: (streamId, session_config) → session_id self._evs_sessions: dict[tuple, str] = {} self._evs_sessions_lock = threading.Lock() self._output_tpool = concurrent.futures.ThreadPoolExecutor( max_workers=self._max_batch_size ) adaptive_config = _get_adaptive_preprocess_config() if adaptive_config.enabled: self._multimodal_preprocess_limiter = AdaptivePreprocessLimiter( adaptive_config, self._get_cuda_free_memory_mb, self._get_cuda_utilization_percent, ) self._multimodal_preprocess_limiter.register_otel_metrics() logger.info( "Adaptive multimodal preprocessing enabled: " "shadow_mode=%s, workers=%d..%d, headroom=%d MiB, " "initial_estimate=%d MiB/request, safety_factor=%.2f, timeout=%.1fs, " "scale_up_cooldown=%.1fs, scale_up_gpu_threshold=%.1f%%, " "calibration_samples=%d, tensor_ipc=%s", adaptive_config.shadow_mode, adaptive_config.min_workers, adaptive_config.max_workers, adaptive_config.gpu_headroom_mb, adaptive_config.initial_estimated_request_mb, adaptive_config.estimate_safety_factor, adaptive_config.admission_timeout_seconds, adaptive_config.scale_up_cooldown_seconds, adaptive_config.scale_up_gpu_utilization_threshold_percent, adaptive_config.calibration_samples_required, self._use_cuda_mm_tensor_ipc, ) if self._use_cuda_mm_tensor_ipc: self._cuda_ipc_collect_thread = threading.Thread( target=self._collect_released_cuda_ipc_allocations, name="rtvi-cuda-ipc-collect", daemon=True, ) self._cuda_ipc_collect_thread.start() @property def model_name(self): return self._model_name def get_conv(self): # Initialize _conv if not already done if not hasattr(self, "_conv"): self._conv = [] return self._conv.copy() def _resolve_prompt_reasoning_config( self, config: VlmGenerationConfig ) -> VlmGenerationConfig: """Honor Cosmos Reason 3's prompt-driven ```` contract.""" if ( getattr(self, "_vlm_model_type", None) != "cosmos-reason3" or config.enable_reasoning or not config.prompt_driven_reasoning ): return config effective_config = copy.copy(config) effective_config.enable_reasoning = True return effective_config def _get_apply_chat_template_kwargs(self, config: VlmGenerationConfig) -> dict: # Reasoning-capable chat templates open a block by default. Keep the RTVI # default non-reasoning unless the request explicitly enables reasoning. if ( self._model_architecture in _NEMOTRON_OMNI_ARCHS or self._model_architecture in _QWEN35_ARCHS or self._model_architecture in _QWEN3VL_ARCHS or _is_cosmos3_edge_arch(self._model_architecture) ): return {"enable_thinking": bool(config.enable_reasoning)} return {} def _uses_qwen3vl_non_reasoning_fallback(self, config: VlmGenerationConfig) -> bool: return ( self._model_architecture in _QWEN3VL_ARCHS and getattr(self, "_vlm_model_type", None) != "cosmos-reason3" and not config.enable_reasoning ) def _apply_chat_template(self, messages: list[dict], config: VlmGenerationConfig) -> str: """Apply the model template with a Qwen3-VL non-reasoning fallback.""" template_messages = messages suppress_qwen_reasoning = self._uses_qwen3vl_non_reasoning_fallback(config) if suppress_qwen_reasoning: template_messages = copy.deepcopy(messages) for message in reversed(template_messages): if message.get("role") != "user": continue content = message.get("content") if isinstance(content, str): message["content"] = f"{content} /no_think" elif isinstance(content, list): for item in reversed(content): if isinstance(item, dict) and item.get("type") == "text": item["text"] = f"{item.get('text', '')} /no_think" break break prompt = self._processor.apply_chat_template( template_messages, tokenize=False, add_generation_prompt=True, **self._get_apply_chat_template_kwargs(config), ) if suppress_qwen_reasoning and not prompt.rstrip().endswith(""): prompt += "\n\n\n\n" return prompt def _apply_reasoning_suppression_sampling_params( self, sampling_kwargs: dict, config: VlmGenerationConfig ) -> None: """Block reasoning tags without changing fixed-work generation length.""" if self._uses_qwen3vl_non_reasoning_fallback(config): sampling_kwargs["bad_words"] = ["", ""] def _qwen3vl_answer_boundary_token_ids(self) -> set[int]: tokenizer = self._processor.tokenizer boundary_ids = set() eos_token_ids = getattr(tokenizer, "eos_token_id", None) if isinstance(eos_token_ids, int): boundary_ids.add(eos_token_ids) elif eos_token_ids is not None: boundary_ids.update(int(token_id) for token_id in eos_token_ids) im_end_id = tokenizer.convert_tokens_to_ids("<|im_end|>") if isinstance(im_end_id, int) and im_end_id != getattr(tokenizer, "unk_token_id", None): boundary_ids.add(im_end_id) return boundary_ids def _truncate_qwen3vl_non_reasoning_output(self, output) -> str: generated = output.outputs[0] token_ids = list(getattr(generated, "token_ids", ())) boundary_ids = self._qwen3vl_answer_boundary_token_ids() for index, token_id in enumerate(token_ids): if token_id in boundary_ids: return self._processor.tokenizer.decode( token_ids[:index], skip_special_tokens=True ).rstrip() return generated.text def _remove_orphan_think_tags(self, text: str, reasoning_description: str) -> tuple: # Handle orphan (no opening — start token was cut off or never generated). # Everything before is reasoning; everything after is the actual answer. close_idx = text.find("") if close_idx != -1: if not reasoning_description: reasoning_description = text[:close_idx] text = text[close_idx + len("") :] # Handle orphan (no closing — truncated generation mid-reasoning). # Answer always follows , so there is no answer text here; warn the user. think_idx = text.find("") if think_idx != -1: if not reasoning_description: reasoning_description = text[think_idx + len("") :] text = "" logger.warning( "Generated text is empty after removing incomplete reasoning block. " "The model likely ran out of tokens mid-reasoning. " "Consider increasing MAX_MODEL_LEN or max_tokens." ) return text, reasoning_description def _postprocess_vllm( self, output, video_frames_times, chunk=None, ignore_eos=False, preserve_reasoning_tags=False, enable_reasoning=True, ): with TimeMeasure("VLLM postprocess"): original_output = output if hasattr(output, "result"): output = output.result() if original_output in self._inflight_req_ids: self._inflight_req_ids.remove(original_output) elif isinstance(output, concurrent.futures.Future): output = output.result() if original_output in self._inflight_req_ids: self._inflight_req_ids.remove(original_output) # Extract and validate response if not output or not output[0].outputs: logger.warning("No output generated from model") return [ VlmModelOutput( output="Error: No response generated", input_tokens=0, output_tokens=0, ) ] generated_text = output[0].outputs[0].text if ( self._model_architecture in _QWEN3VL_ARCHS and not enable_reasoning and ignore_eos ): generated_text = self._truncate_qwen3vl_non_reasoning_output(output[0]) logger.debug("VLLM raw text output: %s", generated_text) if not generated_text: logger.warning("Empty response from model") return [VlmModelOutput(output="", input_tokens=0, output_tokens=0)] if preserve_reasoning_tags and enable_reasoning: final_response = generated_text.strip() if not ignore_eos else generated_text reasoning_description = "" else: # Step 1: Strip leading/trailing whitespace cleaned_text = generated_text.strip() if not ignore_eos else generated_text # Step 2: Extract reasoning description reasoning_description = re.search( r"(.*?)", cleaned_text, flags=re.DOTALL ) if reasoning_description: reasoning_description = reasoning_description.group(1) else: reasoning_description = "" # Step 3: Remove complete ... block if found, otherwise handle orphan tags if reasoning_description: cleaned_text = re.sub(r".*?", "", cleaned_text, flags=re.DOTALL) else: cleaned_text, reasoning_description = self._remove_orphan_think_tags( cleaned_text, reasoning_description ) if not enable_reasoning: reasoning_description = "" logger.debug("VLLM reasoning description: %s", reasoning_description) # Step 4: Remove , , , and tags, but keep their content for tag in ["", "", "", ""]: cleaned_text = cleaned_text.replace(tag, "") # Step 4: Final cleanup (strip whitespace) final_response = cleaned_text.strip() if not ignore_eos else cleaned_text logger.debug("VLLM cleaned text output: %s", final_response) try: input_tokens = ( len(output[0].prompt_token_ids) if hasattr(output[0], "prompt_token_ids") else 0 ) output_tokens = ( len(output[0].outputs[0].token_ids) if hasattr(output[0].outputs[0], "token_ids") else 0 ) except (AttributeError, IndexError): input_tokens = 0 output_tokens = 0 logger.debug( "VLM result: total_prompt_tokens=%d (text+visual), output_tokens=%d", input_tokens, output_tokens, ) try: if chunk and self._vlm_model_type == "cosmos-reason1": final_response = self._update_video_frames_times( final_response, chunk, video_frames_times ) except Exception as e: logger.error("Error updating video frames times: %s", e) return [ VlmModelOutput( output=final_response, input_tokens=input_tokens, output_tokens=output_tokens, reasoning_description=reasoning_description, ) ] def _update_video_frames_times(self, text, chunk, video_frames_times): updated_text = re.sub( r"<([0-9]+(?:\.[0-9]+)?)>", lambda m: ( "<" + chunk.get_timestamp(float(video_frames_times[0]) + float(m.group(1))) + ">" ), text, ) return updated_text @staticmethod def _get_cuda_free_memory_mb() -> int: device_count = torch.cuda.device_count() if device_count < 1: raise RuntimeError("No CUDA devices are visible") return min( int(torch.cuda.mem_get_info(device)[0] / (1024 * 1024)) for device in range(device_count) ) @staticmethod def _get_cuda_utilization_percent() -> float: device_count = torch.cuda.device_count() if device_count < 1: raise RuntimeError("No CUDA devices are visible") return max(float(torch.cuda.utilization(device)) for device in range(device_count)) @staticmethod def _multimodal_preprocess_workload( llm_inputs, sampling_params=None, ) -> tuple[str, int]: """Describe raw multimodal work without assuming a model processor. The model process owns the resulting calibration table, so changing the model starts with an empty table. Shape, dtype, modality, processor options, and raw payload size distinguish workloads within that model. """ descriptors = [] payload_bytes = 0 multi_modal_data = llm_inputs.get("multi_modal_data", {}) if not isinstance(multi_modal_data, dict): multi_modal_data = {} for modality in sorted(multi_modal_data): value = multi_modal_data[modality] items = value if isinstance(value, list) else [value] for item in items: media = item[0] if isinstance(item, tuple) and item else item shape = tuple(int(dimension) for dimension in getattr(media, "shape", ())) dtype = str(getattr(media, "dtype", type(media).__name__)) nbytes = getattr(media, "nbytes", None) if callable(nbytes): nbytes = nbytes() if nbytes is None and isinstance(media, torch.Tensor): nbytes = media.numel() * media.element_size() if nbytes is None and isinstance(media, Image.Image): channels = len(media.getbands()) nbytes = media.width * media.height * channels shape = (media.height, media.width, channels) dtype = f"PIL.{media.mode}" if nbytes is None and isinstance(media, (bytes, bytearray, memoryview)): nbytes = len(media) shape = (nbytes,) nbytes = max(0, int(nbytes or 0)) payload_bytes += nbytes descriptors.append((modality, shape, dtype, nbytes)) processor_kwargs = llm_inputs.get("mm_processor_kwargs", {}) try: processor_signature = json.dumps( processor_kwargs, sort_keys=True, separators=(",", ":"), default=str, ) except (TypeError, ValueError): processor_signature = repr(processor_kwargs) prompt_tokens = len(llm_inputs.get("prompt_token_ids", ())) max_tokens = int(getattr(sampling_params, "max_tokens", 0) or 0) def power_of_two_bucket(value: int) -> int: return 0 if value < 1 else 1 << (value - 1).bit_length() signature = json.dumps( { "media": descriptors, "processor": processor_signature, "prompt_token_bucket": power_of_two_bucket(prompt_tokens), "output_token_bucket": power_of_two_bucket(max_tokens), }, sort_keys=True, separators=(",", ":"), ) workload_key = hashlib.sha256(signature.encode("utf-8")).hexdigest()[:16] return workload_key, max(1, math.ceil(payload_bytes / (1024 * 1024))) def _ensure_legacy_preprocess_semaphore(self): if self._cuda_mm_legacy_preprocess_semaphore is None: self._cuda_mm_legacy_preprocess_semaphore = asyncio.Semaphore( _LEGACY_MAX_CONCURRENT_CUDA_MM_PREPROCESS ) logger.info( "Limiting concurrent CUDA multimodal prompt preprocessing " "to %d while retaining %d configured vLLM preprocess workers", _LEGACY_MAX_CONCURRENT_CUDA_MM_PREPROCESS, _get_num_preprocess_workers(), ) return self._cuda_mm_legacy_preprocess_semaphore async def _add_multimodal_request(self, request_id, llm_inputs, vllm_sampling_params): # Decoder backpressure may spill raw video frames to CPU. Promote only # after admission so concurrent copies cannot recreate a residency burst. multi_modal_data = llm_inputs.get("multi_modal_data") if isinstance(multi_modal_data, dict): video_items = multi_modal_data.get("video") if isinstance(video_items, list) and video_items: video_item = video_items[0] if isinstance(video_item, tuple): video_tensor, video_metadata = video_item else: video_tensor, video_metadata = video_item, None if ( self._use_cuda_mm_tensor_ipc and isinstance(video_tensor, torch.Tensor) and not video_tensor.is_cuda ): video_tensor = video_tensor.to( device=torch.device("cuda", torch.cuda.current_device()) ) video_items[0] = ( (video_tensor, video_metadata) if isinstance(video_item, tuple) else video_tensor ) return await self._llm.add_request( request_id, llm_inputs, vllm_sampling_params, ) async def _generate_with_preprocess_admission( self, llm_inputs, vllm_sampling_params, request_id, ): """Submit a multimodal prompt with bounded frontend preprocessing. AsyncLLM.add_request() returns after its threaded InputProcessor finishes. The default RPC path retains admission until the first EngineCore output, which proves the visual encoder has consumed the processed request. """ from vllm.v1.engine.async_llm import STREAM_FINISHED output_queue = None admission = None preprocess_success = False preprocess_memory_pressure = False memory_sampler_task = None async def sample_memory_until_release(): while admission is not None: limiter.sample_active_memory(request_id) await asyncio.sleep(limiter.config.poll_interval_seconds) async def release_admission(): nonlocal admission, memory_sampler_task if admission is None: return workload_key = admission.workload_key limiter.sample_active_memory(request_id) if memory_sampler_task is not None: memory_sampler_task.cancel() with contextlib.suppress(asyncio.CancelledError): await memory_sampler_task memory_sampler_task = None previous_snapshot = limiter.snapshot() await limiter.release( admission, success=preprocess_success, memory_pressure=preprocess_memory_pressure, ) admission = None snapshot = limiter.snapshot() if snapshot.effective_limit != previous_snapshot.effective_limit: logger.info( "Adaptive multimodal preprocessing limit changed: " "previous=%d, current=%d, memory_pressure_events=%d, " "pressure_active=%s, backpressure=%s, cooldown_remaining=%.1fs, " "gpu_utilization=%s%%, free=%s MiB, reserved=%d MiB", previous_snapshot.effective_limit, snapshot.effective_limit, snapshot.memory_pressure_events, snapshot.memory_pressure_active, snapshot.backpressure_observed, snapshot.scale_up_cooldown_remaining_seconds, snapshot.last_gpu_utilization_percent, snapshot.last_free_memory_mb, snapshot.pending_reserved_mb, ) logger.debug( "Multimodal preprocessing release: request=%s, observed=%s MiB, " "active=%d, queued=%d, limit=%d, reserved=%d MiB", request_id, snapshot.estimated_mb_by_workload.get(workload_key), snapshot.active, snapshot.queued, snapshot.effective_limit, snapshot.pending_reserved_mb, ) try: workload_key, payload_mb = self._multimodal_preprocess_workload( llm_inputs, vllm_sampling_params, ) limiter = self._multimodal_preprocess_limiter if limiter is not None: try: admission = await limiter.acquire( request_id, workload_key, payload_mb, ) memory_sampler_task = asyncio.create_task(sample_memory_until_release()) except PreprocessAdmissionTimeout as exc: snapshot = limiter.snapshot() logger.warning( "Adaptive multimodal preprocessing admission timed out: " "request=%s, workload=%s, payload=%d MiB, active=%d, queued=%d, " "limit=%d, free=%s MiB, reserved=%d MiB", request_id, workload_key, payload_mb, snapshot.active, snapshot.queued, snapshot.effective_limit, snapshot.last_free_memory_mb, snapshot.pending_reserved_mb, ) raise ServiceException( "Insufficient GPU memory for multimodal preprocessing. " "Retry after active requests complete or reduce video frames/resolution.", "ServerBusy", 503, ) from exc logger.debug( "Multimodal preprocessing admission: request=%s, workload=%s, " "payload=%d MiB, estimate=%d MiB, wait=%.3fs, enforced=%s, " "would_admit=%s", request_id, workload_key, payload_mb, admission.estimated_mb, admission.wait_seconds, admission.enforced, admission.policy_would_admit, ) use_legacy_gate = self._use_cuda_mm_tensor_ipc and ( limiter is None or limiter.config.shadow_mode ) try: if use_legacy_gate: async with self._ensure_legacy_preprocess_semaphore(): output_queue = await self._add_multimodal_request( request_id, llm_inputs, vllm_sampling_params, ) else: output_queue = await self._add_multimodal_request( request_id, llm_inputs, vllm_sampling_params, ) preprocess_success = True except Exception as exc: preprocess_memory_pressure = _is_cuda_oom_error(exc) raise finally: if self._use_cuda_mm_tensor_ipc: await release_admission() if self._use_cuda_mm_tensor_ipc: self._finish_cuda_mm_submission(request_id) # add_request has completed frontend preprocessing and submitted the # EngineCore request. EngineCore owns the processed IPC tensors now; # the raw input frames are no longer needed by this process. multi_modal_data = llm_inputs.get("multi_modal_data") if isinstance(multi_modal_data, dict): multi_modal_data.clear() llm_inputs.clear() finished = False while not finished: output = output_queue.get_nowait() or await output_queue.get() finished = output.finished if output is not STREAM_FINISHED: await release_admission() self._finish_preprocess_submission(request_id) if self._use_cuda_mm_tensor_ipc: self._release_cuda_mm_residency(request_id) yield output except (asyncio.CancelledError, GeneratorExit): preprocess_success = False if output_queue is not None: await self._llm.abort(output_queue.request_id, internal=True) raise except Exception as exc: preprocess_success = False preprocess_memory_pressure = _is_cuda_oom_error(exc) if output_queue is not None: await self._llm.abort(output_queue.request_id, internal=True) raise finally: await release_admission() self._finish_preprocess_submission(request_id) if self._use_cuda_mm_tensor_ipc: self._finish_cuda_mm_submission(request_id) self._release_cuda_mm_residency(request_id) # Also release an input rejected during preprocessing. In the # successful path these mappings are already empty. multi_modal_data = llm_inputs.get("multi_modal_data") if isinstance(multi_modal_data, dict): multi_modal_data.clear() llm_inputs.clear() if output_queue is not None: output_queue.close() @staticmethod def _should_use_preprocess_admission(use_tensor_ipc, limiter) -> bool: return use_tensor_ipc or limiter is not None def _register_live_request(self, stream_id: str, request_id: str) -> None: lock = getattr(self, "_live_request_ids_lock", None) if lock is None: self._live_request_ids_lock = threading.Lock() self._live_request_ids = {} self._live_request_futures = {} self._live_stream_abort_requested = set() lock = self._live_request_ids_lock with lock: self._live_request_ids.setdefault(stream_id, set()).add(request_id) def _attach_live_request_future( self, stream_id: str, request_id: str, request_future: concurrent.futures.Future, ) -> None: with self._live_request_ids_lock: self._live_request_futures[request_id] = request_future abort_requested = stream_id in self._live_stream_abort_requested if abort_requested: request_future.cancel() def _release_live_request(self, stream_id: Optional[str], request_id: str) -> None: if request_id in self._inflight_req_ids: self._inflight_req_ids.remove(request_id) if not stream_id: return lock = getattr(self, "_live_request_ids_lock", None) if lock is None: return with lock: self._live_request_futures.pop(request_id, None) request_ids = self._live_request_ids.get(stream_id) if request_ids is None: return request_ids.discard(request_id) if not request_ids: self._live_request_ids.pop(stream_id, None) self._live_stream_abort_requested.discard(stream_id) def abort_live_stream_requests(self, stream_id: str, timeout_sec: float = 30.0) -> int: """Abort vLLM requests currently owned by one live stream.""" lock = getattr(self, "_live_request_ids_lock", None) if lock is None: return 0 with lock: request_ids = tuple(self._live_request_ids.get(stream_id, ())) self._live_stream_abort_requested.add(stream_id) request_futures = tuple( future for request_id in request_ids if (future := self._live_request_futures.get(request_id)) is not None ) if not request_ids: return 0 for request_future in request_futures: request_future.cancel() abort_future = asyncio.run_coroutine_threadsafe( self._llm.abort(request_ids), self._event_loop, ) abort_future.result(timeout=timeout_sec) return len(request_ids) async def process_async_vllm( self, llm_inputs, vllm_sampling_params, video_frames_times, request_id, chunk=None, preserve_reasoning_tags=False, stream_id: Optional[str] = None, generation_config: Optional[VlmGenerationConfig] = None, ): try: return await self._process_async_vllm( llm_inputs, vllm_sampling_params, video_frames_times, request_id, chunk, preserve_reasoning_tags, generation_config, ) finally: self._release_live_request(stream_id, request_id) async def _process_async_vllm( self, llm_inputs, vllm_sampling_params, video_frames_times, request_id, chunk=None, preserve_reasoning_tags=False, generation_config: Optional[VlmGenerationConfig] = None, ): use_tensor_ipc = getattr(self, "_use_cuda_mm_tensor_ipc", False) if CPU_COPY_OTHER_THREAD: if "video" in llm_inputs["multi_modal_data"]: video_tensor = llm_inputs["multi_modal_data"]["video"][0][0] video_metadata = llm_inputs["multi_modal_data"]["video"][0][1] if use_tensor_ipc: # The HF torch video path expects TCHW. Its numpy path used # by the baseline detects and converts RTVI's native THWC # layout automatically. if video_tensor.ndim == 4 and video_tensor.shape[-1] in (1, 3, 4): video_tensor = video_tensor.permute(0, 3, 1, 2) llm_inputs["multi_modal_data"]["video"][0] = ( video_tensor, video_metadata, ) # Keep only the reference in llm_inputs so the CUDA prompt # can be released immediately after add_request returns. del video_tensor else: # The direct-RPC path serializes raw frames as numpy. With # torch_shm, keep Qwen3-VL frames on CUDA: its fast HF # processor is torch-native and the processed CUDA tensor is # transferred to EngineCore by vLLM's tensor IPC queue. video_tensor_cpu = await asyncio.to_thread(lambda: video_tensor.cpu().numpy()) llm_inputs["multi_modal_data"]["video"][0] = ( video_tensor_cpu, video_metadata, ) else: # Image input: default to the historical CPU/NumPy path. The # raw tensor opt-in lets native video keep CUDA tensors through # vLLM preprocessing for Qwen-style image prompts. # NemotronH_Nano_VL_V2/Omni_Reasoning_V3 use NanoNemotronVLProcessor # whose image path # calls image.size expecting a PIL Image (tuple), not a numpy array (int). # The video path works because video_to_pixel_values does Image.fromarray # internally, but the image path has no such conversion. image_input = llm_inputs["multi_modal_data"]["image"] if _use_raw_image_tensor_input(getattr(self, "_model_architecture", None)): logger.debug( "Keeping raw image tensor input for vLLM request %s", request_id, ) else: def _image_to_numpy(image_tensor): if isinstance(image_tensor, numpy.ndarray): return image_tensor return image_tensor.cpu().numpy() if isinstance(image_input, list): images_numpy = await asyncio.to_thread( lambda: [_image_to_numpy(image_tensor) for image_tensor in image_input] ) else: images_tensor = image_input[0] images_numpy = await asyncio.to_thread( lambda: _image_to_numpy(images_tensor) ) if self._model_architecture in _NEMOTRON_OMNI_ARCHS: if isinstance(images_numpy, list): llm_inputs["multi_modal_data"]["image"] = [ ( Image.fromarray(img_arr.squeeze(0), mode="RGB") if img_arr.ndim == 4 else Image.fromarray(img_arr, mode="RGB") ) for img_arr in images_numpy ] else: # Squeeze batch dim if present: (1, H, W, C) → (H, W, C) img_arr = ( images_numpy.squeeze(0) if images_numpy.ndim == 4 else images_numpy ) llm_inputs["multi_modal_data"]["image"] = Image.fromarray( img_arr, mode="RGB" ) else: llm_inputs["multi_modal_data"]["image"] = images_numpy logger.debug( f"Request {request_id} entering AsyncLLMEngine queue. " f"Inflight requests: {len(self._inflight_req_ids)}" ) final_output = None with TimeMeasure("vLLM generate"): try: preprocess_limiter = getattr(self, "_multimodal_preprocess_limiter", None) if self._should_use_preprocess_admission( use_tensor_ipc, preprocess_limiter, ): output_stream = self._generate_with_preprocess_admission( llm_inputs, vllm_sampling_params, request_id, ) else: output_stream = self._llm.generate( llm_inputs, sampling_params=vllm_sampling_params, request_id=request_id, ) async for output_item in output_stream: final_output = output_item except ValueError as e: # vLLM raises ValueError for input-validation failures: decoder # prompt longer than max_model_len, image count over the # processor's per-prompt cap, etc. These are user-input issues # (too many frames for the chosen model), not server crashes. # Surface as ServiceException 400 with an actionable message # so the client knows what to change, and log a single-line # WARNING with the suggested fix instead of a multi-frame # traceback that drowns the logs (nvbug 6110762). self._inflight_req_ids.remove(request_id) err_msg = str(e) if ( "is longer than the maximum model length" in err_msg or "may be provided in one prompt" in err_msg ): logger.warning( "vLLM rejected input as exceeding model limits: %s. " "Reduce num-frames-per-second-or-fixed-frames-chunk, " "shorten chunk_duration, or raise VLM_MAX_MODEL_LEN to " "cover the prompt length.", err_msg, ) raise ServiceException( f"Input exceeds model limits: {err_msg} Reduce frames " f"per chunk or raise VLM_MAX_MODEL_LEN.", "InvalidParameter", 400, ) from e logger.error("Error during vLLM generate: %s", e) raise except Exception as e: logger.error("Error during vLLM generate: %s", e) self._inflight_req_ids.remove(request_id) raise e if not final_output: logger.warning("Async for retuned no output") self._inflight_req_ids.remove(request_id) return [ VlmModelOutput( output="Error: No response generated", input_tokens=0, output_tokens=0, ) ] self._inflight_req_ids.remove(request_id) return self._postprocess_vllm( [final_output], video_frames_times, chunk, ( vllm_sampling_params.ignore_eos if hasattr(vllm_sampling_params, "ignore_eos") else False ), preserve_reasoning_tags, generation_config.enable_reasoning if generation_config is not None else True, ) @staticmethod def _cuda_mm_residency_units(llm_inputs) -> int: """Return weighted CUDA residency units for one multimodal request. Up to 20 frames, processed-prompt residency scales closely enough with frame count to use one unit per 10 frames. Above 20 frames, the actual Qwen3-VL processed prompt grows much faster: allowing 21 resident 40-frame prompts raised frontend CUDA memory to 17.49 GiB and still OOMed. Weight those requests at four units per 10 frames, limiting the 8K processed-prompt buffer to eight requests. That matches the eight raw decoder buffers, keeps the encoder fed, and leaves the established 2K and 4K limits unchanged. """ try: video = llm_inputs["multi_modal_data"]["video"][0] video_tensor = video[0] if isinstance(video, tuple) else video num_frames = int(video_tensor.shape[0]) except (KeyError, IndexError, TypeError, AttributeError): return 1 linear_units = max(1, math.ceil(num_frames / _CUDA_MM_2K_REFERENCE_FRAMES)) if num_frames > (2 * _CUDA_MM_2K_REFERENCE_FRAMES): return linear_units * 4 return linear_units def _reserve_cuda_mm_residency(self, request_id, llm_inputs) -> None: units = self._cuda_mm_residency_units(llm_inputs) with self._cuda_mm_residency_lock: self._cuda_mm_resident_units_by_request[request_id] = units self._cuda_mm_pending_submission_ids.add(request_id) def _release_cuda_mm_residency(self, request_id) -> None: with self._cuda_mm_residency_lock: released_units = self._cuda_mm_resident_units_by_request.pop(request_id, None) if released_units is not None: # EngineCore has dropped its imported torch_shm tensors after the # vision encoder consumed them. Wake one coalescing collector so # PyTorch can retire the producer-side CUDA IPC refcounter leases. # Do not run ipc_collect() on the model event loop or empty the # allocator cache; both would add synchronization to inference. self._cuda_ipc_collect_event.set() def _collect_released_cuda_ipc_allocations(self) -> None: while True: self._cuda_ipc_collect_event.wait() self._cuda_ipc_collect_event.clear() try: torch.cuda.ipc_collect() except Exception: logger.exception("Failed to collect released CUDA IPC allocations") def _finish_cuda_mm_submission(self, request_id) -> None: with self._cuda_mm_residency_lock: self._cuda_mm_pending_submission_ids.discard(request_id) def _reserve_preprocess_submission(self, request_id) -> None: with self._cuda_mm_residency_lock: self._adaptive_preprocess_pending_submission_ids.add(request_id) def _finish_preprocess_submission(self, request_id) -> None: with self._cuda_mm_residency_lock: self._adaptive_preprocess_pending_submission_ids.discard(request_id) def can_enqueue_requests(self): """Check if the model can accept new requests.""" limiter = self._multimodal_preprocess_limiter if limiter is not None and not limiter.config.shadow_mode: with self._cuda_mm_residency_lock: if ( len(self._adaptive_preprocess_pending_submission_ids) >= limiter.queue_capacity() ): limiter.note_backpressure() return False if not limiter.can_accept(): limiter.note_backpressure() return False if self._use_cuda_mm_tensor_ipc: preprocess_capacity = _LEGACY_MAX_CONCURRENT_CUDA_MM_PREPROCESS if self._multimodal_preprocess_limiter is not None: preprocess_capacity = self._multimodal_preprocess_limiter.queue_capacity() with self._cuda_mm_residency_lock: if len(self._cuda_mm_pending_submission_ids) >= preprocess_capacity: return False if ( sum(self._cuda_mm_resident_units_by_request.values()) >= _MAX_RESIDENT_CUDA_MM_2K_EQUIVALENT_UNITS ): return False max_inflight = self._max_batch_size if _is_evs_session_enabled(): evs_max_inflight = _get_evs_max_inflight_clips() if evs_max_inflight is not None: max_inflight = min(max_inflight, evs_max_inflight) return len(self._inflight_req_ids) < max_inflight def release_idle_resources(self, wait_timeout_sec: float = 0.0): """Release allocator caches after the service becomes fully idle. The vLLM EngineCore owns a separate CUDA allocator. Clearing only the RTVI process cache therefore leaves encoder and worker allocations visible as used memory, which can make the live-stream admission guard reject the next benchmark level even though no requests remain. """ deadline = time.monotonic() + max(0.0, wait_timeout_sec) while True: with self._cuda_mm_residency_lock: pending = bool( self._adaptive_preprocess_pending_submission_ids or self._cuda_mm_pending_submission_ids or self._cuda_mm_resident_units_by_request ) with self._live_request_ids_lock: live_requests = bool(self._live_request_ids or self._live_request_futures) inflight = len(self._inflight_req_ids) if not inflight and not pending and not live_requests: break if time.monotonic() >= deadline: logger.info( "Skipping idle VLM resource release after %.1fs: inflight=%d, " "pending=%s, live_requests=%s", max(0.0, wait_timeout_sec), inflight, pending, live_requests, ) return False time.sleep(0.05) async def _release_engine_resources(): import cloudpickle try: await self._llm.pause_generation(mode="wait", clear_cache=True) worker_method = cloudpickle.dumps(_empty_vllm_worker_cuda_cache) return await self._llm.collective_rpc(worker_method, timeout=60.0) finally: await self._llm.resume_generation() worker_memory = asyncio.run_coroutine_threadsafe( _release_engine_resources(), self._event_loop ).result(timeout=90.0) torch.cuda.synchronize() torch.cuda.ipc_collect() torch.cuda.empty_cache() free_bytes, total_bytes = torch.cuda.mem_get_info() logger.info( "Released idle VLM resources: frontend_free=%d MiB/%d MiB, workers=%s", free_bytes // (1024 * 1024), total_bytes // (1024 * 1024), worker_memory, ) return True def is_healthy(self) -> bool: """Return false after the independently-running vLLM engine dies.""" engine = getattr(self, "_llm", None) if engine is None: return False errored = getattr(engine, "errored", None) if errored is not None: return not bool(errored() if callable(errored) else errored) is_stopped = getattr(engine, "is_stopped", None) if is_stopped is not None: return not bool(is_stopped() if callable(is_stopped) else is_stopped) return True def warmup(self): """Warm up the model with dummy tensors to initialize CUDA kernels and memory.""" logger.info("Starting model warmup...") # VLLM multimodal warmup - create dummy tensors and follow the complete VLLM flow. dummy_images = torch.stack( [torch.ones(100, 100, 3, dtype=torch.uint8).cuda() for _ in range(8)] ) video_warmup_prompt = "Describe this video briefly." video_warmup_config = VlmGenerationConfig( temperature=0.7, max_new_tokens=50, # Short for warmup top_p=0.9, top_k=100, repetition_penalty=1.1, seed=42, ) text_warmup_config = VlmGenerationConfig( temperature=0.4, max_new_tokens=8, top_p=0.8, top_k=20, repetition_penalty=1.1, seed=42, ) try: logger.info("Starting video model warmup...") video_ret = self.generate( video_warmup_prompt, chunks=[ChunkInfo()], # chunks video_frames=[dummy_images], # video_frames video_frames_times=[list(range(8))], # video_frames_times generation_config=video_warmup_config, ) video_result = video_ret.result() logger.info("Video model warmup completed") logger.info("Starting text-only model warmup...") text_ret = self.generate_text_only( messages=[{"role": "user", "content": "Reply with: ok"}], generation_config=text_warmup_config, ) text_result = text_ret.result() logger.info("Text-only model warmup completed") return text_result or video_result except Exception as e: logger.error("Error during model warmup: %s", e) raise e # --- EVS session helpers --- def _ensure_evs_handler(self): """Lazily create the EVS session handler.""" if self._evs_handler is None: from vllm.entrypoints.openai.serving_video_sessions import ( OpenAIServingVideoSessions, ) self._evs_handler = OpenAIServingVideoSessions( engine_client=self._llm, max_sessions=int(os.environ.get("VIA_EVS_MAX_SESSIONS") or "256"), pruning_rate=get_video_pruning_rate() or 0.5, similarity_threshold=_get_evs_similarity_threshold(), pd_server_url=os.environ.get("VIA_PD_SERVER_URL") or None, pd_server_timeout_s=float(os.environ.get("VIA_PD_SERVER_TIMEOUT_S") or "120.0"), ) if os.environ.get("VIA_EVS_STREAMING_PREFILL", "").lower() in ("true", "1"): self._evs_handler.streaming_prefill = True return self._evs_handler def _ensure_evs_session( self, stream_id, prompt="", max_tokens=2048, chunk_size_s=0, timestamp_prompt_template=None, generation_config=None, system_prompt=None, ): """Return (or create) the EVS session for *stream_id*.""" handler = self._ensure_evs_handler() token_budget = _get_evs_token_budget() model_name = self._vlm_model_type or self.model_dir_name event_only = os.environ.get("VIA_EVS_EVENT_ONLY", "false").lower() in ( "true", "1", ) event_chunk_duration_s = float(chunk_size_s) if chunk_size_s > 0 else 0.0 event_ema_memory_s = float(os.environ.get("VIA_EVS_EMA_MEMORY_S") or "0") event_spike_std_k = float(os.environ.get("VIA_EVS_SPIKE_STD_K") or "2.0") event_settling_std_k = float(os.environ.get("VIA_EVS_SETTLING_STD_K") or "1.5") event_std_floor_ratio = float(os.environ.get("VIA_EVS_STD_FLOOR_RATIO") or "0.1") event_min_clips = int(os.environ.get("VIA_EVS_MIN_CLIPS") or "3") # Later chunks a present chunk waits for before its decision (and idle # discard) commits. Buys slack for out-of-order arrivals; 1 suits # strictly in-order delivery, where the extra wait buys nothing. event_decision_lag = int(os.environ.get("VIA_EVS_DECISION_LAG") or "3") # Baseline floor below which downward ("comes to rest") detection is # suppressed. Auto-disables downward on static-camera streams (low # baseline) while keeping it for moving cameras (high baseline). Set # to 0.0 to always allow downward. event_downward_baseline_min = float( os.environ.get("VIA_EVS_DOWNWARD_BASELINE_MIN") or "0.10" ) event_chunk_duration_s_config = ( event_chunk_duration_s if event_chunk_duration_s > 0 else None ) event_ema_memory_s_config = event_ema_memory_s if event_ema_memory_s > 0 else None # Default sampling policy for this session's event-gated generations. # The detector triggers generation server-side with no per-call request # body, so the session must carry the same sampling knobs the non-EVS # path applies (defaults mirror VlmGenerationConfig). Deliberate # differences from the non-EVS path: # - temperature is ALWAYS sent: on the session schema an omitted # temperature defaults to 1.0 (stochastic), so temperature=0 must be # sent as 0.0 to actually get greedy decoding (the inverse of the # non-EVS "omit-when-zero" idiom). # - seed is forwarded into the session: a server-side session is not # affected by the process-global RNG reseed the non-EVS path does. # - ignore_eos / min_tokens are forwarded (see _build_evs_sampling_kwargs) # so VLLM_IGNORE_EOS reaches event-gated generations for OSL/perf runs. session_sampling_kwargs = _build_evs_sampling_kwargs(max_tokens, generation_config) # The key holds only what can actually differ between two requests on the # same stream. A session bakes these in at creation and keeps them for # its life, so reusing a session across a change here would answer with # the wrong prompt or sampling policy. # # Everything else in the create request below is deliberately excluded: # - The event_* tunables, token_budget and event_only are read from # os.environ on every call, so they are process constants. # - timestamp_prompt_template derives from those env vars plus whether # the source is RTSP, which is a property of the stream. # - event_chunk_duration_s is measured per chunk as # (end_pts - start_pts) / 1e9, and live chunks are finalized with # end_pts rewritten to the real last-frame PTS (see # video_file_frame_getter.py), so it lands on a different float every # chunk. Keying on it minted a new session per chunk until the engine # hit its max-sessions cap. It cannot discriminate anyway: a live # stream rejects a subscriber whose decode signature (chunk_duration # included) differs, and each file request gets its own stream id. # # Adding a request-overridable knob to the create request means adding it # here too; adding a process- or stream-scoped one does not. session_config_key = _freeze_evs_session_config( { "model": model_name, "prompt": prompt, "system_prompt": system_prompt or None, "sampling_params": session_sampling_kwargs, } ) session_cache_key = (stream_id, session_config_key) with self._evs_sessions_lock: if session_cache_key in self._evs_sessions: return self._evs_sessions[session_cache_key] from vllm.entrypoints.openai.engine.protocol import ( EvsAdvancedConfig, VideoSessionCreateRequest, VideoSessionSamplingParams, ) session_sampling_params = VideoSessionSamplingParams(**session_sampling_kwargs) request = VideoSessionCreateRequest( model=model_name, token_budget=token_budget, event_only=event_only, prompt=prompt, system_prompt=system_prompt or None, timestamp_prompt_template=timestamp_prompt_template, sampling_params=session_sampling_params, event_chunk_duration_s=event_chunk_duration_s_config, event_ema_memory_s=event_ema_memory_s_config, event_advanced=EvsAdvancedConfig( spike_std_k=event_spike_std_k, settling_std_k=event_settling_std_k, std_floor_ratio=event_std_floor_ratio, min_clips=event_min_clips, downward_baseline_min=event_downward_baseline_min, decision_lag=event_decision_lag, ), ) async def _create(): return await handler.create_session(request) try: resp = asyncio.run_coroutine_threadsafe(_create(), self._event_loop).result() except ServiceException: # Already classified (code + status_code) by the layer that raised # it; re-wrapping would flatten a 400 into a 500. logger.error( "EVS session creation failed for stream %s:\n%s", stream_id, traceback.format_exc(), ) raise except Exception as e: # The session manager raises bare RuntimeErrors, so without this the # caller only sees "An unknown error occurred" -- ProcessBase's # _handle_result forwards a message and status code only for a # ServiceException. The most common one is operator-fixable: # "Cannot create session: max sessions (N) reached", which is a # capacity condition (503) rather than an internal fault (500). is_at_capacity = "max sessions" in str(e).lower() logger.error( "EVS session creation failed for stream %s: %r\n%s", stream_id, e, traceback.format_exc(), ) hint = " Raise VIA_EVS_MAX_SESSIONS, Default value is 256." if is_at_capacity else "" raise ServiceException( f"EVS session creation failed for stream {stream_id}: {e}.{hint}", "EVSSessionCreateError", 503 if is_at_capacity else 500, ) from e duplicate_session_id = None with self._evs_sessions_lock: existing_session_id = self._evs_sessions.get(session_cache_key) if existing_session_id is not None: duplicate_session_id = resp.session_id session_id = existing_session_id else: self._evs_sessions[session_cache_key] = resp.session_id session_id = resp.session_id if duplicate_session_id is not None: logger.info( "Closing duplicate EVS session %s for stream %s after concurrent creation", duplicate_session_id, stream_id, ) async def _delete_duplicate(): await handler.delete_session(duplicate_session_id) asyncio.run_coroutine_threadsafe(_delete_duplicate(), self._event_loop).result() return session_id logger.info( "EVS session created: %s for stream %s (budget=%d, " "event_only=%s, similarity_threshold=%.2f, chunk_dur=%.2fs, " "ema_memory=%.2fs, spike_k=%.2f, settling_k=%.2f, " "std_floor_ratio=%.4f, min_clips=%d, " "downward_baseline_min=%.4f, decision_lag=%d)", session_id, stream_id, token_budget, event_only, _get_evs_similarity_threshold(), event_chunk_duration_s, event_ema_memory_s, event_spike_std_k, event_settling_std_k, event_std_floor_ratio, event_min_clips, event_downward_baseline_min, event_decision_lag, ) logger.info( "EVS session %s sampling: temp=%.2f top_p=%.2f top_k=%d " "rep_pen=%.2f seed=%s", session_id, session_sampling_params.temperature, session_sampling_params.top_p, session_sampling_params.top_k, session_sampling_params.repetition_penalty, session_sampling_params.seed, ) return session_id def _close_evs_session(self, stream_id): """Delete the EVS session for a single stream.""" self.close_evs_session(stream_id) def close_evs_session(self, stream_id=None): """Delete matching sessions, retaining failed releases for a later close.""" with self._evs_sessions_lock: session_items = [ (cache_key, session_id) for cache_key, session_id in self._evs_sessions.items() if stream_id is None or _evs_session_cache_stream_id(cache_key) == stream_id ] if session_items and self._evs_handler is not None: async def _delete_all(): first_error = None for cache_key, session_id in session_items: try: await self._evs_handler.delete_session(session_id) except Exception as error: if first_error is None: first_error = error logger.warning("Failed to close EVS session %s", session_id, exc_info=True) continue with self._evs_sessions_lock: if self._evs_sessions.get(cache_key) == session_id: self._evs_sessions.pop(cache_key) if first_error is not None: raise first_error asyncio.run_coroutine_threadsafe(_delete_all(), self._event_loop).result() logger.info( "EVS sessions closed: %s", [session_id for _cache_key, session_id in session_items], ) def _evs_strip_thinking_tags(self, text: str) -> tuple: """Extract reasoning from ..., return (content, reasoning). Mirrors models.common.utils.strip_thinking_tags used by via-engine; the rtvi target does not import that helper, so we inline a minimal version consistent with the regex pattern used in _postprocess_vllm above. """ if not text: return text or "", "" match = re.search(r"(.*?)", text, flags=re.DOTALL) reasoning = match.group(1) if match else "" if reasoning: text = re.sub(r".*?", "", text, flags=re.DOTALL) else: text, reasoning = self._remove_orphan_think_tags(text, reasoning) for tag in ["", "", "", ""]: text = text.replace(tag, "") return text.strip(), reasoning def _uses_absolute_timestamp_metadata(self) -> bool: """Whether absolute frame timestamps should be encoded in video metadata.""" return _VIDEO_METADATA_ABSOLUTE_TIMESTAMPS or _is_evs_session_enabled() def _generate_evs_session( self, prompt, images, generation_config, video_frames_times, chunk, timestamp_prompt_template=None, system_prompt=None, ): """EVS session flow: add clip as tensors, auto-generate when ready. Returns a concurrent.futures.Future so the VLM pipeline dispatcher thread can proceed to dequeue the next chunk without blocking. Up to max_batch_size add_clip_tensors coroutines run on the shared event loop concurrently, which is what lets vLLM actually batch across clips instead of processing them one at a time. """ stream_id = getattr(chunk, "streamId", None) if chunk else None if not stream_id: stream_id = "__default__" # generation_config may be either a dict (via-engine convention) or a # VlmGenerationConfig dataclass (rtvi convention). Support both. if isinstance(generation_config, dict): requested_mm_kwargs = generation_config.get("mm_processor_kwargs") preserve_reasoning_tags = generation_config.get("preserve_reasoning_tags", False) else: requested_mm_kwargs = getattr(generation_config, "mm_processor_kwargs", None) preserve_reasoning_tags = getattr(generation_config, "preserve_reasoning_tags", False) mm_processor_kwargs = _merge_mm_processor_kwargs( _EVS_MM_PROCESSOR_DEFAULTS, requested_mm_kwargs ) if mm_processor_kwargs.get("do_sample_frames"): # EVS pairs each frame with an explicit timestamp; resampling inside # the processor would desynchronise frames from timestamps. logger.warning( "Ignoring mm_processor_kwargs['do_sample_frames']=True for stream %s: " "EVS sessions require processor-side frame sampling to stay off.", stream_id, ) mm_processor_kwargs["do_sample_frames"] = False if isinstance(generation_config, dict): max_tokens = generation_config.get("max_new_tokens", 2048) else: max_tokens = getattr(generation_config, "max_new_tokens", 2048) chunk_size_s = 0 if chunk and chunk.start_pts >= 0 and chunk.end_pts > chunk.start_pts: chunk_size_s = (chunk.end_pts - chunk.start_pts) / 1e9 session_id = self._ensure_evs_session( stream_id, prompt=prompt, max_tokens=max_tokens, chunk_size_s=chunk_size_s, timestamp_prompt_template=timestamp_prompt_template, generation_config=generation_config, system_prompt=system_prompt, ) handler = self._evs_handler placeholder = [ VlmModelOutput(output="", input_tokens=0, output_tokens=0, reasoning_description="") ] # Prepare images (same transforms as regular path) if self._vlm_model_type == "cosmos-reason1": images = self.overlay_frame_number_cr1(images, video_frames_times) images = self.smart_resize_tensor(images) images = images.half() else: # cosmos-reason2 / Qwen3-VL: keep frames in their native # (T, H, W, C) layout and hand the HF processor numpy (see the CPU # handoff below). This mirrors the non-EVS video path, which # converts raw RTVI frames to numpy "so the model processor handles # layout and resizing normally". The previous permute to NCHW + # torch tensor made Qwen3-VL compute a degenerate video_grid_thw # (0 video tokens -> "0 prompt placeholders" crash at startup). pass # Cap frames the same way the regular path does. EVS prunes frames of # its own, but that happens *after* the encoder has seen the whole clip, # so an uncapped fps-based chunk would still be encoded in full and can # exceed what the vLLM processor accepts. Timestamps are subsampled with # the frames so the per-frame list handed to the session stays aligned. max_frames = _get_max_video_frames() original_frame_count = len(images) images, video_frames_times = _cap_video_frames(images, video_frames_times, max_frames) if len(images) != original_frame_count: logger.debug( "EVS clip: subsampled %d frames to %d (VLLM_MM_PROCESSOR_VIDEO_NUM_FRAMES)", original_frame_count, max_frames, ) # Pad a clip that falls below the video processor's temporal factor. # Qwen3-VL's smart_resize rejects a lone frame outright ("t:1 must be # larger than temporal_factor:2"). The regular path never gets there -- # a one-frame chunk goes down the image branch (is_single_image), which # has no temporal dimension -- but EVS has no image branch, so every # clip travels as a video. This is reachable from ordinary input: fps # chunking computes int(fps * chunk_seconds), so 4 fps over a 0.167s # clip asks for 0 frames and video_file_frame_getter clamps that to 1. # Repeat the last frame (with its timestamp) so the request still gets # an answer; the duplicate is exactly what EVS similarity pruning # collapses. if 0 < len(images) < _EVS_MIN_CLIP_FRAMES: has_aligned_times = bool(video_frames_times) and len(video_frames_times) == len(images) repeat_index = list(range(len(images))) repeat_index += [len(images) - 1] * (_EVS_MIN_CLIP_FRAMES - len(images)) logger.debug( "EVS clip: padded %d frame(s) to %d to satisfy the video " "processor's temporal factor", len(images), _EVS_MIN_CLIP_FRAMES, ) images = images[repeat_index] if has_aligned_times: video_frames_times = [video_frames_times[i] for i in repeat_index] # Build video metadata. Qwen3-VL's HF processor expects # frames_indices/fps for video inputs; keep absolute timestamps # operator-controlled, but still provide relative metadata by default. # It is never optional here: EVS has no single-image branch, so a # degenerate clip (one frame, or timestamps the decoder could not # supply) still goes over as a video. Handing the session an empty dict # leaves frames_indices unset, and Qwen3-VL only recomputes it when # do_sample_frames is on -- which EVS pins off -- so the clip dies in # the processor with "'NoneType' object has no attribute 'tolist'". has_frame_times = bool(video_frames_times) and len(video_frames_times) == len(images) duration = 0.0 if has_frame_times and len(video_frames_times) > 1: duration = video_frames_times[-1] - video_frames_times[0] if has_frame_times and self._uses_absolute_timestamp_metadata(): video_metadata = self._build_absolute_timestamp_video_metadata( images, video_frames_times, duration ) else: # Without usable frame times the clip loses its real timestamps, # not its caption: fall back to relative indices at a nominal fps. fps = 1 if duration > 0: fps = (len(video_frames_times) - 1) / duration video_metadata = { "total_num_frames": len(images), "frames_indices": list(range(len(images))), "fps": fps, "duration": duration, } is_last = getattr(chunk, "is_last", False) if chunk else False # Same decision as the metadata above: a list that does not describe the # frames being sent must not reach the session, which uses it for the # kept-frame timestamps and the {timestamps} prompt placeholder. The # fallback mirrors the relative metadata (indices at fps=1). if has_frame_times: client_timestamps = [float(t) for t in video_frames_times] else: client_timestamps = [float(i) for i in range(len(images))] ooo_chunk_id = getattr(chunk, "chunkIdx", None) if chunk is not None else None if len(images) < 3 and not is_last: logger.info("EVS skipping single-frame clip") done = concurrent.futures.Future() done.set_result(placeholder) return done # Move to CPU once on the dispatcher thread before handing off. # cosmos-reason1 keeps its torch (half) tensor path; all other models # (Qwen3-VL / cosmos-reason2) enter vLLM as numpy in native NHWC, which # is what the non-EVS video path does so the processor infers channel # layout and resizes normally (avoids a collapsed grid -> 0 video # tokens). # # CPU_COPY_OTHER_THREAD is deliberately NOT honored here. On the non-EVS # path it defers to asyncio.to_thread from an event loop that is never # blocked, so the copy starts at once. EVS's only other thread is an # _output_tpool worker, and those block for the whole add_clip_tensors # round trip (encode plus, when the detector fires, a full generation). # A deferred copy could therefore queue behind every worker and pin this # clip's CUDA frames (~49 MB for a 40-frame 640x640 chunk) for a whole # generation cycle -- to save ~14 ms on a dispatcher that is not the # bottleneck. Copying now lets the pipeline free the CUDA frames as soon # as generate() returns. if self._vlm_model_type == "cosmos-reason1": images_cpu = images.cpu() else: images_cpu = images.cpu().numpy() # Track in-flight count so _is_busy() gates at max_batch_size. request_id = str(uuid.uuid4()) self._inflight_req_ids.append(request_id) def _run_evs_clip(): async def _add(): return await handler.add_clip_tensors( session_id=session_id, images=images_cpu, metadata=video_metadata, mm_processor_kwargs=mm_processor_kwargs, timestamps=client_timestamps, is_last=is_last, chunk_id=ooo_chunk_id, ) try: clip_resp = asyncio.run_coroutine_threadsafe(_add(), self._event_loop).result() except ServiceException: # Already classified (code + status_code) by the layer that # raised it; re-wrapping would flatten a 400 into a 500. logger.error( "EVS add_clip_tensors failed for stream %s chunk %s:\n%s", stream_id, ooo_chunk_id, traceback.format_exc(), ) raise except Exception as e: # Surface as a chunk error rather than an empty caption. A # placeholder here made a failed clip indistinguishable from a # successful one with nothing to say, so neither the ERROR_BUS # nor the request's FAILED status ever saw the failure. As a # ServiceException the message survives ProcessBase's # _handle_result verbatim instead of becoming "An unknown error # occurred"; keeping the original text inline also preserves the # CUDA-OOM match that maps the chunk to 503. logger.error( "EVS add_clip_tensors failed for stream %s chunk %s: %r\n%s", stream_id, ooo_chunk_id, e, traceback.format_exc(), ) raise ServiceException( f"EVS clip processing failed for stream {stream_id} " f"(chunk {ooo_chunk_id}): {e}", "EVSClipProcessingError", 500, ) from e finally: # Keep the admission slot for the complete EVS operation, not # merely until its encoder finishes. The worker closure owns # images_cpu until add_clip_tensors returns after any triggered # generation. Releasing on_encode_done let a second full batch # accumulate while the first batch still retained its frames, # exhausting unified host/GPU memory on Thor (NVBug 6759865). if request_id in self._inflight_req_ids: self._inflight_req_ids.remove(request_id) logger.debug( "EVS clip: tokens=%d/%d, kept=%d, dropped=%d%s", clip_resp.tokens_used, clip_resp.tokens_used + clip_resp.tokens_remaining, clip_resp.frames_kept, clip_resp.frames_dropped, ", GENERATED" if clip_resp.generated else "", ) if clip_resp.generated: content = clip_resp.response_text or "" # Honor preserve_reasoning_tags the way _postprocess_vllm does on # the regular path: leave the raw text alone when the caller asked # to keep blocks in the output. if preserve_reasoning_tags: content, reasoning = content.strip(), "" else: content, reasoning = self._evs_strip_thinking_tags(content) usage = clip_resp.response_usage or {} # Log which time range the response actually covers # (may differ from the current chunk that triggered generation). if clip_resp.round_timestamps: ts = clip_resp.round_timestamps logger.debug( "EVS response covers timestamps: %.2f-%.2f " "(%d entries), response: %s", ts[0], ts[-1], len(ts), content, ) # NOTE: rtvi's VlmModelOutput has no evs_round_timestamps field; # we log it above instead of returning it. return [ VlmModelOutput( output=content, input_tokens=usage.get("prompt_tokens", 0), output_tokens=usage.get("completion_tokens", 0), reasoning_description=reasoning, ) ] return placeholder return self._output_tpool.submit(_run_evs_clip) def _shutdown_model(self): try: self.close_evs_session() except Exception: logger.debug("Error closing EVS sessions during shutdown", exc_info=True) logger.info("Shutting down VllmCompatibleModel...") # Shutdown the AsyncLLMEngine async def shutdown_engine(): self._llm.shutdown() asyncio.run_coroutine_threadsafe(shutdown_engine(), self._event_loop).result(timeout=5.0) # Stop the event loop gracefully logger.debug("Stopping event loop") self._event_loop.call_soon_threadsafe(self._event_loop.stop) self._event_loop_thread.join(timeout=5.0) # Close the event loop if not self._event_loop.is_closed(): self._event_loop.close() logger.info("VllmCompatibleModel shutdown complete") @property def num_time_tokens(self): return self._num_time_tokens def smart_resize_tensor(self, images: torch.Tensor) -> torch.Tensor: """ Resize a tensor image so that: - Its total pixels are between min_pixels and max_pixels. - Height and width are divisible by 'factor'. - Aspect ratio is preserved. """ # Assuming image is in (H, W, C) format n, c, h, w = images.shape logger.debug("smart_resize_tensor: n: %d, h: %d, w: %d, c: %d", n, h, w, c) orig_pixels = h * w n = n + n % 2 min_pixels = MIN_PIXELS / n max_pixels = MAX_PIXELS / n # Determine scaling factor based on pixel bounds scale = None if orig_pixels < min_pixels: scale = math.sqrt(min_pixels / orig_pixels) elif orig_pixels > max_pixels: scale = math.sqrt(max_pixels / orig_pixels) logger.debug( "smart_resize_tensor: scale: %s, orig_pixels: %d, min_pixels: %f, max_pixels: %f", scale, orig_pixels, min_pixels, max_pixels, ) if scale is not None: new_h = int(round(h * scale)) new_w = int(round(w * scale)) new_w = new_w // FACTOR * FACTOR new_h = new_h // FACTOR * FACTOR images = TF.resize( images, [new_h, new_w], interpolation=TF.InterpolationMode.BICUBIC, antialias=True, ) logger.debug("smart_resize_tensor: resized tensor shape: %s", images.shape) return images def _build_absolute_timestamp_video_metadata(self, images, video_frames_times, duration): """Build video metadata with absolute timestamps encoded in frames_indices. Uses a synthetic fps=1000 so frame_index/fps recovers the real timestamp (ms resolution) instead of a 0-based chunk-relative offset. Preserves absolute start offset and non-uniform frame spacing. """ return { "total_num_frames": len(images), "frames_indices": [ int(round(float(t) * _ABSOLUTE_TIMESTAMP_SOURCE_FPS)) for t in video_frames_times ], "fps": _ABSOLUTE_TIMESTAMP_SOURCE_FPS, "duration": duration, } def _resolve_system_prompt(self, config: VlmGenerationConfig) -> str: """Per-request system prompt, falling back to the model's default.""" return config.system_prompt if config.system_prompt else self._system_prompt def _apply_reasoning_prompts(self, query_text, system_prompt, config): """Add the model-appropriate ```` format instruction. Shared by the regular generate path and the EVS session path. cosmos-reason1 takes the instruction on the system prompt; cosmos-reason2 and cosmos-reason3 take it on the user query. Returns ``(query_text, system_prompt)`` unchanged when reasoning is off or an instruction is already present. """ system_prompt = system_prompt or "" if not config.enable_reasoning: return query_text, system_prompt if self._vlm_model_type == "cosmos-reason1" and "" not in system_prompt: system_prompt += ( " Answer the question in the following format: " "\nyour reasoning\n\n\n\nyour answer\n.\n" ) elif ( self._vlm_model_type in ("cosmos-reason2", "cosmos-reason3") and "" not in query_text and "" not in system_prompt ): query_text += ( "Answer the question using the following format:\n\n" "\n" "Your reasoning.\n" "\n\n" "Write your final answer immediately after the tag.\n" ) return query_text, system_prompt def _apply_timestamp_prompt(self, query_text, chunk, video_frames_times): """Prepend/append the timestamp prompt to the user query. Shared by the regular generate path and the EVS session path so both inject an identical, env-configurable timestamp prompt (``RTVI_ADD_TIMESTAMP_TO_VLM_PROMPT`` plus the optional ``RTVI_TIMESTAMP_PROMPT_*`` templates). Returns ``query_text`` unchanged when disabled or when chunk / frame-time data is missing. NOTE (EVS session path): the session prompt is fixed at session creation, so the injected timestamps reflect the *first* clip's frame times, not the full merged range seen at generate time. """ add_timestamp_to_prompt = ( self._vlm_model_type != "cosmos-reason1" and ADD_TIMESTAMP_TO_PROMPT ) if not (add_timestamp_to_prompt and chunk and video_frames_times): return query_text is_rtsp = chunk.file.startswith("rtsp://") prefix_tpl = _TIMESTAMP_PROMPT_PREFIX_RTSP if is_rtsp else _TIMESTAMP_PROMPT_PREFIX_FILE suffix_tpl = _TIMESTAMP_PROMPT_SUFFIX_RTSP if is_rtsp else _TIMESTAMP_PROMPT_SUFFIX_FILE first_ts = chunk.get_timestamp(video_frames_times[0]) last_ts = chunk.get_timestamp(video_frames_times[-1]) if prefix_tpl or suffix_tpl: string_of_times = " ".join(chunk.get_timestamp(t) for t in video_frames_times) fmt_kwargs = dict( timestamps=string_of_times, query=query_text, first_ts=first_ts, last_ts=last_ts, ) parts = [] if prefix_tpl: parts.append(prefix_tpl.format(**fmt_kwargs)) parts.append(query_text) if suffix_tpl: parts.append(suffix_tpl.format(**fmt_kwargs)) return "\n".join(parts) # Preserve the established non-EVS prompt when no operator override is # supplied. EVS deliberately does not reuse this per-clip wording: an # EVS event can merge several clips and needs an explicit template whose # timestamps are filled only after the full event range is known. string_of_times = "".join( chunk.get_timestamp(frame_time) + " " for frame_time in video_frames_times ) return ( "These are images sampled from the same video at times " + string_of_times + ". " + query_text ) def generate( self, query: str, chunks: List[ChunkInfo], video_frames: Optional[List[torch.Tensor]] = None, video_frames_times: List[List[float]] = None, generation_config: Optional[VlmGenerationConfig] = None, audio_frames=None, **kwargs, ): """Generate a response for prompt using the video frames Args: query: Prompt for the VLM model or ChatConversation object chunks: List of chunk information video_frames: List of video frames video_frames_times: List of video frame times generation_config: VLM generation config. Defaults to None. audio_frames: Decoded audio frames from video. Defaults to None. **kwargs: Additional keyword arguments for future extensibility and API compatibility across different model implementations. Currently unused but preserved for maintaining consistent interface across all model classes. Returns: List of responses for the batch of chunks """ query_text = query video_frames_times = video_frames_times[0] chunk = chunks[0] # Get generation config with defaults config = generation_config or VlmGenerationConfig() config = self._resolve_prompt_reasoning_config(config) # Route to EVS session mode if configured. EVS owns its own prompt # construction / mm-data path and returns a concurrent.futures.Future # so the caller's contract (Future[List[VlmModelOutput]]) is preserved. # NOTE: video_frames[0] is the first batch entry (rtvi wraps frames in # an outer list); matches what the non-EVS path uses for `images`. if os.environ.get("VIA_EVS_SESSION", "").lower() in ("true", "1"): # EVS spans multiple clips, so pass the selected source's template # unfilled. vLLM fills timestamps from the complete merged event # range. With no prefix/suffix override, EVS uses the dev/aa/evs # timestamp instruction while non-EVS profiles keep their defaults. want_ts = self._vlm_model_type != "cosmos-reason1" and ADD_TIMESTAMP_TO_PROMPT ts_template = None if want_ts and chunk: is_rtsp = chunk.file.startswith("rtsp://") prefix_tpl, suffix_tpl, used_evs_default = _get_timestamp_prompt_templates( is_rtsp, use_evs_default=True, ) if prefix_tpl or suffix_tpl: if used_evs_default: ts_template = "{query}" + suffix_tpl else: template_fields = { field_name.split(".")[0].split("[")[0] for template in (prefix_tpl, suffix_tpl) for _, field_name, _, _ in string.Formatter().parse(template) if field_name is not None } template_parts = [] if prefix_tpl: template_parts.append(prefix_tpl) if "query" not in template_fields: template_parts.append("{query}") if suffix_tpl: template_parts.append(suffix_tpl) ts_template = "\n".join(template_parts) # Resolve the system prompt and the reasoning instruction exactly as # the non-EVS path does. Both are fixed for the life of the session # (see _ensure_evs_session), so they are applied here, at creation # time, rather than per clip. evs_system_prompt = self._resolve_system_prompt(config) query_text, evs_system_prompt = self._apply_reasoning_prompts( query_text, evs_system_prompt, config ) # Pass the FULL generation config (not just max_new_tokens) so the # session can apply the configured sampling params to its # event-gated generations; see _ensure_evs_session. return self._generate_evs_session( query_text, video_frames[0], config, video_frames_times, chunk, timestamp_prompt_template=ts_template, system_prompt=evs_system_prompt, ) # Build generation params dict for the model (excluding non-generation params) generation_params = { "max_new_tokens": config.max_new_tokens, "top_p": config.top_p, "top_k": int(config.top_k), "repetition_penalty": config.repetition_penalty, "temperature": config.temperature, } # Set the seed seed = config.seed random.seed(seed) numpy.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) # Handle system prompt system_prompt = self._resolve_system_prompt(config) # Override system prompt in environment variable with reasoning prompt if enable_reasoning is True query_text, system_prompt = self._apply_reasoning_prompts(query_text, system_prompt, config) if self._vlm_model_type == "cosmos-reason1": cr1_frames = video_frames[0] if isinstance(cr1_frames, torch.Tensor) and not cr1_frames.is_cuda: cr1_frames = cr1_frames.cuda(non_blocking=True) images = self.overlay_frame_number_cr1(cr1_frames, video_frames_times).half() # convert PIL Images to tensors images = self.smart_resize_tensor(images) else: images = video_frames[0] # Cap frames to VLLM_MM_PROCESSOR_VIDEO_NUM_FRAMES to prevent vLLM rejecting # >256 images. When fps-based chunking produces many frames (e.g. 10fps × 60s = 600), # uniformly subsample to the configured limit before sending to the engine. max_frames = _get_max_video_frames() original_frame_count = len(images) images, video_frames_times = _cap_video_frames(images, video_frames_times, max_frames) if len(images) != original_frame_count: logger.info( "VLM generate: subsampled %d frames to %d (VLLM_MM_PROCESSOR_VIDEO_NUM_FRAMES)", original_frame_count, max_frames, ) # Audio is processed natively by the VLM when VLM_MODEL_SUPPORTS_AUDIO=true. # RIVA ASR is not yet supported; process_audio_in_vlm is true only for Omni models. process_audio_in_vlm = os.environ.get("VLM_MODEL_SUPPORTS_AUDIO", "false").lower() == "true" # Handle nested list structure: audio_frames is [[dict, ...]] # Only check for audio data if VLM should process it has_audio = False if process_audio_in_vlm and audio_frames is not None and len(audio_frames) > 0: if isinstance(audio_frames[0], list): # Nested list structure: [[dict, ...]] inner = audio_frames[0] has_audio = ( len(inner) > 0 and isinstance(inner[0], dict) and inner[0].get("audio") is not None ) elif isinstance(audio_frames[0], dict): # Flat list structure: [dict, ...] has_audio = audio_frames[0].get("audio") is not None query_text = self._apply_timestamp_prompt(query_text, chunk, video_frames_times) # VLLM model generation is_single_image = len(images) == 1 use_multi_image_chunk_input = ( not is_single_image and _parse_bool_env("VLLM_MULTI_IMAGE_CHUNK_INPUT", False) and self._model_architecture not in _NEMOTRON_OMNI_ARCHS and not has_audio ) if ( not is_single_image and _parse_bool_env("VLLM_MULTI_IMAGE_CHUNK_INPUT", False) and (has_audio or self._model_architecture in _NEMOTRON_OMNI_ARCHS) ): logger.warning( "Ignoring VLLM_MULTI_IMAGE_CHUNK_INPUT for unsupported chunk shape; " "falling back to video multimodal input." ) if is_single_image: input = (images if CPU_COPY_OTHER_THREAD else _frame_batch_as_numpy(images),) elif use_multi_image_chunk_input: input = list(images) if CPU_COPY_OTHER_THREAD else list(_frame_batch_as_numpy(images)) else: duration = video_frames_times[-1] - video_frames_times[0] if self._uses_absolute_timestamp_metadata(): video_metadata = self._build_absolute_timestamp_video_metadata( images, video_frames_times, duration ) else: fps = 1 if len(video_frames_times) > 1 and duration > 0: fps = (len(video_frames_times) - 1) / duration video_metadata = { "total_num_frames": len(images), "frames_indices": list(range(len(images))), "fps": fps, "duration": duration, } input = ( images if CPU_COPY_OTHER_THREAD else _frame_batch_as_numpy(images), video_metadata, ) # Single query mode messages = [] logger.debug("System prompt %s user prompt %s", system_prompt, query_text) if system_prompt: messages.append( { "role": "system", "content": system_prompt, } ) # Build message content based on modalities message_content = [] if is_single_image: message_content.extend( [ {"type": "text", "text": query_text}, {"type": "image", "image": "sample.jpg"}, ] ) elif use_multi_image_chunk_input: message_content.append({"type": "text", "text": query_text}) message_content.extend( {"type": "image", "image": f"frame_{idx:06d}.jpg"} for idx in range(len(images)) ) else: message_content.extend( _build_video_message_content( query_text, self._vlm_model_type, self._model_architecture ) ) # Add audio if VLM should process it natively (not handled by RIVA ASR) if process_audio_in_vlm and has_audio: message_content.append({"type": "audio", "audio": "sample.wav"}) messages.append( { "role": "user", "content": message_content, } ) # Reasoning-capable chat templates open a block by default. Keep the RTVI # default non-reasoning unless the request explicitly enables reasoning. apply_chat_template_kwargs = self._get_apply_chat_template_kwargs(config) prompt = self._apply_chat_template(messages, config) # NemotronH_Nano_VL_V2/Omni_Reasoning_V3 chat template stringifies multimodal content # dicts rather than inserting placeholder tokens. Detect this and rebuild with explicit # placeholders so vLLM can find and replace them with visual features. if self._model_architecture in _NEMOTRON_OMNI_ARCHS: if is_single_image and "" not in prompt: image_placeholder = f"{query_text}\n" fallback_messages = ( [{"role": "system", "content": system_prompt}] if system_prompt else [] ) + [{"role": "user", "content": image_placeholder}] prompt = self._processor.apply_chat_template( fallback_messages, tokenize=False, add_generation_prompt=True, **apply_chat_template_kwargs, ) elif not is_single_image and "