Self-Hosted Multimodal Inference with Video Input: A Practical Implementation Guide

    This article explains how to extend a self-hosted multimodal inference service to accept video input. It covers model capability boundaries, video decoding and frame sampling parameters, temporal encoding and visual-token budgeting, request protocol and deployment recipes, health checks and rollback, and an evaluation checklist. The goal is to help teams implement video requests without changing the core inference stack when the model already supports the required temporal information.

    1. Confirm Capability Boundaries and Model Prerequisites

    Before modifying the inference service, confirm whether the model can process video. The main difficulty with video input is temporal information. If multiple frames are simply concatenated in order, the model cannot reliably distinguish what happened first and what happened later. As a result, the modification cost varies significantly across models.

    Model situation Can it be reused directly? What needs to be done
    Natively supports video input with temporal positional encoding The vision encoder and projection layer can be reused Mainly modify preprocessing and the request protocol
    Supports only multi-image input without temporal encoding Frames can be fed into the vision encoder one by one Add timestamp text or temporal markers, and run regression validation
    Requires a new temporal module or retraining Cannot be completed only with an inference-side plugin Out of scope for this article; requires a separate project

    For example, the Qwen2-VL series officially supports video input and handles frame order through time-dimensional positional encoding (M-RoPE). Models such as LLaVA-NeXT-Video also have corresponding video processing approaches. For supported input formats, frame limits, and inference framework versions, refer to the model’s official documentation and the actual deployed version.

    2. Decoding and Frame Sampling: How to Set Parameters

    2.1 Choosing a Decoding Tool

    There are three common decoding options. decord is convenient for random frame sampling and suitable for retrieving frames by index. PyAV is based on FFmpeg bindings, covers a wide range of formats, and fits scenarios that require fine-grained control. torchvision.io integrates easily with PyTorch data flows. A team only needs to choose one option and does not need to maintain multiple sets at the same time.

    Below is a frame sampling example based on decord:

    1. import numpy as np
    2. from decord import VideoReader, cpu
    3. def sample_frame_indices(total_frames, src_fps, sample_fps=1.0,
    4. min_frames=4, max_frames=32):
    5. duration = total_frames / src_fps
    6. n = int(round(duration * sample_fps))
    7. n = max(min_frames, min(n, max_frames))
    8. n = min(n, total_frames)
    9. # Uniformly select n indices across the entire video
    10. return np.linspace(0, total_frames - 1, n).round().astype(int).tolist()
    11. def load_frames(path, **kwargs):
    12. vr = VideoReader(path, ctx=cpu(0))
    13. indices = sample_frame_indices(len(vr), vr.get_avg_fps(), **kwargs)
    14. frames = vr.get_batch(indices).asnumpy() # shape (N, H, W, C)
    15. return frames, indices

    In practice, two additional points need to be handled. First, some mobile videos carry rotation metadata, and the decoded frame orientation may be wrong; the frames need to be rotated according to the metadata. Second, read the video duration and resolution before frame sampling. Requests that exceed the limits should be rejected or processed in segments rather than fully decoded before making a decision.

    Parameter Default value Description
    sample_fps 1.0 Frames sampled per second, suitable for most short videos
    min_frames 4 Guarantees a minimum number of frames even for very short videos
    max_frames 32 Per-request frame limit; downsampling is applied automatically when exceeded
    max_frame_side 448 Longest side of a single frame in pixels; can be lowered when GPU memory is tight
    max_duration_sec 600 Videos exceeding this duration are rejected or segmented
    chunk_size 2 Number of frames in each temporal chunk; must match the model’s temporal merge stride

    These values are starting points, not final conclusions. Teams should compare results on their own video samples before deciding on final values.

    2.3 How to Choose a Frame Sampling Strategy

    Strategy Suitable scenario Frame count characteristics Memory risk Recommendation
    Uniform sampling Long videos with stable visual changes Fixed at N frames Low Use as the default strategy
    Frame-rate sampling Short videos with dense motion Grows linearly with duration Grows with duration A frame limit is mandatory
    Hybrid keyframe sampling Videos with frequent scene changes Dynamically allocated within a budget Medium; detection itself has extra overhead Enable only when the data volume is large enough

    2.4 Common Mistakes

    1. Looking only at frame count and ignoring resolution. With the same number of frames, high-resolution frames can produce several times more visual tokens than low-resolution frames, and GPU memory usage grows accordingly.
    2. Ignoring rotation metadata, causing the model to read upside-down or sideways frames and significantly reducing answer quality.
    3. Confusing frame indices with timestamps. Sampling indices and display times are not the same quantity; temporal encoding should use actual timestamps.
    4. Fully decoding very long videos and causing process memory overflow. Duration checks should be completed before frame sampling.
    5. The number of visual placeholders does not match the actual number of frames, causing request errors on the model side. A count check should be performed during preprocessing.

    3. Temporal Encoding and Framework Adaptation

    3.1 How Temporal Information Is Passed to the Model

    The way temporal information is passed depends on the model. For models that natively support temporal positional encoding, pass the video’s temporal grid information through the official processor. Do not calculate positional encoding yourself, as this can easily diverge from the distribution used during training.

    For models without temporal encoding, you can insert temporal text before each temporal chunk, such as “from second 2.0 to second 4.0.” This approach is simple to implement, but its effectiveness depends on the model’s ability to understand textual time and must be validated through evaluation.

    3.2 Estimating the Number of Visual Tokens

    The GPU memory cost of a video request mainly comes from visual tokens. The estimation formula is:

    Visual tokens per request ≈ ceil(N ÷ T) × (H ÷ p) × (W ÷ p) ÷ m²

    Here, N is the number of frames, T is the temporal merge stride, H and W are the height and width of a single frame, p is the patch size, and m is the spatial merge factor. Use the values defined by the preprocessor of the model you are using.

    For example, assume N = 32, T = 2, a single frame of 448×448, p = 14, and m = 2. There are 16 groups in the temporal direction, and each spatial group yields 256 tokens, for a total of about 4096 visual tokens. This is about 16 times a single 448×448 image (256 tokens).

    3.3 Scheduling and Memory Quotas

    It is recommended to set a separate quota for video requests so that long videos do not consume the concurrency capacity of text and image requests:

    • Per-request visual token limit, default 4096; downsample or reject when exceeded;
    • Video request concurrency limit, default 2, scheduled separately from the text queue;
    • Reserve KV cache space based on the number of visual tokens rather than the number of images;
    • Set a separate timeout for video requests, default 120 seconds.

    3.4 Prefix Caching

    When the same video is asked about multiple times, the encoding results of its visual tokens can be cached. The cache key should include the following information: the SHA-256 of the video content, sampling parameters, model version, and processor version. Any change to any of these must invalidate the old cache.

    The cache also needs an expiration time (for example, 1 hour) and a total capacity limit. When the limit is exceeded, evict entries according to least recently used (LRU) policy. When using prefix caching, place the video at the front of the prompt and the question at the back, so that different questions can share the video prefix.

    4. Plugin Interface and Deployment Recipe

    4.1 Request Protocol Example

    1. {
    2. "model": "your-vl-model",
    3. "messages": [
    4. {
    5. "role": "user",
    6. "content": [
    7. {"type": "video", "video_uri": "s3://your-bucket/clip.mp4"},
    8. {"type": "text", "text": "What actions do the people in the video perform?"}
    9. ]
    10. }
    11. ],
    12. "video_options": {
    13. "max_frames": 32,
    14. "sample_fps": 1.0,
    15. "chunk_size": 2,
    16. "return_temporal_pos": true
    17. }
    18. }

    video_uri should only accept allowlisted buckets or domains to prevent server-side request forgery (SSRF).

    4.2 Error Codes

    Error code HTTP status Meaning
    VIDEO_URI_INVALID 400 Invalid address format or address not in the allowlist
    VIDEO_TOO_LONG 413 Video duration exceeds max_duration_sec
    VIDEO_CODEC_UNSUPPORTED 415 Codec not supported by the decoder
    VIDEO_DECODE_FAILED 422 Decoding failed; the file may be corrupted
    VISUAL_TOKEN_EXCEEDED 413 Visual tokens exceed the per-request limit
    VIDEO_FETCH_TIMEOUT 504 Fetching the video file timed out

    4.3 Deployment Recipe Directory

    1. video-plugin/
    2. plugin.yaml # Plugin name, version, entry module
    3. config.yaml # Frame sampling parameters and quota defaults
    4. requirements.lock # Version lock for decoding libraries and dependencies
    5. deploy/values.yaml # Container resources, replica count, probe configuration
    6. healthcheck.sh # Health check script

    The recipe should lock the following versions: the model weight revision (using a commit hash is recommended), vision components, processor, decoding library, FFmpeg, and inference framework. After versions are locked, any upgrade should go through a canary rollout process.

    4.4 Health Checks

    Health checks should be divided into two layers. The first layer checks the inference service itself:

    1. curl -fsS http://127.0.0.1:8000/health

    The second layer checks plugin status, including decoder availability and the FFmpeg version:

    1. curl -fsS http://127.0.0.1:8000/plugins/video/health

    This endpoint should return the decoder name, FFmpeg version, and the duration of the most recent decode. The container readiness probe should check both endpoints and only accept traffic when both pass.

    4.5 Release and Rollback

    Keep the previous image tag for every release. Deploy the new version with a small number of replicas first, and observe the error rate and P95 latency. If the error rate exceeds the threshold, switch back to the previous version directly. The threshold is set by the team according to the business, for example, rolling back when the error rate exceeds 1% for 5 consecutive minutes.

    5. Evaluation and Acceptance

    5.1 Building an Evaluation Set

    The evaluation set should contain no fewer than 200 video question-answering samples, covering the following types: short videos and long videos, single actions and multi-step events, causal relationships, on-screen text or subtitles, and multi-person scenes. Each sample needs a human-annotated reference answer.

    5.2 Comparison Metrics

    Metric Description
    Answer accuracy Human or rule-based scoring, reported separately by type
    Agreement rate with the reference system Proportion of identical outputs for the same input on the comparison system
    First-token latency Latency from request submission to the first token