How to Add Video Input to a Self-Hosted Multimodal LLM
Video is often the last missing modality when you self-host a multimodal LLM. This article walks through adding video input to an existing text-and-image inference service without retraining: how to decode and sample frames, organize them into a temporal sequence, and feed them through the existing vision pipeline. It covers reusing the current image path, frame sampling and temporal chunking, adapting multi-frame input to a model's processor, the three main ways models represent time, and the cost centers of context budget and visual tokens. It also addresses building a pluggable modality adapter, defining a multimodal request payload, turning the setup into a repeatable deployment recipe, and a pre-launch verification checklist with common troubleshooting tips.
1. The Starting Point: Video Is the Last Missing Piece
If you have already deployed a multimodal large model as a usable inference service, you have likely gotten two input paths working: text and images. A request comes in, the image is decoded, resized, and normalized, passed through the vision encoder and a feature projection module to map it into the language model’s hidden dimension, concatenated with the text vectors, fed into the LLM, and streamed back as an answer. The pipeline is complete, load-tested, and monitored.
Then the business side makes a natural request: can we pass in a video directly? And the problem appears. The model’s official API has long supported video input, but in your self-hosted deployment, video is recognized by neither the request layer nor the multimodal processor. The result is that the same model can answer “what appears at second X in the video” on the official endpoint, but on your own service it either errors out or silently ignores the video. This is the so-called “last missing piece.”
This piece is not about training a new model. It is about filling in a missing processing pipeline: how a video is read in, how it is organized into a frame sequence the model can understand, and how it is fed into the existing vision path without blowing up the context and memory budget. This article unpacks that pipeline layer by layer and offers practical engineering guidance.
2. The Big Picture: How Text, Images, and Video Feed Into One Model
Let’s first make clear the final form of all three inputs, because every design decision that follows builds on this “funnel.”
- Text: After tokenization you get token IDs, which the embedding layer turns into a vector sequence the language model can consume directly. This step is the foundation of every multimodal model: any additional modality must ultimately become “a few segments of vectors mixed into the text vectors.”
- Image: Read the container/URL/byte stream → decode into a pixel array → image preprocessing (resize, pad, normalize, patch splitting) → vision encoder (usually a ViT-style structure) produces visual features → a Projector (feature projection module) maps the visual features into the language model’s hidden dimension.
- Video: After decoding, you first get a series of image frames, then sample frames according to configuration and split them into chunks by time order. From there it goes through the exact same preprocessing and vision encoding path as images. In other words, video is architecturally not a “third modality” but “a group of images given temporal relationships.”
The key point: text vectors and visual vectors are ultimately interleaved into a single unified input sequence according to the position of placeholders in the prompt (markers like <image>/<video>). The Projector’s job is “dimension alignment + semantic space alignment,” so that visual tokens and text tokens sit in the same vector space and are processed together by self-attention.
This leads to a very important engineering conclusion: video input capability is essentially about “how frames are organized,” not about “a new neural network.” This sentence determines all the trade-offs that follow.
3. Reuse First: What You Can Keep and What You Must Add
Once you understand the funnel, the list of changes becomes clear. Your existing image pipeline already has: image preprocessing, vision encoder weights, the feature projection module, the LLM backbone, KV cache management, and sampling and streaming output. All of these can be reused as-is — no retraining, no new memory-resident modules.
Only three things genuinely need to be added.
3.1 Video Container Parsing and Decoding
Video requests usually arrive as a local path, an HTTP(S) URL, or an object storage address (storing the video in object storage and referencing it via a signed link is the more robust approach, avoiding stuffing a large file directly into the request body). The decode layer must face the long tail of codec and container formats: MP4/WebM/MKV containers, H.264/H.265/AV1 codecs, variable frame rates, rotation metadata, multiple audio tracks, and B-frames that cause display order to differ from decode order.
Engineering recommendations:
- Prefer system-level or hardware-accelerated decoding (e.g., using system commands to demux the first frame or sample frames), which significantly reduces cost — but its codec support matrix changes over time, so you must have a pure-software decode fallback.
- Standardize output to RGB three-channel, and ensure frame time order matches display order (variable-frame-rate videos must compute sampling positions by timestamp, not frame index).
- Put hard limits on input: maximum duration, maximum resolution, maximum file size, and an allowed-codec whitelist. These limits aren’t just for performance; they also prevent a maliciously crafted 8K long video from taking down your service.
Skeleton code (decoding and frame sampling):
import subprocess, numpy as np, cv2def sample_frames(video_path, target_fps=1.0, max_frames=64):"""Sample frames uniformly at the target frame rate; return [(timestamp_sec, frame_bgr), ...]"""# First probe duration and total frame count to avoid a full decodeprobe = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0","-show_entries", "stream=nb_frames,avg_frame_rate,duration","-of", "json", video_path],capture_output=True, text=True, check=True)# ... parse duration / fps and compute the actual sampling stepcap = cv2.VideoCapture(video_path)fps = cap.get(cv2.CAP_PROP_FPS) or target_fpsstep = max(1, int(round(fps / target_fps)))frames, idx = [], 0while len(frames) < max_frames:ok, frame = cap.read()if not ok:breakif idx % step == 0:frames.append((idx / fps, frame))idx += 1cap.release()return frames
3.2 Frame Sampling and Temporal Chunking
Frame sampling answers “how many frames and which frames to take,” while temporal chunking answers “at what granularity are these frames encoded together.”
- Sampling strategy: The simplest and most reliable approach is uniform sampling at a fixed target frame rate, or “fixed total frame count with uniform slicing.” A more refined approach combines scene detection to keep key frames, then re-samples long shots. This is very effective for questions like “find the second at which a cut happens.” Also set a
max_framescap; when exceeded, prefer downsampling over truncating the tail, to avoid the temporal information being skewed entirely toward the start of the video. - Temporal chunking: Split the sampled frame sequence into several contiguous segments (e.g., 8 or 16 frames each), keeping frames within a segment in their original time order. This has three benefits: first, it turns a “long sequence” into “multiple medium sequences,” making batching and memory control easier; second, segments can be pooled/summarized at the vision encoding layer to reduce the total number of visual tokens entering the LLM; third, segment boundaries naturally correspond to the video’s timeline, making later timestamp alignment and referencing convenient.
- Timestamp preservation: Make sure each frame carries its original timestamp (a second-level float), not the frame index. When the model answers “around the 12-second mark,” it depends precisely on this information being explicitly expressed in the prompt.
3.3 Multi-Frame Inference Adaptation
This is the most underestimated part. After sampling, you must turn frames into an input the model’s processor accepts. Processor interfaces vary widely across models: some accept videos=[np.ndarray] (shape (T, H, W, C)), some accept a list of frame images, and some require chunking first and then calling the image processor block by block. The adapter’s job is to hide these differences, converting a unified intermediate representation (timestamped frame sequence + target resolution) into the form each model expects, then mapping the visual token expansion positions one-to-one with the placeholders in the prompt.
The easiest pitfall here is placeholder count mismatch: if the number of visual tokens the processor expands doesn’t match the number of <video> tags you wrote by hand, the sequence becomes misaligned, and the model output looks normal while completely ignoring the video content. The safe approach is to infer the number of placeholders from the actual token count the processor returns, rather than estimating it manually.
4. How the Model “Sees” Time: Three Mainstream Representations
Once you have an ordered frame sequence, the model needs to know the order and intervals between frames. The industry has roughly three approaches, each suited to different scenarios:
| Approach | How It Works | Pros | Limits |
|---|---|---|---|
| Explicit time markers | Insert text-form timestamps between frame visual tokens, e.g., [00:03.5] |
No model changes; most direct for time-point localization/reference questions | Adds text token overhead; format must match training |
| Implicit temporal encoding | Overlay time-interval embeddings or rotary position encoding on visual tokens, so frame order is implied in the vectors | High token efficiency, low inference overhead | Effectiveness depends on whether the model was trained this way; extrapolation ability uncertain |
| Inter-frame relation/summarization | Do inter-frame attention or cross-frame pooling at the vision encoder, compressing before feeding the LLM | Greatly reduces the number of tokens on the LLM side | Requires extra encoding compute; highest implementation complexity |
The practical judgment is simple: feed it the way the model was trained. If the model natively supports timestamp insertion, honestly write per-frame time markers in the prompt; if the model understands multi-frame order through position-encoding extrapolation, don’t stuff in a pile of extra text timestamps to interfere with it. Inventing a temporal representation out of thin air is the most common self-inflicted wound in self-hosted deployments — it looks “smarter,” but the model has never seen this input format.
5. The Overlooked Cost Center: Context Budget and Visual Tokens
Where video input really bites is that it amplifies two costs at once: context length and memory usage.
Let’s do the math (the following are illustrative estimates to show the order of magnitude, not the actual parameters of any specific model). Suppose a 30-second video is sampled at 1 fps to get 30 frames, and each frame expands into hundreds of visual tokens after patch splitting in preprocessing — the video portion alone can occupy thousands of token positions. If the user also stuffs in the entire conversation history, system prompt, and reference documents, it’s easy to hit the model’s context limit at the prefill stage.
So a video input service must make clear design decisions at the architectural level:
- Set a hard visual token budget. Based on the model’s context window, allocate quotas for “video visual tokens + text tokens + generation reserve,” and degrade by strategy when exceeded (lower fps, lower resolution, fewer frames) rather than letting the request fail outright or truncating the output.
- Joint control of resolution and frame count. The number of visual tokens is roughly proportional to “frame count × patches per frame,” and patches per frame are in turn affected by input resolution. Treating frame count as the coarse-tuning knob and resolution as the fine-tuning knob is the most practical tuning approach.
- Watch the compute cost of the prefill stage. Both vision encoding and long-sequence attention are compute-intensive, so a long-video request’s prefill time can far exceed that of a text request, showing up directly as a spike in “time to first token.” If the inference framework supports chunked prefill, you can interleave scheduling of long-video and short-text requests, avoiding head-of-line blocking.
- The vision encoder’s own memory peak. Intermediate activations when encoding high-resolution, multi-frame content simultaneously can consume more memory than the KV cache. It’s advisable to chunk the vision encoding (encode segment by segment, then concatenate) to keep the peak within a controllable range.
- Cache reusable parts. If the same video will be queried repeatedly (very common in quality inspection, teaching, and customer-service review scenarios), consider caching the video’s visual features, or at least the decode/sample results, to avoid re-running vision encoding on every request. The cache key should include the video content hash and preprocessing parameters, to prevent reading stale data after parameters change.
6. Engineering Integration: Making Video a Pluggable Component
The lowest-cost, easiest-to-maintain approach is to not scatter video logic through the main flow, but converge it into an independent modality adapter layer. A suggested module breakdown:
Request layer → Modality detection (text / image / video / mixed)↓Adapter layer → Video decode + frame sampling + temporal chunking + preprocessing param negotiation↓ (independent plugin, can be toggled and upgraded separately)Processor → Vision encoding + feature projection (reuse existing weights, no retraining)↓LLM layer → Unified sequence assembly → prefill → decode → streaming output
The benefit of this design is that any change to the video path doesn’t need to touch the text/image main path; when something breaks, you can roll back to image-only mode with one switch; and canary releases can also split traffic by modality.
The multimodal request payload is also worth designing carefully. The recommended form is an “array of content blocks,” each with an explicit type and optional metadata:
{"messages": [{"role": "user","content": [{ "type": "text", "text": "Describe what happens in this video and give the key timestamps." },{ "type": "video_url","video_url": { "url": "https://example.com/demo.mp4" },"metadata": { "target_fps": 1.0, "max_frames": 32 }}]}]}
Putting metadata at the block level rather than as global parameters has the advantage that a single request can mix multiple videos with different configurations, and the caller doesn’t need to understand the model’s internals. It’s also recommended to return the parameters actually in effect in the response (actual sampled frame count, actual fps, number of visual tokens), making it easier for the business side to troubleshoot “why the model didn’t see a certain moment clearly.”
Minimal example on the calling side:
from openai import OpenAIclient = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")resp = client.chat.completions.create(model="local-multimodal-model",messages=[{"role": "user","content": [{"type": "text", "text": "How many times does the person reach out to grab an object in this video? At which seconds?"},{"type": "video_url","video_url": {"url": "https://example.com/demo.mp4"},"metadata": {"target_fps": 2.0, "max_frames": 64}},],}],stream=True,)for chunk in resp:print(chunk.choices[0].delta.content or "", end="")
7. Deployment: From a Script to a Reusable Recipe
For local validation, manually starting the service, tweaking config, and restarting is enough. But to enter production, you need to distill the pipeline above into a repeatable deployment unit — a “deployment recipe” that pins down the image version, the model weight source (usually from object storage), decode dependencies (system-level multimedia codec components), startup parameters (context length, visual token cap, default sampling values, max concurrency), and log and monitoring metric collection config.
A few easily overlooked operational details:
- Decode dependencies are a hidden failure source. A container image missing a certain codec will run a local mp4 fine but error in production. Pinning the decode components together with the model image at fixed versions is far more reliable than installing them on the fly during deployment.
- Temporary file cleanup. Frame sampling and transcoding produce temporary files, and long videos can easily fill the disk. Be sure to set a working-directory limit and a periodic cleanup policy.
- Observability must cover the visual dimension. Beyond the usual QPS, TTFT, TPOT, and memory watermark, also collect “average sampled frames,” “average visual tokens,” “video decode failure rate,” and “average video duration.” These metrics are direct signals of whether the video path is healthy.
- Concurrency isolation. Long-video requests have far longer prefill times than text requests, and mixing them in the same batch causes noticeable queueing jitter. You can pool by input size, or rate-limit video requests separately.
8. Pre-Launch Verification Checklist
The problem most likely to appear with video input is not “erroring out” but “not erroring yet answering wrong.” It’s recommended to cover at least the following:
| Category | What to Verify | Signals to Watch |
|---|---|---|
| Functional correctness | Single image / multiple images / short video / long video / mixed image-text-video | Whether all generate normally, whether placeholders align |
| Temporal sensitivity | Questions depending on order, time-point localization questions | Whether the answer timestamps match the facts |
| Edge cases & robustness | Oversized files, unsupported codecs, no audio track, corrupted files, extremely long duration | Whether it degrades gracefully rather than returning 500 |
| Context budget | Long video + long system prompt + multi-turn history | Whether the degradation strategy triggers, whether output is truncated |
| Performance | TTFT, throughput, memory peak, queuing delay under concurrency | Whether video requests drag down text requests |
| Consistency | Output stability of the same video under different sampling parameters | Whether conclusions drift significantly with fps |
A practical tip: prepare 20–30 human-labeled video QA samples (covering four categories: object recognition, action counting, time localization, and event causality), and run a regression after every change to sampling or temporal logic. Problems in the video path are often not “crashes” but “drifts,” and only a regression set can catch them.
9. Common Issues and Troubleshooting
- The model completely ignores the video and answers from text only: Most likely a mismatch between the placeholder count and the visual token count, or visual features not correctly projected into the sequence. Print the token count after processor expansion and compare it against the number of placeholders in the prompt.
- Video requests are an order of magnitude slower than text requests: This is normal (heavy prefill compute), but if it’s slow enough to time out, first check whether chunked prefill is enabled, whether vision encoding runs in chunks, and whether memory has triggered swapping.
- OOM concentrated in the vision encoding stage: Lower the resolution or frame count, or change vision encoding to run segment by segment serially, avoiding encoding all frames at once.
- Unreliable timestamp answers: Confirm you’re passing real timestamps rather than frame indices, and check whether the timestamps after sampling match the display order after decoding (variable-frame-rate videos are especially error-prone here).
- Runs locally but errors in production: Almost always a decode-dependency or video-access issue. Confirm the codec component versions inside the container, and the network reachability and authentication of the URL reference.
10. Conclusion
Landing video input capability is essentially completing a pipeline rather than rebuilding a model. The model weights, vision encoder, feature projection, and LLM backbone are all existing assets. The real engineering investment is three pieces of “wiring”: reading video in reliably (decoding and sampling), feeding the frame sequence in an organized way (temporal chunking and timestamp alignment), and spreading the cost controllably (context budget, memory peak, and scheduling isolation).
Do these three solidly, converge them into a pluggable modality adapter and a repeatable deployment recipe, and video input stops being a “demo that occasionally works” and becomes a standard capability that can go to production, be load-tested, rolled back, and observed. Looking back at the “last missing piece” metaphor from the beginning, you’ll find it’s actually three pieces that got filled in: a decode pipeline, a temporal organization strategy, and a set of operationally acceptable engineering constraints.
