Track VIII · Inference & Optimisation · 07/09

서빙을 위한 병렬화와 MoEParallelism for serving, and MoE

TP·PP·DP·EP가 토큰 하나당 무엇을 얼마나 주고받는지 바이트 단위로 유도하고, MLA가 왜 attention을 DP로 돌리게 만드는지, 왜 큰 MoE는 수백 GPU에 걸친 wide EP로 서빙되는지(GPU당 메모리, expert당 토큰, 산술 강도)를 계산한다. expert 부하 불균형을 샘플링 잡음과 인기 편중으로 나눠 보고 redundant expert와 EPLB가 어느 쪽을 고치는지 확인한 뒤, DeepSeek의 공개 서빙 구성과 SGLang·vLLM 재현을 읽는다.Derive, in bytes, what TP, PP, DP and EP exchange per token; why MLA pushes attention to data parallelism; and why large MoEs are served with wide EP across hundreds of GPUs (memory per GPU, tokens per expert, arithmetic intensity). Split expert load imbalance into sampling noise and popularity skew and see which one redundant experts and EPLB fix, then read DeepSeek's published serving setup and the SGLang and vLLM re-implementations.

50 분min inference · tensor parallel · pipeline parallel · expert parallel · MoE · all-to-all · DeepEP · EPLB · DP attention · MLA · prefill-decode disaggregation · DeepSeek 먼저 볼 것:Before this: 추론 최적화Inference optimisation, MoE 해부: routing, 세분화·shared expert, 부하 균형, dropless, LatentMoEAnatomy of MoE: routing, fine-grained and shared experts, load balancing, dropless, LatentMoE, Roofline과 추론 지표The roofline and inference metrics, 배칭과 스케줄링Batching and scheduling

The inference basics lesson ended its MoE paragraph with “large MoEs are served with expert parallelism and all-to-all communication”. This lesson opens that sentence up. A 671B-parameter model in FP8 is 671 GB of weights: it does not fit on one 8-GPU node of 80 GB cards, and even when it fits, the room left for the KV cache decides how many sequences decode together, which decides cost. So the question is not “which parallelism is fastest” but which split of weights, KV and tokens across N GPUs gives the most tokens per second per GPU under a latency target, and each of the four axes (tensor, pipeline, data, expert) trades memory for communication in a different currency.

The prerequisites are the roofline lesson (decode is bound by bytes read, not FLOPs) and the MoE anatomy lesson (routing, shared experts, load balancing during training). Here everything is seen from the serving side.

Serving is not training

Three things change when the same model moves from training to serving.

  1. No gradients, no optimiser state. Mixed-precision Adam training holds roughly 16 bytes per parameter; serving holds 1–2. The weight memory that forced training to shard everything shrinks by an order of magnitude.
  2. The KV cache takes its place. Every live sequence owns its keys and values. The KV-cache lesson gives the size; here what matters is that any HBM not used by weights becomes batch, and batch is what amortises the weight read.
  3. Each step is a latency. Decode runs one token per sequence per step, thousands of times. A collective that costs 15 µs is negligible in a training step of seconds and a large fraction of a 20 ms decode step when it is paid twice per layer.

So a serving plan has four goals at once: fit the weights, leave room for KV, keep the per-step communication short, and gather enough tokens behind every weight read that the read is amortised.

What each axis moves per token

Take one layer with hidden size dd and a batch of BB tokens in the step (in decode, BB = number of sequences). Activations are BF16 (2 bytes).

Tensor parallelism (TP, degree tt). Megatron-LM splits attention by heads (Q, K, V column-parallel, output projection row-parallel) and the MLP by its intermediate dimension (up/gate column-parallel, down row-parallel). Each row-parallel matmul leaves every GPU with a partial sum of the full B×dB \times d output, so each layer ends its attention and its MLP with an all-reduce of B×dB \times d. A ring all-reduce makes each GPU send

2⏟attn + MLP×2(t−1)t×d×2 bytesper token per layer.\underbrace{2}_{\text{attn + MLP}} \times \frac{2(t-1)}{t} \times d \times 2\ \text{bytes} \quad \text{per token per layer.}

For d=7168d = 7168 and t=8t = 8 that is 49 KiB per GPU, and all tt GPUs do it. Bandwidth is not the main problem at decode, though: the message is B⋅d⋅2B \cdot d \cdot 2 bytes, only tens of kilobytes, so each all-reduce costs about its fixed latency, and a 61-layer model pays it 2×61=1222 \times 61 = 122 times per step. That is why TP stays inside an NVLink domain.

Pipeline parallelism (PP, pp stages). Layers are split into pp contiguous stages; a stage boundary hands over one hidden state, d×2d \times 2 bytes per token, once per stage rather than per layer. The cost is elsewhere. A token must traverse all stages in sequence, so time per output token is pp times a stage step, and pp micro-batches must be in flight to keep every stage busy. PP also does not shrink the KV per GPU at a fixed throughput: each GPU stores 1/p1/p of the layers but for pp times as many in-flight sequences.

Data parallelism (DP). Replicas. No communication and no weight saving; it only multiplies throughput.

Expert parallelism (EP, degree GG). The routed experts of each MoE layer are distributed over GG GPUs. A token that picks kk experts is dispatched to the GPUs that own them and the kk expert outputs are combined back on the token’s home GPU, weighted by the gates. DeepSeek-V3 quantises the activations to FP8 before dispatch and keeps combine in BF16 (report §3.3.3), so per token per MoE layer, if all kk experts are remote,

k⋅d⋅1⏟dispatch (FP8)+k⋅d⋅2⏟combine (BF16) bytes×G−1G.\underbrace{k \cdot d \cdot 1}_{\text{dispatch (FP8)}} + \underbrace{k \cdot d \cdot 2}_{\text{combine (BF16)}} \ \text{bytes} \times \frac{G-1}{G}.

With k=8k = 8 and d=7168d = 7168 that is about 167 KiB. Per token, EP actually moves less in total than TP8 across the model (9.4 MiB vs 23.4 MiB for the DeepSeek-V3 shape; the code below computes both), but most of it leaves the node, and InfiniBand is slow: the V3 report quotes NVLink at 160 GB/s and IB at 50 GB/s on its H800 cluster (§3.2.2). Expert parallelism is bought for weights, not for communication: it is the only axis that divides the 654B routed-expert parameters by hundreds while each GPU still runs whole experts.

axiswhat is splitper-token trafficwhere it hurts
TP ttevery matrix2 all-reduces of dd per layer, on every GPUlatency × 2L per step; leaves NVLink badly
PP pplayersdd per stage boundaryTPOT × pp; needs pp micro-batches
DPnothing (replicas)noneweights replicated
EP GGexpertsk⋅dk \cdot d out + k⋅dk \cdot d back per MoE layercrosses nodes; load imbalance

The KV cache decides the attention layout

Under TP the KV cache is split by KV heads. With GQA and 8 KV heads, TP8 gives each GPU one KV head, an 8× saving; beyond t=nkvt = n_{kv} the heads must be replicated. MLA (the attention-and-KV lesson) is the extreme case: in decode, the absorbed form attends over a single 576-number latent per token that every head shares, so every TP rank needs the whole latent and TP saves nothing on KV. The SGLang team’s large-EP write-up chooses DP attention because it “avoids KV cache duplication”, and vLLM’s wide-EP post says TP is not optimal for MLA because “each rank must duplicate latent attention projections”.

So the layout of choice for an MLA MoE is DP attention + EP experts: every GPU is its own attention replica, holding all non-expert weights and the KV of its own sequences, and at every MoE layer all GPUs join one all-to-all. Try it below.

추론 기초 레슨은 MoE 문단을 “큰 MoE는 expert parallelism과 all-to-all 통신으로 서빙한다”로 끝냈다. 이 레슨은 그 문장을 펼친다. 671B 매개변수 모델은 FP8로 가중치만 671 GB다. 80 GB 카드 8장짜리 노드 하나에 들어가지 않고, 들어가더라도 남은 공간이 KV cache를 얼마나 둘지, 즉 몇 개의 시퀀스를 함께 decode할지를 정하며, 그것이 비용을 정한다. 그래서 질문은 “어느 병렬화가 가장 빠른가”가 아니라 N장의 GPU에 가중치·KV·토큰을 어떻게 나눠야 지연 목표 아래에서 GPU당 토큰/초가 가장 큰가이고, 네 축(tensor, pipeline, data, expert)은 각자 다른 화폐로 메모리와 통신을 맞바꾼다.

선수 지식은 roofline 레슨(decode는 FLOPs가 아니라 읽는 바이트에 묶인다)과 MoE 해부 레슨(routing, shared expert, 학습 중 부하 균형)이다. 여기서는 모두 서빙 쪽에서 본다.

서빙은 학습과 다르다

같은 모델이 학습에서 서빙으로 옮겨 오면 세 가지가 바뀐다.

  1. gradient도 optimizer state도 없다. mixed-precision Adam 학습은 매개변수당 대략 16바이트를 들고 있지만 서빙은 1–2바이트다. 학습에서 모든 것을 쪼개게 만들던 가중치 메모리가 한 자릿수 줄어든다.
  2. 그 자리를 KV cache가 차지한다. 살아 있는 시퀀스마다 자기 key·value를 가진다. 크기는 KV cache 레슨에 있다. 여기서 중요한 점은 가중치가 쓰지 않은 HBM은 모두 배치가 되고, 배치가 가중치 읽기를 나눠 낸다는 것이다.
  3. step 하나하나가 지연이다. decode는 시퀀스마다 step당 한 토큰을 수천 번 반복한다. 15 µs짜리 collective는 몇 초짜리 학습 step에서는 무시되지만, 층마다 두 번씩 치르면 20 ms decode step의 큰 몫이 된다.

그래서 서빙 계획은 네 가지를 동시에 노린다. 가중치를 넣고, KV 자리를 남기고, step당 통신을 짧게 하고, 가중치 읽기 한 번 뒤에 충분한 토큰을 모아 그 읽기를 나눠 내게 한다.

축마다 토큰 하나당 무엇이 오가는가

hidden 크기 dd인 층 하나와 그 step의 토큰 BB개를 생각한다(decode에서 BB = 시퀀스 수). activation은 BF16(2바이트)이다.

