{
  "id": "moe-architectures",
  "module": "llm-core",
  "level": 3,
  "minutes": 40,
  "audiences": [
    "researcher"
  ],
  "software": [],
  "text": {
    "en": {
      "title": "MoE and New Architectures: Sparse Experts, Load Balancing, State Space Models, Linear Attention and Hybrids",
      "description": "A systematic account of two ways of reworking the Transformer. The first replaces the feed-forward layer with a mixture of experts (MoE): sparse gating, top-k routing, load-balancing losses, the capacity factor, fine-grained and shared experts, auxiliary-loss-free balancing and expert parallelism, with total and active parameters computed from the official configs of Mixtral, Qwen3 and DeepSeek-V3. The second replaces some or all attention layers: S4, Mamba and Mamba-2, linear attention, RWKV, RetNet, Hyena, xLSTM and Gated DeltaNet, hybrids such as Jamba and Qwen3-Next, and diffusion language models, with a runnable example.",
      "updated": "2026-11-15",
      "takeaways": [
        "MoE replaces the feed-forward layer with several experts and a router, and each token passes through only a few experts, decoupling total parameters from compute per token. From the official config.json files, Mixtral 8x7B has 46.7B parameters with 12.9B active per token, Qwen3-235B-A22B has 235B / 22B and DeepSeek-V3 671B / about 37B; experts account for more than 95% of all parameters.",
        "Load balancing is the central problem in training MoE. Switch Transformer uses the auxiliary loss α·N·Σfᵢ·Pᵢ (α = 0.01) with a capacity factor, skipping tokens that exceed capacity; DeepSeek-V3 instead gives each expert a bias that is used only for selection, not for weighting, and nudges it by 0.001 per step according to load, barely relying on an auxiliary loss and dropping no tokens in training or inference.",
        "DeepSeekMoE introduced fine-grained and shared experts: experts are cut smaller and more of them are activated, while always-active shared experts hold common knowledge. DeepSeek-V3 has 1 shared and 256 routed experts per layer and picks 8 per token; Qwen3’s MoE models pick 8 of 128 experts and have no shared expert.",
        "State space models and linear attention replace the KV cache, which grows with length, by a fixed-size recurrent state, so per-step compute and memory at inference do not depend on context length. Mamba makes the SSM parameters input-dependent (selective) and reports 5× the inference throughput of a Transformer of the same size; Gated DeltaNet combines gating with the delta update rule to overwrite memory precisely.",
        "Large-scale practice is now mostly hybrid: Jamba has one attention layer in every eight and needs 4GB of KV cache for a 256K context against 32GB for Mixtral; Qwen3-Next-80B-A3B uses Gated DeltaNet in three of every four layers and gated attention in the fourth, with 80B parameters in total and 3B active per token."
      ],
      "faq": [
        {
          "q": "Why does an MoE model save compute at inference but not memory?",
          "a": "Each token passes through only a few experts, so compute per token is close to that of a dense model with the same number of active parameters; but which expert will be chosen is not known in advance, so all expert weights must stay in memory or be quickly reachable. Mixtral 8x7B activates about 12.9B parameters per token while all 46.7B must be held in memory. MoE pays off most with large batches in which every expert gets enough tokens; with a single request and small batches, the bandwidth needed to read expert weights is often the bottleneck."
        },
        {
          "q": "Do experts really specialise by subject or domain?",
          "a": "Not necessarily. The Mixtral paper analysed expert assignments on subsets of The Pile and found the distributions for ArXiv, PubMed and PhilPapers text very similar, with no obvious topic specialisation; routing showed more syntactic regularities, for example ‘self’ in Python, ‘Question’ in English and code indentation often going to the same expert, and consecutive tokens often sharing an expert. DeepSeekMoE’s fine-grained and shared experts are designed precisely to make experts more specialised."
        },
        {
          "q": "Why does Mamba not need a KV cache at inference?",
          "a": "A Transformer attends to all previous tokens at each step, so it caches the keys and values of the whole history and the cache grows linearly with context. State space models such as Mamba compress the history into a fixed-size state; each step updates the state from the current input and reads out the output, and the state size does not depend on context length. The price is that history is compressed, so exact retrieval and copying over long distances are weaker than with attention, which is why hybrids keep a few attention layers."
        },
        {
          "q": "How are linear attention and Mamba related?",
          "a": "Both can be written as a matrix state that is updated recurrently and read out by a query. Katharopoulos et al. (2020) showed that once softmax is replaced by a kernel feature map, causal attention can be written as an RNN; the Mamba-2 paper went further with state space duality (SSD), showing that a class of structured SSMs and masked linear attention are two ways of writing the same computation, and used this to build a core layer 2–8× faster than Mamba’s. Gated DeltaNet improves the state update rule within this framework."
        },
        {
          "q": "Will diffusion language models replace autoregressive models?",
          "a": "There is no settled answer yet. LLaDA (2025) trained an 8B masked diffusion language model from scratch and reports in-context learning competitive with LLaMA3 8B and better results than GPT-4o on a reversal poem-completion task, suggesting that core LLM abilities do not necessarily depend on autoregression. Mainstream open and commercial models are still autoregressive Transformers, and the inference efficiency, long-form generation and tool use of diffusion language models are still being studied."
        }
      ],
      "sources": [
        {
          "title": "Shazeer et al. (2017), Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer",
          "url": "https://arxiv.org/abs/1701.06538"
        },
        {
          "title": "Lepikhin et al. (2020), GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding",
          "url": "https://arxiv.org/abs/2006.16668"
        },
        {
          "title": "Fedus, Zoph and Shazeer (2021), Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity",
          "url": "https://arxiv.org/abs/2101.03961"
        },
        {
          "title": "Zoph et al. (2022), ST-MoE: Designing Stable and Transferable Sparse Expert Models",
          "url": "https://arxiv.org/abs/2202.08906"
        },
        {
          "title": "Jiang et al. (2024), Mixtral of Experts",
          "url": "https://arxiv.org/abs/2401.04088"
        },
        {
          "title": "Dai et al. (2024), DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models",
          "url": "https://arxiv.org/abs/2401.06066"
        },
        {
          "title": "Wang et al. (2024), Auxiliary-Loss-Free Load Balancing Strategy for Mixture-of-Experts",
          "url": "https://arxiv.org/abs/2408.15664"
        },
        {
          "title": "DeepSeek-AI (2024), DeepSeek-V3 Technical Report",
          "url": "https://arxiv.org/abs/2412.19437"
        },
        {
          "title": "Qwen Team (2025), Qwen3 Technical Report",
          "url": "https://arxiv.org/abs/2505.09388"
        },
        {
          "title": "Gu, Goel and Ré (2021), Efficiently Modeling Long Sequences with Structured State Spaces",
          "url": "https://arxiv.org/abs/2111.00396"
        },
        {
          "title": "Gu and Dao (2023), Mamba: Linear-Time Sequence Modeling with Selective State Spaces",
          "url": "https://arxiv.org/abs/2312.00752"
        },
        {
          "title": "Dao and Gu (2024), Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality",
          "url": "https://arxiv.org/abs/2405.21060"
        },
        {
          "title": "Katharopoulos et al. (2020), Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention",
          "url": "https://arxiv.org/abs/2006.16236"
        },
        {
          "title": "Peng et al. (2023), RWKV: Reinventing RNNs for the Transformer Era",
          "url": "https://arxiv.org/abs/2305.13048"
        },
        {
          "title": "Sun et al. (2023), Retentive Network: A Successor to Transformer for Large Language Models",
          "url": "https://arxiv.org/abs/2307.08621"
        },
        {
          "title": "Poli et al. (2023), Hyena Hierarchy: Towards Larger Convolutional Language Models",
          "url": "https://arxiv.org/abs/2302.10866"
        },
        {
          "title": "Beck et al. (2024), xLSTM: Extended Long Short-Term Memory",
          "url": "https://arxiv.org/abs/2405.04517"
        },
        {
          "title": "Yang, Kautz and Hatamizadeh (2024), Gated Delta Networks: Improving Mamba2 with Delta Rule",
          "url": "https://arxiv.org/abs/2412.06464"
        },
        {
          "title": "Lieber et al. (2024), Jamba: A Hybrid Transformer-Mamba Language Model",
          "url": "https://arxiv.org/abs/2403.19887"
        },
        {
          "title": "Nie et al. (2025), Large Language Diffusion Models",
          "url": "https://arxiv.org/abs/2502.09992"
        },
        {
          "title": "Dehghani et al. (2018), Universal Transformers",
          "url": "https://arxiv.org/abs/1807.03819"
        },
        {
          "title": "Mixtral-8x7B-v0.1 official config.json",
          "url": "https://huggingface.co/mistralai/Mixtral-8x7B-v0.1/blob/main/config.json"
        },
        {
          "title": "Official Qwen model card: Qwen3-30B-A3B",
          "url": "https://huggingface.co/Qwen/Qwen3-30B-A3B"
        },
        {
          "title": "Official Qwen model card: Qwen3-Next-80B-A3B-Instruct",
          "url": "https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Instruct"
        },
        {
          "title": "DeepSeek-V3 official config.json",
          "url": "https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/config.json"
        },
        {
          "title": "Official AI21 model card: Jamba-v0.1",
          "url": "https://huggingface.co/ai21labs/Jamba-v0.1"
        },
        {
          "title": "Hugging Face blog: Mixture of Experts Explained",
          "url": "https://huggingface.co/blog/moe"
        },
        {
          "title": "Sasha Rush and Sidd Karamcheti: The Annotated S4",
          "url": "https://srush.github.io/annotated-s4/"
        },
        {
          "title": "Tri Dao’s blog: State Space Duality (Mamba-2) Part I",
          "url": "https://tridao.me/blog/2024/mamba2-part1-model/"
        },
        {
          "title": "state-spaces/mamba (official Mamba implementation)",
          "url": "https://github.com/state-spaces/mamba"
        },
        {
          "title": "fla-org/flash-linear-attention (Triton implementations of linear attention, Gated DeltaNet and more)",
          "url": "https://github.com/fla-org/flash-linear-attention"
        },
        {
          "title": "databricks/megablocks (MoE training library)",
          "url": "https://github.com/databricks/megablocks"
        }
      ],
      "url": "https://aimap.page/en/learn/llm-core/moe-architectures/",
      "markdown": "**Overview**: the previous lesson, [Modern LLM Architectures](/learn/llm-architectures), kept the overall Transformer structure and changed only normalisation, positional schemes and the organisation of attention heads. This lesson covers two larger changes. The first keeps attention and replaces the feed-forward layer with a **mixture of experts (MoE)**, decoupling total parameters from compute per token; Mixtral, the MoE versions of Qwen3 and DeepSeek-V3 belong here. The second replaces some or all attention layers with **state space models (SSMs)**, **linear attention** or their variants, swapping the KV cache that grows with context for a fixed-size recurrent state, and has led to **hybrid architectures** that interleave attention and recurrent layers. The lesson ends with a short look at diffusion language models and looped language models. Figures come from the cited papers, official model cards and config files, or the runnable example at the end.\n\nThis lesson belongs to the [MoE and New Architectures](/learn/unit/u43-moe-newarch) unit. Its prerequisite is [Modern LLM Architectures](/learn/llm-architectures); the KV cache and inference bandwidth are covered in [How LLMs Generate Text](/learn/llm-inference). Related algorithm cards: [sparsely-gated MoE](/learn/algorithms/sparse-moe), [GShard](/learn/algorithms/gshard), [Switch Transformer](/learn/algorithms/switch-transformer), [Mixtral](/learn/algorithms/mixtral), [DeepSeekMoE](/learn/algorithms/deepseek-moe), [auxiliary-loss-free load balancing](/learn/algorithms/aux-free-balancing), [S4](/learn/algorithms/s4), [Mamba](/learn/algorithms/mamba), [Mamba-2](/learn/algorithms/mamba2), [linear attention](/learn/algorithms/linear-attention), [RWKV](/learn/algorithms/rwkv), [RetNet](/learn/algorithms/retnet), [Hyena](/learn/algorithms/hyena), [xLSTM](/learn/algorithms/xlstm), [Gated DeltaNet](/learn/algorithms/gated-deltanet), [Jamba and hybrids](/learn/algorithms/jamba), [diffusion language models](/learn/algorithms/diffusion-lm) and [looped language models](/learn/algorithms/looped-lm).\n\n## The basic structure of MoE\n\nIn a dense Transformer every token passes through the same feed-forward layer (FFN). An MoE layer replaces it with N feed-forward networks of the same shape but with separate parameters (the experts), plus a router (also called the gating network). For an input x, the router scores every expert, keeps only the k highest, and the output is the weighted sum of those k experts’ outputs:\n\n> Routing probabilities p = softmax(W_r · x); select the k experts with the largest p, forming the set S\n> Output y = Σ_{i∈S} gᵢ · FFNᵢ(x), where gᵢ is pᵢ renormalised over S\n\nBecause each token goes through only k experts, compute is about that of k FFNs while the parameter count is that of N FFNs. Shazeer et al. (2017) validated the idea at scale on LSTM language models and machine translation: using noisy top-k gating, with MoE layers of up to 137 billion parameters, they increased model capacity by more than 1000× with only minor losses in computational efficiency.\n\n| Model | Experts / active per token | Shared experts | Total parameters | Active per token | Source |\n|---|---|---|---|---|---|\n| Switch-C (2021) | 2048 / 1 | none | 1.6T | — | Switch Transformer paper |\n| Mixtral 8x7B (2024) | 8 / 2 | none | 46.7B | 12.9B | paper and config.json |\n| Qwen3-30B-A3B (2025) | 128 / 8 | none | 30.5B | 3.3B | model card and config.json |\n| Qwen3-235B-A22B (2025) | 128 / 8 | none | 235B | 22B | technical report and config.json |\n| DeepSeek-V3 (2024) | 256 / 8 | 1 | 671B | 37B | technical report and config.json |\n| Qwen3-Next-80B-A3B (2025) | 512 / 10 | 1 | 80B | 3B | model card |\n\nCounting term by term from the official config files (part 1 of the example), Mixtral 8x7B has 46.7B parameters with 12.88B active per token; Qwen3-30B-A3B has 30.5B (29.9B without embedding and output layers), matching the 30.5B and 29.9B on its model card, with 3.35B active (3.3B on the card); DeepSeek-V3 has 671.0B with 37.55B active (671B and 37B in the technical report). In all four, experts hold more than 95% of the parameters, and the active fraction falls from 27.6% for Mixtral to 5.6% for DeepSeek-V3. The “8x7B” in Mixtral’s name does not mean 56B parameters: only the feed-forward layers are replicated eight times, while attention, embeddings and the rest are shared, which gives 46.7B in total.\n\nMoE saves compute, not memory: which expert will be chosen is not known in advance, so all expert weights must be available. MoE therefore pays off most in training and large-batch inference; for single-request inference each step must read the selected experts’ weights, and memory bandwidth remains the main bottleneck. Deployment trade-offs are covered in [LLM Serving Engines](/learn/serving-engines).\n\n## Routing and load balancing\n\nLeft unconstrained, the router tends to keep choosing a few experts: those experts train better, get chosen even more, and the rest barely train (routing collapse). With expert parallelism, experts sit on different devices and imbalance also lets the busiest device slow everything down. There are three main remedies.\n\n**Auxiliary losses.** Shazeer et al. (2017) used two auxiliary losses that push the importance (sum of gate weights) and the load of the experts towards uniform. GShard (Lepikhin et al., 2020) used top-2 gating in the encoder and decoder of a Transformer, adding expert capacity, group-level dispatching, an auxiliary loss and random routing (the token is dispatched to the second expert with a probability proportional to its gate weight), and trained a 600-billion-parameter multilingual translation model on 2048 TPU v3 cores in 4 days. Switch Transformer (Fedus et al., 2021) simplified routing to top-1 and wrote the auxiliary loss as:\n\n> Auxiliary loss = α · N · Σᵢ fᵢ · Pᵢ\n\nwhere fᵢ is the fraction of tokens in the batch dispatched to expert i (not differentiable), Pᵢ is the average router probability for expert i (differentiable) and N is the number of experts. Under uniform routing fᵢ = Pᵢ = 1/N and the loss equals α. The paper swept α from 10⁻¹ to 10⁻⁵ and settled on α = 10⁻². ST-MoE (Zoph et al., 2022) added the router z-loss, which penalises large logits entering the router, to improve training stability.\n\n**The capacity factor.** To keep computation shapes fixed, GShard and Switch Transformer give each expert a capacity:\n\n> Expert capacity = (tokens per batch / number of experts) × capacity factor\n\nTokens beyond capacity are skipped (dropped) at that layer and pass to the next layer only through the residual connection. A larger capacity factor drops fewer tokens but wastes more compute and communication. Switch Transformer reports drop rates typically below 1% in its setting. Part 2 of the example sets an artificial routing preference towards expert 0: with top-2 routing the busiest expert receives 2.64 times the mean load and the auxiliary loss is 1.650 (1.000 when uniform); with capacity factors of 1.0, 1.25 and 2.0, 29.0%, 22.3% and 8.0% of assignments are dropped. Later implementations such as the dropless MoE in [MegaBlocks](https://github.com/databricks/megablocks) handle expert batches of unequal size with block-sparse computation and no longer need a capacity factor.\n\n**Auxiliary-loss-free balancing.** Wang et al. (2024) note that an auxiliary loss introduces gradients that interfere with the main objective: too large a coefficient hurts quality, too small fails to balance. Their method gives each expert i a bias bᵢ used only when selecting the top k:\n\n> Selection: pick the k experts with the largest sᵢ + bᵢ; weighting: gate values still use the original score sᵢ\n> Update: after each step, subtract γ from bᵢ for overloaded experts and add γ for underloaded ones\n\nThe biases are updated only from the load of previous batches and take no part in back-propagation, so they create no interfering gradients and leak no information about future tokens in the current sequence. DeepSeek-V3 adopts this strategy, with a bias update speed γ of 0.001 for the first 14.3T tokens and 0 for the final 500B; it keeps a sequence-wise balance loss with a coefficient of only 0.0001 to prevent extreme imbalance within a single sequence. The technical report says that thanks to good load balance DeepSeek-V3 drops no tokens in training or inference. Part 3 of the example applies the same rule (γ = 0.001) to the skewed routing above: after 300 steps the busiest expert’s load falls from 2.63 to 1.02 times the mean. Qwen3’s MoE models instead use a global-batch load-balancing loss, measuring load over the whole global batch rather than each micro-batch, which the technical report says encourages expert specialisation.\n\n## Fine-grained experts, shared experts and expert parallelism\n\nDeepSeekMoE (Dai et al., 2024) proposed two structural changes:\n\n1. **Fine-grained expert segmentation**: keeping total parameters and compute fixed, each expert’s intermediate dimension is cut down and the number of experts increased, with more experts activated. Splitting each of N experts into m gives mN experts with mK activated per token, greatly increasing the number of possible expert combinations;\n2. **Shared expert isolation**: a few shared experts are always active for every token to hold common knowledge, reducing redundancy among routed experts.\n\nThe paper reports that DeepSeekMoE 2B matches GShard 2.9B, which has 1.5 times the expert parameters and compute, and that DeepSeekMoE 16B matches LLaMA2 7B with about 40% of the compute. Each MoE layer of DeepSeek-V3 has 1 shared expert and 256 routed experts with an intermediate dimension of 2048, and each token activates 8 routed experts; the first 3 layers remain dense FFNs. Routing scores use a sigmoid and are normalised over the selected experts. Qwen3’s MoE models also use fine-grained experts (8 of 128 active) but have no shared expert.\n\n**Expert parallelism** places different experts of the same layer on different GPUs: each token is sent to the devices holding its experts and the results are sent back, i.e. two all-to-all exchanges. Traffic grows with the number of active experts and of nodes crossed, so DeepSeek-V3 uses node-limited routing: each layer’s routed experts are spread evenly over 64 GPUs in 8 nodes, and each token goes to at most 4 nodes. The technical report estimates that at the same communication cost the number of experts per token could in principle grow from 8 to 13 (4 nodes × 3.2 experts per node). Other forms of parallelism are covered in [Distributed Training and Clusters](/learn/distributed-training).\n\n**What experts learn.** The Mixtral paper analysed expert assignments across subsets of The Pile and found the distributions for ArXiv papers, biomedical abstracts (PubMed) and philosophy papers (PhilPapers) very similar, with no obvious topic specialisation; only the synthetic DM Mathematics set differed slightly. Routing showed more syntactic regularities: `self` in Python, “Question” in English and code indentation often went to the same expert, and consecutive tokens often shared an expert.\n\n## State space models: from S4 to Mamba\n\nAttention compute grows quadratically with sequence length and the KV cache grows linearly at inference. State space models (SSMs), which come from control theory, summarise the history recurrently in a hidden state h:\n\n> Continuous form: h′(t) = A·h(t) + B·x(t), y(t) = C·h(t)\n> After discretisation with step Δ: hₜ = Ā·hₜ₋₁ + B̄·xₜ, yₜ = C·hₜ\n\nWhen A, B and C do not depend on the input (linear time-invariant, LTI), unrolling the recurrence gives yₜ = Σⱼ (C·Āʲ·B̄)·xₜ₋ⱼ: the output is the input convolved with a fixed kernel. Training can therefore compute the whole sequence in parallel as a convolution (via FFT), while inference generates step by step with the recurrence. Part 6 of the example confirms that the two algorithms differ by at most 1.4×10⁻¹⁴.\n\n**S4** (Gu et al., 2021) introduced a structured parameterisation of A and an efficient way to compute with it, letting SSMs model very long dependencies stably. The paper reports state-of-the-art results on every Long Range Arena task at the time and was the first model to solve the length-16384 Path-X task (88% accuracy); on image and language modelling it substantially closed the gap to Transformers while generating 60× faster.\n\n**Mamba** (Gu and Dao, 2023) argues that the weakness of LTI models is that they cannot decide what to remember or ignore based on content, which particularly hurts discrete data such as text. Mamba makes B, C and the step Δ functions of the current input (a selective SSM), so the model can propagate or forget information token by token. The price is that there is no longer a fixed convolution kernel, so the paper designs a hardware-aware parallel scan that runs the recurrence in GPU SRAM. Mamba blocks contain no attention and no separate MLP. The paper reports 5× the inference throughput of a Transformer of the same size, compute linear in sequence length and improving performance on sequences up to a million long; Mamba-3B outperforms Transformers of the same size and matches Transformers twice its size in pre-training and downstream evaluation.\n\n**Mamba-2** (Dao and Gu, 2024) introduces the state space duality (SSD) framework: once A is restricted to a scalar times the identity, the selective SSM is equivalent to a linear attention with a structured mask, so it can be computed either recurrently or block-wise with matrix multiplications that make better use of GPU matrix units. The paper reports a core layer 2–8× faster than Mamba’s selective scan.\n\n## Linear attention and its refinements\n\nStandard attention computes, for each query, a softmax(q·kⱼ)-weighted average. **Linear attention** (Katharopoulos et al., 2020) replaces the softmax similarity with an inner product of kernel feature maps φ(q)·φ(k) and uses the associativity of matrix multiplication to change the order of computation:\n\n> Output oₜ = φ(qₜ)ᵀ·Sₜ / φ(qₜ)ᵀ·zₜ, where Sₜ = Sₜ₋₁ + φ(kₜ)·vₜᵀ and zₜ = zₜ₋₁ + φ(kₜ)\n\nCausal attention thereby becomes an RNN with the matrix Sₜ as its state, and complexity falls from O(N²) to O(N). The paper reports performance similar to vanilla Transformers and up to 4000× faster autoregressive prediction on very long sequences. Part 5 of the example uses φ(x) = elu(x) + 1 and finds a maximum difference of 8.9×10⁻¹⁶ between the parallel and recurrent forms, with the state fixed at 32×32.\n\nThe simplest linear attention only accumulates; it neither forgets nor overwrites, and the state fills up with old information. Later work mainly improves the update rule:\n\n| Method | How the state is updated | Reported |\n|---|---|---|\n| RWKV (Peng et al., 2023) | linear attention with channel-wise time decay (WKV); parallel like a Transformer in training, recurrent like an RNN at inference | trained up to 14 billion parameters |\n| RetNet (Sun et al., 2023) | a “retention” mechanism with exponential decay, computable in parallel, recurrent and chunk-wise recurrent form | O(1) inference memory and latency |\n| Hyena (Poli et al., 2023) | no recurrent state; implicitly parameterised long convolutions interleaved with data-controlled gating | Transformer quality with 20% less training compute at length 2K; 100× faster than optimised attention at 64K |\n| xLSTM (Beck et al., 2024) | exponential gating; sLSTM with scalar memory, mLSTM with matrix memory and a covariance update, fully parallelisable | — |\n| Gated DeltaNet (Yang et al., 2024) | gating (global decay) plus the delta rule (precise overwrite by key) | beats Mamba2 and DeltaNet on language modelling, in-context retrieval, length extrapolation and other benchmarks |\n\nThe **delta rule** comes from the classic learning rule of Widrow et al. (1960): before writing a new key–value pair, read out what the key currently stores and write only the difference, Sₜ = Sₜ₋₁ + βₜ·(vₜ − Sₜ₋₁·kₜ)·kₜᵀ. Writing to the same key again then overwrites the old value instead of adding to it. Part 7 of the example writes v1 and then v2 under the same unit key: the delta-rule read-out is 1.9×10⁻¹⁵ from v2, whereas plain linear attention reads v1 + v2, at a distance of 8.13 from v2. The Gated DeltaNet paper argues that gating allows memory to be erased quickly and the delta rule allows it to be modified precisely, that the two are complementary, and builds hybrids that combine Gated DeltaNet layers with sliding-window attention or Mamba2 layers. Triton implementations of many of these layers are available in [flash-linear-attention](https://github.com/fla-org/flash-linear-attention).\n\n## Hybrid architectures\n\nPurely recurrent models compress all history into a fixed-size state, and are weaker than attention at exact retrieval and copying over long distances. Large-scale practice is therefore mostly **hybrid**: most layers use an SSM or linear attention and a few full-attention layers are kept.\n\n**Jamba** (Lieber et al., 2024) has 8 layers per Jamba block with an attention-to-Mamba ratio of 1:7, and applies MoE every other layer (2 of 16 experts). The released model has 52B parameters in total and 12B active, fits on a single 80GB GPU and supports a 256K context. The paper’s ablations show virtually no difference between ratios of 1:3 and 1:7, with 1:7 more compute-efficient. Table 1 of the paper gives the KV cache for a 256K context in 16 bits: 128GB for LLaMA-2 6.7B, 32GB for both Mistral 7.2B and Mixtral, and 4GB for Jamba. Part 8 of the example recomputes these from the official Jamba and Mixtral configs and gets the same 4 GiB and 32 GiB.\n\n**Qwen3-Next-80B-A3B** (2025): its model card gives the layout as 12 groups of “3 × (Gated DeltaNet → MoE) + 1 × (gated attention → MoE)”, 48 layers in all; the MoE part has 512 experts with 10 active per token plus 1 shared expert, 80B parameters in total with 3B active, and a native context of 262,144 tokens. From the config, the KV cache of the 12 attention layers at 256K is 6 GiB, and the recurrent state of the 36 Gated DeltaNet layers totals about 18.9 million elements regardless of context length. The model card says the base model outperforms Qwen3-32B-Base on downstream tasks at about 10% of its training cost, with about 10 times its inference throughput for contexts above 32K.\n\nMain considerations when choosing an architecture:\n\n| Aspect | Dense Transformer | MoE Transformer | SSM / linear attention | Hybrid |\n|---|---|---|---|---|\n| Compute per token | proportional to parameters | proportional to active parameters only | independent of context length | in between |\n| Inference memory | weights + KV cache growing with length | all expert weights + KV cache | weights + fixed state | small KV cache + fixed state |\n| Exact retrieval and copying | strong | strong | weaker | handled by the attention layers |\n| Engineering ecosystem | most mature | needs expert parallelism and load balancing | needs specialised kernels | must support both kinds of kernel |\n\n## Diffusion and looped language models\n\n**Diffusion language models** do not generate left to right. In LLaDA (Nie et al., 2025) the forward process masks tokens at random in a given proportion and the reverse process uses a Transformer to predict all masked positions at once, training on a bound on the likelihood. The paper trains an 8B LLaDA from scratch and reports in-context learning competitive with LLaMA3 8B, instruction following such as multi-turn dialogue after SFT, and better results than GPT-4o on a reversal poem-completion task, arguing that core LLM abilities do not necessarily depend on autoregressive modelling. The official implementation is [ML-GSAI/LLaDA](https://github.com/ML-GSAI/LLaDA).\n\n**Looped language models** run the same layers several times, trading “recurrence in depth” for more compute without more parameters. The idea goes back to the Universal Transformer (Dehghani et al., 2018), which applies the same Transformer block recurrently in depth with a dynamic per-position halting mechanism; the paper shows that under certain assumptions it is Turing-complete, and reports a 0.9 BLEU improvement over the Transformer on WMT14 English–German. Like the test-time compute scaling in [Reasoning Models](/learn/reasoning-models), it aims to let a model spend more computation when needed.\n\n## Runnable example\n\nThe code below was run on PyTorch 2.15 (CPU). It downloads the public `config.json` of six models from Hugging Face (no weights), takes a few seconds, and its output matches the figures in the text.\n\n```python\nimport json, math, urllib.request, torch\ntorch.manual_seed(0); torch.set_num_threads(3)\nGiB = 1024**3\ndef cfg(repo): return json.load(urllib.request.urlopen(f'https://huggingface.co/{repo}/resolve/main/config.json'))\n\n# 1) Total and active parameters from config.json\ndef gqa_attn(c):\n    h, H, KV = c['hidden_size'], c['num_attention_heads'], c['num_key_value_heads']\n    hd = c.get('head_dim') or h // H\n    return h*H*hd*2 + h*KV*hd*2 + (2*hd if 'Qwen' in c['architectures'][0] else 0)\ndef report(name, c, attn, n_exp, k, d_exp, n_shared=0, d_shared=0, dense_layers=0, d_dense=0):\n    h, L, V = c['hidden_size'], c['num_hidden_layers'], c['vocab_size']\n    expert = 3*h*d_exp                      # SwiGLU expert: three matrices\n    moe_tot = n_exp*expert + n_shared*3*h*d_shared + n_exp*h\n    moe_act = k*expert + n_shared*3*h*d_shared + n_exp*h\n    base = L*(attn + 2*h) + dense_layers*3*h*d_dense + 2*V*h + h\n    tot = base + (L-dense_layers)*moe_tot; act = base + (L-dense_layers)*moe_act\n    print(f'{name}: {tot/1e9:.1f}B total ({(tot-2*V*h)/1e9:.1f}B without embedding and output layers), {act/1e9:.2f}B active per token ({act/tot:.1%}); experts hold {(L-dense_layers)*n_exp*expert/tot:.1%}')\nm = cfg('mistralai/Mixtral-8x7B-v0.1')\nreport('Mixtral 8x7B', m, gqa_attn(m), m['num_local_experts'], m['num_experts_per_tok'], m['intermediate_size'])\nfor repo in ('Qwen/Qwen3-30B-A3B', 'Qwen/Qwen3-235B-A22B'):\n    q = cfg(repo); report(repo.split('/')[1], q, gqa_attn(q), q['num_experts'], q['num_experts_per_tok'], q['moe_intermediate_size'])\nd = cfg('deepseek-ai/DeepSeek-V3'); h, H = d['hidden_size'], d['num_attention_heads']\nmla = (h*d['q_lora_rank'] + d['q_lora_rank'] + d['q_lora_rank']*H*(d['qk_nope_head_dim']+d['qk_rope_head_dim'])\n       + h*(d['kv_lora_rank']+d['qk_rope_head_dim']) + d['kv_lora_rank'] + d['kv_lora_rank']*H*(d['qk_nope_head_dim']+d['v_head_dim'])\n       + H*d['v_head_dim']*h)\nreport('DeepSeek-V3', d, mla, d['n_routed_experts'], d['num_experts_per_tok'], d['moe_intermediate_size'],\n       d['n_shared_experts'], d['moe_intermediate_size'], d['first_k_dense_replace'], d['intermediate_size'])\n\n# 2) Top-k routing, the Switch auxiliary loss and the capacity factor\nN, K, T, dm = 8, 2, 4096, 64\nx = torch.randn(T, dm)\nW = torch.randn(dm, N) * 0.15\nskew = torch.tensor([1.5, 0.8, 0.3, 0., 0., -0.3, -0.6, -1.0])   # an artificial routing preference: expert 0 is the most popular\ndef route(logits, k):\n    p = logits.softmax(-1); topv, topi = p.topk(k, -1)\n    return p, topi, topv / topv.sum(-1, keepdim=True)\np, topi, gates = route(x @ W + skew, K)\nload = torch.bincount(topi.flatten(), minlength=N).float()\nf = torch.bincount(topi[:, 0], minlength=N).float() / T; P = p.mean(0)\nprint(f'Top-{K} routing ({N} experts, {T} tokens): tokens per expert {load.int().tolist()}, max/mean = {load.max()/load.mean():.2f}')\nprint(f'  Switch auxiliary loss N·Σfᵢ·Pᵢ = {N*(f*P).sum():.3f} (1.000 when perfectly uniform)')\nfor cf in (1.0, 1.25, 2.0):\n    cap = math.floor(T*K/N*cf); dropped = (load - cap).clamp(min=0).sum()\n    print(f'  Capacity factor {cf}: capacity {cap} per expert, {int(dropped)} overflowing assignments dropped ({dropped/(T*K):.1%})')\n\n# 3) Auxiliary-loss-free balancing: adjust routing biases only, not the gate weights\nb = torch.zeros(N); u = 0.001; s = torch.sigmoid(x @ W + skew)\nfor step in range(1, 3001):\n    idx = torch.randint(0, T, (512,)); sc = s[idx]\n    sel = (sc + b).topk(K, -1).indices\n    c = torch.bincount(sel.flatten(), minlength=N).float()\n    b += u * torch.sign(c.mean() - c)\n    if step in (1, 300, 3000):\n        sel_all = (s + b).topk(K, -1).indices; la = torch.bincount(sel_all.flatten(), minlength=N).float()\n        print(f'  Bias update step {step:>4}: max/mean load = {la.max()/la.mean():.2f}, bias of expert 0 {b[0]:+.3f}')\n\n# 4) An 8-expert, top-2 MoE feed-forward layer (SwiGLU experts)\nclass MoE(torch.nn.Module):\n    def __init__(s, d, dff, n=8, k=2):\n        super().__init__(); s.k = k; s.router = torch.nn.Linear(d, n, bias=False)\n        s.w1 = torch.nn.Parameter(torch.randn(n, d, dff)*d**-0.5); s.w3 = torch.nn.Parameter(torch.randn(n, d, dff)*d**-0.5)\n        s.w2 = torch.nn.Parameter(torch.randn(n, dff, d)*dff**-0.5)\n    def forward(s, x):\n        p, idx, g = route(s.router(x), s.k); y = torch.zeros_like(x)\n        for e in range(s.w1.shape[0]):\n            tok, slot = (idx == e).nonzero(as_tuple=True)\n            if len(tok) == 0: continue\n            xe = x[tok]; he = torch.nn.functional.silu(xe @ s.w1[e]) * (xe @ s.w3[e])\n            y.index_add_(0, tok, g[tok, slot, None] * (he @ s.w2[e]))\n        return y\nmoe = MoE(256, 512); xx = torch.randn(1024, 256); yy = moe(xx)\ntot = sum(p.numel() for p in moe.parameters()); act = moe.router.weight.numel() + 2*3*256*512\nprint(f'MoE layer: output shape {tuple(yy.shape)}, {tot/1e6:.2f}M parameters, {act/1e6:.2f}M active per token (about 2x the compute and 8x the parameters of one dense FFN of the same width)')\n\n# 5) Linear attention: the parallel and recurrent forms agree, and the state has a fixed size\nTn, dk = 512, 32\nq, k, v = torch.randn(Tn, dk, dtype=torch.float64), torch.randn(Tn, dk, dtype=torch.float64), torch.randn(Tn, dk, dtype=torch.float64)\nphi = lambda z: torch.nn.functional.elu(z) + 1\nQ, Kf = phi(q), phi(k)\nA = (Q @ Kf.T).tril(); par = (A @ v) / A.sum(-1, keepdim=True)\nS = torch.zeros(dk, dk, dtype=torch.float64); z = torch.zeros(dk, dtype=torch.float64); rec = []\nfor t in range(Tn):\n    S += torch.outer(Kf[t], v[t]); z += Kf[t]; rec.append((Q[t] @ S) / (Q[t] @ z))\nprint(f'Linear attention: max difference between parallel and recurrent forms {(par - torch.stack(rec)).abs().max():.1e}; recurrent state {dk}×{dk} elements, independent of sequence length')\n\n# 6) A linear time-invariant SSM: recurrence equals convolution (the starting point of S4)\nNs, Ls = 16, 256\nAd = torch.diag(torch.rand(Ns, dtype=torch.float64) * 0.9); Bv = torch.randn(Ns, 1, dtype=torch.float64); Cv = torch.randn(1, Ns, dtype=torch.float64)\nuu = torch.randn(Ls, dtype=torch.float64); hs = torch.zeros(Ns, 1, dtype=torch.float64); yr = []\nfor t in range(Ls): hs = Ad @ hs + Bv * uu[t]; yr.append((Cv @ hs).item())\nKern = torch.stack([(Cv @ torch.matrix_power(Ad, j) @ Bv).squeeze() for j in range(Ls)])\nyc = torch.stack([(Kern[:t+1].flip(0) * uu[:t+1]).sum() for t in range(Ls)])\nprint(f'SSM: max difference between recurrent and convolutional outputs {(torch.tensor(yr, dtype=torch.float64) - yc).abs().max():.1e}; once Mamba makes B, C and Δ input-dependent there is no fixed kernel, so it uses a parallel scan')\n\n# 7) The delta rule: write the same key twice; linear attention adds up, the delta rule overwrites\ndk = 64; kk = torch.nn.functional.normalize(torch.randn(dk, dtype=torch.float64), dim=0)\nv1, v2 = torch.randn(dk, dtype=torch.float64), torch.randn(dk, dtype=torch.float64)\nS_lin = torch.outer(v1, kk) + torch.outer(v2, kk)\nS_del = torch.zeros(dk, dk, dtype=torch.float64)\nfor vv in (v1, v2): S_del = S_del + torch.outer(vv - S_del @ kk, kk)        # delta rule with β = 1\nprint(f'Delta rule: distance of the read-out from v2 {(S_del @ kk - v2).norm():.1e}; linear attention reads v1+v2, distance from v2 {(S_lin @ kk - v2).norm():.2f}')\n\n# 8) KV cache of hybrid models (BF16, 256K context)\ndef kv(layers, kvh, hd, T=262144): return 2*layers*kvh*hd*T*2\nj = cfg('ai21labs/Jamba-v0.1'); n_attn = j['num_hidden_layers'] // j['attn_layer_period']\nprint(f'Jamba: {n_attn} attention layers out of {j[\"num_hidden_layers\"]}, KV cache {kv(n_attn, j[\"num_key_value_heads\"], j[\"hidden_size\"]//j[\"num_attention_heads\"])/GiB:.0f} GiB; '\n      f'Mixtral (attention in all 32 layers) {kv(m[\"num_hidden_layers\"], m[\"num_key_value_heads\"], m[\"hidden_size\"]//m[\"num_attention_heads\"])/GiB:.0f} GiB')\nqn = cfg('Qwen/Qwen3-Next-80B-A3B-Instruct'); na = qn['num_hidden_layers'] // qn['full_attention_interval']\nst = (qn['num_hidden_layers'] - na) * qn['linear_num_value_heads'] * qn['linear_key_head_dim'] * qn['linear_value_head_dim']\nprint(f'Qwen3-Next-80B-A3B: {na} gated-attention layers out of {qn[\"num_hidden_layers\"]}, KV cache {kv(na, qn[\"num_key_value_heads\"], qn[\"head_dim\"])/GiB:.0f} GiB; '\n      f'the recurrent state of the {qn[\"num_hidden_layers\"]-na} Gated DeltaNet layers totals {st/1e6:.1f}M elements, independent of context length')\n```\n\nOutput:\n\n```text\nMixtral 8x7B: 46.7B total (46.4B without embedding and output layers), 12.88B active per token (27.6%); experts hold 96.6%\nQwen3-30B-A3B: 30.5B total (29.9B without embedding and output layers), 3.35B active per token (11.0%); experts hold 95.0%\nQwen3-235B-A22B: 235.1B total (233.8B without embedding and output layers), 22.19B active per token (9.4%); experts hold 96.6%\nDeepSeek-V3: 671.0B total (669.2B without embedding and output layers), 37.55B active per token (5.6%); experts hold 97.4%\nTop-2 routing (8 experts, 4096 tokens): tokens per expert [2703, 1681, 1062, 755, 770, 517, 462, 242], max/mean = 2.64\n  Switch auxiliary loss N·Σfᵢ·Pᵢ = 1.650 (1.000 when perfectly uniform)\n  Capacity factor 1.0: capacity 1024 per expert, 2374 overflowing assignments dropped (29.0%)\n  Capacity factor 1.25: capacity 1280 per expert, 1824 overflowing assignments dropped (22.3%)\n  Capacity factor 2.0: capacity 2048 per expert, 655 overflowing assignments dropped (8.0%)\n  Bias update step    1: max/mean load = 2.63, bias of expert 0 -0.001\n  Bias update step  300: max/mean load = 1.02, bias of expert 0 -0.187\n  Bias update step 3000: max/mean load = 1.03, bias of expert 0 -0.155\nMoE layer: output shape (1024, 256), 3.15M parameters, 0.79M active per token (about 2x the compute and 8x the parameters of one dense FFN of the same width)\nLinear attention: max difference between parallel and recurrent forms 8.9e-16; recurrent state 32×32 elements, independent of sequence length\nSSM: max difference between recurrent and convolutional outputs 1.4e-14; once Mamba makes B, C and Δ input-dependent there is no fixed kernel, so it uses a parallel scan\nDelta rule: distance of the read-out from v2 1.9e-15; linear attention reads v1+v2, distance from v2 8.13\nJamba: 4 attention layers out of 32, KV cache 4 GiB; Mixtral (attention in all 32 layers) 32 GiB\nQwen3-Next-80B-A3B: 12 gated-attention layers out of 48, KV cache 6 GiB; the recurrent state of the 36 Gated DeltaNet layers totals 18.9M elements, independent of context length\n```\n\nNotes: active parameters in part 1 include the embedding and output layers and count the router as active; the routing skew in parts 2 and 3 is set by hand to demonstrate load statistics and bias updates and does not represent any real model; part 4 implements the MoE feed-forward layer with a loop over experts for readability, whereas real systems gather each expert’s tokens into a batch and use grouped matrix multiplication or block-sparse kernels.\n\n## Exercises\n\n1. **Unit project**: replace the feed-forward layer of your small GPT with the `MoE` class from part 4 (8 experts, top-2) and compare validation loss with the dense version on the same data; every few steps, count the tokens each expert receives, with no auxiliary loss, with the Switch auxiliary loss (α = 0.01) and with bias updates, and compare the load distributions.\n2. Following the [Hugging Face MoE blog](https://huggingface.co/blog/moe), extend part 1 of the example to the `config.json` of another open MoE model, compute total and active parameters and check them against its model card.\n3. Install Mamba as described in the [official repository](https://github.com/state-spaces/mamba), run its example and compare throughput and memory of Mamba and a Transformer of the same size on one GPU at different generation lengths.\n4. Replace some attention layers of a small model with Gated DeltaNet layers from [flash-linear-attention](https://github.com/fla-org/flash-linear-attention) (for example keeping one attention layer in every four), and compare training speed, validation loss and accuracy on a simple synthetic key–value retrieval task.\n\n## Suggested reading order\n\nStart with the [Hugging Face MoE blog](https://huggingface.co/blog/moe) for the overall picture, then read about routing and load balancing in the gating and balancing sections of Shazeer et al. (2017), Switch Transformer section 2, DeepSeekMoE section 3 and section 2.1.2 of the DeepSeek-V3 technical report. For SSMs, read [The Annotated S4](https://srush.github.io/annotated-s4/) and section 3 of the Mamba paper, then [Tri Dao’s blog on Mamba-2](https://tridao.me/blog/2024/mamba2-part1-model/); for linear attention, section 3 of Katharopoulos et al. (2020) and the gated delta rule sections of the Gated DeltaNet paper. For hybrids, read the Jamba paper and the Qwen3-Next model card. Then move on to [Distributed Training and Clusters](/learn/distributed-training) and [How LLMs Generate Text](/learn/llm-inference) to see how expert parallelism and the KV cache play out at the systems level."
    },
    "zh-hans": {
      "title": "MoE 与新架构：稀疏专家、负载均衡、状态空间模型、线性注意力与混合架构",
      "description": "系统梳理两条改造 Transformer 的路线：一是把前馈层换成混合专家（MoE），涵盖稀疏门控、top-k 路由、负载均衡损失、容量因子、细粒度与共享专家、无辅助损失均衡及专家并行，以 Mixtral、Qwen3 与 DeepSeek-V3 的官方配置实算总参数与激活参数；二是替换或部分替换注意力，涵盖 S4、Mamba 与 Mamba-2、线性注意力、RWKV、RetNet、Hyena、xLSTM、Gated DeltaNet，以及 Jamba、Qwen3-Next 等混合架构与扩散语言模型，附可运行示例。",
      "updated": "2026-11-15",
      "takeaways": [
        "MoE 把前馈层换成多个专家和一个路由器，每个 token 只经过少数专家，因此总参数量与每 token 计算量脱钩。按官方 config.json 计算，Mixtral 8x7B 总参数 46.7B、每 token 激活 12.9B；Qwen3-235B-A22B 为 235B / 22B；DeepSeek-V3 为 671B / 约 37B，专家参数占总参数的 95% 以上。",
        "负载均衡是 MoE 训练的核心问题。Switch Transformer 用辅助损失 α·N·Σfᵢ·Pᵢ（α = 0.01）并设容量因子，超出容量的 token 被跳过；DeepSeek-V3 改为给每个专家加一个只参与选择、不参与加权的偏置，按负载每步增减 0.001，基本不再依赖辅助损失，训练和推理都不丢弃 token。",
        "DeepSeekMoE 提出细粒度专家与共享专家：把专家切得更小、激活更多个，并设始终激活的共享专家承载通用知识。DeepSeek-V3 每层 1 个共享专家和 256 个路由专家、每 token 选 8 个；Qwen3 的 MoE 模型为 128 个专家选 8 个，不设共享专家。",
        "状态空间模型与线性注意力用固定大小的递推状态代替随长度增长的 KV Cache，推理时每步计算和显存都与上下文长度无关。Mamba 让 SSM 参数随输入变化（选择性），论文报告推理吞吐为同规模 Transformer 的 5 倍；Gated DeltaNet 把门控与 delta 更新规则结合，用于精确改写记忆。",
        "目前的大规模实践以混合架构为主：Jamba 每 8 层只有 1 层注意力，256K 上下文的 KV Cache 为 4GB，而 Mixtral 为 32GB；Qwen3-Next-80B-A3B 每 4 层中 3 层为 Gated DeltaNet、1 层为门控注意力，总参数 80B、每 token 激活 3B。"
      ],
      "faq": [
        {
          "q": "MoE 模型为什么推理时省计算却不省显存？",
          "a": "每个 token 只经过少数专家，所以每 token 的计算量接近同激活参数量的稠密模型；但哪个专家会被选中事先未知，所有专家的权重都必须常驻显存或可快速取用。以 Mixtral 8x7B 为例，每 token 激活约 12.9B 参数，而显存中要放下全部 46.7B 参数。MoE 在批量较大、能让各专家都分到足够 token 时最划算；单请求、小批量时，读取专家权重的带宽往往成为瓶颈。"
        },
        {
          "q": "专家真的按“学科”或“领域”分工吗？",
          "a": "不一定。Mixtral 论文分析了 The Pile 不同子集上的专家分配，发现 ArXiv、PubMed 和 PhilPapers 文本的专家分布非常接近，没有明显的按主题分工；路由更多表现出句法层面的规律，例如 Python 中的 self、英文中的 Question 以及代码缩进常被分到同一专家，连续 token 也常被分到同一专家。DeepSeekMoE 设计细粒度专家与共享专家，目的正是让专家更专门化。"
        },
        {
          "q": "Mamba 推理时为什么不需要 KV Cache？",
          "a": "Transformer 每生成一个 token 都要与之前全部 token 做注意力，所以要缓存所有历史 token 的键和值，缓存随上下文线性增长。Mamba 等状态空间模型把历史压缩进一个固定大小的状态，每步只用当前输入更新状态并读出输出，状态大小与上下文长度无关。代价是历史信息被压缩，精确检索和复制长距离内容的能力弱于注意力，这也是混合架构保留少量注意力层的原因。"
        },
        {
          "q": "线性注意力与 Mamba 是什么关系？",
          "a": "两者都可以写成“用矩阵状态递推、按查询读出”的形式。Katharopoulos 等（2020）指出，去掉 softmax、改用核特征映射后，因果注意力可以写成 RNN；Mamba-2 论文进一步提出状态空间对偶（SSD），证明一类结构化 SSM 与带掩码的线性注意力是同一计算的两种写法，并据此得到比 Mamba 快 2–8 倍的核心层。Gated DeltaNet 则在这一框架内改进状态的更新规则。"
        },
        {
          "q": "扩散语言模型会取代自回归模型吗？",
          "a": "目前还没有定论。LLaDA（2025）从头训练了一个 8B 掩码扩散语言模型，论文报告其上下文学习能力与 LLaMA3 8B 相当，并在倒序诗句补全任务上超过 GPT-4o，说明大模型的核心能力不一定依赖自回归。但主流开源与商用模型仍以自回归 Transformer 为主，扩散语言模型在推理效率、长文本生成与工具调用等方面的表现仍在研究中。"
        }
      ],
      "sources": [
        {
          "title": "Shazeer 等（2017），Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer",
          "url": "https://arxiv.org/abs/1701.06538"
        },
        {
          "title": "Lepikhin 等（2020），GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding",
          "url": "https://arxiv.org/abs/2006.16668"
        },
        {
          "title": "Fedus、Zoph、Shazeer（2021），Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity",
          "url": "https://arxiv.org/abs/2101.03961"
        },
        {
          "title": "Zoph 等（2022），ST-MoE: Designing Stable and Transferable Sparse Expert Models",
          "url": "https://arxiv.org/abs/2202.08906"
        },
        {
          "title": "Jiang 等（2024），Mixtral of Experts",
          "url": "https://arxiv.org/abs/2401.04088"
        },
        {
          "title": "Dai 等（2024），DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models",
          "url": "https://arxiv.org/abs/2401.06066"
        },
        {
          "title": "Wang 等（2024），Auxiliary-Loss-Free Load Balancing Strategy for Mixture-of-Experts",
          "url": "https://arxiv.org/abs/2408.15664"
        },
        {
          "title": "DeepSeek-AI（2024），DeepSeek-V3 Technical Report",
          "url": "https://arxiv.org/abs/2412.19437"
        },
        {
          "title": "Qwen Team（2025），Qwen3 Technical Report",
          "url": "https://arxiv.org/abs/2505.09388"
        },
        {
          "title": "Gu、Goel、Ré（2021），Efficiently Modeling Long Sequences with Structured State Spaces",
          "url": "https://arxiv.org/abs/2111.00396"
        },
        {
          "title": "Gu、Dao（2023），Mamba: Linear-Time Sequence Modeling with Selective State Spaces",
          "url": "https://arxiv.org/abs/2312.00752"
        },
        {
          "title": "Dao、Gu（2024），Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality",
          "url": "https://arxiv.org/abs/2405.21060"
        },
        {
          "title": "Katharopoulos 等（2020），Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention",
          "url": "https://arxiv.org/abs/2006.16236"
        },
        {
          "title": "Peng 等（2023），RWKV: Reinventing RNNs for the Transformer Era",
          "url": "https://arxiv.org/abs/2305.13048"
        },
        {
          "title": "Sun 等（2023），Retentive Network: A Successor to Transformer for Large Language Models",
          "url": "https://arxiv.org/abs/2307.08621"
        },
        {
          "title": "Poli 等（2023），Hyena Hierarchy: Towards Larger Convolutional Language Models",
          "url": "https://arxiv.org/abs/2302.10866"
        },
        {
          "title": "Beck 等（2024），xLSTM: Extended Long Short-Term Memory",
          "url": "https://arxiv.org/abs/2405.04517"
        },
        {
          "title": "Yang、Kautz、Hatamizadeh（2024），Gated Delta Networks: Improving Mamba2 with Delta Rule",
          "url": "https://arxiv.org/abs/2412.06464"
        },
        {
          "title": "Lieber 等（2024），Jamba: A Hybrid Transformer-Mamba Language Model",
          "url": "https://arxiv.org/abs/2403.19887"
        },
        {
          "title": "Nie 等（2025），Large Language Diffusion Models",
          "url": "https://arxiv.org/abs/2502.09992"
        },
        {
          "title": "Dehghani 等（2018），Universal Transformers",
          "url": "https://arxiv.org/abs/1807.03819"
        },
        {
          "title": "Mixtral-8x7B-v0.1 官方配置文件 config.json",
          "url": "https://huggingface.co/mistralai/Mixtral-8x7B-v0.1/blob/main/config.json"
        },
        {
          "title": "Qwen 官方模型卡：Qwen3-30B-A3B",
          "url": "https://huggingface.co/Qwen/Qwen3-30B-A3B"
        },
        {
          "title": "Qwen 官方模型卡：Qwen3-Next-80B-A3B-Instruct",
          "url": "https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Instruct"
        },
        {
          "title": "DeepSeek-V3 官方配置文件 config.json",
          "url": "https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/config.json"
        },
        {
          "title": "AI21 官方模型卡：Jamba-v0.1",
          "url": "https://huggingface.co/ai21labs/Jamba-v0.1"
        },
        {
          "title": "Hugging Face 博客：Mixture of Experts Explained",
          "url": "https://huggingface.co/blog/moe"
        },
        {
          "title": "Sasha Rush、Sidd Karamcheti：The Annotated S4",
          "url": "https://srush.github.io/annotated-s4/"
        },
        {
          "title": "Tri Dao 博客：State Space Duality (Mamba-2) Part I",
          "url": "https://tridao.me/blog/2024/mamba2-part1-model/"
        },
        {
          "title": "state-spaces/mamba（Mamba 官方实现）",
          "url": "https://github.com/state-spaces/mamba"
        },
        {
          "title": "fla-org/flash-linear-attention（线性注意力与 Gated DeltaNet 等的 Triton 实现）",
          "url": "https://github.com/fla-org/flash-linear-attention"
        },
        {
          "title": "databricks/megablocks（MoE 训练库）",
          "url": "https://github.com/databricks/megablocks"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/llm-core/moe-architectures/",
      "markdown": "**概要**：上一课的[现代大模型架构](/learn/llm-architectures)沿用了 Transformer 的整体结构，只替换了归一化、位置编码与注意力头的组织方式。本课讨论两类更大的改动。第一类保留注意力、把前馈层换成**混合专家（Mixture of Experts，MoE）**，让总参数量与每 token 计算量脱钩，Mixtral、Qwen3 的 MoE 版本与 DeepSeek-V3 都属于这一类。第二类替换或部分替换注意力，用**状态空间模型（SSM）**、**线性注意力**或其变体，以固定大小的递推状态代替随上下文增长的 KV Cache，并发展出注意力与递推层交错的**混合架构**。最后简要介绍扩散语言模型与循环（Looped）语言模型。文中数字来自所引论文、官方模型卡与配置文件，或文末可运行示例。\n\n本课属于 [MoE 与新架构](/learn/unit/u43-moe-newarch)单元，前置为[现代大模型架构](/learn/llm-architectures)，KV Cache 与推理带宽见[大模型推理](/learn/llm-inference)。相关算法卡：[稀疏门控 MoE](/learn/algorithms/sparse-moe)、[GShard](/learn/algorithms/gshard)、[Switch Transformer](/learn/algorithms/switch-transformer)、[Mixtral](/learn/algorithms/mixtral)、[DeepSeekMoE](/learn/algorithms/deepseek-moe)、[无辅助损失负载均衡](/learn/algorithms/aux-free-balancing)、[S4](/learn/algorithms/s4)、[Mamba](/learn/algorithms/mamba)、[Mamba-2](/learn/algorithms/mamba2)、[线性注意力](/learn/algorithms/linear-attention)、[RWKV](/learn/algorithms/rwkv)、[RetNet](/learn/algorithms/retnet)、[Hyena](/learn/algorithms/hyena)、[xLSTM](/learn/algorithms/xlstm)、[Gated DeltaNet](/learn/algorithms/gated-deltanet)、[Jamba 与混合架构](/learn/algorithms/jamba)、[扩散语言模型](/learn/algorithms/diffusion-lm)、[循环语言模型](/learn/algorithms/looped-lm)。\n\n## MoE 的基本结构\n\n稠密 Transformer 中，每个 token 都经过同一个前馈层（FFN）。MoE 层把它换成 N 个结构相同、参数独立的前馈网络（专家），再加一个路由器（router，也称门控网络）。对输入 x，路由器给出每个专家的分数，只保留分数最高的 k 个，输出为这 k 个专家输出的加权和：\n\n> 路由概率 p = softmax(W_r · x)；选出 p 最大的 k 个专家，记为集合 S\n> 输出 y = Σ_{i∈S} gᵢ · FFNᵢ(x)，其中 gᵢ 为 pᵢ 在 S 内重新归一化后的权重\n\n由于每个 token 只经过 k 个专家，计算量约为 k 个 FFN，而参数量为 N 个 FFN。这一思路由 Shazeer 等（2017）在 LSTM 语言模型和机器翻译上大规模验证：论文使用带噪声的 top-k 门控，MoE 层最多含 1370 亿参数，在计算效率只有轻微损失的情况下把模型容量提高了 1000 倍以上。\n\n| 模型 | 专家数 / 每 token 激活 | 共享专家 | 总参数 | 每 token 激活参数 | 来源 |\n|---|---|---|---|---|---|\n| Switch-C（2021） | 2048 / 1 | 无 | 1.6T | — | Switch Transformer 论文 |\n| Mixtral 8x7B（2024） | 8 / 2 | 无 | 46.7B | 12.9B | 论文与 config.json |\n| Qwen3-30B-A3B（2025） | 128 / 8 | 无 | 30.5B | 3.3B | 模型卡与 config.json |\n| Qwen3-235B-A22B（2025） | 128 / 8 | 无 | 235B | 22B | 技术报告与 config.json |\n| DeepSeek-V3（2024） | 256 / 8 | 1 | 671B | 37B | 技术报告与 config.json |\n| Qwen3-Next-80B-A3B（2025） | 512 / 10 | 1 | 80B | 3B | 模型卡 |\n\n按官方配置文件逐项计算（文末示例第 1 部分），Mixtral 8x7B 总参数 46.7B、每 token 激活 12.88B；Qwen3-30B-A3B 总参数 30.5B（不含嵌入与输出层 29.9B），与模型卡给出的 30.5B 和 29.9B 一致，激活 3.35B（模型卡为 3.3B）；DeepSeek-V3 总参数 671.0B、激活 37.55B（技术报告为 671B 与 37B）。四个模型中专家参数都占总参数的 95% 以上，激活比例从 Mixtral 的 27.6% 降到 DeepSeek-V3 的 5.6%。Mixtral 名称中的 “8x7B” 并不意味着 56B 参数：只有前馈层复制了 8 份，注意力、嵌入等部分由各专家共享，因此总参数为 46.7B。\n\nMoE 节省的是计算，不是显存：哪个专家会被选中事先未知，所有专家的权重都要能随时取用。因此 MoE 在训练和大批量推理时最划算；单请求推理时，每步都要读取被选中专家的权重，显存带宽仍是主要瓶颈。部署上的取舍见[推理服务引擎](/learn/serving-engines)。\n\n## 路由与负载均衡\n\n如果不加约束，路由器容易反复选择少数几个专家：这些专家训练得更好，又被选得更多，其余专家几乎得不到训练（路由坍缩）。在专家并行中，各专家分布在不同设备上，负载不均还会让最忙的设备拖慢整体。主要的解决方法有三类。\n\n**辅助损失。** Shazeer 等（2017）用两项辅助损失分别鼓励各专家的重要性（门控权重之和）和负载接近均匀。GShard（Lepikhin 等，2020）在 Transformer 的编码器与解码器中使用 top-2 门控，加入专家容量、分组分派、辅助损失和随机路由（以与第二个专家门控权重成正比的概率决定是否派发给它），在 2048 个 TPU v3 上用 4 天训练了 6000 亿参数的多语言翻译模型。Switch Transformer（Fedus 等，2021）把路由简化为 top-1，并把辅助损失写成：\n\n> 辅助损失 = α · N · Σᵢ fᵢ · Pᵢ\n\n其中 fᵢ 是一个批次中被分到专家 i 的 token 比例（不可导），Pᵢ 是路由器分给专家 i 的平均概率（可导），N 为专家数。完全均匀时 fᵢ = Pᵢ = 1/N，损失等于 α。论文在 10⁻¹ 到 10⁻⁵ 间扫描，最终取 α = 10⁻²。ST-MoE（Zoph 等，2022）又加入路由器 z 损失，惩罚进入路由器的过大 logits，以改善训练稳定性。\n\n**容量因子。** 为了让计算形状固定，GShard 与 Switch Transformer 给每个专家设定容量：\n\n> 专家容量 = （批次 token 数 / 专家数）× 容量因子\n\n超出容量的 token 在该层被跳过（dropped），只经残差连接传到下一层。容量因子越大，丢弃越少，但计算与通信的浪费越多。Switch Transformer 报告在其设置下丢弃率通常低于 1%。示例第 2 部分人为设定了偏向专家 0 的路由，top-2 路由下最忙专家的负载是平均值的 2.64 倍，辅助损失为 1.650（均匀时为 1.000）；容量因子取 1.0、1.25、2.0 时，分别有 29.0%、22.3%、8.0% 的分配被丢弃。后来的实现（如 [MegaBlocks](https://github.com/databricks/megablocks) 的 dropless MoE）用块稀疏计算处理不等长的专家批次，从而不再需要容量因子。\n\n**无辅助损失均衡。** Wang 等（2024）指出辅助损失会引入干扰主目标的梯度，系数太大损害模型效果、太小又平衡不了。他们的做法是给每个专家 i 加一个偏置 bᵢ，只在选择 top-k 时使用：\n\n> 选择：按 sᵢ + bᵢ 选出前 k 个专家；加权：门控值仍用原始分数 sᵢ\n> 更新：每步结束后，过载专家 bᵢ 减 γ，欠载专家 bᵢ 加 γ\n\n偏置只根据此前批次的负载更新，不参与反向传播，因此不产生干扰梯度，也不会泄露当前序列中未来 token 的信息。DeepSeek-V3 采用这一策略，偏置更新速度 γ 在前 14.3T token 设为 0.001、最后 500B token 设为 0；另保留系数仅为 0.0001 的序列级平衡损失，防止单个序列内的极端不均衡。技术报告称由于负载均衡良好，DeepSeek-V3 在训练和推理中都不丢弃任何 token。示例第 3 部分用相同的更新规则（γ = 0.001）作用于上面的偏斜路由：300 步后最忙专家的负载从平均值的 2.63 倍降到 1.02 倍。Qwen3 的 MoE 模型则采用全局批次（global-batch）负载均衡损失，即在整个全局批次而不是单个微批次上统计负载，技术报告称这有助于专家专门化。\n\n## 细粒度专家、共享专家与专家并行\n\nDeepSeekMoE（Dai 等，2024）提出两项结构改动：\n\n1. **细粒度专家切分**：在总参数和计算量不变的前提下，把每个专家的中间维度切小、专家数量增多，同时激活更多专家。例如把 N 个专家各切成 m 份，就得到 mN 个专家，每 token 激活 mk 个，专家组合方式大幅增加；\n2. **共享专家隔离**：留出若干个对所有 token 始终激活的共享专家，承载通用知识，减少路由专家之间的冗余。\n\n论文报告 DeepSeekMoE 2B 与专家参数和计算量为其 1.5 倍的 GShard 2.9B 性能相当，DeepSeekMoE 16B 用约 40% 的计算量达到与 LLaMA2 7B 相当的效果。DeepSeek-V3 每个 MoE 层有 1 个共享专家和 256 个路由专家，专家中间维度 2048，每 token 激活 8 个路由专家；前 3 层仍为稠密 FFN。路由分数改用 sigmoid，再在选中的专家间归一化。Qwen3 的 MoE 模型同样使用细粒度专家（128 个专家激活 8 个），但不设共享专家。\n\n**专家并行**（expert parallelism）把同一层的不同专家放到不同 GPU 上：每个 token 先按路由结果发送到其专家所在的设备，计算后再送回，即两次 all-to-all 通信。通信量随激活专家数和跨节点次数增长，因此 DeepSeek-V3 采用节点受限路由：每层路由专家均匀分布在 8 个节点的 64 张 GPU 上，每个 token 最多发往 4 个节点。技术报告估计在通信成本不变的情况下，每 token 选择的专家数理论上可以从 8 扩展到 13 个（4 个节点 × 每节点 3.2 个）。分布式训练的其他并行方式见[分布式训练](/learn/distributed-training)。\n\n**专家学到了什么。** Mixtral 论文分析了 The Pile 各子集上的专家分配，发现 ArXiv 论文、生物医学摘要（PubMed）和哲学论文（PhilPapers）的专家分布非常相似，没有明显按主题分工，只有合成数据 DM Mathematics 略有不同；路由更多呈现句法规律，例如 Python 中的 `self`、英文中的 “Question” 以及代码缩进常由同一专家处理，连续 token 也常被分到同一专家。\n\n## 状态空间模型：从 S4 到 Mamba\n\n注意力的计算随序列长度平方增长，推理时 KV Cache 随长度线性增长。状态空间模型（SSM）来自控制理论，用一个隐藏状态 h 递推地汇总历史：\n\n> 连续形式：h′(t) = A·h(t) + B·x(t)，y(t) = C·h(t)\n> 离散化（步长 Δ）后：hₜ = Ā·hₜ₋₁ + B̄·xₜ，yₜ = C·hₜ\n\n当 A、B、C 与输入无关时（线性时不变，LTI），把递推展开可得 yₜ = Σⱼ (C·Āʲ·B̄)·xₜ₋ⱼ，即输出等于输入与一个固定卷积核的卷积。因此训练时可以用卷积（FFT）并行计算整个序列，推理时又可以按递推逐步生成。示例第 6 部分验证递推与卷积两种算法的输出最大差为 1.4×10⁻¹⁴。\n\n**S4**（Gu 等，2021）给出了对矩阵 A 的结构化参数化和高效计算方法，使 SSM 能稳定地建模很长的依赖。论文报告 S4 在 Long Range Arena 基准的所有任务上取得当时最佳结果，是第一个解决长度 16384 的 Path-X 任务的模型（准确率 88%）；在图像与语言建模上大幅缩小了与 Transformer 的差距，同时生成速度快 60 倍。\n\n**Mamba**（Gu 与 Dao，2023）指出，LTI 模型的弱点是不能根据内容决定记住或忽略什么，这对文本等离散数据尤其不利。Mamba 让 B、C 和步长 Δ 都成为当前输入的函数（选择性 SSM），模型因此可以按 token 选择性地传播或遗忘信息。代价是不再存在固定卷积核，论文为此设计了硬件感知的并行扫描算法，在 GPU SRAM 中完成递推。Mamba 块不含注意力，也不另设 MLP。论文报告其推理吞吐是同规模 Transformer 的 5 倍，计算随序列长度线性增长，在长达百万的序列上性能仍在提升；Mamba-3B 在预训练和下游评测上超过同规模 Transformer，并与两倍规模的 Transformer 相当。\n\n**Mamba-2**（Dao 与 Gu，2024）提出状态空间对偶（SSD）框架：把 A 限制为标量乘单位阵后，选择性 SSM 等价于一种带结构化掩码的线性注意力，因此既能按递推计算，也能按矩阵乘法分块计算，更好地利用 GPU 的矩阵单元。论文报告其核心层比 Mamba 的选择性扫描快 2–8 倍。\n\n## 线性注意力及其改进\n\n标准注意力对每个查询计算 softmax(q·kⱼ) 加权平均。**线性注意力**（Katharopoulos 等，2020）把 softmax 相似度替换为核特征映射的内积 φ(q)·φ(k)，利用矩阵乘法的结合律改变计算顺序：\n\n> 输出 oₜ = φ(qₜ)ᵀ·Sₜ / φ(qₜ)ᵀ·zₜ，其中 Sₜ = Sₜ₋₁ + φ(kₜ)·vₜᵀ，zₜ = zₜ₋₁ + φ(kₜ)\n\n这样因果注意力就变成一个以矩阵 Sₜ 为状态的 RNN，复杂度从 O(N²) 降到 O(N)。论文称其效果与普通 Transformer 相近，在超长序列的自回归预测上最多快 4000 倍。示例第 5 部分用 φ(x) = elu(x) + 1 验证并行形式与递推形式的最大差为 8.9×10⁻¹⁶，状态大小始终为 32×32。\n\n最简单的线性注意力只会累加，不会遗忘或改写，状态容易被旧信息“写满”。此后的工作主要改进状态更新规则：\n\n| 方法 | 状态更新的特点 | 论文报告 |\n|---|---|---|\n| RWKV（Peng 等，2023） | 带随通道衰减的线性注意力（WKV），训练时像 Transformer 并行，推理时像 RNN | 训练到 140 亿参数 |\n| RetNet（Sun 等，2023） | 带指数衰减的“保留”机制，支持并行、递推与分块递推三种计算方式 | 推理 O(1) 显存与延迟 |\n| Hyena（Poli 等，2023） | 不用递推状态，而用隐式参数化的长卷积与数据控制的门控交替 | 2K 长度下以少 20% 训练计算达到 Transformer 质量；64K 长度下比优化过的注意力快 100 倍 |\n| xLSTM（Beck 等，2024） | 指数门控；sLSTM 用标量记忆，mLSTM 用矩阵记忆与协方差更新、可完全并行 | — |\n| Gated DeltaNet（Yang 等，2024） | 门控（整体衰减）加 delta 规则（按键精确改写） | 语言建模、上下文检索、长度外推等多项基准超过 Mamba2 与 DeltaNet |\n\n**delta 规则**来自 Widrow 等（1960）的经典学习规则：写入新的键值对之前，先读出该键当前存的值，只把差值写进去，即 Sₜ = Sₜ₋₁ + βₜ·(vₜ − Sₜ₋₁·kₜ)·kₜᵀ。这样对同一个键重复写入时，新值会覆盖旧值，而不是与旧值叠加。示例第 7 部分把同一个单位键先后与 v1、v2 写入：delta 规则读出的结果与 v2 的距离为 1.9×10⁻¹⁵，普通线性注意力读出的是 v1 + v2，与 v2 的距离为 8.13。Gated DeltaNet 论文认为门控便于快速清除记忆、delta 规则便于精确修改记忆，两者互补，并在此基础上构建了与滑动窗口注意力或 Mamba2 层组合的混合模型。上述多种层的 Triton 实现可在 [flash-linear-attention](https://github.com/fla-org/flash-linear-attention) 中找到。\n\n## 混合架构\n\n纯递推模型把全部历史压缩进固定大小的状态，精确检索和复制长距离内容的能力弱于注意力。因此目前的大规模实践多为**混合架构**：大部分层使用 SSM 或线性注意力，保留少量全注意力层。\n\n**Jamba**（Lieber 等，2024）每个 Jamba 块含 8 层，注意力层与 Mamba 层之比为 1:7，每隔一层使用 MoE（16 个专家选 2 个）。发布的模型总参数 52B、激活 12B，可放入单张 80GB GPU，支持 256K 上下文。论文的消融实验显示 1:3 与 1:7 的比例效果几乎相同，1:7 计算效率更高。论文表 1 给出 256K 上下文（16 位）的 KV Cache：LLaMA-2 6.7B 为 128GB、Mistral 7.2B 与 Mixtral 均为 32GB、Jamba 为 4GB。示例第 8 部分按 Jamba 与 Mixtral 的官方配置复算，结果同为 4 GiB 与 32 GiB。\n\n**Qwen3-Next-80B-A3B**（2025）的模型卡给出的布局为 12 组“3 层（Gated DeltaNet → MoE）+ 1 层（门控注意力 → MoE）”，共 48 层；MoE 部分为 512 个专家、每 token 激活 10 个，另有 1 个共享专家，总参数 80B、激活 3B，原生上下文 262,144 个 token。按配置计算，256K 上下文下 12 层注意力的 KV Cache 为 6 GiB，36 层 Gated DeltaNet 的递推状态共约 1890 万个元素，与上下文长度无关。模型卡称其基础模型以 Qwen3-32B 基础模型约 10% 的训练成本取得更好的下游效果，在 32K 以上上下文中推理吞吐约为后者的 10 倍。\n\n选择架构时的主要考量：\n\n| 维度 | 稠密 Transformer | MoE Transformer | SSM / 线性注意力 | 混合架构 |\n|---|---|---|---|---|\n| 每 token 计算 | 与参数量成正比 | 只与激活参数成正比 | 与上下文长度无关 | 介于两者之间 |\n| 推理显存 | 权重 + 随长度增长的 KV Cache | 全部专家权重 + KV Cache | 权重 + 固定状态 | 少量 KV Cache + 固定状态 |\n| 精确检索与复制 | 强 | 强 | 较弱 | 由注意力层承担 |\n| 工程生态 | 最成熟 | 需要专家并行与负载均衡 | 需专用算子 | 两套算子都要支持 |\n\n## 扩散语言模型与循环语言模型\n\n**扩散语言模型**不按从左到右的顺序生成。LLaDA（Nie 等，2025）的前向过程按比例随机遮盖 token，反向过程由一个 Transformer 同时预测所有被遮盖的位置，训练目标是似然的一个下界。论文从头训练了 8B 参数的 LLaDA，报告其上下文学习能力与 LLaMA3 8B 相当，经 SFT 后具备多轮对话等指令跟随能力，并在倒序诗句补全任务上超过 GPT-4o，以此说明大模型的核心能力不一定依赖自回归建模。官方实现见 [ML-GSAI/LLaDA](https://github.com/ML-GSAI/LLaDA)。\n\n**循环语言模型**让同一组层重复执行多次，用“深度上的循环”换取更多计算而不增加参数。这一思路可追溯到 Universal Transformer（Dehghani 等，2018）：它在深度方向循环使用同一个 Transformer 块，并加入按位置自适应停止的机制，论文证明在一定假设下它是图灵完备的，并在 WMT14 英德翻译上比 Transformer 高 0.9 BLEU。它与[推理模型](/learn/reasoning-models)中的测试时计算扩展都试图让模型按需使用更多计算。\n\n## 可运行示例\n\n以下代码在 PyTorch 2.15（CPU）上实测，运行时从 Hugging Face 下载六个模型的公开 `config.json`（不下载权重），约需数秒，输出与正文数字一致。\n\n```python\nimport json, math, urllib.request, torch\ntorch.manual_seed(0); torch.set_num_threads(3)\nGiB = 1024**3\ndef cfg(repo): return json.load(urllib.request.urlopen(f'https://huggingface.co/{repo}/resolve/main/config.json'))\n\n# 1) 由 config.json 算总参数与激活参数\ndef gqa_attn(c):\n    h, H, KV = c['hidden_size'], c['num_attention_heads'], c['num_key_value_heads']\n    hd = c.get('head_dim') or h // H\n    return h*H*hd*2 + h*KV*hd*2 + (2*hd if 'Qwen' in c['architectures'][0] else 0)\ndef report(name, c, attn, n_exp, k, d_exp, n_shared=0, d_shared=0, dense_layers=0, d_dense=0):\n    h, L, V = c['hidden_size'], c['num_hidden_layers'], c['vocab_size']\n    expert = 3*h*d_exp                      # SwiGLU 专家：三个矩阵\n    moe_tot = n_exp*expert + n_shared*3*h*d_shared + n_exp*h\n    moe_act = k*expert + n_shared*3*h*d_shared + n_exp*h\n    base = L*(attn + 2*h) + dense_layers*3*h*d_dense + 2*V*h + h\n    tot = base + (L-dense_layers)*moe_tot; act = base + (L-dense_layers)*moe_act\n    print(f'{name}：总参数 {tot/1e9:.1f}B（不含嵌入与输出层 {(tot-2*V*h)/1e9:.1f}B），每 token 激活 {act/1e9:.2f}B（{act/tot:.1%}）；专家参数占 {(L-dense_layers)*n_exp*expert/tot:.1%}')\nm = cfg('mistralai/Mixtral-8x7B-v0.1')\nreport('Mixtral 8x7B', m, gqa_attn(m), m['num_local_experts'], m['num_experts_per_tok'], m['intermediate_size'])\nfor repo in ('Qwen/Qwen3-30B-A3B', 'Qwen/Qwen3-235B-A22B'):\n    q = cfg(repo); report(repo.split('/')[1], q, gqa_attn(q), q['num_experts'], q['num_experts_per_tok'], q['moe_intermediate_size'])\nd = cfg('deepseek-ai/DeepSeek-V3'); h, H = d['hidden_size'], d['num_attention_heads']\nmla = (h*d['q_lora_rank'] + d['q_lora_rank'] + d['q_lora_rank']*H*(d['qk_nope_head_dim']+d['qk_rope_head_dim'])\n       + h*(d['kv_lora_rank']+d['qk_rope_head_dim']) + d['kv_lora_rank'] + d['kv_lora_rank']*H*(d['qk_nope_head_dim']+d['v_head_dim'])\n       + H*d['v_head_dim']*h)\nreport('DeepSeek-V3', d, mla, d['n_routed_experts'], d['num_experts_per_tok'], d['moe_intermediate_size'],\n       d['n_shared_experts'], d['moe_intermediate_size'], d['first_k_dense_replace'], d['intermediate_size'])\n\n# 2) top-k 路由、Switch 辅助损失与容量因子\nN, K, T, dm = 8, 2, 4096, 64\nx = torch.randn(T, dm)\nW = torch.randn(dm, N) * 0.15\nskew = torch.tensor([1.5, 0.8, 0.3, 0., 0., -0.3, -0.6, -1.0])   # 人为设定的路由偏好：专家 0 最“热门”\ndef route(logits, k):\n    p = logits.softmax(-1); topv, topi = p.topk(k, -1)\n    return p, topi, topv / topv.sum(-1, keepdim=True)\np, topi, gates = route(x @ W + skew, K)\nload = torch.bincount(topi.flatten(), minlength=N).float()\nf = torch.bincount(topi[:, 0], minlength=N).float() / T; P = p.mean(0)\nprint(f'top-{K} 路由（{N} 个专家，{T} 个 token）：各专家接收 token 数 {load.int().tolist()}，最大/平均 = {load.max()/load.mean():.2f}')\nprint(f'  Switch 辅助损失 N·Σfᵢ·Pᵢ = {N*(f*P).sum():.3f}（完全均匀时为 1.000）')\nfor cf in (1.0, 1.25, 2.0):\n    cap = math.floor(T*K/N*cf); dropped = (load - cap).clamp(min=0).sum()\n    print(f'  容量因子 {cf}：每个专家容量 {cap}，溢出被丢弃的分配 {int(dropped)}（{dropped/(T*K):.1%}）')\n\n# 3) 无辅助损失负载均衡：只调路由偏置，不改门控权重\nb = torch.zeros(N); u = 0.001; s = torch.sigmoid(x @ W + skew)\nfor step in range(1, 3001):\n    idx = torch.randint(0, T, (512,)); sc = s[idx]\n    sel = (sc + b).topk(K, -1).indices\n    c = torch.bincount(sel.flatten(), minlength=N).float()\n    b += u * torch.sign(c.mean() - c)\n    if step in (1, 300, 3000):\n        sel_all = (s + b).topk(K, -1).indices; la = torch.bincount(sel_all.flatten(), minlength=N).float()\n        print(f'  偏置更新 {step:>4} 步：最大/平均负载 = {la.max()/la.mean():.2f}，专家 0 的偏置 {b[0]:+.3f}')\n\n# 4) 一个 8 专家 top-2 的 MoE 前馈层（SwiGLU 专家）\nclass MoE(torch.nn.Module):\n    def __init__(s, d, dff, n=8, k=2):\n        super().__init__(); s.k = k; s.router = torch.nn.Linear(d, n, bias=False)\n        s.w1 = torch.nn.Parameter(torch.randn(n, d, dff)*d**-0.5); s.w3 = torch.nn.Parameter(torch.randn(n, d, dff)*d**-0.5)\n        s.w2 = torch.nn.Parameter(torch.randn(n, dff, d)*dff**-0.5)\n    def forward(s, x):\n        p, idx, g = route(s.router(x), s.k); y = torch.zeros_like(x)\n        for e in range(s.w1.shape[0]):\n            tok, slot = (idx == e).nonzero(as_tuple=True)\n            if len(tok) == 0: continue\n            xe = x[tok]; he = torch.nn.functional.silu(xe @ s.w1[e]) * (xe @ s.w3[e])\n            y.index_add_(0, tok, g[tok, slot, None] * (he @ s.w2[e]))\n        return y\nmoe = MoE(256, 512); xx = torch.randn(1024, 256); yy = moe(xx)\ntot = sum(p.numel() for p in moe.parameters()); act = moe.router.weight.numel() + 2*3*256*512\nprint(f'MoE 层：输出形状 {tuple(yy.shape)}，总参数 {tot/1e6:.2f}M，每 token 激活 {act/1e6:.2f}M（约为同宽稠密 FFN 的 2 倍计算、8 倍参数）')\n\n# 5) 线性注意力：并行形式与递推形式等价，状态大小固定\nTn, dk = 512, 32\nq, k, v = torch.randn(Tn, dk, dtype=torch.float64), torch.randn(Tn, dk, dtype=torch.float64), torch.randn(Tn, dk, dtype=torch.float64)\nphi = lambda z: torch.nn.functional.elu(z) + 1\nQ, Kf = phi(q), phi(k)\nA = (Q @ Kf.T).tril(); par = (A @ v) / A.sum(-1, keepdim=True)\nS = torch.zeros(dk, dk, dtype=torch.float64); z = torch.zeros(dk, dtype=torch.float64); rec = []\nfor t in range(Tn):\n    S += torch.outer(Kf[t], v[t]); z += Kf[t]; rec.append((Q[t] @ S) / (Q[t] @ z))\nprint(f'线性注意力：并行形式与递推形式最大差 {(par - torch.stack(rec)).abs().max():.1e}；递推状态 {dk}×{dk} 个元素，与序列长度无关')\n\n# 6) 线性时不变 SSM：递推与卷积等价（S4 的出发点）\nNs, Ls = 16, 256\nAd = torch.diag(torch.rand(Ns, dtype=torch.float64) * 0.9); Bv = torch.randn(Ns, 1, dtype=torch.float64); Cv = torch.randn(1, Ns, dtype=torch.float64)\nuu = torch.randn(Ls, dtype=torch.float64); hs = torch.zeros(Ns, 1, dtype=torch.float64); yr = []\nfor t in range(Ls): hs = Ad @ hs + Bv * uu[t]; yr.append((Cv @ hs).item())\nKern = torch.stack([(Cv @ torch.matrix_power(Ad, j) @ Bv).squeeze() for j in range(Ls)])\nyc = torch.stack([(Kern[:t+1].flip(0) * uu[:t+1]).sum() for t in range(Ls)])\nprint(f'SSM：递推输出与卷积输出最大差 {(torch.tensor(yr, dtype=torch.float64) - yc).abs().max():.1e}；Mamba 让 B、C、Δ 随输入变化后不再是固定卷积核，改用并行扫描')\n\n# 7) delta 规则：同一个键写入两次，线性注意力叠加，delta 规则覆盖\ndk = 64; kk = torch.nn.functional.normalize(torch.randn(dk, dtype=torch.float64), dim=0)\nv1, v2 = torch.randn(dk, dtype=torch.float64), torch.randn(dk, dtype=torch.float64)\nS_lin = torch.outer(v1, kk) + torch.outer(v2, kk)\nS_del = torch.zeros(dk, dk, dtype=torch.float64)\nfor vv in (v1, v2): S_del = S_del + torch.outer(vv - S_del @ kk, kk)        # β=1 的 delta 规则\nprint(f'delta 规则：读出与 v2 的距离 {(S_del @ kk - v2).norm():.1e}；线性注意力读出 = v1+v2，与 v2 的距离 {(S_lin @ kk - v2).norm():.2f}')\n\n# 8) 混合架构的 KV Cache（BF16，256K 上下文）\ndef kv(layers, kvh, hd, T=262144): return 2*layers*kvh*hd*T*2\nj = cfg('ai21labs/Jamba-v0.1'); n_attn = j['num_hidden_layers'] // j['attn_layer_period']\nprint(f'Jamba：{j[\"num_hidden_layers\"]} 层中注意力层 {n_attn} 层，KV Cache {kv(n_attn, j[\"num_key_value_heads\"], j[\"hidden_size\"]//j[\"num_attention_heads\"])/GiB:.0f} GiB；'\n      f'Mixtral（32 层全注意力）{kv(m[\"num_hidden_layers\"], m[\"num_key_value_heads\"], m[\"hidden_size\"]//m[\"num_attention_heads\"])/GiB:.0f} GiB')\nqn = cfg('Qwen/Qwen3-Next-80B-A3B-Instruct'); na = qn['num_hidden_layers'] // qn['full_attention_interval']\nst = (qn['num_hidden_layers'] - na) * qn['linear_num_value_heads'] * qn['linear_key_head_dim'] * qn['linear_value_head_dim']\nprint(f'Qwen3-Next-80B-A3B：{qn[\"num_hidden_layers\"]} 层中门控注意力 {na} 层，KV Cache {kv(na, qn[\"num_key_value_heads\"], qn[\"head_dim\"])/GiB:.0f} GiB；'\n      f'{qn[\"num_hidden_layers\"]-na} 层 Gated DeltaNet 的递推状态共 {st/1e6:.1f}M 个元素，与上下文长度无关')\n```\n\n输出：\n\n```text\nMixtral 8x7B：总参数 46.7B（不含嵌入与输出层 46.4B），每 token 激活 12.88B（27.6%）；专家参数占 96.6%\nQwen3-30B-A3B：总参数 30.5B（不含嵌入与输出层 29.9B），每 token 激活 3.35B（11.0%）；专家参数占 95.0%\nQwen3-235B-A22B：总参数 235.1B（不含嵌入与输出层 233.8B），每 token 激活 22.19B（9.4%）；专家参数占 96.6%\nDeepSeek-V3：总参数 671.0B（不含嵌入与输出层 669.2B），每 token 激活 37.55B（5.6%）；专家参数占 97.4%\ntop-2 路由（8 个专家，4096 个 token）：各专家接收 token 数 [2703, 1681, 1062, 755, 770, 517, 462, 242]，最大/平均 = 2.64\n  Switch 辅助损失 N·Σfᵢ·Pᵢ = 1.650（完全均匀时为 1.000）\n  容量因子 1.0：每个专家容量 1024，溢出被丢弃的分配 2374（29.0%）\n  容量因子 1.25：每个专家容量 1280，溢出被丢弃的分配 1824（22.3%）\n  容量因子 2.0：每个专家容量 2048，溢出被丢弃的分配 655（8.0%）\n  偏置更新    1 步：最大/平均负载 = 2.63，专家 0 的偏置 -0.001\n  偏置更新  300 步：最大/平均负载 = 1.02，专家 0 的偏置 -0.187\n  偏置更新 3000 步：最大/平均负载 = 1.03，专家 0 的偏置 -0.155\nMoE 层：输出形状 (1024, 256)，总参数 3.15M，每 token 激活 0.79M（约为同宽稠密 FFN 的 2 倍计算、8 倍参数）\n线性注意力：并行形式与递推形式最大差 8.9e-16；递推状态 32×32 个元素，与序列长度无关\nSSM：递推输出与卷积输出最大差 1.4e-14；Mamba 让 B、C、Δ 随输入变化后不再是固定卷积核，改用并行扫描\ndelta 规则：读出与 v2 的距离 1.9e-15；线性注意力读出 = v1+v2，与 v2 的距离 8.13\nJamba：32 层中注意力层 4 层，KV Cache 4 GiB；Mixtral（32 层全注意力）32 GiB\nQwen3-Next-80B-A3B：48 层中门控注意力 12 层，KV Cache 6 GiB；36 层 Gated DeltaNet 的递推状态共 18.9M 个元素，与上下文长度无关\n```\n\n几点说明：第 1 部分的激活参数计入了嵌入层与输出层，并把路由器参数计入激活部分；第 2、3 部分的路由偏斜是人为设定的，用于演示负载统计与偏置更新，不代表真实模型的分布；第 4 部分用逐专家循环实现 MoE 前馈层，便于阅读，实际系统会把同一专家的 token 收集成批，用分组矩阵乘法或块稀疏计算一次完成。\n\n## 动手练习\n\n1. **单元项目**：用示例第 4 部分的 `MoE` 类替换自己的小型 GPT 中的前馈层（8 个专家、top-2），在同一数据上与稠密版本比较验证损失；每隔若干步统计各专家接收的 token 数，分别在不加辅助损失、加 Switch 辅助损失（α = 0.01）和使用偏置更新三种设置下观察负载分布。\n2. 参照 [Hugging Face 的 MoE 博客](https://huggingface.co/blog/moe)，把示例第 1 部分扩展到另一个开源 MoE 模型的 `config.json`，算出总参数与激活参数并与模型卡核对。\n3. 按 [Mamba 官方仓库](https://github.com/state-spaces/mamba)的说明安装并运行示例，在同一 GPU 上比较 Mamba 与同规模 Transformer 在不同生成长度下的吞吐和显存。\n4. 用 [flash-linear-attention](https://github.com/fla-org/flash-linear-attention) 中的 Gated DeltaNet 层替换小模型的部分注意力层（如每 4 层保留 1 层注意力），比较训练速度、验证损失和一个简单的“键值检索”合成任务的准确率。\n\n## 推荐学习顺序\n\n先读 [Hugging Face 的 MoE 博客](https://huggingface.co/blog/moe)建立整体概念，再按 Shazeer 等（2017）中门控网络与负载均衡部分、Switch Transformer 第 2 节、DeepSeekMoE 第 3 节和 DeepSeek-V3 技术报告第 2.1.2 节的顺序阅读路由与负载均衡。SSM 部分先读 [The Annotated S4](https://srush.github.io/annotated-s4/) 与 Mamba 论文第 3 节，再读 [Tri Dao 关于 Mamba-2 的博客](https://tridao.me/blog/2024/mamba2-part1-model/)；线性注意力部分读 Katharopoulos 等（2020）第 3 节与 Gated DeltaNet 论文中关于门控 delta 规则的部分。混合架构读 Jamba 论文与 Qwen3-Next 模型卡。之后可进入[分布式训练](/learn/distributed-training)和[大模型推理](/learn/llm-inference)，了解专家并行与 KV Cache 在系统层面的影响。"
    }
  }
}