Data Structures and Algorithms4 min read

Top-K Gating, Expert Capacity, and Load-Balancing Algorithms in 1T+ Mixture-of-Experts Models

An algorithmic deep dive into 1T+ Mixture-of-Experts routing—covering Top-K softmax gating, expert capacity factor, auxiliary load-balancing loss, and token-dropping mitigation with TypeScript and Python implementations.

Modern 1T+ Mixture-of-Experts (MoE) architectures—such as 1.1T total / 55B active parameter models—achieve sub-linear FLOPs per token by routing each token to only K experts (typically K=2) via Top-K softmax gating, enforcing static tensor shapes with an Expert Capacity Factor, penalizing routing skew with a differentiable auxiliary load-balancing loss, and mitigating token drops through capacity-aware routing or residual fallback.

Key takeaways

  • MoE routing is fundamentally a constrained online dispatch problem: maximize affinity score while keeping per-shard queue lengths below hardware buffer capacity C.
  • Choosing K=2 over K=1 doubles router dispatch fan-out but provides a natural backup path when an expert's primary queue overflows.
  • Replacing or augmenting auxiliary loss with dynamic per-expert bias terms prevents gradient interference between language modeling loss and load balancing.

Quick facts

  • Top-K gating selects only K of N experts per token, reducing per-token FFN compute from O(N * d^2) to O(K * d^2).
  • Expert capacity C = ceil((T * K / N) * capacity_factor) bounds each expert's batch buffer for static TPU/GPU compilation.
  • Switch/GShard auxiliary loss L_aux = alpha * N * sum(f_i * P_i) pushes token distribution toward uniform load.
  • Token dropping occurs when an expert's queue exceeds C; aux-loss-free bias updates and capacity overflow routing minimize quality degradation.

Scaling a dense Transformer past 100 billion parameters forces every token through every weight matrix, locking compute cost to total parameter count. Modern 1T+ Mixture-of-Experts (MoE) architectures—exemplified by 1.1T-total / 55B-active parameter designs such as Amazon Ergo-1.0—break this coupling. Each Transformer block replaces the monolithic Feed-Forward Network (FFN) with NN independent expert FFNs and a lightweight learned router that activates only K≪NK \ll N experts per token.

From a Data Structures and Algorithms perspective, MoE routing is a constrained parallel dispatch problem: given a batch of TT tokens and NN distributed expert queues, assign each token to its highest-affinity KK experts without triggering routing collapse (all tokens piling onto 1-2 experts) or buffer overflow (dropped tokens).

Top-K Softmax Gating Mechanics

Given a token hidden state x∈Rdx \in \mathbb{R}^d and a router projection matrix Wg∈Rd×NW_g \in \mathbb{R}^{d \times N}, the router computes unnormalized logits h=xWg∈RNh = x W_g \in \mathbb{R}^N.

Two ordering choices exist in production kernels:

  1. Softmax-then-TopK: Compute p=softmax(h)p = \text{softmax}(h) over all NN experts, select the top KK indices, and optionally renormalize their weights to sum to 11.
  2. TopK-then-Softmax: Select the top KK logits first, then apply softmax\text{softmax} only over those KK values. This is slightly faster and avoids vanishing gradients when NN is large (e.g., N=64N = 64 or N=128N = 128).

For K=2K = 2, the expert output for token tt is a sparse convex combination:

yt=∑e∈TopK(ht,K)gt,e⋅Ee(xt)y_t = \sum_{e \in \text{TopK}(h_t, K)} g_{t,e} \cdot E_e(x_t)$$y_t = \sum_{e \in \text{TopK}(h_t, K)} g_{t,e} \cdot E_e(x_t)$$

Because only KK experts execute per token, FFN FLOPs drop from O(N⋅d⋅dff)O(N \cdot d \cdot d_{ff}) to O(K⋅d⋅dff)O(K \cdot d \cdot d_{ff})—roughly a 20×20\times reduction in active compute for a 1.1T / 55B-active model.

Expert Capacity Factor and Token Dropping

Distributed accelerators (GPUs and TPUs) rely on static tensor shapes for All-to-All collective communication. An expert shard cannot dynamically allocate a variable-length array without padding overhead or kernel recompilation.