Tensor parallelism (TP, 차수 tt). Megatron-LM은 attention을 head로(Q, K, V는 column-parallel, 출력 projection은 row-parallel), MLP를 중간 차원으로(up/gate는 column-parallel, down은 row-parallel) 나눈다. row-parallel matmul은 GPU마다 전체 B×dB \times d 출력의 부분합을 남기므로, 층마다 attention 끝과 MLP 끝에서 B×dB \times d의 all-reduce가 한 번씩 필요하다. ring all-reduce에서 GPU 하나가 보내는 양은

2⏟attn + MLP×2(t−1)t×d×2 bytes(토큰 하나, 층 하나당)\underbrace{2}_{\text{attn + MLP}} \times \frac{2(t-1)}{t} \times d \times 2\ \text{bytes} \quad \text{(토큰 하나, 층 하나당)}

이다. d=7168d = 7168, t=8t = 8이면 GPU당 49 KiB이고, tt장 모두가 이것을 한다. 하지만 decode에서 문제는 대역폭이 아니다. 메시지가 B⋅d⋅2B \cdot d \cdot 2바이트, 수십 KB뿐이라 all-reduce 하나의 비용은 거의 고정 지연이고, 61층 모델은 step마다 그것을 2×61=1222 \times 61 = 122번 낸다. TP가 NVLink 영역 안에 머무는 이유다.

Pipeline parallelism (PP, stage pp개). 층을 연속된 pp개 stage로 나눈다. stage 경계는 토큰당 hidden state 하나, d×2d \times 2바이트를 층마다가 아니라 stage마다 한 번 넘긴다. 비용은 다른 곳에 있다. 토큰은 모든 stage를 차례로 지나야 하므로 출력 토큰당 시간이 stage step의 pp배가 되고, 모든 stage를 바쁘게 하려면 micro-batch pp개가 동시에 돌아야 한다. 같은 처리량에서 GPU당 KV도 줄지 않는다. GPU마다 층의 1/p1/p만 저장하지만 동시에 도는 시퀀스가 pp배이기 때문이다.

Data parallelism (DP). 복제본이다. 통신도 없고 가중치 절약도 없다. 처리량만 곱한다.

Expert parallelism (EP, 차수 GG). 각 MoE 층의 routed expert를 GPU GG장에 나눠 둔다. expert kk개를 고른 토큰은 그 expert를 가진 GPU로 dispatch되고, kk개 expert 출력은 gate 가중치를 곱해 토큰의 원래 GPU로 combine된다. DeepSeek-V3는 dispatch 전에 activation을 FP8로 양자화하고 combine은 BF16으로 둔다(보고서 §3.3.3). 그래서 kk개 expert가 모두 원격이면 토큰 하나, MoE 층 하나당

k⋅d⋅1⏟dispatch (FP8)+k⋅d⋅2⏟combine (BF16) bytes×G−1G\underbrace{k \cdot d \cdot 1}_{\text{dispatch (FP8)}} + \underbrace{k \cdot d \cdot 2}_{\text{combine (BF16)}} \ \text{bytes} \times \frac{G-1}{G}

이다. k=8k = 8, d=7168d = 7168이면 약 167 KiB다. 모델 전체로 보면 토큰당 EP가 TP8보다 오히려 적게 옮긴다(DeepSeek-V3 형태에서 9.4 MiB vs 23.4 MiB, 아래 코드가 둘 다 계산한다). 그러나 대부분이 노드 밖으로 나가고 InfiniBand는 느리다. V3 보고서는 H800 클러스터에서 NVLink 160 GB/s, IB 50 GB/s를 든다(§3.2.2). EP는 통신이 아니라 가중치 때문에 산다. 654B개의 routed expert 매개변수를 수백 장으로 나누면서도 GPU마다 expert를 통째로 돌리게 해 주는 유일한 축이다.

축무엇을 나누나토큰당 통신어디가 아픈가
TP tt모든 행렬층마다 dd all-reduce 두 번, 모든 GPU가step마다 지연 × 2L, NVLink 밖으로 나가면 나쁘다
PP pp층stage 경계마다 ddTPOT × pp, micro-batch pp개 필요
DP없음(복제)없음가중치 복제
EP GGexpertMoE 층마다 k⋅dk \cdot d 나가고 k⋅dk \cdot d 돌아옴노드를 넘는다, 부하 불균형

attention 배치는 KV cache가 정한다

TP에서 KV cache는 KV head로 나뉜다. KV head 8개인 GQA라면 TP8에서 GPU마다 KV head 하나, 8배 절약이다. t>nkvt > n_{kv}가 되면 head를 복제해야 한다. MLA(attention·KV 레슨)는 극단적인 경우다. decode에서 흡수(absorb)된 형태는 토큰당 576개 숫자짜리 latent 하나에 attention하고 이것을 모든 head가 공유하므로, TP rank마다 latent 전체가 필요하고 KV 절약은 없다. SGLang 팀의 large-EP 글은 DP attention을 고른 이유로 “KV cache 복제를 피한다”를 들고, vLLM의 wide-EP 글은 MLA에서 TP가 최적이 아닌 이유를 “rank마다 latent attention projection을 복제해야 해서”라고 쓴다.

그래서 MLA MoE의 정석 배치는 DP attention + EP expert다. GPU 하나하나가 자기 attention 복제본으로서 expert가 아닌 가중치 전부와 자기 시퀀스의 KV를 들고, MoE 층마다 모든 GPU가 하나의 all-to-all에 참여한다. 아래에서 직접 배치해 본다.

Left: one decode step of one pipeline stage on one GPU. HBM = reading this GPU's weights (blue) and its share of the KV cache (amber); tensor cores = FLOPs (green); network = TP all-reduces, EP dispatch/combine and the PP hand-off (red). The step ends at the black line. Right: tokens/s per GPU as the batch grows; grey = out of memory. Try: DeepSeek-V3 shape on 8 GPUs (does not fit) → 32 GPUs with EP; then switch experts to TP; raise attention TP with MLA and watch the batch limit (the latent KV is duplicated, not split); push b up until compute or the network dominates; tick overlap. All hardware numbers (bandwidths, FLOP/s, ~10–15 µs per collective) are assumed round values and expert load is taken as perfectly balanced, so read the shape, not the absolute numbers. 왼쪽: 한 pipeline stage의 decode 한 step을 GPU 하나에서 본 것. HBM = 이 GPU의 가중치(파랑)와 KV cache 몫(주황) 읽기, tensor core = FLOPs(초록), network = TP all-reduce, EP dispatch/combine, PP 전달(빨강). step은 검은 선에서 끝난다. 오른쪽: 배치에 따른 GPU당 토큰/초, 회색은 메모리 초과. 해 볼 것: DeepSeek-V3 형태를 8 GPU에(안 들어간다) → EP로 32 GPU에. 그다음 expert를 TP로 바꿔 보기. MLA에서 attention TP를 올리면 배치 한도가 어떻게 되는지(latent KV는 나뉘지 않고 복제된다). b를 올려 compute나 network가 지배할 때까지. overlap 체크. 하드웨어 수치(대역폭, FLOP/s, collective당 ~10–15 µs)는 가정한 어림값이고 expert 부하는 완전 균형으로 둔다. 절대값이 아니라 모양을 읽을 것.

Things to check in the planner (the hardware numbers are assumed round values, so read the shapes):

  1. DeepSeek-V3 shape, 8 GPUs, experts by EP. Weights alone are about 99 GB per GPU: out of memory. Move to 32 GPUs and the routed experts shrink to 20 GB per GPU, leaving room for about a hundred 4K-token sequences per GPU.
  2. Switch experts to TP. Each TP group must hold every expert, which is hundreds of GB per GPU at these sizes. EP is the only axis that makes the expert weights scale with N.
  3. Raise attention TP to 4 with the MLA model. Weights per GPU drop (the 17B of attention and other non-expert weights are now split), but max b does not rise in proportion, because the latent KV is duplicated on all four ranks. Do the same with the 70B GQA model and the KV is split. The V3 report’s decode setup in fact used TP4 attention with DP80 (§3.4) and the later production setup pure DP: these are two points on this trade-off.
  4. Push b up. At small b the HBM row is almost all blue: every GPU reads 17 GB of replicated non-expert weights for a handful of tokens. As b grows, the per-GPU throughput rises until the KV read (amber), the FLOPs (green) or the all-to-all (red) catches up. With EP across nodes the red bar is large; tick overlap and it hides behind the HBM time — this is what two-batch overlap buys.
  5. Try PP = 4 with the dense model on 32 GPUs and TP 8: TPOT quadruples while tokens/s per GPU barely moves.

Why wide EP: memory and tokens per expert

Two pieces of arithmetic explain why DeepSeek serves decode across 144–320 GPUs rather than on a few nodes.

Memory. With DP attention every GPU holds all non-expert weights (≈\approx 17B parameters for the V3 shape: 671B minus 58×25658 \times 256 experts of 3⋅7168⋅20483 \cdot 7168 \cdot 2048 parameters) plus 1/G1/G of the 654B routed-expert parameters. In FP8 that is 37.5 GB per GPU at G=32G = 32 and 21.6 GB at G=144G = 144 (redundant experts ignored). Every gigabyte saved is KV cache, i.e. batch.

Tokens per expert. A routed expert is a d×md \times m up/gate pair and an m×dm \times d down matrix. Processing nn tokens costs 2⋅3dm⋅n2 \cdot 3dm \cdot n FLOPs and reads 3dm⋅b3dm \cdot b bytes of weights, so its arithmetic intensity is

Iexpert=2nb FLOP/byte,n=Bglobal kE.I_{\text{expert}} = \frac{2n}{b}\ \text{FLOP/byte}, \qquad n = \frac{B_{\text{global}}\, k}{E}.

Here BglobalB_{\text{global}} is the number of tokens in the whole EP group’s step. With FP8 weights (b=1b = 1) and an H100-class ridge of about 590 FLOP/byte (989 TFLOP/s is BF16; the FP8 dense figure is about twice that, divided by 3.35 TB/s — an assumed spec-sheet value), an expert becomes compute-bound only at about 300 tokens. With top-8 of 256 that needs Bglobal≈300⋅256/8≈9,600B_{\text{global}} \approx 300 \cdot 256 / 8 \approx 9{,}600 tokens per step. No single node holds 9,600 concurrent decode sequences; a few hundred GPUs, each running a few dozen sequences of attention, do. Wide EP is how a decode step gathers enough tokens behind each expert’s weight read. (These two numbers are my estimates from the assumed ridge, not figures from DeepSeek.)

