Mixture of Experts Multimodal LLMs: Architecture Principles and Engineering Practices

    This article explores the architecture principles and engineering practices of mid-sized Mixture of Experts (MoE) multimodal large models. It covers MoE routing mechanisms, resource estimation for total versus activated parameters, multimodal input processing, long context memory costs, function calling workflows, benchmark interpretation, and a comprehensive deployment checklist for production environments.

    1. Background: Why Focus on Mid-Sized Mixture of Experts Models

    The capability of large models generally correlates positively with parameter size, but scaling up parameters simultaneously increases memory footprint and inference costs. Dense models utilize all parameters during every forward pass, meaning larger models inherently require more computation per inference. For teams needing to balance performance, latency, and deployment costs, this linear relationship is often unsustainable.

    Mixture of Experts (MoE) models offer an alternative approach. The model contains multiple “expert” sub-networks, but each input token is routed to only a few of them for computation. Consequently, the model’s knowledge capacity is borne by all experts collectively, while the computational cost per inference is tied only to the few activated experts.

    Mid-sized MoE multimodal models have gained attention recently because they address two goals simultaneously: the total parameter count is sufficient to cover a broad range of knowledge and capabilities, while the activated parameters are small enough to run on a single machine or a few accelerator cards. This article uses such models as an example to discuss their architecture, capability boundaries, and engineering practices. Note that the model specifications and performance metrics mentioned are for reference only; always refer to the official documentation provided by the model publisher.

    2. Basic Principles of the Mixture of Experts Architecture

    A typical MoE layer consists of two components:

    1. Router: Takes the hidden vector of the current token and outputs a score for each expert.
    2. Experts: Usually independent Feed-Forward Networks (FFNs) with identical structures but different parameters.

    The router generally employs a Top-k strategy, retaining only the top k highest-scoring experts. It renormalizes their scores and performs a weighted sum of the expert outputs. The following code demonstrates this process using pure Python without third-party dependencies:

    1. import math
    2. def softmax(xs):
    3. m = max(xs)
    4. exps = [math.exp(x - m) for x in xs]
    5. total = sum(exps)
    6. return [e / total for e in exps]
    7. def top_k_route(logits, k=2):
    8. probs = softmax(logits)
    9. ranked = sorted(range(len(probs)), key=lambda i: probs[i], reverse=True)[:k]
    10. norm = sum(probs[i] for i in ranked)
    11. return [(i, probs[i] / norm) for i in ranked]
    12. # Assume 8 experts and the following router logits for the current token
    13. router_logits = [0.1, 2.3, -0.5, 1.7, 0.0, -1.2, 0.8, 0.3]
    14. print(top_k_route(router_logits, k=2))
    15. # Output selected expert indices and their weights, e.g., [(1, ...), (3, ...)]

    When training MoE models, two additional issues require attention:

    • Load Balancing: If the router consistently favors a few experts, the remaining experts will be under-trained, wasting model capacity. A common practice is to add auxiliary terms to the loss function to encourage an even distribution of tokens across all experts.
    • Capacity Limits: In distributed training, the computational capacity of each expert usually has an upper bound. Tokens exceeding this capacity may be dropped or handled by fallback strategies, which can affect training stability and requires hyperparameter tuning.

    Understanding these points helps explain why MoE models can exhibit stronger capabilities with the same number of activated parameters, while also explaining why they are more complex to train and schedule than dense models.

    3. Total vs. Activated Parameters: Estimating Resources Correctly

    When reviewing the specifications of an MoE model, the most common misconception is conflating “total parameters” with “activated parameters.”

    • Total parameters determine the storage requirements for the model weights. All expert parameters must reside in GPU or CPU memory so the router can select any expert for any given token.
    • Activated parameters determine the primary computational cost per step, affecting the processing time and throughput per token.

    Using the reference specifications as an example, the total parameter count is roughly 25.2B, while the activated parameter count is about 3.8B. Weight storage can be estimated as follows:

    1. def weight_memory_gb(num_params_billion, bytes_per_param):
    2. return num_params_billion * bytes_per_param # Billion params × bytes per param ≈ GB
    3. print("bf16 (2 bytes/param):", weight_memory_gb(25.2, 2), "GB") # ~50.4 GB
    4. print("INT4 (0.5 bytes/param):", weight_memory_gb(25.2, 0.5), "GB") # ~12.6 GB

    This estimate covers only the weights themselves. Actual deployment requires additional space for activations, framework runtime, and concurrent request caches. It is generally recommended to reserve an extra 20% to 40% buffer, depending on batch size and sequence length.

    This leads to an important conclusion: An MoE model’s memory pressure is comparable to a dense model with the same total parameter count, but its per-token computation speed is closer to a dense model with an equivalent number of activated parameters. This characteristic makes it suitable for scenarios requiring “high knowledge capacity and fast response,” but it does not mean it can be run freely on devices with minimal memory.

    4. Engineering Multimodal Inputs

    Models that support both text and image inputs typically convert images into a set of visual tokens internally, which are then fed into the language backbone alongside text tokens. The standard workflow is as follows:

    1. Image Preprocessing: Scaling, cropping, and normalizing the image to the model’s required resolution.
    2. Visual Encoding: The visual encoder divides the image into patches and outputs feature vectors.
    3. Projection Alignment: A small projection layer maps the visual features to the same dimensionality as text tokens.
    4. Input Concatenation: Visual tokens and text tokens are concatenated according to a template and processed uniformly by the language model.

    In engineering practice, image resolution directly dictates the number of visual tokens. Higher resolutions yield more detail but increase context usage and computation. For tasks like receipt recognition or UI screenshot understanding, testing at medium resolution first is advisable. For large-area scenes or scanned documents, you may need to split them into sub-images based on precision requirements.

    Cost evaluation for multimodal requests must include image tokens in the total count, not just text length. Many production incidents stem from underestimating the latency and cost fluctuations introduced by image inputs.

    5. Long Context Capabilities and Memory Costs

    Reference materials indicate that this class of models can support a context window of up to approximately 256K tokens. Long context allows the model to process long documents, extensive codebases, or lengthy multi-turn conversations in a single pass, but it also imposes significant memory requirements.

    During inference, the model must cache the keys and values (KV Cache) of historical tokens for each layer. This footprint grows linearly with sequence length and can be estimated using the following formula:

    1. def kv_cache_gb(layers, kv_heads, head_dim, seq_len, bytes_per_elem=2):
    2. total_bytes = 2 * layers * kv_heads * head_dim * seq_len * bytes_per_elem
    3. return total_bytes / 1e9
    4. # The following are assumed structural parameters for demonstration only
    5. print(round(kv_cache_gb(layers=48, kv_heads=8, head_dim=128, seq_len=256_000), 1), "GB")

    As shown, even if the weights fit comfortably in memory, a single ultra-long request can monopolize a massive amount of cache space. Therefore, long-context services typically require the following measures:

    • Limit the maximum input length per request and provide clear warnings at the gateway layer.
    • Use chunking, retrieval, or summarization for long documents before feeding them into the context, rather than stuffing everything in at once.
    • Schedule requests in buckets based on length to prevent short requests from being blocked by long ones.

    Long context does not equate to “remembering everything.” The model’s utilization of information in the middle of the context window may be lower than at the beginning or end. It is best to place critical information near the start or end of the input and verify performance through actual tasks.

    6. Reasoning, Code Generation, and Function Calling

    These models typically feature built-in reasoning, code generation, and function calling capabilities. In business systems, function calling is the capability that most easily generates engineering value, but it is also the one requiring the most constraints.

    The basic workflow for function calling is: developers describe available tools in a structured way, the model decides whether to call a tool based on user intent, outputs parameters in the correct format, the application executes the actual operation, and the results are returned to the model. Tool descriptions can use the standard JSON Schema format:

    1. {
    2. "name": "get_order_status",
    3. "description": "Query the current status of an order by order ID",
    4. "parameters": {
    5. "type": "object",
    6. "properties": {
    7. "order_id": {"type": "string", "description": "Order ID consisting of letters and numbers"}
    8. },
    9. "required": ["order_id"]
    10. }
    11. }

    Parameters generated by the model should not be trusted blindly; the application layer must validate them:

    1. def validate_args(args, required, allowed_keys):
    2. if not isinstance(args, dict):
    3. raise ValueError("Args must be an object")
    4. missing = [k for k in required if k not in args]
    5. if missing:
    6. raise ValueError(f"Missing required parameters: {missing}")
    7. unknown = [k for k in args if k not in allowed_keys]
    8. if unknown:
    9. raise ValueError(f"Unknown parameters detected: {unknown}")
    10. return args
    11. args = validate_args({"order_id": "A1001"}, required=["order_id"], allowed_keys=["order_id"])

    At this layer, the following issues should also be addressed:

    • For operations with side effects, such as payments, order modifications, or deletions, require manual confirmation or secondary validation. Do not let the model execute these directly.
    • Treat the content returned by tools as data, not instructions, to prevent malicious text from inducing the model to make unauthorized tool calls.
    • Log the inputs, outputs, and duration of each tool call for traceability and auditing.

    Code generation capabilities are well-suited for assisting with boilerplate code, explaining existing code, and generating test cases. Generated code must pass compilation, unit testing, and code review before entering production.

    7. How to Interpret Benchmark Results

    When models are released, they often come with various benchmark scores covering knowledge QA, mathematical reasoning, coding, and more. When reading these numbers, keep the following in mind:

    • Test Conditions: Whether tool calling was allowed, whether chain-of-thought reasoning was used, and the sampling parameters. The same model can score very differently under different conditions.
    • Data Contamination: Whether benchmark questions might have appeared in the training data. The training data cutoff date is an important clue for assessing contamination risk.
    • Task Matching: There is a gap between public benchmarks and business tasks. For scenarios like customer service QA, contract clause extraction, or ticket classification, you should construct your own evaluation sets.
    • Confidence Intervals: Score differences on small test sets might just be random noise and should not be over-interpreted.

    A prudent approach is to establish a three-tier evaluation system: general capability spot-checks, business task metrics, and online real-traffic feedback. Every time you switch models or adjust prompts, re-run them on the same dataset and record changes in latency, cost, and quality.

    8. Deployment Checklist

    Before deploying an MoE multimodal model to production, you can verify the following items:

    1. Resource Planning

    • Define weight precision and memory budget clearly, reserving buffers for cache and concurrency.
    • Estimate throughput based on peak concurrency and average output length, not just single-request latency.

    2. Performance Optimization

    • Evaluate the impact of low-precision quantization on quality to balance precision and memory.
    • Enable general scheduling techniques like Continuous Batching to improve hardware utilization.
    • Monitor Time To First Token (TTFT) and Tokens Per Second (TPS), setting separate targets for interactive experiences and batch tasks.

    3. Security and Compliance

    • Apply length limits, sensitive content filtering, and basic prompt injection detection to user inputs.
    • Perform structural validation on outputs to prevent format errors from breaking downstream systems.
    • Read the model’s licensing terms carefully to ensure requirements for commercial use, redistribution, and data usage are met.

    4. Operations and Rollback

    • Maintain unified version records for model versions, prompt templates, and evaluation results.
    • Retain the capability to serve the previous version so you can switch back quickly if quality degrades.
    • Set up cost alerts to prevent sudden spikes caused by long-context or multimodal requests.

    9. Conclusion

    The Mixture of Experts architecture uses sparse activation to achieve higher knowledge capacity and lower per-step computation, at the cost of larger weight storage and more complex scheduling. Multimodal inputs, long context, and function calling expand the application boundaries but also introduce new challenges in memory, security, and evaluation.

    When selecting a model, it is recommended to clarify your business metrics and resource constraints first, and establish a rigorous evaluation and deployment process to ensure stable, secure, and cost-effective production operations.