Native Multimodal Large Models: Technical Innovations and Long-Context Engineering Practices
This article explains how native multimodal large models unify text and images in a shared sequence, how long-context mechanisms such as sliding-window attention work in practice, and how to deploy reliable multimodal inference on limited GPU memory. It covers visual tokenization, positional encoding, KV cache optimization, chunked prefill, quantization, evaluation, and local/cloud deployment patterns.
1. Introduction: From “Seeing Images” to “Natively Understanding Any Image”
Over the past two years, the capability boundary of large models has expanded from pure text understanding to mixed text-and-image understanding. Flowcharts in technical documents, tables in financial reports, objects in monitoring footage, and lesions in medical images all require the model to process text and pixels within the same reasoning process.
At the same time, user inputs are becoming increasingly “heavy.” A several-hundred-page product manual may contain dozens of images, a monitoring video may contain thousands of frames, and images referenced across multiple conversation turns can continue to accumulate. Relying only on a text-oriented sliding window is no longer sufficient for such long, image-text mixed contexts.
Against this background, a group of models claiming to be “native multimodal” has emerged. Their typical characteristics are:
- Model scale in the range of billions to tens of billions of parameters;
- Native support for arbitrary resolution, arbitrary aspect ratio, and arbitrary numbers of image inputs;
- Text and images sharing the same context window.
What exactly is new about these models from a technical perspective? Can their design be implemented under limited hardware conditions? This article addresses these two questions. It first reviews the core architectural innovations of native multimodality, then discusses key mechanisms for long context and inference efficiency, and finally presents a reusable set of engineering practices.
2. From “Bolted-on Vision” to “Native Multimodality”
2.1 Structural limitations of early multimodal approaches
Early image-text understanding systems mostly adopted a “bolted-on” architecture. A common approach was to freeze a pretrained vision encoder and a language model, then train a lightweight projection layer or adapter to map visual features into the language model’s embedding space.
This approach is simple to implement, but it has several structural limitations:
- Restricted input formats: Vision encoders are usually pretrained at a fixed resolution. Input images need to be resized or padded into square shapes, and fine-grained information in long documents or wide charts may be lost during preprocessing.
- Difficult image-count scaling: Multiple images can only be encoded one by one and then concatenated. There is no unified mechanism for modeling spatial relationships and cross-references between images.
- Potential weakening of text capabilities: Model parameters are effectively split into separate visual and language sides. Because knowledge sharing between the two sides is limited, text-only tasks may experience capability regression.
2.2 Three criteria for “native multimodality”
The industry usually evaluates whether a model is “natively multimodal” from the following three dimensions:
- Unified sequence modeling: Images are converted into visual tokens by a vision encoder and concatenated with text tokens into a single sequence. The same Transformer backbone performs joint modeling across modalities. The model does not need a dedicated cross-modal attention module or independent adapter to build associations between modalities.
- Arbitrary resolution: The vision side uses pixel-patch splitting that is decoupled from resolution. Image size and aspect ratio no longer need to be unified in advance. Each pixel patch is converted into a fixed-dimensional vector, and the sequence length changes dynamically with image size.
- Arbitrary number of images: Multiple images are placed in the same sequence and separated by predefined placeholder markers. The model can compare and reason across different images, such as comparing two versions of a design draft or matching a chart with the surrounding text.
2.3 Capability gains from native approaches
The significance of unified sequence modeling goes beyond architectural simplification. More importantly, it changes the training paradigm.
Interleaved image-text corpora, such as web pages, textbooks, and presentation slides, no longer require complex modality alignment preprocessing. They can be organized directly as interleaved “image-text-image-text” sequences according to their original layout and trained with the same autoregressive objective as pure text.
This brings three benefits:
- The model learns the distribution of mixed image-text content itself, rather than isolated image-text pairs;
- Positional information naturally aligns with the original layout, allowing the model to determine whether a passage describes the previous image or the next image;
- There is no need to maintain two separate parameter sets for the vision side and the language side, greatly simplifying deployment and upgrade processes.
3. Technical Innovation 1: Image Markers, Visual Tokens, and Positional Encoding
3.1 Image markers and placeholder tokens
In a unified sequence, image boundaries need explicit markers. A common approach is to introduce special image-start and image-end tokens and insert placeholders between them equal to the number of visual tokens.
During training, the model fills the visual encoder outputs into the corresponding placeholder slots. During inference, the image only needs to pass through the vision encoder once, and the result can be reused across turns. In multi-turn dialogue, an image referenced repeatedly does not need to be encoded repeatedly.
Several engineering details require special attention:
- The number of placeholder tokens must exactly match the actual output length of the visual encoder; otherwise, embedding alignment will be incorrect.
- Tokens occupied by special markers should be counted toward the context budget.
- Template concatenation logic must cover all combinations: text-only, single image, multiple images, and interleaved text-image content. Unit tests should be used to ensure boundary correctness.
3.2 Estimating the number of image tokens
Once images are converted into visual tokens, the sequence length increases. Suppose the vision encoder uses p×p pixel patches and then applies k×k spatial merging, which means adjacent k×k pixel-patch features are concatenated or pooled into one visual token. The number of visual tokens for a single image is approximately:
N ≈ ⌈H/p⌉ × ⌈W/p⌉ / k²
In common configurations, p is 14 or 16, and k is 2. For example, for a 1024×768 image with p=16 and k=2:
- The number of pixel patches is 64×48, totaling 3072 patches;
- After merging, the number of visual tokens is approximately 32×24 = 768 visual tokens.
This is already close to half of the approximately 1K training context used by many models. It can be estimated that in a 32K context window, the maximum number of full-resolution images is about 40. However, if budget must also be reserved for text instructions and model responses, the number of usable images will be further reduced.
These estimates are only for capacity planning. Different models differ significantly in patch size, merging method, and special token handling. The actual token count should be determined based on the tokenizer and image-processing logic of the chosen model.
3.3 High-resolution document input: two necessary practices
- Choose resolution based on the task: Fine-grained tasks such as information extraction and receipt recognition require sufficiently high resolution, but higher resolution means more visual tokens. It is recommended to test with representative samples and compare task metrics and inference latency across resolutions to find the inflection point, rather than blindly using the highest resolution.
- Chunk long documents: A PDF of several hundred pages cannot be fed into the model at once. It should be split according to layout structure, such as chapters, pages, and paragraphs, and then combined with image-text retrieval to recall relevant segments. This is the most effective way to control context length and inference cost.
3.4 Image positional encoding: 1D or 2D?
For text, rotary position embedding (RoPE) applies position-dependent rotational transformations to query and key vectors, allowing attention scores to naturally depend on relative distance. RoPE is widely used for long-context extension.
Images, however, are flattened into a one-dimensional sequence and fed into the model. If pure one-dimensional encoding is used, the model can only perceive the order of pixel patches and may struggle to accurately understand vertical and horizontal spatial relationships.
Several common approaches are used in industry:
- Encoding horizontal and vertical coordinates for visual tokens at the same time, such as two-dimensional rotary position embedding;
- Learning independent positional embeddings for each pixel patch;
- Introducing local spatial priors implicitly through structures such as convolution inside the vision encoder.
The goal of these methods is the same: preserve the spatial structure of images while ensuring compatibility between the positional systems of visual tokens and text tokens. This enables the model to answer questions such as “the red arrow in the upper-right corner points to the third box.”
4. Technical Innovation 2: Sliding Window Attention and Long Context
4.1 Traditional full attention: the “quadratic tax” of length growth
Standard Transformer self-attention computes relationships between any two tokens in the sequence. When the sequence length is n, the computational and memory complexity is O(n²).
For example, with a 4K context, the attention matrix alone contains approximately 16 million elements. If the length increases to 32K, the value grows to approximately 1 billion, about 64 times larger. In real systems, the bottleneck is not only computation but also the memory pressure caused by the KV cache.
4.2 Sliding window attention: changing O(n²) to O(n×w)
Sliding Window Attention (SWA) assigns each token a fixed attention window w. For example, when w=4096, the token at position i can only attend to tokens in the range [i−4095, i]. The total computation is reduced to O(n×w). When the sequence length is much larger than the window size, complexity grows linearly with n.
The following example shows the masking logic. In real inference, lower-level operators usually compute attention in blocks according to the window size, so there is no need to explicitly construct the full n×n matrix:
def sliding_window_causal_mask(seq_len: int, window: int = 4096):"""Construct a sliding-window causal mask, where True means attention is allowed.The shape is (1, 1, seq_len, seq_len). This is for illustration only and isnot recommended for direct instantiation in high-performance inference."""idx = torch.arange(seq_len)q_pos = idx.view(-1, 1) # Query positionk_pos = idx.view(1, -1) # Key positioncausal = k_pos <= q_pos # Causal constraint: can only attend to previous tokensin_window = (q_pos - k_pos) < window # Window constraint: only attend to the most recent window tokensreturn (causal & in_window).view(1, 1, seq_len, seq_len)
4.3 Why sliding window attention works
The rationality of sliding window attention is based on three points:
- Local dependencies in language: Adjacent words and sentences have the strongest dependencies, and most semantic information comes from nearby content.
- Sparsity of attention: Research shows that attention weights are highly concentrated on a small number of key positions, but these key positions are usually not uniformly distributed across the entire text.
- Hierarchical propagation: A token outside the window in the current layer can transmit information through intermediate tokens across subsequent layers.
Some models also use a hierarchical structure that alternates local window layers with global attention layers. This controls overall overhead while preserving a global view.
4.4 Cost and boundaries: not “lossless window expansion”
The cost of sliding window attention is clear: any two tokens beyond the propagation range of the window layers cannot establish an accurate, one-step direct association. This leads to an important conclusion:
“Input length” is not equal to “effective perception range.”
Some models may have a context window of 32K, but a single layer may only attend to 4K tokens. This means:
- Information at the beginning of the input may be diluted or even lost after being passed through dozens of layers;
- The direct association between the 1st token and the 20000th token may be weak;
- Exact “needle-in-a-haystack” retrieval ability may degrade as positions move farther away from the window boundary.
A practical principle follows: the value of long context depends on how key information is organized, not just the size of the window number.
4.5 Methods for making long context effective
| Method | Practice | Applicable scenarios |
|---|---|---|
| Key information first | Put summaries, task goals, and output format constraints at the beginning or close to the question | Global instruction requirements |
| Segmented summarization | Compress long text in sections; send summaries and original fragments together | Long report analysis, contract review |
| Image-text retrieval | Retrieve relevant image-text fragments first, then reorganize the input in original order | Knowledge base QA, document QA |
| Hierarchical caching | Preserve historical summaries and key information across turns to control context growth | Multi-turn dialogue, long-session agents |
| Position validation | Place key information at the beginning, middle, and end during testing | Robustness validation before launch |
5. Technical Innovation 3: System Design for Inference Efficiency
5.1 KV cache: the memory benefit of sliding window
During autoregressive generation, the model needs the keys and values of all previous tokens for each new token. Recomputing them at every step would be too expensive, so KV caching is used in practice.
Sliding window attention naturally supports cache optimization: tokens beyond the window will never be attended to again, so their KV cache entries can be evicted directly.
In engineering, a ring buffer is commonly used to store the KV cache. Space is preallocated to the window size, and newly written positions cyclically overwrite the oldest positions. Memory usage changes from growing linearly with sequence length to remaining constant.
A rough estimate is:
KV memory ≈ 2 × number of layers × number of KV heads × head dimension × sequence length × bytes per precision × concurrency
For example, a typical 7B-level model with 32 layers, 8 KV heads, head dimension 128, and FP16:
- KV cache per token is approximately 0.125 MB;
- Caching a 32K context requires approximately 4 GB;
- With 8 concurrent requests, approximately 32 GB is needed.
If 32 KV heads are reduced to 8, KV memory can be reduced by approximately three quarters. This is why techniques such as grouped-query attention and multi-query attention are widely adopted: they do not fundamentally change the main expressive power of the model, but significantly reduce memory and memory-access overhead.
5.2 Chunked prefill
The prefill stage needs to process all input tokens at once. Peak activation memory and attention computation can be very high, especially for long documents.
Chunked prefill splits the input into several blocks and processes them sequentially, passing necessary state between blocks. This keeps peak memory controlled at the size of a single block. Small blocks can also be interleaved with decoding requests in scheduling, reducing time-to-first-token in concurrent scenarios.
5.3 Quantization: the dividing line for memory thresholds
| Precision | Bytes per parameter | Estimated 7B model weights | Typical use case |
|---|---|---|---|
| FP16 | 2 | About 13–14 GB | Ample memory, pursuit of accuracy |
| INT8 | 1 | About 7 GB | Mainstream GPUs with 12–16 GB memory |
| 4-bit | 0.5 | About 4–5 GB, slightly higher with quantization metadata | Entry-level GPUs with about 8 GB memory |
For a 7B-level model, full precision requires about 13 GB of memory for weights alone, which many consumer GPUs cannot support. With 8-bit quantization, it is about 7 GB, and with 4-bit quantization it can drop to around 5 GB. An entry-level 8 GB GPU can also run a 7B-level model after leaving enough room for activations, KV cache, and framework overhead.
Key points for quantization:
- Format selection: 8-bit quantization is simple to implement and has low accuracy loss. 4-bit often uses formats such as NF4, a quantile quantization format designed for weights with normal distributions, combined with double quantization to reduce the storage overhead of quantization constants.
- Calibration and protection: Specify the computation data type during loading, such as FP16 or BF16. Quantization applies only to weights, while matrix multiplication accumulation is performed at higher precision. Numerically sensitive components such as LayerNorm and embedding layers can also be kept at higher precision.
- Accuracy validation: After quantization, output quality must be compared on task-specific datasets. Perplexity only reflects general language ability and cannot replace domain-specific task evaluation.
6. Engineering Practice: Long-Context Inference on Limited GPU Memory
In a real practice of handling ultra-long context, a team initially planned to perform long-text analysis based on a model with a 4K context window. They found that even if a larger sliding window was set through the configuration file, the actual attention computation logic did not change, and inputs were still truncated by the position limit. They then evaluated another model with a larger window, but its hardware compute and memory could not support a task of the same scale. Finally, the team selected a model with native sliding window support and a 32K context window as the practice target.
This experience reveals a point often overlooked during model selection: the model parameter count is only a necessary condition. Whether the implementation truly supports the mechanism, and whether the hardware can handle it, are the decisive factors.
Based on this, the team built a complete local deployment solution. Its core capabilities included:
- Supporting 4/8-bit quantization and running on ordinary GPUs with more than 6 GB memory;
- Optimizing Chinese prompt organization so that an English-centric model can output high-quality Chinese results;
- Using the native sliding window mechanism to process Chinese long texts of more than 20,000 characters;
- Providing a complete inference workflow, including input length validation, latency statistics, and structured result extraction.
6.1 Memory budget: weights are only the starting point
The full composition of memory usage is as follows:
Total memory ≈ model weights + KV cache + activations + framework and runtime overhead
- A 7B model quantized to 4-bit has weights of about 5 GB;
- Framework, CUDA context, and runtime reservations usually take 1–2 GB;
- The remaining space is used for the KV cache.
Therefore, the officially claimed “minimum memory” often only covers the weights. Production environments should reserve at least 20%–30% extra margin for peak usage to avoid memory overflow with long inputs or high concurrency.
6.2 Left padding: a hidden pitfall in batch processing
Left padding means adding padding tokens on the left side of a sequence so that the effective content of all samples is right-aligned. It is especially important for long-text generation for three reasons:
- Consistent generation position: New tokens for all samples in a batch start from the same relative position. With right padding, the generation position of shorter samples differs from that of longer samples. Since position encoding and causal masks are calculated based on absolute positions, this can easily cause attention offset.
- Avoiding padding tokens in computation: As long as the attention mask is correct, padding positions do not participate in attention computation. However, if the framework handles attention mask concatenation improperly, padding tokens may still enter the KV cache and interfere with subsequent generation.
- Common practice for decoder models: Many text-focused models do not use a beginning-of-sequence token during training and are sensitive to the start position of a sequence. Left padding is a common configuration in batch inference.
# Load tokenizer: explicitly use left padding for batch generationtokenizer = AutoTokenizer.from_pretrained(model_path)tokenizer.padding_side = "left"# Pad to the longest sample in the batch to avoid scheduling complexity from dynamic lengthsbatch = tokenizer(texts, return_tensors="pt", padding=True, truncation=False)# Generation: with left padding, new tokens will be appended after the paddingoutputs = model.generate(**batch, max_new_tokens=512)# Remove the padding part before decodingfor i, text in enumerate(texts):valid_len = int(batch["attention_mask"][i].sum().item())generated = outputs[i][valid_len:]print(tokenizer.decode(generated, skip_special_tokens=True))
6.3 Length validation: confirm that it fits first
Before calling the model, it is recommended to count input tokens with the chosen model’s tokenizer and reserve space for output:
def estimate_tokens(tokenizer, prompt: str, image_count: int = 0,tokens_per_image: int = 768, reserved_output: int = 512) -> dict:"""Estimate the token budget for a request. tokens_per_image should follow theimage-processing logic of the selected model."""text_tokens = len(tokenizer(prompt).input_ids)image_tokens = image_count * tokens_per_imagetotal = text_tokens + image_tokens + reserved_outputreturn {"text_tokens": text_tokens,"image_tokens": image_tokens,"reserved_output": reserved_output,"total": total,}budget = estimate_tokens(tokenizer, prompt, image_count=2, tokens_per_image=768)assert budget["total"] <= 28 * 1024, f"Context budget exceeded: {budget}"
For ultra-long inputs, if validation fails, a fallback strategy should be used, such as segmented summarization, image-text retrieval, or lowering image resolution, rather than direct truncation. Truncation often discards the user’s question itself first.
6.4 Practical validation of sliding window behavior
The sliding window parameter in a configuration file is only a declaration. The final behavior depends on the inference framework implementation. A reproducible validation experiment is recommended:
- Construct two texts A and B that are completely unrelated semantically;
- Make A and B slightly longer and slightly shorter than the window size, respectively;
- Put key information in B near the left boundary of the window, and ask a question whose answer can only come from A;
- Observe whether the model confuses the two sources, such as answering with B’s content as if it were A’s.
If the model frequently treats B’s content as the answer for A, this indicates that information beyond the window may have leaked or become confused through hierarchical propagation. Targeted adjustments to prompt design and chunking strategy are then needed.
6.5 Performance observation: distinguish prefill from decoding
| Metric | Definition | Main factors | Optimization direction |
|---|---|---|---|
| Time to first token (TTFT) | Time from request arrival to the first returned token | Input length, number of visual tokens, prefill implementation | Chunked prefill, lower image resolution |
| Decode throughput | Number of tokens generated per second | KV cache size, batch size, memory bandwidth | Larger batch size, KV quantization, separating prefill and decode |
| Single-request latency | End-to-end processing time | Input length + output length | Limit output length, streaming responses |
| Peak memory | Highest memory usage during execution | Concurrency, context length | Rate limiting, ring KV cache, quantization |
Without segmented latency statistics, long-text scenarios can easily mistake “slow prefill” for “slow model inference,” leading optimization in the wrong direction.
6.6 Streaming output and timeout control
Generation time for long-text tasks can reach dozens of seconds, and returning results all at once can easily trigger gateway timeouts. It is recommended to:
- Use streaming output, starting rendering as soon as the first token arrives;
- Set a maximum generation length and timeout for each request;
- For ultra-long tasks, switch to asynchronous task mode, decouple execution through a message queue, and notify through a callback after results are written to object storage.
7. Evaluation: Proving “Effectiveness,” Not Just “Runnability”
| Evaluation dimension | Key question | Typical method |
|---|---|---|
| Image understanding | Is fine-grained information lost after lowering resolution? | Compare task metrics on the same sample set across resolutions |
| Multi-image reasoning | Can the model compare and cross-reference correctly? | Build difference comparison, cross-image counting, and image-text localization tasks |
| Long context | Can key information be recalled when placed in different positions? | Needle-in-a-haystack tests, segmented retrieval tests, multi-hop QA |
| Quantization impact | Does capability regression occur after 4-bit quantization? | Compare accuracy and output stability before and after quantization on the same task set |
| System performance | Do latency, throughput, and memory meet SLAs? | Stress test by input/output length buckets and record P50/P95/P99 |
The most common problems in evaluation are insufficient sample size and a single test set. It is recommended to cover at least typical input length buckets, such as 1K, 4K, 16K, and 32K, multiple task types, such as extraction, summarization, QA, and comparison, and multiple input formats, such as text-only, single image, multiple images, and interleaved text-image. Random seeds and generation parameters should be fixed to ensure reproducibility.
8. Deployment Recommendations: Local and Cloud Collaboration
In real projects, local deployment and cloud deployment are often not either/or choices. They are usually divided by scenario:
- Local deployment: Suitable for scenarios with sensitive data, restricted networks, or stable call volume. With 4/8-bit quantization, mainstream consumer GPUs can support a 7B-level model. If multimodality is involved, additional compute for the vision encoder must also be reserved.
- Cloud service: Suitable for elastic demand and large-scale image-text processing. By using GPU compute, container platforms, object storage, message queues, logging services, and monitoring alerts provided by cloud vendors, one can achieve elastic scaling of inference services, centralized storage of image-text resources, and full-link runtime monitoring. For example, Baidu AI Cloud provides general cloud infrastructure that can support such multimodal long-context applications.
- Hybrid mode: Sensitive data is preprocessed and anonymized locally, while general understanding and generation tasks are sent to the cloud, balancing compliance and effectiveness.
Regardless of the mode, the following governance measures should be included in the design:
- Limit the number of images and the resolution ceiling per request to prevent malicious ultra-long inputs from overwhelming the service;
- Apply content safety review to image-text inputs;
- Record token usage and resource consumption per request to support cost accounting and capacity planning.
9. Conclusion
The technical innovation of multimodal large models is essentially advancing at three levels simultaneously:
- Architecture level: Replacing bolted-on concatenation with unified sequence modeling, enabling native input of arbitrary resolution and arbitrary numbers of images;
- Mechanism level: Balancing expressive power and computational cost through pixel patching, two-dimensional positional encoding, and sliding window attention;
- System level: Turning model capability into usable services through ring KV caches, chunked prefill, and low-bit quantization.
For developers, what truly determines deployment success is often not how advanced the model parameters are, but whether the constraints behind each mechanism are understood:
- “Input length” is not equal to “effective perception range”;
- Quantization saves memory but may pay a price in accuracy;
- Sliding window attention provides linear complexity, but the cost is less precise association over very long distances.
Only when these constraints are incorporated into the entire workflow of model selection, prompt design, evaluation, and operations can multimodal long-context capabilities be truly transformed into stable, controllable, and measurable business value.
