How to Add Video Input to a Multimodal Inference Service

    This article explains how a multimodal inference service can accept video alongside text and images. It covers why video needs its own design, the overall data flow, video decoding, frame sampling strategies, temporal chunking, shared image preprocessing, visual token control, and the adjustments an inference service needs for video.

    1. Why Video Input Needs a Separate Design

    Text and image inputs into multimodal models are already well established. Text is tokenized and converted into vectors through an embedding layer. Images are decoded, resized, and split into patches before they enter a vision encoder. A video may look like a collection of images, but it adds three problems. It contains far more frames than a single image, the frames have a temporal order, and the computation grows linearly with the number of frames. If every frame goes directly into the vision encoder, GPU memory use and latency quickly exceed what an online service can handle. The core task of the video pipeline is to keep temporal information while controlling the size of the input.

    2. Overall Data Flow

    The three modalities can be viewed as three entry points into the same pipeline:

    • Text: tokenization and embedding, which produce the input vectors for the language model.
    • Image: reading and decoding into pixels, image preprocessing, then visual encoding.
    • Video: reading and decoding into a sequence of frames, sampling frames, and dividing them into temporally ordered chunks. Each chunk enters the same preprocessing and visual encoding pipeline as an image batch, and the temporal order is preserved.

    The visual encoder’s output is mapped into the language model’s hidden space by a projection module. The projected features are placed at placeholder positions and concatenated with the text vectors. The language model then generates the response. Video reuses the image vision path. It adds three steps at the front end (reading, frame sampling, and chunking) and adds temporal information at the back end.

    3. Video Reading and Decoding

    Decoding must handle differences in container formats, encoding formats, frame rates, and resolutions. In practice, follow these principles:

    1. Read the metadata first to get the total duration, original frame rate, resolution, and total frame count. Later sampling calculations depend on these values.
    2. Decode on demand. Do not decode the entire video into memory at once. Full decoding of a long video quickly fills memory.
    3. When decoding fails, return a clear error message and log the failing request and position to make troubleshooting easier.

    4. Frame Sampling Strategies

    Sampling determines how much information the model can receive. There are three common strategies:

    • Uniform sampling with a fixed frame count: take a fixed number of frames regardless of video length. This is simple and gives a predictable input size. Short videos get oversampled, and details in long videos are easily lost.
    • Fixed-rate sampling: extract a set number of frames per second. This gives stable temporal resolution, but the frame count grows quickly for long videos.
    • Hybrid strategy: set both a target frame rate and a maximum frame count. Calculate the frame count from the target rate first. If the result exceeds the maximum, thin the frames at equal intervals.

    The hybrid strategy limits both the input size and the temporal coverage, so it works well as the default. Below is an illustrative implementation:

    1. def sample_indices(total_frames, src_fps, target_fps, max_frames):
    2. duration = total_frames / src_fps
    3. n = min(int(duration * target_fps), max_frames)
    4. n = max(n, 1)
    5. step = total_frames / n
    6. return [min(int(i * step), total_frames - 1) for i in range(n)]

    The actual values must match the sampling settings used during model training. Bias in the sampling distribution directly affects response quality.

    5. Temporal Chunking and Time Information

    After sampling, the frames are organized into temporal chunks. Chunking serves two purposes. It keeps each batch that the vision encoder processes at a manageable size, and it preserves the temporal relationships between neighboring frames within a local range. Adjacent chunks can overlap to reduce the chance that an action is cut off at a chunk boundary.

    1. def chunk_frames(indices, chunk_size, overlap):
    2. stride = chunk_size - overlap # Requires stride > 0
    3. chunks = []
    4. for start in range(0, len(indices), stride):
    5. chunk = indices[start:start + chunk_size]
    6. if chunk:
    7. chunks.append(chunk)
    8. if start + chunk_size >= len(indices):
    9. break
    10. return chunks

    Time information can be passed to the model in two main ways:

    • Explicit injection: add temporal position encodings to the visual features, or add timestamp text for each frame to the prompt, so the language model can recognize which second a frame belongs to. A timestamp can be calculated by dividing the frame index by the original frame rate.
    • Implicit ordering: rely only on the order of frames in the sequence and let the model structure learn the temporal relationships.

    The right choice depends on the conventions set during model training. If the time encoding does not match training, answers to time-related questions degrade noticeably. This is the issue most often overlooked during deployment.

    6. Shared Image Preprocessing

    Video frames and images go through the same preprocessing pipeline, which includes these steps:

    1. Resizing: resize to the resolution limits the model requires while keeping the aspect ratio. Crop or pad when necessary.
    2. Padding: use a neutral fill value to avoid color casts.
    3. Normalization: use the mean and standard deviation from model training.
    4. Patch splitting: divide the image into fixed-size patches and flatten them into a sequence.

    Reusing the same preprocessing keeps the logic consistent and lets test cases be shared. Frame resolution should be more conservative than single-image resolution. The visual token count grows quickly when the frame count is multiplied by the resolution.

    7. Visual Encoding and Feature Fusion

    The visual encoder outputs a feature sequence for each chunk. The projection module then maps these features to the hidden dimension of the language model. Videos usually produce far more visual tokens than images. Common ways to control the token count include:

    • Pooling or merging features of adjacent frames along the time dimension.
    • Setting a token limit for each chunk and downsampling when the limit is exceeded.
    • Removing adjacent frames that are nearly identical.

    For capacity planning, estimate the total number of visual tokens as (number of frames × patches per frame) ÷ merge ratio. Then compare the result with the language model’s context length.

    During fusion, the prompt template reserves placeholders for video. Each placeholder is replaced with the corresponding visual feature sequence, and the result is concatenated with the text sequence. The placeholder order must match the temporal order. Otherwise, the model reads a scrambled sequence of events.

    8. Adapting the Inference Service Layer

    Starting from request intake, the service layer needs to handle the following:

    • Parameter validation: identify the type of each multimodal input. For video, set limits on maximum duration, maximum resolution, and maximum frame count to keep oversized inputs from exhausting resources.
    • Asynchronous preprocessing: run decoding and frame sampling in a separate thread pool or process pool so they do not block the inference main loop.
    • Result caching: use a hash of the video content together with the sampling parameters as the cache key, and cache the sampled frames or visual features. Repeated requests can then skip front-end processing.
    • Memory budget: estimate for the worst case, which is the maximum number of chunks multiplied by the visual tokens per chunk, multiplied by the number of concurrent requests. Leave a safety margin in the budget.