The price is that every GPU now waits on every other GPU at every MoE layer.

Load imbalance: noise and skew

An EP step is synchronous: the combine of layer ℓ\ell cannot finish until the slowest GPU has run its experts. If GPU gg processes ngn_g tokens, the MoE layer’s time is set by max⁡gng\max_g n_g, and the useful fraction is

efficiency=mean⁡gngmax⁡gng.\text{efficiency} = \frac{\operatorname{mean}_g n_g}{\max_g n_g}.

Two different things make max⁡/mean>1\max/\text{mean} > 1.

Sampling noise. Even with perfectly uniform routing, ngn_g is random. With μ=Bk/G\mu = Bk/G expected tokens per GPU and roughly Poisson fluctuations, the maximum of GG such counts is about μ+2ln⁡G μ\mu + \sqrt{2 \ln G}\,\sqrt{\mu}, so

max⁡mean≈1+2ln⁡Gμ.\frac{\max}{\text{mean}} \approx 1 + \sqrt{\frac{2 \ln G}{\mu}}.

At a fixed batch per GPU (μ\mu constant), widening EP makes it worse like ln⁡G\sqrt{\ln G}; more tokens per step make it better like 1/μ1/\sqrt{\mu}.

Popularity skew. Real routers do not use experts uniformly: the SGLang write-up observes that most experts are used infrequently while a small subset is heavily used. If expert ee is chosen with probability πe\pi_e, a GPU’s expected load is ∑e∈gπe\sum_{e \in g} \pi_e, and the imbalance of those sums is a floor that no amount of batching removes. Worse, the floor rises with GG: with 32 experts per GPU a hot expert is averaged with 31 others; with one expert per GPU it is not averaged at all.

The fix is placement. Redundant experts give hot experts extra replicas on other GPUs and split their tokens; the EPLB algorithm then packs replicas so that GPU loads are equal. DeepSeek’s EPLB repository has two policies: a hierarchical one, used when the number of nodes divides the number of expert groups (pack groups onto nodes, replicate within nodes, pack onto GPUs — it keeps group-limited routing’s locality and suits prefill’s smaller EP), and a global one that replicates across the whole cluster, for decode’s larger EP. Load is estimated from history; the README suggests a moving average. In the V3 report the prefill deployment carries 32 redundant experts so that each GPU hosts its 8 original experts plus one, re-selected from online statistics “e.g., every 10 minutes”; the decode deployment of the report gave each of 256 GPUs one expert and used 64 more GPUs for redundant and shared experts (§3.4).

플래너에서 확인할 것(하드웨어 수치는 가정한 어림값이니 모양을 읽는다).

  1. DeepSeek-V3 형태, GPU 8장, expert는 EP. 가중치만 GPU당 약 99 GB라 메모리를 넘는다. 32장으로 늘리면 routed expert가 GPU당 20 GB로 줄고, GPU마다 4K 토큰 시퀀스 백여 개를 둘 자리가 생긴다.
  2. expert를 TP로 바꾸기. TP 그룹마다 모든 expert를 들어야 해서, 이 크기에서는 GPU당 수백 GB다. expert 가중치가 N에 따라 줄어들게 하는 축은 EP뿐이다.
  3. MLA 모델에서 attention TP를 4로. GPU당 가중치는 줄지만(attention 등 expert가 아닌 17B가 나뉜다) b 최대치는 비례해서 늘지 않는다. latent KV가 네 rank 모두에 복제되기 때문이다. 70B GQA 모델로 같은 일을 하면 KV가 나뉜다. V3 보고서의 decode 구성은 실제로 attention을 TP4 + DP80으로 했고(§3.4) 나중의 운영 구성은 순수 DP였다. 이 trade-off 위의 두 점이다.
  4. b를 올리기. b가 작으면 HBM 줄이 거의 파랑이다. GPU마다 복제된 17 GB의 비-expert 가중치를 토큰 몇 개 때문에 읽는다. b가 커지면 GPU당 처리량이 올라가다가 KV 읽기(주황), FLOPs(초록), all-to-all(빨강) 중 하나가 따라잡는다. 노드를 넘는 EP에서는 빨간 막대가 크다. overlap을 체크하면 HBM 시간 뒤로 숨는다. two-batch overlap이 사는 것이 이것이다.
  5. dense 모델에 32장, TP 8, PP = 4를 해 보면 TPOT은 네 배가 되는데 GPU당 토큰/초는 거의 그대로다.

왜 wide EP인가: 메모리와 expert당 토큰

DeepSeek이 decode를 노드 몇 개가 아니라 GPU 144–320장에 걸쳐 서빙하는 이유는 두 가지 계산으로 설명된다.

메모리. DP attention에서 GPU마다 expert가 아닌 가중치 전부(V3 형태에서 약 17B: 671B에서 3⋅7168⋅20483 \cdot 7168 \cdot 2048개짜리 expert 58×25658 \times 256개를 뺀 것)와 654B routed expert 매개변수의 1/G1/G을 든다. FP8로 G=32G = 32이면 GPU당 37.5 GB, G=144G = 144이면 21.6 GB다(redundant expert 제외). 아낀 1 GB는 모두 KV cache, 곧 배치다.

expert당 토큰. routed expert는 d×md \times m up/gate 쌍과 m×dm \times d down 행렬이다. 토큰 nn개를 처리하면 FLOPs는 2⋅3dm⋅n2 \cdot 3dm \cdot n, 가중치 읽기는 3dm⋅b3dm \cdot b바이트이므로 산술 강도는

Iexpert=2nb FLOP/byte,n=Bglobal kEI_{\text{expert}} = \frac{2n}{b}\ \text{FLOP/byte}, \qquad n = \frac{B_{\text{global}}\, k}{E}

다. BglobalB_{\text{global}}은 EP 그룹 전체가 한 step에 처리하는 토큰 수다. FP8 가중치(b=1b = 1)와 H100급 ridge 약 590 FLOP/byte(989 TFLOP/s는 BF16이고 FP8 dense는 그 약 두 배, 이를 3.35 TB/s로 나눈 가정값)에서 expert는 토큰 300개쯤에서야 compute-bound가 된다. 256개 중 top-8이면 step당 Bglobal≈300⋅256/8≈9,600B_{\text{global}} \approx 300 \cdot 256 / 8 \approx 9{,}600 토큰이 필요하다. 동시 decode 시퀀스 9,600개를 노드 하나가 들 수는 없다. 각자 수십 개 시퀀스의 attention을 도는 GPU 수백 장이라면 된다. wide EP는 decode step이 expert 가중치 읽기 한 번 뒤에 충분한 토큰을 모으는 방법이다. (이 두 수치는 가정한 ridge로 낸 내 추정이지 DeepSeek의 수치가 아니다.)

대가는 MoE 층마다 모든 GPU가 다른 모든 GPU를 기다린다는 것이다.

부하 불균형: 잡음과 편중

EP step은 동기식이다. 층 ℓ\ell의 combine은 가장 느린 GPU가 expert를 다 돌릴 때까지 끝나지 않는다. GPU gg가 토큰 ngn_g개를 처리하면 MoE 층 시간은 max⁡gng\max_g n_g가 정하고, 쓸모 있는 비율은

efficiency=mean⁡gngmax⁡gng\text{efficiency} = \frac{\operatorname{mean}_g n_g}{\max_g n_g}

이다. max⁡/mean>1\max/\text{mean} > 1을 만드는 것은 서로 다른 두 가지다.

샘플링 잡음. routing이 완벽히 균등해도 ngn_g는 확률변수다. GPU당 기대 토큰 μ=Bk/G\mu = Bk/G, 대략 Poisson 요동이라면 이런 값 GG개의 최댓값은 약 μ+2ln⁡G μ\mu + \sqrt{2 \ln G}\,\sqrt{\mu}이므로

max⁡mean≈1+2ln⁡Gμ\frac{\max}{\text{mean}} \approx 1 + \sqrt{\frac{2 \ln G}{\mu}}

이다. GPU당 배치를 고정하면(μ\mu 일정) EP를 넓힐수록 ln⁡G\sqrt{\ln G}처럼 나빠지고, step당 토큰을 늘리면 1/μ1/\sqrt{\mu}처럼 좋아진다.

인기 편중. 실제 router는 expert를 고르게 쓰지 않는다. SGLang 글은 대부분의 expert가 드물게 쓰이고 일부가 집중적으로 쓰인다고 관찰한다. expert ee가 확률 πe\pi_e로 선택되면 GPU의 기대 부하는 ∑e∈gπe\sum_{e \in g} \pi_e이고, 이 합들의 불균형은 배치를 아무리 키워도 사라지지 않는 바닥이다. 더 나쁘게도 이 바닥은 GG와 함께 오른다. GPU당 expert가 32개면 hot expert가 나머지 31개와 평균되지만, GPU당 하나면 전혀 평균되지 않는다.

해법은 배치(placement)다. redundant expert는 hot expert에 다른 GPU의 복제본을 주어 토큰을 나누고, EPLB 알고리즘은 GPU 부하가 같아지도록 복제본을 채워 넣는다. DeepSeek의 EPLB 저장소에는 정책이 둘 있다. 노드 수가 expert group 수를 나누면 쓰는 계층적 정책(group을 노드에 채우고, 노드 안에서 복제하고, GPU에 채운다. group-limited routing의 지역성을 지키고 prefill의 작은 EP에 맞는다)과, 클러스터 전체에서 복제하는 전역 정책(decode의 큰 EP용)이다. 부하는 과거 통계로 추정하며 README는 이동평균을 예로 든다. V3 보고서의 prefill 구성은 redundant expert 32개를 두어 GPU마다 원래 expert 8개에 하나를 더 올리고, 온라인 통계로 “예컨대 10분마다” 다시 고른다. 보고서의 decode 구성은 GPU 256장에 expert를 하나씩 주고 64장을 redundant·shared expert에 썼다(§3.4).

