Mixture-of-Depths (MoD): Mathematical Foundations, Dynamic Token-Level Compute Routing, Top-k Capacity Budgeting, and FLOP-Optimal Transformer Architectures

Standard autoregressive Transformers allocate an identical compute budget to every token in a sequence. Regardless of whether a token represents a trivial punctuation mark, a common grammatical function word, or a complex semantic reasoning step, the model applies the exact same sequence of multi-head self-attention and multilayer perceptron (MLP) operations across all $L$ layers. In Mixture-of-Depths: Dynamically allocating compute in transformer-based language models, researchers at Google De

6 min
Mixture-of-Depths (MoD): Mathematical Foundations, Dynamic Token-Level Compute Routing, Top-k Capacity Budgeting, and FLOP-Optimal Transformer Architectures

Standard autoregressive Transformers allocate an identical compute budget to every token in a sequence. Regardless of whether a token represents a trivial punctuation mark, a common grammatical function word, or a complex semantic reasoning step, the model applies the exact same sequence of multi-head self-attention and multilayer perceptron (MLP) operations across all LL layers.

In Mixture-of-Depths: Dynamically allocating compute in transformer-based language models, researchers at Google DeepMind (Raposo et al., 2024) introduced Mixture-of-Depths (MoD). MoD reallocates FLOPs dynamically across sequence positions and model depth. By enforcing an explicit total compute capacity per layer, MoD routes only a subset of informative tokens through attention and MLP blocks while allowing the remaining tokens to bypass computation entirely via residual skip connections.

Mixture of Depths Dynamic Routing Architecture

Mathematical Formulation of Mixture-of-Depths

In a conventional Transformer layer ll, the input tensor Xl=[x1l,x2l,,xTl]TRT×dX^l = [x_1^l, x_2^l, \dots, x_T^l]^T \in \mathbb{R}^{T \times d} undergoes computation across all TT token positions:

yil=xil+fl(xil)y_i^l = x_i^l + f_l(x_i^l)

where fl()f_l(\cdot) represents the computational block (multi-head attention or MLP) and xilRdx_i^l \in \mathbb{R}^d is the hidden state vector at sequence position ii.

Router Scoring and Dynamic Capacity Budgeting

Mixture-of-Depths introduces a learned router parameter vector wr,lRdw_{r,l} \in \mathbb{R}^d at each routable layer ll. The router assigns a scalar routing weight rilr_i^l to each token position:

ril=wr,lTxilr_i^l = w_{r,l}^T x_i^l

Rather than applying a soft gating factor to all tokens or setting an unconstrained threshold (which creates variable tensor dimensions and destabilizes distributed hardware execution), MoD enforces a strict capacity factor C(0,1]C \in (0, 1]. The total number of tokens permitted to participate in computation block flf_l is bounded by capacity kk:

k=CTk = \lfloor C \cdot T \rfloor

Typical configurations set C=0.5C = 0.5 (50% token capacity) or C=0.125C = 0.125 (12.5% token capacity). The layer determines the active token set SlS_l by identifying the indices corresponding to the top-kk router scores:

Sl=TopK({ril}i=1T,k)S_l = \text{TopK}\left( \{r_i^l\}_{i=1}^T, k \right)

Block Execution and Residual Bypassing

Tokens belonging to index set SlS_l are collected into a packed tensor X~lRk×d\tilde{X}^l \in \mathbb{R}^{k \times d} and processed through computation block flf_l. The output of flf_l is scaled by the router weight rilr_i^l to ensure continuous gradient flow during backpropagation:

