Multimodal Visual Reasoning in Large Models: Technical Paths and Engineering Practices
This article examines why large models need image understanding, how multimodal architectures and Mixture-of-Experts support visual reasoning, and how visual-token compression controls cost. It also covers visual primitives in reasoning chains, agent scenarios, evaluation, latency, security, deployment, and technology selection for production multimodal systems.
1. Background: Why Large Models Need to Understand Images
Early large language models processed only text. In real business systems, much information exists as screenshots, charts, scanned documents, and PDFs with layout. If a model cannot read these images, it cannot complete report analysis, UI operations, document review, and similar tasks.
The goal of multimodal capability is to let the same model handle text and images within the same inference framework. There are two direct benefits. First, the information source is more complete, and the model does not need manual transcription of image content. Second, the reasoning pipeline is shorter; standalone modules such as OCR, layout analysis, and chart parsing can be merged or simplified.
Multimodal capability also introduces new costs. Images are converted into many visual tokens, which increases inference cost, latency, and memory usage. Engineering therefore needs to address both “can it understand” and “can it run at acceptable cost and speed.”
2. Basic Architecture of Multimodal Models
Current mainstream multimodal models usually consist of three parts.
- Visual encoder: splits an image into fixed-size patches and encodes each patch into a vector sequence.
- Modality connector: maps visual vectors into the embedding space of the language model. Common implementations include linear projection, multilayer perceptrons, and resampling modules with a fixed number of query vectors.
- Language model backbone: concatenates visual tokens and text tokens into one sequence and models them autoregressively.
Training is generally divided into two stages. The first is image-text alignment pretraining, which usually freezes the language model and trains only the connector so that visual vectors align with text semantics. The second is instruction fine-tuning, which uses question answering, captioning, reasoning, and other samples to train the model to follow user instructions. If the alignment stage is skipped and fine-tuning is done directly, a common problem is that the model can describe the general idea but struggles to read numbers and small text accurately.
3. Role of Mixture-of-Experts Architecture in Multimodal Models
Mixture of Experts (MoE) splits feed-forward layers into multiple expert subnetworks. A router selects a small number of experts for each token. The total parameter count can be large, but only the activated parameters participate in computation at each step.
For multimodal models, this structure has two benefits. First, image token counts are usually much larger than text token counts, and the expert structure can expand model capacity without proportionally increasing computation. Second, different types of visual content, such as natural images, tables, and text-dense screenshots, may be handled by different experts.
Implementation needs to address load balancing. If most tokens are routed to a few experts, training becomes unstable, and some devices may be overloaded during inference. Common practices include adding a load-balancing term to the training loss and monitoring expert activation ratios during inference.
The following is illustrative code for the routing process:
def route_tokens(hidden_states, router, top_k=2):"""Select the top_k experts with the highest scores for each token and normalize the weights (illustrative)."""logits = router(hidden_states) # Shape: [number of tokens, number of experts]probs = softmax(logits)weights, expert_ids = topk(probs, top_k)weights = weights / weights.sum(dim=-1, keepdim=True)return expert_ids, weights
4. Visual Token Compression: A Core Method for Cost Control
The higher the image resolution, the more visual tokens are produced. Self-attention computation scales with the square of sequence length, so token count directly determines inference latency. For a 1024×1024 image, if the patch size is 14 pixels, an uncompressed image produces more than 5,000 visual tokens.
Common compression methods include the following categories.
- Adjacent patch merging: merges adjacent 2×2 or larger visual vectors into one, reducing token count in proportion to the merged area.
- Fixed-length resampling: uses a set of learnable query vectors to extract a fixed-length representation from a large number of visual features, suitable for length-sensitive scenarios.
- Dynamic resolution tiling: splits the image into sub-images according to aspect ratio and adds a thumbnail to retain global information. Resolution can be adjusted according to task needs.
- Region cropping: first locates regions relevant to the question, then performs high-resolution encoding only on those regions.
The following is illustrative code for estimating visual token count:
import mathdef estimate_visual_tokens(width, height, patch=14, merge=2):"""Estimate the number of visual tokens after patching and merging (illustrative)."""cols = math.ceil(width / patch)rows = math.ceil(height / patch)tokens = cols * rowsreturn tokens // (merge * merge) # Each merge×merge region is merged into one token
Compression loses detail. Small text, dense tables, and fine-line charts are most affected. Therefore, the compression ratio should be determined together with evaluation results, not based on cost metrics alone.
5. Visual Primitives and Reasoning Chains
Traditional multimodal answers often provide only conclusions, making it difficult to check whether the model actually read the correct image regions. One direction worth attention is to write visual primitives—referenceable visual units such as bounding boxes, point coordinates, and local crops—directly into the reasoning chain. During reasoning, the model explicitly points to evidence locations instead of only giving descriptions.
This approach usually brings three benefits.
- Verifiability: each reasoning step corresponds to a specific region, making it easier for humans or programs to check.
- Less speculation: the model must locate evidence before drawing a conclusion, which is more stable for counting, spatial relationships, and numerical reading.
- Composability: region coordinates can serve as input for the next operation, such as cropping followed by high-precision recognition.
An illustrative reasoning record is as follows:
Thought: The bar chart in the upper right contains two data series.Localization: Region [0.62, 0.10, 0.95, 0.48]; read the vertical axis scale.Conclusion: In the sample data, the second series has higher values than the first.
In engineering, the representation of visual primitives must be consistent with the training data. If coordinate format, normalization method, and region granularity differ between training and inference, the model may output plausible-looking but incorrectly located results.
6. Multimodal Applications in Agent Scenarios
Agent tasks require a model to work in a loop of “observe, decide, execute,” and multimodal capability is the observation part. Typical scenarios include the following.
- Screenshot understanding and UI operation: the model reads a screen capture, outputs click coordinates or operation instructions, and an external executor performs the action and returns a new screenshot.
- Chart parsing: reads axes, legends, and data labels, and converts charts into structured data for downstream computation.
- Document processing: performs layout analysis, table reconstruction, and formula recognition, and outputs editable structured content.
The basic structure of an agent loop is as follows:
def run_visual_agent(task, env, model, max_steps=20):history = []for step in range(max_steps):screenshot = env.capture()action = model.decide(task=task, image=screenshot, history=history)if action.type == "finish":return action.resultenv.execute(action) # Validate coordinate ranges and operation permissions before executionhistory.append((step, action))raise TimeoutError("Maximum steps exceeded without completing the task")
Execution must have boundaries. For irreversible operations such as deletion, submission, and payment, human confirmation should be required. The external executor should only allow access to whitelisted applications and pages.
7. Engineering Implementation Considerations
7.1 Evaluation System
A single end-to-end accuracy metric cannot locate problems. It is advisable to build evaluation metrics by layer.
- Text recognition layer: character accuracy, with emphasis on small-font and low-resolution samples.
- Structure understanding layer: table cell reconstruction rate and chart value error.
- Task layer: end-to-end task success rate and average number of steps.
Evaluation sets should include difficult samples such as dense tables, blurred screenshots, and multilingual mixed-layout images. Evaluating only on clear samples can easily overestimate model performance in real business settings.
7.2 Cost and Latency
- Estimate visual token count at the request entry point; if it exceeds the limit, reduce resolution or crop regions first.
- Set different resolution levels by task tier. Simple classification tasks do not need high resolution.
- Cache repeated requests for the same image to avoid repeated encoding.
- Measure time to first token and generation latency separately to identify whether the bottleneck is in encoding or generation.
7.3 Security and Privacy
Screenshots often contain personal information, accounts, and internal data. Deployment should ensure the following.
- Encrypt data in transit and set explicit retention periods for storage.
- Redact data before writing logs to avoid long-term retention of original images.
- Text in images may contain instructions that attempt to change model behavior. The system should treat such content as data to be processed, not as operation instructions to execute.
7.4 Deployment Architecture
Original images are usually stored in object storage, and inference services run on a container platform. Logging services and monitoring alerts track latency, error rate, and resource usage. When deploying on a cloud platform, teams can combine general-purpose cloud services in these categories to build the architecture.
8. Technology Selection Recommendations
Three common approaches appear in real projects, and they should be compared across the following dimensions.
- Directly calling a multimodal model API: fastest development and low maintenance cost, but weaker control over output format and the reasoning process.
- Self-built approach with a visual encoder plus language model: strongest controllability and can be fine-tuned on business data, but requires training resources and ongoing maintenance.
- Pipeline approach with optical character recognition plus layout parsing: clear structure and each stage can be debugged separately, but cross-module errors accumulate and complex images that require holistic understanding are difficult to handle.
Selection should prioritize task accuracy requirements, data sensitivity, budget limits, and the team’s maintenance capability. First run a baseline with a small evaluation set, then decide whether to invest in customized development.
