Skip to content

Balance MoE expert placement ​

Use redundant expert slots and recorded routing load to balance mixture-of-experts (MoE) traffic. Choose a static placement derived from a profile, or rebalance the placement while serving.

For parameter defaults and valid values, see expert placement parameters.

Static expert placement with redundant experts ​

Real routing is skewed: a few experts of a layer draw many times their uniform share of routes, and the rank holding them carries the layer's critical path. For each MoE layer, --ep-num-redundant-experts R adds R redundant slots to the E logical routed experts, for P = E + R physical expert slots. Each rank holds P / ep_size slots. The expert placement maps each physical slot to a logical expert, which lets TokenSpeed replicate hot experts across ranks.

TokenSpeed derives the placement from recorded load with DeepSeek's Expert Parallelism Load Balancer (EPLB) algorithm. It can derive the placement once at startup from a profile record or online from live counters. For the online procedure, see dynamic expert rebalancing on this page.

Check model and parallelism support ​

Models opt in explicitly through supports_expert_placement on the model class. Each supported model builds its MoE layers from the placement and loads every placed slot. Expert parallelism (EP) distributes those slots across ranks. The supported configurations are:

  • LongCat-Flash: Supports static placement and online rebalancing.
  • Inkling2: Supports static placement only. It does not expose its expert weights to --enable-eplb.
  • Kimi-K3: Supports static placement with attention data parallelism (DP) and EP-only MoE. Use MegaMoE or all-to-all/all-gather dispatch to the local MoE. This path requires static dispatch and supports neither load recording nor online rebalancing.
  • DeepSeek-V4.1-Flash: Supports static placement and online rebalancing with attention tensor parallelism (TP) 1, MoE TP 1, MegaMoE, and --ep-dispatch-algorithm static.

TokenSpeed refuses the placement flags for any other model, so it never installs a placement only to ignore it.

Redundant experts require EP, with ep_size > 1, because replicas live on other ranks. Redundant slots also support an EP size that does not divide the routed experts. For example, Kimi-K3's 896 experts run at EP20 with --ep-num-redundant-experts 4: 900 slots, 45 per rank.

Record and apply a static placement ​

To record and apply a static placement, follow these steps:

  1. Record the load of a representative workload. Start the server with --expert-distribution-recorder-mode stat --ep-dispatch-algorithm static_with_zero_expert. For models without zero experts, use static instead. The router counts every route into a per-layer, per-physical-expert counter on the device, and the EXPERT_LOAD profile activity frames the window.

    Only real tokens count. A padded replay, such as a decode graph at a ladder batch size, a prefill graph at a bucket, or an idle attention-DP rank, feeds filler rows through the MoE layers. The graph owners mark those rows in a device-side live-row mask before the replay and clear it afterward, so the counters see traffic, not padding. Startup forwards, including autotune, warm-up, and graph capture, are not traffic either. The runtime zeroes the counters after capture, so the first profile or rebalance window starts at the first served forward.

    Start a profile with the EXPERT_LOAD activity and an output_dir through the engine's ProfileReq control operation. The frontend driving the engine sends this operation. Under ts serve, call the gateway's POST /start_profile endpoint with a JSON body such as:

    json
    {
      "activities": ["EXPERT_LOAD"],
      "output_dir": "/tmp/expert-load"
    }

    Replace /tmp/expert-load with your record directory. Serve the workload, and then call POST /stop_profile.

    Stopping writes one record per rank, <id>-<rank tag>.expert-load.pt. Confirm that the expected records appear in the output directory. Each record holds what that rank's router counted:

    • physical_count: Per-slot counts with shape [layers, slots] and type int64.
    • logical_count: The counts summed over each logical expert's replicas, with shape [layers, routed experts].
    • physical_to_logical_map: The placement that produced the counts.
    • ep_rank and ep_size: The rank's position and the size of its EP group.

    The serving path deliberately does not reduce the records. A profile stop reaches attention-DP workers independently, and a rank running a collective inside the request would wait on a peer still synchronizing its scheduling round. When merge_expert_load_records consumes the records, it sums them over the EP group. Under all-to-all EP, every rank counted its own tokens, so the merge needs every rank's record. Under replicated-input EP, every rank counted every token, so one record is complete. Merging more records only scales the counts uniformly, which does not affect the placement algorithm.

  2. Derive and load the placement. Restart with the redundant slots and the recorded load. Point --init-expert-location at the record directory or a glob to merge the records. Records with [windows, layers, experts] logical counts retain matching windows across ranks. Different window counts or a mix with [layers, experts] records are combined using per-expert totals.

    Add the following flags to the server launch. This command fragment uses /tmp/expert-load as the record directory; replace that path with your directory or glob:

    bash
    --ep-num-redundant-experts 128 \
    --init-expert-location /tmp/expert-load \
    --ep-dispatch-algorithm static_with_zero_expert

    P must be divisible by the EP size. For example, LongCat 2.0 uses 768 + 128 = 896 slots at EP128, or 7 per rank. The loader fills every local slot from the logical expert that the placement assigns to it. Each replica receives the checkpoint tensor. Reinforcement learning (RL) weight synchronization through the same path also fills every placed replica.

    --init-expert-location also accepts a single record file and uses its logical_count alone. A file holding only a physical_to_logical_map pins a placement exactly. --eplb-algorithm selects the balancing algorithm; auto picks the hierarchical variant when the model's expert groups divide over the nodes. When you compare placements, compare the merged record's per-layer balancedness: mean rank load divided by the busiest rank's load.

    For this directory-based example, confirm that the startup log reports an EPLB placement from the expected number of merged expert load records.

