Native Video Input for Multimodal LLM Inference: A Full-Stack Implementation Guide
Most self-hosted multimodal inference services handle text and images well but stall on video, forcing clients to extract frames and send image arrays instead. This article walks through building a complete native video input pipeline that runs entirely server-side. It covers the overall architecture where a single model serves three input paths (text, images, video), the multimodal request structure, preprocessing (decoding, frame sampling, resolution control, and adaptive sampling), temporal chunking and feature fusion with the LLM, and finally plugin-based integration, deployment recipes, resource planning, and acceptance testing. The goal is to bring self-hosted inference up to parity with official cloud APIs while keeping data and cost under your own control.
1. Introduction: Why Video Input Is the Last Piece of the Inference Puzzle
Deploying multimodal large language models in a local or private environment is a common choice for enterprises pushing their AI applications forward. Keeping data within your own domain, controlling the cost per token, and being able to deeply customize the inference path make self-hosted inference the default option for many teams.
However, the capability coverage of these services is often uneven:
- The text side is the most mature: tokenization, template rendering, streaming output, and KV Cache reuse all have established solutions.
- The image side is also working: the connection between the vision encoder, the feature projection module, and the LLM is a foundational capability of these models.
- The video side often gets stuck. The model weights and conversation templates already support video understanding, but the main inference framework pipeline usually only covers text and images. There remain gaps in video reading, decoding, frame extraction, and temporal chunking.
As a result, official cloud APIs already support passing in video directly, while self-hosted services can only accept concatenated frame images. There is a clear gap between the two.
1.1 Why Workarounds Fall Short
Faced with this gap, a common stopgap is to extract frames on the client and pass an array of images to the inference service. This path works, but it has plenty of problems:
- Mismatched capability boundaries: Decoding, frame extraction, and temporal organization are the inference engine’s responsibility. The model side usually does not distinguish between “video” and “multiple images concatenated in order.” So the core of video input is not adding a new model, but filling the gap in the inference engine’s video-processing pipeline.
- Scattered, hard-to-unify strategies: Each business team implements its own frame-extraction logic, with different sampling rates, resolutions, and temporal organization. The server cannot govern this uniformly, making cross-team comparison difficult.
- Heavy client burden: Mobile and edge devices vary widely in decoding capability, and processing long videos takes noticeably longer.
- Hard-to-trace state: The server cannot obtain the mapping between frames and their original timestamps, making it hard to reproduce and troubleshoot problems when they occur online.
1.2 What Native Video Input Should Deliver
A complete native video input pipeline must satisfy at least four points:
- Direct request upload: Requests can carry video directly (a remote reference or file content) and allow specifying sampling parameters.
- Server-side processing: Decoding, frame extraction, and temporal chunking are all done on the server, independent of the client device.
- Modality reuse: Reuse the existing vision encoder and LLM without adding new model weights.
- Configurable strategies and traceable process: Sampling strategies can be configured per model and per business, and the mapping between frames and timestamps is fully preserved.
This article centers on this pipeline and breaks down a complete piece of work to “fill in video input”: first the data flow, then request access and sampling strategies, then temporal chunking and feature fusion, and finally plugin-based transformation, one-click deployment, and acceptance methods.
2. Overall Architecture: One Model, Three Input Paths
2.1 How the Three Modalities Enter the LLM
For a typical multimodal large language model, text, images, and video all converge into a token sequence at the LLM input. The difference lies in where the vector for each token segment comes from:
- Text: Tokenized into token IDs, then looked up through the embedding layer to obtain the vectors used by the language model.
- Images: First decoded into a pixel tensor, normalized, and fed into the vision encoder to extract features. A feature projection module then maps them to the LLM’s hidden dimension, replacing the image placeholder in the prompt.
- Video: Can be viewed as a “sequence of frames with timestamps.” It is first decoded into image frames, sampled according to configuration, and organized into temporal chunks. It is then encoded and projected in exactly the same way as images, and finally the features of each chunk are concatenated in time order.
Text ──► Tokenize ──► Embedding ───────────────────────────┐Image ──► Decode ──► Vision encoder ──► Feature proj ──► Vision tokens ─┤Video ──► Decode ──► Frame sampling ──► Temporal chunk ──► Vision encoder ─┤──► Feature proj ──► Temporal markers ──► Video tokens ─────────────┤▼Fuse at placeholder ──► LLM ──► Answer
2.2 Reuse Is the Premise of This Approach
The most important message in this diagram is: video has no separate model path. It reuses the vision encoder, the feature projection module, and the LLM that images have already validated. What is newly added is only the data path that turns video into a frame sequence.
From this we can derive three design principles, and the concrete implementations later in this article are all elaborations of them:
- Reuse first: If an existing module can do it, don’t write a new one.
- Training-inference consistency: Sampling methods, resolution, and temporal organization must remain compatible with the model’s training or alignment phase.
- Minimal intrusion: Keep the adaptation logic decoupled from the framework’s main pipeline as much as possible.
Finally, a note: video input adaptation is strongly tied to the specific model and inference framework version. The parameters and code below illustrate the approach; when implementing, defer to your actual versions.
3. Request Access: Making the Service “Recognize” Video
3.1 A Unified Multimodal Request Structure
The first step to completing the pipeline is to give video a clear place at the protocol layer. Building on the “message-content block” structure, simply add a video type to the content block types:
from typing import Literalfrom pydantic import BaseModelclass VideoContent(BaseModel):type: Literal["video"] = "video"url: str | None = None # Remote reference, e.g., a video URL in object storagevideo_bytes: bytes | None = None # Inline small files directly (server usually enforces a size cap)fps: float | None = None # Sampling frame rate; uses the model default when nullmax_frames: int | None = None # Frame cap, to prevent context from being filled by visual tokens
A request can mix text, image, and video blocks, and the order is exactly what the model perceives. For example, “look at image 1, then the video, then answer using both” — this interleaved semantics can be expressed without any extra protocol.
Video sources generally come in two forms:
- Remote reference: Recommended first, to avoid large files occupying request memory.
- Direct file upload: Suitable for small files, but request body size must be limited.
If the video is stored in object storage, you can generate a temporary access URL with an expiration time, avoiding long-term credentials on the service.
3.2 What the Access Layer Must Do
The protocol is only the entry point. What really determines whether the service is robust is the access layer’s validation and governance:
- Access control: Remote references should allow only whitelisted protocols and domains, to prevent the service from being used to probe the internal network; uploaded content should have its file header validated, not just its extension.
- Resource limits: Set caps on per-request duration, file size, and request body size, and return clear error codes when exceeded.
- Timeouts and circuit breaking: Decoding a large video can take anywhere from seconds to tens of seconds, so a preprocessing timeout must be set. On timeout, return an identifiable error rather than hanging.
- Asynchronous option: Long-video offline tasks can use a “submit-query” asynchronous interface to avoid holding long connections.
4. Preprocessing: Decoding, Frame Sampling, and Resolution
4.1 Lightweight Probing First
Once you have the video bytes, the first step is lightweight probing: read only the file header and index information to obtain metadata such as duration, resolution, frame rate, codec, and whether an audio track is present, without decoding a single frame. The probe result directly determines the subsequent strategy:
- Duration determines the actual sampling rate.
- Resolution determines whether to scale or chunk.
- Codec determines the choice of decoder.
A failed probe should fail early and give a clear reason such as “unsupported format” or “corrupted file,” rather than leaving the problem to the encoding stage.
4.2 Uniform Sampling and Keyframe Sampling
The sampling strategy determines how much content the model “sees”:
- Uniform sampling: Take frames at equal intervals within a given time range. Simple to implement, with even time coverage.
- Keyframe sampling: Prefer I-frames and other random-access points. Low decoding cost, but the temporal distribution of frames is uneven.
- Hybrid strategy: Primarily uniform sampling, with denser sampling for segments where adjacent frames differ sharply. Suitable for content with frequent shot changes, and more complex to implement.
Keyframe sampling is especially suited to the “extract frames by time range” scenario. With the container index, the decoder can start decoding from the nearest keyframe and then discard intermediate frames:
def sample_frames(video_path, start_sec, end_sec, fps, max_frames):"""Sample within the time range [start_sec, end_sec); frames returned in ascending time order."""interval = 1.0 / fpsframes, timestamps = [], []t = start_secwhile t < end_sec and len(frames) < max_frames:# The decoder automatically starts from the nearest keyframe and discards frames before the target timeframe, pts = decode_frame_at(video_path, t)frames.append(frame)timestamps.append(pts) # pts: presentation timestamp, i.e., the frame's true time in the videot += intervalreturn frames, timestamps
The benefit is direct: to process a 10-minute video, you only decode the few dozen frames you actually need, rather than decoding the whole thing.
4.3 Frame Rate and Frame Count: Two Knobs That Constrain Each Other
The actual sampling frame rate is determined jointly by the requested frame rate, the frame cap, and the video duration:
actual frame count = min(fps × duration, max_frames)actual fps = min(fps, max_frames / duration)
Assume max_frames = 32:
| Video duration | Frames expected at fps=1 | Actual frames | Actual fps |
|---|---|---|---|
| 30 seconds | 30 | 30 | 1.00 |
| 2 minutes | 120 | 32 | 0.27 |
| 10 minutes | 600 | 32 | 0.05 |
In other words, the longer the video, the coarser the temporal resolution. When a 10-minute video yields only 32 frames, the model sees roughly one frame every 19 seconds. Short-action or fast-counting questions are nearly impossible to answer reliably under such sampling. To improve the temporal resolution of long videos, there are only three paths: raise the frame cap, adopt a more efficient temporal representation, or do a second round of sampling guided by the question (see Section 4.5).
4.4 Resolution and Visual Token Budget
Resolution also needs controlling. A common approach is to set a pixel budget, scale the long edge to no more than the limit while preserving the aspect ratio, then align the dimensions. For frames that exceed the vision encoder’s maximum size, you can slice them into multiple sub-images and encode them separately. All preprocessing must be done on the server, and the same video must produce consistent results across multiple runs (reproducibility); otherwise both effect evaluation and online troubleshooting lose their baseline.
You also need to answer a capacity question: How many visual tokens will a video eventually become? The granularity of visual tokens differs across models. Some compress the visual features before concatenating them with the text; others essentially flatten and lay out the vision encoder’s output. Even if you can’t compute it precisely, you can measure it first, then constrain it with an empirical formula:
video tokens ≈ frame count × tokens per frame + temporal marker overhead
4.5 Adaptive Sampling: Spend the Frame Budget on “Useful” Frames
Fixed sampling treats information-dense segments and static scenes alike. A low-cost improvement is to first do a very sparse pre-sampling pass (e.g., 1 frame every 2 seconds), compute adjacent-frame differences on the decoded low-resolution frames, and allocate denser sampling time ranges accordingly.
Pseudocode:
def adaptive_sample(video_path, duration, max_frames):coarse = sample_frames(video_path, 0, duration, fps=0.5, max_frames=200)diffs = frame_differences(coarse.frames) # Adjacent-frame differences, e.g., histogram distancebudget = allocate_budget(diffs, total=max_frames) # Assign more frames to high-difference rangesframes, timestamps = [], []for seg_start, seg_end, n in budget:seg = sample_frames(video_path, seg_start, seg_end, fps=n / (seg_end - seg_start), max_frames=n)frames.extend(seg)timestamps.extend(seg.timestamps)return frames, timestamps
Three points to watch during implementation:
- Pre-sampling results can be cached for reuse across multiple conversation turns on the same video.
- The sum of frames across all time ranges must not exceed the cap.
- When decoding in parallel, frames must be reordered by timestamp. Parallel decoding can significantly speed up long-video preprocessing, but the return order is inherently scrambled. If used directly, the “order” the model perceives is wrong, and this kind of error often manifests in the output only as “answering off-topic,” which is extremely hard to locate.
5. Temporal Encoding and Chunking: Helping the Model Understand “Order”
5.1 Why Chunk
Encoding frame by frame carries no temporal information: the model sees a pile of unordered frame features, with no difference between frame 1 and frame 20. Yet “who came first,” “how long an action lasted,” and “when a shot changed” are exactly what require the model to understand inter-frame relationships.
A widely accepted practice is temporal chunking: split the frame sequence into fixed-length segments (chunks), organize frames within a chunk in time order, and explicitly annotate the temporal relationships between chunks.
def build_temporal_blocks(frames, timestamps, block_size=8):blocks = []for i in range(0, len(frames), block_size):chunk = frames[i:i + block_size]ts = timestamps[i:i + block_size]blocks.append({"index": i // block_size,"start_sec": round(ts[0], 2),"end_sec": round(ts[-1], 2),"frames": chunk,})return blocks
The choice of chunk size is a trade-off:
- Larger chunks: fewer chunks and lower overhead, but temporal information within a chunk is compressed, losing more fine-grained ordering.
- Smaller chunks: finer temporal granularity, but more separators and a lower proportion of useful information.
A common starting point is 4-8 frames, adjusted based on measurements on the target task.
5.2 Sending Temporal Information into the Model
Chunking alone is not enough; the model also needs to know “when” each chunk is. There are three common organizational approaches:
- Text markers: Insert a natural-language time description before each chunk, such as “Frames from 0.0 to 3.9 seconds:”.
- Structured markers: Insert special tokens before and after each chunk as boundaries, laying out features in frame order within the chunk.
- Time embeddings: Generate a time encoding for each chunk or frame and add it to the visual features.
In practice, these can be combined. An illustration:
<video>30 frames total, sampling interval 1.0 second, split into 4 sections:<section idx=0 t=0.0-7.0> [v0][v1]...[v7]<section idx=1 t=8.0-15.0> [v8][v9]...[v15]<section idx=2 t=16.0-23.0> [v16]...[v23]<section idx=3 t=24.0-29.0> [v24]...[v29]</video>
Mapped to the token sequence, placeholders, frame features, and time markers are interleaved:
[..., <video>, <sec 0 0.0-7.0>, [v0]...[v7], <sec 1 8.0-15.0>, [v8]...[v15], ...]
Here [v0] and similar are not real tokens, just illustrative positions occupied by visual features.
5.3 Confirm Three Things Before Adapting
The temporal scheme must be verified against the model before adaptation, otherwise you’ll “do a lot, but get it wrong”:
- Training template: What video organization did the model use during training or alignment? If you invent a format at inference time, you are effectively giving the model an input distribution it has never seen.
- Placeholder form: Do the special tokens already exist in the vocabulary? If you need to add them, you must update the vocabulary and embedding layer together. This involves a change in weight shapes and counts as “adaptation,” not “reuse.”
- Resolution alignment: Do the preprocessed dimensions match training time? A mismatch directly affects encoding quality.
These three points are the dividing line between “reuse” and “modification” across the entire pipeline, and the most error-prone spots.
6. Fusing Visual Tokens with the LLM
6.1 Placeholder Replacement
Once the frame features are computed, the final step is “feeding” them to the LLM. The mainstream approach places placeholders in the prompt template, then at inference time replaces the embedding positions corresponding to the placeholders with the visual features:
def build_prompt(blocks, question):"""Assemble the prompt per the model's conversation template; the number of placeholders must match the frame count."""parts = [f"<video>{len(blocks)} sections total:"]for b in blocks:parts.append(f"<section idx={b['index']} t={b['start_sec']}-{b['end_sec']}>")parts.append("<frame>" * len(b["frames"])) # One placeholder per frameparts.append("</video>")parts.append(f"Question: {question}")return "\n".join(parts)def merge_inputs(prompt, frame_features, embed_tokens, image_newline_id=None):input_ids = tokenize(prompt) # Tokenize to get the token ID sequenceinputs_embeds = embed_tokens(input_ids) # Text embeddingsframe_pos = [i for i, t in enumerate(input_ids) if t == FRAME_TOKEN_ID]assert len(frame_pos) == len(frame_features), "Number of frame placeholders does not match number of frame features"for pos, feat in zip(frame_pos, frame_features):inputs_embeds[pos] = feat # Replace placeholder embedding with visual featurereturn inputs_embeds, input_ids
FRAME_TOKEN_ID must correspond to the actual image/video placeholder in the model’s vocabulary and cannot be specified arbitrarily.
The most important thing in this code is that assertion. The biggest difference between video and images is that the frame count depends on runtime conditions: video duration varies, the sampling strategy is configurable, and the frame count differs greatly across requests. A mismatch between the number of placeholders and the number of frame features usually means that sampling counting, chunk splitting, or parallel reordering went wrong somewhere. Once misaligned, the visual features are “mixed up,” yet the model’s output errors often look like “poor comprehension.” Placing the validation before feeding the LLM can catch this class of problems at minimal cost.
6.2 Context Budget: Visual Tokens Are the “Big Spender”
A video request’s context composition is entirely different from pure text. Using the formula from Section 4.4, with a configuration of “about 256 visual tokens per frame, up to 64 frames,” a single video can consume more than 16K visual tokens; combined with the conversation history, it easily hits the context limit.
The service layer needs a “budget” mechanism:
- Total control: Based on the context window, prompt length, and expected output length, work backward to the visual token cap available per video.
- Downsampling fallback: When exceeded, sample frames at equal intervals per chunk, or enable chunk-level summarization (see Section 7.2), rather than simply truncating.
- History video reduction: In multi-turn conversations, earlier videos usually only need to keep a summary or key frames. If the inference framework supports cross-request cache reuse, you can compute the same video only once in later turns.
6.3 The “Instructions” to the Model Must Also Match Training
Video prompts usually consist of two parts: a fixed temporal description (like the example in Section 5), and text describing the overall video content. The latter should generally follow the model’s default prompt used at training; if you need to customize it, validate the effect on an evaluation set first.
For questions like “what happens in the video” or “what did the person do first, then next,” emphasizing “please describe in time order” and “please state clearly when you cannot determine from the frames” in the prompt often noticeably reduces the model’s speculation about non-existent content.
7. Plugin-Based Transformation and One-Click Deployment
7.1 Why Use a Plugin Instead of Modifying the Framework Directly
Writing video processing logic directly into the inference framework’s main pipeline brings three practical problems:
- The inference framework iterates quickly, so every upgrade requires re-merging the changes.
- Different models need different sampling and temporal strategies, so branches keep growing.
- Problems are hard to locate, making it difficult to tell whether it’s a framework issue or an adaptation issue.
Wrapping the adaptation as a standalone plugin lets it be loaded on demand at startup, decoupled from the framework’s main pipeline. A plugin usually contains four parts:
| Module | Responsibility |
|---|---|
| Request preprocessing | Identify video content blocks, perform probing, decoding, frame extraction, and chunking, and produce frame features and frame timestamps |
| Model adaptation | Load the vision encoder and feature projection module, register placeholder tokens, and declare the video conversation template |
| Budget control | Dynamically adjust frame count and resolution based on the context window and concurrency |
| Observability | Instrument to record decoding time, frame count, visual token count, and per-stage latency |
┌──────────────────────── Inference framework main pipeline ─────────────────────┐│ Request routing ──► Batch scheduling ──► LLM inference ──► Streaming output ││ ▲ ▲ ││ │ Video request │ Generated tokens │└───────┼──────────────────────────────────┼───────────┘│ │┌───────┴──────────────── Video input plugin ──────────────┴───────────┐│ Request preprocessing │ Model adaptation │ Budget control │ Observability │└─────────────────────────────────────────────────────────────────────┘
This layering brings an extra benefit: the same service can serve multiple vision-language models at once. The plugin provides an independent “capability description” for each model, and the framework only handles scheduling, without needing to maintain a separate service for each model.
7.2 A Two-Stage Strategy for Long Videos
For long videos, you can implement a two-stage process inside the plugin:
- Sparse preview: Extract representative frames at low resolution and low frame rate to generate a “global summary.”
- Targeted close-up: After the model identifies the time ranges of interest, do dense sampling and re-encode only those ranges.
This strategy is essentially “coarse first, then fine,” trading one extra encoding pass for better temporal resolution on long videos. It suits latency-insensitive scenarios such as offline analysis and generating video review reports.
7.3 Solidifying the Adaptation into a Deployment Recipe
The gap between “it runs” and “it’s reproducible” is a deployment recipe. A solid recipe should include:
- Version locking: model version, inference framework version, plugin version, and dependency library versions.
- Startup configuration: tensor parallelism, context length, GPU memory fraction, KV Cache strategy, etc.
- Default video parameters: sampling frame rate, frame cap, resolution cap, chunk size, and time-marker format.
- Dependency declaration: the video decoding library and its system dependencies (fixed in the container image as well).
- Self-check cases: sample requests covering short videos, long videos, multi-segment videos, videos without audio tracks, and corrupted files.
Version locking solves the “works on my machine, not yours” problem, default parameters guarantee consistent behavior across instances, and self-check cases turn post-deployment validation from “manually try a few” into “run once automatically.”
7.4 Resource Planning: Don’t Just Watch the GPU
The resource bottleneck of video inference is often not the GPU but the CPU and memory:
- Decoding is CPU-intensive work. When GPU utilization isn’t high, first check whether decoding has become the bottleneck.
- Preprocessing time may account for a substantial portion of total latency. You can instrument “probe time, decode time, encoding time, and first-token latency” separately to pinpoint the real weak spot.
- Decoding and inference can be decoupled. Making video preprocessing an independent service that submits tasks to the inference service via a message queue can smooth out peaks and valleys and let both sides scale independently.
- Containerized deployment. On a container platform, deploy in either a “decode and inference in the same container” or a “preprocessing as an independent service” form, combined with logging and monitoring/alerting to establish full-link tracing from request to token.
In a cloud environment, video files can be placed in object storage and read on demand, preprocessing tasks can run asynchronously via a message queue, the container platform handles elastic scaling, and monitoring/alerting guard the SLO. These general capabilities can be combined into various deployment forms; the key is selecting based on the business’s latency requirements:
- Interactive Q&A: synchronous interface, preprocessing and inference in the same process, prioritizing reduced decoding time.
- Batch analysis: asynchronous tasks, preprocessing and inference separated, prioritizing higher throughput.
8. Effect Verification and Common Problems
8.1 Acceptance Checklist
Before going live, it’s recommended to verify across four dimensions:
| Dimension | Check item | Pass criterion (example) |
|---|---|---|
| Functionality | Different container formats, codecs, frame rates, with/without audio | All parsed correctly; unsupported formats return a clear error code |
| Temporal | Event ordering, action counting, time-point localization questions | Build an evaluation set with ground-truth answers; compare before and after adjusting the temporal organization scheme |
| Consistency | Multiple requests on the same video | Output is reproducible after enabling deterministic decoding; frame-to-timestamp mapping is consistent |
| Stability | Corrupted files, extremely long videos, high concurrency | No crash, no hang; over-length requests are rejected or truncated per policy with the user notified |
In addition, continuously compare the local service against official cloud capabilities on the same questions. When the gap is obvious, prioritize investigating sampling parameters, temporal organization, and prompt templates, rather than suspecting the model itself.
8.2 Common Problems and Countermeasures
| Problem | Typical cause | Countermeasure |
|---|---|---|
| Long video “loses the middle,” answering only the beginning and end | Effective frame rate too low under uniform sampling | Raise the frame cap; do question-guided second-round sampling; two-stage processing |
| The answer’s time order doesn’t match the frames | Frames not reordered by timestamp after parallel decoding; missing time markers | Sort by timestamp; add temporal markers per the model’s training template |
| Output unrelated to the frames, or content not present in the frames | Placeholder and frame-feature count misalignment; preprocessing inconsistent with training | Add a count assertion; fix the preprocessing configuration and put it under version control |
| High first-token latency but low GPU utilization | Decoding is a CPU bottleneck; large-video preprocessing is serial | Make preprocessing a service; set a reasonable number of decoding threads; use hardware decoding if necessary |
| Prompt says “video too long” or output is truncated | Visual tokens exceed the context budget | Budget control; history video reduction; chunk-level summarization |
| Video function breaks after changing or upgrading the inference framework | Plugin too tightly coupled to the framework’s internal interfaces | Depend only on the framework’s stable public extension points, and write regression tests for the plugin |
9. Conclusion
Filling in a service’s video input capability has never been about “making the model understand video” — the weights already have that ability. The real work lies in turning video from a stream of bytes into the kind of input distribution the model saw during training. This requires:
- Reuse: The vision encoder, feature projection module, and LLM need no changes.
- Temporal: Frame extraction, chunking, and time markers together reconstruct the “order.”
- Consistency: Preprocessing parameters, templates, and placeholders strictly align with training.
- Decoupling: Adaptation exists as a plugin, and deployment is solidified as a recipe.
These four points are also the basic yardstick for evaluating whether a video input solution is “production-ready.” As for deployment form, interactive scenarios and batch tasks can adopt different splits, and general cloud capabilities such as object storage, message queues, container platforms, and logging and monitoring can be combined as needed. In the end, they all serve the same goal: making your local inference service no worse than the official cloud capability at video understanding, while keeping data and cost in your own hands.
