## Summary
Kimi-K3's attention-DP MoE path allowed routed EP only with attention TP
1 (DEP). This PR allows attention TP > 1 under attention DP when MoE TP
is 1 and `attention TP x DP == MoE EP == world size`. For example, a
16-GPU decode instance can hold two attention replicas of TP8 with KV
parallelism 8, with routed EP16 across both replicas:
```
--attn-tp-size 8 --data-parallel-size 2 --kv-parallel-size 8 \
--decode-context-parallel-size 8 --moe-tp-size 1 --expert-parallel-size 16
```
It stays one path for every attention TP size:
- Each attention-TP rank routes a disjoint, consecutive slice of its
replica's rows (`scatter_count`, in expert-parallel rank order). At
attention TP 1 the slice is the whole replica.
- The shared experts shard over the replica's attention-TP group and
read all of the replica's rows.
- A token reduce-scatter adds the shared partials onto the slices. A
token all-gather restores the replica's rows.
- The fused input projection, its packed weight and static expert
placement keep requiring attention TP 1.
- Transport is unchanged: FlashInfer all-to-all, the all-gather
fallback, or MegaMoE.
#4001 is merged; its commit is still the first one on this branch and
matches main, so please review commit 82eb424b9 only.
This PR overlaps #3838, which adds attention TP > 1 for MegaMoE only.
Coordinated with the author of #3838. #3838's MegaMoE-only guards are
replaced here by the general slice. One difference in the tail follows
from main's `KimiLinearMoEDeepEP`:
- DeepEP gathers the routed latent, shards the up projection by column
and all-reduces it with the shared output: AG(latent) + AR(hidden).
- This PR reduce-scatters the shared partials onto the slices, adds the
slice's routed output and gathers the rows: RS(hidden) + AG(hidden).
That is about one AR(hidden), so it skips DeepEP's extra latent gather.
In a decode profile of this layout with MegaMoE (below), all-reduce,
all-gather and reduce-scatter together take 3.0 ms of a 33.2 ms forward.
Masking CUDA-graph padding rows from routing, as DeepEP does, is left to
a follow-up. The attention TP 1 path on main does not mask them either.
## Results
Kimi-K3.1-Pro (MXFP4), GB300. The PD decode pool is 4 nodes (16 GPUs) in
each layout, and prefill is DWDP16 on 4 nodes. The workload is the
public agentic trace `semianalysisai/cc-traces-weka-062126` with sticky
routing, 30 minutes per point.
### MegaMoE (`--moe-backend mega_moe --all2all-backend none`), this
branch
GSM8K (1319, 5-shot) of EP16 + 2xDCP8 on this branch: 97.95% strict
match, 97.88% flexible extract.
Decode profile, 4 nodes aggregated, 96 requests of 72K prompt tokens, 30
decode forwards, mean ms per forward over ranks:
| | EP16 + 2xDCP8 | DEP16 |
|---|---|---|
| dense GEMMs | 9.0 | 20.8 |
| MegaMoE kernel (dispatch + experts + combine) | 12.9 | 15.7 |
| MegaMoE routing and top-k reduce | 1.9 | 3.0 |
| all-reduce / all-gather / reduce-scatter | 3.0 | 0 |
| attention | 2.6 | 2.5 |
| other | 3.8 | 3.7 |
| **forward** | **33.2** | **45.6** |
| median inter-token latency in the window | 27.9 | 38.4 |
Under DEP16 every rank reads the full attention and dense weights for
about six requests; attention TP8 shards those reads.
PD sweep (decode pool above, 30 minutes per concurrency point):
| concurrency | EP16 + 2xDCP8 output tok/s/GPU | DEP16 output tok/s/GPU
| EP16 + 2xDCP8 P90 interactivity | DEP16 P90 interactivity |
|---|---|---|---|---|
| 16 | 22.0 | 18.2 | 45.6 | 28.4 |
| 32 | 47.3 | 36.9 | 39.3 | 26.3 |
| 64 | 81.4 | 63.5 | 33.0 | 25.0 |
| 96 | 132.2 | 86.6 | 32.1 | 18.0 |
Output tok/s/GPU counts the 16 decode GPUs; interactivity is tok/s/user.
At concurrency 96, EP16 + 2xDCP8 gives 1.53x the throughput and 1.78x
the P90 interactivity of DEP16. Each point ran once.
### `flashinfer_trtllm` MoE, before this branch's rebase
With the FlashInfer all-to-all:
| layout | concurrency | output tok/s/GPU (decode GPUs) | P90
interactivity (tok/s/user) |
|---|---|---|---|
| EP16 + 2xDCP8 | 96 | 125.8 | 30.3 |
| DEP16 | 96 | 78.6 | 16.1 |
GSM8K (1319, 5-shot, strict match): EP16 + 2xDCP8 scores 97.88% and
DEP16 97.80%.
### Numerics
On a 12-layer subset (4 GPUs), the mean absolute logprob difference over
32 greedy requests is:
- attention TP2 x DP2 vs DEP4: 0.055 under MegaMoE and 0.054 under
trtllm.
- MegaMoE repeated runs: 0.002–0.006.
- This branch vs main at attention TP 1: 0.0054, which is within the
repeated-run range.
## Test Plan
- `test/runtime/test_kimi_k3_moe_attn_dp.py`:
- Every rank of two attention-TP2 replicas, including uneven,
fewer-rows-than-ranks and idle replicas, returns the replica's reference
output, and each row is routed exactly once.
- Route slices cover each replica.
- Layouts whose expert group does not span every attention rank are
rejected.
- Shared experts shard over the attention-TP group.
- Kimi-K3 runtime tests and the FlashInfer MXFP4 MegaMoE kernel test
pass on GB300.
- `pre-commit run --all-files` passes.
---------
Signed-off-by: Xiangyi Zhang <xiangyiz@nvidia.com>
Signed-off-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
Co-authored-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
66 KiB
Parallelism
TokenSpeed exposes familiar --tensor-parallel-size and --tp entry points
plus additional split parallelism controls for attention, dense, and MoE layers.
Scheduler process names in ps include their parallel ranks, for example
tokenspeed::scheduler_tp1_ep3_dp0. tp always identifies the attention TP
rank, including tp0 for a single process. Other suffixes appear only when
their parallel size exceeds one: ep for MoE expert parallelism, dp and
kvp for attention data and KV parallelism, and pp for pipeline
parallelism. These are zero-based ranks within their respective
groups, not parallel sizes.
Quick start
When the same tensor-parallel group is acceptable for the model, use this form:
tokenspeed serve <model> \
--tensor-parallel-size 8
--tensor-parallel-size maps to TokenSpeed attention tensor parallelism, and
you cannot combine it with --attn-tp-size.
Split parallelism
When different layer families need different process groups, use split knobs:
tokenspeed serve <model> \
--world-size 8 \
--attn-tp-size 4 \
--dense-tp-size 4 \
--moe-tp-size 4
| Parameter | Use |
|---|---|
--world-size |
Total worker processes across all nodes. |
--nprocs-per-node |
Worker processes launched on each node. |
--attn-tp-size |
Attention tensor parallel size. |
--dense-tp-size |
Dense layer tensor parallel size. Defaults to the attention TP width: the full world without DP attention, one replica with it. |
--moe-tp-size |
MoE layer tensor parallel size. |
--data-parallel-size |
Replicated data-parallel groups. |
--kv-parallel-size |
KV parallelism: shard the full-history KV pages over a consecutive subgroup of attention TP on an aggregated or PD engine (see "KV parallelism" below). |
--decode-context-parallel-size |
Decode context parallelism in aggregated or PD decode engines; required with and equal to --kv-parallel-size there. |
--query-context-parallel-size |
Query context parallelism: the prefill role's query-row sharding over the sharded pages; equal to --kv-parallel-size and --attn-tp-size (see "Query context parallelism" below). |
--mm-encoder-tp-mode |
weights (default), or TP1 whole-item DP within each attention TP group (data). |
--enable-expert-parallel |
Expert parallelism across the selected world size. |
--expert-parallel-size |
Explicit expert parallel size. |
Kimi-K3 TP8 deployments must combine --tensor-parallel-size 8 with
--mm-encoder-tp-mode data. This keeps the text model at TP8 while running the
wide-QKV MoonViT encoder at TP1 with whole-item DP8.
Decode-side TP layouts under attention DP
An MLA decode engine runs attention at TP1 with DP across the world: the
per-token latent KV cannot shard by heads, so every rank keeps its own KV.
That layout replicates every non-MoE weight on every rank: the MLA head
projections (q_b_proj, kv_b_proj, o_proj), the dense MLPs, and the LM
head. On a large model that is tens of GB per rank that could hold KV
instead. Three knobs shard those weights over contiguous groups of DP ranks
(one node, typically) while attention and the KV stay TP1/DP:
| Parameter | Use |
|---|---|
--attn-head-tp-size W |
Shard q_b_proj, kv_b_proj, and o_proj by heads over W contiguous ranks that hold different rows. Over DP ranks: requires attention TP 1, attention DP, W dividing the stage world, num_heads % W == 0, and a decode engine (--disaggregation-mode decode). Over the query shards of a prefill engine: W equal to --query-context-parallel-size (see Query context parallelism). |
--lm-head-tp-size W |
Vocab-shard the LM head over W contiguous ranks. Under attention DP the default is 1 (replicated); a wider group gathers distinct DP groups' rows before the logits GEMM and transposes the vocabulary shards back. Attention TP greater than one is supported; LM-head and attention TP widths must tile each other. Without attention DP it must equal the attention TP size. |
--dense-tp-size W |
Already shards the dense MLPs over W ranks (token all-gather in, token reduce-scatter out). |
--tp-batch-invariant {none,attn,attn+dense} |
Make the sharded o_proj (attn) and dense down_proj (attn+dense) column-parallel on hidden so no cross-rank sum remains outside MoE; see below. |
--attn-head-tp-size is the one that changes the attention data flow. With
W ranks holding T_full decode rows together and this rank owning T_own
of them, each attention layer runs:
- token all-gather of the normalized q latent:
[T_own, q_lora]to[T_full, q_lora]; q_b_projand the absorption on this rank'sH / Wheads:[T_full, H / W, kv_lora + rope];- all-to-all, heads to tokens:
[T_own, H, kv_lora + rope]-- every head of this rank's own tokens; - the attention prologue (RoPE, KV write) and core attention on this rank's own KV, with the full head count;
- all-to-all, tokens to heads:
[T_full, H / W, kv_lora]; - the value projection with the local
w_vc:[T_full, H / W * v]; - the
o_projtail back to[T_own, hidden]: row-parallelo_projand a token reduce-scatter of the head partials, or, under--tp-batch-invariant attn, an all-gather of the heads, the column-parallelo_proj([T_full, hidden / W]) and an all-to-all back to this rank's rows.
The head exchange precedes the prologue, so the prologue sees one row count for the query, the latent and the write slots (RoPE commutes with the head permutation). The KV write and any sparse-attention indexer stay as they are. The head group's ranks all take part in every leg, including a DP rank with no rows this step: it still owns a head shard of the group's tokens. That participation lives in the attention module alone -- every decoder layer calls its attention on an idle forward too, with its empty rows, and the attention joins the exchanges or returns at once depending on the layout -- so no layer branches on the layout (the NextN and Eagle3 drafters' layers and LongCat's two-attention layer included). A head group whose ranks are all idle moves nothing and skips its collectives together. The exchange counts come from the gathered per-rank token tables, so there is no device sync: the legs up to core attention move the forward's input rows, the legs after it the rows a narrowing draft step reported as its collective sizing (one live row per request), and an idle rank sizes by the same tables. Decode CUDA graphs pad every DP rank to the same batch.
Decode rows only. An expanded prefill needs every head's K and V for the
cached prefix. Under head TP each rank holds kv_b_proj for its H / W
heads and the latent cache for its own requests only, so no rank can expand
the other heads of its prefix, and no other rank holds that prefix to expand
it for it: the full-head K/V of a prefill is not available on the layout.
TokenSpeed therefore refuses the layout over DP ranks outside
--disaggregation-mode decode (head TP over the query shards of a prefill
engine serves its extend rows through the absorbed sparse prefill instead,
see below), and the decode engine keeps every extend-shaped forward off its
path:
- startup tunes on a decode step instead of the usual extend-shaped dummy
forward, and the prefill CUDA graph (which records extend forwards) is
turned off (
--disable-prefill-graphis set, with a log line); - a decode node runs no prefill of its own in any case: a request a capacity
retraction suspends is imaged to Host and copied back by a restore
(
docs/design/scheduler.md, sections 2 and 4), never recomputed, so the layout needs no admission rule and no generation cap -- anymax_new_tokensis admitted, as on every other engine.
A prefill row reaching the attention is then an invariant violation and raises, not a configuration the operator can hit.
--lm-head-tp-size under attention DP gathers distinct DP groups' logits rows,
runs the vocab-shard GEMM and transposes the shards back to each rank's own
rows ([T_own, V]), so sampling and logprobs downstream see the same
full-vocab rows as a replicated head. With attention TP greater than one,
only one peer writes each DP slot into a zeroed hidden-state buffer, which
is all-reduced across the LM-head group. The vocabulary shards are gathered
and each attention TP peer reads its DP slot. This avoids multiplying the
LM-head GEMM rows by attention TP. LM-head and attention TP widths must tile
each other. For example, DP4/TP2 supports an explicit LM-head TP8 while its
default stays replicated. A shared MTP head uses the same row layout.
When the LM-head group stays within a single attention TP group (including
when LM-head TP equals attention TP), its peers already hold identical
hidden states, so the input row exchange is skipped. The output still
gathers the vocabulary unless the consumer requests greedy token IDs.
For greedy heads, eligible cross-DP layouts reduce each row's vocabulary maximum and global token ID before selecting the owning DP rows. They use fused distributed argmax with alternating slot bands when supported, and otherwise the packed-key argmax collective, instead of gathering full logits. The alternating bands allow consecutive target/draft calls without an extra group barrier; calls sharing a state must still be ordered across streams. The greedy DSpark draft walk runs each Markov position (bias, add, and argmax) as one launch that exchanges candidates through the same slots and band order. Returned logits remain vocabulary-sharded and are not a full distribution. Sampled draft distributions and consumers requiring full logits keep the vocabulary exchange; padded vocabularies, softcapping, and other argmax eligibility limits also retain the full-logit fallback.
On the decode path the row counts come
from the per-rank token tables (every rank's logits rows are its decode
tokens, or the live rows a narrowing draft step reported), so the step has
no host sync. The shapes without a table -- a prefill's one row per request
or its logprob rows, a MIXED round, a model selecting its own logits rows --
exchange the counts. A drafter sharing the target's head must build its own
head on the same layout (the NextN, Eagle3-MLA and Llama-Eagle3 drafters do;
TokenSpeed refuses the others with a clear error). It cannot combine with
--dp-sampling, and admission refuses a request asking for prompt logprobs
(logprob_start_len): that path pushes the prompt rows through the LM head
in per-request chunks, a per-rank number of row exchanges the group cannot
agree on.
LM-head vocabulary gathering uses a separate communication buffer sized for sampling and speculative verification rows, rather than the attention prefill chunk. With attention DP, its capacity covers the global request limit times the number of speculative verification tokens (at least 128 rows). Larger batches, including prompt-logprob batches, fall back to NCCL without growing the persistent multicast buffer.
--tp-batch-invariant replaces the two reduce-scatters of these layouts
(after o_proj, after the dense down_proj) with column-parallel GEMMs on
hidden: the ranks all-gather the reduction dimension (heads, intermediate
channels), every rank computes its hidden shard of every token with full K,
and an all-to-all returns the rows. Every collective is then a pure
permutation of bytes, so the result is bitwise the full-K GEMM a TP1 or
replicated layer computes -- the point when a prefill engine with such a
layer must agree with the decode engine. It moves about the bytes of the
reduce-scatter it replaces and needs unquantized o_proj / down_proj.
attn requires head TP, and attn+dense also requires a dense TP group
wider than attention TP (never under query context parallelism, whose dense
group is 1 or the attention TP width).
The decode preset for a 128-way DP MLA model is thus one node-local group of 8 reused three times:
tokenspeed serve --headless <model> \
--world-size 128 --nprocs-per-node 8 --attn-tp-size 1 --data-parallel-size 128 \
--attn-head-tp-size 8 --dense-tp-size 8 --lm-head-tp-size 8 \
--tp-batch-invariant attn+dense --disaggregation-mode decode ...
--tp-batch-invariant attn+dense needs the checkpoint's o_proj and dense
down_proj in the loading dtype. A quantized checkpoint qualifies only when
its disable_quant_module keeps those modules unquantized (self_attn for
o_proj; dense_mlp, or mlps for LongCat, for down_proj); the check
runs against the checkpoint's resolved quantization, not only
--quantization, and the layers check their own weights once built. Without
such an exclusion drop --tp-batch-invariant (the ordered-fold
reduce-scatter remains batch-invariant, see docs/design/numerics.md).
Pinning a request to an attention-DP rank
Each attention-DP rank owns a private prefix cache, so multi-turn requests
only reuse their cache when every turn lands on the same rank. The
data_parallel_rank field of the wire request a frontend submits pins a
request to one rank: the frontend dispatches it straight there, bypassing load
balancing — overload spill is the router's job. A pin that names no rank fails
that request. The engine keeps serving.
Disaggregated prefill and decode requests each honor their own rank pin,
since any decode rank finds the prefill rank from the room. The
bootstrap_room still identifies the prefill KV source: room % dp_size
must match the rank a prefill pin selects, so a frontend pins the prefill
rank and mints the room from one decision. Without a pin, a PD request
follows the room residue (room % dp_size).
Under ts serve, the engine's attention-DP ranks register with the bundled
gateway as one grouped worker, which places each unpinned request on its
least-loaded rank itself; the gateway's --dp-aware expansion does not apply
to it.
MoE deployments
Large MoE models usually choose one of these shapes:
- TP only: simplest startup path, often best for smaller MoE checkpoints.
- TP + EP: tensor parallelism within a replica, expert parallelism across ranks.
- DP + EP: multiple replicated decode groups with experts distributed inside each group.
Start with the recipe closest to your model family, then tune:
--tensor-parallel-sizeor split TP values--enable-expert-parallel--moe-backend--all2all-backend--deepep-mode
With --moe-backend flashinfer_trtllm, TokenSpeed automatically pads NVFP4
expert shards to a multiple of 64 along their per-rank intermediate
dimension. The padding zero-fills the packed weights and block scales in the
tail, so the extra dimensions do not change the MoE result. For example,
TokenSpeed pads a 640-wide expert under MoE TP4 from 160 to 192 values per
rank. TokenSpeed zero-pads BF16 SiLU/SwiGLU expert shards the same way to a
multiple of 64 (128 when it cannot adapt the installed FlashInfer launcher,
or when FlashInfer's JIT cannot build the adapted one). For example,
Qwen3-30B-A3B's 768-wide experts need no padding under MoE TP4 (192 per
rank), while TokenSpeed pads a 96-wide shard to 128.
On Hopper, MXFP4 routed experts with a SiLU/SwiGLU activation and dense EP
(--all2all-backend none) default to the FlashInfer CUTLASS mixed-input
kernel (flashinfer_cutlass), which needs the per-rank intermediate size and
the hidden size to be multiples of 128. Other widths, SiTU experts and DeepEP
all-to-all layouts keep marlin. --moe-mxfp4-fp8-activation selects its
W4A8 variant.
Kimi-K3 attention DP with MoE EP
With none, agrs, or flashinfer transport and attention DP greater than one,
Kimi-K3 requires MoE TP 1 and
attention TP x attention DP == MoE EP == world size. Only the routed experts
require dispatch/combine communication. With attention TP 1 (DEP), shared
experts and attention projections are replicated. With attention TP greater
than one, each attention-TP rank routes a slice of its replica's rows and the
shared experts shard over the replica's attention-TP group. For example, two
attention replicas of TP8 with KV parallelism 8 and routed EP16 across both:
--attn-tp-size 8 --data-parallel-size 2 --kv-parallel-size 8 --decode-context-parallel-size 8 --moe-tp-size 1 --expert-parallel-size 16.
Static expert placement requires attention TP 1.
On this path (any transport but deepep, or MegaMoE), an EP size that does
not divide the 896 routed experts takes redundant slots
(static expert placement),
for example --ep-num-redundant-experts 4 --ep-dispatch-algorithm static at EP20.
Select the transport with --all2all-backend:
none(default): automatically use FlashInfer on NVIDIA ranks sharing a CUDA fabric, otherwise AG/RS.agrs: use reference all-gather dispatch and reduce-scatter combine.flashinfer: use FlashInfer MNNVL all-to-all; errors without the required CUDA fabric.deepep: Hopper Marlin supports attention TP combined with DP and pipeline parallelism. It requires attention CP=1, MoE TP=1/DP=1, andMoE EP == attention TP * attention DPwithin each pipeline stage. DeepEP owns routed dispatch/combine. Shared experts stay in the attention TP group. The construction-selectedKimiLinearMoEDeepEPkeeps this token ownership and its projection/shared-expert weight placement in one module. See Kimi-K3 Hopper PD for deployment layouts.
For NVIDIA NVFP4 and MXFP4 checkpoints, --moe-backend mega_moe replaces routed
dispatch, SiTU expert computation, and combine with MegaMoE. It requires
--all2all-backend none, keeps routing weights after FC2, and returns BF16 outputs.
MXFP4 experts run FlashInfer's Kimi K3 MegaMoE, which quantizes the BF16 routed
rows to MXFP8.
The AG/RS and FlashInfer transports quantize NVFP4 activations before dispatch and transfer their block scales alongside the routing IDs and weights. Combine outputs remain BF16.
Tensor-parallel subgroups within DP
Shard selected dense weights across contiguous groups of DP ranks with these
independent settings. Set the same values on every worker before launch.
Unset or 1 keeps that component replicated. Non-integer values produce a
warning and use 1. Workers must agree on the resulting sizes before
creating TP subgroups.
| Environment variable | Sharded computation |
|---|---|
TOKENSPEED_KIMI_K3_QKV_PROJ_TP_SIZE |
KDA QKV/gates and MLA QKV-A/output gate |
TOKENSPEED_KIMI_K3_O_PROJ_TP_SIZE |
KDA and MLA output projections |
TOKENSPEED_KIMI_K3_SHARED_EXPERT_TP_SIZE |
BF16 shared-expert MLP |
Each size must be a positive divisor of world size. Shared-expert TP must also be smaller than world size and divide the MLP intermediate width. Keep attention and linear attention at TP1/DPworld, routed MoE at TP1/EPworld, and pipeline parallelism disabled. QKV and output projection sharding also require attention head-TP at 1. DEP16 can use TP2, TP4, or TP8 subgroups. These settings do not change attention caches or token ownership.
QKV and output projection sharding support BF16 and 128×128 block-FP8 weights with BF16 activations, including the FP8 attention weights in an NVFP4 checkpoint. The sharding preserves checkpoint FP8 codes and scales. QKV TP requires gated MLA with Q-LoRA. TokenSpeed rejects gated MLA without Q-LoRA even with replicated projections. MLA Q-B, KV-B, KDA convolution and norms keep their existing mapping. Target-model projection settings do not change the draft model. Kimi-K3.1 sparse MLA (DSA) supports the same QKV and output projection settings.
Each sharded computation restores complete outputs to the original token owner:
- QKV: AllGather → column-parallel projection → All-to-All.
- Output projection: All-to-All → row-parallel projection → ReduceScatter.
- Shared expert: AllGather → gate/up → activation → down → ReduceScatter.
Empty ranks still join collectives when peers have work. Uneven batches pad to the subgroup's largest physical token count. The runtime prepares communication buffers before CUDA-graph capture and reuses them across layers. Shared experts use separate buffers. Shared AllGather finishes before routed dispatch, shared GEMMs finish before routed BMM, and shared ReduceScatter runs after dispatch and before combine. With MegaMoE, shared ReduceScatter instead follows its fused dispatch/BMM/combine kernel and overlaps the routed norm and local up-projection. Native collectives cover the configured decode batch bound including speculative tokens; larger batches retain NCCL. Place each subgroup on a CUDA-IPC-accessible node to use the optimized paths.
Automatic projection fusion uses TP2 or TP4. Column fusion requires input
widths and output shard widths aligned to 128 channels. Row fusion requires
input and output widths aligned to TP × 128 channels. BF16 TP4 sparse-MLA QKV-A
can fuse with 96-channel shard alignment on SM100 and SM103. This layout pads
14400 logical outputs to 14592 stored channels and preserves the original order
and width of the checkpoint and returned logical outputs. With multicast
memory, the 512-row bucket can use 192-channel GEMM tiles on both architectures.
Block-FP8 and BF16 fusion support SM100 and SM103. A subgroup can span nodes within one NVLink domain when every rank can allocate fabric memory. The subgroup maximum must be at least 32 physical rows for BF16 column fusion and 64 for BF16 row or block-FP8 fusion. BF16 fusion uses BF16 operands directly. Row GEMM partials round to BF16, then sum in FP32 rank order before final BF16 rounding. Unsupported configurations use the ordinary projection collectives.
These projection settings apply to DEP; DWDP still requires them to be 1.
Shared-expert TP requires BF16 weights.
TP4 reduces the selected weights to approximately one quarter per GPU, not total model memory or latency. Communication and padding can outweigh GEMM savings, especially for uneven traffic or large prefill batches. Compare TTFT, decode latency, and cache capacity separately with real weights and the full model. A fixed memory budget can turn weight savings into more cache rather than lower device usage. Reduced-layer tests do not establish full-model capacity.
DEP16 example with TP4 subgroups
This example enables all three settings. Set any one to 1 to keep that
component replicated, or set all three to 1 for the DEP16 baseline.
export TOKENSPEED_KIMI_K3_QKV_PROJ_TP_SIZE=4
export TOKENSPEED_KIMI_K3_O_PROJ_TP_SIZE=4
export TOKENSPEED_KIMI_K3_SHARED_EXPERT_TP_SIZE=4
python -m tokenspeed.cli serve \
--model MODEL_DIR --quantization nvfp4 --dtype bfloat16 \
--world-size 16 --nprocs-per-node 4 \
--attn-tp-size 1 --data-parallel-size 16 --dense-tp-size 1 \
--moe-tp-size 1 --expert-parallel-size 16 \
--all2all-backend flashinfer --moe-backend flashinfer_trtllm \
--attention-backend tokenspeed_mla --kda-backend cudnn \
--dist-init-addr HEAD_NODE:29500 \
--max-num-seqs 256 --max-model-len 4096 \
--chunked-prefill-size 1024 --max-prefill-tokens 1024 \
--enable-prefix-caching --disable-kvstore \
--max-cudagraph-capture-size 16 --cudagraph-capture-sizes 1 2 4 8 16
Launch one server process per node on four nodes with four GPUs each, using the
same checkpoint, container, and environment. HEAD_NODE is the allocated head
node, not localhost. On Slurm, reserve a persistent allocation with salloc,
then launch through the site's submit wrapper or srun. The global sequence
limit above allows 16 requests per rank. For higher concurrency, increase both
the sequence budget and graph capture sizes and check cache admission. Keep
hardware, inputs, and serving settings fixed when comparing TP configurations.
DeepEP all-to-all
--all2all-backend deepep moves expert routing off all-gather and onto DeepEP
dispatch/combine. It requires a MoE backend whose kernels own those legs:
--moe-backend deep_gemm (block-scale FP8), --moe-backend flashinfer_cutedsl
(nvfp4, decode-shaped batches only), or --moe-backend marlin (MXFP4 W4A16
with BF16 activations, normal and low-latency legs). K3 on Hopper uses the
Marlin bridge with disjoint TP token slices. Its shared experts and restored
output stay within each attention-TP group. See the
K3 Hopper PD guide for PP4/TP8/EP8 prefill
and DP4/TP8/EP32 decode.
All DeepEP MoE plans reserve their persistent communication buffer during the
common moe_process_weights call, after backend weight preprocessing and before
KV cache memory profiling. This applies to Marlin, DeepGEMM, and FlashInfer.
Non-DeepEP plans do not initialize DeepEP. The input hidden width and global
expert count come from the MoE module's declared geometry, never inferred from
packed weights. Dispatchers retain their backend-specific execution settings
and reuse the prepared buffer. Compatible layers share the process-wide buffer.
Incompatible geometry, mode, or capacity fails through the same reuse checks as
runtime acquisition. The capacity remains the explicit server setting (256 by
default), with no model-name-based sizing in ModelRunner.
DeepEP has two sets of legs, and --deepep-mode picks between them:
| Mode | Legs | Fits |
|---|---|---|
low_latency |
IBGDA dispatch into a preallocated per-expert buffer | Decode-shaped batches up to --low-latency-max-num-tokens-per-gpu |
normal |
High-throughput dispatch, tokens permuted into per-expert row blocks | Extend-shaped batches of any size |
auto (default) |
Both are allocated; each forward picks | Aggregated serving, which mixes both shapes |
For block-scale FP8 with deep_gemm, keep auto unless the instance only ever
sees one shape -- for example, a decode-only worker in a PD split, which can pin
low_latency and skip the normal-mode buffers. The nvfp4
flashinfer_cutedsl kernel implements only the low-latency legs, so it requires
an explicit --deepep-mode low_latency. TokenSpeed rejects auto and
normal while building the execution plan. Every forward on such an
instance, including any prefill, must fit
--low-latency-max-num-tokens-per-gpu.
The runtime rejects a batch above the low-latency capacity rather than
truncating it. If decode plus speculative draft tokens exceed the capacity,
raise --low-latency-max-num-tokens-per-gpu. All current DeepEP MoE backends
require BF16 activations and do not support --dtype float16.
Each forward picks the mode from a value every rank agrees on, because the two modes are different collectives. With DP attention that value is "every DP rank is decoding", so one extending rank moves the whole group to the normal legs.
When DeepEP is selected, TokenSpeed disables the prefill CUDA graph:
normal-mode dispatch reports its per-expert receive counts to the host, and a
graph cannot capture a host sync. Decode graphs replay the low-latency legs;
--deepep-mode normal has none to replay, so it disables CUDA graphs
altogether.
For block-scale FP8 decode on NVIDIA, the low-latency path keeps routing metadata in DeepEP's required contiguous int64/float32 formats across both collective legs. Ordinary softmax routing selects experts and normalizes their weights in one Triton launch before dispatch, instead of materializing the full softmax and launching separate ATen top-k, reduction, and division kernels. Its fused SwiGLU quantizer writes packed UE8M0 scales directly in DeepGEMM's MN-major TMA layout, so padded rows need no zero-fill and the second expert GEMM needs no separate activation-scale transpose/pack pass. For sparse decode it launches a bounded number of row splits per expert and walks only rows below the device-side expert count. Full-capacity workloads retain one-CTA-per-row parallelism. The host-side expected-row estimate selects between these mappings without synchronizing the expert counts to the CPU. The runtime expands and packs expert weight scales once at weight load, instead of ahead of both expert GEMMs in every layer forward. The runtime queues shared-expert work between the dispatch send and receive legs to overlap the collective whenever the model has a shared expert. Low-latency dispatch asks DeepEP to produce packed UE8M0 scales directly in its column-major TMA layout. Normal-mode dispatch still transports FP32 power-of-two scales, but the existing expert scatter packs them while permuting tokens, so neither mode needs a separate sequence of elementwise shifts, fills, copies, and a transpose before GEMM1.
Dense (128, 128) FP8 projections have two scale contracts against
FlashInfer's FP8 block-scale GEMM, and both are copy-free for the layout they
own. The canonical K-major contract takes the quant kernel's [M, K/128]
activation scales and the checkpoint's [N/128, K/128] weight scales with no
layout conversion (the runtime normalizes strided scale views to contiguous
first).
The prepared MN-major contract, selected at load time on every Blackwell
datacenter part, transposes the weight scales once and then consumes the
TRT-LLM quantizer's native [K/128, M] activation scales directly, which is
what the canonical path would otherwise have to transpose on every call. Both
produce bitwise identical output.
MN-major requires M to be a multiple of four, so a prepared layer falls back
to the canonical contract once padding would cost more than the transpose it
saves — the fused padding quantizer grows with M while the transpose does
not. Decode row counts stay on the prepared path.
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. --ep-num-redundant-experts R gives every MoE layer
P = E + R physical expert slots, P / ep_size per rank, and an expert
placement decides which logical expert each slot holds, so the placement
replicates a hot expert across ranks. TokenSpeed derives the placement from
recorded load with DeepSeek's EPLB algorithm — once at startup from a
profile record, or online from the live counters (dynamic
rebalancing below). Models opt in explicitly
(supports_expert_placement on the model class) by building their MoE layers
from the placement and loading every placed slot — LongCat-Flash does, and
Inkling2 does for static placements (it does not expose its expert weights to
--enable-eplb), and so does Kimi-K3 with attention DP and EP-only MoE
(MegaMoE, or the all-to-all / all-gather dispatch to the local MoE; static
dispatch, no load recording or online rebalancing).
DeepSeek-V4.1-Flash supports static placement and online rebalancing with
attention TP1, MoE TP1, 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.
--ep-num-redundant-experts also needs expert parallelism (ep_size > 1):
replicas live on other ranks. It also serves an EP size that does not divide
the routed experts: Kimi-K3's 896 experts run at EP20 with
--ep-num-redundant-experts 4 (900 slots, 45 per rank).
-
Record the load of a representative workload. Serve with
--expert-distribution-recorder-mode stat --ep-dispatch-algorithm static_with_zero_expert(staticfor models without zero experts): the router counts every route into a per-layer, per-physical-expert counter on the device, and theEXPERT_LOADprofile activity frames the window. Only real tokens count: a padded replay (a decode graph at a ladder batch size, a prefill graph at a bucket, an idle attention-DP rank) feeds filler rows through the MoE layers, and the graph owners mark those rows in a device-side live-row mask before the replay and clear it after, so the counters see traffic, not padding. Startup forwards (autotune, warm-up, graph capture) are not traffic either: the runtime zeroes the counters once capture is done, so the first window -- a profile's or a rebalance's -- starts at the first served forward.Start a profile with the
EXPERT_LOADactivity and anoutput_dir(the engine'sProfileReqcontrol operation, which the frontend driving the engine sends; underts serve, the gateway'sPOST /start_profilewith{"activities": ["EXPERT_LOAD"], "output_dir": ...}), serve the workload, then stop the profile (POST /stop_profile).Stopping writes one record per rank,
<id>-<rank tag>.expert-load.pt, holding what that rank's router counted:physical_count([layers, slots], int64), the same summed over each logical expert's replicas aslogical_count([layers, routed experts]), thephysical_to_logical_mapthat produced them and the rank'sep_rank/ep_size. 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.merge_expert_load_recordstakes the sum over the EP group when it consumes the records: 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 and merging more only scales the counts uniformly, which the placement algorithm is blind to. -
Place: restart with the redundant slots and the recorded load, pointing
--init-expert-locationat the directory (or a glob) of the records to merge them. 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.--ep-num-redundant-experts 128 \ --init-expert-location /tmp/expert-load \ --ep-dispatch-algorithm static_with_zero_expertPmust divide over the EP size (LongCat 2.0: 768 + 128 = 896 slots at EP128, 7 per rank). The loader fills every local slot from the logical expert the placement assigns it — one checkpoint tensor lands in each of its replicas, and RL weight sync through the same path does too.--init-expert-locationalso accepts a single record file (itslogical_countalone). A file holding only aphysical_to_logical_mappins a placement exactly.--eplb-algorithmselects the balancing algorithm (autopicks the hierarchical variant when the model's expert groups divide over the nodes). The merged record's per-layer balancedness (mean rank load over the busiest rank's load) is what to compare between placements. -
Route. The router emits physical ids. Zero experts (LongCat) stay
-1and 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, so
every rank dispatches to its nearest replica — one on the same GPU,
else on the same node (nodes taken from the EP group's actual ranks),
else a seeded fair draw — through a static per-rank map
(
--ep-dispatch-algorithm static*; thedynamic*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 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-bitwisethe placement must be deterministic (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. - Under all-to-all EP (DeepEP) each rank routes only its own tokens, so
every rank dispatches to its nearest replica — one on the same GPU,
else on the same node (nodes taken from the EP group's actual ranks),
else a seeded fair draw — through a static per-rank map
(
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 using 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, so the placement follows drifts in the traffic's expert
distribution without a restart. For example, a LongCat launch can use
--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
--eplb-window-size W sets the number of forwards sampled per snapshot.
The first snapshot is taken after W forwards, then every
--eplb-rebalance-num-iterations N forwards using the most recent W
(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 each scheduling round pays: the rebalance switches the
model's MoE layers L per round, each layer's weights first and its routing
tables right after, so a forward 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, since the rebalance
owns the same counters. The engine log reports the balancedness each snapshot
saw and the one the new placement is expected to reach.
- 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) each rank's counters already are the group load, and the runtime compares the ranks' checksums — a difference means the ranks routed differently within a forward, 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.
- 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. - Apply, one chunk per round. Each rank receives every incoming slot into a staging buffer reserved at startup (one layer per participating model, before startup sizes the KV arena) and sends every outgoing slot from its live tensor, in one batched P2P over the EP group. 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 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 — quantized weights and scales included — so the rebalance re-derives nothing.
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 (both are 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 (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 (see
docs/design/numerics.md).
KV parallelism
Three context-parallel terms appear in this project, and they name different things:
- KVP (KV parallelism) is a storage layout: the full-history KV cache
pages are sharded page-cyclically over a consecutive subgroup of attention
TP by virtual block id, so each rank stores
1/Nof every request's pages and the KV capacity per GPU grows byN.--kv-parallel-size Nselects it;mapping.attn.kvp_size / kvp_rank / kvp_groupdescribe it; the cache, scheduler feedback, Host tiers and PD transfer reason about it (page ownership, residue classes, owner translation, sharded page tables). - DCP (decode context parallelism) is the decode-side compute over KVP
pages: every rank keeps all of its query heads, attends only the pages it
owns, and the partial outputs are merged across the KVP group by their
log-sum-exp (LSE).
--decode-context-parallel-size Nnames it in aggregated or PD decode engines, where it is the only way to decode over a sharded cache (so both require it with--kv-parallel-size N, equal); the attention backends' decode algorithms, their kernels and the LSE-merge code carry the DCP name and key onkvp_size, which the drafter's steps on a sharded prefill engine take as well. - QCP (query context parallelism) is the prefill-side sharding of the
query rows over the attention TP group against the full, gathered KV
history; there is no LSE merge.
--query-context-parallel-sizeselects it on the PD prefill role (next section).
--kv-parallel-size N must divide --attn-tp-size; the KVP subgroups are
aligned runs of N consecutive attention-TP ranks. It applies to the
full-history groups of MLA/DSA models (latent KV and index-K) and to DeepSeek
V4.1's global KV; groups that every rank reads whole (sliding windows,
compressor state) stay replicated. The attention backend decides how it
attends the sharded pages (DCP decode, chunked or gathered prefill history);
the scheduler plans the same virtual blocks on every rank and the runtime
translates ownership where it reads, writes or copies them
(docs/design/cache-concepts.md). An aggregated engine combines the existing
sharded-history prefill with DCP decode, without a PD transfer or QCP. On PD,
a prefill engine (with or without a query shard) and a decode engine (with
--decode-context-parallel-size) each shard their cache independently; a
transfer edge copies the pages its prefill rank and decode rank both own.
Works with the Host KVStore, the retraction snapshot pool and L3 storage.
The Host KVStore takes either --kvstore-write-policy; write_back only on
an aggregated or prefill engine, without a query shard or L3 storage. L3 reuse
requires the same CP layout; see
Host L2 and Mooncake Store L3,
which also lists every write_back requirement.
For non-PD MLA serving, use a DCP-capable backend, for example:
ts serve --model MODEL --attention-backend flashmla \
--attn-tp-size 8 --kv-parallel-size 8 --decode-context-parallel-size 8
Keep --disaggregation-mode at null and QCP at 1. With
--enable-mixed-batch, a mixed round runs its KVP extend rows and DCP decode
rows in one forward. MLA decode remains absorbed; MLA/KDA hybrids
shard only MLA history. Ordinary TP with KVP = DCP = 1 is unaffected.
Speculative decoding runs on a sharded cache with the backends whose DCP
decode takes a verify window (FlashMLA, CuTe MLA, GPU DSA); the draft group
shards like the target's. A FlashMLA verify under KVP runs one kernel row per
query against that query's local causal length, so a width-w window reads
each request's owned pages w times instead of once. The full rule set is in
docs/configuration/server.md.
The chunked prefill of an MLA model reads each prefix chunk's history from its
page owners, a window of chunks per all-gather. On SM100 and SM103 GPUs (GB200,
GB300) a KVP group of 2, 4, or 8 ranks (on one host, or across hosts over an
NVLink fabric) gathers these windows with a fused all-gather kernel instead of
a pack copy plus an NCCL all-gather: each owner stores its rows straight from
its cache into every rank's receive slot, over NVLink multicast where the group
has it, else with one store per peer. There is no flag; startup picks it for
the whole group and reserves two receive slots per GPU before the KV cache is
sized, each holding one chunk's history capacity (--chunked-prefill-size x
--mla-chunk-multiplier rows) from every rank: 2 x kvp_size x capacity x row bytes, 288 MiB at KVP 8 with the defaults (8192 x 4) and an FP8 MLA cache
(576-byte rows). The group keeps NCCL on other GPUs and group sizes, for
DeepSeek V4.1 (which gathers its own history), on a PD decode engine, without
chunked prefill, when one receive slot would take 2 GiB or more (such as at
KVP 8 with an FP8 cache and --chunked-prefill-size 131072), with
--kv-cache-quant-method per_token_head (an FP8 --kv-cache-dtype cache is
gathered fused), and when a configured kernel waits on other ranks inside a
kernel that needs the whole GPU (MegaMoE, DeepEP or any other all-to-all
backend, fused DP projections, or any MoE backend or solution the runtime does
not list as safe). A reader whose cache rows differ from the target's
(another row width or dtype) uses NCCL. The fused kernel's waits end 30 s
before --distributed-timeout-seconds (at half of it when it is under 90 s).
The group's first rank logs the choice: KVP history group ... gathers through the fused all-gather, or ... keeps its NCCL all-gather: with the reason.
Query context parallelism on the prefill role
--query-context-parallel-size N (QCP) splits every extend forward's rows
over the attention TP group of a PD prefill engine, request by request in
zigzag: every request's new rows are cut into 2N near-equal segments and
rank r computes segments r and 2N - 1 - r of every request, against
the full KV history of the request. For sufficiently long requests, each
rank holds an early and a late part, balancing causal attention and letting
the ranks compute each history group in parallel. Short requests can leave
some ranks empty; they still participate in all collectives. It is a layout of the
Mapping (mapping.attn.qcp_size / qcp_rank / qcp_group), not a mode: the
scheduler plans the same chunk on every rank, cache allocation and the P->D
transfer see page ownership only, and --chunked-prefill-size keeps counting
the whole chunk, so size it as N x rows-per-rank.
Per layer the rows a rank holds are its shard: attention needs no gather or
reduce around it (its weights are head-replicated by default, or its own
head-TP tail returns the shard's rows, see below), the dense and MoE legs run
the all-gather / reduce-scatter path over the shard's row table, the KV write
all-gathers each rank's rotated latent to the whole span before the
owner-masked store, the sparse DSA indexer and attention score the gathered
history of each request group, and the model exit gathers only the sampled
rows (one per request) before the LM head. Every QCP collective is data
movement, so a row's bits do not depend on which rank computes it
(docs/design/numerics.md).
DSA packs whole request histories into contiguous groups within its reserved history workspace. It keeps the minimum group count that fits the workspace, then minimizes the largest group's history row count. Request order and query ownership stay unchanged. This reduces the peak rows presented to the indexer without adding history gathers; latency still depends on query distribution and the selected kernels. A request whose history exceeds the workspace is rejected.
Requirements: --disaggregation-mode prefill with --kv-parallel-size N
(the query shard is a layout over the sharded pages; the engine keeps the
Host KVStore, the retraction snapshot pool and L3 storage, as every
KVP engine does, but not yet --kvstore-write-policy write_back),
N == --attn-tp-size, attention DP 1, no
--enable-mixed-batch, GPU DSA attention with a bf16 KV cache (checked where
the attention config is built), and --dense-tp-size and the MoE TP×EP group
each 1 or N (attention returns complete rows, so the drafter's replicated
decode rows are never scattered and a narrower group would have nothing to
gather). The prefill stays eager: the GPU DSA backend declares no prefill
graph under a shard, so the launch need not say --disable-prefill-graph.
The drafter's extend step is sharded like the target's; its decode steps run
every row on every rank.
Head TP over the query shards. Without --attn-head-tp-size the shard
group's ranks hold different rows and every rank holds every head of
q_b_proj, kv_b_proj, and o_proj (the mapping resolves
attn.head_tp_size to 1). --attn-head-tp-size N shards those three
projections by heads over the shard group instead — the same head group the
decode-side layout above builds over DP ranks, here == qcp_group, with the
same exchange around core attention: the ranks token-all-gather the
normalized q latent to the span, q_b_proj runs this rank's H / N heads of
every row, the heads-to-tokens all-to-all returns the shard's rows with every
head, the prologue rotates them on the shard's own positions and writes the
gathered KV as every QCP forward does, the sparse core attends the gathered
history with every head, the tokens-to-heads all-to-all hands the head slice
of every row to the local w_vc, and the o_proj tail returns the shard's
rows (row-parallel o_proj plus a token reduce-scatter, or under
--tp-batch-invariant attn the column-parallel o_proj with an all-gather
of the heads in front and an all-to-all back). The exchange counts are the
shard plan's, so there is no host sync. A rank whose shard is empty joins
every leg. The drafter's decode steps hold every row on every rank, exchange
nothing, attend this rank's head slice (the DCP arm over the KVP pages --
the page-sharded KV of --kv-parallel-size -- as attention TP
runs it) and all-reduce the o_proj partials (all-gather the
hidden shards under --tp-batch-invariant attn). The expanded (dense MLA)
prefill still refuses head TP; the layout serves the absorbed sparse prefill
only. The decode-only rules of the DP layout (role, decode-shaped autotune)
do not apply: the prefill role's rules above and
--attn-head-tp-size == --query-context-parallel-size gate it.
Memory: the head-shardable weights of one attention instance go from the
whole matrices to 1 / N of them per rank. For a model with hidden 8192, 64
heads, q_lora 1536, kv_lora 512, qk 192 and v 128 that is q_b_proj
kv_b_proj+o_proj≈ 94M parameters = 189 MB (bf16) per instance down to ≈ 24 MB per rank atN = 8. A five-layer pipeline stage of a model with two attention instances per layer saves ≈ 1.7 GB per rank, which the KV cache takes.
Numerics: with row-parallel o_proj the shard group computes the same
per-rank head partials the plain TP8 prefill engine does and reduce-scatters
them where TP8 all-reduces. Under --numerics rl-bitwise both are the
rank-ordered fold, so the two engines sum o_proj bitwise alike, and so do
the QCP engine's own drafter decode steps (replicated rows, all-reduced).
With --tp-batch-invariant attn there is no cross-rank sum in
o_proj, and QCP is bitwise the TP1 / head-replicated form the decode
engine's batch-invariant layout computes (docs/design/numerics.md, "Layout
invariance of query context parallelism").
A preset for an eight-GPU prefill engine with head TP and the
batch-invariant o_proj:
tokenspeed serve --headless <dsa-model> \
--disaggregation-mode prefill \
--attn-tp-size 8 --dense-tp-size 1 --enable-expert-parallel \
--kv-parallel-size 8 --query-context-parallel-size 8 \
--attn-head-tp-size 8 --tp-batch-invariant attn \
--chunked-prefill-size 16384
Drop --attn-head-tp-size 8 --tp-batch-invariant attn for the
head-replicated layout (the same bits, 189 MB more attention weight per
instance per rank), or --tp-batch-invariant attn alone for TP8's head
partials, summed in the fold's order.
--tp-batch-invariant attn needs an unquantized o_proj, as on the decode
side.
A model supports the layout by slicing its rows by ctx.query_shard and,
for head TP, threading the attention module's head-TP hooks around its
sparse core (docs/design/unified_path.md, "Query context parallelism").
Every other model refuses it at construction.
Multi-node
Set these explicitly:
tokenspeed serve <model> \
--nnodes 2 \
--node-rank 0 \
--nprocs-per-node 8 \
--world-size 16 \
--dist-init-addr <rank0-host>:25000
Each node must use the same model, backend, precision, and scheduler settings.
Only --node-rank should differ between nodes.
Run one tokenspeed serve per node. Node rank 0 serves the HTTP API. Higher
ranks run the engine only and expose no endpoint. Each attention-DP replica's
first rank registers with node 0's bundled gateway: over a same-host socket
when every one of them is on node 0, otherwise over TCP. The gateway then
listens on the host of --dist-init-addr, at the port below its, which every
node derives from its own flags, so keep that port free on node 0 and
reachable from the other nodes. These sockets carry no authentication: run
the nodes on a trusted network.
Under a launcher
Inside a multi-node Slurm step, TokenSpeed derives --nnodes, --node-rank,
and --dist-init-addr from the step environment when you do not give them,
so the same command line runs on every node:
srun --nodes=2 --ntasks-per-node=1 tokenspeed serve <model> --attn-tp-size 16
| Argument | Derived from |
|---|---|
--nnodes |
SLURM_STEP_NUM_NODES |
--node-rank |
SLURM_NODEID |
--dist-init-addr |
first host of SLURM_STEP_NODELIST, port 23456 |
Rules:
- An explicit
--nnodesor--node-rankthat contradicts the environment is an error, not an override. Omit the flag to accept the launcher's value. - TokenSpeed always uses an explicit
--dist-init-addras given. - Derivation only engages inside an
srunstep of more than one node. Outside a step — including the batch script of a multi-nodesbatch— or in a single-node step, behavior is unchanged: launch the ranks yourself and pass--nnodes/--node-rank/--dist-init-addr. - If TokenSpeed detects a multi-node step but cannot resolve the topology, startup fails with the reason rather than falling back to a single node.
- The derived address is the one the head node's hostname resolves to. Where
that is not the interface you want carrying bootstrap traffic, set
--dist-init-addrexplicitly. - TokenSpeed sets
GLOO_SOCKET_IFNAMEandNCCL_SOCKET_IFNAMEfrom the interface that routes to the head node, unless they are already present in the environment. Gloo needs this: it has no peer-address heuristic and otherwise binds whatever the local hostname resolves to, which is a loopback entry on many hosts. NCCL normally selects correctly on its own. TokenSpeed sets it for consistency. - TokenSpeed does not set
NCCL_IB_HCA. NCCL's own device selection prefers the higher-bandwidth InfiniBand devices and skips Ethernet-link ones. - The rendezvous port is a fixed constant, not a function of
--port. Every node has to arrive at the same port without talking to any other node, and undertokenspeed serveTokenSpeed allocates the engine's own port per node. The constant also stays clear of the kernel's ephemeral range, which startup checks. Pass--dist-init-addrto use a different port.
Apply the same NCCL transport and channel settings on every node as well. In
particular, do not mix IB and Socket selection or different
NCCL_MIN_NCHANNELS / NCCL_MAX_NCHANNELS values across ranks.
Stopping
Stop every node. A node that stops does not stop the others: they find out at their next collective with it, which fails or can hang.
A node that receives SIGTERM or SIGINT, or whose scheduler fails, sends SIGTERM to the engine rank processes it started and gives them 30 seconds to exit. It then kills whatever is left of them and of the processes they started. On Linux the rank processes of a node of rank 1 or higher are also killed when the node process itself is killed, for example with SIGKILL at the end of a grace period.
Emulating rank 0 on one GPU
--emulate-rank-zero runs only global rank 0 of the configured layout, so you
can profile the per-rank work of a multi-GPU deployment on a single GPU:
tokenspeed serve <model> --tp 8 --emulate-rank-zero --load-format dummy
The layout resolves as usual (TP8 here), so the rank builds the weight shards, kernels, and cache sizing rank 0 of the full deployment would. Its collectives are local stand-ins that return the real shapes and dtypes, filled from this rank's operand alone.
Compared with the real rank:
- Communication takes no time, and the fused all-reduce paths are off because they need peers; their epilogues run as separate kernels.
- Values after a reduction are this rank's partial results, so outputs are not meaningful and data-dependent work such as MoE routing follows the emulated values.
A typical launch combines the flag with --load-format dummy, which reads
only the model's config and tokenizer, not its weights. With dummy weights,
also set TOKENSPEED_MOE_ROUTING_SIMULATION=uniform so tokens spread over
experts instead of all picking the same ones, and, with speculative
decoding, set TOKENSPEED_SPEC_SIMULATED_ACCEPT_LEN to the avg_accept_len
of a real run.
TokenSpeed currently supports the flag on AMD GPUs, on one node, without
pipeline, context or attention data parallelism, an MoE TP x EP size other
than the attention TP size, --mm-encoder-tp-mode data, PD disaggregation,
fused all-reduce, or an --all2all-backend transport.
Plugin registration at startup
All launchers use the same plugin discovery and registration lifecycle before argument parsing. Plugins publish schemas, model profiles, reporter callbacks and execution references once. Ranks resolve model and kernel implementations during initialization; the launcher can prepare metrics without importing model code. See plugin registration.
Runtime notes
Overlap scheduling can prepare the next forward on the CPU while the previous forward's non-blocking host-to-device copies are still in flight. Any pinned CPU staging buffer used for per-step model inputs must therefore have per-step lifetime, or use an explicit synchronization before reuse. This applies to MTP/GDN mamba state indices as well as token, length, and request-pool inputs.
CUDA IPC collectives are node-local. The mnnvl fabric workspace spans nodes.
AutoBackend serves single-tensor SUM all-reduces (16-bit, or fp32 where a
single-node workspace was armed for it; mnnvl serves 16-bit only) on groups
whose fan-in is 2, 4, 8, or 16 through the armed workspace -- one-shot
inside its traffic window, two-shot up to the workspace token capacity.
Where FlashInfer's BT presets cover the group (8 ranks, width 7168,
SM103), payloads of at least 1 MiB per rank instead take its owner
reduction, which sums the ranks in order in fp32 where the Lamport kernels sum
in BF16 (tokenspeed_kernel/ops/communication/README.md has the measurements).
Cross-node groups arm the full two-shot capacity at startup. Single-node
groups start at the one-shot window and serve larger shapes once
model-level preparation widens the shared workspace. Other
fan-ins and dtypes, and any shape the workspace rejects, fall back to NCCL
(inside the trtllm backend for armed groups; the Iris all-reduce tier
serves AMD only, where no trtllm workspace exists). Single-node token
all-gather/reduce-scatter runs on the Triton RSAG backend and uses NCCL
across nodes. Logits all-gather and distributed argmax use the same
cross-node fallback. Layouts such as attention DP with dense TP or MoE EP
spanning nodes need this fallback.
On the tiered route, Inkling 2's output convolutions sum their producer's
partial themselves (all_reduce_sconv) for target-verify decode batches the
one-shot mnnvl lane serves: the all-reduce releases the convolution once it
has waited for its input rather than at its end, so the convolution's cold
reads of its taps, ring and routing run under the reduction. Other batches
reduce in the producer with the release at the end.
When the attention TP group is also the MoE EP group and the node has
multicast memory, decode batches of up to 8 rows skip both all-reduces:
the attention's output projection (publish_projection) and the MoE route
fold store each rank's partial straight into slot rank of every rank's
Lamport mailbox (ops.communication.mailbox), and the output convolutions
read the sum from there (inkling_ring_sconv_mailbox, FP32 in rank order,
rounded once). The model builds the mailbox in prepare_communication_runtime;
each layer uses both chains or neither, so the two uses alternate the
mailbox's parities.
Past 1024 rows, a Kimi-K3 attention layer's BF16 o-projection writes its
partial straight into the multimem staging buffer of the MoE tail's
up-projection (K3AttnComm.prepare_staged_projection). The sum then runs as
the same in-switch all-reduce instead of NCCL. The MoE's shared experts then
write their partial straight into the same buffer
(K3MoeTailComm.acquire_shared_output), where the tail reduces it. On a layer
with an AttnRes prefix the attention's reduced rows are a delta, which AttnRes
adds into the residual in place before the MoE starts. Only a block-write
layer copies them out, because its residual is the sum itself and outlives
the shared partial. Under
--batch-invariant-collectives or --force-deterministic-rsag the attention
keeps its ordinary all-reduce.
Under --numerics rl-bitwise (--batch-invariant-collectives) every
reduction takes NCCL data movement plus a rank-ordered fp32 fold, and the
gathers stay on the multicast kernels; the in-switch reduction's order moves
with a row's offset in the buffer, so it serves only the performance routes.
The distributed argmax
and the fused all-reduce kernels are off. --force-deterministic-rsag keeps
every collective on NCCL (reductions on the fold). AutoBackend.route is
the one place that decides. docs/design/numerics.md has the measured
basis.
Under plain attention TP with replicated MLA latent KV (no KVP, no query
context parallelism), a GPU DSA sparse prefill of at least 4096 rows runs its
core attention on a row shard instead of a head shard. An all-to-all hands
each rank 1 / W of the rows with every rank's heads (padded to the
trtllm-gen core's head count), the core attends them, and a second all-to-all
returns each rank's heads of every row. The core then reads each selected KV
row once for all heads instead of once per rank. The bitwise numerics
envelopes keep the head shard.
On ARM systems, NCCL 2.29.3 fixes a weak compare-and-swap failure that can hang NCCL when it was compiled with GCC older than 10. Affected NCCL builds older than 2.29.3 can exhaust proxy operations during repeated multi-node CUDA graph replay. Use NCCL 2.29.3 or newer for this configuration. Disabling CUDA graphs avoids the affected path, but you do not need it with the fixed NCCL runtime.
Validation
Before benchmarking:
- verify every rank starts and joins the distributed group
- verify the API responds before sending load
- confirm GPU visibility and process placement
- compare output correctness before tuning throughput
- keep the full launch command with benchmark results
Distributed expert-weight storage
--moe-weight-sharing-size N enables DWDP: each prefill worker stores one of
N immutable expert shards and fetches remote weights while executing its own
batch. Execution remains TP1/EP1; attention DP still identifies the serving
workers. Omitting the option keeps resident expert weights.
DWDP supports the CUDA 12.8 and 13 toolkits.
The initial K3 configuration (NVFP4 or MXFP4 experts on the FlashInfer TRT-LLM
kernels; pass --moe-backend flashinfer_trtllm for MXFP4, where auto may
select another kernel) requires --attn-tp-size 1 --moe-tp-size 1 --ep-size 1 --all2all-backend none, --disaggregation-mode prefill, and a
fixed prefill token budget. Eager execution and ordinary breakable prefill
graphs are supported.
The routed experts run on FlashInfer's TRT-LLM-Gen kernels
(--moe-backend flashinfer_trtllm) or, for NVFP4, its CuTe DSL kernels
(--moe-backend flashinfer_cutedsl). The weight-sharing size must divide the
instance size. Shared-expert and attention-projection TP overrides must also
remain local. The additional staging memory is allocated before KV cache sizing.
Live checkpoint replacement requires restarting these workers.
See distributed immutable weights for storage ownership and stream-ordering invariants.
Every forward streams the expert shards the worker does not own, so a DWDP
prefill forward takes seconds whether it carries one token or the whole
budget; the per-forward cost is paid in full by forwards well below the
budget. Choose the chunk size and admission so forwards stay near the budget.
Every timeout between the frontend and the decode side must then cover at
least one full forward plus queueing: the gateway's per-worker silence bound
(SMG --worker-wedge-secs, 3 s by default, after which every request on the
worker returns 504), and in prefill/decode disaggregation
TOKENSPEED_DISAGGREGATION_BOOTSTRAP_TIMEOUT (120 s) and
TOKENSPEED_DISAGGREGATION_WAITING_TIMEOUT (300 s), which otherwise drop
requests queued behind a saturated decode instance as KV transfer failed;
the client's stream then ends with no content and no error. A larger token
budget also grows the MoE activation workspace, which must fit beside the
staging pools; if startup runs out of memory there, lower
--gpu-memory-utilization rather than the budget.
DWDP supports local Device and Host L2 caches and auto/safetensors checkpoint loading. Memory-saver sleep/wake is unsupported. Shared L3 cache control and online expert rebalancing are currently unsupported: L3 flushes coordinate across DP ranks, and rebalancing changes immutable expert ownership.