# DeepEP, Part 3: V2 and Mega MoE *How the April 2026 rewrite of DeepEP replaced queues, NVSHMEM and two kernel families with one buffer of fixed slots on top of NCCL, and how DeepGEMM's Mega MoE kernel, released two weeks earlier, folded dispatch and combine into the expert GEMMs* *Series: [Part 1](https://sleepy-capybara.vercel.app/deepep/1-original-release/) · [Part 2](https://sleepy-capybara.vercel.app/deepep/2-v1-in-2025/) · [Part 3](https://sleepy-capybara.vercel.app/deepep/3-v2/) · [Part 4](https://sleepy-capybara.vercel.app/deepep/4-v2-5/)* At the end of part 2, we left DeepEP V1 in February 2026 as a mature library with two kernel families and two APIs. The normal kernels count the tokens and stream the data through ring buffers, and they make the CPU wait for the counts unless the caller asks for worst-case-sized outputs, which became possible in the summer of 2025. The low-latency kernels give every token a fixed slot in a large buffer and never involve the CPU. Both had been made faster many times over, but the structure was the same as on the first day, and the README itself told readers that "fixed-size buffers allocated to maximum capacity" would be simpler and faster than the queues. On April 30, 2026, DeepSeek published V2 under the commit title "Introducing EPv2: faster EP, and Engram/PP/CP supports". Its README calls it "a complete refactoring of Expert Parallelism" and now spells out the name as "DeepEveryParallel". Two weeks earlier, on April 17, DeepSeek had released a kernel in DeepGEMM called Mega MoE, which does dispatch, both expert GEMMs and combine in a single kernel. In this third part, we will look at both. As in the earlier parts, I will ask the same four questions of each: what is sent, how the receiver knows, which layout the experts get, and what it costs. And I will compare V2 with V1 on the same machine with eight B300 GPUs. That machine has no RDMA network cards, so the measurements cover what happens inside one NVLink domain, and V2 had to run with its RDMA backend switched off (`EP_DISABLE_GIN=1`), which its documentation provides for exactly this case. The snippets assume `import torch`. ## 1. What V2 Throws Away It helps to start with what is gone, since almost everything from parts 1 and 2 is: - **The ring buffers.** There are no more queues whose slots get reused, and so no heads that have to be sent back to the sender. Every token gets a fixed slot, as in V1's low-latency kernels, but one slot per destination GPU rather than one per destination expert. (The cross-machine mode still sends tails to tell the receiver how far the data has come, as we will see in section 5, but nothing ever comes back.) - **The two kernel families.** There is one class, `ElasticBuffer`, with one `dispatch` and one `combine`. Prefill and decode differ only in their arguments. - **NVSHMEM.** The new kernels talk to the network through NCCL's device API, and they can reuse the NCCL communicator that PyTorch already created. (V2.0 still ships the V1 kernels as `deep_ep.Buffer`, which need NVSHMEM, but labels them legacy.) - **Auto-tuning.** The number of SMs and queue pairs is computed from a model of the traffic, and the README says "no more auto-tuning needed". - **Precompiled kernels.** Everything is compiled at run time, with the problem sizes baked in as constants. - **The SM-free hook.** "0 SM RDMA low-latency EP is no longer supported", in the README's words. V2's kernels always occupy SMs while they run. In exchange, the README claims "up to 1.3x peak performance, while saving up to 4x SM count", support for expert-parallel groups of up to 2,048 GPUs ("EP2048"), and, for training in the style of DeepSeek-V3, an SM budget of 4 to 6 instead of 24. One of these doesn't match the code, though: at this first V2 commit, `WorkspaceLayout` asserts at most 1,024 ranks and 2,048 experts, so EP2048 would fail that check. Let's go through the new design piece by piece, starting with the transport underneath. ## 2. NCCL's Device API ### 2.1 Teams and Windows For years, NCCL was a library of collectives that you call from the CPU: an all-reduce, an all-gather, and so on. Recent NCCL versions (V2.0 requires 2.30.4) add a device API that lets kernels communicate directly, which is what DeepEP V2 is built on. Three of its ideas matter here. The first is the window. A buffer that is registered with `ncclCommWindowRegister` becomes symmetric memory: every GPU has a buffer of the same size, and an offset into one GPU's buffer means the same thing on every other GPU. The second is the team. NCCL groups the GPUs of a communicator in three ways. The world team contains all of them. The LSA team ("load/store accessible") contains the GPUs that can reach each other's memory with ordinary loads and stores, which in practice is one NVLink domain. The rail team contains the GPUs with the same index in their NVLink domain, which are the ones connected by the same rail of the network. Figure 1 shows the three for two machines. ![NCCL teams on two machines](https://sleepy-capybara.vercel.app/deepep/3-v2/figures/fig01_teams.png) *Figure 1: The three NCCL teams that DeepEP V2 uses, for two machines with 8 GPUs each: the world team (all 16 GPUs), the LSA team of GPU 2 (its NVLink domain) and the rail team of GPU 2 (GPU 2 of every machine).* The third is GIN, NCCL's GPU-initiated networking. It gives a kernel the same operations that V1 built by hand on IBGDA: `put` to copy bytes into a remote window, `putValue` to write one word, `signal` for an atomic add, and `flush` to wait for completion. A kernel issues these through a GIN context, which on InfiniBand corresponds to a queue pair, and the communicator is created with a fixed number of them. The important rule is that ordering only holds within one context: if a warp puts a token through context 3 and then sends a signal through context 5, the signal may arrive first. So DeepEP has to send a token and the signal that announces it through the same context, which is why V2 assigns each warp one context (one "QP", possibly shared with other warps) for the whole kernel. NCCL's [GIN documentation](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/api/device_gin.html) has the details. ### 2.2 One Code Path for NVLink and RDMA DeepEP wraps these in a small struct, `NCCLGin`, and its most important function decides between the two transports for a single destination. If the destination is in the same LSA team, NCCL can return a pointer into that GPU's window, and the kernel writes to it directly. If not, the function returns `nullptr`, and the caller falls back to a GIN put: ```cpp // deep_ep/include/deep_ep/common/handle.cuh at b306af0 (cut down) template dtype_t* get_sym_ptr(dtype_t* ptr, const int& dst_rank_idx) const { // Team world and not accessible by symmetric pointers if (not is_nvlink_accessible(dst_rank_idx)) return nullptr; // ... translate the world rank into an NVLink rank // Local rank bypass if (dst_nvl_rank_idx == team_lsa.rank) return ptr; // Get base ptr const auto dst_ptr = ncclGetLsaPointer( nccl_window, get_sym_offset(ptr), dst_nvl_rank_idx); return static_cast(dst_ptr); } ``` This is the same decision that the May 2025 change from part 2 added to V1's low-latency kernels, except that it is now part of the transport. Every write in V2 goes through it: data, counts, barrier signals. That is also why the single-machine benchmarks below can run with GIN switched off: every destination is reachable through a pointer. ## 3. One Buffer of Fixed Slots ### 3.1 The Layout The receive buffer of a V2 dispatch is a three-dimensional array: one block per source GPU, one slot per token that the source GPU might send, and in each slot one token in a fixed format. The format is the same in every slot: the hidden vector, its scale factors, and the token's metadata (its top-k expert indices and weights, its global index on the source GPU, and an index for a linked list that we will meet in section 5), each part aligned to 32 bytes so that TMA can move it. Figure 2 compares this with V1's normal kernels. ![V1 ring buffers versus V2 fixed slots](https://sleepy-capybara.vercel.app/deepep/3-v2/figures/fig02_slots.png) *Figure 2: A V1 normal dispatch (left) streams tokens through small ring buffers per channel and source GPU. A V2 dispatch (right) writes every token into its own slot of a buffer with room for all tokens of every source GPU.* As we can see in Figure 2, V2 never reuses a slot within one call, so the sender doesn't have to ask whether a slot is free and the receiver doesn't have to tell it. The only question is which slot to take, and the answer is an `atomicAdd` on a counter per destination GPU. The slot is also per destination GPU and not per destination expert, as it was in V1's low-latency kernels. A token that goes to three experts on the same GPU is sent once. For DeepSeek-V3's shape with uniform routing on 8 GPUs, that is 5.29 copies per token instead of 8. ### 3.2 What It Costs in Memory The price of fixed slots is memory, and V2's README says so ("buffer size consumption is larger than V1"). We can compute the size from `get_dispatch_buffer_size` and `get_combine_buffer_size` in `csrc/elastic/buffer.hpp`. The buffer is shared between dispatch and combine, so it is the larger of the two: ```python def a32(n): # TMA needs 32-byte alignment return (n + 31) // 32 * 32 def v2_buffer_bytes(tokens, hidden, top_k, gpus_per_node, nodes): """DeepEP V2.0's buffer for FP8 dispatch and BF16 combine.""" meta = top_k * 8 # top-k ids and weights d_tok = (a32(hidden) + a32((hidden + 31) // 32 * 4) # FP8 + scales + a32(meta + (1 + top_k) * 4)) # + source and list indices c_tok = a32(hidden * 2) + a32(meta) up, out, k = gpus_per_node, nodes, top_k if out == 1: # one NVLink domain dispatch = up * tokens * d_tok combine = min(up, k) * tokens * c_tok else: # hybrid: RDMA, then NVLink dispatch = (up * out * tokens + tokens + out * (tokens + 1280)) * d_tok combine = (min(up, k) * out * tokens + min(out, k) * tokens + out * (tokens + 1280)) * c_tok return max(dispatch, combine) for tokens in (128, 4096): sizes = [v2_buffer_bytes(tokens, 7168, 8, 8, n) / 2**20 for n in (1, 8, 32)] print(f"{tokens:>4} tokens: " + ", ".join( f"EP{8 * n} {s:,.0f} MiB" for n, s in zip((1, 8, 32), sizes))) # 128 tokens: EP8 14 MiB, EP64 281 MiB, EP256 1,083 MiB # 4096 tokens: EP8 450 MiB, EP64 4,641 MiB, EP256 17,212 MiB ``` (For one machine, this agrees byte for byte with `ElasticBuffer.get_buffer_size_hint` from the V2.0 build.) Two things stand out. For decoding, V2 needs much less memory than V1's low-latency kernels, which reserved 1.75 GiB per GPU for 128 tokens no matter the group size (part 1). V2's dispatch buffer grows with the number of GPUs rather than the number of experts, and its combine buffer has only `min(GPUs, top-k)` slots per token, for a reason we will see in section 6. For prefill across many machines, on the other hand, a buffer for every token of every source is large: about 4.53 GiB per GPU on 64 GPUs, and 17 GiB on 256. V1's normal kernels, with their small queues, needed a fraction of that. The README lists "reducing intermediate buffer sizes" among the "still on-going features". ## 4. The Dispatch Kernel ### 4.1 Two Kinds of Warps The single-machine dispatch kernel (`dispatch_impl` in `deep_ep/include/deep_ep/impls/dispatch.cuh`) has two kinds of warps, which Figure 3 shows together with the kernel that follows it. ![The V2 dispatch](https://sleepy-capybara.vercel.app/deepep/3-v2/figures/fig03_dispatch.png) *Figure 3: A V2 dispatch on one machine. Notify warps count and exchange the numbers of tokens per GPU and expert; dispatch warps copy each token into its slot on every destination GPU with TMA. A second kernel, the copy epilogue, starts through programmatic dependent launch and arranges the tokens for the expert GEMMs.* The notify warps count, for their slice of the tokens, how many go to each GPU (deduplicated) and to each expert, using atomics in shared memory. They then add the counts of all SMs together in global memory with a 64-bit atomic that carries both a count and an arrival tag: ```cpp // deep_ep/include/deep_ep/impls/dispatch.cuh at b306af0 (cut down) for (int i = thread_idx; i < kNumRanks + kNumExperts; i += kNumNotifyThreads) { const int64_t counter = (1ll << 32ll) | rank_expert_count[i]; ptx::red_add(workspace_layout.get_notify_reduction_workspace_ptr() + i, counter); } ``` The upper 32 bits count how many SMs have added their part, and the lower 32 bits hold the sum, so SM 0 knows the total is complete when the upper half reaches the number of SMs. It is the same idea as V1's `FINISHED_SUM_TAG` from part 1, packed into one word, so a single atomic both contributes a count and reports an arrival. SM 0 then sends the totals to the other GPUs with `put_value`, waits for theirs, and computes the prefix sums that the epilogue needs. This replaces V1's separate layout and notify kernels. By default, the CPU still waits for the final counts, as in V1, but with `do_cpu_sync=False` it doesn't (more on that in section 8). ### 4.2 One Token, One Warp The dispatch warps take one token at a time. A single lane issues a TMA load of the token's hidden vector into shared memory, while the other lanes fetch its top-k indices and weights and append them to the copy in shared memory, together with the token's global index. Then each lane that holds a destination GPU takes a slot on that GPU and the warp writes the whole token there with one TMA store. Lane i holds the GPU of the token's i-th expert, so two lanes may hold the same GPU. `ptx::deduplicate` resolves that with `__match_any_sync`, which tells each lane which other lanes hold the same value, and only the lowest of those lanes keeps its GPU: ```cpp // deep_ep/include/deep_ep/impls/dispatch.cuh at b306af0 (cut down) // Deduplicate ranks and assign slots if (ptx::deduplicate(stored_dst_rank_idx, lane_idx) and stored_dst_rank_idx >= 0) stored_dst_slot_idx = atomicAdd( workspace_layout.get_scaleup_atomic_sender_counter() + stored_dst_rank_idx, 1); // ... // Issue TMA NVLink stores const auto dst_ptr = stored_dst_slot_idx >= 0 ? gin.get_sym_ptr(recv_buffer.get_token_buffer(stored_dst_slot_idx) .get_base_ptr(), stored_dst_rank_idx) : nullptr; if (dst_ptr != nullptr) ptx::tma_store_1d(dst_ptr, tma_buffer.get_base_ptr(), tma_buffer.get_num_bytes()); ``` (Some long lines are wrapped.) This is the change that part 2 anticipated: V1's intranode kernels only used TMA for copies into local memory, and V2 stores straight into the peer GPU's memory over NVLink. Each token is written over NVLink once, directly into its final slot, and never passes through the registers of 32 threads. If the destination is on another machine, the token is first stored into a local send buffer and then sent with a GIN put. Note also the `atomicAdd` on a counter in the sender's own workspace. Each sender owns a contiguous region of slots on each receiver, namely the region for its rank, so the counter only has to be unique per (sender, receiver) pair, and the order of the tokens within that region doesn't matter. Figure 4 puts the two steps together for one token. ![Deduplicating destination GPUs within a warp](https://sleepy-capybara.vercel.app/deepep/3-v2/figures/fig04_dedup.png) *Figure 4: The eight lanes of a dispatch warp for one token on EP8. Lanes whose experts live on the same GPU get the same match mask from `__match_any_sync`, only the lowest of them keeps the GPU, and each remaining lane takes a slot from its sender-side counter (the counter values are made up).* In the figure, the token's experts 40 and 45 both live on GPU 1, so lanes 1 and 2 hold the same GPU, `__match_any_sync` gives both of them the mask {1, 2}, and only lane 1 keeps it. The same happens to lanes 3 and 4 and to lanes 6 and 7. Five lanes are left, so the warp issues five TMA stores, and GPUs 1, 4 and 7 each receive the token once even though they own two of its experts. No lane has to talk to another lane to decide this, since all lanes of a group get the same mask. ### 4.3 The Copy Epilogue When all tokens are in place, a barrier makes sure every GPU's writes have arrived, and the kernel calls `cudaTriggerProgrammaticLaunchCompletion`. That is the signal for programmatic dependent launch (PDL). Normally, a kernel on the same stream can't start before the previous one has completely finished, and the gap between the two costs a few microseconds of launch latency. With PDL, the trigger allows the next kernel, which was launched with the PDL attribute, to start as soon as every block of the current kernel has triggered, so its launch and its setup code overlap with the last instructions of the dispatch kernel. The next kernel then waits at `cudaGridDependencySynchronize()` until the dispatch kernel has fully completed and its memory writes are visible. Figure 5 shows the two timelines. ![Programmatic dependent launch](https://sleepy-capybara.vercel.app/deepep/3-v2/figures/fig05_pdl.png) *Figure 5: The dispatch kernel and its copy epilogue without and with programmatic dependent launch. With PDL, the epilogue is launched and runs its setup as soon as every block of the dispatch kernel has triggered, and it waits at `cudaGridDependencySynchronize()` only before it reads the dispatch output.* What runs early is everything before `cudaGridDependencySynchronize()`, which in the epilogue is setup that doesn't touch the dispatch output: computing the buffer layouts and initializing the mbarrier for its TMA loads. A few microseconds don't sound like much, but they matter when a whole call takes 30 us. The source also has a note at this spot not to use `__ldg`. That load goes through the non-coherent path, which assumes the data doesn't change while the kernel runs, and with PDL, the epilogue is already running while the dispatch kernel is still writing. The second kernel, `dispatch_copy_epilogue`, reads the tokens from the buffer and writes them into the output tensors in one of two layouts. In the plain layout, there is one row per received token, with its top-k indices translated to local experts, which is what part 1's normal dispatch returned. In the expanded layout (`do_expand=True`), there is one row per (token, local expert) pair, grouped by expert and padded to the GEMM's alignment, which is DeepGEMM's contiguous layout from part 1. The epilogue builds it with the exclusive prefix sum of the aligned per-expert counts that the notify warps computed, and an `atomicAdd` per expert that hands out the rows. Here is the same logic in PyTorch for GPU 0 of 4: ```python torch.manual_seed(0) ranks, experts, top_k, tokens, align = 4, 16, 4, 8, 4 local = experts // ranks # GPU 0 holds experts 0..3 idx = [torch.rand(tokens, experts).topk(top_k).indices for _ in range(ranks)] # Dispatch kernel: each sender fills its own region of GPU 0's buffer, # in whatever order its warps take slots from its own counter slots = [(src, int(t)) for src in range(ranks) for t in torch.randperm(tokens) if (idx[src][t] // local == 0).any()] # Copy epilogue: one row per (token, local expert), experts contiguous mine = [[e for e in idx[s][t].tolist() if e < local] for s, t in slots] counts = torch.bincount(torch.tensor(sum(mine, [])), minlength=local) padded = (counts + align - 1) // align * align next_row = torch.cumsum(padded, 0) - padded # exclusive prefix sum rows = [] for experts_of_token in mine: rows.append([int(next_row[e]) for e in experts_of_token]) for e in experts_of_token: next_row[e] += 1 # atomicAdd in the kernel print(f"{len(slots)} slots, {int(counts.sum())} expert rows, " f"{int(padded.sum())} rows with padding; counts {counts.tolist()}") # 20 slots, 26 expert rows, 28 rows with padding; counts [3, 8, 8, 7] ``` (In the kernel, the order of the tokens within a sender's region depends on which of its warps takes a slot first, and so do the rows that the epilogue hands out. That is why V2 has a `deterministic` option: a small prologue kernel first computes every token's slot from prefix sums in token order, and the dispatch kernel then uses those slots instead of its `atomicAdd` (in V2.0, only within one machine).) The epilogue also records, for every row, where it came from, so that combine can send the result back. The handle that dispatch returns carries all of this, and a later dispatch with the same routing (in the backward pass, or a second call with the same handle) can skip the counting and reuse the slot assignments. ## 5. Across Machines: the Hybrid Mode ### 5.1 Three Warp Roles Instead of Five Across machines, V2 keeps V1's two-hop idea (RDMA once per destination machine, then NVLink inside it), which the README calls the hybrid mode, as opposed to the direct mode that sends straight to every GPU. The hybrid kernel has three kinds of warps, shown in Figure 6. ![The V2 hybrid dispatch](https://sleepy-capybara.vercel.app/deepep/3-v2/figures/fig06_hybrid.png) *Figure 6: The V2 hybrid dispatch across two machines. Scale-out warps send each token once to every machine that needs it, over the rail team. On the receiving machine, forward warps pick up the tokens and store them over NVLink into the final slots on the GPUs that need them.* The notify warps do what they did in section 4, plus an exchange of counts across machines. Each scale-out warp is a channel: it takes every n-th token, deduplicates the destination machines among its top-k experts, and puts the token into the receive buffer of GPU r on every destination machine, where r is its own index (the rail team). The forward warps on the receiving machine read those tokens and store each one over NVLink into its final slot on every GPU of the machine that needs it, exactly like the single-machine dispatch. How do the forward warps know that tokens have arrived? The scale-out warps tell them with an atomic add of a packed 64-bit word that holds a finish flag and the channel's tail, every 3 tokens (`kScaleoutUpdateInterval`, which later V2.0 commits raised to 6): ```cpp // deep_ep/include/deep_ep/impls/hybrid_dispatch.cuh at b306af0 (cut down) const auto update_scaleout_tail = [&](const bool& finish_flag = false) { if (lane_idx < kNumScaleoutRanks and (stored_scaleout_tail >= stored_old_scaleout_tail + kScaleoutUpdateInterval or finish_flag)) { const auto signaled_tail = math::pack2( finish_flag, stored_scaleout_tail); const auto old_signaled_tail = math::pack2( 0, stored_old_scaleout_tail); // NOTES: ... For RDMA requests, "release" is ensured by "atomic" gin.red_add_rel(ptr, signaled_tail - old_signaled_tail, lane_idx); stored_old_scaleout_tail = stored_scaleout_tail; } }; ``` This is part 2's atomic-add trick again: the sender adds the difference between the new and the old value, so the order of arrival doesn't matter. And since the forward warps never hand slots back, there is no credit flowing the other way. Each channel's receive area has room for every token the channel could send, which is the `num_max_tokens + 1280` in the buffer formula of section 3 (1,280 is the maximum number of channels, 8 per SM on up to 160 SMs). ### 5.2 Linked Lists for Combine There is one complication. On the receiving machine, each GPU gets tokens from many forward warps in an order that nobody controls, but combine has to send each result back along the same two hops in reverse, channel by channel. For this, each forward warp counts the tokens it sends to each GPU of its machine and writes that position into the token's metadata (the linked-list index from section 3). The copy epilogue then reads the position and stores, at that place in `channel_linked_list`, the row where the token ended up. The result is a table that says, for channel i and GPU k, which row holds the j-th token, so the combine kernel can walk a channel's tokens in the order they were forwarded. That bookkeeping replaces the `send_head` arrays of V1's normal kernels. ## 6. Combine Reduces Before It Sends V2's combine does something that V1's low-latency combine didn't: it adds up the outputs of a token's experts on the expert side before sending anything back. If a token went to three experts on GPU 5, GPU 5 sends one row back, not three. Figure 7 shows the difference. ![Reduce before sending](https://sleepy-capybara.vercel.app/deepep/3-v2/figures/fig07_combine.png) *Figure 7: Combine for a token with three of its experts on GPU 5. V1's low-latency combine (left) sends three rows back and the source GPU weights and adds them. V2 (right) adds the three rows on GPU 5, so only one row is sent back, and the source GPU adds the partial sums of all GPUs in a second kernel.* That is why, with multiple reduction enabled by default, the combine receive buffer has only `min(GPUs, top-k)` slots per token: at most one partial sum arrives from each GPU, and at most top-k GPUs can have one. With 8 GPUs and top-8, it has a slot per source GPU (the code calls this the rank layout); with more GPUs than top-k, a token's partial sums go into slots indexed by the top-k position of the first of its experts on each GPU. The reduction happens in two places. The combine kernel reduces locally on the expert side, and a second kernel launched with PDL, `combine_reduce_epilogue`, adds the partial sums on the token's own GPU, together with up to two bias tensors (a shared expert's output, for example), and writes the result with TMA. Because the expert-side partial sum is stored in BF16 before sending, a token's output is rounded more than once; for training runs that care, `allow_multiple_reduction=False` turns the first reduction off and sends every expert's row, as V1's low-latency kernels did. One more difference to part 1: V2's combine never applies the router weights, as V1's low-latency combine did. Like V1's normal combine, it only adds, and the caller multiplies each expert's output by its weight first. In the expanded layout, `recv_topk_weights` has one weight per row for exactly that purpose. ## 7. Compilation and Resource Estimates ### 7.1 Kernels Compiled for the Problem V1's kernels were compiled when DeepEP was installed, with templates for a few hidden sizes and GPU counts, and they took their chunk sizes and SM counts from a table of configurations that DeepSeek had tuned on their cluster ("the default configurations are optimized on the DeepSeek's internal cluster", said part 1's README). V2 compiles every kernel at run time, the first time it sees a combination of sizes, and caches the result on disk (`$HOME/.deep_ep` by default). Here is the instantiation that V2.0 compiled for a 128-token dispatch on the B300 machine, taken from that cache: ```cpp // $EP_JIT_CACHE_DIR/cache/kernel.dispatch./kernel.cu static void __instantiate_kernel() { auto ptr = reinterpret_cast(&dispatch_impl< true, true, false, // NVLink scale-up, CPU sync, reuse slots 26, 4, 20, // SMs, notify warps, dispatch warps 8, 7168, 56, 128, // GPUs, hidden bytes, scale packs, max tokens 256, 8, 1, // experts, top-k, expert alignment 129, 203200000000>);// QPs, timeout cycles } ``` (I added the comments and the line breaks.) Everything that determines the structure of the kernel is a constant here: the number of SMs and warps of each kind, the token size, the number of GPUs and experts. So the compiler can unroll the copy loops for exactly 7,168 bytes and size the shared memory exactly, which V1 could only do for the few hidden sizes it had templates for. The actual number of tokens still comes in at run time, since it changes from batch to batch; the 128 here is only the maximum, which fixes the buffer layout. ### 7.2 Choosing the Number of SMs The other half is the number of SMs, which V2 computes with `get_theoretical_num_sms`. The idea is to find the link that limits the transfer (NVLink or RDMA), estimate how many bytes each SM has to read from and write to memory per byte sent over that link, and give the kernel just enough SMs that the SMs aren't the bottleneck, assuming each SM can read 200 GB/s and write 50 GB/s. The expected number of distinct GPUs (or machines) per token comes from a closed formula for uniform routing. Here is the model for the cases without and with RDMA, rewritten from the Python source: ```python from math import comb, ceil def expected_groups(experts, top_k, groups): """Expected number of distinct groups among a token's top-k experts.""" return groups * (1 - comb(experts - experts // groups, top_k) / comb(experts, top_k)) def v2_num_sms(nodes, gpus, nvlink_gbs, rdma_gbs, experts=256, top_k=8): k = expected_groups(experts, top_k, nodes * gpus) # GPUs per token read, write = 1 / k, 1.0 # per byte of received data rdma, nvl = 0.0, 1 - 1 / gpus # traffic per received byte if nodes > 1: # hybrid: RDMA, then NVLink k_out = expected_groups(experts, top_k, nodes) # machines per token write += 1 / k + (1 / k) * (k_out / nodes) read += k_out / k rdma = (1 / k) * k_out * (1 - 1 / nodes) gbs, traffic = nvlink_gbs, nvl # whichever link is the bottleneck if nodes > 1 and rdma / rdma_gbs > nvl / nvlink_gbs: gbs, traffic = rdma_gbs, rdma sms = gbs / traffic * max(read / 200, write / 50) # 200, 50 GB/s per SM sms = ceil(sms * 1.25) return max(4, sms + sms % 2) b300 = 18 * 53.125 * 0.9 # 18 links from nvidia-smi print("8 B300 in one machine:", v2_num_sms(1, 8, b300, 0)) print("4 machines of 8 Hopper GPUs:", v2_num_sms(4, 8, 191, 50)) # 8 B300 in one machine: 26 # 4 machines of 8 Hopper GPUs: 6 ``` The first number is what V2.0 chose on the B300 machine in all my runs (it reads the NVLink speeds from `nvidia-smi` and takes 90% of their sum). The second matches the 6 SMs that the README's table lists for 4 machines of 8 Hopper GPUs with CX7 network cards. The README doesn't say which link speeds it assumed (and its table was measured with 8,192 tokens per GPU, though the SM model doesn't depend on that), so I used an H800's NVLink (8 links at 26.6 GB/s, which V2 would turn into 191 GB/s) and 50 GB/s for a 400 Gb/s card. For two machines, though, the formula gives 8 SMs where the README's table used 12, so either the README assumed different link speeds or someone picked 12 by hand; I can't tell which. The source also warns that the model assumes balanced routing and should not be used for "V3.0's group-limited gate". With RDMA in the path, the network is so much slower than NVLink that very few SMs suffice, which is where the README's "SM usage reduced from 24 to 4 - 6" comes from. If you don't want to overlap the communication with computation, `prefer_overlap_with_compute=False` raises the count to at least 64. ## 8. Decoding With the Same Function Since V2 has no separate low-latency kernels, decoding uses the same `dispatch`, with `do_cpu_sync=False`. In that mode, the notify warps still compute the counts, but nobody waits for them on the CPU: the output tensors are allocated for the worst case, and the prefix sums stay on the GPU, in the handle (`psum_num_recv_tokens_per_expert`). An expert kernel can read its per-expert ranges from there. Note that the expanded tensor is still the flat, contiguous layout, with the experts' segments one after another, and not the `[experts, max tokens, hidden]` slab that DeepGEMM's masked GEMM takes. A framework that wants the masked GEMM has to rearrange it, or use a grouped GEMM that reads the segment boundaries from the GPU. SGLang's V2 integration is a good example. For decoding, it calls dispatch with `do_cpu_sync=False` and `do_expand=True`, copies the segments into a masked slab with a small kernel (`expand_to_masked_slab`, which takes the segment boundaries from `psum_num_recv_tokens_per_expert`), and runs DeepGEMM's masked GEMM on that. For prefill, it uses `do_cpu_sync=True`, which returns exactly sized outputs that go to the contiguous GEMM: ```python # python/sglang/srt/layers/moe/token_dispatcher/deepep_v2.py (cut down) is_decode = not get_is_extend_in_batch() use_masked = is_decode use_expand_layout = is_decode or self._prefill_expand_enabled # ... recv_x, recv_topk_idx, recv_topk_weights, handle, event = buffer.dispatch( dispatch_x, topk_idx=topk_ids, topk_weights=topk_weights, num_experts=self.num_experts, num_max_tokens_per_rank=num_max_tokens, expert_alignment=_EXPERT_ALIGNMENT, do_cpu_sync=not use_masked, do_expand=use_expand_layout) ``` (This is SGLang's code at commit `5cbf949`, shortened; the original sets `do_cpu_sync` through a variable.) What V2 gave up is V1's receive hook, which let the network move a decoding batch while the SMs did something else. V2's kernels hold their SMs until the data has arrived, so overlapping two micro-batches now means running communication and computation on separate SMs at the same time, which is what `prefer_overlap_with_compute=True` (the default) and the small SM counts of section 7 are for. ## 9. More Than Expert Parallelism The new name, DeepEveryParallel, refers to three experimental features that V2.0 added to the same buffer: - **Engram**, a remote memory lookup: `engram_fetch(indices)` reads rows of a table that lives on other GPUs over RDMA, with no SMs involved ("0 SM Engram" in the README), and returns a hook that waits for the data. - **Pipeline parallelism**, a `pp_send` and `pp_recv` between neighboring ranks over RDMA. - **All-gather sessions** for context parallelism, under the name AGRS (all-gather/reduce-scatter). The README calls it "0 SM CP (with Copy Engine)": the all-gather copies each rank's tensor into the other GPUs' symmetric memory with the copy engines, the DMA units that `cudaMemcpy` uses, and returns a hook that waits for the data. Despite the name, V2.0 only has the all-gather half; the README lists the reduce-scatter as still to come. Part 4 will show how V2.5 split these into separate buffers. ## 10. V2 on the B300 Machine ### 10.1 Prefill Figure 8 compares V2.0 with V1.2.1 for 4,096 tokens per GPU on the 8 B300 GPUs, by the number of SMs. ![V2.0 and V1.2.1 by number of SMs](https://sleepy-capybara.vercel.app/deepep/3-v2/figures/fig08_v2_vs_v1_sms.png) *Figure 8: Bandwidth of dispatch (FP8, left) and combine (BF16, right) for DeepEP v1.2.1 and V2.0 on eight B300 GPUs, 4,096 tokens per GPU, by the number of SMs. The time is the sum of the kernel durations, including V2.0's copy and reduce epilogues.* As we can see in Figure 8, the gap is largest where V1 was weakest, with few SMs. With 8 SMs, a V2.0 dispatch reaches 391 GB/s against V1.2.1's 147 GB/s, and combine 364 GB/s against 164 GB/s. For dispatch, V2.0 with 8 SMs is faster than V1.2.1 with 24 (349 GB/s); for combine, V2.0 needs 12 SMs (518 GB/s) to beat V1.2.1 with 24 (407 GB/s). That is in line with the README's "saving up to 4x SM count". At the top, the two end up closer: with 64 SMs, V2.0 dispatches at 565 GB/s and combines at 625 GB/s, compared with 496 and 602 GB/s for V1.2.1. In time, a dispatch of 4,096 tokens per GPU with 24 SMs takes 322 us in V2.0 and 459 us in V1.2.1. The curves aren't smooth, though. V2.0's dispatch is faster with 12 SMs than with 16 or 20, which I suspect has to do with how the channels map onto SMs at those counts (each warp is a channel, and the queue-pair assignment changes with the SM count), but I didn't investigate it further. DeepEP's own test, which reports only the main kernel and counts the metadata in its bytes, gives 716 GB/s for dispatch and 730 GB/s for combine on this machine with 64 SMs, close to the 726 and 740 GB/s that the README lists for Blackwell (SM100) with 64 SMs (measured there with 8,192 tokens per GPU). ### 10.2 Decoding For decoding, Figure 9 compares V2.0 in its decoding mode (`do_cpu_sync=False`, expanded layout) with V1.2.1's low-latency kernels, for up to 512 tokens per GPU. ![V2.0 decoding versus V1's low-latency kernels](https://sleepy-capybara.vercel.app/deepep/3-v2/figures/fig09_decode.png) *Figure 9: Summed device-kernel durations for V1.2.1's low-latency kernels and V2.0 in decoding mode on eight B300 GPUs, by tokens per GPU. V2.0 uses its automatic 26-SM setting; CPU time and gaps between kernels are excluded.* As shown in Figure 9, V2.0's dispatch is as fast as V1's low-latency dispatch from about 128 tokens up (31.8 us versus 31.4 us at 128 tokens), but its combine is slower at small batches (55 us versus 43 us at 128 tokens). At 16 tokens, V2.0's dispatch takes 27 us against 21 us, and its combine 39 us against 23 us. My reading is that V2 pays a fixed cost per call for its counting step, its barriers and its second kernel (the epilogue), which V1's low-latency kernels didn't have. At 512 tokens, V2.0 is faster for dispatch (63 us against 70 us) and equal for combine (104 us). The last V2.0-era commit from September 2026, which I also measured, is within a few percent of V2.0 everywhere. ## 11. Mega MoE: Communication Inside the GEMM ### 11.1 One Kernel Two weeks before V2, DeepSeek published a different answer to the same problem in DeepGEMM. Mega MoE "fuses and overlaps EP dispatch, linear 1 (FP8xFP4), SwiGLU, linear 2 (FP8xFP4), and EP combine into a single mega-kernel, overlapping NVLink communication and tensor core computation", in the words of its README. It runs on Blackwell GPUs (SM100), inside one NVLink domain, on symmetric memory that PyTorch allocates (`torch.distributed._symmetric_memory`), and in its first version with FP8 activations and FP4 expert weights. From the caller's side, it looks like this: ```python # DeepGEMM README (cut down) buffer = deep_gemm.get_symm_buffer_for_mega_moe( group, num_experts, num_max_tokens_per_rank, num_topk, hidden, intermediate_hidden) transformed_l1, transformed_l2 = deep_gemm.transform_weights_for_mega_moe( l1_weights, l2_weights) buffer.x[:num_tokens].copy_(x_fp8) buffer.x_sf[:num_tokens].copy_(x_sf) buffer.topk_idx[:num_tokens].copy_(topk_idx) buffer.topk_weights[:num_tokens].copy_(topk_weights) y = torch.empty((num_tokens, hidden), dtype=torch.bfloat16, device='cuda') deep_gemm.fp8_fp4_mega_moe(y, transformed_l1, transformed_l2, buffer) ``` The tokens go in, the MoE layer's output comes out, and there is no dispatch or combine call in between. Figure 10 shows what happens inside. ![Inside Mega MoE](https://sleepy-capybara.vercel.app/deepep/3-v2/figures/fig10_mega_moe.png) *Figure 10: The warp roles of DeepGEMM's Mega MoE kernel. Dispatch warps pull tokens from the GPUs that own them; TMA warps feed the tensor cores with tokens and weights; one warp issues the MMAs; epilogue warps apply SwiGLU and the router weight after the first GEMM and write the second GEMM's output straight into the source GPU's combine buffer, where the combine step adds it up.* ### 11.2 Pull Instead of Push The most interesting difference to DeepEP is the direction of the transfer. In DeepEP, the GPU that holds a token writes it into the receiver's memory (push). In Mega MoE, the dispatch warps of the source GPU only write the token's index into the expert owner's workspace, and after a barrier, the owner's dispatch warps read the tokens themselves with TMA loads from the source GPU's memory (pull), as shown in Figure 11. ![Push versus pull](https://sleepy-capybara.vercel.app/deepep/3-v2/figures/fig11_push_pull.png) *Figure 11: DeepEP V2 pushes every token into a slot on the destination GPU (left). Mega MoE writes only the token's index to the expert's owner, which then pulls the token into its own GEMM input buffer (right).* Pulling has two advantages here. The owner decides the order in which tokens arrive, and it can put each one directly at its final row in the buffer that the first GEMM reads (with a TMA load from the remote GPU into shared memory and a TMA store from there), in the expert-grouped order that the GEMM needs, so there is no copy epilogue. And the order can be chosen to spread the reads over all source GPUs. For each expert, Mega MoE takes tokens from all GPUs in turn, round by round, until the GPUs with fewer tokens run out; the kernel calls it "round-robin rank selection via iterative min-peeling": ```python def pull_order(counts): """Row i of an expert's input comes from (source GPU, token on that GPU).""" order, remaining, offset = [], list(counts), 0 while any(remaining): active = [r for r, n in enumerate(remaining) if n > 0] length = min(remaining[r] for r in active) # one round for i in range(length): order += [(r, offset + i) for r in active] offset += length remaining = [max(n - length, 0) for n in remaining] return order counts = [3, 0, 5, 1] # tokens for this expert per GPU for row, (gpu, token) in enumerate(pull_order(counts)): print(f"row {row}: GPU {gpu}, token {token}") # row 0: GPU 0, token 0 # row 1: GPU 2, token 0 # row 2: GPU 3, token 0 # row 3: GPU 0, token 1 # row 4: GPU 2, token 1 # row 5: GPU 0, token 2 # row 6: GPU 2, token 2 # row 7: GPU 2, token 3 # row 8: GPU 2, token 4 ``` The order is the same as a plain round-robin over the GPUs that still have tokens. The point of the peeling is that it can be computed for any row without walking the rows before it: in the kernel, each dispatch warp computes this mapping for its own row index directly (with warp-wide minimum and count reductions over the source GPUs), so the warps can pull different rows in parallel without talking to each other. ### 11.3 Overlap at the Block Level The tensor cores don't wait for all tokens. After pulling a token, a dispatch warp adds one to a counter for the block of the GEMM input that the token belongs to (`l1_arrival_count` in the April version), and the TMA warp that feeds the first GEMM starts loading a block as soon as its counter shows that all its rows are there. So the first GEMM of expert 0 can run while the tokens of expert 5 are still being pulled. The same happens on the way out: the second GEMM's epilogue converts its output to BF16 and stores each row over NVLink into the source GPU's combine buffer, at the slot of the token's top-k position, and after a barrier across all GPUs, the same epilogue warps on the source GPU add up the top-k rows of each token. The router weight is applied right after the first GEMM, together with SwiGLU, before the intermediate result is converted back to FP8 for the second GEMM. That is earlier than in DeepEP's flow, where the caller applies it to the second GEMM's output, but since the second GEMM is linear, the result is the same up to rounding. ### 11.4 The V4 Connection DeepSeek-V4's technical report names DeepGEMM PR 304, the Mega MoE release, as its fused MoE implementation, so DeepSeek presents this kernel as part of V4's own infrastructure. The FP8-by-FP4 GEMMs also match how the report describes V4's experts: the weights are trained with FP4 quantization-aware training (FP32 master weights, with FP4 simulated in the forward pass) and stored in FP4 for inference. That is a statement about the expert weights, though. The tokens that Mega MoE moves between GPUs are still FP8 on the way in and BF16 on the way out, so FP4 weights don't make the communication any smaller. Mega MoE also only works within one NVLink domain, where every GPU can load from every other GPU's memory. On B300 machines with 8 GPUs per NVLink domain, that means at most EP8, while a GB200 or GB300 rack has up to 72 GPUs in one domain. Anything that spans machines over InfiniBand still needs DeepEP. Part 4 comes back to this with V4.1, whose report names DeepGEMM's fused kernels next to several other kinds of communication. ### 11.5 Two Answers So by the end of April 2026, DeepSeek had two answers to the question of how to move tokens to experts. DeepEP V2 is a general communication library: it works across machines with RDMA, on Hopper and Blackwell, with any expert computation the caller wants, and its kernels can run beside a GEMM on separate SMs. Mega MoE gives up that generality (one NVLink domain, Blackwell, DeepGEMM's own GEMMs and weight layout) in exchange for doing the whole MoE layer in one kernel, with the communication hidden under the tensor-core work block by block. I couldn't measure Mega MoE on the B300 machine for this article, so I won't compare their speed; DeepGEMM's pull request #316 has DeepSeek's own benchmarks. ## 12. Summary To summarize, here is how V2 answers the four questions: 1. **What is sent.** Each token once per destination GPU (inside a machine) or once per destination machine and then once per GPU (across machines), in a fixed format with its metadata attached. Combine sends one partial sum per GPU, already reduced on the expert side. 2. **How the receiver knows.** Counts are reduced inside the kernel and exchanged with NCCL device writes; there is a slot for every token, so there are no queues to manage, and arrival is signalled with barriers and, across machines, atomic adds of packed tails. 3. **The layout.** The same call returns either one row per token or DeepGEMM's expert-grouped layout (`do_expand=True`), with exact sizes after a CPU sync or worst-case sizes with the counts on the GPU. 4. **The cost.** Fewer SMs for the same bandwidth (26 on one B300 machine by V2's own estimate, and for dispatch, V2.0 with 8 SMs beats V1.2.1 with 24), at the price of more memory for prefill and slower calls for very small decoding batches. The CPU waits only with `do_cpu_sync=True`. Mega MoE answers the same questions inside one kernel: tokens are pulled instead of pushed, arrival is tracked per GEMM block, and no layout is ever handed to the caller. The caller only provides FP8 tokens with their scales, the routing, and weights that were rearranged once with `transform_weights_for_mega_moe`. In part 4, we will look at V2.5 from September 2026, which split `ElasticBuffer` into separate buffers for expert parallelism, Engram, pipeline parallelism and collectives, added primitives for replicating experts, made the epilogues deferrable, and removed V1 and NVSHMEM for good. ## Sources - [DeepEP V2.0 (b306af0)](https://github.com/deepseek-ai/DeepEP/tree/b306af06afd412c88e51e71802951606e40b7358) - [DeepEP V2.0 dispatch kernel](https://github.com/deepseek-ai/DeepEP/blob/b306af06afd412c88e51e71802951606e40b7358/deep_ep/include/deep_ep/impls/dispatch.cuh) - [DeepEP PR #630: single-node initialization without GIN](https://github.com/deepseek-ai/DeepEP/pull/630) - [NCCL documentation: device API](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/index.html) - [DeepGEMM at the Mega MoE release (7f2a703)](https://github.com/deepseek-ai/DeepGEMM/tree/7f2a703ed51ac1f7af07f5e1453b2d3267d37d50) - [DeepGEMM PR #316: optimizations and Mega MoE benchmarks](https://github.com/deepseek-ai/DeepGEMM/pull/316) - [SGLang's DeepEP V2 dispatcher](https://github.com/sgl-project/sglang/blob/5cbf949839b1fc73802d20670943ccbeb805d3f2/python/sglang/srt/layers/moe/token_dispatcher/deepep_v2.py) - [DeepSeek-V4 technical report](https://arxiv.org/html/2606.19348v1)