To enforce fixed memory bounds, each expert is assigned a static capacity CC:

C=⌈T⋅KN⋅CF⌉C = \left\lceil \frac{T \cdot K}{N} \cdot \text{CF} \right\rceil$$C = \left\lceil \frac{T \cdot K}{N} \cdot \text{CF} \right\rceil$$

where: - TT is the number of tokens in the micro-batch (or sequence chunk), - KK is the active experts per token, - NN is the total number of experts, - CF≥1.0\text{CF} \ge 1.0 is the Capacity Factor (typically 1.01.0 to 1.51.5 during training, 1.251.25 to 2.02.0 during inference).

When more than CC tokens select expert ee, the first CC tokens (by batch order or highest router confidence) fill expert ee's buffer. Any remaining tokens overflow and are either dropped (passed through via the residual connection xtx_t unchanged) or rerouted to their secondary expert if K=2K=2.

Top-2 MoE Router: Balanced vs Overflowed Expert Queues
Tokens route to Top-2 experts. When Expert 2 exceeds capacity C=3, excess tokens overflow and fall back to residual pass-through or secondary routing.

Auxiliary Load-Balancing Loss

Without an explicit balancing term, gradient descent reinforces a positive feedback loop: an expert that happens to get slightly better early gradients receives more tokens, trains faster, and attracts even more tokens—collapsing the model to a tiny subset of experts.

The standard differentiable penalty from GShard and Switch Transformer is the auxiliary load-balancing loss:

Laux=α⋅N∑i=1Nfi⋅Pi\mathcal{L}_{\text{aux}} = \alpha \cdot N \sum_{i=1}^{N} f_i \cdot P_i$$\mathcal{L}_{\text{aux}} = \alpha \cdot N \sum_{i=1}^{N} f_i \cdot P_i$$

where: - fi=1T∑t=1TI(token t routed to expert i)f_i = \frac{1}{T} \sum_{t=1}^{T} \mathbb{I}(\text{token } t \text{ routed to expert } i) is the actual fraction of tokens dispatched to expert ii (non-differentiable), - Pi=1T∑t=1Tpt,iP_i = \frac{1}{T} \sum_{t=1}^{T} p_{t,i} is the mean router probability assigned to expert ii (differentiable), - α\alpha is a scalar hyperparameter (typically 10−210^{-2}).

Because ∑fi=K\sum f_i = K and ∑Pi=1\sum P_i = 1, minimizing ∑fiPi\sum f_i P_i under the Cauchy-Schwarz inequality drives both vectors toward the uniform distribution (KN,…,KN)\left(\frac{K}{N}, \dots, \frac{K}{N}\right) and (1N,…,1N)\left(\frac{1}{N}, \dots, \frac{1}{N}\right), achieving a minimum of α⋅K\alpha \cdot K.

Algorithmic Walkthrough in Python (PyTorch-Style) and TypeScript

Below is a clean, self-contained TypeScript implementation of Top-K routing with static capacity tracking and auxiliary loss calculation, followed by the equivalent PyTorch-style vectorized dispatch logic.

TYPESCRIPT
export interface DispatchResult {
  expertQueues: number[][]; // token indices assigned per expert
  droppedTokens: number[];  // tokens that exceeded capacity
  auxLoss: number;
}

export function routeTopKWithCapacity(
  logits: number[][], // shape [T, N]
  k: number,
  capacityFactor: number,
  alpha = 0.01
): DispatchResult {
  const T = logits.length;
  const N = logits[0]?.length ?? 0;
  const capacity = Math.ceil(((T * k) / N) * capacityFactor);

  const probs = logits.map((row) => {
    const maxLogit = Math.max(...row);
    const exps = row.map((v) => Math.exp(v - maxLogit));
    const sum = exps.reduce((acc, v) => acc + v, 0);
    return exps.map((v) => v / sum);
  });

  const expertQueues: number[][] = Array.from({ length: N }, () => []);
  const droppedTokens: number[] = [];
  const dispatchCounts = new Array<number>(N).fill(0);
  const probSums = new Array<number>(N).fill(0);

  for (let t = 0; t < T; t++) {
    for (let e = 0; e < N; e++) probSums[e] += probs[t][e];

    const topExperts = probs[t]
      .map((p, e) => ({ e, p }))
      .sort((a, b) => b.p - a.p)
      .slice(0, k);

    for (const { e } of topExperts) {
      dispatchCounts[e] += 1;
      if (expertQueues[e].length < capacity) {
        expertQueues[e].push(t);
      } else {
        droppedTokens.push(t);
      }
    }
  }

  let dotProduct = 0;
  for (let e = 0; e < N; e++) {
    const f_i = dispatchCounts[e] / T;
    const P_i = probSums[e] / T;
    dotProduct += f_i * P_i;
  }

  return {
    expertQueues,
    droppedTokens,
    auxLoss: alpha * N * dotProduct,
  };
}