Left: tokens each EP rank processes in one MoE layer (bars), the mean (dashed) and the max (red), which sets the layer's time. Right: max/mean as tokens per step grow — red without redundancy, green with EPLB, grey dashed = the part due to skew alone (no sampling noise). Set s = 0: imbalance is pure sampling noise and shrinks as T grows. Raise s: a floor appears that more tokens cannot remove — only placement can. Raise EP at fixed T: fewer experts per GPU, so less averaging and worse max/mean. Tick EPLB and add redundant slots: the skew floor vanishes and what remains is noise. 왼쪽: MoE 층 하나에서 EP rank마다 처리하는 토큰 수(막대), 평균(점선), 그리고 층 시간을 정하는 최댓값(빨강). 오른쪽: step당 토큰 수에 따른 max/mean. 빨강은 redundancy 없음, 초록은 EPLB, 회색 점선은 편중만의 몫(샘플링 잡음 없음). s = 0으로 두면 불균형은 순수 샘플링 잡음이라 T가 커지면 줄어든다. s를 올리면 토큰을 늘려도 사라지지 않는 바닥이 생긴다. 배치(placement)만이 그것을 없앤다. T를 고정하고 EP를 올리면 GPU당 expert가 줄어 평균 효과가 약해지고 max/mean이 나빠진다. EPLB를 켜고 redundant slot을 더하면 편중의 바닥이 사라지고 잡음만 남는다.

Things to check:

  1. s = 0, EP 64, EPLB off. Imbalance is pure noise: well above 1 at a few hundred tokens per step and falling toward 1 as T grows, roughly like the 1+2ln⁡G/μ1 + \sqrt{2\ln G/\mu} curve.
  2. s = 0.5. The red curve flattens onto the grey dashed floor. That floor is the skew; tokens cannot remove it.
  3. EP 256 with 256 experts (one expert per GPU) and s = 0.5: the hottest GPU does several times the mean, so the MoE layer runs at a fraction of its capacity.
  4. Tick EPLB with one redundant slot per GPU. The green curve drops to the noise level. Extra slots beyond that buy little; what remains is sampling noise, which only more tokens per step reduce.

How DeepSeek actually serves it

DeepSeek published its production inference setup in February 2025. Prefill and decode run on separate deployments (prefill–decode disaggregation, see the batching and scheduling lesson):

prefilldecode
routed expertsEP32EP144
MLA + shared expertDP32DP144
deployment unit4 nodes18 nodes
per GPU9 routed + 1 shared expert2 routed + 1 shared expert
redundant routed experts per unit3232

(256 + 32 = 288 routed experts, which is exactly 9 per GPU over 32 GPUs and 2 per GPU over 144.) Communication is hidden by splitting the batch into two micro-batches in prefill, and by a five-stage pipeline that splits attention into two steps in decode. There are three load balancers: prefill balances core-attention compute and input tokens per GPU, decode balances KV-cache usage and request counts per GPU — because with DP attention a GPU with more or longer sequences is itself a straggler — and the expert-parallel balancer minimises the maximum dispatch receive load. Over one 24-hour window the overview reports about 73.7k input tokens/s per H800 node in prefill (including cache hits) and about 14.8k output tokens/s per node in decode, with an average KV length of 4,989 tokens per output token. It also computes a theoretical cost-profit margin of 545% if every token were billed at R1 prices, and notes that actual revenue is substantially lower.

Why prefill and decode must separate under EP. vLLM’s post puts it in one line: “a single compute-bound prefill request can delay the forward pass of the entire EP group”. Because every MoE layer is a barrier across all GPUs, one rank chewing on a 32K-token prompt stalls hundreds of decoding ranks. There is also a kernel reason. DeepEP has a high-throughput path for prefill and training and a low-latency path for decode. Its README ties do_cpu_sync=True (exact output sizes on the CPU) to training and prefill, and GPU-side counts to decode. The SGLang write-up explains the consequence: normal dispatch produces symbolic shapes incompatible with CUDA graphs, so it does not suit decode; low-latency dispatch supports CUDA graphs but needs preallocated buffers of a fixed size; and without PD disaggregation the two modes cannot be used in the same communication group. The PyTorch code at the end of this lesson shows where that CPU sync comes from.

Open re-implementations. SGLang reproduced the design on 96 H100s (12 nodes) and reports 52.3k input and 22.3k output tokens/s per node at 2,000-token inputs, up to 5.2× the decode throughput of a TP16 baseline. Two of its measurements make this lesson’s points directly. EPLB gave 1.49× in prefill and 2.54× in decode, larger in decode because decode’s EP is wider and its per-step token count smaller. Two-batch overlap gave 27–35% in prefill, but in decode it was −27% at 32 tokens per device and +25.5% at 256: splitting a small batch in two halves each half’s arithmetic intensity, so overlap pays only once there is enough compute to hide the all-to-all behind. vLLM’s wide-EP post cites community benchmarks of about 2.2k tokens/s per H200 in multi-node deployments with the same ingredients (DP attention, EP, dual-batch overlap, EPLB, DeepEP kernels).

Architecture can also attack the all-to-all directly. Nemotron’s LatentMoE projects tokens to a smaller latent before routing, cutting dispatch and combine bytes by d/ℓd/\ell (4× in Ultra) and spending the saving on more experts (Nemotron 3 Ultra review); DeepSeek-V3’s node-limited routing caps each token at 4 nodes so that IB traffic per token is bounded (V3 review).

The trainer’s layout is not the rollout engine’s

An RL system holds the same weights twice, in two layouts, because training and serving are bound by different things. This is only a sketch from the serving side; the training-parallelism lesson covers the trainer in depth.

The trainer shards state. Mixed-precision Adam needs 2Ψ+2Ψ+12Ψ=16Ψ2\Psi + 2\Psi + 12\Psi = 16\Psi bytes for Ψ\Psi parameters (fp16 weights, fp16 gradients, and fp32 master weights plus two moments; ZeRO paper), before activations. ZeRO removes the replication of that state across data-parallel ranks in three stages: partitioning optimizer states gives a 4× memory reduction at the same communication volume as DP, adding gradients gives 8×, and adding parameters makes the reduction linear in the DP degree at 50% more communication (3Ψ3\Psi instead of 2Ψ2\Psi). PyTorch FSDP is the same idea in PyTorch; FSDP2’s fully_shard uses “DTensor-based dim-0 per-parameter sharding”, all-gathers each module’s parameters before forward and reduce-scatters gradients after backward. Megatron’s distributed optimizer is the ZeRO-1 equivalent for Megatron runs.

Megatron model parallelism for training. TP is the column-then-row split above, costing “two all-reduces in the forward path and two in the backward path” per layer (Shoeybi et al.). PP uses micro-batches to fill the pipeline; the default schedule’s bubble is (p−1)/m(p-1)/m for mm micro-batches, and the interleaved schedule gives each device vv smaller “virtual” stages to cut it to 1v⋅p−1m\tfrac{1}{v}\cdot\tfrac{p-1}{m} at vv times the communication (Narayanan et al.). For MoE, Megatron-Core’s parallel folding lets attention use TP × CP × DP × PP while the MoE layers use ETP × EP × EDP × PP; its guide recommends expert TP = 1 for fine-grained MoE and keeping EP × TP within one node.

trainerrollout engine
memory dominated byoptimizer state, gradients, activationsweights + KV cache
one stepforward + backward over long packed sequencesthousands of one-token decode steps
goaltokens/s for a fixed global batchtokens/s per GPU under a TPOT target
typical layoutFSDP / ZeRO-3, or TP × PP × EP with a distributed optimizersmall TP or DP attention + wide EP, replicas
collectivesall-gather / reduce-scatter per layer, TP all-reduces, PP send/recvper-layer all-to-all, few small all-reduces

So the two layouts almost never match, and every weight sync is a reshard: gather the trainer’s shards (FSDP dim-0 chunks, or TP/PP/EP slices), convert dtype if the rollout runs in FP8, and scatter into the engine’s layout (different TP degree, experts on different ranks, possibly hundreds of replicas). How that is done fast, and why different TP degrees and reduction orders make the two engines disagree in the last bits, is the subject of inference for RL.

Implementing dispatch and combine

The first block re-implements EP dispatch and combine in NumPy and checks it against a token-by-token reference MoE. The second simulates load imbalance under real top-k routing (Gumbel top-k, i.e. sampling kk experts without replacement in proportion to popularity) and runs a small EPLB-style replicate-then-pack heuristic. The third computes the traffic and memory numbers quoted above.

NumPy EP dispatch → expert → combine, checked against a dense reference
import numpy as np
rng = np.random.default_rng(0)

# toy MoE: E SwiGLU experts, top-k routing, G EP ranks owning E/G experts each
T, d, m, E, k, G = 64, 16, 32, 8, 2, 4
E_local = E // G
x = rng.standard_normal((T, d))
Wr = rng.standard_normal((d, E)) * 0.5
W1 = rng.standard_normal((E, d, m)) / np.sqrt(d)
W3 = rng.standard_normal((E, d, m)) / np.sqrt(d)
W2 = rng.standard_normal((E, m, d)) / np.sqrt(m)

def expert(e, h):                        # SwiGLU expert e on rows h: (n, d) -> (n, d)
    a, b = h @ W1[e], h @ W3[e]
    return (a / (1 + np.exp(-a)) * b) @ W2[e]

