Adding Video Input to Multimodal Inference Services: A Complete Implementation Guide
This article walks through the complete path for adding video input to a multimodal inference service without changing model weights. It breaks the work into five coordinated stages—access, sampling, chunking, inference, and deployment—and explains how to turn a video into "frames plus a timeline" that fit an existing text-and-image stack. You'll find practical guidance on input forms and security limits, unified-grid geometry (round-then-pad) that keeps per-frame token counts stable, sampling strategies that balance information against a token budget, three temporal-chunking techniques, VRAM and KV-cache estimation formulas, hardware sizing, batching and TTFT mitigation, configuration recipes, and an evaluation and observability checklist with common failure modes and fixes.
1. The Capability Gap: From “Text + Image Ready” to “Video Ready”
Frontier models’ official APIs already support video input: the client submits a video and a question, and the server handles decoding, sampling, and frame organization before returning an answer. Teams that build their own inference and want to match this experience often stall at “image capability.”
The problem isn’t whether the weights support video—it’s the data pipeline of the inference service. Most common open-source multimodal inference stacks already support “text + image”: after decoding, frames still have to be organized according to a unified convention before the server can build a request, plan VRAM, and correctly invoke the vision encoder. The existing interface contracts, preprocessing modules, and scheduling logic were all designed around a single image. When a video request arrives, it either gets treated as one image or falls straight into an “unsupported input type” branch.
So video input is not as simple as “passing one more image.” Completing it means answering four questions at once:
- Access: In what form is the video submitted, who decodes it, and how do you keep huge files from overwhelming the service.
- Sampling: A video that runs several minutes can contain tens of thousands of frames—which ones to keep, and which timestamp each corresponds to.
- Organization: How the multiple frames sent to the vision encoder are grouped, aligned, and arranged, and how temporal information enters the language model.
- Inference: How the large number of visual tokens from the video share the context window with long text, and how to control VRAM and latency.
The sections below unfold layer by layer in the order: architecture → access → sampling → chunking → inference → deployment → evaluation.
2. Overall Architecture: Add Only a Video Access Plugin, Don’t Change Model Weights
2.1 Reusing the “Text + Image Toolkit”
The path from text, image, and video input to the language model (LLM):
- Text: Tokenized and embedded into token vectors.
- Image: Decoded into pixels, then resized, padded, normalized, and patch-split; the vision encoder extracts features, and a projection layer maps them to the LLM’s hidden dimension.
- Video: Has an extra time axis, but each frame is essentially still an image.
Images and videos share the same vision encoder weights. After visual encoding, features are aligned to the language space through the projection layer and then arranged with the text vectors into a unified sequence according to the prompt template.
Notation: video frame count is N; single-frame visual token count is k; every k tokens form a visual block B, with the timestamp written into the text separator in front of the block; frame order is f₁, f₂, …, f_N. The unified input sequence can be written as:
[System prompt] [Conversation history] [User text] [B(f₁)] [B(f₂)] … [B(f_N)] [Text separator] [Generation position…]
Video does not change the sequence structure—it only increases the visual blocks from 1 to N. This is the fundamental reason “video can be supported without changing weights,” and also the reason VRAM pressure grows linearly with frame count.
2.2 Modality Processing Comparison
| Processing stage | Image pipeline (existing) | Video pipeline (added here) | Nature of change |
|---|---|---|---|
| Request access | Image URL / Base64 | Add video URL, upload, duration and format validation | Interface extension |
| Decoding | Image decoding | Video decoding, keyframe locating, hardware decode acceleration | New |
| Sampling | Not needed | Uniform sampling + frame-difference dedup | New |
| Size alignment | Long-side resize, padding | Same, plus verify side length is divisible by the patch size | Reuse |
| Temporal chunking | None | Dual-frame interleaving, sliding window, block-boundary timestamps | New |
| Visual encoding | Vision encoder | Same encoder, batched forward pass | Reuse |
| Feature projection | Projection layer aligns hidden dimension | Same projection layer, emits a visual block per frame | Reuse |
| Sequence construction | Text-image interleaving template | Text + N visual blocks + time markers | Interface extension |
| Inference scheduling | Single-image request scheduling | Multimodal mixed batching, visual token budget, disaggregated deployment | Refactor |
3. Access Layer: Turn Video into “Frames + Timeline”
3.1 Three Input Forms
- Object storage URL: The client sends only a reference; the server pulls on demand. Suited to large files and offline tasks.
- Inline Base64: Works in environments without outbound network access, but bloats the request body by roughly one third and consumes gateway memory.
- Chunked upload + task ID: Suited to very long videos; requires an async interface with a task-status query to accompany it.
Whatever the form, the server should enforce limits on duration, file size, maximum resolution, and encoding format. If only a few encodings are accepted, converge them through transcoding at the access layer rather than handing arbitrary formats straight to the vision encoder. For inline Base64 in particular, add four defenses: set a request body size limit (e.g., 8 MB per request; reject anything larger and require switching to an object storage URL); set a download/decode timeout so slow uploads don’t tie up gateway connections; verify that the MIME type and magic number match the actual content to catch disguised file extensions; and run a virus/malware scan on uploaded files before enqueuing them. These should be hard constraints of the access layer, not problems left to surface at the inference stage.
3.2 Decoding: Software, Hardware, and In-Batch Consistency
Video decoding is CPU-intensive and can become the bottleneck before the GPU under high concurrency. If the runtime supports hardware decoding, offload decoding to dedicated hardware to free up CPU for pre- and post-processing. The decode thread-pool size, maximum resolution per request, and maximum duration are three parameters that must be tuned together to keep the decode queue from growing without bound.
3.3 The Hidden Pitfall of Geometric Transforms: round-then-pad
Most mainstream vision encoders use a patch of 14 pixels. Dynamic-resolution schemes typically use a strategy like smart_resize to round width and height to integer multiples of the patch before padding, in these steps: first round each side to a multiple of 28 (two patches); then clamp within [min_pixels, max_pixels]; finally pad out to the target grid size.
This is fine for a single image. The key difference for video is that every frame in the same video must produce exactly the same output size. If you run the above process per frame independently, floating-point rounding can make adjacent frames differ by a patch width, causing the visual token count to fluctuate across frames, breaking block alignment, and in extreme cases even triggering out-of-bounds access. The correct approach is to first compute a single target grid and pixel size based on the resolution ceiling, then apply the same geometric transform to all frames:
# Illustration: fix the grid and target pixel size first, then transform all framesdef target_grid(width, height, patch=14, merge=2, max_pixels=602112, max_iter=16):cell = patch * merge # Minimum alignment granularity per side (pixels)w = max(cell, round(width / cell) * cell)h = max(cell, round(height / cell) * cell)it = 0while w * h > max_pixels and it < max_iter: # If over limit, scale down proportionally and realign; cap iterations as a safeguardscale = (max_pixels / (w * h)) ** 0.5w = max(cell, round(width * scale / cell) * cell)h = max(cell, round(height * scale / cell) * cell)it += 1rows = h // patch # Grid rows = pixel side length ÷ patchcols = w // patch # Grid columns = pixel side length ÷ patchtarget_w, target_h = cols * patch, rows * patch # Target pixel size derived from the gridreturn rows, cols, target_w, target_h# Apply the same target pixel size to all sampled frames to guarantee consistent outputrows, cols, target_w, target_h = target_grid(frame.width, frame.height)frames = [letterbox_resize(f, target_w, target_h) for f in sampled_frames]
The key point: grid rows/columns = pixel side length ÷ patch, but letterbox_resize needs pixel sizes, so you have to multiply the grid back by the patch (cols×patch, rows×patch) to recover the target pixel size. Adding a max_iter iteration cap to the while loop prevents an infinite loop from repeated rounding failures at extreme resolutions; combined with the integer-divisibility floor from max(cell, …), this guarantees that every side stays an integer multiple of the patch.
4. Sampling Strategy: Trading Off “Information” vs. “Token Budget”
4.1 Fix the Frame Rate First, Then the Count
Two hard rules are recommended to constrain video input:
- Frame rate cap: e.g., at most 2 frames per second, and never exceeding the source video’s frame rate.
- Frame count cap: e.g., at most 96 frames per video; effective fps = min(target fps, frame count cap ÷ video duration).
On top of this, layer optional strategies: uniform sampling (equal-interval frame extraction, the most complete temporal coverage, the default choice); scene-cut awareness (detect abrupt visual changes and sample more densely around cut points, suited to heavily edited videos); and frame-difference dedup (when a long segment is nearly static, use perceptual hashing or low-resolution frame differencing to drop near-duplicate frames, reallocating the budget to segments with rapid change).
4.2 Comparison of Two Typical Strategies
| Dimension | Uniform sampling | Scene-cut + uniform fallback |
|---|---|---|
| Implementation complexity | Low | Medium; needs frame-difference or histogram comparison |
| Recall of short events | Misses events that are too short and fall off the sample points | Extra frames near cut points, higher recall |
| Frame consumption for static shots | Fixed, with redundancy | Can shrink dynamically |
| Suitable scenarios | Continuous footage like tutorials and demos | Content with many abrupt changes, like edited video or surveillance playback |
In practice, set two thresholds: a scene-cut threshold (e.g., adjacent frames with a histogram difference > 0.3 count as a cut) and a frame-difference dedup trigger (e.g., merge when the perceptual-hash Hamming distance across 5 consecutive frames is < 4). Also monitor the dedup rate: a persistently high rate (e.g., > 60%) means a lot of footage is being discarded and short, critical events may be missed; treat it as an alert metric and fall back to pure uniform sampling when it trips. Whatever the strategy, record each frame’s timestamp in the source video—this feeds the temporal chunking in Section 5.
4.3 Why the Frame Count Limit Matters
Let single-frame token count be k, the tokens used by conversation history and the question be L_text, the reserved output length be L_out, and the model’s context length be L_ctx. A single video request must satisfy:
N × k + L_text + L_out ≤ L_ctx
From this you can derive two useful figures:
- Visual tokens per second ≈ fps × k: roughly how many visual tokens a second of video consumes at a given sampling frame rate.
- Increment per +1 fps ≈ k: the extra visual tokens you pay each time you raise the frame rate by 1 (i.e., the per-frame cost).
For example, with L_ctx = 128K, k = 256, fps = 2: visual tokens per second ≈ 2 × 256 = 512 tokens/s; increment per +1 fps ≈ 256 tokens. Three implications follow:
- Video requests inherently crowd the context; long videos or multi-turn video conversations need more headroom.
- Lowering resolution and lowering frame rate are not equally cost-effective: single-frame token count drops roughly with the square of resolution, while frame rate affects the total linearly. For tasks insensitive to image quality, reduce resolution first.
- The frame count cap should be derived from context length and latency targets together, not hard-coded from experience.
5. Temporal Chunking: Let Visual Encoding “See” the Order
5.1 Why Per-Frame Independent Encoding Is Not Enough
The model’s positional encoding mainly captures 2D spatial position; the order between frames must be injected explicitly. If every frame is encoded independently, the model only sees an unordered string of image features and struggles to answer “which action happened first.” Temporal information therefore has to be embedded in a structured way before it enters the language model.
5.2 Three Directly Deployable Approaches
Approach 1: In-block dual-frame interleaving. Take two adjacent frames, scale them to a unified grid, merge into visual tokens via 2×2 patches, then interleave the two frames’ tokens along the sequence dimension. After positional encoding, the interleaved tokens are spatially offset from one another, which implicitly encodes the “first frame, second frame” order. It depends on no specific model implementation and changes no positional-encoding scheme. With a 16×16 grid and 64 tokens per frame after merging:
Frame 1: t0 t1 t2 t3 …Frame 2: s0 s1 s2 s3 …Interleaved: t0 s0 t1 s1 t2 s2 t3 s3 …
Approach 2: Sliding-window chunking. Cut into blocks by size (e.g., 8 frames), overlapping adjacent blocks by 1–2 frames. Block-level visual summaries preserve temporal order while easing the encoding load within a single block; the cost is redundancy from overlapping frames, so the token budget must be raised according to the overlap rate.
Approach 3: Textualized timestamps. Insert a text marker before each frame’s or block’s visual tokens, e.g., [Frame 12 | 00:06.0], letting the language model reason about time at the pure-text level. Timestamps consume text tokens and are cheap, but on their own they lack a visual-level ordering constraint. Real solutions usually build on Approach 1 or 2 and then add timestamps.
5.3 Don’t Cut Key Actions at Block Boundaries
For a continuous action spanning several frames, like “reaching out to grab an object,” it’s best to let one block cover the whole process rather than splitting the action across blocks. You can align block boundaries using the scene-cut points recorded during sampling. This way a single visual block carries one semantically complete event, which also makes long-video summarization easier to organize block by block.
5.4 Example of Video Request Parameter Expansion
# Illustration: expand one video request into a frame sequence and text segmentsdef expand_video_request(video, sampling, model):frames = decode_and_sample(video, sampling) # 1. Decode and sample, keep timestampsframes = letterbox_all(frames, model.max_pixels) # 2. Unify grid across all frames to keep output size consistentpairs = [frames[i:i + 2] for i in range(0, len(frames), 2)] # 3. Group two frames; duplicate the last frame to pad an odd countvisual_blocks = [interleave_pair(p) for p in pairs] # In-block dual-frame interleavingspans = [ts_to_marker(p[0][1], p[-1][1]) for p in pairs] # 4. Insert a text timestamp before each blockreturn visual_blocks, spans
6. Multi-frame Inference Adaptation: VRAM, Batching, and First Token Latency
6.1 Estimating the Visual Token Count
Let the patch size be p, the spatial merge factor be m, and the single-frame patch grid be h × w. Then:
- Single-frame token count k = h × w ÷ m²;
- With g interleaved frames per block, tokens per block = g × k.
A note in particular: g = 2 only changes how frames are arranged (interleaving two adjacent frames into the same block); it does not add frames. So the total visual tokens for 96 frames is still computed as “frame count × single-frame tokens,” i.e., 96 × k, and does not double because of interleaving. The table below gives illustrative estimates under this convention:
| Single-frame input grid (patch level) | Merge factor m | Single-frame tokens | Total visual tokens for 96 frames (=96×k) |
|---|---|---|---|
| 26 × 46 | 2 | 299 | ≈ 28.7K |
| 51 × 91 | 2 | 1161 | ≈ 111.5K |
| 78 × 139 | 2 | 2711 | ≈ 260.3K |
The contrast is clear: raising the long side from about 650 pixels to about 1800 pixels (2.8×) grows single-frame tokens roughly 9×, and total visual tokens jump from under 128K past 260K. Even if the context window reaches the millions, resolution and frame count must still be “double-limited.”
6.2 KV Cache VRAM Estimation
Most mainstream inference frameworks use paged cache management like PagedAttention. The KV Cache VRAM for a single request can be approximated as:
KV_bytes ≈ 2 × L_layers × L_ctx × H_kv × d_head × bytes_per_element
where L_layers is the layer count, L_ctx is the context length, H_kv is the KV head count, d_head is the per-attention-head dimension, and the coefficient 2 accounts for Key and Value each taking a copy. With 61 layers, 8 KV heads, head dimension 128, and FP16 storage, each 1K tokens of context needs about 0.24 GB of VRAM, and 100K of context needs about 24 GB.
Worth noting: the visual features themselves are tiny—a single float16 feature is usually only a few hundred bytes, and 10,000 visual tokens amount to only a few MB. What actually consumes VRAM is the expansion of visual tokens in the KV Cache. So the focus of video optimization is not “features too large” but “too many visual tokens.” This overhead is especially pronounced in requests that mix long text and video.
6.3 Compute Intensity and Hardware Selection
To judge the hardware bottleneck, use a verifiable memory-access formula rather than a vague “compute intensity” conclusion.
Assumptions: model parameter count is P; bytes per parameter is b (2 for FP16); single-card memory bandwidth is BW; in the Decode phase, generating one token requires reading all weights once.
Under these assumptions:
- Memory access per token ≈ P × b bytes (read all weights once);
- Single-card Decode throughput ceiling ≈ BW ÷ (P × b) tokens/s (memory-bandwidth-bound);
- With multi-card tensor parallelism, aggregate bandwidth ≈ N × BW, the model is split across N cards, so aggregate throughput ≈ N × BW ÷ (P × b).
Example (memory-bandwidth-bound, ignoring communication and scheduling overhead): with single-card bandwidth 2 TB/s, P = 70 billion, b = 2, memory access per token ≈ 1.4×10¹¹ bytes, so single-card throughput ceiling ≈ 2×10¹² ÷ 1.4×10¹¹ ≈ 14 tokens/s; with 8-card tensor parallelism, the aggregate ceiling ≈ 8 × 14 ≈ 112 tokens/s. As for “how many cards are needed,” estimate by memory capacity first: card count ≈ (P × b + KV memory + activations) ÷ per-card memory, then verify against the throughput target. This way “card count” comes from two measurable measures—capacity and bandwidth—rather than a made-up constant.
Practical implication: video requests introduce more visual tokens, which raises both KV Cache and memory access together, so the lower the memory bandwidth, the more strictly you must control resolution and frame count; with abundant bandwidth, you can relax them moderately.
6.4 Continuous Batching and First Token Latency
Before a video request’s first token (TTFT), decoding, sampling, visual encoding, and long-sequence Prefill all have to complete. In continuous-batching scheduling, a single video request occupies a large VRAM block and can squeeze out text requests in the same batch. Common mitigations:
- Decouple decoding from inference: run video decoding in a separate CPU worker process or service so the GPU doesn’t wait on I/O.
- Block-level budget control: set a maximum number of visual blocks per request; when exceeded, produce a block-level summary before entering the main inference.
- Dedicated instance groups for multimodal requests: deploy them separately from text-only instances to avoid head-of-line blocking from long videos.
- Vision-encoder quantization: under an acceptable accuracy trade-off, run the vision encoder at lower precision (INT8/FP8, etc.) to reduce first-frame encoding time.
7. Deployment and Configuration: One-Click Recipes
7.1 Configuration Example
Video capability is best wired in through a config switch rather than hard-coded into code branches. This lets the text, image, and video pipelines share one service image:
video_input:enabled: truedecode:backend: hardware # software / hardware, chosen per runtimemax_duration_sec: 600 # reject or truncate when exceededmax_file_size_mb: 500max_base64_mb: 8 # inline Base64 limitrequest_timeout_sec: 120 # download/decode timeoutsampling:target_fps: 2.0 # target sampling frame ratemax_frames: 96 # max frames per videodedup: perceptual_hash # optional: none / perceptual_hashscene_threshold: 0.3 # scene-cut thresholdtiling:window_size: 8overlap: 1interleave: truebudget:max_visual_blocks: 48min_frames_keep: 8
Parameters must be validated against one another. In particular, the effective sampling frame rate should satisfy:
actual_fps = min(target_fps, max_frames ÷ duration_sec)
That is, when a video is long and the frame count hits its cap, the effective frame rate is automatically pushed down. Other constraints: max_visual_blocks must be no smaller than the block count corresponding to min_frames_keep; max_pixels, together with the model’s patch size, determines single-frame token count. It’s advisable to run a self-check at service startup and refuse to start on parameter conflicts, rather than discovering problems only after live requests arrive.
7.2 Request Example
The following payload is illustrative; field names may differ across implementations:
POST <inference-service-url>/v1/chat{"model": "<model-id>","messages": [{"role": "user","content": [{ "type": "video","video_url": "<object storage URL or Base64 data>","sampling": { "fps": 2, "max_frames": 96 } },{ "type": "text","text": "List, in chronological order, the three key actions that appear in the video, and mark their approximate timestamps." }]}],"max_tokens": 512}
Besides the answer text, the response can also return usage statistics: number of frames sampled, number of visual tokens, prompt and output token counts, and video processing time. These figures help callers estimate cost and help the server run budget analysis.
7.3 Cloud Deployment Considerations
In a cloud environment, this capability is typically carried by a combination of general-purpose cloud products:
- Object storage: holds video assets and supports chunked upload and lifecycle management;
- Container platform: hosts the inference service and scales elastically by GPU instance type;
- Message queue: absorbs asynchronous video-processing tasks and smooths out peaks and troughs;
- Logging and monitoring/alerting: collects metrics such as TTFT, decode time, and visual-token distribution.
For example, on a cloud platform such as Baidu AI Cloud, you can combine object storage (BOS), the container engine (CCE), a messaging service (such as Kafka), the log service (BLS), and cloud monitoring (BCM) to build a complete “upload → async parsing → inference → observability” pipeline. Recommended engineering practices: package the video input capability as an independent deployment recipe or Helm chart, version the image, parameters, resource specs, and probe configuration together; adopt canary release—start with 1% of video requests, watch TTFT, VRAM usage, and error rate, then scale up; and prepare one-click rollback so that setting video_input.enabled to false reverts to the text-and-image pipeline without rebuilding the image.
8. Evaluation and Observability
8.1 Evaluation Dimensions
Before going live, video input should cover at least the following scenarios:
| Evaluation dimension | Example question | Metric of interest |
|---|---|---|
| Temporal order | Which of two actions happened first | Order-judgment accuracy |
| Event localization | At which second did a certain action occur | Time-localization error |
| Counting | How many times an object appears | Counting accuracy |
| Cross-frame reference | State of an object seen earlier, in the final frame | Coreference-resolution accuracy |
| Long-video summarization | Summarizing a ten-minute video | Key-point coverage, factual consistency |
| Robustness | Fast cuts, jitter, low light, subtitle occlusion | Accuracy drop under each condition |
| Temporal disruption | Answer after frames are shuffled out of order | Order-judgment accuracy drop |
| Missing metadata | Removing timestamps, using a wrong sampling fps | Whether temporal reasoning degrades |
It’s recommended to evaluate under both a fixed frame rate and the full frame rate to judge whether the sampling strategy loses key information. Keep the evaluation set versioned and reproducibly executable, and fold it into the regression process.
8.2 Observability Metrics
Decode time and decode-queue length; effective sampling frame rate and dedup rate; per-request visual token count and its percentiles (P50/P95/P99); TTFT/end-to-end latency/output throughput; the share of requests truncated or down-sampled because of budget overruns; and the share of video requests among all requests plus their VRAM usage. The “truncation rate” deserves particular attention: a persistently high value usually means the sampling parameters or context planning don’t match the real business distribution.
9. Summary and Implementation Checklist
The essence of video input capability is adding the “time” dimension to an existing text-and-image inference pipeline without changing model weights. It requires five stages—access, sampling, chunking, inference, and deployment—to work together; an imbalance in any stage’s parameters surfaces as truncation, latency, or off-topic answers.
Common failure modes and their handling:
| Symptom | Common root cause | Recommended fix |
|---|---|---|
| Visual token count fluctuates across frames | Per-frame independent round-then-pad | Unified grid and pixel size across all frames |
| Decode queue builds up, TTFT rises | Decoding not separated from inference | Independent decode process/service + hardware decoding |
| Truncation rate rises | Frame count/resolution exceeds the context budget | Dual limits + actual_fps check + block-level summary |
| Wrong answers on temporal questions | Missing timestamps, or block boundaries cutting actions | In-block interleaving + timestamps + cut-point alignment |
Implementation checklist: ① Unified grid—use the same output size for all frames in a video to avoid round-then-pad token-count fluctuation; ② Dual limits—set both a frame rate and a frame count cap, which together determine the effective sampling rate; ③ Keep timestamps—record each frame’s original time and inject it into the language model as text markers after chunking; ④ Formula-driven budgeting—derive parameters from N × k + L_text + L_out ≤ L_ctx, and count visual tokens per second as fps × k; ⑤ Size capacity first—estimate card count by VRAM capacity and throughput by bandwidth; ⑥ Async and decoupling—separate decoding from inference and deploy multimodal instances independently; ⑦ Plugin-style configuration—ship the capability through a config switch that supports canary rollout and one-click rollback; ⑧ Build an evaluation set—cover temporal order, counting, cross-frame reference, temporal disruption, and other dimensions, and fold it into regression testing.