Replica selection for static placements ​

The router emits physical IDs. Zero experts (LongCat) stay -1 and never enter the tables. How a route picks among an expert's replicas follows the MoE kernel:

  • Under all-to-all EP (DeepEP), each rank routes only its own tokens. Every rank dispatches to its nearest replica through a static per-rank map: first a replica on the same GPU, then one on the same node, and otherwise a seeded fair draw. The EP group's actual ranks determine the nodes. --ep-dispatch-algorithm static* selects this behavior; the dynamic* variants draw at random per route. The runtime computes the map only on this path.
  • Under replicated-input EP, every rank routes every token, such as on the rl-bitwise slot-combine path. Exactly one rank must compute each route, so the replica is a pure function of the token: replicas[logical, (token row + route rank) mod replicas], identical on every rank. TokenSpeed refuses random replica choice on this path.

Under --numerics rl-bitwise, the placement must be deterministic, so use static algorithms only. The MoE output remains a pure function of the token and its routes, so a placed server stays bitwise aligned with the trainer.

A placement is only as good as the recorded distribution's match to the traffic it serves: record on production traffic and re-derive when it drifts. Decode benefit depends on the kernel being row-bound. Where a grouped GEMM streams every touched expert regardless of row count (small decode batches), balancing the rows changes little.

DeepSeek V4.1 with DSpark ​

With online EPLB, V4.1 hashes each local token row and its EP rank to a replica and counts live routes. When you use its DSpark draft, choose explicitly whether to rebalance it. --eplb-balance-draft starts the draft with a trivial placement and gives it its own redundant slots, staging buffer, and apply chunks. --no-eplb-balance-draft keeps the draft on its ordinary layout. Offline EXPERT_LOAD profiles record the target.

Dynamic expert rebalancing ​

--enable-eplb re-derives the placement while serving and moves the expert weights to match. The placement can then follow drifts in the traffic's expert distribution without a restart.

