Mixture of Experts (MoE) Large Language Models: Architecture and Long-Context Engineering in Practice

    This article explains how Mixture of Experts (MoE) architecture works in large language models and what it means for engineering teams. It covers sparse activation and top-K routing, total versus active parameters, training stability issues, KV cache memory costs for long contexts, requirements for AI coding tasks, inference performance metrics, deployment options, and practical steps for evaluation and governance.

    1. Background: Why Mixture of Experts Matters

    Over the past two years, gains in large language model capabilities have mainly come from scaling up parameters and training data. A dense model runs all of its parameters for every inference step, so a larger model needs more compute and memory for each token. This makes inference costs hard for many businesses to afford.

    Mixture of Experts (MoE) offers another path. It splits the feed-forward network into several “expert” sub-networks, and each input token activates only a few of them. The total parameter count can be very large, while only a fraction of the parameters take part in each forward pass. For users, this means a better balance between knowledge capacity and the cost of each inference.

    For developers, understanding this architecture has three practical uses. It helps you read model specifications correctly, estimate the memory and bandwidth needed for deployment, and judge how the model performs in long-context, code generation, and multi-step tool calling scenarios.

    2. Core Principles of Mixture of Experts

    2.1 Dense and Sparse Models

    In a dense model, the feed-forward network in each layer uses the same set of weights for every token. In a sparse model, each layer contains several sets of expert weights. A gating network, called the router, decides which experts to call based on each token’s hidden state.

    The main differences between the two types are:

    • Dense model: total parameters equal the parameters used in each computation, so compute cost scales roughly linearly with parameter count.
    • Sparse model: total parameters are much larger than the parameters activated per token, so compute cost depends mainly on the active parameters.

    A sparse model does not reduce the total amount of parameter memory. All expert weights must still be loaded into GPU memory or system memory. The savings are mainly in compute.

    2.2 Gating Routing and Top-K Selection

    The gating network is usually a linear layer followed by a normalization function. For each token, it outputs a score for each expert, keeps the K experts with the highest scores, and renormalizes the weights of those K experts.

    The following code shows the basic logic of this process. It is for illustration only.

    1. import numpy as np
    2. def softmax(x):
    3. e = np.exp(x - x.max(axis=-1, keepdims=True))
    4. return e / e.sum(axis=-1, keepdims=True)
    5. def top_k_route(hidden, router_w, k=2):
    6. # hidden: [tokens, hidden_dim]
    7. # router_w: [hidden_dim, num_experts]
    8. logits = hidden @ router_w
    9. probs = softmax(logits)
    10. topk_idx = np.argsort(-probs, axis=-1)[:, :k]
    11. topk_p = np.take_along_axis(probs, topk_idx, axis=-1)
    12. topk_p = topk_p / topk_p.sum(axis=-1, keepdims=True)
    13. return topk_idx, topk_p

    The routing result determines which experts each token is sent to and how their outputs are weighted. In real implementations, tokens must also be grouped by expert and processed in batches. This step has a large effect on communication and memory access efficiency.

    2.3 Total Parameters and Active Parameters

    When reading a model specification, distinguish two metrics:

    • Total parameters: the number of all trainable weights in the model. They determine model capacity and storage requirements.
    • Active parameters: the number of weights actually used in the forward pass for a single token. They determine compute cost and the theoretical latency of one inference.

    A smaller ratio between the two means higher sparsity. However, a smaller ratio is not always better. When sparsity is too high, routing decisions become harder, the risk of unstable training rises, and load across experts is more likely to become unbalanced.

    3. Training Stability Challenges

    Sparse model training commonly faces three types of problems.

    The first is load imbalance. If the router keeps sending most tokens to a few experts, those experts become overloaded while the others receive almost no training. Common remedies include adding a load-balancing term to the loss function or setting a capacity limit during routing.

    The second is numerical instability. In large-scale training, attention scores can reach very large values. These values can overflow the softmax computation, causing loss spikes and even training divergence. Common mitigations include normalizing query and key vectors, clipping attention logits, and using more stable optimizer settings.

    The third is routing degradation. Late in training, routing patterns may become fixed, and functional overlap between experts increases. Regularly monitoring each expert’s activation frequency and output similarity helps detect this problem early.

    Users of a model usually do not see these training details directly, but they show up in the model’s stability and consistency. When you evaluate a model, do not look only at the quality of a single response. Also observe how much results vary across multiple runs of the same task.

    4. Long-Context Design and Memory Cost

    4.1 Converting Context Length to Document Size

    The context window is measured in tokens. The relationship between tokens and words depends on the tokenizer. For Chinese text, one character typically corresponds to about one to two tokens. English words are often split into subword pieces. Any estimate of how much text fits in a window is therefore approximate. For a formal evaluation, count tokens with the tokenizer of the target model.

    4.2 KV Cache Memory Overhead

    The main memory consumption in long-context inference comes from the KV cache. For every generated token, the model stores key and value vectors for every layer. Cache size grows in proportion to sequence length. The approximate formula is:

    KV cache bytes ≈ 2 × layers × KV heads × head dimension × sequence length × bytes per element × batch size

    Take a hypothetical configuration with 60 layers, 8 KV heads, a head dimension of 128, a sequence length of 131,072 (about 128K), half precision (2 bytes per element), and batch size 1. Substituting these values gives a KV cache of about 30 GiB. This figure does not include model weights or intermediate activations.

    This result shows that the cost of long-context capability appears mainly in memory capacity and memory bandwidth. When planning deployment, base memory estimates on concurrency, average context length, and maximum context length together.

    4.3 Engineering Strategies for Long Context

    For tasks involving long documents and code repositories, common strategies include:

    • Chunked retrieval: index the document in chunks first, then place only the relevant segments in the context.
    • Rolling summaries: in long conversations, periodically compress history and keep key facts and constraints.
    • On-demand loading: inject a full file into the context only when it is needed, so unrelated content does not take up window space.

    These strategies are usually more economical than simply enlarging the context window. They also make output quality easier to control.

    5. Requirements for AI Coding

    Coding assistance is one of the typical applications of large language models. These tasks usually involve several steps: understanding the requirement, locating code, modifying multiple files, running tests, and iterating based on error messages. A model needs the following abilities:

    1. Code understanding: read source code in different languages and understand dependencies between modules.
    2. Multi-file editing: keep interfaces consistent across files, and avoid changing only one place in a way that causes compile failures.
    3. Tool calling: call tools to read and write files, run commands, and query documentation, following the agreed format.
    4. Multi-round self-correction: locate problems from test output instead of repeating the same faulty change.

    When evaluating these abilities, design a task set that is close to real workflows. For example, give the model a small repository with a bug, then ask it to locate the problem, submit a patch, and pass the tests. Code completion scores alone rarely reflect performance on such complex tasks.

    6. Inference Metrics and Deployment

    6.1 Key Performance Metrics

    When evaluating an inference service, consider these metrics:

    • Time to first token (TTFT): the time from sending a request to receiving the first token. It affects how responsive the interaction feels.
    • Output speed: the number of tokens generated per second during the generation phase. It determines how long a long answer takes