MoE Model Deployment in Practice: A Checklist for Deployment and Evaluation
This checklist covers the engineering steps for deploying Mixture-of-Experts (MoE) models. It explains how to estimate parameters, memory, and compute, implement gating and load balancing, choose attention methods for long contexts, and plan deployment and load testing on heterogeneous clusters. It also lists the metrics to monitor and the order for troubleshooting.
1. Parameter, Memory, and Compute Estimation
Verify the source of every number before you estimate. Total parameter count, active parameter count, layer count, head count, and similar values should come from the official technical report or model card. Numbers without a source should not appear in a design document.
MoE models have two parameter metrics that are easy to confuse:
- Total parameters: These determine the memory needed for weights. The weights of all experts must be stored in memory on the devices that hold them, even though a single inference step activates only a subset.
- Active parameters: These determine the compute per token. As a rule of thumb, a forward pass costs about 2 × active parameters floating-point operations (FLOPs) per token.
The common estimation formulas are below. All units are bytes or FLOPs.
- Weight memory ≈ total parameters × bytes per parameter ÷ number of expert-parallel shards. Shared layers (attention and embedding layers) are typically replicated under pure expert parallelism and are not divided. Calculate them separately.
- KV cache = 2 × layers × KV heads × head dimension × sequence length × bytes per element.
- Forward compute per token ≈ 2 × active parameters.
The following hypothetical values illustrate the calculation only: 100 billion total parameters, 10 billion active parameters, BF16 storage (2 bytes per parameter), 48 layers, 8 KV heads, and 128 dimensions per head.
- Weights (unsharded, in decimal GB): about 200 GB in BF16, 100 GB in INT8, and 50 GB in INT4.
- Forward compute per token: 2 × 10^10 FLOPs, or about 20 GFLOPs.
- KV cache for one 128K-token sequence: 2 × 48 × 8 × 128 × 131072 × 2 bytes ≈ 25.77 GB.
These figures exclude activations, working buffers, and communication buffers. Actual memory requirements are higher.
Memory checklist:
- Read the layer count, hidden size, attention head count, KV head count, expert count, and number of active experts per token from the config file (such as config.json). Field names differ across frameworks, so check each one.
- Calculate the memory for weights, KV cache, and activations by hand using the formulas above.
- Load the model in the target framework. Record idle memory and peak memory, and compare them with your hand calculations.
- If the gap is large (use 10% as the review threshold), check whether the KV cache is preallocated for the maximum length. Also check whether working buffers, communication buffers, and memory fragmentation are counted.
- If you use INT4, confirm that the target hardware has a matching quantization kernel. Measure the throughput loss from dequantization.
2. Gating and Load Balancing Implementation Notes
The gate’s expert weights must be normalized. The Top-K weights should sum to 1. Otherwise, the output magnitude changes with the number of active experts. When tokens are dropped because they exceed expert capacity, renormalize the weights of the remaining experts. Otherwise, the output magnitude shifts in the same way.
The code below is a simplified teaching implementation. It loops over tokens one at a time, so its performance is poor, and it is not suitable for production. Production systems should use grouped matrix multiplication or fused operators.
import torchimport torch.nn.functional as Fdef moe_forward(x, gate, experts, k=2, capacity_factor=1.25):# x: [T, d], T tokensT, E = x.size(0), len(experts)probs = F.softmax(gate(x), dim=-1) # [T, E]topk_p, topk_idx = torch.topk(probs, k, dim=-1) # [T, k]# Allocate capacity in token order. (token, expert) pairs over capacity are dropped.capacity = int(capacity_factor * T * k / E)counts = [0] * Ekeep = torch.zeros_like(topk_p, dtype=torch.bool)for t in range(T):for j in range(k):e = topk_idx[t, j].item()if counts[e] < capacity:counts[e] += 1keep[t, j] = True# Renormalize weights only over the experts that were keptw = topk_p * keepw = w / w.sum(dim=-1, keepdim=True).clamp_min(1e-9)out = torch.zeros_like(x)for t in range(T):for j in range(k):if keep[t, j]:e = topk_idx[t, j].item()out[t] += w[t, j] * experts[e](x[t:t+1]).squeeze(0)# The return value excludes the residual. Tokens whose experts were all dropped output 0,# so the caller's residual connection (x + moe_forward(x)) preserves the original information.return out
Training usually adds an auxiliary load-balancing loss. This keeps a few experts from being selected repeatedly while others sit nearly idle. When you implement it, note the following:
topk_idxmust be oflongtype and on the same device asrouter_probs.dispatch.scatter_(1, topk_idx, 1.0)sets the position of each expert selected for each token to 1. This forms a one-hot dispatch matrix.- The auxiliary loss coefficient
alphacommonly starts at 0.01. Adjust it based on the expert load distribution during training.
During inference, monitor the following metrics:
- Expert hit ratio: The share of total dispatches received by each expert. Under uniform routing, each expert’s ratio is close to 1/E.
- Drop rate: The share of total dispatches dropped for exceeding expert capacity.
- Skew multiple: The ratio of an expert’s hit ratio to the average. Use 2× as the initial alert threshold, and judge it together with how long the condition lasts.
If an expert consistently receives several times the average number of requests, the device that hosts it becomes a bottleneck. This usually has one of three causes: routing that differs from training, a request distribution that differs substantially from the training data, or a model version that does not match its routing weights.
3. Long Context: Attention Trade-offs
Standard attention compute grows quadratically with sequence length n. Without a fused kernel, the memory for the attention score matrix also scales with n². KV cache memory grows linearly with n. Fused attention kernels avoid materializing the full n×n score matrix, but compute still grows quadratically.
The trade-offs among three common approaches are shown below.
| Approach | Compute growth with length | KV cache memory | Exact retrieval ability | Main cost |
|---|---|---|---|---|
| Full attention | Quadratic | Grows linearly | Strongest | Memory and compute grow quickly with length |
| Linear attention | Linear | Fixed state size | Usually weaker | Compresses history into a fixed-size state, losing detail |
| Sparse attention | Lower than full attention | Depends on the retention strategy | Depends on the selection mechanism | Requires sliding windows, chunking, or Top-K selection, and the selection itself has overhead |
Selection steps:
- Determine the maximum context length the application requires.
- Use the KV cache formula to calculate the memory one request needs at that length.
- Estimate concurrency as the memory available for KV cache divided by the KV memory per request.
- Run a retrieval test at the target length. For example, insert a specific value into a long document and ask the model to retrieve it. Report accuracy separately for insertions at the beginning, middle, and end, so that an average does not hide weak positions.
- If concurrency does not meet business needs, evaluate sparse or hybrid approaches. Use the retrieval results from step 4 as the acceptance criterion.
4. Heterogeneous Cluster Deployment and Load Testing Troubleshooting Checklist
Choose the parallelism strategy based on communication patterns. Expert parallelism (EP) generates all-to-all communication. Tensor parallelism (TP) triggers frequent all-reduce operations within each layer. Pipeline parallelism (PP) mainly passes activations between layers. A common practice is to place the most communication-intensive parallel dimension within a single node connected by high-speed interconnect, so cross-node traffic stays small. Validate this principle on the target cluster.
Considerations for heterogeneous clusters, meaning clusters with different GPU models, memory capacities, or interconnect bandwidths:
- Do not split layers or experts evenly by node count. Allocate them according to memory capacity and compute power.
- After deployment, check each GPU’s memory usage and compute utilization. Confirm that no device is noticeably idle or overloaded.
- Avoid placing frequently used experts on nodes with low cross-node bandwidth.
Load test metrics:
- TTFT (time to first token): The time from request arrival to the first output token.
- TPOT (time per output token): The average time per generated token during the generation phase.
- Throughput: The number of tokens generated per second. Report it together with the input and output length distributions.
- P95/P99 latency: Tail latency. It reflects user experience better than averages do.
- Peak memory and KV cache utilization: Check whether they are approaching their limits.
- Expert hit ratio, drop rate, and skew multiple: See Section 2.
- All-to-all communication time share: The proportion of each step’s time spent on all-to-all communication.
Load test method:
- Use the input and output length distribution of real requests, not fixed-length synthetic data.
- Ramp up load in steps. Hold each concurrency level long enough for stable operation, and record where throughput and latency begin to inflect
