Native Video Input for Multimodal Inference Services: Engineering Practices

    This article explains how to add native video support to self-hosted multimodal inference services. It describes the shared input path for text, image, and video, the key video processing stages, plugin-based packaging, request protocols, service constraints, deployment practices, and validation checks needed to bring video input to production.

    1. Problem Definition: Why Video Is the Hardest Input to Complete

    Managed cloud APIs often treat video as a first-class input type. For teams that want to build their own inference service and embed multimodal capability into their own business workflows, the situation is often different. Early versions of many open-source multimodal inference pipelines fully support only text and single-image paths: text is tokenized and vectorized, while images go through decoding, preprocessing, visual encoding, and projection alignment. Video is either missing or supported only through a degraded approach that treats the video as a set of unrelated images.

    The resulting gap is concrete. Video parameters submitted by clients may be ignored or rejected. Missing temporal information makes it impossible to answer questions about what happened before what. Long videos may be truncated entirely or exhaust the context window during the prefill stage. Adding video capability is therefore not simply adding a parameter. It means completing a processing path from request ingress to visual feature fusion.

    2. Unified Input Abstraction: How Three Modalities Converge into One Language Model

    Before designing the video path, it helps to see where the three input paths converge:

    • Text: raw string → tokenization → vocabulary mapping → input vector sequence.
    • Image: byte stream → decoding into a pixel matrix → resize/pad/normalize → patch splitting → visual encoding → projection into the language model dimension.
    • Video: byte stream or frame sequence → decoding into image frames → frame sampling according to policy → temporal chunking with order preservation → the same preprocessing and encoding flow shared with images.

    The key step is the last one. After temporal organization, video can reuse the existing image preprocessing, visual encoder, and projection module. There is no need to train an entirely new vision tower for video. This is the core premise that allows the service to gain video capability without expanding the model, and it is also the technical basis for delivering the capability as a plugin.

    3. Four Key Stages of the Video Pipeline

    3.1 Decoding and Frame Sampling: Balancing Information and Cost

    The decoding stage reconstructs the video stream from the container format into a frame sequence. The sampling policy directly determines what the model sees. Common policies include:

    • Uniform sampling: frames are sampled at equal intervals over the duration. This is simple and temporally balanced, and it works well for content with stable action rhythm.
    • Scene-cut sampling: scene boundaries are detected from frame differences, and a representative frame is selected for each shot. This works well for content with frequent editing.
    • Fixed-FPS normalization: all videos are normalized to a target frame rate, which makes cross-video comparison easier but can be costly for high-frame-rate material.

    In practice, the real constraint is a triangle: duration, frame count, and per-frame resolution together determine the number of visual tokens. All three should be exposed as tunable upper limits. When limits are exceeded, the system should degrade in the order of “first lower resolution, then reduce frame count,” rather than failing immediately.

    1. # Illustrative code: frame sampling and temporal metadata construction
    2. def sample_frames(frames, policy="uniform", max_frames=32, fps_hint=1.0):
    3. total = len(frames)
    4. if policy == "uniform" and total > max_frames:
    5. idx = [round(i * (total - 1) / (max_frames - 1)) for i in range(max_frames)]
    6. elif policy == "scene" and total > max_frames:
    7. idx = pick_keyframes_by_diff(frames, budget=max_frames)
    8. else:
    9. idx = list(range(0, total, max(1, int(1 / fps_hint))))
    10. return [(i, frames[i]) for i in sorted(set(idx))] # Preserve order to avoid temporal disorder

    3.2 Temporal Chunking and Order Preservation

    The sampled frames must be organized in time order, and the language model must know what moment each frame corresponds to after encoding. Three common approaches are:

    1. Segmented encoding plus global sequence concatenation: the frame sequence is split into short segments for separate encoding, then concatenated into one visual sequence in time order. This controls peak GPU memory usage during a single encoding pass.
    2. Timestamp injection: textual time markers are inserted before or after visual tokens so the model can explicitly perceive intervals and absolute positions.
    3. Temporal positional encoding: frame-index-related temporal position signals are added at the feature level.

    Whichever method is used, the order invariant must hold: the order of the concatenated visual sequence must strictly match the sampling time order. If the order is wrong, the model’s judgment of causal relationships breaks down, and this type of error is often hard to detect in offline evaluation.

    3.3 Unified Preprocessing: Sharing the Same Transformations as Images

    Once video frames enter preprocessing, they should go through exactly the same resize, padding, normalization, and patch splitting as images. For inputs with large resolution differences, dynamic resolution and multi-tiling can be used to split a high-resolution frame into sub-blocks that are encoded separately. This balances detail preservation and controlled computation.

    The importance of consistency is practical: parameters and weights tuned for the image path can be transferred directly to video frames without secondary calibration.

    3.4 Visual Encoding and Feature Projection: No Additional Model Parameters

    Sampled frames are batched into the visual encoder after preprocessing. The output features are projected through a projection layer into the hidden dimension of the language model, replacing the image placeholders in the prompt template. Because video frames share the same path as images, the model side can perform multi-frame joint reasoning once the request side has completed frame-sequence organization and placeholder expansion.

    If the business requires stronger fine-grained temporal understanding, such as long-duration action recognition, a lightweight temporal adapter can be introduced for feature enhancement. This is an optional enhancement and should not be a prerequisite for getting the pipeline running.

    4. Plugin-Based Packaging: Pluggable and Rollback-Ready

    Packaging the pipeline as an independent adapter plugin is one of the highest-value engineering decisions in this design. A recommended layered structure is:

    1. Request parsing layer → modality recognition (text / image / video)
    2. Media loading layer → local file / object storage reference / byte stream
    3. Sampling and chunking layer → decoding, frame sampling, temporal chunking, timestamp generation
    4. Feature building layer → unified preprocessing + visual encoding + projection
    5. Inference scheduling layer → prompt template expansion, batching, KV cache

    Plugin-based packaging brings three direct benefits:

    • Backward compatibility: requests without video parameters continue on the original path, with unchanged behavior and performance.
    • Independent upgrades: decoder versions and sampling policies can be iterated inside the plugin without affecting the inference core.
    • Rollback capability: if an issue occurs, video capability can be disabled independently while the rest of the service remains unaffected.

    5. Request Protocol and Error Handling

    The core of the protocol design is to separate the media reference from the sampling policy: the former describes where the content is, while the latter describes how it should be viewed.

    1. {
    2. "messages": [
    3. {
    4. "role": "user",
    5. "content": [
    6. {
    7. "type": "video",
    8. "video_ref": "object-storage://bucket/path/demo.mp4",
    9. "video_policy": {
    10. "mode": "uniform",
    11. "max_frames": 32,
    12. "max_pixels": 448
    13. }
    14. },
    15. {
    16. "type": "text",
    17. "text": "Describe the order of operations in the video"
    18. }
    19. ]
    20. }
    21. ]
    22. }

    Error handling should use structured categories rather than generic failure responses. Examples include unsupported formats or codecs, empty sampling results, visual tokens exceeding the context budget, decoding timeouts, and unreachable media addresses. Each category should map to a different client-side handling strategy, such as switching the source, reducing parameters, or shortening the duration. Clear classification is necessary for clients to implement automatic degradation and retry.

    6. Service-Side Engineering Constraints

    Video input shifts the pressure from “do we have enough GPU memory?” to “are throughput and latency stable?” The main constraints are:

    • Token budget: the number of visual tokens in a single request equals the number of sampled frames multiplied by the number of tokens per frame. This must be constrained together with text length within the context window, and excess requests should be rejected early rather than failing during inference.
    • Prefill overhead: long sequences caused by multiple frames significantly increase prefill cost. This can be mitigated through batched visual encoding, request-level concurrency limits, and caching visual features when necessary.
    • CPU and I/O bottlenecks: decoding and resizing are CPU-intensive operations and can become bottlenecks before the GPU. It is advisable to enable hardware decoding, limit the number of frames per request, and isolate preprocessing in a separate process pool so that it does not block the scheduling thread.
    • Long-video isolation: extremely long requests should be routed to a separate queue or a separate instance pool, with stricter timeout and frame-count limits, to prevent a single request from exhausting shared resources.
    • Degradation strategy: “resolution degradation → frame-count degradation → duration truncation” should be implemented as a configurable chain, and the parameters that actually take effect should be communicated to the client.

    7. Deployment and Operations

    Several deployment-side issues are easily underestimated.

    First is decoding dependencies. The container image must include complete media decoding libraries and the required codec support, and their licenses must be suitable for distribution. Image layers should be cached appropriately so that decoding dependencies do not have to be reinstalled on every update.

    Second is the large-file path. Video is much larger than text. Object storage with reference-based input is recommended, together with internal-network direct access and pre-signed URLs, to avoid embedding large files in the request body.

    Third is observability. At minimum, collect decoding time, actual frame-count distribution, average per-frame resolution, visual-token count distribution, time to first token, overall failure rate, and failure-reason distribution. These metrics are the only basis for later tuning.

    In cloud environments, generic container services can host inference instances, object storage can hold media assets, and monitoring, alerting, and logging services can cover the above metrics. This forms a “configuration-as-deployment” recipe, where the complexity of model integration, temporal processing, and framework adaptation is encapsulated inside components. Users only need to complete parameter configuration to enable the capability.

    8. Launch Validation Checklist

    1. Regression validation: requests without video parameters, including text-only and image-only requests, should produce exactly the same results as before the change.
    2. Order validation: use materials with clear before/after sequences to verify the model’s judgment of causality and temporal order, focusing on frame-order disorder and timestamp misalignment.
    3. Boundary validation: test extremely short videos (single frame), extremely long videos, extremely high-resolution inputs, and abnormal encoded files, and confirm whether each case follows the degradation path or produces a clear error.
    4. Stress validation: under mixed load, observe preprocessing queue backlog and long-tail latency for the first token, and confirm that the degradation path is triggered as expected.
    5. Consistency validation: switch sampling policies for the same material and confirm that results stay within a reasonable range rather than jumping drastically.

    Conclusion

    Adding native video input to an inference service is not mainly a model-structure problem. The difficulty lies in the completeness of the pipeline engineering and the rigor of constraint design. The sampling policy determines the upper limit of information, temporal organization determines comprehension accuracy, token budgets and degradation strategies determine whether the service remains stable, and plugin-based packaging determines whether the capability can be maintained and iterated over the long term. By encapsulating video ingress, temporal processing, and framework adaptation into reusable components and deployment recipes, a self-hosted service can truly align with the video understanding capability of official APIs and continue to evolve in local business scenarios.