Architecture Design and Implementation Practices for Mixture-of-Experts LLM Platforms

    This article discusses the architecture and engineering practices of a large language model platform built around mixture-of-experts (MoE) models. It covers the main constraints faced by LLM platforms, sparse expert activation and routing load balancing, multi-head latent attention for KV-cache compression, long-context inference with sparse attention and cache scheduling, FP8 mixed-precision training and multi-token prediction, multimodal preprocessing, API and on-premises deployment, compliance considerations, and a practical platform evaluation checklist.

    I. Background: What Problems Must an LLM Platform Solve?

    An LLM platform typically serves three types of scenarios at the same time: end-user conversational interaction, developer API access, and enterprise private deployment. Each scenario imposes different requirements on the platform.

    • Compute and VRAM pressure: As model parameter scale grows, the VRAM and computation required for a single inference pass increase, directly raising serving costs.
    • Long-context requirements: Tasks such as document analysis and codebase question answering require models to process tens of thousands of tokens or even longer contexts. Attention computation and cache occupancy become bottlenecks.
    • Multimodal input: Data from multiple modalities, such as images and text, must be uniformly encoded and preprocessed before it can enter the same model.
    • Cost and stability: The platform must balance throughput, latency, and unit cost while ensuring service availability under high concurrency.

    Once these constraints are understood, the core architectural question becomes clear: how to expand model capability under limited compute while keeping memory and computational overhead during inference under control.

    II. Mixture-of-Experts Architecture: Expanding Parameter Scale with Sparse Activation

    2.1 Basic Approach

    Mixture of Experts (MoE) splits the feed-forward network into multiple expert sub-networks. For each input token, a router computes scores and selects only the few experts with the highest scores to participate in computation. The total number of model parameters can be large, but only a small fraction of parameters actually participates in computation for each token.

    The following example calculation is illustrative only; the numbers are used to explain the principle. Assume the model has 600B total parameters and each token activates about 35B parameters, giving an activation ratio of about 6%. The forward computation per token is related to the activated parameters, so model capacity and inference cost can be partially decoupled.

    2.2 Routing and Load Balancing

    Routing design needs to solve two problems. First, which experts to select. Second, avoiding all tokens flooding to a few experts, which would overload some experts while leaving others idle.

    The traditional approach is to add an auxiliary loss term to the training loss that penalizes load imbalance. This is effective, but the auxiliary loss competes with the main task objective and may affect model quality. A common alternative is to maintain a bias term for each expert and use that bias only during expert selection. When an expert has a high load, lower its bias; when it has a low load, raise its bias. The bias does not participate in the final weighted output, so it interferes less with model expressiveness.

    1. import torch
    2. def topk_route(hidden, gate_weight, bias, k=8):
    3. # hidden: [tokens, d_model]
    4. # gate_weight: [n_experts, d_model]
    5. # bias: [n_experts], used only for expert selection
    6. logits = hidden @ gate_weight.T
    7. scores = torch.sigmoid(logits)
    8. # The bias only affects top-k selection, not the final weighting
    9. _, idx = torch.topk(logits + bias, k, dim=-1)
    10. weights = torch.gather(scores, -1, idx)
    11. weights = weights / weights.sum(dim=-1, keepdim=True)
    12. return idx, weights
    13. def update_bias(bias, expert_load, target_load, lr=1e-3):
    14. # Lower the bias for experts above target load; raise it for those below target load
    15. return bias - lr * torch.sign(expert_load - target_load)

    2.3 Engineering Considerations

    • Expert parallelism requires cross-device communication. All-to-all communication is often the main overhead in both training and inference, and latency needs to be hidden by overlapping communication with computation.
    • The number of experts and the size of each expert need to be designed jointly. Experts that are too small reduce the representational capacity of each expert, while experts that are too large increase VRAM occupancy.
    • During inference, a batch may mix multiple routing patterns. The serving side should monitor the actual load of each expert rather than relying only on statistics from the training phase.

    III. Multi-Head Latent Attention: Compressing the KV Cache

    3.1 Source of the Problem

    During autoregressive generation, the model needs to cache the Key and Value of historical tokens, i.e., the KV cache. Cache size is proportional to context length, number of layers, number of heads, and head dimension. When the context is long or there are many concurrent requests, the KV cache can exhaust VRAM before compute capacity is exhausted.

    3.2 Compression Approach

    The core idea of Multi-head Latent Attention (MLA) is to first project Key and Value into a low-dimensional latent vector and cache only this latent vector. When computing attention, the required Key and Value are reconstructed through up-projection matrices.

    The following example calculation ignores the position-encoding-related parts:

    • In standard multi-head attention, the number of bytes that need to be cached per layer per token is: 2 × number of heads × head dimension × bytes per element.
    • If the number of heads is 32, the head dimension is 128, and FP16 is used (2 bytes per element), then the result is 2 × 32 × 128 × 2 = 16384 bytes, or about 16 KB.
    • If the compressed latent dimension is 512, then each layer caches about 512 × 2 = 1024 bytes per token, or about 1 KB.

    The cache is compressed by about 16×. The cost is additional up-projection computation during inference, so this approach essentially trades computation for VRAM.

    3.3 Deployment Recommendations

    • The compression dimension is a key hyperparameter. Over-compression loses attention quality, while under-compression yields limited benefit. It should be determined jointly using perplexity on a validation set and downstream task metrics.
    • The up-projection can be fused with attention computation to reduce additional memory reads and writes.
    • The serving side should monitor both VRAM usage and per-token latency to confirm that the compute-for-VRAM tradeoff actually delivers a net benefit on the target hardware.

    IV. Long-Context Inference: Sparse Attention and Cache Management

    4.1 Sparse Attention

    The computational complexity of full attention grows quadratically with sequence length. Sparse attention lets each query attend to only a subset of key-value blocks. Common combinations include:

    • Sliding window: Keep the most recent tokens to maintain local context coherence.
    • Block-level compression: Compress historical sequences into summary representations by block to obtain a coarse-grained view of global information.
    • Content selection: Select a small number of key blocks for fine-grained computation based on the relevance between the query and the blocks.

    The speedup from such methods depends on context length, hardware, and the specific implementation. Documentation should not present fixed speedup multiples detached from the scenario. First-token latency and overall throughput should be measured on the actual workload.

    4.2 Cache and Scheduling During Inference

    • Chunked prefill: Split long prompts into chunks and process them step by step to avoid a single long request blocking other requests.
    • Prefix caching: When multiple requests share the same system prompt or document prefix, reuse the already computed KV cache.
    • Request scheduling: Group and batch requests by sequence length to reduce wasted computation caused by padding.

    V. Low-Precision Training and Training Objective Design

    5.1 FP8 Mixed Precision

    FP8 mixed-precision training stores the inputs and weights of most matrix multiplications as 8-bit floating-point numbers to reduce VRAM usage and improve compute throughput. Implementation需要注意: (Implementation notes:)

    • Use block-wise or group-wise quantization, with an independent scaling factor for each block, to avoid overflow or underflow caused by insufficient numerical range.
    • Keep accumulation operations at higher precision, usually FP32, to ensure numerical stability.
    • Layers sensitive to gradients, such as normalization layers and output layers, can retain higher precision.

    The benefit of low-precision training depends on hardware support. If the hardware does not natively support FP8, the effect may be limited and must be evaluated separately.

    5.2 Multi-Token Prediction

    A standard language model predicts only the next token at each step. Multi-Token Prediction additionally requires the model to predict multiple subsequent tokens at the same position and uses these prediction losses as auxiliary objectives.

    This design has two practical values: first, it provides a denser training signal for the model; second, it provides draft predictions for speculative decoding during inference. When using it, note that additional prediction heads increase training overhead, and the benefit should be measured against downstream task performance.

    VI. Engineering Essentials for Multimodal Data Processing

    The key to a multimodal platform is a unified preprocessing pipeline. A typical flow includes:

    1. Input validation: Check file format, size, and content safety.
    2. Modality encoding: Images are converted into visual tokens by a vision encoder, and text is converted into text tokens by a tokenizer.
    3. Alignment and concatenation: Organize the multimodal sequence according to the format used during model training to ensure consistent position information.
    4. Caching and reuse: Compute hashes for repeatedly uploaded images or documents to avoid redundant encoding.

    The preprocessing stage should be decoupled from model serving, and message queues or task queues should be used for long-running encoding tasks to prevent blocking online inference.

    VII. Access Methods: API, Chat Interface, and Local Deployment

    7.1 API Access

    Most platforms provide HTTP interfaces compatible with common industry chat completion formats. When integrating, note the following:

    • Read keys from environment variables or a secret management service; do not write them into code or logs.
    • Set reasonable timeouts and use exponential backoff retries for 429 and 5xx errors.
    • Streaming output can reduce the user-perceived first-token latency and is suitable for conversational applications.
    1. import os
    2. import requests
    3. API_URL = "https://api.example.com/v1/chat/completions" # Placeholder URL; replace with the actual service address
    4. API_KEY = os.environ["MODEL_API_KEY"]
    5. def ask(prompt: str, model: str = "your-model-id") -> str:
    6. headers = {
    7. "Authorization": f"Bearer {API_KEY}",
    8. "Content-Type": "application/json",
    9. }
    10. payload = {
    11. "model": model,
    12. "messages": [{"role": "user", "content": prompt}],
    13. "temperature": 0.7,
    14. "max_tokens": 512,
    15. }
    16. resp = requests.post(API_URL, json=payload, headers=headers, timeout=30)
    17. resp.raise_for_status()
    18. return resp.json()["choices"][0]["message"]["content"]

    7.2 Local Deployment

    Local deployment is suitable for scenarios with strict requirements on data residency, network isolation, or latency. The following assessments need to be completed before deployment:

    • Hardware planning: Estimate VRAM based on model parameter count, quantization method, and target concurrency. The KV cache grows with concurrency and context length, so separate space should be reserved for it.
    • Quantization scheme: Weight quantization can reduce VRAM usage but introduces some accuracy loss, which needs regression testing on business data.
    • Inference engine: Choose a mature engine that supports continuous batching, paged KV cache, and tensor parallelism, and conduct stress tests on the target hardware.
    • Operations monitoring: Collect throughput, first-token latency, VRAM utilization, and error rate, and set alert thresholds.

    7.3 Compliance Requirements for Industry Applications

    For examples such as medical imaging analysis and traditional Chinese medicine (TCM) health management, model output should be positioned as auxiliary reference and should not replace clinical judgment. Data processing must comply with relevant regulations, patient information should be de-identified before entering the model, and access logs should be retained for auditing.

    VIII. Selection and Evaluation Checklist

    When selecting or evaluating an LLM platform, check the following dimensions one by one:

    Dimension Focus Verification Method
    Model capability Accuracy on target tasks, long-context performance Build a business evaluation set and compare with a fixed random seed
    Inference performance First-token latency, throughput, concurrency limit Stress test using a real request distribution
    Cost Cost per request, share of VRAM and compute Estimate monthly cost based on actual call volume
    Data security Data retention, transport encryption, access control Check terms of service and security configuration
    Integration complexity — —