To enable and verify online rebalancing, follow these steps:

  1. Add the online rebalancing flags to the server launch. The following LongCat command fragment adds 128 redundant slots, takes a snapshot every 10,000 forwards, and moves at most four MoE layers per scheduling round. Adjust these values for your deployment:

    bash
    --enable-eplb \
    --ep-num-redundant-experts 128 \
    --expert-distribution-recorder-mode stat \
    --ep-dispatch-algorithm static_with_zero_expert \
    --eplb-rebalance-num-iterations 10000 \
    --eplb-rebalance-layers-per-chunk 4
  2. Serve traffic and inspect the engine log. Confirm that the log contains Expert rebalance entries for the snapshot, committed placement, and completed apply. The snapshot entry reports the observed balancedness, and the committed-placement entry reports the balancedness expected from the new placement.

Rebalance timing and manual triggers ​

--eplb-window-size W sets the number of forwards sampled per snapshot. The runtime takes the first snapshot after W forwards, then takes a snapshot every --eplb-rebalance-num-iterations N forwards using the most recent W forwards. By default, W = N. Real and DP-idle forwards both count. The runtime derives a new placement from those routes, and the weights move.

--eplb-rebalance-layers-per-chunk L bounds the stall that each scheduling round pays. The rebalance switches the model's MoE layers L per round, moving each layer's weights first and its routing tables immediately after. A forward therefore never sees a layer whose tables and slots disagree.

TokenSpeed allows --ep-num-redundant-experts 0: the rebalance then only permutes experts across ranks. --init-expert-location still seeds the first placement.

The RebalanceExpertsReqInput control operation starts one rebalance with weights resident on all ranks. A full-window trigger snapshots immediately. With a short window, it opens a sample or waits for the remaining forwards. A missed deadline starts a fresh window after the previous rebalance.

TokenSpeed refuses the EXPERT_LOAD profile activity under --enable-eplb because the rebalance owns the same counters.

Rebalance stages ​

Each rebalance proceeds through the following stages:

  1. Snapshot. The runtime copies the counters to the host and zeroes them in one step on the execution stream, so the window boundary is exact at forward granularity. Logical counts credit the expert owning each slot at dispatch, even when a window spans a placement switch. Under replicated-input EP, every rank routes every token, so each rank's counters already are the group load. The runtime compares the ranks' checksums. A difference means the ranks routed differently within a forward, which is a correctness bug, so the server fails rather than average the difference away. Under all-to-all EP (DeepEP), each rank counted its own tokens, and the runtime sums the load over the EP group.
  2. Compute and commit. EP rank 0 derives the placement on a solver thread. After 200 more forwards, it broadcasts the result over the EP group, and every rank plans the same slot moves from the old and new rows. Only the [layers, slots] map crosses the wire. Each rank rebuilds the inverse tables locally.
  3. Apply, one chunk per round. Each rank receives every incoming slot into a staging buffer reserved at startup and sends every outgoing slot from its live tensor in one batched peer-to-peer (P2P) operation over the EP group. The buffer holds one layer per participating model and is reserved before startup sizes the key-value (KV) arena. A same-GPU move goes through staging too, and a slot that needs an expert an earlier local slot just received copies it from there. Both ends order the P2P operation by logical expert ID, so the pairs match on every rank by construction. The rebalance prefers a same-node source and spreads destinations evenly over the sources. The processed parameters move as bytes, including quantized weights and scales, so the rebalance re-derives nothing.

Coordination and numerical invariants ​

Snapshot, commit, and apply each run through the same attention-DP same-round gate as the RL weight ops, so all ranks switch a layer in the same round and a weight update can never interleave with a chunk. A weight update and a chunk are both blocking device ops, one per round. A weight update between chunks lands in the current placement: the loader reads the live map, and the pending chunks copy whatever the source slots hold. An idle engine takes no snapshot because the counter is frozen, and a pending commit waits for forwards. The engine refuses a memory-saver release while a rebalance is in progress.

The routing path is unchanged: slot ownership stays contiguous per rank, the replica choice is a pure function of the token, and a placement change alters only table entries and slot contents. Under --numerics rl-bitwise, the MoE combine must be placement-independent (slot-order combine) for the output to stay bitwise identical across a rebalance. The envelope folds --moe-combine-order slot in, so it accepts the combination. For more information, see the numerics design.

TokenSpeed documentation