In Python/PyTorch, the same dispatch avoids Python loops by sorting expert_mask indices or using torch.topk + torch.cumsum to assign buffer slot positions in O(Tlog⁡N)O(T \log N) or O(T⋅N)O(T \cdot N) vectorized GPU operations:

PYTHON
def aux_load_balancing_loss(probs, topk_indices, num_experts: int, alpha: float = 0.01):
    # probs: [T, N], topk_indices: [T, K]
    T = probs.shape[0]
    one_hot = F.one_hot(topk_indices, num_classes=num_experts).float()  # [T, K, N]
    f_i = one_hot.sum(dim=(0, 1)) / T  # [N]
    P_i = probs.mean(dim=0)            # [N]
    return alpha * num_experts * torch.sum(f_i * P_i)

Token-Dropping Mitigation Strategies

Dropping tokens hurts perplexity on rare syntax, code tokens, and long-tail entities. Modern 1T+ MoE training pipelines apply four complementary mitigations:

  1. Priority-Based Capacity Retention: Instead of First-Come-First-Served (which systematically drops tokens near the end of a sequence), sort tokens within each expert's candidate list by their router probability pt,ep_{t,e} so the highest-confidence tokens win buffer slots.
  2. Aux-Loss-Free Dynamic Bias: Rather than adding Laux\mathcal{L}_{\text{aux}} to the backpropagation graph—which introduces gradient conflict with cross-entropy—maintain a non-differentiable per-expert bias beb_e added to logits before TopK: ht,e′=ht,e+beh'_{t,e} = h_{t,e} + b_e. After each step, decrease beb_e by γ\gamma for overloaded experts and increase it for underloaded experts.
  3. Dropless MoE (MegaBlocks): Replace fixed-capacity padded tensors with block-sparse matrix multiplication (dSD / dDS kernels), packing variable-length expert queues into contiguous tiles with zero dropped tokens.
  4. Shared / Always-On Experts: Dedicate 11 or 22 small dense experts that process every token unconditionally, ensuring common syntactic and reasoning patterns never suffer from routing capacity limits.

Complexity Analysis

StageTime ComplexityMemory / Comm ComplexityNotes
Router Projection (xWgx W_g)O(T⋅d⋅N)O(T \cdot d \cdot N)O(T⋅N)O(T \cdot N)Negligible vs FFN (N≪dffN \ll d_{ff})
Top-K SelectionO(T⋅Nlog⁡K)O(T \cdot N \log K)O(T⋅K)O(T \cdot K)Partial sort / warp-level bitonic select
All-to-All DispatchO(T⋅K⋅dP)O(\frac{T \cdot K \cdot d}{P}) per rankO(N⋅C⋅d)O(N \cdot C \cdot d)Bounded by interconnect bandwidth (NVLink / RoCE)
Expert FFN ExecutionO(N⋅C⋅d⋅dff)O(N \cdot C \cdot d \cdot d_{ff})O(N⋅d⋅dff)O(N \cdot d \cdot d_{ff})Active FLOPs scale with KK, not NN

At 1T+ total parameters, the primary systems bottleneck is rarely the router math itself—it is All-to-All communication and load-imbalance tail latency, where a single straggler expert stalls the entire synchronized step. Combining K=2K=2 routing, dynamic bias balancing, and block-sparse or priority-retained buffers keeps active FLOPs flat while preserving dense-model convergence quality.

Continue reading

Related dispatches across technical domains.