yil={xil+rilfl(xil),if iSlxil,if iSly_i^l = \begin{cases} x_i^l + r_i^l \cdot f_l(x_i^l), & \text{if } i \in S_l \\ x_i^l, & \text{if } i \notin S_l \end{cases}

For tokens outside SlS_l, the computation block is omitted entirely. The hidden state propagates unchanged along the residual stream, incurring zero matrix multiply FLOPs for that layer.

Because the output is directly modulated by rilr_i^l, the loss gradient propagates to the router weights:

Lwr,l=iSlLyilfl(xil)(xil)T\frac{\partial \mathcal{L}}{\partial w_{r,l}} = \sum_{i \in S_l} \frac{\partial \mathcal{L}}{\partial y_i^l} f_l(x_i^l) (x_i^l)^T

This objective incentivizes the router to allocate high scores to tokens whose transformation under flf_l produces the greatest reduction in task loss.

Architectural Configurations and MoD Routing Schemes

MoD supports several routing topologies across Transformer layers:

  1. Joint Attention and MLP Routing: A single router determines whether a token participates in both the self-attention block and the subsequent MLP block of layer ll. Tokens bypassing the layer skip all compute primitives.
  2. Staggered Block Routing: Independent routers gate self-attention and MLP sub-layers separately. A token may participate in self-attention to aggregate contextual information while bypassing the feed-forward projection, or vice versa.
  3. Alternating Static and Dynamic Layers: Fixed dense Transformer layers alternate with MoD layers. This ensures periodic global information mixing across all sequence positions while saving compute in intermediate representations.

Mixture-of-Depths vs. Mixture-of-Experts (MoE)

While Mixture-of-Experts (Shazeer et al., 2017; DeepSeek AI, 2024) and Mixture-of-Depths both utilize conditional routing, their scaling dimensions differ:

  • Mixture-of-Experts (MoE) routes tokens horizontally across parallel expert sub-networks. Total model parameter count expands significantly while compute per token remains constant.
  • Mixture-of-Depths (MoD) routes tokens vertically through network depth. Total model parameter count remains constant while compute per token decreases according to capacity factor CC.

Mixture-of-Depths-and-Experts (MoDE)

MoD and MoE can be integrated into a unified architecture termed MoDE. In MoDE, the routing mechanism selects both whether a token executes an MLP block (depth routing) and which specific expert MLP processes the token (expert routing).

This can be implemented by adding a null "no-op" path to a standard MoE top-kk router, or by cascading a binary MoD router ahead of an MoE expert gating network. MoDE enables models to decouple active parameters, total parameters, and sequence execution cost simultaneously.

Solving the Autoregressive Causal Routing Dilemma

During standard non-causal training and prefill phases, the top-kk selection operator evaluates router logits across all sequence positions TT simultaneously. However, during autoregressive generation (decoding), tokens are produced sequentially one token at a time. A token at position tt cannot rank its router score against future tokens t+1,,Tt+1, \dots, T.

Raposo et al. evaluated two approaches to maintain causal autoregressive generation:

1. Auxiliary Binary Classification Loss

The primary router logits rilr_i^l are supervised with an auxiliary binary cross-entropy loss Laux\mathcal{L}_{\text{aux}}. The top-kk selections computed across the full sequence during training act as binary pseudo-labels:

Laux=1Ti=1T[I(iSl)logσ(ril)+(1I(iSl))log(1σ(ril))]\mathcal{L}_{\text{aux}} = -\frac{1}{T} \sum_{i=1}^T \left[ \mathbb{I}(i \in S_l) \log \sigma(r_i^l) + (1 - \mathbb{I}(i \in S_l)) \log(1 - \sigma(r_i^l)) \right]

where σ(z)=11+ez\sigma(z) = \frac{1}{1 + e^{-z}}. This loss shifts the router logits so that tokens destined for computation produce σ(ril)>0.5\sigma(r_i^l) > 0.5. During autoregressive decoding, the model routes token tt through block flf_l whenever σ(rtl)>0.5\sigma(r_t^l) > 0.5, completely removing dependency on future tokens.

Empirical measurements demonstrate that this auxiliary objective achieves over 99% routing classification accuracy relative to true top-kk selection, while causing less than 0.3% degradation on the primary language modeling cross-entropy loss.

2. Predictor-Based Routing Modules

Alternatively, a small auxiliary MLP predictor processes intermediate hidden states from previous layers to forecast whether token tt warrants deep computation at layer ll. Because the predictor relies exclusively on historical activations xtx_{\le t}, routing remains strictly causal at inference time.

IsoFLOP Scaling Analysis and Empirical Results

To evaluate whether dynamic compute allocation outperforms static scaling, Raposo et al. evaluated MoD models under compute-optimal training frameworks following the Chinchilla scaling laws (Hoffmann et al., 2022).

Under strict IsoFLOP comparisons (matching total training floating-point operations precisely across baselines and experimental models):

  • Loss Parity with 50% Compute: An MoD Transformer configured with capacity factor C=0.5C = 0.5 matches the validation loss of a standard dense Transformer while consuming 50% fewer FLOPs per forward pass in the routed layers.
  • Superior IsoFLOP Performance: When trained with an identical total FLOP budget, an MoD model can be scaled to a larger baseline parameter footprint. The larger, sparsely routed model achieves lower validation loss and higher benchmark accuracy than the compute-optimal dense baseline.
  • Inference Speedups: During generation, skipping 50% to 87.5% of layer computations reduces key-value (KV) cache memory access overhead and Tensor Core activation load, producing measurable latency reductions in high-throughput inference engines.

Hardware and Execution Mechanics

Deploying Mixture-of-Depths in production environments requires specific kernel handling to avoid hardware underutilization:

  1. Static Shape Guarantees: Because capacity k=CTk = \lfloor C \cdot T \rfloor is fixed prior to layer execution, memory allocation for intermediate activation buffers remains completely static. Unlike dynamic thresholding, MoD avoids GPU memory reallocation and tensor shape thrashing.
  2. Gather/Scatter Overhead: Selected tokens must be gathered into contiguous memory blocks before entering high-performance fused GEMM and attention kernels (e.g., FlashAttention), and scattered back to the residual tensor afterward. Efficient CUDA implementations fuse index gathering into the input projection kernel to hide memory latency.
  3. KV Cache Compression: For tokens that bypass self-attention layers, new key and value projections do not need to be written to GPU high-bandwidth memory (HBM). This reduces KV cache footprint for non-participating token positions.

Mixture-of-Depths demonstrates that the uniform FLOP allocation of standard Transformers is computationally inefficient. By combining explicit capacity budgets with learned routing, MoD provides a principled architectural mechanism for non-uniform compute distribution in large language models.

Sources

Written by

More to read

  • Agentic Memory and Context Management Systems in Production: Comparing Letta, Zep, Mem0, and LangMem

    Agentic Memory and Context Management Systems in Production: Comparing Letta, Zep, Mem0, and LangMem Stateless large language model APIs present a fundamental bottleneck for autonomous agents operating across extended multi-turn sessions: context window exhaustion, quadratic attention overhead, and memory drift. While standard Retrieval-Augmented Generation (RAG) retrieves static document chunks based on semantic similarity, autonomous agents require dynamic, stateful memory capable of updating

    1 min
  • South Korea Launches AI for All Initiative Treating Frontier Models as Public Utilities

    South Korea's Ministry of Science and ICT (MSIT) has launched the "AI for All" initiative, a government-sponsored project aimed at deploying nationwide, free-tier access to artificial intelligence chatbots and public administrative agents. The initiative structures generative AI capabilities and agent workflows as public utilities, establishing a subsidized access model for South Korean citizens. Consortia and Public Bidding Six major commercial consortia submitted bids to operate the public

    1 min
  • LLM Evaluation and Automated Testing Frameworks in Production: Comparing Ragas, DeepEval, Promptfoo, and TruLens Architecture, Synthetic Testsets, LLM-as-a-Judge Economics, and CI/CD Pipelines

    Evaluating large language model applications in production requires transitioning from subjective manual spot-checking to automated, reproducible testing pipelines. Unlike traditional software unit tests where deterministic inputs produce exact expected outputs, LLM-driven applications exhibit non-deterministic generation, complex multi-hop retrieval dynamics, and open-ended tool interactions. Deploying updates to prompts, retrieval parameters, embedding models, or base LLM checkpoints introduc

    1 min