Efficient Inference Practices for Mixture of Experts Multimodal Models
This article explores the efficient inference practices of a Mixture of Experts (MoE) multimodal model. It covers MoE architecture principles, key specifications, multimodal capabilities, benchmark interpretation, and VRAM resource estimation. Additionally, it provides practical engineering implementations, including code examples for multimodal requests and function calling, alongside guidance on model selection and risk control for real-world deployment.
I. Background: Why Sparse Activation is Gaining Attention
The capabilities of large language models generally scale with parameter size, but inference costs rise accordingly. Dense models require activating all parameters for every generated token, making both memory footprint and computational load directly proportional to the total parameter count. For scenarios requiring online services, edge devices, or consumer-grade GPUs, this overhead is often prohibitive.
The Mixture of Experts (MoE) architecture offers an alternative. The model contains a vast number of parameters, but each token only passes through a small subset of them. Consequently, the computation required for a single inference is determined by the active parameters rather than the total parameters. This approach allows developers to balance high model capacity with lower per-inference compute costs.
This article uses a multimodal model featuring an MoE structure that supports both text and image inputs as an example. It illustrates its design essentials, capability scope, and engineering implementation methods.
II. Basic Principles of the MoE Architecture
2.1 Experts, Routing, and Shared Experts
An MoE layer typically consists of three components:
- Expert Networks: Multiple structurally identical feedforward subnetworks, where each expert learns different patterns.
- Router: Calculates matching scores between the current token’s hidden representation and each expert, selecting the top-scoring experts.
- Shared Expert: An expert that is always active for all tokens, used to handle universal base transformations and reduce redundant learning among other experts.
The router only activates the selected experts; the remaining experts do not participate in that computation step. Therefore, the total number of experts can be very large while keeping the actual computation per step manageable.
2.2 Total Parameters vs. Active Parameters
Distinguishing these two concepts is crucial for evaluating model performance:
- Total Parameters: The count of all weights in the model, determining the storage size and the memory required to load the model.
- Active Parameters: The number of weights actually involved in computation when processing a single token, primarily determining computational latency and throughput.
In MoE models, total parameters are typically much larger than active parameters. However, the storage overhead does not decrease because all expert weights must reside in memory during inference, even though only a portion is read during computation. This is often overlooked during hardware selection.
2.3 Comparison with Dense Models
All parameters in a dense model participate in every computation step. Assuming identical total parameters, the MoE model’s per-step computation is significantly lower, resulting in faster generation speeds. However, its storage requirements are comparable to a same-sized dense model, and the routing logic and load balancing among experts increase engineering complexity.
III. Key Specifications
The following specifications are derived from original materials; actual deployment should refer to officially released technical documentation.
- Parameter Scale: Total parameters ~25.2B, active parameters per token ~3.8B.
- Architecture Configuration: 30 layers total, attention uses a 1024-token sliding window. Each layer’s expert configuration consists of 8 active experts, 128 total experts, and 1 shared expert.
- Context Length: Supports up to 256K tokens.
- Input Modalities: Supports text and image, including interleaved text and image inputs.
- Output Modality: Outputs text.
- Training Data Cutoff: January 2025.
- Licensing: Uses a permissive open-source license allowing commercial use and redistribution, subject to the specific terms of the license text.
Sliding window attention limits each token’s attention range to nearby tokens, reducing computational load over long sequences. This directly aids in supporting a 256K context, but it also means distant information must be transmitted layer by layer, potentially affecting retrieval accuracy, which is discussed later.
IV. Multimodal Capabilities and Typical Scenarios
The model’s multimodal capabilities cover the following task categories:
- General Image Understanding: Recognizing image content and answering questions related to the visual.
- Object Detection and Referring: Locating objects in an image based on natural language descriptions.
- Document and PDF Parsing: Reading layout structures, tables, and paragraphs to convert document content into structured text.
- Screen and UI Understanding: Recognizing controls, text, and layouts in screenshots, useful for automated testing and preliminary analysis of assisted operations.
- Chart Understanding: Reading axes, legends, and data points to answer trend or value-related questions.
- OCR and Handwriting Recognition: Recognizing printed and handwritten text.
Interleaved input means that a single request can mix multiple text segments and multiple images—for example, providing an explanation first, then two comparison screenshots, and finally asking a question. This input method aligns closer with real-world business document formats than single-image Q&A.
Regarding multilingual support, the model natively supports over 35 languages out of the box, with pretraining data covering over 140 languages. For cross-lingual document processing, you can directly ask questions in the target language, but output quality for minor languages should be validated separately on business data.
V. How to Interpret Benchmark Scores
The original materials list multiple benchmark results. The following explains them by capability category, along with the original scores.
| Capability Category | Benchmark Direction | Original Score |
|---|---|---|
| Comprehensive Knowledge | Multidisciplinary Knowledge | 82.6% |
| Math Reasoning | Competition-level Math (no tools) | 88.3% |
| Code Generation | Real-time Coding Problems | 77.1% |
| Coding Competitions | Programming Competition Rating | 1718 |
| Science QA | Graduate-level Science Questions | 82.3% |
| Multilingual Knowledge | Multilingual Comprehensive Benchmark | 86.3% |
| Visual Reasoning | Multidisciplinary Image-Text Questions | 73.8% |
| Visual Math | Graph and Math Questions | 82.4% |
| Long Context Retrieval | Needle in a Haystack (128K, avg) | 44.1% |
Three points should be noted when reading these benchmark scores:
First, different benchmarks have varying question types, scoring rules, and operating conditions. Scores can only be compared under the same metrics. Direct numerical comparisons across different benchmarks are meaningless.
Second, the long-context retrieval score is notably lower than other items. This indicates that while the model supports ultra-long inputs, it does not mean every piece of information within an ultra-long input can be accurately retrieved. If business logic relies on precise localization in long documents, you should design chunking, retrieval, or reference validation mechanisms rather than relying entirely on a single-pass input.
Third, the scores are provided by the original materials and represent results from specific benchmarking environments. Before going live, you should validate using real samples from your own business, especially covering edge cases and scenarios with high error costs.
VI. Inference Resource Estimation
Resource estimation is the most practical aspect of model selection. The following estimates VRAM usage based on weight storage precision, calculating only model weights, excluding activations, KV cache, and runtime overhead.
- 16-bit float: 25.2B × 16 bit ÷ 8 ≈ 50.4 GB
- 8-bit integer: 25.2B × 8 bit ÷ 8 ≈ 25.2 GB
- 4-bit integer: 25.2B × 4 bit ÷ 8 ≈ 12.6 GB
Regarding computation, the forward computation per token correlates with active parameters, so the single-step compute cost can be estimated based on 3.8B. This means that on the same hardware, its decoding speed is typically significantly faster than a dense model with the same total parameters.
Long context also introduces additional KV cache overhead. The cache size depends on context length, number of layers, attention head configuration, and precision. When the context approaches 256K, the cache may exceed the footprint of the weights themselves, so concurrency and context length must be planned together.
The following script can be used to roughly estimate weight footprint at different precisions:
def estimate_weight_memory_gb(total_params_b: float, bits: int) -> float:"""Estimate VRAM for model weights (GB), excluding cache and runtime overhead."""bytes_per_param = bits / 8return total_params_b * bytes_per_param # Billion params × bytes ≈ GBfor bits in (16, 8, 4):gb = estimate_weight_memory_gb(25.2, bits)print(f"{bits}-bit weights require approx {gb:.1f} GB")
VII. Engineering Practices: Multimodal Requests and Function Calling
The following examples demonstrate two common use cases: mixed text and image input, and having the model output structured function calls. The examples only illustrate data organization methods; specific API endpoints, authentication, and field names should follow the documentation of the inference service you are using.
7.1 Constructing Mixed Text and Image Messages
import base64from pathlib import Pathdef build_multimodal_message(question: str, image_path: str) -> dict:"""Combine a text question and a local image into a user message."""image_bytes = Path(image_path).read_bytes()image_b64 = base64.b64encode(image_bytes).decode("utf-8")return {"role": "user","content": [{"type": "text", "text": question},{"type": "image", "mime_type": "image/png", "data": image_b64},],}message = build_multimodal_message(question="In this table, which region has the highest sales in the third quarter?",image_path="sales_table.png",)
In practice, pay attention to image size and format. Oversized images increase token consumption and latency; it is recommended to compress them appropriately while maintaining text clarity.
7.2 Defining Function Calls
Function calling allows the model to output a structured request that meets parameter constraints based on user intent, which is then executed by the program to perform the actual business logic. When defining, try to clearly specify descriptions and parameter constraints.
tools = [{"name": "query_inventory","description": "Query current inventory quantity by product code, returns an integer.","parameters": {"type": "object","properties": {"sku": {"type": "string","description": "Product code, consisting of letters and numbers.",},},"required": ["sku"],},}]
The calling process usually involves four steps: the model outputs the function name and parameters; the program validates the parameter types and value ranges; the program executes the actual query; the result is fed back to the model to generate the final answer. The validation step cannot be omitted because the parameters output by the model may still not meet business constraints, especially when user input is ambiguous.
VIII. Model Selection and Risk Control
8.1 Suitable Scenarios
- Services that need to process both text and images simultaneously and are sensitive to single-inference latency.
- Text-and-image-centric tasks such as document parsing, UI understanding, and chart Q&A.
- Long-document assisted reading, but requiring integration with retrieval and reference mechanisms.
- Teams needing local deployment or private operations with limited hardware budgets.
8.2 Scenarios Requiring Caution
- Tasks requiring exact verbatim retrieval of information from ultra-long contexts should add retrieval and validation steps.
- Businesses requiring very high output quality in minor languages need separate evaluation.
- High-risk decisions, such as medical, legal, or financial judgments, should treat model output as auxiliary only and must be reviewed by humans.
8.3 Pre-launch Validation Checklist
- Build an evaluation set using real business samples, covering common and edge cases.
- Measure time-to-first-token and continuous generation speed separately to ensure service metrics are met under target concurrency.
- Test weight footprint according to your precision plan, and reserve space for the KV cache.
- Strictly validate function call parameters and log failed samples.
- Establish a sampling review mechanism for output content to continuously track quality changes.
IX. Key Takeaways
- The MoE architecture makes single-inference computation determined by active parameters, but storage still needs to accommodate the weights of all experts.
- This model has ~25.2B total parameters, ~3.8B active parameters per token, supports text and image inputs, and features a 256K context.
- Benchmark scores must be compared under the same metrics; the long-context retrieval score indicates that ultra-long inputs require complementary retrieval mechanisms.
- When selecting a model, estimate weight VRAM, KV cache, and concurrency requirements simultaneously, rather than looking only at active parameters.
- Key engineering practices involve validating data, validating function call parameters, and establishing continuous quality monitoring.