logits = x @ Wr
p = np.exp(logits - logits.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
idx = np.argsort(-p, axis=1)[:, :k]                        # (T, k) chosen experts
gate = np.take_along_axis(p, idx, 1); gate /= gate.sum(1, keepdims=True)

# reference: token-by-token loop over the chosen experts
ref = np.zeros_like(x)
for t in range(T):
    for j in range(k):
        ref[t] += gate[t, j] * expert(idx[t, j], x[t:t + 1])[0]

# EP: token t lives on rank src[t]; dispatch -> local experts -> combine
src = np.repeat(np.arange(G), T // G)
flat_e = idx.reshape(-1)                                   # one entry per (token, slot) pair
flat_t = np.repeat(np.arange(T), k)
dst = flat_e // E_local                                    # destination rank of each pair
traffic = np.zeros((G, G), dtype=np.int64)                 # pairs sent src -> dst
np.add.at(traffic, (src[flat_t].astype(np.intp), dst.astype(np.intp)), 1)

order = np.lexsort((flat_e, dst))                          # sort pairs by dst rank, then expert
y_pair = np.zeros((T * k, d))
for r in range(G):                                         # each rank runs only its own experts
    pairs = order[dst[order] == r]                         # = what rank r receives (dispatch)
    h = x[flat_t[pairs]]
    for e in range(r * E_local, (r + 1) * E_local):
        sel = flat_e[pairs] == e
        if sel.any():
            y_pair[pairs[sel]] = expert(e, h[sel])         # result returns to its pair slot (combine)
out = np.zeros_like(x)
np.add.at(out, flat_t.astype(np.intp), gate.reshape(-1)[:, None] * y_pair)

print("all-to-all matrix: rows = source rank, cols = destination rank (token copies)")
print(traffic)
print(f"local fraction = {np.trace(traffic) / traffic.sum():.2f}   (uniform routing: 1/G = {1 / G:.2f})")
print(f"max |EP output - reference| = {np.abs(out - ref).max():.1e}")
 

The all-to-all matrix is the whole communication pattern: off-diagonal entries are token copies that cross ranks, and with uniform routing only about 1/G1/G of the copies stay home. The output matches the reference to rounding error, as it must: EP changes where each expert runs, not what it computes (the order of the final kk-term sum can differ between implementations, which is a bitwise, not a mathematical, difference — it matters for RL, see the callout below).

NumPy Load imbalance vs EP size, and EPLB-style redundant experts
import time
t0 = time.time()
rng = np.random.default_rng(1)
E, k = 256, 8                                              # DeepSeek-V3-shaped routing: top-8 of 256

def popularity(skew):                                      # Zipf-like expert popularity, shuffled over ids
    w = (np.arange(E) + 1.0) ** (-skew)
    return rng.permutation(w / w.sum())

def route(pop, T):                                         # top-k without replacement ∝ pop (Gumbel top-k)
    g = np.log(pop) - np.log(-np.log(rng.random((T, E))))
    return np.argpartition(-g, k, axis=1)[:, :k]

def expert_counts(idx):
    return np.bincount(idx.reshape(-1).astype(np.intp), minlength=E).astype(float)

def gpu_load(counts, place, reps, G):                      # tokens processed by each GPU
    load = np.zeros(G)
    for e, gpus in enumerate(place):
        for g in gpus:
            load[g] += counts[e] / reps[e]                 # replicas of e split its tokens evenly
    return load

def contiguous(G):                                         # no redundancy: E/G consecutive experts per GPU
    return [[e // (E // G)] for e in range(E)], np.ones(E)

def eplb(expected, G, r):                                  # replicate hot experts, then balanced packing
    reps = np.ones(E)
    for _ in range(G * r):                                 # G*r extra replicas (r per GPU)
        reps[np.argmax(expected / reps)] += 1
    items = sorted([(expected[e] / reps[e], e) for e in range(E) for _ in range(int(reps[e]))], reverse=True)
    slots, load = np.full(G, (E + G * r) // G), np.zeros(G)
    place = [[] for _ in range(E)]
    for w, e in items:                                     # heaviest replica -> least-loaded GPU with a free slot
        free = np.where(slots > 0)[0]
        g = free[np.argmin(load[free])]
        place[e].append(g); load[g] += w; slots[g] -= 1
    return place, reps

def imbalance(load):
    return load.max() / load.mean()

print("max/mean GPU load of one MoE layer (1.00 = perfect; step time ∝ max)")
print(f"{'skew':>4} {'tokens':>6} " + " ".join(f"EP{G:<4}" for G in (8, 32, 64, 256)))
for skew in (0.0, 0.5):
    pop = popularity(skew)
    for T in (256, 4096):
        c = expert_counts(route(pop, T))
        row = [imbalance(gpu_load(c, *contiguous(G), G)) for G in (8, 32, 64, 256)]
        print(f"{skew:>4} {T:>6} " + " ".join(f"{v:6.2f}" for v in row))

print("\nEPLB-style replication + packing, EP64, skew 0.5, 4096 tokens/step")
pop = popularity(0.5)
history = expert_counts(route(pop, 16384))                 # load statistics from earlier traffic
now = expert_counts(route(pop, 4096))                      # the step we actually serve
for r in (0, 1, 2, 4):
    place, reps = eplb(history, 64, r) if r else contiguous(64)
    print(f"  redundant experts/GPU = {r}: max/mean = {imbalance(gpu_load(now, place, reps, 64)):.2f}")
print(f"\n(done in {time.time() - t0:.1f}s)")
 

Read the table by rows and columns. Without skew, imbalance falls with tokens and rises with EP (1.24 at EP256 even with 4,096 tokens). With skew 0.5 it no longer falls with tokens, and at EP256 the hottest GPU does several times the mean. One redundant expert per GPU, placed from historical counts, brings EP64 back to about 1.1 on a new step; more replicas do not help because what is left is noise.

NumPy Traffic per token, tokens per expert, and weights per GPU (DeepSeek-V3 shape)
# DeepSeek-V3 shape (report / config): d=7168, 61 layers (3 dense + 58 MoE), 256 routed experts of
# intermediate size 2048, top-8, + 1 shared expert. Byte sizes: BF16 activations = 2, FP8 dispatch = 1.
d, L, L_moe, E, k, m = 7168, 61, 58, 256, 8, 2048
expert_params = 3 * d * m                                  # gate, up, down of one routed expert
routed_total = L_moe * E * expert_params
rest = 671e9 - routed_total                                # everything that is not a routed expert
print(f"routed experts: {routed_total / 1e9:.0f}B params; everything else ≈ {rest / 1e9:.0f}B (from the 671B total)")
print(f"active per token ≈ {(rest + L_moe * k * expert_params) / 1e9:.1f}B  (report: 37B)\n")

def tp_bytes(t):          # per token, per layer, sent by EACH GPU: 2 ring all-reduces of a d-vector
    return 2 * 2 * (t - 1) / t * d * 2
def ep_bytes(G):          # per token, per MoE layer: k copies out (FP8) and k results back (BF16)
    return k * d * (1 + 2) * (G - 1) / G
def pp_bytes():           # per token, per stage boundary: one BF16 hidden state
    return d * 2

print("communication per token")
for t in (4, 8, 16):
    print(f"  TP{t:<3}: {tp_bytes(t) / 1024:6.1f} KiB per layer per GPU  x{t} GPUs x{L} layers "
          f"= {tp_bytes(t) * t * L / 2**20:5.1f} MiB moved per token")
for G in (32, 144, 320):
    print(f"  EP{G:<3}: {ep_bytes(G) / 1024:6.1f} KiB per MoE layer           x{L_moe} layers "
          f"= {ep_bytes(G) * L_moe / 2**20:5.1f} MiB moved per token")
print(f"  PP    : {pp_bytes() / 1024:6.1f} KiB per stage boundary (independent of layers)")

# Why wide EP: tokens per expert decide whether expert GEMMs are memory- or compute-bound
ridge = 1979e12 / 3.35e12          # assumed H100/H800-class FP8 dense FLOP/s over HBM bytes/s
print(f"\nexpert GEMM, FP8 weights: intensity = 2n FLOP/byte for n tokens; ridge ≈ {ridge:.0f}")
for B in (256, 2048, 16384, 65536):
    n = B * k / E
    print(f"  global decode batch {B:>6} -> {n:7.1f} tokens/expert -> intensity {2 * n:7.1f} "
          f"({'memory' if 2 * n < ridge else 'compute'}-bound)")

# Weights per GPU when experts are spread over G GPUs and the rest is replicated (DP attention)
print("\nFP8 weights per GPU (non-expert part replicated, routed experts split; redundancy ignored)")
for G in (8, 32, 144, 320):
    per_gpu = rest + routed_total / G
    print(f"  {G:>3} GPUs: {per_gpu / 1e9:5.1f} GB   ({E / G:5.2f} routed experts per GPU per layer)")
 

In a real engine the all-to-all is a collective with sizes known only at run time. The PyTorch version below makes that explicit: a first all-to-all exchanges the per-rank counts, .tolist() brings them to the CPU to size the receive buffers, and only then can the payload move. That CPU round trip is exactly what DeepEP’s low-latency mode avoids by preallocating a fixed-size buffer, and why it is the mode that works with CUDA graphs.

PyTorch PyTorch: EP dispatch/combine with all_to_all_single (one process per GPU) 로컬에서 실행run locally (pip install torch)
import torch
import torch.distributed as dist

@torch.no_grad()
def ep_moe_forward(x, router_logits, experts, k, n_experts):
    """x: (T, d) tokens on this rank; router_logits: (T, E).
    experts: the E/world experts this rank owns; rank r owns ids [r*E_local, (r+1)*E_local)."""
    world, rank = dist.get_world_size(), dist.get_rank()
    E_local = n_experts // world
    T, d = x.shape
    gate, idx = router_logits.softmax(-1).topk(k, dim=-1)              # (T, k)
    gate = gate / gate.sum(-1, keepdim=True)

    flat_e = idx.reshape(-1)                                            # (T*k,) one per (token, slot)
    order = torch.argsort(flat_e, stable=True)                          # group pairs by expert → by rank
    tok = order // k                                                    # source token of each sorted pair
    e_sorted = flat_e[order]
    x_send = x[tok]                                                     # (T*k, d), contiguous per rank

    send_counts = torch.bincount(e_sorted // E_local, minlength=world)  # pairs for each destination
    recv_counts = torch.empty_like(send_counts)
    dist.all_to_all_single(recv_counts, send_counts)                    # 1) exchange sizes
    s, r = send_counts.tolist(), recv_counts.tolist()                   #    CPU sync: sizes needed on host

    x_recv = x.new_empty(sum(r), d)
    dist.all_to_all_single(x_recv, x_send, output_split_sizes=r, input_split_sizes=s)    # 2) dispatch
    e_recv = e_sorted.new_empty(sum(r))
    dist.all_to_all_single(e_recv, e_sorted, output_split_sizes=r, input_split_sizes=s)  #    expert ids

    y_recv = torch.empty_like(x_recv)
    local = e_recv - rank * E_local
    for j, expert in enumerate(experts):                                # grouped GEMM in real kernels
        mask = local == j
        if mask.any():
            y_recv[mask] = expert(x_recv[mask])

    y_back = torch.empty_like(x_send)
    dist.all_to_all_single(y_back, y_recv, output_split_sizes=s, input_split_sizes=r)    # 3) combine
    out = torch.zeros_like(x)
    w = gate.reshape(-1)[order].unsqueeze(-1).to(x.dtype)
    out.index_add_(0, tok, y_back * w)                                  # weighted sum of the k results
    return out
 
확인 문제Check yourself

DeepSeek-V3 uses MLA. Why does its serving stack run attention data-parallel (one replica per GPU) rather than tensor-parallel across the 8 GPUs of a node?

In decode, the absorbed MLA attends over one 576576-number latent per token that every head reads. Splitting heads across TP ranks therefore does not split the cache: each rank stores the whole latent for its sequences, so the KV per GPU is the same as with no TP while the batch per GPU is not larger. With DP attention each GPU stores the latents of its own sequences only. TP still reduces the weight read (the planner shows the trade-off), which is why the V3 report’s decode configuration used a small TP4 for attention and the later production one pure DP.

확인 문제Check yourself

A decode step over the whole EP group processes 8,192 tokens with top-8 routing over 256 experts and perfect balance. How many tokens does each routed expert see per layer, and what is its arithmetic intensity with FP8 weights?

n=Bk/E=8192⋅8/256=256n = B k / E = 8192 \cdot 8 / 256 = 256 tokens, and I=2n/b=512I = 2n/b = 512 FLOP/byte for b=1b = 1. That is just under an assumed FP8 ridge of about 590, so the expert GEMM is near the balance point. With 8 GPUs instead of a few hundred, the same per-GPU batch would give 8× fewer tokens per expert and a memory-bound expert layer.

Summary

  • Serving drops gradients and optimiser state but adds the KV cache; every byte of HBM not used by weights becomes batch, and batch amortises the weight read. Decode steps are short, so per-collective latency matters.
  • Per token per layer: TP sends two all-reduces of dd (2⋅2(t−1)t⋅2d2 \cdot \tfrac{2(t-1)}{t} \cdot 2d bytes per GPU, latency-bound at decode); PP sends 2d2d bytes per stage boundary but multiplies TPOT by pp; DP sends nothing; EP sends kdk d (FP8) out and kdk d (BF16) back per MoE layer, mostly across nodes.
  • MLA’s single shared latent makes TP useless for KV, so MLA MoEs are served with DP attention + wide EP.
  • Wide EP buys memory (routed experts split GG ways) and tokens per expert (n=Bk/En = Bk/E, intensity 2n/b2n/b); an FP8 expert needs a few hundred tokens per step to approach compute-bound, i.e. a global decode batch of thousands.
  • The step waits for the most loaded GPU. Imbalance = sampling noise (≈1+2ln⁡G/μ\approx 1 + \sqrt{2\ln G/\mu}, shrinks with tokens) + popularity skew (a floor that grows with GG). Redundant experts + EPLB remove the skew; only more tokens remove the noise.
  • In practice (DeepSeek, SGLang, vLLM): prefill EP32 and decode EP144 on separate deployments, DeepEP high-throughput vs low-latency kernels, two-batch overlap that pays only at large per-device batches, and EPLB worth 1.5× in prefill and 2.5× in decode.
  • Trainers shard optimizer state, gradients and parameters (ZeRO, FSDP, distributed optimizer) and use TP × PP × EP shaped for backward; rollout engines shard for KV and per-step latency. Weight sync between them is always a reshard.

확인할 것:

  1. s = 0, EP 64, EPLB 끔. 불균형은 순수 잡음이다. step당 토큰이 수백 개면 1보다 꽤 크고, T가 커지면 대략 1+2ln⁡G/μ1 + \sqrt{2\ln G/\mu}처럼 1로 내려간다.
  2. s = 0.5. 빨간 곡선이 회색 점선 바닥 위에서 평평해진다. 그 바닥이 편중이고, 토큰으로는 없앨 수 없다.
  3. expert 256개에 EP 256(GPU당 expert 하나), s = 0.5: 가장 바쁜 GPU가 평균의 몇 배를 하므로 MoE 층이 용량의 일부로만 돈다.
  4. EPLB를 켜고 GPU당 redundant slot 하나. 초록 곡선이 잡음 수준으로 내려온다. 그 이상의 slot은 별 도움이 없다. 남은 것은 샘플링 잡음이고, 그것은 step당 토큰을 늘려야만 준다.

DeepSeek은 실제로 어떻게 서빙하는가

DeepSeek은 2025년 2월에 운영 중인 추론 구성을 공개했다. prefill과 decode는 따로 배포된다(prefill–decode 분리, 배칭·스케줄링 레슨 참고).

prefilldecode
routed expertEP32EP144
MLA + shared expertDP32DP144
배포 단위노드 4개노드 18개
GPU당routed 9 + shared 1routed 2 + shared 1
단위당 redundant routed expert3232

(256 + 32 = 288개의 routed expert는 GPU 32장에 정확히 9개씩, 144장에 2개씩이다.) 통신은 prefill에서는 배치를 micro-batch 둘로 나눠, decode에서는 attention을 두 단계로 쪼갠 5단계 pipeline으로 숨긴다. load balancer는 셋이다. prefill용은 GPU당 core-attention 계산량과 입력 토큰 수를, decode용은 GPU당 KV cache 사용량과 요청 수를 맞춘다. DP attention에서는 시퀀스가 많거나 긴 GPU 자체가 낙오자(straggler)가 되기 때문이다. expert-parallel balancer는 dispatch 수신 부하의 최댓값을 최소화한다. 24시간 구간에서 overview는 prefill에서 H800 노드당 입력 약 73.7k 토큰/초(cache hit 포함), decode에서 노드당 출력 약 14.8k 토큰/초, 출력 토큰당 평균 KV 길이 4,989 토큰을 보고한다. 모든 토큰을 R1 가격으로 받았다면 이론적 원가 대비 이익률이 545%라는 계산도 내놓되, 실제 매출은 그보다 훨씬 낮다고 밝힌다.

EP에서 prefill과 decode를 나눠야 하는 이유. vLLM 글은 한 줄로 말한다. “compute-bound prefill 요청 하나가 EP 그룹 전체의 forward를 늦출 수 있다.” MoE 층마다 모든 GPU에 걸친 barrier가 있으므로, 32K 토큰 프롬프트를 씹고 있는 rank 하나가 decode 중인 rank 수백 개를 멈춘다. 커널 쪽 이유도 있다. DeepEP에는 prefill·학습용 고처리량 경로와 decode용 저지연 경로가 있다. README는 do_cpu_sync=True(CPU에서 정확한 출력 크기를 얻음)를 학습·prefill에, GPU 쪽 count를 decode에 연결한다. SGLang 글이 그 결과를 설명한다. normal dispatch는 CUDA graph와 맞지 않는 symbolic shape를 만들어 decode에 맞지 않고, low-latency dispatch는 CUDA graph를 지원하지만 고정 크기 버퍼를 미리 잡아야 하며, PD 분리 없이는 두 모드를 같은 통신 그룹에서 함께 쓸 수 없다. 이 레슨 끝의 PyTorch 코드가 그 CPU 동기화가 어디서 오는지 보여 준다.

공개 재현. SGLang은 H100 96장(노드 12개)으로 이 설계를 재현해 입력 2,000 토큰에서 노드당 입력 52.3k, 출력 22.3k 토큰/초를 보고하며, decode 처리량은 TP16 기준선의 최대 5.2배다. 측정 중 둘이 이 레슨의 요점을 그대로 보여 준다. EPLB는 prefill에서 1.49배, decode에서 2.54배였다. decode의 EP가 더 넓고 step당 토큰이 더 적어서 decode에서 더 크다. two-batch overlap은 prefill에서 27–35%였지만 decode에서는 device당 32 토큰일 때 −27%, 256 토큰일 때 +25.5%였다. 작은 배치를 둘로 쪼개면 각 절반의 산술 강도가 반이 되므로, all-to-all을 뒤에 숨길 만큼 계산이 있을 때만 overlap이 이득이다. vLLM의 wide-EP 글은 같은 재료(DP attention, EP, dual-batch overlap, EPLB, DeepEP 커널)로 다중 노드 배포에서 H200당 약 2.2k 토큰/초를 낸 커뮤니티 벤치마크를 인용한다.

아키텍처가 all-to-all을 직접 공략하기도 한다. Nemotron의 LatentMoE는 routing 전에 토큰을 작은 latent로 projection해 dispatch·combine 바이트를 d/ℓd/\ell배(Ultra에서 4배) 줄이고 그 절약을 expert 수에 쓴다(Nemotron 3 Ultra 리뷰). DeepSeek-V3의 node-limited routing은 토큰마다 노드 4개로 제한해 토큰당 IB 통신을 묶는다(V3 리뷰).

학습기의 배치는 rollout 엔진의 배치가 아니다

RL 시스템은 같은 가중치를 두 가지 배치로 두 번 들고 있다. 학습과 서빙을 묶는 제약이 다르기 때문이다. 여기서는 서빙 쪽에서 본 스케치만 하고, 학습기는 학습 병렬화 레슨이 깊게 다룬다.

학습기는 state를 쪼갠다. mixed-precision Adam은 매개변수 Ψ\Psi개에 대해 activation을 빼고도 2Ψ+2Ψ+12Ψ=16Ψ2\Psi + 2\Psi + 12\Psi = 16\Psi바이트가 필요하다(fp16 가중치, fp16 gradient, fp32 master 가중치와 moment 둘. ZeRO 논문). ZeRO는 data-parallel rank 사이에 이 state가 복제되는 것을 세 단계로 없앤다. optimizer state를 나누면 DP와 같은 통신량으로 메모리가 4배 줄고, gradient까지 나누면 8배, 매개변수까지 나누면 통신이 50% 늘어나는 대신(2Ψ2\Psi 대신 3Ψ3\Psi) DP 차수에 비례해 준다. PyTorch FSDP는 같은 생각을 PyTorch로 구현한 것이다. FSDP2의 fully_shard는 “DTensor 기반 dim-0 매개변수별 sharding”을 쓰고, 모듈마다 forward 전에 매개변수를 all-gather하고 backward 뒤에 gradient를 reduce-scatter한다. Megatron의 distributed optimizer는 Megatron에서 쓰는 ZeRO-1에 해당한다.

학습용 Megatron 모델 병렬화. TP는 위의 column→row 분할이고 층마다 “forward에서 all-reduce 두 번, backward에서 두 번”이 든다(Shoeybi 외). PP는 micro-batch로 pipeline을 채운다. 기본 스케줄의 bubble은 micro-batch mm개에서 (p−1)/m(p-1)/m이고, interleaved 스케줄은 device마다 더 작은 “가상” stage vv개를 주어 통신이 vv배 느는 대신 bubble을 1v⋅p−1m\tfrac{1}{v}\cdot\tfrac{p-1}{m}로 줄인다(Narayanan 외). MoE에 대해 Megatron-Core의 parallel folding은 attention에 TP × CP × DP × PP를, MoE 층에 ETP × EP × EDP × PP를 따로 쓰게 하며, 가이드는 fine-grained MoE에서 expert TP = 1, EP × TP를 노드 하나 안에 두라고 권한다.

학습기rollout 엔진
메모리를 차지하는 것optimizer state, gradient, activation가중치 + KV cache
step 하나긴 packed 시퀀스의 forward + backward한 토큰짜리 decode step 수천 번
목표고정된 global batch에서 토큰/초TPOT 목표 아래 GPU당 토큰/초
흔한 배치FSDP / ZeRO-3, 또는 TP × PP × EP + distributed optimizer작은 TP나 DP attention + wide EP, 복제본
collective층마다 all-gather / reduce-scatter, TP all-reduce, PP send/recv층마다 all-to-all, 작은 all-reduce 몇 번

그래서 두 배치는 거의 맞지 않고 가중치 동기화는 매번 re-shard다. 학습기의 조각(FSDP의 dim-0 chunk나 TP/PP/EP 조각)을 모으고, rollout이 FP8로 돈다면 dtype을 바꾸고, 엔진의 배치(다른 TP 차수, 다른 rank의 expert, 때로는 수백 개의 복제본)로 흩뿌린다. 그것을 빠르게 하는 방법과, 서로 다른 TP 차수와 합의 순서 때문에 두 엔진이 마지막 비트에서 어긋나는 이유는 RL을 위한 추론에서 다룬다.

dispatch와 combine 구현하기

첫 블록은 EP dispatch와 combine을 NumPy로 다시 짜고, 토큰 하나씩 도는 기준 MoE와 비교한다. 둘째는 실제 top-k routing(Gumbel top-k, 즉 인기도에 비례해 expert kk개를 비복원 추출)에서 부하 불균형을 시뮬레이션하고, EPLB 식으로 복제한 뒤 채워 넣는 작은 휴리스틱을 돌린다. 셋째는 위에서 인용한 통신량과 메모리 수치를 계산한다.

NumPy EP dispatch → expert → combine, dense 기준과 비교
import numpy as np
rng = np.random.default_rng(0)

# 장난감 MoE: SwiGLU expert E개, top-k routing, EP rank G개가 expert를 E/G개씩 가진다
T, d, m, E, k, G = 64, 16, 32, 8, 2, 4
E_local = E // G
x = rng.standard_normal((T, d))
Wr = rng.standard_normal((d, E)) * 0.5
W1 = rng.standard_normal((E, d, m)) / np.sqrt(d)
W3 = rng.standard_normal((E, d, m)) / np.sqrt(d)
W2 = rng.standard_normal((E, m, d)) / np.sqrt(m)

def expert(e, h):                        # expert e를 행 h에 적용: (n, d) -> (n, d)
    a, b = h @ W1[e], h @ W3[e]
    return (a / (1 + np.exp(-a)) * b) @ W2[e]

logits = x @ Wr
p = np.exp(logits - logits.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
idx = np.argsort(-p, axis=1)[:, :k]                        # (T, k) 고른 expert
gate = np.take_along_axis(p, idx, 1); gate /= gate.sum(1, keepdims=True)

# 기준: 토큰 하나씩, 고른 expert를 돈다
ref = np.zeros_like(x)
for t in range(T):
    for j in range(k):
        ref[t] += gate[t, j] * expert(idx[t, j], x[t:t + 1])[0]

# EP: 토큰 t는 rank src[t]에 산다. dispatch -> 로컬 expert -> combine
src = np.repeat(np.arange(G), T // G)
flat_e = idx.reshape(-1)                                   # (토큰, slot) 쌍마다 하나
flat_t = np.repeat(np.arange(T), k)
dst = flat_e // E_local                                    # 각 쌍의 목적지 rank
traffic = np.zeros((G, G), dtype=np.int64)                 # src -> dst로 보낸 쌍의 수
np.add.at(traffic, (src[flat_t].astype(np.intp), dst.astype(np.intp)), 1)

order = np.lexsort((flat_e, dst))                          # 목적지 rank, 그다음 expert 순으로 정렬
y_pair = np.zeros((T * k, d))
for r in range(G):                                         # rank마다 자기 expert만 돌린다
    pairs = order[dst[order] == r]                         # = rank r이 받는 것(dispatch)
    h = x[flat_t[pairs]]
    for e in range(r * E_local, (r + 1) * E_local):
        sel = flat_e[pairs] == e
        if sel.any():
            y_pair[pairs[sel]] = expert(e, h[sel])         # 결과는 원래 쌍의 자리로 돌아간다(combine)
out = np.zeros_like(x)
np.add.at(out, flat_t.astype(np.intp), gate.reshape(-1)[:, None] * y_pair)

print("all-to-all 행렬: 행 = 보내는 rank, 열 = 받는 rank (토큰 사본 수)")
print(traffic)
print(f"로컬 비율 = {np.trace(traffic) / traffic.sum():.2f}   (균등 routing이면 1/G = {1 / G:.2f})")
print(f"max |EP 출력 - 기준| = {np.abs(out - ref).max():.1e}")
 

all-to-all 행렬이 통신 패턴의 전부다. 대각선 밖의 값은 rank를 넘는 토큰 사본이고, 균등 routing이면 사본의 1/G1/G 정도만 집에 남는다. 출력은 반올림 오차 수준에서 기준과 같다. 당연하다. EP는 expert가 어디서 도는지를 바꿀 뿐 무엇을 계산하는지는 바꾸지 않는다(마지막 kk항 합의 순서는 구현마다 다를 수 있는데, 이것은 수학이 아니라 비트 수준의 차이다. RL에서는 이것이 중요하다. 아래 callout 참고).

NumPy EP 크기에 따른 부하 불균형, EPLB식 redundant expert
import time
t0 = time.time()
rng = np.random.default_rng(1)
E, k = 256, 8                                              # DeepSeek-V3 형태 routing: 256개 중 top-8

def popularity(skew):                                      # Zipf 꼴 expert 인기도, id에 섞어 배치
    w = (np.arange(E) + 1.0) ** (-skew)
    return rng.permutation(w / w.sum())

def route(pop, T):                                         # pop에 비례한 비복원 top-k (Gumbel top-k)
    g = np.log(pop) - np.log(-np.log(rng.random((T, E))))
    return np.argpartition(-g, k, axis=1)[:, :k]

def expert_counts(idx):
    return np.bincount(idx.reshape(-1).astype(np.intp), minlength=E).astype(float)

def gpu_load(counts, place, reps, G):                      # GPU마다 처리하는 토큰 수
    load = np.zeros(G)
    for e, gpus in enumerate(place):
        for g in gpus:
            load[g] += counts[e] / reps[e]                 # e의 복제본들이 토큰을 고르게 나눈다
    return load

def contiguous(G):                                         # redundancy 없음: GPU마다 연속된 expert E/G개
    return [[e // (E // G)] for e in range(E)], np.ones(E)

def eplb(expected, G, r):                                  # hot expert 복제 후 균형 있게 채우기
    reps = np.ones(E)
    for _ in range(G * r):                                 # 복제본 G*r개 추가 (GPU당 r개)
        reps[np.argmax(expected / reps)] += 1
    items = sorted([(expected[e] / reps[e], e) for e in range(E) for _ in range(int(reps[e]))], reverse=True)
    slots, load = np.full(G, (E + G * r) // G), np.zeros(G)
    place = [[] for _ in range(E)]
    for w, e in items:                                     # 가장 무거운 복제본 -> 빈 slot이 있는 가장 한가한 GPU
        free = np.where(slots > 0)[0]
        g = free[np.argmin(load[free])]
        place[e].append(g); load[g] += w; slots[g] -= 1
    return place, reps

def imbalance(load):
    return load.max() / load.mean()

print("MoE 층 하나의 GPU 부하 max/mean (1.00 = 완벽, step 시간 ∝ max)")
print(f"{'skew':>4} {'tokens':>6} " + " ".join(f"EP{G:<4}" for G in (8, 32, 64, 256)))
for skew in (0.0, 0.5):
    pop = popularity(skew)
    for T in (256, 4096):
        c = expert_counts(route(pop, T))
        row = [imbalance(gpu_load(c, *contiguous(G), G)) for G in (8, 32, 64, 256)]
        print(f"{skew:>4} {T:>6} " + " ".join(f"{v:6.2f}" for v in row))

print("\nEPLB식 복제 + 채우기, EP64, skew 0.5, step당 4096 토큰")
pop = popularity(0.5)
history = expert_counts(route(pop, 16384))                 # 이전 트래픽에서 모은 부하 통계
now = expert_counts(route(pop, 4096))                      # 실제로 서빙하는 step
for r in (0, 1, 2, 4):
    place, reps = eplb(history, 64, r) if r else contiguous(64)
    print(f"  GPU당 redundant expert = {r}: max/mean = {imbalance(gpu_load(now, place, reps, 64)):.2f}")
print(f"\n({time.time() - t0:.1f}초)")
 

표를 행과 열로 읽는다. 편중이 없으면 불균형은 토큰이 늘면 줄고 EP가 넓어지면 커진다(4,096 토큰이어도 EP256에서 1.24). skew 0.5에서는 토큰을 늘려도 줄지 않고, EP256에서는 가장 바쁜 GPU가 평균의 몇 배를 한다. 과거 통계로 배치한 GPU당 redundant expert 하나가 새 step에서 EP64를 약 1.1로 되돌린다. 남은 것이 잡음이라 복제본을 더 늘려도 소용없다.

NumPy 토큰당 통신량, expert당 토큰, GPU당 가중치 (DeepSeek-V3 형태)
# DeepSeek-V3 형태(보고서·config): d=7168, 61층(dense 3 + MoE 58), 중간 크기 2048인 routed expert 256개,
# top-8, shared expert 1개. 바이트: BF16 activation = 2, FP8 dispatch = 1.
d, L, L_moe, E, k, m = 7168, 61, 58, 256, 8, 2048
expert_params = 3 * d * m                                  # routed expert 하나의 gate, up, down
routed_total = L_moe * E * expert_params
rest = 671e9 - routed_total                                # routed expert가 아닌 나머지 전부
print(f"routed expert: {routed_total / 1e9:.0f}B; 나머지 ≈ {rest / 1e9:.0f}B (총 671B에서)")
print(f"토큰당 활성 ≈ {(rest + L_moe * k * expert_params) / 1e9:.1f}B  (보고서: 37B)\n")

def tp_bytes(t):          # 토큰·층당, GPU 하나가 보내는 양: d 벡터 ring all-reduce 두 번
    return 2 * 2 * (t - 1) / t * d * 2
def ep_bytes(G):          # 토큰·MoE 층당: 사본 k개 나감(FP8), 결과 k개 돌아옴(BF16)
    return k * d * (1 + 2) * (G - 1) / G
def pp_bytes():           # 토큰·stage 경계당: BF16 hidden state 하나
    return d * 2

print("토큰당 통신")
for t in (4, 8, 16):
    print(f"  TP{t:<3}: 층·GPU당 {tp_bytes(t) / 1024:6.1f} KiB  x GPU {t}장 x {L}층 "
          f"= 토큰당 {tp_bytes(t) * t * L / 2**20:5.1f} MiB")
for G in (32, 144, 320):
    print(f"  EP{G:<3}: MoE 층당 {ep_bytes(G) / 1024:6.1f} KiB          x {L_moe}층 "
          f"= 토큰당 {ep_bytes(G) * L_moe / 2**20:5.1f} MiB")
print(f"  PP    : stage 경계당 {pp_bytes() / 1024:6.1f} KiB (층 수와 무관)")

# 왜 wide EP인가: expert당 토큰이 expert GEMM의 memory/compute-bound를 정한다
ridge = 1979e12 / 3.35e12          # H100/H800급 FP8 dense FLOP/s ÷ HBM bytes/s (가정값)
print(f"\nexpert GEMM, FP8 가중치: 토큰 n개면 강도 = 2n FLOP/byte, ridge ≈ {ridge:.0f}")
for B in (256, 2048, 16384, 65536):
    n = B * k / E
    print(f"  전체 decode 배치 {B:>6} -> expert당 {n:7.1f} 토큰 -> 강도 {2 * n:7.1f} "
          f"({'memory' if 2 * n < ridge else 'compute'}-bound)")

# expert를 G장에 나누고 나머지는 복제(DP attention)할 때 GPU당 가중치
print("\nGPU당 FP8 가중치 (비-expert는 복제, routed expert는 분할, redundancy 제외)")
for G in (8, 32, 144, 320):
    per_gpu = rest + routed_total / G
    print(f"  GPU {G:>3}장: {per_gpu / 1e9:5.1f} GB   (층·GPU당 routed expert {E / G:5.2f}개)")
 

실제 엔진에서 all-to-all은 크기를 실행 중에야 아는 collective다. 아래 PyTorch 버전이 그것을 드러낸다. 첫 all-to-all이 rank별 개수를 교환하고, .tolist()가 그 값을 CPU로 가져와 수신 버퍼 크기를 정한 뒤에야 본 데이터가 움직인다. DeepEP의 low-latency 모드가 고정 크기 버퍼를 미리 잡아 피하는 것이 바로 이 CPU 왕복이고, 그래서 CUDA graph와 함께 쓸 수 있는 모드가 그쪽이다.

PyTorch PyTorch: all_to_all_single로 EP dispatch/combine (GPU당 프로세스 하나) 로컬에서 실행run locally (pip install torch)
import torch
import torch.distributed as dist

@torch.no_grad()
def ep_moe_forward(x, router_logits, experts, k, n_experts):
    """x: 이 rank의 토큰 (T, d); router_logits: (T, E).
    experts: 이 rank가 가진 expert E/world개; rank r은 id [r*E_local, (r+1)*E_local)을 가진다."""
    world, rank = dist.get_world_size(), dist.get_rank()
    E_local = n_experts // world
    T, d = x.shape
    gate, idx = router_logits.softmax(-1).topk(k, dim=-1)              # (T, k)
    gate = gate / gate.sum(-1, keepdim=True)

    flat_e = idx.reshape(-1)                                            # (T*k,) (토큰, slot)마다 하나
    order = torch.argsort(flat_e, stable=True)                          # expert 순 → rank 순으로 묶기
    tok = order // k                                                    # 정렬된 각 쌍의 원래 토큰
    e_sorted = flat_e[order]
    x_send = x[tok]                                                     # (T*k, d), rank별로 연속

    send_counts = torch.bincount(e_sorted // E_local, minlength=world)  # 목적지마다 보낼 쌍 수
    recv_counts = torch.empty_like(send_counts)
    dist.all_to_all_single(recv_counts, send_counts)                    # 1) 크기 교환
    s, r = send_counts.tolist(), recv_counts.tolist()                   #    CPU 동기화: 크기가 host에 필요

    x_recv = x.new_empty(sum(r), d)
    dist.all_to_all_single(x_recv, x_send, output_split_sizes=r, input_split_sizes=s)    # 2) dispatch
    e_recv = e_sorted.new_empty(sum(r))
    dist.all_to_all_single(e_recv, e_sorted, output_split_sizes=r, input_split_sizes=s)  #    expert id

    y_recv = torch.empty_like(x_recv)
    local = e_recv - rank * E_local
    for j, expert in enumerate(experts):                                # 실제 커널은 grouped GEMM
        mask = local == j
        if mask.any():
            y_recv[mask] = expert(x_recv[mask])

    y_back = torch.empty_like(x_send)
    dist.all_to_all_single(y_back, y_recv, output_split_sizes=s, input_split_sizes=r)    # 3) combine
    out = torch.zeros_like(x)
    w = gate.reshape(-1)[order].unsqueeze(-1).to(x.dtype)
    out.index_add_(0, tok, y_back * w)                                  # k개 결과의 가중합
    return out
 
확인 문제Check yourself

DeepSeek-V3는 MLA를 쓴다. 서빙 스택이 attention을 노드의 GPU 8장에 tensor-parallel로 나누지 않고 data-parallel(GPU마다 복제본 하나)로 돌리는 이유는?

decode에서 흡수된 MLA는 토큰당 576576개 숫자짜리 latent 하나에 attention하고, 모든 head가 그것을 읽는다. 그래서 head를 TP rank에 나눠도 cache는 나뉘지 않는다. rank마다 자기 시퀀스의 latent 전체를 저장하므로 GPU당 KV는 TP가 없을 때와 같고, GPU당 배치도 커지지 않는다. DP attention에서는 GPU마다 자기 시퀀스의 latent만 저장한다. TP는 여전히 가중치 읽기는 줄인다(플래너가 그 trade-off를 보여 준다). V3 보고서의 decode 구성이 attention에 작은 TP4를 쓰고 이후 운영 구성이 순수 DP를 쓴 이유다.

확인 문제Check yourself

EP 그룹 전체의 decode step 하나가 256개 expert 중 top-8 routing으로 토큰 8,192개를 처리하고 부하가 완벽히 균형이다. routed expert 하나가 층마다 보는 토큰 수와, FP8 가중치일 때 산술 강도는?

n=Bk/E=8192⋅8/256=256n = B k / E = 8192 \cdot 8 / 256 = 256 토큰이고, b=1b = 1이면 I=2n/b=512I = 2n/b = 512 FLOP/byte다. 가정한 FP8 ridge 약 590 바로 아래라 expert GEMM이 균형점 근처에 있다. GPU 수백 장 대신 8장이라면 같은 GPU당 배치에서 expert당 토큰이 8분의 1이 되어 expert 층이 memory-bound가 된다.

정리

  • 서빙은 gradient와 optimizer state를 버리지만 KV cache가 생긴다. 가중치가 쓰지 않은 HBM은 모두 배치가 되고, 배치가 가중치 읽기를 나눠 낸다. decode step은 짧아서 collective당 지연이 중요하다.
  • 토큰·층당: TP는 dd짜리 all-reduce 두 번(GPU당 2⋅2(t−1)t⋅2d2 \cdot \tfrac{2(t-1)}{t} \cdot 2d바이트, decode에서는 지연에 묶임), PP는 stage 경계당 2d2d바이트지만 TPOT을 pp배로, DP는 없음, EP는 MoE 층마다 kdk d(FP8)를 보내고 kdk d(BF16)를 받으며 대부분 노드를 넘는다.
  • MLA의 공유 latent 하나 때문에 TP는 KV에 소용이 없고, 그래서 MLA MoE는 DP attention + wide EP로 서빙된다.
  • wide EP가 사는 것은 메모리(routed expert를 GG로 분할)와 expert당 토큰(n=Bk/En = Bk/E, 강도 2n/b2n/b)이다. FP8 expert가 compute-bound에 가까워지려면 step당 토큰 수백 개, 즉 전체 decode 배치 수천이 필요하다.
  • step은 가장 바쁜 GPU를 기다린다. 불균형 = 샘플링 잡음(≈1+2ln⁡G/μ\approx 1 + \sqrt{2\ln G/\mu}, 토큰이 늘면 준다) + 인기 편중(GG와 함께 오르는 바닥). redundant expert + EPLB가 편중을 없애고, 잡음은 토큰을 늘려야만 준다.
  • 실제(DeepSeek, SGLang, vLLM): prefill EP32와 decode EP144를 따로 배포, DeepEP 고처리량 대 저지연 커널, device당 배치가 클 때만 이득인 two-batch overlap, prefill 1.5배·decode 2.5배 효과의 EPLB.
  • 학습기는 optimizer state·gradient·매개변수를 나누고(ZeRO, FSDP, distributed optimizer) backward에 맞춘 TP × PP × EP를 쓴다. rollout 엔진은 KV와 step당 지연에 맞춰 나눈다. 둘 사이의 가중치 동기화는 언제나 re-shard다.

더 읽을거리Further reading