Mixture of Experts in Practice: Scaling, Post-Training, and Customization for Open-Source LLMs

    This article provides a practical walkthrough of Mixture-of-Experts (MoE) architecture for large language models, covering how sparse activation enables cost-effective scaling, how to structure pre-training and reinforcement learning in the post-training phase, the engineering requirements for long-horizon agentic tasks, and how to fine-tune an MoE model with proprietary data for custom deployment scenarios.

    Open-Source LLMs Enter a High-Frequency Iteration Cycle

    Over the past year or two, both the open-source community and research institutions have been steadily releasing large language models with hundreds of billions of parameters. Model capabilities are improving at an accelerated pace, and the number of viable models available within any given timeframe has grown significantly. When selecting a model, teams now need to evaluate architecture characteristics, training methodologies, deployment costs, and license terms against their specific use cases—benchmark rankings alone are no longer sufficient.

    This article focuses on the Mixture-of-Experts (MoE) architecture and addresses four practical questions: how this model family scales under constrained compute budgets, how reinforcement learning can be organized during the post-training phase, what engineering safeguards are needed for long-running autonomous agent tasks, and how to customize an MoE model with proprietary data through fine-tuning.

    Fundamentals of the Mixture-of-Experts Architecture

    In conventional dense models, every parameter participates in computation during each forward pass. As parameter count increases, so does the computational cost per token. The Mixture-of-Experts (MoE) architecture decomposes the feed-forward network into multiple “expert” sub-networks and relies on a router to activate only a small subset of experts per token.

    This design introduces two distinct metrics that are often conflated:

    • Total parameter count: The sum of all expert and shared-layer parameters. This determines storage footprint and the model’s knowledge capacity.
    • Active parameter count: The number of parameters actually involved in computation for a single token. This determines the per-step inference cost.

    An MoE model’s per-step inference compute can be substantially lower than that of a dense model with the same total parameter count. However, GPU memory requirements are still dictated by the total parameter count, since all experts must remain resident in memory—they are simply not all activated simultaneously. Deployment planning must therefore account for memory capacity, memory bandwidth, and inter-card communication overhead.

    Take a configuration with 64 experts where 4 are selected per token: each token only uses about 6.25% of the expert parameters. The core routing logic can be illustrated with the following pseudocode:

    1. # Pseudocode: select the top-k scoring experts for each token
    2. logits = hidden * router_weight # one score per expert
    3. probs = softmax(logits)
    4. top_idx, top_probs = topk(probs, k) # select top-k experts and their weights
    5. top_probs = top_probs / sum(top_probs) # normalize so selected weights sum to 1
    6. output = sum(top_probs[i] * expert[top_idx[i]](hidden) for i in range(k))

    If the router tends to favor a small subset of experts, the remaining experts receive almost no training signal. To counter this, a load-balancing auxiliary loss is typically added during training to regularize the call distribution across experts. This constraint can sometimes conflict with the language modeling objective, and the weighting coefficient needs to be tuned empirically.

    Designing a Multi-Stage Pre-Training Pipeline

    Large-scale pre-training rarely runs on a single homogeneous dataset from start to finish. Instead, the process is typically organized into distinct phases:

    1. General phase: Uses large volumes of text and code from diverse sources to establish foundational language and knowledge capabilities.
    2. Capability enhancement phase: Increases the proportion of code, mathematical, and scientific text, adjusting the data mixing ratios.
    3. Long-context phase: Progressively extends the training sequence length so the model adapts to long documents and long multi-turn conversations.
    4. Annealing phase: Finalizes training with a lower learning rate on high-quality data to stabilize the final model.

    The critical factor between phases is the interplay between data mixing ratios and the learning rate schedule. Switching too aggressively can cause previously acquired capabilities to regress; being too slow limits the headroom for subsequent phases. Each phase should have its own independent validation set to monitor for unintended degradation, and the scheduling strategy—including when to adjust learning rates relative to data mix changes—needs to be planned in advance.

    An additional design consideration is the input tokenizer. Many MoE models continue to use byte-level BPE tokenizers; for non-English languages, the vocabulary compression rate may be less favorable. Some recent models have added a top-level language gating mechanism on top of a shared vocabulary: expert selection can be partially biased toward experts that specialize in certain languages. This differs from the load-balancing auxiliary loss mentioned above, which only encourages balanced usage globally. The specialization-based gating approach allows the model to form implicit linguistic specialization among experts without violating the overall load-balancing objective.

    Reinforcement Learning: RM Training and Reward Modeling

    After pre-training and supervised fine-tuning (SFT), reinforcement learning is used to align the model with human preferences. A common approach is to train a reward model (RM) that scores model outputs, then use an optimization algorithm to maximize the expected reward.

    For reward model training, the typical data format is pairwise comparison: a prompt is paired with two responses, and annotators indicate which one is preferable. This produces a binary ranking label. The reward model is trained to maximize the score difference between the preferred response and the rejected response—in other words, the model must learn to assign a clearly higher score to the better sample.

    A key practical consideration is that reward values must be normalized through a sigmoid function. In loss calculations, the preference label for chosen/dischosen pairs can be encoded as a constant difference, allowing the loss to be expressed as a mean binary cross-entropy term. In practice, some implementations convert the chosen/rejected label into a floating-point target (e.g., 1.0 for chosen, 0.0 for rejected) and compute cross-entropy directly. The other head outputs in the reward model, if any, are typically not used in reward computation.

    Another detail worth noting: some models add a special token to the beginning or end of the response before feeding it into the reward model, helping it produce a distinct score for the “whole response” rather than a per-position score that is later pooled.

    When applying the trained reward model to reinforcement learning, a common problem is reward hacking—the policy model finds shortcuts that satisfy the reward model without genuinely improving output quality. To mitigate this, several mechanisms are used simultaneously:

    • KL penalty: Constraining the deviation between the current policy and the reference policy to prevent excessive drift.
    • Reward normalization: Adjusting reward distributions across different task types so they are comparable during combined training.
    • Reward scaling: In some RL algorithms, reward values are clipped or standardized to maintain stability during policy updates.

    Deploying Long-Horizon Agentic Tasks: Engineering Considerations

    MoE models are increasingly used for agentic tasks that require autonomous execution over long periods—parse requests, call tools, process results, and iteratively adjust. These scenarios place distinct demands on both the model and the serving infrastructure.

    Inference Latency and KV Cache Optimization

    Long-horizon tasks typically involve several rounds of reasoning and tool calls. Each round uses a long chain-of-thought (CoT) process, which means the model must repeatedly reason through context that grows as conversation history accumulates. The key challenge is that during the “thinking” phase, decoding latency is directly affected by sequence length—the longer the generated text, the longer the user waits.

    To reduce this, several techniques are applied:

    • Pre-computation and reuse: Shared prompt prefixes and tool-call templates can be pre-computed and their key-value (KV) caches reused.
    • KV cache quantization: Activating quantization for the KV cache reduces memory bandwidth pressure and speeds up decoding, at some cost to precision.
    • Multi-token prediction: Predicting multiple tokens in parallel is effective when there are strong dependencies in the generated text. This is particularly beneficial for deterministic content such as code fragments from tool outputs or structured JSON processing.

    Multi-Agent Concurrency and Memory Management

    In scenarios where multiple agent instances run concurrently, total GPU memory consumption grows in proportion to the number of tokens in all processes. Each agent’s KV cache competes for the same GPU memory pool. The serving framework must support flexible memory management—such as paged attention, which allocates and reclaims KV cache in fixed-size blocks rather than reserving contiguous memory. This improves memory utilization and reduces fragmentation.

    For MoE models, another consideration is that only a subset of experts is active at each decoding step, so GPU utilization can be uneven. The number of experts activated per token scales linearly with batch size; a practical rule of thumb for batch size selection is to ensure the number of active experts per token is in the range of approximately 10 to 15 percent of the router’s total routing choices. This keeps the load balanced enough for stable throughput without overloading the all-to-all communication between GPUs.

    Reliability in Long-Running Tasks

    Once a task runs for hours, a single numerical anomaly (NaN/Inf) in the middle of the process can waste hours of compute. Several practical safeguards are needed:

    • Periodic state persistence: Intermediate states, including generated results and KV caches (or a compact representation of them), should be periodically serialized and saved, so the task can resume from a checkpoint rather than restarting.
    • Automatic anomaly detection: The serving layer should monitor for divergence in hidden states or loss metrics, automatically roll back the generation to the last safe checkpoint, and restart from there.
    • Structured output verification: For multi-stage tasks, the output of each stage should be validated against a predefined format—parsing JSON, matching tool-call schemas, etc.—before the next stage begins.

    Terminology and Implementation Notes

    In current serving frameworks, the terms “prefill” and “decode” are used respectively for the precomputation phase and the token-generation phase. In “decode-only” or “generation-only” execution modes, the model receives only incremental token IDs for the new tokens and does not re-process the entire context each time. A prefill operation is triggered only when new context is introduced. This distinction is important for optimizing both latency and throughput in long-running tasks.

    To support concurrent generation of multiple reasoning paths from a single prompt, some frameworks implement “parallel sampling,” where multiple decoding branches run against the same shared prefix. This can be implemented by duplicating the KV cache of the shared prefix—each sample branch maintains its own extension of the cache, and when the shared prefix’s cache is no longer needed, it is released.

    For large-scale inter-node communication (typically via InfiniBand with RDMA), the load on the network can vary as different batches of experts are activated. If the transport layer supports it, overlapping the all-to-all expert communication with the computation of the next layer (such as the attention layer) can hide network latency under compute time.

    SFT and Knowledge Distillation for Customization

    For domain-specific deployments, teams often need to train a customized model rather than use a general-purpose one. The common path is supervised fine-tuning (SFT) on domain-specific instruction data, often combined with knowledge distillation from a larger teacher model.

    Distillation Setup

    A typical approach is to deploy a powerful teacher model (e.g., a cloud-hosted API model) and use it to generate responses for the target dataset. Each sample consists of a prompt and a teacher-generated response. A key step is post-hoc filtering: remove low-quality samples by checking for empty responses, repeated patterns, or irrelevant output. For numeric or code verification tasks, rerun the code or verify the output against the expected schema.

    For MoE models, it’s important to note that during SFT, the load-balancing auxiliary loss is usually retained to prevent router collapse. The two objectives—fitting the target distribution and maintaining balanced expert utilization—need to be jointly managed.

    Reflection-Based Data Generation

    In some pipelines, a “reflection” pass is inserted after the teacher model generates an initial answer. The model is asked to critique its own response, then regenerate a revised answer based on the critique. This iterative approach produces fine-grained positive and negative examples that are useful for training the student model to recognize its own errors.

    For instance, a multi-step prompting template can be applied where the system prompt instructs the model to first draft an answer, then review it for correctness and completeness, and finally produce a revised answer only after the review pass. However, this method increases token consumption significantly—each sample requires multiple completions. The additional cost is only justified if the downstream task benefits from the improved data quality.

    Instruction Data Composition

    When constructing the instruction tuning dataset, several categories are commonly included:

    • Multi-turn dialogue: Preserves natural conversational flow and context switching.
    • Single-turn structured generation: tasks such as JSON extraction and translation.
    • Complex reasoning: Multi-step problem solving that requires the model to decompose the task, plan steps, and produce an intermediate result before the final answer.

    In multi-turn dialogue, the model is trained on sequences of past exchanges and must only produce the response for the current turn. During training, the loss for the prompt portion is typically masked out so the model is not penalized for failing to predict the user’s input.

    Summary

    The MoE architecture offers a practical path to scaling model capacity without a proportional increase in inference compute, making it well suited for the current open-source model landscape. Deployment requires careful attention to memory planning, router load balancing, and serving-engine capabilities. Post-training with RL and reward models can further align the model with downstream tasks, while SFT and distillation from a stronger teacher model remain effective routes to domain customization. For teams choosing a model architecture in 2025, MoE is no longer a niche option—it is a mainstream design that demands deliberate engineering across the full model lifecycle.