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 independent expert FFNs and a lightweight learned router that activates only experts per token.
From a Data Structures and Algorithms perspective, MoE routing is a constrained parallel dispatch problem: given a batch of tokens and distributed expert queues, assign each token to its highest-affinity 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 and a router projection matrix , the router computes unnormalized logits .
Two ordering choices exist in production kernels:
- Softmax-then-TopK: Compute over all experts, select the top indices, and optionally renormalize their weights to sum to .
- TopK-then-Softmax: Select the top logits first, then apply only over those values. This is slightly faster and avoids vanishing gradients when is large (e.g., or ).
For , the expert output for token is a sparse convex combination:
Because only experts execute per token, FFN FLOPs drop from to —roughly a 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 :
where: - is the number of tokens in the micro-batch (or sequence chunk), - is the active experts per token, - is the total number of experts, - is the Capacity Factor (typically to during training, to during inference).
When more than tokens select expert , the first tokens (by batch order or highest router confidence) fill expert 's buffer. Any remaining tokens overflow and are either dropped (passed through via the residual connection unchanged) or rerouted to their secondary expert if .
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:
where: - is the actual fraction of tokens dispatched to expert (non-differentiable), - is the mean router probability assigned to expert (differentiable), - is a scalar hyperparameter (typically ).
Because and , minimizing under the Cauchy-Schwarz inequality drives both vectors toward the uniform distribution and , achieving a minimum of .
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.
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 or vectorized GPU operations:
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:
- 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 so the highest-confidence tokens win buffer slots.
- Aux-Loss-Free Dynamic Bias: Rather than adding to the backpropagation graph—which introduces gradient conflict with cross-entropy—maintain a non-differentiable per-expert bias added to logits before
TopK: . After each step, decrease by for overloaded experts and increase it for underloaded experts. - Dropless MoE (MegaBlocks): Replace fixed-capacity padded tensors with block-sparse matrix multiplication (
dSD/dDSkernels), packing variable-length expert queues into contiguous tiles with zero dropped tokens. - Shared / Always-On Experts: Dedicate or small dense experts that process every token unconditionally, ensuring common syntactic and reasoning patterns never suffer from routing capacity limits.
Complexity Analysis
| Stage | Time Complexity | Memory / Comm Complexity | Notes |
|---|---|---|---|
| Router Projection () | Negligible vs FFN () | ||
| Top-K Selection | Partial sort / warp-level bitonic select | ||
| All-to-All Dispatch | per rank | Bounded by interconnect bandwidth (NVLink / RoCE) | |
| Expert FFN Execution | Active FLOPs scale with , not |
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 routing, dynamic bias balancing, and block-sparse or priority-retained buffers keeps active FLOPs flat while preserving dense-model convergence quality.
