Adding Video Input to Local Multimodal LLM Inference: From Frame Decoding to Temporal Encoding
When teams deploy multimodal large language models locally, image Q&A often runs smoothly, yet video input tends to break in predictable ways: requests get rejected, answers fail to describe what happens on screen, or the model hedges on the order of events. The root cause is that a video is not simply "more images" but a timestamped sequence of frames. This article shows how to reuse the existing image pipeline—image preprocessing, visual encoding, and feature projection—and add three pieces: video reading and decoding, frame sampling with temporal chunking, and video visual-encoding adaptation with time-position encoding. It also covers visual-token budgeting, inference-framework integration, deployment and operations, validation, and common pitfalls. If you follow the "get it working, then tune, then standardize" approach, you can bring text, image, and video into the same local inference service and match the video understanding of hosted services.
When you deploy multimodal large language models on your own infrastructure, many teams hit the same gap: image Q&A works fine, but the moment you switch to video, problems pile up.
- The serving layer rejects it. A request that carries a video throws an error outright.
- It runs but answers poorly. The video plays through, yet the answer never clearly says what happens on screen.
- Order gets lost. For questions like “what happens first, what happens next,” the model stays vague.
Meanwhile, the open-source version of the same model already supports video input on the vendor’s hosted service. That gap in experience is a real headache for teams running their own deployment.
The root cause is this: a video is not just “more images” but a timestamped sequence of frames. From request handling and video decoding to frame sampling and chunking, and then to visual encoding, feature projection, and sequence assembly, if any single step is missing, the model never receives complete, ordered visual information.
The good news is that the image input path already provides image preprocessing, visual encoding, feature projection, and text generation. The visual encoder reads pixels, the Projector (the feature-projection module) maps the encoded result into the language model’s hidden space, and the LLM answers using that alongside the text. Adding video does not mean rebuilding a model from scratch—you just complete three pieces on the existing pipeline:
- Video reading and decoding: reconstruct the video stream into frames ordered by time.
- Frame sampling and temporal chunking: organize the order across frames within a controllable token budget.
- Video visual-encoding adaptation: reuse the image encoder weights while letting the model perceive the time position of each frame.
1. The end-to-end pipeline: how three inputs merge into one token sequence
To understand this extension, first see how text, image, and video inputs all eventually enter the LLM.
Text ── tokenization ── Embedding ───────────────────────────────────────┐│Image ── read + decode ──┐ │├─► Image preprocessing (resize / pad / │Video ── read + decode ──┘ normalize / patch split) │└─ sampling + temporal chunking ┘ │▼ │Visual encoding (shared image/video weights) │▼ │Projector projection │▼ │Splice at placeholder positions in the prompt ◄────────────┘▼LLM ──► token-by-token generation
(Figure 1: How text, image, and video inputs are processed. Images and video frames share the same image preprocessing and reuse the same set of visual-encoding weights, while the exact processing flow differs.)
The text path is the most direct: the tokenizer splits the input into subword units and looks up an embedding vector for each token. Multimodal prompts are usually organized by a chat template, and the template keeps placeholders for images, videos, and so on. These placeholders are just one or two special tokens; the actual visual information is “expanded” into the corresponding positions in a later step.
The image path has four steps:
- Read the image file and decode it into a pixel array.
- Resize to the resolution configured for the model and pad, preserving the original aspect ratio.
- Apply channel normalization.
- Split into fixed-size patches and flatten them into a sequence of visual tokens.
The visual encoder (typically a vision-Transformer-style structure) outputs a feature for each patch, and the Projector maps it into the language model’s hidden dimension, producing visual vectors that can be spliced with the text embeddings.
The video path is highly consistent with the image path after preprocessing; the only difference is one extra step before preprocessing:
- An image is a single piece of pixel data.
- A video is a string of timestamped image frames.
A video must first be read and decoded into frames, then sampled according to configuration and organized into chunks in time order, after which it enters image preprocessing just like an image. Put differently, video = an ordered frame sequence + time information.
This observation drives the whole extension strategy: write as little new code as possible, and retrain as few weights as possible. The existing image pipeline already has image preprocessing, visual encoding, feature projection, and answer generation, all of which can be reused in full when you add video. What’s genuinely new is just the connective logic that turns a “single frame” into a “sequence of frames with time coordinates.”
2. Piece one: video reading and decoding
2.1 What decoding needs to produce
The goal of the video-reading step is not to “open a file” but to produce a set of frames ordered by time, keeping a timestamp for each frame.
A common mistake is to record only the “frame number” and ignore the “second.” Here’s why:
- Variable frame rate. Frame intervals are not uniform across segments, so the frame number alone cannot reconstruct the real playback rhythm.
- Display order vs. decode order. Modern codecs widely use bidirectional-prediction frames, so the stored order in the bitstream differs from the playback order. The decoder handles the reordering automatically, but if the adapter simply concatenates frames by their raw frame number, the picture order can end up scrambled.
- Later capabilities depend on time information. When the model answers questions like “at what second did this action happen” or “how far apart are these two scenes,” it needs to tie visual features to real time.
So the adapter should use the timestamp (usually in seconds or microseconds) as the primary key for each frame at decode time, with the frame number kept only as a secondary field.
2.2 Choosing a decoding strategy
If a long video is decoded in full from start to finish, you run into two problems:
- Decode time grows linearly with video duration.
- Intermediate states during decoding also consume memory.
In practice, teams use two strategies, or combine them:
- Keyframe seeking. Video encoding uses “keyframes” as anchors, and a number of frames form an independent decode unit. Jump to the keyframe closest to the target time and decode sequentially from there to the target position, so you process only the small slice you need instead of the whole video.
- Streaming reads. The service reads directly from the video location and fetches data on demand, avoiding downloading the entire video to local storage first.
Streaming reads add a requirement: the video storage service must support range reads by byte. In practice, teams usually first transfer user-uploaded videos to object storage, then pass the stable internal address to the inference service, avoiding the security and stability risks of letting inference nodes connect directly to external addresses.
2.3 Edge cases and error handling
Video sources in real business settings are messy, so the adapter needs clear boundary policies up front:
- Protective caps. Set limits on file size, video duration, and per-frame resolution; return a clear error quickly when they’re exceeded, rather than letting a doomed decode exhaust resources.
- Format and codec compatibility. Whatever container formats and video codecs the service claims to support should truly be supported (“declared means supported”). When something is unsupported, return a clear error code instead of throwing an exception inside the service that’s hard to trace.
- Metadata correction. Some videos shot on phones carry rotation flags, and some have non-square pixel aspect ratios that affect the display aspect ratio. Apply rotation correction from metadata before preprocessing; otherwise you feed the model a “lying down” image.
- Short-video fallback. When the duration is shorter than one sampling window, define how to handle it explicitly—for example, error out if there isn’t even one frame, or honestly note “this clip contains only 3 frames.”
Illustrative code below; the function names are for explanation only:
def load_video_frames(source, max_duration_s=120, max_frames=64):"""Read a video and return a list of (frame, timestamp) ordered by time"""meta = probe_video(source) # probe duration, resolution, frame rate, and other metadataif meta.duration_s > max_duration_s:raise InputTooLongError(meta.duration_s)frames = []for frame in decode_stream(source): # streaming decode, no whole-file downloadif frame.timestamp_s >= max_duration_s:breakframes.append((apply_rotation(frame.image, meta.rotation),round(frame.timestamp_s, 3))) # correct rotation, keep the real timestampreturn frames
3. Piece two: frame sampling and temporal chunking
3.1 Why sampling is necessary
Every frame produces several visual tokens after encoding. Without sampling, a video of just a few seconds can fill the entire context window, and inference cost multiplies.
More importantly, the vast majority of multimodal models saw sampled frames during training. What the model learned is “temporal patterns under sparse sampling,” not “every single consecutive frame.” If the adapter sends an un-sampled dense sequence, it actually pushes the input away from the model’s training distribution—a poor trade.
3.2 Common sampling strategies
- Fixed frame-rate sampling. For example, take one frame per second: time coverage is even, but the frame count grows linearly with duration.
- Uniform sampling by total frame count. First decide on a maximum of N frames, then split the video duration into N equal segments and take one frame from each. No matter how long the video is, the visual cost stays fixed.
- Two-level constraint. Set a maximum frame count first, then sample at a target frame rate; stop when either condition is hit first. Most production services use this approach to balance coverage against cost.
A few implementation details also matter:
- After you change the target frame count, recompute the index mapping so sampled moments are spread evenly across the whole video.
- Check frame-count boundaries before and after sampling to avoid off-the-end indexing.
- Keep the real timestamp of each sampled point, and hand it to the temporal-encoding step later.
3.3 Why temporal chunking matters
The sampled frames are still a long sequence. Feeding it to the visual encoder all at once brings several problems:
- Peak GPU memory. GPU memory usage during visual encoding scales with sequence length, and long sequences easily trigger out-of-memory errors.
- Poor scheduling fit. Batching and cache management in inference frameworks usually operate at the granularity of small processing units.
- Too coarse. A video of several tens of seconds gets compressed into a few dozen pieces of visual information, which is hard to support fine-grained temporal localization.
Temporal chunking works like this: split the sampled frames into several contiguous small chunks by time order, feed each chunk into the visual-encoding pipeline as an independent unit, then splice them at the sequence level in chunk order.
It’s worth stressing that chunking solves an organization problem, not a compression problem:
- The total number of visual tokens does not shrink because of chunking.
- But chunking keeps each encoding unit controllable and gives you a handle for finer budgeting of frame count and resolution.
3.4 Implementation notes for temporal chunking
Illustrative code below:
def split_temporal_chunks(frames, chunk_size=4, max_chunks=8):"""frames is a time-ordered [(image, timestamp)]; split into temporally contiguous frame chunks"""chunks = [frames[i:i + chunk_size] for i in range(0, len(frames), chunk_size)]return chunks[:max_chunks] # truncate over-long videos to the first chunks, or sample evenly across segments
A few points to keep in mind:
- Temporal continuity within a chunk. Frames within a chunk stay sorted by ascending timestamp; keep that order through both decoding and chunking.
- Configurable chunk length. Chunk length depends on the visual encoder’s processing granularity and the GPU-memory budget, and shouldn’t be hard-coded.
- A clear policy for over-long videos. When you exceed the maximum chunk count, do you truncate to the first few segments or pick a few segments evenly across the timeline? The two strategies fit different tasks. The former suits scenarios focused on opening information; the latter suits locating key events within a long video.
3.5 Coordinating sampling and chunking
In practice, sampling and chunking are often two sides of the same configuration:
- The frame rate determines how finely you cover time.
- The chunk size determines how much visual information each encoding pass carries.
Together they determine the final number of video visual tokens, and directly determine the maximum video duration the service can handle. It’s a good idea to collect these parameters as configuration items alongside “resolution tiers” and pass them explicitly per request, rather than scattering them as constants in the code.
4. Piece three: adapting visual encoding for video
4.1 Reuse the weights, adjust the flow
Once video frames enter preprocessing, they go through exactly the same resize, pad, normalize, and patch-split flow as images, and both the visual encoder and the Projector reuse the same set of weights.
This means you don’t need to train a separate visual encoder for video, nor introduce a new model file. The only adjustment is “how to organize multi-frame input”:
- Frame-dimension handling. Flatten multiple frames into the batch dimension and encode frame by frame.
- Batched encoding. When GPU memory allows, combine multiple frames from the same chunk into one batch to improve hardware utilization.
- Reordering the encoding output. Restore the encoding output to the “chunk–frame–patch” hierarchy for later splicing.
4.2 Organizing video visual tokens
After encoding and projection, a single image produces a fixed number of visual tokens. Video needs that base image-token count multiplied by the number of frames (or the total frames after chunking).
An easy-to-follow structure looks like this:
[video placeholder] → [chunk 0: frame 0 patch sequence][frame 1 patch sequence]...[chunk 1: frame 4 patch sequence][frame 5 patch sequence]... → [video placeholder end]
This layout has three benefits:
- Visual tokens map one-to-one with the placeholders in the prompt, so the LLM knows exactly which vectors come from the video.
- The boundaries between chunks are clear, which makes later time-aware attention processing easier.
- When debugging, you can pinpoint “which chunk, which frame” has an anomalous feature.
4.3 Time-position encoding: telling the model “when”
This is the most easily overlooked step in video adaptation, yet it has the biggest impact on quality.
An LLM’s positional-encoding mechanism only understands “which token index,” and it has no idea which second of the video a given visual token corresponds to. If you simply reuse the image approach and string all video frames into one ordinary sequence, the model can perceive only the order of frames; it cannot build a correspondence between “picture content” and “time coordinate.”
A common industry approach borrows from how multi-dimensional rotary position encoding is used in multimodal models: split a token’s position from a single one-dimensional index into multiple dimensions—time, height, and width—and encode each separately. For video specifically, that means computing, for every visual token:
- which frame it belongs to, or which timestamp it corresponds to;
- its patch row and column position within the frame.
Illustrative code below:
def build_multimodal_positions(video_tokens, frame_timestamps, patch_h, patch_w):"""Generate a (time, row, col) triple position for each visual token"""positions = []for frame_idx, ts in enumerate(frame_timestamps):for row in range(patch_h):for col in range(patch_w):# the time dimension can use the frame index or a discretized timestamp; the exact value depends on the model implementationpositions.append((frame_idx, row, col))return positions
Three points to keep in mind:
- Align the time-dimension value with the model implementation. Some implementations use the frame index, others use a discretized timestamp. This step must strictly follow the design of the version you’re adapting—don’t assume you can swap it in freely, or the positional encoding will “not match” the weights.
- Choose the time step. If the model supports it, using a discrete time step instead of the frame index expresses “how long between two frames” more precisely, which matters especially for sparsely sampled long videos.
- Keep the text-side positions continuous. Video tokens “jump” along the time dimension, but text-token positions should remain naturally continuous. When splicing, maintain two separate position-index sets and ensure they don’t interfere at the attention-mask level.
4.4 The engineering value of chunked pipelining
Splitting video processing into a “decode → sample → chunk → per-chunk visual encoding” pipeline brings an extra benefit: you can encode while decoding, without waiting for the whole video to be read.
This yields three advantages:
- Decoding and visual encoding can overlap, shortening the wait for the first token.
- GPU memory stays at the size of a single chunk and never accumulates with video duration.
- If a frame chunk fails to decode, you can fail fast before it enters visual encoding, avoiding wasted compute.
5. Visual tokens and context budget
Once video is added, the most immediate change is the sharp rise in the number of visual tokens. The adapter needs to do this accounting “before sending to the model.”
A simplified estimation relationship:
- Tokens for a single video ≈ sampled frames × patches per frame.
- With chunked encoding, total tokens ≈ number of chunks × chunk length × patches per frame.
- Prompt tokens, conversation history, and system-instruction text tokens are counted separately.
This means:
- Frame count is the main cost variable. Doubling the frames roughly doubles the visual tokens, and GPU memory and latency rise in step.
- Resolution matters just as much. Higher per-frame resolution increases the patches per frame.
- Multiple videos stack up. When one request carries several videos, the cost adds up, so you need an overall cap.
It’s a good idea to build a “budget check” step into the adapter: estimate the total token count before sending to the model, and when it exceeds the limit, auto-degrade by configuration—first try reducing frame count, then lowering resolution, then truncating video duration.
Also return to the caller the frame count, resolution, and truncation actually used. This is a basis for troubleshooting, and it prevents users from misunderstanding “why the model didn’t see everything.”
6. Inference framework adaptation: bringing video into scheduling
Completing the input-side processing isn’t enough; you also need the inference framework to “recognize” video.
6.1 Extending the request protocol
The interfaces of mainstream inference frameworks usually stay compatible with common multimodal message formats. The video input hook is this: on the server’s request-parsing layer, recognize the content item of the video type and call the corresponding handler.
Illustrative code below (field names are illustrative only, not the interface definition of any specific service):
{"messages": [{"role": "user","content": [{"type": "text", "text": "Describe the order of the person's actions in this video"},{"type": "video_url", "video_url": {"url": "https://example.internal/videos/demo.mp4"}}]}],"extra_body": {"video_sample_fps": 1.0,"video_max_frames": 64,"video_chunk_size": 4}}
Note that the sampling parameters above are custom extension fields of the adapter; naming may differ across service implementations, so don’t apply them directly to another implementation.
6.2 Handler registration and pipeline mounting
Inference frameworks usually provide a mechanism to register “multimodal input handlers.” The adaptation work is essentially:
- Implement a video handler that declares it can process video-type content.
- Register the handler to the framework’s multimodal-processing pipeline at startup.
- Inside the handler, chain together decoding, sampling, chunking, visual encoding, and time-position construction.
Some frameworks use a plugin mechanism, so adding a modality only requires implementing the agreed interface and registering it, with no changes to the core scheduling code. The benefits of this design:
- Video capability can be enabled independently per deployment instance.
- When unused, it adds no extra overhead to the main inference path.
- When you later extend to other modalities such as audio, you can reuse the same integration approach.
6.3 Scheduling and batching
Video requests differ from other requests at the scheduling layer in two ways:
- Preprocessing takes a large share of time. Decoding and visual encoding often take longer than text generation itself, and synchronous processing blocks the request queue. Video preprocessing is usually moved to a separate thread pool or an asynchronous task queue.
- Visual-token lengths vary widely. Token counts differ enormously across videos, so mixing them in a batch easily wastes GPU memory or lets long and short requests drag each other down. Bucket requests by visual-token count so requests of similar length land in the same batch.
6.4 GPU memory and caching
GPU memory is the most direct constraint for video inference. Common measures include:
- Chunked encoding to control the peak of a single encoding pass.
- Visual-feature caching. For videos with identical content and parameters (a cache key can be built from a content hash plus sampling configuration), cache the encoding result so repeated requests reuse it directly.
- Prefix caching. If the framework supports prefix caching, common prefixes like the system prompt before the video placeholder can be reused.
- Quantization. Quantize the LLM weights to free GPU memory for visual encoding. But after quantizing, verify whether visual-feature expressiveness degrades, especially for fine-grained recognition tasks.
7. Deployment, operations, and validation
7.1 Configuration is a prerequisite for production
After video capability goes live, parameters like frame rate, maximum frames, resolution tiers, and chunk length get tuned frequently. It’s a good idea to make all of them configurable and inject them via environment variables or a config file, so you don’t have to rebuild the image every time you tune.
At the same time, distill “model integration + temporal processing + inference-framework adaptation” into a reusable deployment recipe: package dependencies, the handler plugin, default configuration, and health checks together, so a new environment can be brought up by the recipe and get full video-input capability—reducing the environment differences that come from manual steps.
7.2 Cloud deployment notes
If the service runs in the cloud, you can combine generic cloud capabilities as needed:
- Object storage: store video assets and model artifacts, and rely on its range-read capability to support streaming decode.
- Container platform: run the inference service image, with elastic scaling to handle traffic swings.
- Load balancing: distribute video requests to the instance group that has visual-encoding capability.
- Logging and monitoring/alerting: collect decode time, encoding time, frame-count distribution, GPU-memory usage, and error-code distribution, and set alerts on metrics like out-of-memory events and decode failure rate.
7.3 Validation methods
Validating video capability can’t stop at “it runs.” Build a validation set across four levels:
- Basic understanding: recognize single-frame content to confirm the visual-encoding path works.
- Temporal understanding: action order and event sequence, to check whether the time-position encoding is effective.
- Cross-frame reasoning: questions that require combining information from multiple frames, to check whether sampling coverage is sufficient.
- Detail localization: times, text, and object counts appearing on screen, to check whether resolution and frame density are enough.
For the same set of questions, you can answer with both the hosted service and your local service and compare. When differences concentrate on temporal questions, check the time-position encoding first; when they concentrate on detail questions, check the sampling and resolution configuration first.
8. Common pitfalls
| Symptom | Common cause | Suggested fix |
|---|---|---|
| Video request fails outright | The request-parsing layer has no registered video handler | Check handler registration and startup logs |
| Answer is unrelated to the video content | The placeholder wasn’t expanded; visual vectors didn’t enter the sequence | Print the spliced sequence structure to verify |
| Model misses temporal questions | No time-position encoding, or frame order is scrambled | Check timestamp propagation and chunk splicing order |
| Long-video request runs out of GPU memory | Too many frames or no chunked encoding | Tighten the max-frame limit, enable chunked encoding |
| Image orientation is wrong | Rotation metadata not handled | Correct orientation from metadata before preprocessing |
| High time-to-first-token | Synchronous decode of the whole video | Switch to streaming reads and chunked pipelining |
9. Summary
Adding native video input to a local multimodal inference service is essentially an exercise in “doing addition on the existing pipeline,” and the core comes down to three points:
- Keep timestamps in the decode step. A video is first a string of frames with time coordinates, and time information is the foundation for every later temporal capability.
- Control cost with sampling and chunking. Within a limited token budget, use sensible sampling and chunking strategies to buy as complete a time coverage as possible.
- Reuse encoding + align time positions. Reuse the image pipeline’s visual encoder and Projector weights directly; the genuinely new part is encoding “which frame, which second” into the model’s positional representation.
On top of this, combine request-protocol extension, plugin-style handler registration, bucketed scheduling, and GPU-memory management, and you can bring text, image, and video into the same local inference service, achieving video understanding on par with hosted services.
In practice, follow the order “get it working first, then tune, then standardize”:
- First validate the whole pipeline with a single short video.
- Then use comparison experiments to find a good combination of frame rate, frame count, and resolution.
- Finally distill the configuration and handlers into a reusable deployment recipe, turning environment delivery from “manual setup” into “bring-up by recipe.”
